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

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 (78) hide show
  1. package/README.md +47 -13
  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 +3 -2
  15. package/dist/src/alpha6/remediation.js +168 -55
  16. package/dist/src/alpha6/remediation.js.map +1 -1
  17. package/dist/src/alpha6/review.d.ts +5 -0
  18. package/dist/src/alpha6/review.js +110 -2
  19. package/dist/src/alpha6/review.js.map +1 -1
  20. package/dist/src/cli.js +14 -2
  21. package/dist/src/cli.js.map +1 -1
  22. package/dist/src/contracts.d.ts +82 -1
  23. package/dist/src/git.d.ts +1 -1
  24. package/dist/src/git.js +8 -1
  25. package/dist/src/git.js.map +1 -1
  26. package/dist/src/index.d.ts +1 -0
  27. package/dist/src/index.js +1 -0
  28. package/dist/src/index.js.map +1 -1
  29. package/dist/src/lifecycle/corrective-replan.js +8 -3
  30. package/dist/src/lifecycle/corrective-replan.js.map +1 -1
  31. package/dist/src/reviewer.d.ts +26 -0
  32. package/dist/src/reviewer.js +54 -1
  33. package/dist/src/reviewer.js.map +1 -1
  34. package/dist/src/version.d.ts +1 -1
  35. package/dist/src/version.js +1 -1
  36. package/dist/src/workflow.d.ts +5 -0
  37. package/dist/src/workflow.js +449 -148
  38. package/dist/src/workflow.js.map +1 -1
  39. package/docs/autonomy-guardrails.md +42 -33
  40. package/docs/beta11-plan-integrity-recovery-brief.md +38 -0
  41. package/docs/decisions.md +5 -4
  42. package/docs/delegated-approval.md +5 -4
  43. package/docs/development-flow.md +38 -12
  44. package/docs/lifecycle/state-machine-stabilization.md +2 -2
  45. package/docs/pdf/README.md +24 -0
  46. package/docs/pdf/codex-workflow-v2-architecture-ru.pdf +0 -0
  47. package/docs/pdf/codex-workflow-v2-chat-only-guide-ru.pdf +0 -0
  48. package/docs/pdf/codex-workflow-v2-technical-reference-ru.pdf +0 -0
  49. package/docs/pdf/requirements.txt +1 -0
  50. package/docs/pdf/sources/codex-workflow-v2-architecture-ru.md +235 -0
  51. package/docs/pdf/sources/codex-workflow-v2-chat-only-guide-ru.md +334 -0
  52. package/docs/pdf/sources/codex-workflow-v2-technical-reference-ru.md +414 -0
  53. package/docs/problem-briefs/01-pre-implementation-integrity.md +478 -0
  54. package/docs/problem-briefs/02-minimal-step-integrity.md +411 -0
  55. package/docs/problem-briefs/03-minimal-agent-context-integrity.md +358 -0
  56. package/docs/problem-briefs/04-task-dependency-and-structural-replacement-integrity.md +566 -0
  57. package/docs/problem-briefs/BRIEF-TEMPLATE.md +56 -0
  58. package/docs/problem-briefs/README.md +120 -0
  59. package/docs/problem-briefs/evidence/p01-mechanical-feasibility-corpus.md +90 -0
  60. package/docs/problem-briefs/evidence/signal-v4-pre-m3-replay.md +246 -0
  61. package/docs/release.md +17 -6
  62. package/docs/split-required-recovery.md +19 -26
  63. package/docs/validation-report.md +83 -70
  64. package/package.json +5 -1
  65. package/plugins/codex-workflow-gateway/.codex-plugin/plugin.json +1 -1
  66. package/plugins/codex-workflow-gateway/references/protocol.md +31 -9
  67. package/plugins/codex-workflow-gateway/skills/codex-workflow-gateway/SKILL.md +23 -6
  68. package/references/state-machine.md +18 -13
  69. package/references/validation-and-review.md +11 -4
  70. package/schemas/authorization-event.schema.json +64 -1
  71. package/schemas/corrective-decision-event.schema.json +48 -3
  72. package/schemas/milestone-scope-change-event.schema.json +6 -1
  73. package/schemas/milestone.schema.json +6 -1
  74. package/schemas/review-result.schema.json +17 -1
  75. package/schemas/step-review-event.schema.json +15 -0
  76. package/schemas/task-handoff-event.schema.json +18 -2
  77. package/scripts/generate-pdf-docs.py +513 -0
  78. package/scripts/run-pdf-docs.mjs +62 -0
@@ -55,39 +55,48 @@ into the mutation actor slot.
55
55
  Invalid or stale review sidecars fail closed. The workflow blocks downstream acceptance and
56
56
  normal continuation when review evidence is malformed, unverified, or commit-mismatched.
57
57
 
58
- ## Repeated failed review and remediation breaker
59
-
60
- The first failed independent review returns the Task to `needs_fix` and requires a changed or
61
- new remediation Step. After two distinct failed-review attempts, `next` returns
62
- `task plan-set with independent corrective audit`. Another Plan requires a JSON audit:
63
-
64
- ```json
65
- {
66
- "auditor": "corrective-auditor",
67
- "summary": "The corrective Step covers the latest findings without changing the Brief.",
68
- "decision": "continue-fix",
69
- "reviewedFindingIds": ["REV-001", "REV-002"]
70
- }
71
- ```
72
-
73
- Apply it with `task plan-set --corrective-audit-file <file>` only for the `continue-fix`
74
- path. The Auditor must differ from the failed-review author and cover every latest finding.
75
- `replan-required`, `split-required`, and `stop-escalate` are stop decisions: Core does not
76
- start another implementation loop.
77
-
78
- For guarded Steps, remediation attempts are also tracked in
79
- `remediation-events.jsonl`. Two ordinary remediation attempts are allowed. A third ordinary
80
- retry is blocked until `task corrective-decision` records a current corrective decision in
81
- `corrective-decisions.jsonl`. The corrective gate is derived from the guarded Step, current
82
- Plan Risk Audit, remediation history, and corrective-decision history, so it remains visible
83
- after content-only context refresh, Task Knowledge rebind, and reauthorization. `continue-fix`
84
- allows bounded continuation; `replan-required` requires an actual new Plan posture before
85
- execution; the other decisions stop or redirect ordinary execution. If that third, corrective
86
- remediation review also fails, Core enters a hard stop: `next` must report the stop without
87
- throwing, a fourth run and another `continue-fix`/`replan-required` decision are rejected,
88
- and only `split-required` or `stop-escalate` may be recorded. At the corrective boundary,
89
- `next` derives a distinct `agent:corrective-auditor:<task-id>` actor; selecting that actor is
90
- not a human approval, while auditor independence remains mandatory.
58
+ ## Repeated failed review and continuable remediation
59
+
60
+ A failed final Task review returns the same Task to `needs_fix` and requires a changed or new
61
+ remediation Step. The failed-review count is diagnostic evidence, not a lifecycle limit: another
62
+ Plan does not require a separate corrective Plan Auditor merely because two or more reviews failed.
63
+ Every replacement Plan must preserve the Task objective, requirements, and acceptance; changing
64
+ those commitments requires an explicit scope decision outside ordinary remediation.
65
+
66
+ For guarded Steps, every failed review is recorded in `remediation-events.jsonl`. Attempts one and
67
+ two retain mode `ordinary`; later attempts use mode `corrective`, but the mode does not impose a
68
+ maximum attempt ordinal. `next` continues to return `task run` for the same failed Step, and every
69
+ new completion still requires a fresh strict review bound to its exact commit. Therefore repeated
70
+ fixes cannot create an approval, while a fourth, tenth, or later reviewed attempt remains possible.
71
+
72
+ Each failed review finding may carry `route: fix` or `route: replan`. `fix` is the backward-compatible
73
+ default. `replan` is accepted only with `planConflict.planClause`, `whyFixCannotFit`, and
74
+ `minimalPlanChange`; Core retains that evidence in the hash-chained Step-review event and routes
75
+ the failed Step to `task plan-set`. Replan may change implementation Steps only. Explicit historical
76
+ `continue-fix`, `replan-required`, `split-required`, and `stop-escalate` decisions remain readable;
77
+ an explicit split or stop still outranks ordinary execution.
78
+
79
+ ### First-failure Plan-integrity recovery
80
+
81
+ A mechanically impossible Plan check must not consume the second ordinary remediation attempt
82
+ only to unlock corrective replan. After the first guarded `checks-failed` event, Core performs a
83
+ read-only bounded assessment. `next` advertises `task plan-integrity-recover` only when all of the
84
+ following are true:
85
+
86
+ - the failed Step contains an exact root `npm run <script>` or `npm run-script <script>` check;
87
+ - the named script is absent from the current root `package.json`;
88
+ - `package.json` is outside the failed Step's `allowedWrites`;
89
+ - exactly one ordinary `checks-failed` remediation event exists for the Step;
90
+ - no corrective decision exists for its second-attempt binding;
91
+ - every dirty file remains inside the Step's current `allowedWrites` and outside its
92
+ `forbiddenScope`.
93
+
94
+ The recovery appends one hash-bound `replan-required` decision for attempt ordinal 2. It preserves
95
+ the worktree and does not edit the Plan. A claimed C1 Task must present its current writer token and
96
+ then follow `task corrective-yield`; the replacement Plan still requires the existing independent
97
+ validation, Risk Audit, Human confirmation, journaled execution, readback, and renewed execution
98
+ authorization. Other check failures use the normal continuable remediation route; they do not
99
+ receive the narrow Plan-integrity shortcut, but attempt count alone never stops them.
91
100
 
92
101
  ## Atomic context refresh
93
102
 
@@ -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.
package/docs/decisions.md CHANGED
@@ -64,10 +64,11 @@ This document closes the requirement gaps identified during the V2 design review
64
64
  fails closed without changing persisted Task state. This changes navigation and
65
65
  diagnostics only; state schema 2 and protocol 1 remain unchanged.
66
66
  12. **Autonomous correction guardrail.** The initial Plan must make migration,
67
- concurrency, restart/replay, crash-window, and provider risks visible. After two failed
68
- independent reviews, another corrective Plan requires a distinct Auditor covering every
69
- latest finding. The audit is append-only artifact evidence; no Task state field or schema
70
- change is required.
67
+ concurrency, restart/replay, crash-window, and provider risks visible. Repeated failed reviews
68
+ do not impose an attempt-count stop: findings default to a same-Task fix and may request replan
69
+ only with exact Plan-conflict evidence. Attempts after the second are marked corrective for
70
+ diagnosis, remain executable, and require another strict review. Explicit split/stop decisions
71
+ remain append-only authority and are never inferred from the counter.
71
72
  13. **Content-only context refresh.** A delegate may compose reconcile, approval, knowledge
72
73
  rebind, and execution reauthorization only when the approved source classification is
73
74
  identical and only content hashes changed. Core validates both delegated transitions
@@ -191,10 +191,11 @@ Plan-declared supporting additions допустимы только когда и
191
191
  изменении source set, category/authority, gaps или conflicts используй обычный видимый процесс.
192
192
 
193
193
  После submit запусти отдельный Independent Reviewer; Reviewer не использует
194
- grant и не исправляет код. После второго failed review не запускай очередной
195
- патч: получи отдельный corrective Plan audit, охватывающий все последние findings,
196
- и передай его через `--corrective-audit-file`. Продолжай только при
197
- `decision=continue-fix`; остальные решения верни пользователю/координатору.
194
+ grant и не исправляет код. Failed review возвращает ту же Task в remediation: добавь или измени
195
+ remediation Step и снова проведи review. Количество failed reviews не требует отдельного
196
+ corrective Plan audit. Для каждого finding Reviewer использует `route=fix` по умолчанию;
197
+ `route=replan` допустим только с точным Plan clause, доказательством невозможности обычного fix и
198
+ минимальным изменением Plan. Objective, requirements и acceptance через remediation не меняются.
198
199
  Final acceptance делай
199
200
  только при exact task.final_accept option для DGR-ID, затем штатный merge.
200
201
  Если option отсутствует, grant истёк, scope не совпал или требуется смысловое
@@ -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
@@ -73,12 +83,21 @@ to be repeated before merge.
73
83
  The Technical Planner performs a risk review before authorization. Migration work includes a
74
84
  populated forward-upgrade check; concurrent state includes deterministic races; restart,
75
85
  replay, and crash claims include restart/crash-window evidence; provider work includes
76
- failure injection and hidden-default verification. After two failed independent reviews,
77
- another Plan requires a distinct corrective Auditor and `--corrective-audit-file`. Only a
78
- `continue-fix` audit may continue; replan, split, and stop decisions return to coordination.
79
- For guarded remediation, a third ordinary retry is blocked until a current
80
- `task corrective-decision` exists for the same Step and Plan binding. If that corrective
81
- attempt fails review, the third failure is a hard stop and no fourth run is permitted.
86
+ failure injection and hidden-default verification. Repeated failed reviews remain on the same
87
+ Task. They require a new remediation Step for final Task review, or another implementation and
88
+ fresh strict review for a failed guarded Step; they do not require a separate corrective Auditor
89
+ based only on attempt count. Guarded attempts above two are recorded as `corrective` and remain
90
+ executable. A reviewer routes to `replan` only with an exact Plan obstruction and minimal Plan
91
+ change; ordinary findings default to `fix`. Remediation cannot change the Task objective,
92
+ requirements, or acceptance.
93
+
94
+ One bounded exception avoids a deliberately repeated failure for an older authorization without
95
+ P01-A evidence or a contradiction that becomes observable only after execution starts. If the first guarded check failure
96
+ is caused by an absent root npm script that the Step cannot add because `package.json` is outside
97
+ its `allowedWrites`, fresh `next` advertises `task plan-integrity-recover`. The command records only
98
+ the exact evidence-bound early `replan-required` posture; it never edits source, Plan, or Git.
99
+ Continue through the advertised corrective yield and corrective replan rather than calling
100
+ `task run` again.
82
101
 
83
102
  Execution authorization and final acceptance use the human path by default. If the user has
84
103
  previously issued an active delegation grant for the exact transition and scope, the named
@@ -95,7 +114,10 @@ Discovery -> Milestone planning -> execution authorization -> active
95
114
  -> final acceptance -> accepted
96
115
  ```
97
116
 
98
- A Milestone Plan records outcome, success signal, acceptance, checks, and Task membership.
117
+ A Milestone Plan records outcome, success signal, acceptance, checks, Task membership, and the
118
+ canonical Task dependency DAG. Every membership explicitly supplies `dependsOnTaskIds`, including
119
+ `[]`. A required consumer may depend only on required members of the same Milestone; duplicate,
120
+ self, dangling, external, non-required-provider, and cyclic edges are rejected before commit.
99
121
  Membership is `required`, `waived`, or `cancelled`; non-required entries require a reason.
100
122
  Changing the Plan increments the membership revision, supersedes execution authorization,
101
123
  and prevents new linked Tasks from starting. A Task that has started cannot be removed;
@@ -115,18 +137,22 @@ Milestone Autonomy Contract may instead use `milestone autonomy-evolve` for memb
115
137
  changes while the outcome, success signal, acceptance, checks, discovery, and base branch
116
138
  remain unchanged. The same contract may complete an atomic content-only Task context refresh
117
139
  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`.
140
+ journaled recovery across `state.json`, `plan.json`, and `scope-change-events.jsonl`. The initial
141
+ Plan uses the same recovery machinery for its exact two-file `state.json` + `plan.json` commit and
142
+ does not manufacture a scope-change event.
119
143
 
120
144
  A Milestone has no integration branch. Validation requires all required Tasks to be
121
145
  `merged`, checks the current clean base branch, and writes evidence plus Result. Final
122
146
  acceptance binds those artifacts to the unchanged base HEAD. Cancellation records a reason
123
147
  and never changes Task state or reverts merged commits.
124
148
 
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
149
+ Repository-level `next` considers Milestone membership and dependencies before it dispatches a
150
+ Task. A linked Task is actionable only while its Milestone is `active`, its current membership is
151
+ `required`, and every declared required predecessor is `merged`. Handoff prepare, claim before
152
+ lease acquisition, and Task start use the same predicate. Unstarted `waived`/`cancelled`
153
+ memberships and Tasks belonging to
128
154
  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.
155
+ a workspace does not bypass an unsatisfied Milestone predecessor.
130
156
 
131
157
  After successful Milestone validation, `next` emits `requiredHumanGate` containing the
132
158
  Milestone revision, Plan/Result/evidence hashes, validated base HEAD, and a deterministic
@@ -266,7 +266,7 @@ The explorer must be exhaustive over semantic classes, bounded over cardinality,
266
266
  | Actor | human, valid delegate, claimant, other |
267
267
  | Lease | none, valid-owned, valid-other, stale |
268
268
  | Attempts | 0, 1, 2, 3+ |
269
- | Corrective posture | none, decision-needed, continue-fix, replan, split, stop, hard-stop, recovery-needed |
269
+ | Corrective posture | none, automatic-continue, explicit continue-fix, replan, split, stop, recovery-needed |
270
270
  | Knowledge binding | active, stale, awaiting approval, conflicting |
271
271
  | Git | clean-bound, clean-diverged, dirty, malformed |
272
272
  | Authorization | absent, current, stale, superseded |
@@ -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,235 @@
1
+ ---
2
+ title: Codex Workflow V2: архитектура beta.12
3
+ subtitle: Источники истины, lifecycle, роли, delegation, зависимости Tasks и границы доверия
4
+ part: Часть 1 из 3 | Архитектура
5
+ document_version: 2.0
6
+ date: 27 августа 2026
7
+ subject: Архитектура и границы Codex Workflow V2 beta.12
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.12 гарантирует
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.12 не гарантирует
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 не ограничивает число попыток. Попытки 1-2 имеют mode `ordinary`, последующие —
217
+ `corrective`; все исполнимы и требуют нового strict review. `route=fix` продолжает Task, а
218
+ `route=replan` допустим только с точным Plan conflict и меняет лишь implementation Steps, не objective,
219
+ requirements или acceptance. Explicit `split-required` и `stop-escalate` остаются stop/redirect decisions.
220
+
221
+ beta.11 `task plan-integrity-recover` существует для одного первого checks-failed legacy/late case:
222
+ отсутствует exact root npm script и текущий Step не может изменить package.json. Recovery не меняет
223
+ worktree или Plan и не создаёт synthetic second failure; он записывает bound `replan-required`.
224
+
225
+ > **Стоп P04-A:** `split-required` возвращает `STRUCTURAL_REPLACEMENT_REQUIRED` и `structuralReplacementAvailable=false`. Нельзя вызывать retained replacement command, потреблять replacement Discovery или вручную менять topology. Продолжение возможно только после P04-B/P05.
226
+
227
+ # 10. Operational checklist
228
+
229
+ - exact package version установлен, bundled gateway соответствует release и переустановлен;
230
+ - handshake подтверждает protocol 2, state schema 2 и beta.12 capabilities;
231
+ - каждый mutation следует свежему `status -> next` и exact option contract;
232
+ - semantic unknowns и human gates не маскируются delegation;
233
+ - Task chats создаёт coordinator, credentials остаются только в памяти;
234
+ - dependencies, progress и review posture берутся из Core projections;
235
+ - local state не редактируется вручную; release и package update выполняются только после safe preflight и обязательных checks.