codex-workflow-v2 2.0.0-beta.10 → 2.0.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +43 -9
  2. package/dist/src/alpha6/handoff.d.ts +4 -3
  3. package/dist/src/alpha6/handoff.js +58 -3
  4. package/dist/src/alpha6/handoff.js.map +1 -1
  5. package/dist/src/alpha6/mechanical-feasibility.d.ts +7 -0
  6. package/dist/src/alpha6/mechanical-feasibility.js +303 -0
  7. package/dist/src/alpha6/mechanical-feasibility.js.map +1 -0
  8. package/dist/src/alpha6/milestone.d.ts +25 -2
  9. package/dist/src/alpha6/milestone.js +359 -32
  10. package/dist/src/alpha6/milestone.js.map +1 -1
  11. package/dist/src/alpha6/plan-integrity.d.ts +14 -0
  12. package/dist/src/alpha6/plan-integrity.js +127 -0
  13. package/dist/src/alpha6/plan-integrity.js.map +1 -0
  14. package/dist/src/alpha6/remediation.d.ts +2 -1
  15. package/dist/src/alpha6/remediation.js +168 -3
  16. package/dist/src/alpha6/remediation.js.map +1 -1
  17. package/dist/src/cli.js +13 -1
  18. package/dist/src/cli.js.map +1 -1
  19. package/dist/src/contracts.d.ts +69 -1
  20. package/dist/src/git.d.ts +1 -1
  21. package/dist/src/git.js +8 -1
  22. package/dist/src/git.js.map +1 -1
  23. package/dist/src/index.d.ts +1 -0
  24. package/dist/src/index.js +1 -0
  25. package/dist/src/index.js.map +1 -1
  26. package/dist/src/lifecycle/corrective-replan.js +8 -3
  27. package/dist/src/lifecycle/corrective-replan.js.map +1 -1
  28. package/dist/src/version.d.ts +1 -1
  29. package/dist/src/version.js +1 -1
  30. package/dist/src/workflow.d.ts +5 -0
  31. package/dist/src/workflow.js +399 -90
  32. package/dist/src/workflow.js.map +1 -1
  33. package/docs/autonomy-guardrails.md +21 -0
  34. package/docs/beta11-plan-integrity-recovery-brief.md +38 -0
  35. package/docs/development-flow.md +31 -6
  36. package/docs/lifecycle/state-machine-stabilization.md +1 -1
  37. package/docs/pdf/README.md +24 -0
  38. package/docs/pdf/codex-workflow-v2-architecture-ru.pdf +0 -0
  39. package/docs/pdf/codex-workflow-v2-chat-only-guide-ru.pdf +0 -0
  40. package/docs/pdf/codex-workflow-v2-technical-reference-ru.pdf +0 -0
  41. package/docs/pdf/requirements.txt +1 -0
  42. package/docs/pdf/sources/codex-workflow-v2-architecture-ru.md +234 -0
  43. package/docs/pdf/sources/codex-workflow-v2-chat-only-guide-ru.md +334 -0
  44. package/docs/pdf/sources/codex-workflow-v2-technical-reference-ru.md +413 -0
  45. package/docs/problem-briefs/01-pre-implementation-integrity.md +478 -0
  46. package/docs/problem-briefs/02-minimal-step-integrity.md +411 -0
  47. package/docs/problem-briefs/03-minimal-agent-context-integrity.md +358 -0
  48. package/docs/problem-briefs/04-task-dependency-and-structural-replacement-integrity.md +566 -0
  49. package/docs/problem-briefs/BRIEF-TEMPLATE.md +56 -0
  50. package/docs/problem-briefs/README.md +120 -0
  51. package/docs/problem-briefs/evidence/p01-mechanical-feasibility-corpus.md +90 -0
  52. package/docs/problem-briefs/evidence/signal-v4-pre-m3-replay.md +246 -0
  53. package/docs/release.md +15 -6
  54. package/docs/split-required-recovery.md +19 -26
  55. package/docs/validation-report.md +116 -77
  56. package/package.json +5 -1
  57. package/plugins/codex-workflow-gateway/.codex-plugin/plugin.json +1 -1
  58. package/plugins/codex-workflow-gateway/references/protocol.md +19 -2
  59. package/plugins/codex-workflow-gateway/skills/codex-workflow-gateway/SKILL.md +17 -3
  60. package/references/state-machine.md +9 -5
  61. package/schemas/authorization-event.schema.json +64 -1
  62. package/schemas/corrective-decision-event.schema.json +48 -3
  63. package/schemas/milestone-scope-change-event.schema.json +6 -1
  64. package/schemas/milestone.schema.json +6 -1
  65. package/schemas/task-handoff-event.schema.json +18 -2
  66. package/scripts/generate-pdf-docs.py +512 -0
  67. package/scripts/run-pdf-docs.mjs +62 -0
@@ -89,6 +89,27 @@ and only `split-required` or `stop-escalate` may be recorded. At the corrective
89
89
  `next` derives a distinct `agent:corrective-auditor:<task-id>` actor; selecting that actor is
90
90
  not a human approval, while auditor independence remains mandatory.
91
91
 
92
+ ### First-failure Plan-integrity recovery
93
+
94
+ A mechanically impossible Plan check must not consume the second ordinary remediation attempt
95
+ only to unlock corrective replan. After the first guarded `checks-failed` event, Core performs a
96
+ read-only bounded assessment. `next` advertises `task plan-integrity-recover` only when all of the
97
+ following are true:
98
+
99
+ - the failed Step contains an exact root `npm run <script>` or `npm run-script <script>` check;
100
+ - the named script is absent from the current root `package.json`;
101
+ - `package.json` is outside the failed Step's `allowedWrites`;
102
+ - exactly one ordinary `checks-failed` remediation event exists for the Step;
103
+ - no corrective decision exists for its second-attempt binding;
104
+ - every dirty file remains inside the Step's current `allowedWrites` and outside its
105
+ `forbiddenScope`.
106
+
107
+ The recovery appends one hash-bound `replan-required` decision for attempt ordinal 2. It preserves
108
+ the worktree and does not edit the Plan. A claimed C1 Task must present its current writer token and
109
+ then follow `task corrective-yield`; the replacement Plan still requires the existing independent
110
+ validation, Risk Audit, Human confirmation, journaled execution, readback, and renewed execution
111
+ authorization. Other check failures retain the ordinary two-attempt breaker.
112
+
92
113
  ## Atomic context refresh
93
114
 
94
115
  When `next` returns top-level `action: task context-refresh` with an exact option, a
@@ -0,0 +1,38 @@
1
+ # V2 beta.11 bounded Plan-integrity recovery
2
+
3
+ ## Problem
4
+
5
+ A guarded Step may fail its first Core-owned completion because the approved Plan requires an
6
+ exact root `npm run <script>` command, the script is absent, and the same Step cannot modify
7
+ `package.json`. Re-advertising `task run` cannot succeed and consumes a second ordinary remediation
8
+ attempt only to reach corrective replan.
9
+
10
+ P01-A now rejects this contradiction before a fresh execution authorization when it is already
11
+ provable at the selected evaluation HEAD. The beta.11 route remains necessary for pre-P01-A
12
+ authorizations and contradictions that genuinely become observable only after execution starts.
13
+
14
+ ## Decision
15
+
16
+ Add `task plan-integrity-recover` as a narrow explicit repair. Its read-side assessment proves one
17
+ first `checks-failed` event, an absent root npm script, a manifest outside `allowedWrites`, and a
18
+ worktree confined to the guarded Step. The mutation appends a hash-bound `replan-required`
19
+ corrective decision for attempt ordinal 2. Existing C1 yield, corrective-replan Human gate,
20
+ journal, recovery, readback, Plan validation, Risk Audit, and authorization supersession remain
21
+ the only way to publish the replacement Plan.
22
+
23
+ ## Non-goals
24
+
25
+ - No generic shell-command diagnosis.
26
+ - No automatic Plan editing or inferred replacement command.
27
+ - No `allowedWrites` expansion.
28
+ - No second synthetic failure.
29
+ - No bypass of C1 ownership, writer credentials, Human confirmation, independent validation, or
30
+ Risk Audit.
31
+ - No recovery when dirty files escape the current Step boundary.
32
+
33
+ ## Required evidence
34
+
35
+ The recovery event binds Task revision, Plan hash, failed remediation ID/hash, Step-definition
36
+ hash, Git HEAD, root manifest hash, missing scripts, exact check commands, complete changed-file
37
+ set, and a canonical conflict hash. Legacy corrective-decision events remain valid and retain the
38
+ ordinary minimum of two failed attempts.
@@ -28,6 +28,16 @@ uses a bootstrap audit over the preserved non-`completed`, non-`skipped` Steps o
28
28
  The audit names a Plan author and independent auditor, binds each guarded failure mode to
29
29
  exact executable evidence, and blocks authorization on `split-required` or `stop-escalate`.
30
30
 
31
+ P01-A adds a second, bounded admission check without adding a lifecycle stage. Before
32
+ `task authorize`, Core reads the selected committed source and recognizes only three versioned
33
+ mechanical forms: an exact root `npm run <literal-script>`, an exact structured
34
+ `path:<repository-relative POSIX path>` output, and that same path supplied by an exact transitive
35
+ Step predecessor with write authority. A proved contradiction returns to `task plan-set` without
36
+ writing an approval. Unsupported commands, prose, or ambiguous future creation remain
37
+ `unverified`, not pass or failure. A clear payload is stored inside the execution authorization,
38
+ bound to the Brief, Plan, analyzer inputs/set, selected HEAD, and phase-aware base/Task branch.
39
+ Freshness is checked before claim lease acquisition, Task start, and direct execution entry.
40
+
31
41
  Local execution creates `codex/task-<id>-<slug>` from a clean base only after authorization.
32
42
  An externally owned checkout must already use a dedicated non-base branch. The core never
33
43
  creates or removes external worktrees. Each Step declares allowed writes, dependencies, and
@@ -80,6 +90,14 @@ For guarded remediation, a third ordinary retry is blocked until a current
80
90
  `task corrective-decision` exists for the same Step and Plan binding. If that corrective
81
91
  attempt fails review, the third failure is a hard stop and no fourth run is permitted.
82
92
 
93
+ One bounded exception avoids a deliberately repeated failure for an older authorization without
94
+ P01-A evidence or a contradiction that becomes observable only after execution starts. If the first guarded check failure
95
+ is caused by an absent root npm script that the Step cannot add because `package.json` is outside
96
+ its `allowedWrites`, fresh `next` advertises `task plan-integrity-recover`. The command records only
97
+ the exact evidence-bound early `replan-required` posture; it never edits source, Plan, or Git.
98
+ Continue through the advertised corrective yield and corrective replan rather than calling
99
+ `task run` again.
100
+
83
101
  Execution authorization and final acceptance use the human path by default. If the user has
84
102
  previously issued an active delegation grant for the exact transition and scope, the named
85
103
  delegate may perform that transition with `--delegation-grant`. The event keeps the delegate
@@ -95,7 +113,10 @@ Discovery -> Milestone planning -> execution authorization -> active
95
113
  -> final acceptance -> accepted
96
114
  ```
97
115
 
98
- A Milestone Plan records outcome, success signal, acceptance, checks, and Task membership.
116
+ A Milestone Plan records outcome, success signal, acceptance, checks, Task membership, and the
117
+ canonical Task dependency DAG. Every membership explicitly supplies `dependsOnTaskIds`, including
118
+ `[]`. A required consumer may depend only on required members of the same Milestone; duplicate,
119
+ self, dangling, external, non-required-provider, and cyclic edges are rejected before commit.
99
120
  Membership is `required`, `waived`, or `cancelled`; non-required entries require a reason.
100
121
  Changing the Plan increments the membership revision, supersedes execution authorization,
101
122
  and prevents new linked Tasks from starting. A Task that has started cannot be removed;
@@ -115,18 +136,22 @@ Milestone Autonomy Contract may instead use `milestone autonomy-evolve` for memb
115
136
  changes while the outcome, success signal, acceptance, checks, discovery, and base branch
116
137
  remain unchanged. The same contract may complete an atomic content-only Task context refresh
117
138
  without a new human gate, but cannot approve Project Memory independently. Both paths retain
118
- journaled recovery across `state.json`, `plan.json`, and `scope-change-events.jsonl`.
139
+ journaled recovery across `state.json`, `plan.json`, and `scope-change-events.jsonl`. The initial
140
+ Plan uses the same recovery machinery for its exact two-file `state.json` + `plan.json` commit and
141
+ does not manufacture a scope-change event.
119
142
 
120
143
  A Milestone has no integration branch. Validation requires all required Tasks to be
121
144
  `merged`, checks the current clean base branch, and writes evidence plus Result. Final
122
145
  acceptance binds those artifacts to the unchanged base HEAD. Cancellation records a reason
123
146
  and never changes Task state or reverts merged commits.
124
147
 
125
- Repository-level `next` considers Milestone membership before it dispatches a Task. An
126
- unstarted linked Task is actionable only while its Milestone is `active` and its current
127
- membership is `required`. Unstarted `waived`/`cancelled` memberships and Tasks belonging to
148
+ Repository-level `next` considers Milestone membership and dependencies before it dispatches a
149
+ Task. A linked Task is actionable only while its Milestone is `active`, its current membership is
150
+ `required`, and every declared required predecessor is `merged`. Handoff prepare, claim before
151
+ lease acquisition, and Task start use the same predicate. Unstarted `waived`/`cancelled`
152
+ memberships and Tasks belonging to
128
153
  an accepted/cancelled Milestone are historical records, not work. A Task that already owns
129
- a workspace remains actionable while its non-terminal Milestone permits it to finish.
154
+ a workspace does not bypass an unsatisfied Milestone predecessor.
130
155
 
131
156
  After successful Milestone validation, `next` emits `requiredHumanGate` containing the
132
157
  Milestone revision, Plan/Result/evidence hashes, validated base HEAD, and a deterministic
@@ -434,7 +434,7 @@ Production-file ownership is assigned before each implementation iteration. The
434
434
  | I07-CD1 round 4a | completed after fresh changed-evidence review | secret-free indexed closure extras; exact missing/duplicate/substituted closure diagnostics; all round-4 owned-input, generation, totality and budget corrections retained; private kernel remains `available-unwired` with execution linkage `pending-cd2` | Orchestrator typecheck/build/test compile, 56/56 focused, built-root 4-required/26-forbidden probe, genuine Core smoke and final full 262/262; independent typecheck/build/test compile, 56/56, root/Core/credential no-echo probes; fresh review `0 material / 0 major / 0 minor` | final credential Model SHA-256 `469c85247b497926b52a7e736202dcdb417494309a2f282f3affc87536ecf35d`; scoped 150-file candidate SHA-256 `4e120b7ded6d0fecae8d02906b9dda594e523303dab115e03a0e7193f99c835a`; manifest `edab7ee7ac4018e759f5fc702a11a0fd113ef4f2cf8ed8fa823a59fde3012a1a`; closure `3cbf139bc017d0fc87338a6c67dc04617de9ae2e1aafde5c712d8c9b3f7cf0b4` | accept CD-1 private credential kernel only; release readiness and public execution remain false; proceed next only to CD-2 storage/mutex/journal packet |
435
435
  | I07-CD2 | implementation and validation complete; fresh independent changed-evidence review pending | private same-slot Core Task mutex with opaque inode-bound handle; exact five-target preimage/postimage ownership; durable intent/phase hash chains; apply-or-confirm Task CAS; completed-target readback; pending/corrupt/orphan observation and central Task store gate; execution linkage advances to `pending-cd3` | pinned Node 24.17 typecheck/build/test compile; CD-2 oracle 4/4; combined focused 100/100 then final affected 61/61; built-root private-boundary/Core smoke; full regression 266/266; diff-check | live serialized/runtime/catalog/readiness pins unchanged; no public executor, recovery command, protocol/epoch/catalog activation or readiness reduction | retain runtime exclusivity, stale-lock recovery, target application, receipt-handle linkage, replay and dual terminal readback as CD-3/CD-4 blockers; do not call the transition executable |
436
436
  | I07-CD3 | implementation and validation complete; fresh independent changed-evidence review pending | private receipt-bound five-target corrective-replan executor/recovery/replay; exact state-before-publish roll-forward and dual readback; separate fixed-target corrective-yield journal with Writer-to-Core same-slot transfer; central pending-yield observation gate; no public activation | pinned Node 24.17 typecheck/build/test compile; replan/storage/yield focused 13/13; expanded affected 91/91 before final hardening; final full regression 275/275; built-root private-boundary/Core smoke; diff-check | live serialized SHA `626035488c83bb12091d1b5af959635c9af473f5a2d9e47817c70be4c5f58311`, runtime fingerprint `c8de50fcfd869327156afc1a676e87cd8684b25ce95c307f876b119ad3f082a8`, runtime catalog `3491e5d21c5d71385aefa62a62561b694e3ba41debfd31132cb26c05f7e4938b`, readiness report `742f40c20b81f34761fc3ec1c839aa81770e07f1deda33a4b2439297a195ad91`; static readiness and exact 11 blockers unchanged | keep both executors private and `pending-cd4`; CD-4 must atomically add protocol-v2 navigation/CLI, lifecycle epoch/catalog v4 activation, public repair, complete differential evidence and removal of the legacy corrective mutation bypass |
437
- | I07-CD4 | implementation and local changed-evidence hardening complete; independent external sign-off pending | protocol-v2 public yield/prepare/confirm/execute/repair; epoch 2 and definition/catalog format 4; active exact callable linkage; legacy corrective `task plan-set` disabled; protocol-v1 adoption evidence has a bounded read-only compatibility window; public candidate/input budgets, pending-journal admission and non-C1 writer-lease navigation now fail closed | pinned Node 24.17 affected 111/111 and full regression 279/279; built-root 4-required/26-forbidden; genuine Core `staticReady=true`; package dry-run, downstream smoke, plugin and release checks green; unchanged-candidate public CLI yield→prepare→confirm→execute→replay repeated green; legacy bypass, wrong confirmation, pending journal, oversized input and known active non-C1 lease are non-mutating | serialized SHA `6070765ab24dd24641a35ee3b3ed64a9dc9e89d705425f80918ad4500bd57800`; runtime fingerprint `bd4e7a0ddfcb6abc0c5eb107775e6aea7e08c4606dda4d945d77af8a4520710d`; runtime catalog `fa1d11860d4f07978c3b8e85d1f91cd3d15b17284b05f41e05d462d3bb092aed`; readiness report `c7fa9e19a453ee27915cfca298c65f548e992f22c01fec99460daa36cc12948d`; no static blockers | keep the candidate frozen for independent external changed-evidence sign-off; do not claim broad catalog completeness or stable release before that sign-off |
437
+ | I07-CD4 | implementation and local changed-evidence hardening complete; independent external sign-off pending | protocol-v2 public yield/prepare/confirm/execute/repair; epoch 2 and definition/catalog format 4; active exact callable linkage; legacy corrective `task plan-set` disabled; protocol-v1 adoption evidence has a bounded read-only compatibility window; public candidate/input budgets, pending-journal admission and non-C1 writer-lease navigation now fail closed | pinned Node 24.17 affected 111/111 and full regression 279/279; built-root 4-required/26-forbidden; genuine Core `staticReady=true`; package dry-run, downstream smoke, plugin and release checks green; unchanged-candidate public CLI yield→prepare→confirm→execute→replay repeated green; legacy bypass, wrong confirmation, pending journal, oversized input and known active non-C1 lease are non-mutating | serialized SHA `c601cc100790a19e6ece2a1d60fb46d1e1d52e6922e6104d84f4b6ffe7ba0225`; runtime fingerprint `bd4e7a0ddfcb6abc0c5eb107775e6aea7e08c4606dda4d945d77af8a4520710d`; runtime catalog `fa1d11860d4f07978c3b8e85d1f91cd3d15b17284b05f41e05d462d3bb092aed`; readiness report `c7fa9e19a453ee27915cfca298c65f548e992f22c01fec99460daa36cc12948d`; no static blockers | keep the candidate frozen for independent external changed-evidence sign-off; do not claim broad catalog completeness or stable release before that sign-off |
438
438
 
439
439
  No new implementation round starts until every finding from the prior round has a disposition.
440
440
 
@@ -0,0 +1,24 @@
1
+ # Russian PDF documentation
2
+
3
+ The three tracked PDFs in this directory are deterministic release artifacts generated from the
4
+ reviewable Markdown files in [`sources`](sources/).
5
+
6
+ Generate them with:
7
+
8
+ ```bash
9
+ npm run docs:pdf
10
+ ```
11
+
12
+ Verify that the tracked binaries match the current sources and package version with:
13
+
14
+ ```bash
15
+ npm run docs:pdf:check
16
+ ```
17
+
18
+ The generator reads the exact version from the root `package.json`, uses embedded TrueType font
19
+ subsets, and writes deterministic PDF bytes. A release must update source and PDF together. The
20
+ PDFs are human-facing artifacts; runtime code, schemas, the bundled gateway and ordinary Markdown
21
+ documents remain the technical authority.
22
+
23
+ The runner uses `CODEX_WORKFLOW_PDF_PYTHON` when supplied, then the bundled Codex App Python, then
24
+ `python3`. Non-Codex environments can install the pinned dependency from `requirements.txt`.
@@ -0,0 +1 @@
1
+ reportlab==4.4.9
@@ -0,0 +1,234 @@
1
+ ---
2
+ title: Codex Workflow V2: архитектура beta.11
3
+ subtitle: Источники истины, lifecycle, роли, delegation, зависимости Tasks и границы доверия
4
+ part: Часть 1 из 3 | Архитектура
5
+ document_version: 2.0
6
+ date: 24 августа 2026
7
+ subject: Архитектура и границы Codex Workflow V2 beta.11
8
+ ---
9
+
10
+ # 1. Назначение и граница системы
11
+
12
+ Codex Workflow V2 - локальный state machine поверх Codex App, Git и файлов проекта. Codex выполняет
13
+ исследование и реализацию. Workflow Core решает, разрешена ли конкретная мутация, связывает её с
14
+ актуальными revisions и hashes, управляет writer credentials и создаёт проверяемые Git evidence.
15
+
16
+ > **Главная граница:** файлы проекта и Git history являются долговременной продуктовой памятью. Локальный Workflow state хранит производный lifecycle и не может заменять repository knowledge.
17
+
18
+ Система рассчитана на одного пользователя и одну машину. Она не предоставляет distributed locking,
19
+ криптографическую идентификацию actor string или безопасную синхронизацию state между компьютерами.
20
+
21
+ ## 1.1. Что beta.11 гарантирует
22
+
23
+ - exact project-local npm package и совместимый handshake до lifecycle действий;
24
+ - Discovery до materialization Task или Milestone;
25
+ - утверждённую Project Knowledge Map и Plan, связанный с её точной revision/hash;
26
+ - mechanical-feasibility проверку поддерживаемых форм Plan до новой Task authorization;
27
+ - явный Milestone dependency DAG и один общий runnable predicate для routing, handoff, claim и start;
28
+ - один C1 writer lease, секретные one-time credentials и Core-owned Step commits;
29
+ - external-sealed Step/Task review в отдельных Codex tasks;
30
+ - state-bound human gates либо ранее выданные bounded delegation contracts;
31
+ - journaled recovery для составных переходов и fail-closed поведение при drift/corruption.
32
+
33
+ ## 1.2. Что beta.11 не гарантирует
34
+
35
+ - правильность продуктовой идеи или автоматически выбранного provider Task;
36
+ - semantic sufficiency Plan, если точные факты нельзя доказать поддерживаемым analyzer;
37
+ - параллельную работу нескольких writers в одном checkout;
38
+ - автоматический structural replacement после `split-required`;
39
+ - восстановление вручную повреждённого state без штатной recovery transition.
40
+
41
+ # 2. Шесть уровней и источники истины
42
+
43
+ | Уровень | Источник истины | Ответственность |
44
+ |---|---|---|
45
+ | Пользователь / principal | Явные ответы и подтверждённые policies | Scope, semantic unknowns, grant issuance, human gates |
46
+ | Codex App | Project folders, tasks, permissions | User-visible execution contexts и bounded tool access |
47
+ | Роли агентов | Fresh ContextPacket и Workflow projection | Discovery, planning, execution, review, coordination |
48
+ | Project-local gateway | Exact installed package и protocol | Handshake, routing discipline, app chat boundary |
49
+ | Workflow Core | Runtime transitions и schemas | Revisions, hashes, locks, Git ownership, evidence |
50
+ | Repository и local state | Git/files и revisioned state | Durable product facts и производный lifecycle |
51
+
52
+ При расхождении приоритет имеют runtime Core и обычные файлы текущего repository. PDF объясняет
53
+ контракт человеку, но не заменяет `status`, свежий `next`, schemas или package-local help.
54
+
55
+ ## 2.1. Exact package boundary
56
+
57
+ Продуктовый repository обязан объявить `codex-workflow-v2` точной версией в `devDependencies`.
58
+ Gateway разрешает только `node_modules/codex-workflow-v2/dist/src/cli.js` этого repository,
59
+ сравнивает installed и declared versions, затем выполняет `gateway handshake`.
60
+
61
+ ```text
62
+ AGENTS.md
63
+ -> project-local gateway
64
+ -> gateway handshake
65
+ -> status
66
+ -> next [--task <exact TASK-ID>]
67
+ -> только рекламируемая transition
68
+ ```
69
+
70
+ `doctor` является диагностикой, но не заменяет успешные `status` и `next`. Help разрешён только для
71
+ уточнения syntax после свежего routing response.
72
+
73
+ # 3. Долговременные и производные артефакты
74
+
75
+ | Артефакт | Где находится | Кто владеет записью |
76
+ |---|---|---|
77
+ | Product code, tests, Markdown docs | Git repository | Worker в Plan scope; Git commit создаёт Core |
78
+ | AGENTS.md и Project Knowledge | Git repository | Пользователь и обычный reviewable change |
79
+ | Knowledge Map | Local Workflow state | Project-memory transitions |
80
+ | Discovery state | Local Workflow state | Discovery transitions |
81
+ | Brief, Plan, Result, evidence | Local Workflow state с versioned artifacts | Core transitions |
82
+ | Task/Milestone state и sidecars | Local Workflow state | Core, CAS и schema validation |
83
+ | Writer locks и private credentials | Local Workflow state | Lock manager и C1 transitions |
84
+ | Transaction journals | Local Workflow state | Composite transition recovery |
85
+ | codebase graph binding | Local Workflow state | Derived evidence, не product authority |
86
+
87
+ Ручное редактирование state, locks, sidecars или `.versions` запрещено. Оно ломает hash chain,
88
+ expected revision и восстановимость составных операций.
89
+
90
+ # 4. Discovery, Task и Milestone
91
+
92
+ | Сущность | Назначение | Terminal success |
93
+ |---|---|---|
94
+ | Discovery | Уточнить outcome, scope, acceptance, constraints и unknowns | Готова к materialization |
95
+ | Task | Один самостоятельный проверяемый результат | Reviewed, accepted и merged |
96
+ | Step | Атомарный инкремент внутри Task | Checks, один Core commit и evidence |
97
+ | Milestone | Сквозной outcome из связанных Tasks | Required Tasks merged, validation и acceptance |
98
+
99
+ ## 4.1. Task lifecycle
100
+
101
+ ```text
102
+ Discovery -> materialize -> Plan -> Plan Risk Audit
103
+ -> mechanical feasibility -> execution authorization
104
+ -> C1 handoff -> claim -> start -> Steps
105
+ -> submit -> external-sealed review -> Result
106
+ -> final acceptance -> merge
107
+ ```
108
+
109
+ Fresh Task authorization записывает versioned mechanical-feasibility evidence. Analyzer может
110
+ выдать `blocked`, `pass` или `unverified`. `unverified` не означает semantic approval; он означает,
111
+ что поддерживаемая точная грамматика не доказала противоречие.
112
+
113
+ ## 4.2. Milestone initial assembly
114
+
115
+ После materialization Milestone Core возвращает `milestone initial-assembly`. Coordinator создаёт
116
+ linked Task Discoveries и materializes Tasks только через команды, рекламируемые `next`. После
117
+ появления полного intended membership один `milestone plan-set` атомарно публикует state и plan.json.
118
+ До этого execution недоступно.
119
+
120
+ Каждая membership содержит:
121
+
122
+ ```text
123
+ taskId
124
+ disposition: required | waived | cancelled
125
+ reason
126
+ dependsOnTaskIds: [exact predecessor Task IDs]
127
+ ```
128
+
129
+ Даже независимая Task обязана объявить `dependsOnTaskIds: []`. Отсутствующее поле в legacy state
130
+ означает unknown dependency authority, а не пустой граф.
131
+
132
+ ## 4.3. Runnable predicate P04-A
133
+
134
+ Task runnable только когда Milestone active, membership required и все canonical predecessors имеют
135
+ status `merged`. Ordinal, название, время создания и порядок в чате не создают dependency.
136
+
137
+ Один predicate применяется к repository routing, Task-specific routing, handoff preparation,
138
+ claim до lease acquisition и direct start. Authorization не обходит dependency block.
139
+
140
+ # 5. Delegated approval и Milestone autonomy
141
+
142
+ Delegation не превращает agent в human actor. Event отдельно хранит principal, delegate, grant,
143
+ policy hash, transition, scope и expiry.
144
+
145
+ | Механизм | Когда применять | Что не разрешает |
146
+ |---|---|---|
147
+ | Direct human gate | Default path | Никакой последующей автономии |
148
+ | DGA/DGR delegated approval | Exact allow-listed approval transition | Scope expansion, grant issuance, обычные execution transitions |
149
+ | Milestone Autonomy Contract | После полного initial Milestone Plan | Outcome/check/base/discovery changes и standalone map approval |
150
+
151
+ Для нового `AUTO` Discovery допустим короткий project-scoped DGR, если нужен exact
152
+ `project_memory.approve` или будущий approval transition. Blocking semantic unknown всегда возвращается
153
+ пользователю. После полного initial Milestone Plan предпочтителен один bounded
154
+ `milestone autonomy-prepare` gate и отдельное подтверждение `MAC-*`, затем `autonomy-grant`.
155
+
156
+ Milestone Autonomy Contract покрывает разрешённые Task/Milestone approvals, membership-only evolve и
157
+ Project Memory approval только внутри atomic Task context refresh этого Milestone. Grant не применяется
158
+ к handoff, claim, run, step-complete, reviews, sync-base или merge.
159
+
160
+ # 6. Codex App chat topology
161
+
162
+ Milestone coordinator и Task chats являются отдельными user-visible Codex tasks, не fork одного
163
+ conversation. Coordinator создаёт Task chat just-in-time, передаёт закрытый TaskContextPacket и
164
+ остаётся активным supervisor до terminal Milestone либо настоящего user gate.
165
+
166
+ ```text
167
+ Coordinator
168
+ -> Task T01 chat
169
+ -> Step Review chat при external-sealed gate
170
+ -> Final Review chat
171
+ -> Corrective/Plan Audit chat при необходимости
172
+ -> status -> next -> milestone progress
173
+ -> следующий runnable Task chat
174
+ ```
175
+
176
+ Project chat registry атомарно выдаёт monotonic `#NNN`. Название всегда содержит membership ordinal и
177
+ полный entity ID. Sidebar count, creation order и ручное `01/02` не являются authority.
178
+
179
+ Coordinator ждёт routed Task через bounded waits, читает закрытый CoordinatorReport, затем проверяет
180
+ repository `status -> next`. Завершение дочернего чата само по себе не доказывает terminal Task.
181
+
182
+ # 7. C1 handoff, lease и Git ownership
183
+
184
+ `task handoff-prepare` возвращает одноразовый `credentialHandoff`. Он используется ровно один раз
185
+ целевым actor в `task claim`. Claim проверяет Task/Milestone dependency binding и только затем выдаёт
186
+ `writerLeaseReceipt`. `task run` обновляет активный lease и возвращает Step context.
187
+
188
+ Bearer credentials нельзя печатать, сохранять в файлы, передавать Reviewer или включать в evidence.
189
+ Если token утерян, используется только рекламируемая credential recovery transition.
190
+
191
+ Worker меняет только `allowedWrites` и оставляет изменения uncommitted. Coordinator вызывает точный
192
+ `task step-complete`; Core запускает checks, проверяет scope/history, создаёт один commit и evidence.
193
+
194
+ # 8. Knowledge Map и context refresh
195
+
196
+ Project Knowledge Map хранит paths, categories, scope, authority, hashes, gaps и conflicts, но не
197
+ копирует содержимое файлов. Scan является read-only. Reconcile и approve выполняются только через Core.
198
+
199
+ Если top-level `next` возвращает `task context-refresh`, Coordinator вызывает только эту atomic
200
+ transition с указанными revisions, actor и grant. Standalone reconcile перед ней создаёт human-approval
201
+ gap и блокируется.
202
+
203
+ Кроме content-only drift, Core может допустить exact supporting-source addition, заранее объявленное
204
+ execution-authorized Plan и покрытое тем же Milestone Autonomy Contract. Unsafe differences возвращают
205
+ обычный видимый reconcile/approve/rebind/reauthorize flow.
206
+
207
+ # 9. Review и corrective recovery
208
+
209
+ В Codex App strict review выполняется external-sealed:
210
+
211
+ 1. Core формирует read-only review packet и repository seal.
212
+ 2. Task chat создаёт отдельный Reviewer chat.
213
+ 3. Reviewer возвращает закрытый schema-valid result без mutations.
214
+ 4. Core записывает его только если packet и seals не изменились.
215
+
216
+ После двух failed review отдельный Corrective Auditor выбирает `continue-fix`, `replan-required`,
217
+ `split-required` или `stop-escalate`. Continue разрешает один bounded corrective attempt; последующий
218
+ failure создаёт hard stop.
219
+
220
+ beta.11 `task plan-integrity-recover` существует для одного первого checks-failed legacy/late case:
221
+ отсутствует exact root npm script и текущий Step не может изменить package.json. Recovery не меняет
222
+ worktree или Plan и не создаёт synthetic second failure; он записывает bound `replan-required`.
223
+
224
+ > **Стоп P04-A:** `split-required` возвращает `STRUCTURAL_REPLACEMENT_REQUIRED` и `structuralReplacementAvailable=false`. Нельзя вызывать retained replacement command, потреблять replacement Discovery или вручную менять topology. Продолжение возможно только после P04-B/P05.
225
+
226
+ # 10. Operational checklist
227
+
228
+ - exact package version установлен, bundled gateway соответствует release и переустановлен;
229
+ - handshake подтверждает protocol 2, state schema 2 и beta.11 capabilities;
230
+ - каждый mutation следует свежему `status -> next` и exact option contract;
231
+ - semantic unknowns и human gates не маскируются delegation;
232
+ - Task chats создаёт coordinator, credentials остаются только в памяти;
233
+ - dependencies, progress и review posture берутся из Core projections;
234
+ - local state не редактируется вручную; release и package update выполняются только после safe preflight и обязательных checks.