@yunhozz/arc 0.1.7 → 0.1.10

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 (92) hide show
  1. package/MANIFEST.sha256 +86 -61
  2. package/README.md +1 -1
  3. package/claude/agents/{arc-coder.md → arc-implementer.md} +7 -7
  4. package/claude/agents/arc-planner.md +4 -4
  5. package/claude/agents/arc-qa.md +4 -4
  6. package/claude/agents/arc-reviewer.md +5 -5
  7. package/claude/agents/arc-scouter.md +3 -3
  8. package/claude/skill/SKILL.md +7 -7
  9. package/claude/skill/models.toml +3 -3
  10. package/claude/skill/references/commit.md +22 -7
  11. package/claude/skill/references/coordination.md +25 -18
  12. package/claude/skill/references/git-recovery.md +1 -1
  13. package/claude/skill/references/handoff-prep.md +25 -2
  14. package/claude/skill/references/handoff.md +106 -24
  15. package/claude/skill/references/planning.md +73 -22
  16. package/claude/skill/references/verification.md +155 -17
  17. package/claude/skill/runtime/acceptance.mjs +68 -0
  18. package/claude/skill/runtime/assignment.mjs +42 -0
  19. package/claude/skill/runtime/bootstrap.mjs +35 -0
  20. package/claude/skill/runtime/cooperative-schema.mjs +55 -0
  21. package/claude/skill/runtime/cooperative.mjs +136 -0
  22. package/claude/skill/runtime/evaluate.mjs +40 -4
  23. package/claude/skill/runtime/external.mjs +51 -0
  24. package/claude/skill/runtime/gate.mjs +7 -7
  25. package/claude/skill/runtime/git-evidence.mjs +46 -0
  26. package/claude/skill/runtime/operations.mjs +2 -2
  27. package/claude/skill/runtime/role-policy.json +64 -19
  28. package/claude/skill/runtime/schema.mjs +1 -0
  29. package/claude/skill/runtime/scope.mjs +36 -0
  30. package/claude/skill/runtime/store.mjs +25 -4
  31. package/claude/skill/runtime/verification.mjs +123 -0
  32. package/claude/skill/scripts/model_config.py +2 -2
  33. package/codex/agents/{arc-coder.toml → arc-implementer.toml} +8 -8
  34. package/codex/agents/arc-planner.toml +6 -6
  35. package/codex/agents/arc-qa.toml +6 -6
  36. package/codex/agents/arc-reviewer.toml +6 -6
  37. package/codex/agents/arc-scouter.toml +5 -5
  38. package/codex/skill/SKILL.md +9 -9
  39. package/codex/skill/models.toml +3 -3
  40. package/codex/skill/references/commit.md +23 -8
  41. package/codex/skill/references/coordination.md +25 -18
  42. package/codex/skill/references/git-recovery.md +2 -2
  43. package/codex/skill/references/handoff-prep.md +25 -2
  44. package/codex/skill/references/handoff-worktree.md +4 -4
  45. package/codex/skill/references/handoff.md +116 -34
  46. package/codex/skill/references/planning.md +76 -23
  47. package/codex/skill/references/verification.md +160 -22
  48. package/codex/skill/runtime/acceptance.mjs +68 -0
  49. package/codex/skill/runtime/assignment.mjs +42 -0
  50. package/codex/skill/runtime/bootstrap.mjs +35 -0
  51. package/codex/skill/runtime/cooperative-schema.mjs +55 -0
  52. package/codex/skill/runtime/cooperative.mjs +136 -0
  53. package/codex/skill/runtime/evaluate.mjs +40 -4
  54. package/codex/skill/runtime/external.mjs +51 -0
  55. package/codex/skill/runtime/gate.mjs +7 -7
  56. package/codex/skill/runtime/git-evidence.mjs +46 -0
  57. package/codex/skill/runtime/operations.mjs +2 -2
  58. package/codex/skill/runtime/role-policy.json +64 -19
  59. package/codex/skill/runtime/schema.mjs +1 -0
  60. package/codex/skill/runtime/scope.mjs +36 -0
  61. package/codex/skill/runtime/store.mjs +25 -4
  62. package/codex/skill/runtime/verification.mjs +123 -0
  63. package/codex/skill/scripts/model_config.py +3 -3
  64. package/lib/cli/root.mjs +1 -0
  65. package/lib/cli/workflow.mjs +21 -0
  66. package/lib/installer/manifest.mjs +1 -1
  67. package/lib/installer/plan.mjs +27 -13
  68. package/lib/installer/targets.mjs +1 -1
  69. package/lib/models/config.mjs +1 -1
  70. package/lib/models/profiles.mjs +1 -1
  71. package/lib/policy/placement.mjs +6 -6
  72. package/lib/policy/render.mjs +3 -3
  73. package/lib/policy/role-policy.json +64 -19
  74. package/lib/release/artifact.mjs +1 -1
  75. package/lib/runtime/acceptance.mjs +68 -0
  76. package/lib/runtime/assignment.mjs +42 -0
  77. package/lib/runtime/bootstrap.mjs +35 -0
  78. package/lib/runtime/cooperative-schema.mjs +55 -0
  79. package/lib/runtime/cooperative.mjs +136 -0
  80. package/lib/runtime/evaluate.mjs +40 -4
  81. package/lib/runtime/external.mjs +51 -0
  82. package/lib/runtime/gate.mjs +7 -7
  83. package/lib/runtime/git-evidence.mjs +46 -0
  84. package/lib/runtime/operations.mjs +2 -2
  85. package/lib/runtime/schema.mjs +1 -0
  86. package/lib/runtime/scope.mjs +36 -0
  87. package/lib/runtime/store.mjs +25 -4
  88. package/lib/runtime/verification.mjs +123 -0
  89. package/package.json +4 -2
  90. package/claude/skill/scripts/__pycache__/model_config.cpython-314.pyc +0 -0
  91. package/codex/skill/scripts/__pycache__/apply-models.cpython-314.pyc +0 -0
  92. package/codex/skill/scripts/__pycache__/model_config.cpython-314.pyc +0 -0
@@ -19,6 +19,19 @@ text presence alone cannot establish agent compliance. Distinguish tested behavi
19
19
  Unexpected failures trigger diagnosis and stop dependent work; expected failure-first RED does not authorize unrelated
20
20
  repairs.
21
21
 
22
+ ## Evidence after plan history rewrite
23
+
24
+ After an approved execution-time plan rewrite, verify new HEAD, approved plan version/content and old-to-new SHA mapping;
25
+ descendant implementation content and task boundaries; and remaining staged/unstaged/untracked state. Preserve the actual
26
+ approval chronology and recoverable previous contents in the canonical handoff record. The latest version in the original
27
+ commit does not establish approval before its actual approval time.
28
+
29
+ SHA change alone does not invalidate all prior acceptance evidence. Check whether evidence bound to an exact HEAD,
30
+ document or policy can be linked to the new state. If it cannot be linked, or its meaning is affected, repeat affected
31
+ checks and required rechecks. Preserve existing runtime evidence invalidation and exact-state requirements; do not rewrite
32
+ old fingerprints to imply a run against the new HEAD. Refresh affected briefs and gates before dependent work.
33
+ Structural checks establish written-contract alignment, not live agent compliance or successful Git history replay.
34
+
22
35
  ## Reviewer timing and task acceptance
23
36
 
24
37
  Task acceptance and its focused commit need only the task's risk-scaled evidence: a FRESH QA instance per task that
@@ -30,17 +43,17 @@ Reviewer reviews once on the final full change after all plan tasks are accepted
30
43
  QA recheck at the final relevant state; without a plan, Reviewer follows QA before acceptance.
31
44
  A task commit does not mark unperformed final verification complete.
32
45
 
33
- Fresh-per-task rules apply to Coder and QA, not Reviewer. Orchestrator may reuse a Reviewer only while independent
46
+ Fresh-per-task rules apply to Implementer and QA, not Reviewer. Orchestrator may reuse a Reviewer only while independent
34
47
  of implementation and self-review, relevant assignment context remains valid, and refreshed review scope, target
35
48
  state, and evidence are provided; otherwise assign another independent Reviewer. Reusing a Reviewer does not reuse
36
49
  an earlier verdict or waive required review timing or coverage.
37
50
 
38
51
  For final Reviewer findings on already committed plan work, Orchestrator defines a follow-up task and required
39
- planning/approvals. Coder leaves corrections uncommitted during rechecks. Orchestrator refreshes the latest committed
52
+ planning/approvals. Implementer leaves corrections uncommitted during rechecks. Orchestrator refreshes the latest committed
40
53
  state plus uncommitted diff and changed-file list in the Reviewer artifact/brief. Reuse an independent Reviewer or
41
- assign another independent Reviewer as needed. Repeat Coder → Reviewer without QA reassignment until findings are
54
+ assign another independent Reviewer as needed. Repeat Implementer → Reviewer without QA reassignment until findings are
42
55
  resolved; Orchestrator then accepts the corrections and creates one focused follow-up commit.
43
- Final QA findings retain Coder correction and QA recheck before a new focused commit.
56
+ Final QA findings retain Implementer correction and QA recheck before a new focused commit.
44
57
  Do not automatically amend/reset or duplicate the original task commit. Scope expansion keeps existing new
45
58
  planning and approval obligations.
46
59
 
@@ -70,19 +83,19 @@ conditions and expected result to observations. Partial confirmation, out-of-sco
70
83
  environment-blocked gaps stay unverified; omit no criteria. PASS, if used, means only run status.
71
84
  Structural checks prove structure only, not behavior, installation, or live agent compliance.
72
85
 
73
- For QA execution failure or an unmet criterion within the current task, Orchestrator defaults to the current Coder
86
+ For QA execution failure or an unmet criterion within the current task, Orchestrator defaults to the current Implementer
74
87
  for correction and the current QA for a post-fix recheck, subject to the context, task-boundary and amendment rules in
75
88
  [coordination](coordination.md). The finding alone does not create a new task. QA reruns the
76
89
  reproduction path and invalidated related checks before Reviewer, reporting the actual actor, target state, outcomes, and limitations,
77
90
  and the prior finding resolved, unresolved, or unverified with evidence. Reusing QA does not reuse stale evidence.
78
- An unresolved finding returns to Coder correction and another QA recheck before Reviewer.
91
+ An unresolved finding returns to Implementer correction and another QA recheck before Reviewer.
79
92
  Environment blocks, missing checks, and out-of-scope criteria are evidence gaps, not presumed defects;
80
93
  Reviewer does not substitute for QA evidence. Outside the required final plan correction loop,
81
94
  Orchestrator decides when a Reviewer recheck is warranted by the changed scope and independence.
82
95
 
83
96
  For an acceptance-linked finding Reviewer reports criterion, expected behavior, observed problem, related source,
84
97
  reproduction conditions and steps, and evidence, labeling each source-inferred or execution-observed,
85
- without running QA tests. Outside the final plan Reviewer correction exception, Orchestrator routes it to Coder and QA recheck. Reviewer still handles structure, design,
98
+ without running QA tests. Outside the final plan Reviewer correction exception, Orchestrator routes it to Implementer and QA recheck. Reviewer still handles structure, design,
86
99
  factual, and security findings; observable security/interface issues may need both QA and Reviewer.
87
100
 
88
101
  Orchestrator accepts using verdicts, findings, rechecks, and remaining gaps, not an overall run result;
@@ -95,9 +108,9 @@ Read brief-cited `references/superpowers/test-driven-development/SKILL.md`; pres
95
108
  ### Final plan Reviewer correction loop
96
109
 
97
110
  For a plan's final overall Reviewer findings, including behavior findings, Orchestrator assigns
98
- Coder → Reviewer recheck with no QA reassignment. Repeat corrections and Reviewer rechecks until findings are resolved;
111
+ Implementer → Reviewer recheck with no QA reassignment. Repeat corrections and Reviewer rechecks until findings are resolved;
99
112
  the initial single full review does not prohibit necessary rechecks. Before the initial final overall Reviewer,
100
- risk-required checks and QA execution failures or unmet criteria still require Coder correction → QA recheck.
113
+ risk-required checks and QA execution failures or unmet criteria still require Implementer correction → QA recheck.
101
114
  This exception applies only to findings from the final overall Reviewer of work with a plan.
102
115
  Work without a plan retains its existing verification flow. Scope expansion, separate mandatory obligations,
103
116
  or unresolved evidence gaps hold affected work for Orchestrator to resolve and obtain required approvals.
@@ -120,14 +133,14 @@ For Orchestrator, **Evidence verdict**: each criterion is proven, unmet, or unve
120
133
 
121
134
  ## Risk-scaled execution
122
135
 
123
- Orchestrator assigns edits exclusively to Coder except under the Orchestrator direct path in [handoff](handoff.md#orchestrator-direct-path-for-small-tasks), and determines affected
136
+ Orchestrator assigns edits exclusively to Implementer except under the Orchestrator direct path in [handoff](handoff.md#orchestrator-direct-path-for-small-tasks), and determines affected
124
137
  behavior, risk, and smallest meaningful verification.
125
138
 
126
139
  | Risk | Minimum flow |
127
140
  |---|---|
128
- | Small, low risk | Coder, or Orchestrator direct path → Orchestrator's focused checks → acceptance |
129
- | Ordinary behavior | Coder → independent QA → acceptance |
130
- | Significant/high risk | Coder → QA → independent Reviewer of the final full change → acceptance; with a plan, each plan task Coder → FRESH QA → acceptance/commit satisfies the QA step, then independent Reviewer once on the final full change after all plan tasks |
141
+ | Small, low risk | Implementer, or Orchestrator direct path → Orchestrator's focused checks → acceptance |
142
+ | Ordinary behavior | Implementer → independent QA → acceptance |
143
+ | Significant/high risk | Implementer → QA → independent Reviewer of the final full change → acceptance; with a plan, each plan task Implementer → FRESH QA → acceptance/commit satisfies the QA step, then independent Reviewer once on the final full change after all plan tasks |
131
144
 
132
145
  Ordinary and significant plan tasks need a FRESH QA before acceptance; only small, low-risk tasks may be accepted on
133
146
  Orchestrator focused checks. Small, low risk means narrow, understood, readily reversible, and verifiable by focused
@@ -143,7 +156,7 @@ a plan keeps Reviewer after QA before acceptance. Preserve specific approved obl
143
156
  before dependent implementation. Reuse evidence only when scope, relevant state, independence, freshness, and flow
144
157
  position satisfy each covered requirement; changes, failures, or missing/conflicting evidence invalidate affected reuse.
145
158
  QA checks independently without edits; Reviewer independently reads the final full change after QA for significant
146
- work, without QA, planning, edits, delegation, or completion decisions. Orchestrator routes fixes to Coder,
159
+ work, without QA, planning, edits, delegation, or completion decisions. Orchestrator routes fixes to Implementer,
147
160
  obtains affected QA rechecks outside the final plan Reviewer correction exception and required final review, and accepts after findings/evidence gaps are resolved or
148
161
  explicitly dispositioned.
149
162
 
@@ -155,11 +168,136 @@ After gates hold, continue approved scope without saved documents through requir
155
168
  Completion continuity above; a role report alone does not complete the work.
156
169
 
157
170
 
171
+ ## Verification lifecycle in the cooperative CLI
172
+
173
+ The supported `workflow` path is an approved complete spec+plan. No-plan, small-task and document omission paths remain
174
+ `cooperative.unsupported`; this outcome does not imply a violation of existing ARC policy or a new obligation to write documents.
175
+ The CLI does not execute checks or invoke Reviewer. All actors, results and verdicts are `operator-attested`; they do not prove
176
+ identity, actual independence, semantic sufficiency or enforced execution.
177
+
178
+ An Orchestrator actor (`actor.role: "orchestrator"`) registers a verification contract by recording
179
+ `data: {kind: "task", task: {...}}` in `acceptance-evidence` through `record`. The task specifies `id`, absolute `paths`,
180
+ `criteria`, `requiredChecks`, `dependencies`, `approvalRef`, `approvalVersion`, `documentVersion`,
181
+ `scopeVersion` and `targetVersion`. Only pending tasks can be registered; this record is neither acceptance nor a commit.
182
+ Each requiredChecks descriptor is `{executable, args, cwd, env, outputs}`; executable, cwd and outputs are absolute paths.
183
+ cwd and outputs must be within the workspace. Do not include Reviewer in task requiredChecks.
184
+
185
+ `changeFingerprints.tasks[taskId]` and `changeFingerprints.final` in `status` are independent observations.
186
+ They include read-only Git inventory/index observations and current regular-file bytes, modes and deletions. Task fingerprints
187
+ cover owned paths; the final fingerprint covers the whole repository snapshot. Unsupported observations such as symlinks,
188
+ submodules and unmerged indexes cause a hold. This is not a sandbox that atomically locks observation and execution.
189
+ Leave runtimeHash drift as stale/hold; do not automatically update the stored version or convert it through migration or renewed approval.
190
+
191
+ `operation: "check"` in `prepare` accepts `taskId` and
192
+ `arguments: {scope: "task", actor: {id, role: "qa"}, descriptor, changeFingerprint, findingIds?}`.
193
+ Actor ID attestations must be independent of Implementer and Orchestrator; QA/Implementer reuse across tasks is rejected. The descriptor must
194
+ exactly match the registered requiredChecks. After the intent is persisted, the responsible role executes within its existing approved scope.
195
+ `result` or `reconcile` records `intentId` and `{status, messageRef, data}`. data specifies the same
196
+ `actor`, `descriptor` and `scope` as the intent, `taskId` for tasks, `changeFingerprint`, and
197
+ `verdict: "proven" | "unmet" | "unverified"`. Even a succeeded/proven result is valid only for that change version.
198
+ This is an operator verdict record; it does not replace semantic proof of a criterion or Orchestrator acceptance.
199
+ Failures, unknown, mismatch and unverified outcomes are not passing evidence. Preserve previous results and failure records.
200
+
201
+ A failed check/review leaves an open finding. Link a separate finding to an existing check/review through `record` with
202
+ `data: {action: "open", id, checkId, message}`. After a Implementer fix, record
203
+ `data: {action: "resolve", id, actor: {id, role: "implementer"}, changeFingerprint}` and the fix evidence messageRef.
204
+ The actor must be the Implementer assigned to that task, or a relevant task for an overall finding. This marks the finding resolved;
205
+ it becomes closed only when a subsequent prepare includes it in `findingIds` and revalidation passes for the same change version.
206
+ Earlier QA failures retain the Implementer→QA recheck requirement.
207
+
208
+ `operation: "review"` uses `scope: "final"`, `actor.role: "reviewer"` and
209
+ `descriptor: {kind: "source-review", paths: [...]}`, without taskId. The initial final review requires acceptance of all tasks
210
+ and current required task QA evidence. Reviewer is not a prerequisite gate for task acceptance or focused commits.
211
+ For final Reviewer findings in supported plan work, repeat Implementer resolution→Reviewer revalidation without QA reassignment.
212
+ Do not present earlier QA evidence as execution evidence for a subsequent fix. This exception does not omit separate unresolved QA failures.
213
+
214
+ Scope, document and approval change records do not overwrite history. Specifying `data.affectedTaskIds` invalidates task,
215
+ verification and acceptance evidence for those tasks and their dependency chain; omitting it holds all tasks. Final evidence also becomes stale.
216
+ Preserve evidence for unaffected independent tasks. Orchestrator determines semantic impact. Affected tasks require a new approval record
217
+ for the current scope and an updated task contract before preparation; earlier approvals cannot revive them. New checks/reviews and
218
+ finding revalidation are also required. Current evidence supersedes earlier failures without deleting them; acceptance, commits and final completion remain Orchestrator decisions.
219
+
220
+ ### Task acceptance and focused commit reconciliation in the cooperative CLI
221
+
222
+ In the current plan mode, `prepare` supports `operation: "accept"` and `operation: "commit"`.
223
+ Acceptance is an Orchestrator attestation specifying `actor.role: "orchestrator"`, `taskId`, and, in `arguments`,
224
+ `messageRef`, the same `criteria` as the task, exact `checkIds` for current required QA, all task
225
+ `findingIds` and the current `changeFingerprint`. The latest QA result for each required descriptor must be
226
+ passed/proven, and findings must be closed through Implementer fixes and QA rechecks.
227
+ A successful attestation marks the task accepted; passing commands or Implementer reports alone do not constitute acceptance.
228
+ The provenance is `operator-attested`; the operator confirms semantic criterion satisfaction and actor identities.
229
+
230
+ At acceptance, the code pins the actual index tree, staged diff, paths and task fingerprint together. Orchestrator stages only
231
+ approved task paths beforehand and confirms required QA for that index state. Unrelated paths, changes from another registered
232
+ task, or unstaged/untracked changes within scope cause a hold. The code cannot automatically distinguish semantically unrelated
233
+ hunks within the same file; Orchestrator reads the actual diff to confirm them.
234
+
235
+ `operation: "commit"` in `prepare` references the exact acceptance through `arguments: {"acceptanceId": "acceptance requestId"}`.
236
+ The code checks that the current approval, task contract, QA, findings and index match acceptance, then persists a durable intent
237
+ with the expected parent, tree, paths and residual paths. The CLI does not stage or commit.
238
+ Orchestrator creates one focused implementation commit matching these expectations.
239
+
240
+ Then submit `intentId`, `actor.role: "orchestrator"`, and
241
+ `result: {"status": "succeeded", "messageRef": "actual result evidence", "data": {"commit": "full OID"}}`
242
+ through `reconcile` or result-form `result`. The CLI rereads the actual commit object, parent, tree, paths, HEAD, index and residual changes from local Git.
243
+ Only a complete match updates target HEAD and marks the task committed. Failure, unknown and mismatch observations and actual
244
+ history are preserved; the target is not updated arbitrarily. Reusing the same request or a completed intent does not authorize
245
+ a second effect. After a failure, read the actual state, resolve the cause and reconcile the existing intent.
246
+
247
+ Do not rewrite earlier QA fingerprints after a successful commit. Separate post-commit file/index observations detect subsequent
248
+ changes. Under the existing rules, final review requires current task evidence and the final fingerprint.
249
+ A changed runtimeHash follows the existing stale/hold rules; the stored version is not automatically updated.
250
+
158
251
  [ARC role policy: contract begin]
159
252
  Generated from lib/policy/role-policy.json; do not edit this managed section manually.
160
253
  - [git.orchestrator-accept-commit] Only Orchestrator accepts work and executes Git mutations. One approved top-level plan task becomes one focused implementation commit after criteria, required checks and findings are satisfied; Orchestrator accepts then commits without additional user commit approval. Reports, passing checks and Reviewer opinions do not replace acceptance. Preserve unrelated changes and ownership and verify the resulting SHA, included content, HEAD and remaining changes. Existing small-task direct and plan-omission paths are unchanged.
161
- - [review.significant-no-plan] For significant/high-risk work without a plan: Coder → QA and required QA rechecks → Reviewer of the final full change → Orchestrator acceptance. MUST NOT omit Reviewer merely because no plan exists. This creates no new plan obligation.
162
- - [review.significant-plan] For significant/high-risk plan work: each task uses Coder → fresh QA as required → Orchestrator acceptance and focused commit. After all tasks are accepted and required QA is complete, Reviewer reviews the final full change once. Reviewer is NOT a per-task or per-commit required gate. Preserve required checks and necessary finding rechecks.
163
- - [review.final-plan-recheck] For final overall Reviewer findings on plan work, including behavior findings, use Coder → Reviewer without QA reassignment; repeat until resolved. This exception applies only at the final plan stage. Preserve required QA and QA failure rechecks before initial final review and outside this exception.
254
+ - [review.significant-no-plan] For significant/high-risk work without a plan: Implementer → QA and required QA rechecks → Reviewer of the final full change → Orchestrator acceptance. MUST NOT omit Reviewer merely because no plan exists. This creates no new plan obligation.
255
+ - [review.significant-plan] For significant/high-risk plan work: each task uses Implementer → fresh QA as required → Orchestrator acceptance and focused commit. After all tasks are accepted and required QA is complete, Reviewer reviews the final full change once. Reviewer is NOT a per-task or per-commit required gate. Preserve required checks and necessary finding rechecks.
256
+ - [review.final-plan-recheck] For final overall Reviewer findings on plan work, including behavior findings, use Implementer → Reviewer without QA reassignment; repeat until resolved. This exception applies only at the final plan stage. Preserve required QA and QA failure rechecks before initial final review and outside this exception.
257
+ - [planning.plan-amend] During approved task execution, mechanical plan progress records need no new user approval; changed goals, scope, criteria, method, risk, dependencies or required verification require revised-version approval and preparation before affected work. In both cases Orchestrator amends the original planning-document commit at a safe boundary, without a separate document or fixup commit. Preserve actual approval chronology, recoverable old/new contents, hashes, versions and SHA mappings; never retroactively authorize earlier work. Rewrite only unpublished, unshared local linear history with clear ownership and no merges; stop on unknown publication, ownership, unexpected state or replay conflicts, without force push or a fallback document commit. Preserve implementation task boundaries and revalidate affected evidence. See planning, handoff-prep, commit and verification for the full contract.
164
258
  - [platform.claude] Existing per-role tool allowlists reduce available tools; Bash and role contracts are not a filesystem sandbox. A role-scoped Git guard is a separate integration and is not supplied by these policy sections alone.
165
259
  [ARC role policy: contract end]
260
+
261
+
262
+ ## External operations and recovery in the cooperative CLI
263
+
264
+ The three phases support state, documents and assignment; scope, verification, acceptance and focused commits; and external approval, results and audit recovery.
265
+ Use `status.support` to inspect all nine areas and their limits. The supported mode is `plan` with spec+plan; no-plan and omission are unsupported. The CLI does not execute native/provider calls or push, merge, deploy or publish.
266
+ User approvals and execution results confirmed by the operator are `operator-attested`, with `nativeVerified: false` and
267
+ `remoteVerified: false`. Blocking direct calls outside the CLI and independent remote verification are not provided.
268
+
269
+ Orchestrator records an explicit approval it has already confirmed through `record` with
270
+ `evidence: {kind: "external-approval", messageRef, data: {operation, scope, descriptor}}`.
271
+ `scope` is an array of unique absolute paths within the checkout. Local commit approval does not authorize external operations.
272
+ Include the exact action, scope and target in the approval, and record every descriptor field below.
273
+
274
+ | operation | descriptor fields |
275
+ |---|---|
276
+ | push | repository, destination, refspec, sourceOid, expectedRemoteOid |
277
+ | merge | repository, changeRef, targetRef, expectedTargetOid |
278
+ | deploy | service, project, environment, artifactId, destination |
279
+ | publish | service, namespace, name, version, artifactHash, destination |
280
+
281
+ Git OIDs are full 40/64-character lowercase hex values; artifactHash is `sha256:<64-hex>`. Without a remote observation,
282
+ an OID is an expected value asserted by the user, not verified remote state. destination must be an identifier without secrets.
283
+ Do not submit URL userinfo, query or fragment components, or authentication information such as passwords, tokens or credentials.
284
+ The CLI rejects recognized credential inputs before persistence, but cannot determine whether every arbitrary string contains a secret.
285
+
286
+ Pass `{requestId, expectedRevision, actor: {id, role: "orchestrator"}, operation,
287
+ arguments: {approvalRef, scope, descriptor}}` to `prepare`. approvalRef matches the external approval messageRef.
288
+ An intent is persisted only when the exact approval, scope/target versions and runtime version match and no effect is unresolved.
289
+ After confirming `allow` and `persisted: true`, Orchestrator performs the external operation within its separately approved scope.
290
+ This CLI does not expand that execution authority.
291
+
292
+ `result`/`reconcile` accepts `{requestId, expectedRevision, actor, intentId,
293
+ result: {status, messageRef, data: {operation, scope, descriptor}}}`. intentId is the prepare requestId.
294
+ Target mismatches, unknown outcomes and stale results cause a hold while preserving earlier attestations. After an interruption,
295
+ use `status` to inspect the intent, `state.requests`, `state.audit` and `state.results`, and investigate whether the effect occurred.
296
+ Reconcile the investigation result against the same intent rather than preparing again or reusing the same approval to execute again.
297
+ Cancellation additionally requires a `notExecutedEvidence: {messageRef}` attestation that the operation was not executed.
298
+ The approval remains consumed after cancellation. Do not resolve version drift through automatic updates, migration or renewed permission.
299
+ Report the cause of the hold to Orchestrator.
300
+
301
+ Even succeeded results are operator attestations, not independent remote verification. `audit` retains the
302
+ request→decision→intent→result→resolution linkage, but is a locally editable record rather than tamper-proof security evidence.
303
+ Do not retry while the actual external outcome is uncertain.
@@ -0,0 +1,68 @@
1
+ import path from 'node:path';
2
+ import {fingerprintRequest} from './store.mjs';
3
+ import {validateGitPreflight,validateGitCommitResult} from './git-evidence.mjs';
4
+ import {within} from './scope.mjs';
5
+ const reconciliations=new WeakMap();
6
+ export function verifiedCooperativeReconciliation(decision,state){const proof=reconciliations.get(decision);return !!proof&&proof.before===fingerprintRequest(state)&&proof.after===fingerprintRequest(decision.proposedTransition);}
7
+ const completed=(state,id)=>state.tasks?.some(t=>t.id===id&&t.status==='committed'&&!t.invalidated)&&state.commits?.some(c=>c.taskId===id&&c.observationSource==='local-git'&&state.intents.some(i=>i.operation==='commit'&&i.requestId===c.requestId&&i.taskId===id&&i.status==='succeeded'));
8
+ const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
9
+ const text=v=>typeof v==='string'&&v.length>0;
10
+ const list=v=>Array.isArray(v)&&v.every(text)&&new Set(v).size===v.length;
11
+ const exact=(a,b)=>list(a)&&list(b)&&same([...a].sort(),[...b].sort());
12
+ const fields=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).every(k=>keys.includes(k));
13
+ const semanticLimit='Semantically unrelated hunks inside the same file require Orchestrator inspection; path and byte evidence cannot distinguish them automatically.';
14
+ const base=state=>({expectedRevision:state?.revision??0,coverage:{enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false},semanticLimit,requiredEvidence:[],nextActions:[],proposedTransition:null});
15
+ const hold=(state,reason)=>({...base(state),decision:'hold',ruleIds:['cooperative.acceptance'],reason});
16
+ const allow=(state,transition)=>({...base(state),decision:'allow',ruleIds:['cooperative.acceptance'],proposedTransition:transition});
17
+ const approval=(state,id)=>state.records.filter(r=>r.kind==='approval'&&(!r.data.affectedTaskIds||r.data.affectedTaskIds.includes(id))).at(-1);
18
+ function authorized(state,task){const a=approval(state,task?.id);return state.mode==='plan'&&task&&!task.invalidated&&a?.source==='operator-attested'&&a.targetVersion===state.targetVersion&&task.targetVersion===state.targetVersion&&task.scopeVersion===a.scopeVersion&&task.approvalRef===a.messageRef&&task.approvalVersion===a.data.approvalVersion&&task.documentVersion===a.data.documentVersion;}
19
+ function checkEvidence(state,task,a,changes){
20
+ if(!same(a.criteria,task.criteria)||!task.criteria.length||!list(a.checkIds)||!list(a.findingIds)||a.changeFingerprint!==changes?.tasks?.[task.id])return false;
21
+ const checks=state.checks.filter(c=>c.scope==='task'&&c.taskId===task.id);
22
+ const latest=task.requiredChecks.map(d=>checks.filter(c=>same(c.descriptor,d)).at(-1));
23
+ if(!task.requiredChecks.length||latest.some(c=>!c||c.stale||c.status!=='passed'||c.verdict!=='proven'||!text(c.resultRef)||c.source!=='operator-attested'||c.verificationActor?.role!=='qa'||!text(c.verificationActor.id)||state.assignments.some(a=>a.agentId===c.verificationActor.id)||c.changeFingerprint!==a.changeFingerprint)||!exact(a.checkIds,latest.map(c=>c?.id)))return false;
24
+ const findings=state.findings.filter(f=>f.scope==='task'&&f.taskId===task.id);
25
+ return exact(a.findingIds,findings.map(f=>f.id))&&findings.every(f=>f.status==='closed'&&text(f.resolutionRef)&&text(f.recheckRef)&&f.resolutionActor?.role==='implementer'&&f.recheckActor?.role==='qa'&&f.changeFingerprint===a.changeFingerprint);
26
+ }
27
+ function waitingFor(state,task,predecessor){
28
+ if(task.status!=='pending'||state.intents.some(i=>i.taskId===task.id&&i.operation==='assign-agent'&&['prepared','unknown','mismatch','succeeded'].includes(i.status)))return false;
29
+ const seen=new Set(),queue=[...(task.dependencies??[])];while(queue.length){const id=queue.pop();if(id===predecessor)return true;if(seen.has(id))continue;seen.add(id);queue.push(...(state.tasks.find(t=>t.id===id)?.dependencies??[]));}return false;
30
+ }
31
+ function dirtyOtherTask(state,task,git){return git.stagedPaths?.some(name=>state.tasks.some(t=>t.id!==task.id&&!completed(state,t.id)&&!waitingFor(state,t,task.id)&&t.paths.some(p=>within(p,path.join(state.target.realpath,...name.split('/'))))));}
32
+ function freshAcceptance(state,task,acceptance,changes){return acceptance&&!acceptance.stale&&authorized(state,task)&&acceptance.taskFingerprint===fingerprintRequest({...task,status:'pending'})&&same(acceptance.approval,approval(state,task.id))&&same(acceptance.target,state.target)&&same(acceptance.versions,state.versions)&&checkEvidence(state,task,acceptance,changes);}
33
+ /** Operator attests semantic sufficiency; code binds exact current evidence only. */
34
+ export function evaluateCooperativeAcceptance({state,request,evidence}={}){
35
+ const task=state?.tasks?.find(t=>t.id===request?.taskId),a=request?.arguments,g=evidence?.git;
36
+ if(request?.expectedRevision!==state?.revision||request.actor?.role!=='orchestrator'||!authorized(state,task)||task.status!=='pending'||state.acceptances.some(v=>v.taskId===task.id&&!v.stale)||state.commits.some(v=>v.taskId===task.id))return hold(state,'Current pending approved task and Orchestrator acceptance required');
37
+ if(!fields(a,['messageRef','criteria','checkIds','findingIds','changeFingerprint'])||!text(a.messageRef)||!checkEvidence(state,task,a,evidence?.changes)||state.checks.some(c=>a.checkIds?.includes(c.id)&&c.verificationActor?.id===request.actor.id))return hold(state,'Exact criteria, current required QA checks and closed findings required');
38
+ const descriptor={kind:'task',parent:state.target.head,indexTree:g?.indexTree,fingerprint:g?.stagedFingerprint,paths:g?.stagedPaths};
39
+ const invalid=validateGitPreflight({target:state.target,descriptor,scope:task.paths,gitEvidence:g});
40
+ if(invalid||dirtyOtherTask(state,task,g))return hold(state,invalid??'Index includes another task changes');
41
+ return allow(state,{acceptance:{...structuredClone(a),id:request.requestId,taskId:task.id,actor:structuredClone(request.actor),source:'operator-attested',descriptor:structuredClone(descriptor),taskFingerprint:fingerprintRequest({...task,status:'pending'}),approval:structuredClone(approval(state,task.id)),target:structuredClone(state.target),versions:structuredClone(state.versions)}});
42
+ }
43
+ /** Prepares a durable intent; never stages or executes a commit. */
44
+ export function prepareCooperativeCommit({state,request,gitEvidence,evidence}={}){
45
+ const task=state?.tasks?.find(t=>t.id===request?.taskId),a=state?.acceptances?.find(a=>a.id===request?.arguments?.acceptanceId&&a.taskId===request.taskId);
46
+ if(request?.expectedRevision!==state?.revision||request.actor?.role!=='orchestrator'||!fields(request.arguments,['acceptanceId'])||task?.status!=='accepted'||!freshAcceptance(state,task,a,evidence?.changes)||state.commits.some(c=>c.taskId===task.id)||state.intents.some(i=>i.operation==='commit'&&i.taskId===task.id&&['prepared','unknown','mismatch'].includes(i.status)))return hold(state,'Exact current acceptance and no prior task commit or unresolved commit required');
47
+ const invalid=validateGitPreflight({target:state.target,descriptor:a.descriptor,scope:task.paths,gitEvidence});
48
+ if(invalid||dirtyOtherTask(state,task,gitEvidence))return hold(state,invalid??'Index includes another task changes');
49
+ const expected={parent:a.descriptor.parent,tree:a.descriptor.indexTree,paths:[...a.descriptor.paths],fingerprint:a.descriptor.fingerprint,remainingPaths:[...new Set([...gitEvidence.workingPaths,...gitEvidence.untrackedPaths])].sort()};
50
+ return allow(state,{intent:{requestId:request.requestId,operation:'commit',taskId:task.id,status:'prepared',acceptanceId:a.id,acceptanceFingerprint:fingerprintRequest(a),expected,target:structuredClone(state.target),versions:structuredClone(state.versions),fingerprint:fingerprintRequest(request),source:'operator-attested'}});
51
+ }
52
+ /** Results are local Git observations, correlated with an operator statement.
53
+ * Mismatch observations remain historical evidence and never rebind the target. */
54
+ export function reconcileCooperativeCommit({state,intent,result,gitEvidence}={}){
55
+ if(!intent||intent.operation!=='commit'||!['prepared','unknown','mismatch'].includes(intent.status)||state.commits.some(c=>c.taskId===intent.taskId))return hold(state,'Matching unresolved commit intent required; replay cannot authorize another effect');
56
+ const task=state.tasks.find(t=>t.id===intent.taskId),a=state.acceptances.find(a=>a.id===intent.acceptanceId),g=gitEvidence;
57
+ const observation=g?structuredClone(g):null;
58
+ const transition={observation,result:{...structuredClone(result),status:'mismatch',source:'operator-attested'}};
59
+ const reject=reason=>({...hold(state,reason),proposedTransition:transition});
60
+ if(!result||!text(result.messageRef)||!fields(result.data,['commit'])||!['succeeded','failed','unknown','mismatch'].includes(result.status))return reject('Exact commit result statement required');
61
+ if(result.status!=='succeeded'){transition.result.status=result.status;return reject('Execution did not establish a successful commit');}
62
+ if(task?.status!=='accepted'||!authorized(state,task)||a?.stale||!a||intent.acceptanceFingerprint!==fingerprintRequest(a)||a.taskFingerprint!==fingerprintRequest({...task,status:'pending'})||!same(a.approval,approval(state,task.id))||!checkEvidence(state,task,a,{tasks:{[task.id]:a.changeFingerprint}})||!same(intent.target,state.target)||!same(intent.versions,state.versions)||!g?.commit||result.data.commit!==g.commit.commit||g.stagedPaths?.length||g.indexTree!==g.commit.tree)return reject('Acceptance, observed commit or clean resulting index mismatch');
63
+ const actual={...g.commit,target:g.target,remainingPaths:[...new Set([...g.workingPaths??[],...g.untrackedPaths??[]])].sort()};
64
+ const invalid=validateGitCommitResult({target:state.target,expected:intent.expected,result:actual,scope:task.paths});
65
+ if(invalid)return reject(invalid);
66
+ transition.result.status='succeeded';transition.commit={...actual,taskId:task.id,requestId:intent.requestId,acceptanceId:a.id,source:'operator-attested',observationSource:'local-git',fingerprint:a.changeFingerprint};transition.target=structuredClone(g.target);
67
+ const decision=allow(state,transition);reconciliations.set(decision,{before:fingerprintRequest(state),after:fingerprintRequest(transition)});return decision;
68
+ }
@@ -0,0 +1,42 @@
1
+ import {fingerprintRequest} from './store.mjs';
2
+ import {absolute,within} from './scope.mjs';
3
+ const completed=(state,id)=>state.tasks?.some(t=>t.id===id&&t.status==='committed'&&!t.invalidated)&&state.commits?.some(c=>c.taskId===id&&c.observationSource==='local-git'&&state.intents.some(i=>i.operation==='commit'&&i.requestId===c.requestId&&i.taskId===id&&i.status==='succeeded'));
4
+ const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
5
+ const text=value=>typeof value==='string'&&value.length>0;
6
+ const version=value=>Number.isSafeInteger(value)&&value>0;
7
+ const setEqual=(a,b)=>Array.isArray(a)&&Array.isArray(b)&&new Set(a).size===a.length&&new Set(b).size===b.length&&same([...a].sort(),[...b].sort());
8
+ const base=state=>({expectedRevision:state?.revision??0,coverage:{enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false},requiredEvidence:[],nextActions:[],proposedTransition:null});
9
+ const hold=(state,id,reason)=>({...base(state),decision:'hold',ruleIds:['cooperative.'+id],reason});
10
+ /** Pure gate. observations are supplied by trusted local readers, never JSON input. */
11
+ export function prepareCooperativeAssignment({policy,state,request,observations}={}){
12
+ if(policy!==undefined&&policy.workflowKind!=='cooperative')return hold(state,'contract','Explicit cooperative contract required');
13
+ const args=request?.arguments;
14
+ if(state?.mode!=='plan'||request?.operation!=='assign-agent'||!args)return hold(state,'unsupported','Only explicit plan assignment is supported');
15
+ const allowed=['role','paths','operations','documents','approvalRef','approvalVersion','documentVersion','correlation'];
16
+ if(Object.keys(args).some(k=>!allowed.includes(k))||args.role!=='implementer'||!text(request.taskId)||!text(request.requestId)||!text(args.correlation)||!text(args.approvalRef)||!version(args.approvalVersion)||!version(args.documentVersion)||!Array.isArray(args.paths)||!args.paths.length||new Set(args.paths).size!==args.paths.length||args.paths.some(p=>!absolute(p)||!within(state.target.realpath,p))||!Array.isArray(args.operations)||!args.operations.length||args.operations.some(o=>o!=='edit'))return hold(state,'assignment','Invalid assignment or unsupported historical agent import');
17
+ if(!same(observations?.target,state.target)||!same(observations?.git?.target,state.target))return hold(state,'target','Re-observe target and renew approval after drift');
18
+ if(request.expectedRevision!==state.revision)return hold(state,'revision','Stale assignment request');
19
+ if(state.records.some(r=>r.data?.priorExecution===true)||state.assignments.some(a=>a.source!=='operator-attested'))return hold(state,'history','Earlier execution remains unverified; a late commit cannot authorize it');
20
+ if(state.intents.some(i=>i.operation==='assign-agent'&&['prepared','unknown','mismatch','succeeded'].includes(i.status)&&(i.taskId===request.taskId||i.correlation===args.correlation||!(i.status==='succeeded'&&completed(state,i.taskId))&&i.paths?.some(p=>args.paths.some(q=>within(p,q)||within(q,p))))))return hold(state,'assignment-active','Resolve the existing dispatch before preparing another');
21
+ const task=state.tasks?.find(t=>t.id===request.taskId);
22
+ if(task&&(task.invalidated||task.status==='held'||task.dependencies?.some(id=>{const predecessor=state.tasks.find(t=>t.id===id);return !predecessor||predecessor.invalidated||!['accepted','committed'].includes(predecessor.status);})))return hold(state,'task-stale','Affected task or predecessor requires renewed readiness and approval');
23
+ const scope=state.scopes?.findLast(s=>s.scopeVersion===state.scopeVersion&&(!s.data.affectedTaskIds||s.data.affectedTaskIds.includes(request.taskId)));
24
+ if(!task||!task.paths?.length||args.paths.some(p=>!task.paths.some(base=>within(base,p)))||scope&&args.paths.some(p=>!scope.data.paths?.some(base=>within(base,p))))return hold(state,'assignment-scope','Assignment must stay inside approved task and recorded scope');
25
+ const documents=args.documents,git=observations.git;
26
+ if(!Array.isArray(documents)||documents.length!==2||!setEqual(documents.map(d=>d.kind),['spec','plan'])||!git.docsCommit||!setEqual(git.docsCommit.paths,documents.map(d=>d.gitPath))||!same(git.docsCommit.documents,documents)||documents.some(d=>d.commit!==git.docsCommit.commit)||!Array.isArray(git.documents)||git.documents.length!==2||documents.some(d=>!git.documents.some(o=>o.path===d.path&&o.gitPath===d.gitPath&&o.kind===d.kind&&o.observedHash===d.contentHash&&o.currentHash===d.contentHash)))return hold(state,'documents','Exact committed spec and plan plus current bytes must match approval');
27
+ const approval=state.records.filter(r=>r.kind==='approval'&&(!r.data.affectedTaskIds||r.data.affectedTaskIds.includes(request.taskId))).at(-1);
28
+ if(task.approvalRef!==args.approvalRef||task.approvalVersion!==args.approvalVersion||task.documentVersion!==args.documentVersion||task.scopeVersion!==state.scopeVersion||task.targetVersion!==state.targetVersion||!approval||approval.source!=='operator-attested'||approval.messageRef!==args.approvalRef||approval.targetVersion!==state.targetVersion||approval.scopeVersion!==state.scopeVersion||approval.data.approvalVersion!==args.approvalVersion||approval.data.documentVersion!==args.documentVersion||!same(approval.data.documents,documents)||documents.some(d=>d.approvalRef!==args.approvalRef))return hold(state,'approval','Current document and approval versions must match');
29
+ const intent={requestId:request.requestId,taskId:request.taskId,operation:request.operation,status:'prepared',role:args.role,paths:[...args.paths],operations:[...args.operations],correlation:args.correlation,documents:structuredClone(documents),docsCommit:git.docsCommit.commit,approvalRef:args.approvalRef,approvalVersion:args.approvalVersion,documentVersion:args.documentVersion,target:structuredClone(state.target),targetVersion:state.targetVersion,scopeVersion:state.scopeVersion,revision:state.revision+1,fingerprint:fingerprintRequest(request),source:'operator-attested'};
30
+ return {...base(state),decision:'allow',ruleIds:['cooperative.assignment-prepared'],proposedTransition:{intent}};
31
+ }
32
+ /** A native response is an operator statement, not authenticated identity or compliance. */
33
+ export function recordCooperativeAssignmentResult({state,intent,result,observations}={}){
34
+ if(!intent||intent.operation!=='assign-agent')return hold(state,'intent','No matching assignment intent');
35
+ if(!['prepared','unknown','mismatch'].includes(intent.status))return hold(state,'assignment-terminal','Preserve the prior terminal native response');
36
+ if(!result||!['succeeded','failed','unknown','mismatch'].includes(result.status)||!text(result.messageRef)||!result.data)return hold(state,'assignment-result','Invalid native result statement');
37
+ if(result.status==='succeeded'&&(state.assignments.some(a=>a.agentId===result.data.agentId&&a.taskId!==intent.taskId)||state.intents?.some(i=>i.verificationActor?.id===result.data.agentId)||state.checks?.some(c=>c.verificationActor?.id===result.data.agentId)))return hold(state,'assignment-freshness','Implementer actor statements cannot cross tasks');
38
+ let status=result.status;
39
+ if(!same(intent.target,observations?.target)||result.data.correlation!==intent.correlation||result.data.taskId!==intent.taskId||status==='succeeded'&&!text(result.data.agentId))status='mismatch';
40
+ const entry={...structuredClone(result),status,requestId:intent.requestId,source:'operator-attested'};
41
+ return {...base(state),decision:['succeeded','failed'].includes(status)?'allow':'hold',ruleIds:['cooperative.assignment-'+status],proposedTransition:{result:entry}};
42
+ }
@@ -0,0 +1,35 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import {validateCooperativeCommand,validateCooperativeState} from './cooperative-schema.mjs';
5
+ import {observeCooperativeTarget,validateObservedTarget,validateWorkflowId,workflowStatePath,inspectPath} from './scope.mjs';
6
+ import {saveDurableState} from './store.mjs';
7
+ export const COOPERATIVE_RUNTIME_MODULES=Object.freeze([
8
+ 'bootstrap.mjs','cooperative-schema.mjs','cooperative.mjs','evaluate.mjs',
9
+ 'scope.mjs','store.mjs','git-evidence.mjs','assignment.mjs','verification.mjs','acceptance.mjs','external.mjs'
10
+ ]);
11
+ export const cooperativeCoverage=()=>({enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false});
12
+ export function commandResult({workflowId,state,input,decision='allow',ruleId='cooperative.recorded',persisted=false,...extra}){
13
+ return {decision,ruleIds:[ruleId],workflowId,taskId:input?.taskId??null,requestId:input?.requestId??null,revision:state?.revision??0,coverage:cooperativeCoverage(),requiredEvidence:[],nextActions:[],persisted,...extra};
14
+ }
15
+ export async function cooperativeVersions(){
16
+ const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
17
+ let policy;try{policy=await fs.readFile(new URL('../policy/role-policy.json',import.meta.url));}catch(error){if(error.code!=='ENOENT')throw error;policy=await fs.readFile(new URL('./role-policy.json',import.meta.url));}
18
+ const runtime=await Promise.all(COOPERATIVE_RUNTIME_MODULES.map(file=>fs.readFile(new URL(file,import.meta.url))));
19
+ return {policy:'1',runtime:'cooperative-1',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
20
+ }
21
+ export async function initializeCooperativeWorkflow({cwd,workflowId,input,observe=observeCooperativeTarget,storage={}}){
22
+ validateWorkflowId(workflowId);validateCooperativeCommand({command:'init',input});
23
+ if(input.mode!=='plan')return commandResult({workflowId,input,decision:'hold',ruleId:'cooperative.unsupported'});
24
+ const target=await validateObservedTarget(cwd,await observe(cwd));const statePath=await workflowStatePath(target,workflowId);
25
+ const parent=path.dirname(statePath);await fs.mkdir(parent,{recursive:true,mode:0o700});await inspectPath(parent,{directory:true});
26
+ const lockPath=statePath+'.lock';let lock;
27
+ try{
28
+ lock=await fs.open(lockPath,'wx',0o600);await inspectPath(statePath,{missing:true});
29
+ const state={schemaVersion:1,workflowKind:'cooperative',contractVersion:1,workflowId,revision:0,mode:'plan',coverage:cooperativeCoverage(),versions:await cooperativeVersions(),target,targetVersion:1,scopeVersion:0};
30
+ for(const key of ['actors','selections','assignments','identities','leases','scopes','approvals','documents','tasks','requests','intents','results','checks','findings','acceptances','commits','audit','unresolved','records','targetHistory'])state[key]=[];
31
+ state.actors.push({actor:input.actor,source:'operator-attested'});state.selections.push({...input.selection,actor:input.actor,source:'operator-attested',targetVersion:1});
32
+ state.audit.push({command:'init',revision:0,source:'operator-attested',actor:input.actor});validateCooperativeState(state);
33
+ await saveDurableState({statePath,state,create:true,storage});return commandResult({workflowId,state,input,persisted:true,ruleId:'cooperative.initialized'});
34
+ }finally{if(lock){await lock.close();await fs.unlink(lockPath);}}
35
+ }
@@ -0,0 +1,55 @@
1
+ import {ROLES} from './operations.mjs';
2
+ import {assertSecretFree} from './external.mjs';
3
+ import {object,text} from './schema.mjs';
4
+ import {absolute,validateWorkflowId} from './scope.mjs';
5
+ const fail=message=>{throw Error('Cooperative schema: '+message);};
6
+ const hash=value=>typeof value==='string'&&/^sha256:[a-f0-9]{64}$/.test(value);
7
+ const revision=value=>Number.isSafeInteger(value)&&value>=0;
8
+ const actor=value=>object(value)&&text(value.id)&&Object.keys(value).every(k=>['id','role'].includes(k))&&(value.role===undefined||ROLES.includes(value.role));
9
+ const statement=value=>object(value)&&text(value.messageRef)&&object(value.data);
10
+ function fields(value,allowed){if(!object(value)||Object.keys(value).some(k=>!allowed.includes(k)))fail('unexpected input field');}
11
+ function json(value){try{const encoded=JSON.stringify(value);if(encoded===undefined)fail('JSON input');}catch{fail('JSON input');}}
12
+ export function validateCooperativeCommand(command){
13
+ assertSecretFree(command);fields(command,['command','input']);const {input,command:name}=command;
14
+ if(!['init','record','status','reconcile','prepare','result'].includes(name))fail('command');
15
+ if(name==='status'){if(input!==undefined)fail('status takes no input');return command;}
16
+ const resultStatement=name==='reconcile'||name==='result'&&input?.operation===undefined;
17
+ const allowed=name==='init'?['mode','actor','selection']:name==='record'?['requestId','expectedRevision','actor','evidence']:resultStatement?['requestId','expectedRevision','actor','intentId','result']:['requestId','expectedRevision','actor','operation','taskId','arguments'];
18
+ fields(input,allowed);json(input);
19
+ if(!actor(input.actor))fail('actor attestation');
20
+ if(name==='init'){
21
+ if(!['plan','no-plan','small-task'].includes(input.mode)||!object(input.selection)||!text(input.selection.messageRef)||!hash(input.selection.contentHash)||Object.keys(input.selection).some(k=>!['messageRef','contentHash'].includes(k)))fail('target selection');
22
+ return command;
23
+ }
24
+ if(!text(input.requestId)||input.requestId.length>128||!revision(input.expectedRevision))fail('request identity or revision');
25
+ if(name==='record'){
26
+ fields(input.evidence,['kind','messageRef','data']);
27
+ if(input.evidence?.data?.affectedTaskIds!==undefined&&(!Array.isArray(input.evidence.data.affectedTaskIds)||!input.evidence.data.affectedTaskIds.every(text)||new Set(input.evidence.data.affectedTaskIds).size!==input.evidence.data.affectedTaskIds.length))fail('affected task IDs');
28
+ if(!statement(input.evidence)||!['note','approval','external-approval','document','scope','check','finding','review','acceptance-evidence'].includes(input.evidence.kind))fail('evidence');
29
+ }
30
+ if(resultStatement){
31
+ fields(input.result,['status','messageRef','data','notExecutedEvidence']);
32
+ if(!text(input.intentId)||!statement(input.result)||!['succeeded','failed','unknown','mismatch','cancelled'].includes(input.result.status))fail('result evidence');
33
+ if(input.result.status==='cancelled'&&(!object(input.result.notExecutedEvidence)||!text(input.result.notExecutedEvidence.messageRef)))fail('cancel requires not-executed evidence');
34
+ }
35
+ if((name==='prepare'||name==='result'&&!resultStatement)&&!text(input.operation))fail('operation');
36
+ return command;
37
+ }
38
+ export function validateCooperativeState(state){
39
+ if(!object(state)||state.workflowKind!=='cooperative'||state.contractVersion!==1||state.schemaVersion!==1||!revision(state.revision)||state.mode!=='plan')fail('explicit cooperative contract');
40
+ validateWorkflowId(state.workflowId);
41
+ if(!object(state.target)||!absolute(state.target.realpath)||!absolute(state.target.gitCommonDir)||!absolute(state.target.gitDir)||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(state.target.head)||!(state.target.branch===null||text(state.target.branch)))fail('target');
42
+ if(!object(state.versions)||!text(state.versions.policy)||!text(state.versions.runtime)||!hash(state.versions.policyHash)||!hash(state.versions.runtimeHash))fail('versions');
43
+ if(!object(state.coverage)||state.coverage.provenance!=='operator-attested'||state.coverage.nativeVerified!==false||state.coverage.enforcement!=='cooperative')fail('coverage');
44
+ for(const key of ['actors','selections','assignments','identities','leases','scopes','approvals','documents','tasks','requests','intents','results','checks','findings','acceptances','commits','audit','unresolved','records','targetHistory'])if(!Array.isArray(state[key]))fail(key);
45
+ if(state.tasks.some(t=>!object(t)||!text(t.id)||!Array.isArray(t.paths)||!Array.isArray(t.criteria)||!Array.isArray(t.requiredChecks)||!Array.isArray(t.dependencies))||new Set(state.tasks.map(t=>t.id)).size!==state.tasks.length)fail('task contracts');
46
+ if(state.commitObservations!==undefined&&(!Array.isArray(state.commitObservations)||state.commitObservations.some(o=>!object(o)||o.source!=='local-git'||!text(o.intentId)||!revision(o.revision))))fail('commit observations');
47
+ if(!revision(state.scopeVersion)||!revision(state.targetVersion))fail('scope/target version');
48
+ if(state.actors.some(a=>!actor(a.actor)||a.source!=='operator-attested')||state.selections.some(s=>s.source!=='operator-attested'||!text(s.messageRef)))fail('attestations');
49
+ for(const key of ['scopes','approvals','documents','checks','findings','acceptances','commits'])if(state[key].some(entry=>!object(entry)||entry.source!=='operator-attested'))fail('attestation source');
50
+ if(state.records.some(r=>!actor(r.actor)||r.source!=='operator-attested'||!text(r.kind)||!statement(r)))fail('records');
51
+ if(state.requests.some(r=>!text(r.requestId)||!hash(r.requestFingerprint)||!object(r.decision))||new Set(state.requests.map(r=>r.requestId)).size!==state.requests.length)fail('request replay');
52
+ if(state.intents.some(i=>!text(i.requestId)||!['prepared','succeeded','failed','unknown','mismatch','cancelled'].includes(i.status)||!hash(i.fingerprint))||new Set(state.intents.map(i=>i.requestId)).size!==state.intents.length)fail('intents');
53
+ if(state.results.some(r=>!text(r.requestId)||!['succeeded','failed','unknown','mismatch','cancelled'].includes(r.status)||r.source!=='operator-attested'||!object(r.data)))fail('results');
54
+ assertSecretFree(state);json(state);return state;
55
+ }