docs: activate token-efficient agent workflow
This commit is contained in:
@@ -9,4 +9,5 @@
|
||||
- [Audit remediation registry](audit-remediation.md) — текущий статус findings, следующий OpenSpec change и evidence завершённых улучшений.
|
||||
- [Engineering governance](engineering-governance.md) — Change Owner, SDD approvals, Delivery Map, risk-based testing, build-versus-buy и hard guardrails.
|
||||
- [OpenSpec authority и lifecycle](openspec-authority-and-lifecycle.md) — единственный SDD store, границы постоянной документации и условия archive.
|
||||
- [Token-efficient agent workflow](agent-token-efficiency.md) — lazy context routing, session handoff, evidence batching и protocol активного pilot.
|
||||
- [Проверка runtime OpenAPI](runtime-openapi-verification.md) — отдельный read-only contract gate и его границы.
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# Token-efficient agent workflow
|
||||
|
||||
## Статус и границы
|
||||
|
||||
Эта инструкция описывает действующий guidance для сокращения повторной передачи
|
||||
agent context. Она не меняет SDD lifecycle, approvals, canonical gates, semantic
|
||||
verification или independent review и не является hard guardrail.
|
||||
|
||||
Исходный baseline сохранён в
|
||||
[аудите Codex-сессий 26.08.2026](../audits/codex-sessions-token-audit-2026-08-26.md).
|
||||
Raw rollout logs не коммитятся. Числовой budget не блокирует delivery без
|
||||
отдельного утверждённого change, детерминированной non-mutating проверки и
|
||||
controlled positive/negative evidence.
|
||||
|
||||
## Routing context
|
||||
|
||||
До чтения supporting documentation агент определяет:
|
||||
|
||||
1. тип работы и текущую SDD-фазу, если change versioned;
|
||||
2. affected repositories и их canonical gates;
|
||||
3. capability или source identity, нужные для следующего решения.
|
||||
|
||||
После этого загружается только применимый context:
|
||||
|
||||
| Trigger | Обязательный context |
|
||||
| --- | --- |
|
||||
| Versioned SDD planning или Apply | Native OpenSpec instruction, возвращённые `contextFiles` и локальные `AGENTS.md` affected areas |
|
||||
| Engineering policy, approval, testing, delivery или archive | Релевантный раздел `engineering-governance.md` |
|
||||
| Cross-service flow или архитектурная граница | `architecture/system-overview.md` и применимые ADR/feature docs |
|
||||
| Domain или API semantics | Релевантный термин `architecture/domain-glossary.md` и canonical contract/spec |
|
||||
| Работа по известному Audit ID | Найденная через поиск запись и связанное evidence в `audit-remediation.md` |
|
||||
| Диагностика agent token usage или этот pilot | Этот playbook и применимый dated audit snapshot |
|
||||
|
||||
Supporting material загружается on demand, если возникший вопрос меняет
|
||||
семантику, архитектуру, audit disposition или обязательный gate. Guidance нельзя
|
||||
использовать как основание пропустить необходимую authority.
|
||||
|
||||
## Handoff между agent-сессиями
|
||||
|
||||
Approved planning artifact, завершённый implementation slice или verification
|
||||
outcome являются естественной границей новой Codex task. Минимальный handoff:
|
||||
|
||||
```text
|
||||
Change: <identity>
|
||||
Approved through: <explicitly approved artifact>
|
||||
Current phase: <phase>
|
||||
Affected areas: <areas>
|
||||
Unresolved blockers: <none or list>
|
||||
Next allowed outcome: <one outcome>
|
||||
```
|
||||
|
||||
Planning content не копируется: новая task читает его из canonical OpenSpec
|
||||
store. Если явный approval недоступен в новой task, агент повторно запрашивает
|
||||
его и не выводит решение владельца только из наличия artifact.
|
||||
|
||||
Для handoff Apply → Verify дополнительно передаются фактический scope изменённых
|
||||
areas и unresolved failures. Полная история tool calls не передаётся.
|
||||
|
||||
## Evidence batching
|
||||
|
||||
Один evidence batch заканчивается перед следующим смысловым решением:
|
||||
|
||||
- заранее независимые read-only lookups выполняются вместе;
|
||||
- adaptive discovery, side effects и approval boundaries остаются
|
||||
последовательными;
|
||||
- discovery начинается с `rg` или другого identity search, затем читает
|
||||
релевантный диапазон;
|
||||
- diff сначала сужается через status/stat/name-only, затем раскрывает affected
|
||||
paths;
|
||||
- successful command result сохраняет exact command identity, exit status и
|
||||
существенную summary;
|
||||
- failure или неоднозначная summary расширяет diagnostics до достаточной причины;
|
||||
- semantic verification и reviewer всегда получают полный relevant evidence.
|
||||
|
||||
Статический лимит строк или tool tokens не применяется: он может скрыть
|
||||
единственный диагностический сигнал. Compact output — способ убрать заведомо
|
||||
нерелевантный шум, а не обрезать доказательства.
|
||||
|
||||
## Pilot protocol
|
||||
|
||||
Pilot change `optimize-agent-token-workflow` остаётся active до 10 завершённых
|
||||
post-activation SDD-фаз минимум по двум changes. Для каждой попытки local
|
||||
non-authority dataset содержит:
|
||||
|
||||
- change identity, phase type и краткий workload scope;
|
||||
- cumulative input, model calls, context-depth indicators и tool-output volume;
|
||||
- canonical-gate outcome, fix cycles и independent-review findings;
|
||||
- completed или interrupted outcome и причину interruption.
|
||||
|
||||
Interrupted attempts учитываются отдельно и не исчезают из quality assessment.
|
||||
Raw prompts, source contents и rollout logs в Git не добавляются.
|
||||
Рабочий dataset хранится локально в workspace root как
|
||||
`.agent-token-pilot.json`; workspace root не является Git-репозиторием, а файл
|
||||
не является planning, handoff или documentation authority.
|
||||
|
||||
Сравнение выполняется внутри одинаковых phase types и близкого scope, когда это
|
||||
возможно. Aggregate сопровождается ограничениями неоднородности. Снижение
|
||||
resource usage считается улучшением только без ухудшения gate success, rework и
|
||||
review findings. Итоговый versioned report публикует method, scope, aggregates,
|
||||
confounders и verdict; он не экстраполирует quota или стоимость без provider
|
||||
contract.
|
||||
@@ -46,6 +46,30 @@ artifact.
|
||||
|
||||
Изменение принятого upstream artifact инвалидирует approval зависимых артефактов: Proposal — Specs, Design и Tasks; Specs — Design и Tasks; Design — Tasks. Tasks не могут неявно расширять scope или менять поведение и архитектуру: работа возвращается к соответствующему upstream artifact.
|
||||
|
||||
## Token-efficient agent execution
|
||||
|
||||
Agent workflow сначала определяет текущую SDD-фазу и affected delivery areas,
|
||||
затем загружает canonical artifacts, локальные routing instructions и только
|
||||
применимую supporting authority. Полная история предыдущей agent-сессии и
|
||||
отдельный handoff artifact не являются prerequisite: после явного approval
|
||||
следующая фаза восстанавливается из canonical OpenSpec change и компактного
|
||||
handoff state. Если доступный context не подтверждает approval, решение Change
|
||||
Owner запрашивается повторно.
|
||||
|
||||
Независимые read-only evidence следует получать одним batch до следующего
|
||||
смыслового решения. Compact successful output сохраняет command identity, exit
|
||||
status и существенный outcome; failure, semantic verification и independent
|
||||
review получают достаточные diagnostics и полный relevant scope. Эти правила и
|
||||
числовые budgets являются guidance, пока отдельный утверждённый change не
|
||||
предоставит детерминированную non-mutating проверку и controlled evidence нового
|
||||
hard guardrail.
|
||||
|
||||
Эффективность оценивается на завершённую SDD-фазу вместе с gate outcomes, fix
|
||||
cycles, interrupted attempts и review findings. Меньший token usage при большем
|
||||
rework или худшем verification result не считается улучшением. Операционный
|
||||
routing, handoff envelope и pilot protocol находятся в lazy
|
||||
[Token-efficient agent workflow](agent-token-efficiency.md).
|
||||
|
||||
## Delivery Map и multi-repository delivery
|
||||
|
||||
Design каждого change оценивает все четыре области:
|
||||
|
||||
@@ -68,6 +68,26 @@ openspec schema which wealth-ledger-sdd --json
|
||||
|
||||
`schema which` должен указывать project-local source. `specs/openspec/config.yaml` хранит default schema и компактный routing context, а не копию полной policy.
|
||||
|
||||
## Stage context и handoff
|
||||
|
||||
До supporting reads agent определяет текущую OpenSpec-фазу и affected areas.
|
||||
Native instruction и возвращённые `contextFiles` задают planning context;
|
||||
repository-local `AGENTS.md` добавляет только routing и canonical gate своей
|
||||
area. Architecture, glossary, audit registry и подробный operational playbook
|
||||
загружаются по применимому trigger, а не blanket-набором перед любой задачей.
|
||||
|
||||
После явного approval planning artifact следующая фаза может начаться в новой
|
||||
Codex task. Handoff сохраняет change identity, последний approved artifact,
|
||||
current phase, affected areas, unresolved blockers и один следующий outcome.
|
||||
Содержание artifacts повторно не пересказывается и остаётся в canonical store.
|
||||
Если явный approval нельзя подтвердить из новой task, agent повторно запрашивает
|
||||
его до создания downstream artifact.
|
||||
|
||||
Apply → Verify использует ту же boundary, добавляя фактический implementation
|
||||
scope и unresolved failures без полной истории tool calls. Подробная форма
|
||||
handoff и evidence-batching guidance описаны в
|
||||
[Token-efficient agent workflow](agent-token-efficiency.md).
|
||||
|
||||
## Agent entrypoints и обновление OpenSpec
|
||||
|
||||
Root `.opencode/commands` и `.opencode/skills` — локальные non-authority
|
||||
|
||||
Reference in New Issue
Block a user