@yunhozz/arc 0.2.7 → 0.2.8

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 (118) hide show
  1. package/MANIFEST.sha256 +115 -68
  2. package/README.md +21 -5
  3. package/claude/agents/arc-implementer.md +3 -3
  4. package/claude/agents/arc-planner.md +3 -3
  5. package/claude/agents/arc-qa.md +3 -3
  6. package/claude/agents/arc-reviewer.md +3 -3
  7. package/claude/agents/arc-scouter.md +3 -3
  8. package/claude/skill/SKILL.md +5 -5
  9. package/claude/skill/models.toml +7 -48
  10. package/claude/skill/references/commit.md +7 -7
  11. package/claude/skill/references/coordination.md +39 -3
  12. package/claude/skill/references/git-recovery.md +1 -1
  13. package/claude/skill/references/handoff-prep.md +6 -6
  14. package/claude/skill/references/handoff.md +8 -3
  15. package/claude/skill/references/limits.md +2 -0
  16. package/claude/skill/references/planning.md +8 -8
  17. package/claude/skill/references/verification.md +9 -9
  18. package/claude/skill/runtime/adapters/claude.mjs +4 -0
  19. package/claude/skill/runtime/adapters/codex.mjs +3 -0
  20. package/claude/skill/runtime/bootstrap.mjs +4 -2
  21. package/claude/skill/runtime/command.mjs +21 -4
  22. package/claude/skill/runtime/local-cli.mjs +248 -0
  23. package/claude/skill/runtime/role-bridge-args.mjs +148 -0
  24. package/claude/skill/runtime/role-bridge.mjs +227 -0
  25. package/claude/skill/runtime/role-dispatch-policy.mjs +110 -0
  26. package/claude/skill/runtime/role-dispatch-store.mjs +134 -0
  27. package/claude/skill/runtime/role-observe.mjs +299 -0
  28. package/claude/skill/runtime/role-policy.json +12 -10
  29. package/claude/skill/runtime/role-routing-config.mjs +19 -0
  30. package/claude/skill/runtime/role-routing.mjs +233 -0
  31. package/claude/skill/runtime/role-supervisor.mjs +356 -0
  32. package/claude/skill/scripts/model_config.py +23 -5
  33. package/codex/agents/arc-implementer.toml +3 -3
  34. package/codex/agents/arc-planner.toml +3 -3
  35. package/codex/agents/arc-qa.toml +3 -3
  36. package/codex/agents/arc-reviewer.toml +3 -3
  37. package/codex/agents/arc-scouter.toml +3 -3
  38. package/codex/skill/SKILL.md +5 -5
  39. package/codex/skill/models.toml +7 -48
  40. package/codex/skill/references/commit.md +7 -7
  41. package/codex/skill/references/coordination.md +38 -2
  42. package/codex/skill/references/handoff-prep.md +6 -6
  43. package/codex/skill/references/handoff-worktree.md +3 -3
  44. package/codex/skill/references/handoff.md +8 -3
  45. package/codex/skill/references/limits.md +2 -0
  46. package/codex/skill/references/planning.md +8 -8
  47. package/codex/skill/references/verification.md +9 -9
  48. package/codex/skill/runtime/adapters/claude.mjs +4 -0
  49. package/codex/skill/runtime/adapters/codex.mjs +3 -0
  50. package/codex/skill/runtime/bootstrap.mjs +4 -2
  51. package/codex/skill/runtime/command.mjs +21 -4
  52. package/codex/skill/runtime/local-cli.mjs +248 -0
  53. package/codex/skill/runtime/role-bridge-args.mjs +148 -0
  54. package/codex/skill/runtime/role-bridge.mjs +227 -0
  55. package/codex/skill/runtime/role-dispatch-policy.mjs +110 -0
  56. package/codex/skill/runtime/role-dispatch-store.mjs +134 -0
  57. package/codex/skill/runtime/role-observe.mjs +299 -0
  58. package/codex/skill/runtime/role-policy.json +12 -10
  59. package/codex/skill/runtime/role-routing-config.mjs +19 -0
  60. package/codex/skill/runtime/role-routing.mjs +233 -0
  61. package/codex/skill/runtime/role-supervisor.mjs +356 -0
  62. package/codex/skill/scripts/model_config.py +17 -22
  63. package/lib/cli/root.mjs +3 -2
  64. package/lib/installer/install-mode.mjs +34 -0
  65. package/lib/installer/install.mjs +1 -1
  66. package/lib/installer/plan.mjs +16 -7
  67. package/lib/installer/preset.mjs +18 -11
  68. package/lib/installer/role-routing.mjs +175 -0
  69. package/lib/installer/runtime-assets.mjs +9 -0
  70. package/lib/installer/targets.mjs +2 -7
  71. package/lib/installer/transaction.mjs +1 -1
  72. package/lib/installer/uninstall.mjs +10 -5
  73. package/lib/installer/upgrade-state.mjs +9 -6
  74. package/lib/installer/upgrade.mjs +2 -2
  75. package/lib/management/operations.mjs +94 -5
  76. package/lib/management/status.mjs +12 -6
  77. package/lib/management/update.mjs +3 -1
  78. package/lib/models/catalog.mjs +3 -3
  79. package/lib/models/claude-models.json +297 -0
  80. package/lib/models/codex-catalog.mjs +9 -6
  81. package/lib/models/codex-models.json +189 -0
  82. package/lib/models/config.mjs +25 -20
  83. package/lib/models/index.mjs +1 -1
  84. package/lib/models/static-catalog.mjs +42 -0
  85. package/lib/policy/role-policy.json +12 -10
  86. package/lib/runtime/adapters/claude.mjs +4 -0
  87. package/lib/runtime/adapters/codex.mjs +3 -0
  88. package/lib/runtime/bootstrap.mjs +4 -2
  89. package/lib/runtime/command.mjs +21 -4
  90. package/lib/runtime/local-cli.mjs +248 -0
  91. package/lib/runtime/role-bridge-args.mjs +148 -0
  92. package/lib/runtime/role-bridge.mjs +227 -0
  93. package/lib/runtime/role-dispatch-policy.mjs +110 -0
  94. package/lib/runtime/role-dispatch-store.mjs +134 -0
  95. package/lib/runtime/role-observe.mjs +299 -0
  96. package/lib/runtime/role-routing-config.mjs +19 -0
  97. package/lib/runtime/role-routing.mjs +233 -0
  98. package/lib/runtime/role-supervisor.mjs +356 -0
  99. package/lib/tui/app.mjs +32 -23
  100. package/lib/tui/custom-preset.mjs +138 -66
  101. package/lib/tui/render.mjs +4 -3
  102. package/lib/tui/setup.mjs +96 -51
  103. package/lib/watch/args.mjs +43 -0
  104. package/lib/watch/discover-claude.mjs +63 -0
  105. package/lib/watch/discover-codex.mjs +45 -0
  106. package/lib/watch/dispatch.mjs +133 -0
  107. package/lib/watch/git.mjs +29 -0
  108. package/lib/watch/index.mjs +112 -0
  109. package/lib/watch/labels.mjs +24 -0
  110. package/lib/watch/model.mjs +48 -0
  111. package/lib/watch/normalize-claude.mjs +99 -0
  112. package/lib/watch/normalize-codex.mjs +96 -0
  113. package/lib/watch/policy.mjs +52 -0
  114. package/lib/watch/render.mjs +86 -0
  115. package/lib/watch/scope.mjs +64 -0
  116. package/lib/watch/tail.mjs +75 -0
  117. package/lib/watch/watcher.mjs +337 -0
  118. package/package.json +2 -2
@@ -36,7 +36,7 @@ Verify creation in order:
36
36
 
37
37
  The tool copies no uncommitted changes. Transfer rules below apply only to existing approved documents in legacy/restart/explicit-target-change cases, not normal new documents.
38
38
 
39
- - Untracked approved documents must be absent from source HEAD/index, with working-tree bytes matching latest approval.
39
+ - Untracked approved documents MUST be absent from source HEAD/index, with working-tree bytes matching latest approval.
40
40
  - Tracked documents require source index blob/mode equal to HEAD and working-tree bytes equal to latest approval. Approved working revisions may differ from HEAD/index. Do not stage source documents to repair or verify them.
41
41
  - Mismatches, unrelated staged changes, required uncommitted implementation/configuration/test changes or unclear ownership block preparation. Clearly unrelated unstaged/untracked changes stay in source.
42
42
  - Never automatically stash/commit/reset/clean/unstage or transfer dirty implementation. Transfer existing approved documents below before target document preparation.
@@ -47,7 +47,7 @@ The tool copies no uncommitted changes. Transfer rules below apply only to exist
47
47
  Only for existing approved documents in legacy/pre-existing-document, restart, or explicit-target-change cases; not normal new documents:
48
48
 
49
49
  1. Verify existing approved commit SHA/message/paths/content and validity at base/target; reuse them.
50
- 2. Copy only uncommitted approved spec/plan documents to the same relative paths. Never move/delete/modify source documents. Stop for destinations escaping the worktree, including symlinks. Target HEAD must equal selected source base SHA before transfer.
51
- 3. Before replacing a destination, prove clean base state: no staged/unstaged changes, index/working bytes equal base. Documents absent from base must also be absent at destination. Never overwrite unexpected changes.
50
+ 2. Copy only uncommitted approved spec/plan documents to the same relative paths. Never move/delete/modify source documents. Stop for destinations escaping the worktree, including symlinks. Target HEAD MUST equal selected source base SHA before transfer.
51
+ 3. Before replacing a destination, prove clean base state: no staged/unstaged changes, index/working bytes equal base. Documents absent from base MUST also be absent at destination. Never overwrite unexpected changes.
52
52
  4. Verify approved bytes before reusing identical content; verify approved bytes after transfer.
53
53
  5. Record approvals, versions, evidence, absolute source and target paths, common relative paths and content checks. Changed content/approval scope needs revised approval. Transfer nothing else. Failure/partial transfer blocks dependent staging, commits and Implementer handoff.
@@ -55,7 +55,7 @@ One canonical record includes:
55
55
  - Each plan task ID and current Implementer conversation ID, status, last result and reuse/replacement decision. Before same-task replacement, record the prior ID and status, allowed reason and supporting evidence; hold if the reason is not established. Record the returned ID after a successful initial or replacement call, and reconcile an uncertain call result before another assignment.
56
56
  - Worktree source/target paths/common directory/base/branch/name/returned path/app attachment/operationId/registration/source preservation/transfer evidence. No automatic recreation/cleanup/archive.
57
57
 
58
- Give all five roles the same actual workspace/selected checkout, preparation evidence and absolute artifacts. Roles stay there and report missing/inaccessible/conflicting paths/unexpected branches before dependent work, never create/switch workspaces/branches. Tell Implementer others share the repository and unrelated work must be preserved.
58
+ Give all five roles the same actual workspace/selected checkout, preparation evidence and absolute artifacts. Roles stay there and report missing/inaccessible/conflicting paths/unexpected branches before dependent work, never create/switch workspaces/branches. Tell Implementer others share the repository and unrelated work MUST be preserved.
59
59
 
60
60
  <a id="task-readiness-at-every-assignment"></a>
61
61
  ## Task readiness at every assignment
@@ -171,11 +171,11 @@ On scope/docs/approval changes inspect `affectedTaskIds`/dependencies, preserve
171
171
 
172
172
  [ARC role policy: contract begin]
173
173
  Generated from lib/policy/role-policy.json; do not edit this managed section manually.
174
- - [git.specialists-deny] Specialists must not change Git state during implementation or recovery: no stage, commit, push, merge, rebase, reset, branch creation/switching or worktree creation/removal. Explicit Orchestrator assignment cannot authorize these actions; return them to Orchestrator. Read-only Git inspection remains allowed within the assigned scope.
174
+ - [git.specialists-deny] Specialists MUST not change Git state during implementation or recovery: no stage, commit, push, merge, rebase, reset, branch creation/switching or worktree creation/removal. Explicit Orchestrator assignment cannot authorize these actions; return them to Orchestrator. Read-only Git inspection remains allowed within the assigned scope.
175
175
  - [role.implementer-implementation] Edit only assigned, approved files and run focused checks under the existing TDD contract. Report changed files, RED/GREEN or approved exception evidence, results, limits and follow-up. Do not plan, independently QA/review your own work, accept the task or declare overall completion. Git mutations remain forbidden after successful implementation. Implementer and fresh QA handoffs include the exact approved visual source, version, approval and access state; criterion IDs, required properties and comparison method; and actual-output identity, revision and comparison basis. Record pass, mismatch or unverified with accessible evidence and limits. Implementer self-report does not replace fresh QA and its actual comparison. A missing output-to-revision link is unverified; record a visible difference separately as mismatch without inferring current branch UI state. Missing source/output, inaccessible evidence or unapproved interpretation holds the affected visual claim for Orchestrator. Do not silently substitute or redesign.
176
176
  - [review.significant-no-plan] Significant/high-risk work without a plan follows Implementer → QA and required QA rechecks → Reviewer of the final full change → Orchestrator acceptance. Do not omit Reviewer because no plan exists. This adds no plan obligation.
177
177
  - [review.significant-plan] Significant/high-risk plan work follows Implementer → required fresh QA → Orchestrator acceptance and focused commit for each task. 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 gate. Preserve required checks and necessary finding rechecks.
178
- - [review.final-plan-recheck] Final overall Reviewer findings on plan work, including behavior findings, follow Implementer → Reviewer without QA reassignment until resolved. This exception applies only at the final plan stage. Preserve required QA and QA failure rechecks before the initial final review and outside this exception.
178
+ - [review.final-plan-recheck] Complete required QA and QA failure rechecks before the initial final overall Reviewer review. Once that review begins on plan work, every final Reviewer finding, including behavior, follows Implementer → Reviewer without QA reassignment until resolved. Keep corrections uncommitted through Reviewer rechecks, then accept and create one focused follow-up commit. Separate QA findings follow Implementer → QA. Preserve required QA outside this final Reviewer exception.
179
179
  - [platform.codex] Role restrictions are prompt-level contracts, not a filesystem sandbox. ARC supplies no native observer hook or role-specific Git guard. Existing shell capabilities are retained because static read access after shell reduction has not been verified; Implementer and QA need shell for approved checks.
180
180
  [ARC role policy: contract end]
181
181
 
@@ -218,3 +218,8 @@ Git OIDs are full lowercase 40/64-character hex; artifactHash is `sha256:<64-hex
218
218
  `result`/`reconcile` accept `{requestId, expectedRevision, actor, intentId, result: {status, messageRef, data: {operation, scope, descriptor}}}`, with prepare requestId as intentId. Mismatch/unknown/stale outcomes hold while preserving attestations. After interruption inspect intent/`state.requests`/`state.audit`/`state.results` through `status` and investigate actual effects. Reconcile that same intent, not fresh preparation or replayed approvals.
219
219
 
220
220
  Cancellation also requires `notExecutedEvidence: {messageRef}`; approval remains consumed. No automatic update/migration/renewed permission to fix drift. Report holds. Succeeded results remain attestations, not remote proof. `audit` links request→decision→intent→result→resolution but is locally editable, not tamper-proof. Never retry uncertain external outcomes.
221
+
222
+ <a id="composite-bridge-results-and-briefs"></a>
223
+ ## Composite bridge results and briefs
224
+
225
+ For a bridge dispatch the result is the child's final message, saved at the `resultPath` returned by `run-dispatch` and `observe`; read it from there and treat it as `operator-attested` text, not as acceptance. The brief sent to `run-dispatch` or `resume` keeps the fixed brief order from [coordination](coordination.md#token-discipline-and-handoffs) and is delivered on stdin only: never put it in argv, environment variables or a positional prompt, and keep it at most 256 KiB. For audit ARC also stores the brief in `<gitCommonDir>/arc/workflows/<workflowId>/dispatches/<dispatchId>/brief.md` (mode 0600); the child still receives it on stdin only. Do not include secrets or raw CLI output.
@@ -27,3 +27,5 @@ Confirmed completion or termination frees active capacity. Exhaustion holds crea
27
27
  Cumulative limits and scheduling are prompt policy, not hard runtime controls. Text tests prove package consistency, not live compliance/native support.
28
28
  Codex `[agents].max_concurrent_threads_per_session` and Claude `settings.json.env.CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS` constrain their respective sessions.
29
29
  Independent sessions/accounts/platforms do not share the ledger. Agent Teams and hosted APIs are outside this contract. Verify native application separately in a supported new session.
30
+
31
+ Composite platform routes observe these limits and each platform's actual capacity. ARC enforces the bridge limits at `prepare-dispatch`: active bridge dispatches (`reserved`, `starting`, `running`, `unknown`) must not exceed `max_concurrent_subagents` of the installed `limits.toml`, and the bridge dispatches created per workflow must not exceed `max_total_subagents`. `resume` rechecks only `max_concurrent_subagents`; it does not increase the cumulative count. Every bridge dispatch also counts as a created instance in the Orchestrator ledger; the native plus bridge total is kept in that ledger (prompt policy). A dispatch in `unknown` keeps its slot until the operator confirms termination; its slot is never released automatically. Role timeouts are fixed: `arc_implementer` 60 minutes, `arc_qa` 30 minutes, others 20 minutes; `limits.toml` format is unchanged. Terminal leases (`completed`, `failed`, `cancelled`) older than 30 days are pruned automatically; non-terminal leases are never pruned.
@@ -66,7 +66,7 @@ For initial fast judgment apply the [fast gate](handoff.md#orchestrator-direct-p
66
66
  <a id="top-level-plan-tasks"></a>
67
67
  ## Top-level plan tasks
68
68
 
69
- Apply Planner rules: ID/title, goal/scope/files, predecessors/dependencies, criteria, required pre-acceptance QA/checks/evidence and holds. Tasks must be independently implementable/verifiable/acceptable. Inseparable policy/profile/tests/manifest contracts start in one task. If inseparability appears later, stop for revised scope/planning/approvals; never merge distinct approved tasks during execution.
69
+ Apply Planner rules: ID/title, goal/scope/files, predecessors/dependencies, criteria, required pre-acceptance QA/checks/evidence and holds. Tasks MUST be independently implementable/verifiable/acceptable. Inseparable policy/profile/tests/manifest contracts start in one task. If inseparability appears later, stop for revised scope/planning/approvals; never merge distinct approved tasks during execution.
70
70
 
71
71
  Substeps/checkboxes/RED-GREEN/commands are not commits. One top-level task becomes one focused commit after acceptance; [commit](commit.md) governs no-change/hold/resume. Reviewer is never a per-task check. Final whole verification has separate scope/timing; significant work lists one Reviewer after all task acceptances/risk checks. Task boundaries alone add no QA. Apply only to required plans; omission paths gain no plan obligation.
72
72
 
@@ -117,15 +117,15 @@ New planning scope requires list/depth/dependency reassessment and approvals bef
117
117
  <a id="plan-updates-during-execution"></a>
118
118
  ## Plan updates during execution
119
119
 
120
- Mechanical checkboxes/results/evidence/completion preserving the approved contract need no new approval; record classification/reason/actual time. Removing checks, invented success, unsupported acceptance or mixed scope changes are not mechanical.
120
+ Task progress records (checkboxes, notes, results, evidence and completion status) preserving the approved contract need no new approval; record classification/reason/actual time. After task completion Orchestrator includes that task's own records with its accepted implementation work in the same focused commit, excluding other tasks. Do not amend the original planning commit or create a separate docs/fixup commit for those records. Accepted no-change tasks follow the no-change path without empty commits. Removing checks, invented success, unsupported acceptance or mixed scope changes are not mechanical.
121
121
 
122
122
  Changes to goals, task boundaries, scope, criteria, method, risk, dependencies or checks require revised approval before affected work. Hold, obtain ordered design/spec/plan approvals and prepare target/ownership/checks/handoff. Other body corrections follow version approval; classify typos/paths/commands/explanations by semantic effect.
123
123
 
124
- Both kinds amend the original planning commit at safe boundaries, never separate docs/fixup commits, including new scope. Preserve implementation commits. Rewriting does not backdate approval; latest content in an old commit proves no earlier authorization.
124
+ Spec/plan content changes other than task progress records amend the original planning commit at safe boundaries after applicable approval and preparation, never separate docs/fixup commits, including new scope. Preserve implementation commits. Rewriting does not backdate approval; latest content in an old commit proves no earlier authorization.
125
125
 
126
- Preserve absolute/Git plan paths, old/new hashes/versions, prior/revised approval refs/actual times, reason/classification, affected tasks and hold/preparation/resume evidence. Mechanical records state why no approval/time. Keep recoverable contents, not hashes only, and old→new mappings for original/descendant commits. Never overwrite old approvals/content.
126
+ For non-progress content amendments, preserve absolute/Git plan paths, old/new hashes/versions, prior/revised approval refs/actual times, reason/classification, affected tasks and hold/preparation/resume evidence. Keep recoverable old/new contents, not hashes only, and old→new SHA mappings for original/descendant commits. Never overwrite old approvals/content. Task progress records retain their classification, reason and actual time as applicable; they do not trigger original-plan history mappings or amendment.
127
127
 
128
- Orchestrator alone rewrites under [preparation](handoff-prep.md#execution-time-plan-amendment)/[commit](commit.md#execution-time-plan-document-updates). Shared/published/unknown history, merges, unclear ownership, unexpected HEAD/dirty state/replay conflicts stop work. No force push/fallback docs commit. Reconnect evidence under [verification](verification.md#evidence-after-plan-history-rewrite). Add no Git automation/runtime enforcement/authority/check exemptions.
128
+ For non-progress content amendments, Orchestrator alone rewrites under [preparation](handoff-prep.md#execution-time-plan-amendment)/[commit](commit.md#execution-time-plan-document-updates). Shared/published/unknown history, merges, unclear ownership, unexpected HEAD/dirty state/replay conflicts stop work. No force push/fallback docs commit. Reconnect evidence under [verification](verification.md#evidence-after-plan-history-rewrite). Add no Git automation/runtime enforcement/authority/check exemptions.
129
129
 
130
130
  <a id="evidence-refresh-and-limits"></a>
131
131
  ## Evidence refresh and limits
@@ -152,11 +152,11 @@ Follow [handoff-worktree](handoff-worktree.md).
152
152
 
153
153
  [ARC role policy: contract begin]
154
154
  Generated from lib/policy/role-policy.json; do not edit this managed section manually.
155
- - [git.orchestrator-accept-commit] Only Orchestrator accepts work and performs 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 separate user commit approval. Reports, passing checks and Reviewer opinions do not replace acceptance. Preserve unrelated changes and ownership; verify the resulting SHA, content, HEAD and remaining changes. Existing small-task direct and plan-omission paths remain unchanged.
155
+ - [git.orchestrator-accept-commit] Only Orchestrator accepts work and performs Git mutations. One approved top-level plan task becomes one focused implementation commit after criteria, required checks and findings are satisfied. Orchestrator accepts, then includes that task's own progress records made after task completion (checkboxes, notes, results, evidence and status) with its implementation work in that commit, without a separate docs/fixup commit or planning-commit amendment for those records. Exclude other tasks and preserve the no-change path without empty commits. Orchestrator commits without separate user commit approval. Reports, passing checks and Reviewer opinions do not replace acceptance. Preserve unrelated changes and ownership; verify the resulting SHA, content, HEAD and remaining changes. Existing small-task direct and plan-omission paths remain unchanged.
156
156
  - [review.significant-no-plan] Significant/high-risk work without a plan follows Implementer → QA and required QA rechecks → Reviewer of the final full change → Orchestrator acceptance. Do not omit Reviewer because no plan exists. This adds no plan obligation.
157
157
  - [review.significant-plan] Significant/high-risk plan work follows Implementer → required fresh QA → Orchestrator acceptance and focused commit for each task. 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 gate. Preserve required checks and necessary finding rechecks.
158
- - [review.final-plan-recheck] Final overall Reviewer findings on plan work, including behavior findings, follow Implementer → Reviewer without QA reassignment until resolved. This exception applies only at the final plan stage. Preserve required QA and QA failure rechecks before the initial final review and outside this exception.
159
- - [planning.plan-amend] Mechanical plan progress records during approved execution need no new user approval. Changes to goals, scope, criteria, method, risk, dependencies or required verification need revised-version approval and preparation before affected work. In both cases Orchestrator amends the original planning-document commit at a safe boundary, with no separate document or fixup commit. Preserve actual approval chronology, recoverable old/new content, hashes, versions and SHA mappings; never authorize past work retroactively. Rewrite only unpublished, unshared local linear history with clear ownership and no merges. Unknown publication/ownership, unexpected state or replay conflicts stop rewriting; no force push or fallback document commit. Preserve implementation task boundaries and revalidate affected evidence. Follow planning, handoff-prep, commit and verification for the full contract.
158
+ - [review.final-plan-recheck] Complete required QA and QA failure rechecks before the initial final overall Reviewer review. Once that review begins on plan work, every final Reviewer finding, including behavior, follows Implementer → Reviewer without QA reassignment until resolved. Keep corrections uncommitted through Reviewer rechecks, then accept and create one focused follow-up commit. Separate QA findings follow Implementer → QA. Preserve required QA outside this final Reviewer exception.
159
+ - [planning.plan-amend] Task progress records preserving the approved contract need no new user approval; Orchestrator includes the completed task's own records in its accepted implementation commit, without amending the original planning-document commit, creating history mappings or making a separate docs/fixup commit for them; record classification, reason and actual time as applicable. Spec/plan content changes other than task progress records require applicable approval and preparation; changes to goals, scope, criteria, method, risk, dependencies or required verification need revised-version approval and preparation before affected work. For these content changes Orchestrator MUST amend the original planning-document commit at a safe boundary; never create a separate docs or fixup commit. For these non-progress content amendments, preserve actual approval chronology, recoverable old/new content, hashes, versions and old→new SHA mappings; never authorize past work retroactively. For these amendments rewrite only unpublished, unshared local linear history with clear ownership and no merges. Unknown publication/ownership, unexpected state or replay conflicts stop rewriting; no force push or fallback document commit. Preserve implementation task boundaries and revalidate affected evidence. This obligation does not authorize amending implementation commits or rewriting history generally. Follow planning, handoff-prep, commit and verification for the full contract.
160
160
  - [planning.planner-brief] Follow planning.md's Planner drafting preparation and review procedure, including preflight, ledger, evidence classification, target preparation, preceding approvals, provenance and reference gates. Before Planner dispatch, evaluate F1–F8 direct-path eligibility and Bounded plan-omission eligibility independently. Enter each path only when all of that path's existing conditions are proven; if neither path qualifies, use normal full evaluation. Send one complete stage-specific initial brief. Reuse the same Planner instance across related stages when its role, context and source remain valid. Follow-up briefs send changed fields and cite an accessible prior brief for unchanged fields. Reuse evidence only for the same source set, absolute locator, resolved path, content fingerprint, purpose and approval scope in an accessible matching context. When source, target or scope changed, reconfirm affected inputs. Planner returns a complete proportional first draft and self-review. Orchestrator reviews and directly revises the same spec or plan when needed. A missing or failed first draft does not transfer initial authorship to Orchestrator. New product decisions outside approved scope require user input before Orchestrator revises the document. For design and brainstorming, allow the initial draft and one consolidated correction. Orchestrator reviews once with the fixed checklist and sends one consolidated correction using changed fields only. Further calls require user-approved material scope/evidence changes or concrete unmet checklist items after correction, plus meaningful new input or criterion-state progress. State changed input, target criterion, expected artifact and expected progress. Repeated unmet criteria without new input, evidence or progress hold the stage; report the criterion, observed evidence and exact unblock input/decision. Do not split omissions, repeat resolved items or count rewording/agent replacement as progress. Do not invoke Planner only for reformatting, re-expression, save errors or patch-application errors; Orchestrator handles these. Evaluate separate substantive work under the normal Planner gate. Preserve separate sequential design/spec/plan approvals. Add no fixed call cap or profile call-count conditions, and never accept an incomplete draft. Keep user progress brief and based on Planner status without relaying draft content. At approval, present the integrated, saved and reviewed Markdown without repeating its body in chat.
161
161
  - [platform.codex] Role restrictions are prompt-level contracts, not a filesystem sandbox. ARC supplies no native observer hook or role-specific Git guard. Existing shell capabilities are retained because static read access after shell reduction has not been verified; Implementer and QA need shell for approved checks.
162
162
  [ARC role policy: contract end]
@@ -56,9 +56,9 @@ SHA change alone invalidates no entire evidence set. Determine whether exact-HEA
56
56
  <a id="reviewer-timing-and-task-acceptance"></a>
57
57
  ## Task acceptance and final plan acceptance
58
58
 
59
- Task acceptance differs from final verification/acceptance. Connect criteria/observations/current checks/findings, not checkboxes/reports/passing commands alone. Use fresh QA where required or low-risk focused checks. Same-task rechecks default to current QA while scope/workspace/ownership/context remain valid.
59
+ Task acceptance differs from final verification/acceptance. Connect criteria/observations/current checks/findings, not checkboxes/reports/passing commands alone. Use fresh QA where required or low-risk focused checks. For same-task QA findings and required QA rechecks, reuse the current QA while scope/workspace/ownership/context remain valid. Final overall Reviewer findings on plan work follow Implementer → Reviewer without QA reassignment; see the [final plan Reviewer correction loop](#final-plan-reviewer-correction-loop).
60
60
 
61
- Do not delay independently acceptable tasks solely for final-only checks or defer currently required checks to accept early. State final integration scope/timing separately. Whole-plan Reviewer is final verification; task commits prove no unperformed final checks. Orchestrator decides final acceptance with QA/Reviewer/integration evidence/findings and unverified/disposition records. Shared evidence must satisfy all reuse rules.
61
+ Do not delay independently acceptable tasks solely for final-only checks or defer currently required checks to accept early. State final integration scope/timing separately. Whole-plan Reviewer is final verification; task commits prove no unperformed final checks. Orchestrator decides final acceptance with QA/Reviewer/integration evidence/findings and unverified/disposition records. Shared evidence MUST satisfy all reuse rules.
62
62
 
63
63
  Committed-plan final Reviewer findings need a follow-up task/planning/approvals. Keep corrections uncommitted; refresh committed state plus uncommitted diff/files in Reviewer artifacts/briefs. Reuse/assign independent Reviewer and repeat Implementer → Reviewer until resolved, then accept/commit one focused follow-up. Final QA findings still use Implementer → QA. No automatic amend/reset/duplicate originals; scope growth retains planning/approvals.
64
64
 
@@ -69,7 +69,7 @@ Committed-plan final Reviewer findings need a follow-up task/planning/approvals.
69
69
 
70
70
  With assigned criteria/cited prerequisites, QA may use available approved browser tools for apps/URLs.
71
71
 
72
- Briefs must supply workspace, existing launch command/URL, account/test-data scope, allowed interactions and this section's accessible citation. Use existing approved environment/tool/browser-skill instructions. No source/docs/tests/config edits, dependencies or environment changes. Missing prerequisites/tools/environment leave exact reported limits/unverified criteria.
72
+ Briefs MUST supply workspace, existing launch command/URL, account/test-data scope, allowed interactions and this section's accessible citation. Use existing approved environment/tool/browser-skill instructions. No source/docs/tests/config edits, dependencies or environment changes. Missing prerequisites/tools/environment leave exact reported limits/unverified criteria.
73
73
 
74
74
  For each criterion record command/URL, test state/viewport or inapplicability, interactions, expected/observed results and evidence. Startup/page-load/static checks alone prove no complete UI. Clean only QA-created processes/sessions; preserve shared services/sessions.
75
75
 
@@ -96,10 +96,10 @@ Supported `workflow` is approved complete spec+plan. No-plan/small-task/omission
96
96
 
97
97
  1. Orchestrator (`actor.role: "orchestrator"`) registers through `record`/`acceptance-evidence` with `data: {kind: "task", task: {...}}`. Task includes `id`, absolute `paths`, `criteria`, `requiredChecks`, `dependencies`, `approvalRef`, `approvalVersion`, `documentVersion`, `scopeVersion`, `targetVersion`. Pending-only registration is not acceptance/commit. Descriptor: `{executable, args, cwd, env, outputs}`; executable/cwd/outputs absolute, cwd/outputs inside workspace. No Reviewer in task checks.
98
98
  2. `status` observes `changeFingerprints.tasks[taskId]`/`changeFingerprints.final` independently from read-only Git inventory/index and current regular-file bytes/modes/deletions. Task covers owned paths, final the repository. Symlinks/submodules/unmerged indexes hold. This is no atomic observation/execution sandbox. RuntimeHash drift stays stale/hold without automatic stored-version update/migration/reapproval.
99
- 3. Check preparation: `operation: "check"`, `taskId`, `arguments: {scope: "task", actor: {id, role: "qa"}, descriptor, changeFingerprint, findingIds?}`. QA identity attestation must differ from Implementer/Orchestrator; cross-task QA/Implementer reuse is rejected. Descriptor exactly matches registration. After durable intent, execute only existing authorized scope.
99
+ 3. Check preparation: `operation: "check"`, `taskId`, `arguments: {scope: "task", actor: {id, role: "qa"}, descriptor, changeFingerprint, findingIds?}`. QA identity attestation MUST differ from Implementer/Orchestrator; cross-task QA/Implementer reuse is rejected. Descriptor exactly matches registration. After durable intent, execute only existing authorized scope.
100
100
  4. `result`/`reconcile` records `intentId`, `{status, messageRef, data}` with same actor/descriptor/scope, taskId where applicable, fingerprint and `verdict: "proven" | "unmet" | "unverified"`. Even succeeded/proven applies only to that version. It replaces neither semantic proof nor acceptance. Failed/unknown/mismatch/unverified is not passing evidence. Preserve history.
101
101
 
102
- Failed checks/reviews leave findings. Open separately via `data: {action: "open", id, checkId, message}`. After fixes record `data: {action: "resolve", id, actor: {id, role: "implementer"}, changeFingerprint}` plus evidence messageRef. Actor must be assigned to the task or relevant overall task. Resolved becomes closed only after later prepare `findingIds` and same-version successful revalidation. Prior QA failures retain Implementer→QA.
102
+ Failed checks/reviews leave findings. Open separately via `data: {action: "open", id, checkId, message}`. After fixes record `data: {action: "resolve", id, actor: {id, role: "implementer"}, changeFingerprint}` plus evidence messageRef. Actor MUST be assigned to the task or relevant overall task. Resolved becomes closed only after later prepare `findingIds` and same-version successful revalidation. Prior QA failures retain Implementer→QA.
103
103
 
104
104
  Final review uses `operation: "review"`, `scope: "final"`, `actor.role: "reviewer"`, `descriptor: {kind: "source-review", paths: [...]}` without taskId. Initial final review needs all tasks accepted/current required QA, never task acceptance/commit prerequisite. Plan-final findings repeat Implementer resolution→Reviewer without QA reassignment; old QA is not subsequent-fix execution. Separate unresolved QA remains.
105
105
 
@@ -108,7 +108,7 @@ Scope/document/approval records preserve history. `data.affectedTaskIds` invalid
108
108
  <a id="task-acceptance-and-focused-commit-reconciliation-in-the-cooperative-cli"></a>
109
109
  ### Task acceptance and focused commit reconciliation in the cooperative CLI
110
110
 
111
- Plan-mode `prepare` supports `operation: "accept"`/`operation: "commit"`. Acceptance attests `actor.role: "orchestrator"`, taskId and arguments messageRef/same criteria/current exact QA checkIds/all findingIds/current fingerprint. Latest required descriptors must be passed/proven and findings closed by fixes/QA. Successful attestation marks accepted; reports/checks alone do not. `operator-attested` means operator confirms semantics/identity.
111
+ Plan-mode `prepare` supports `operation: "accept"`/`operation: "commit"`. Acceptance attests `actor.role: "orchestrator"`, taskId and arguments messageRef/same criteria/current exact QA checkIds/all findingIds/current fingerprint. Latest required descriptors MUST be passed/proven and findings closed by fixes/QA. Successful attestation marks accepted; reports/checks alone do not. `operator-attested` means operator confirms semantics/identity.
112
112
 
113
113
  Acceptance pins actual index tree/staged diff/paths/fingerprint. Stage approved paths beforehand and confirm QA for that index. Unrelated/other-task paths or in-scope unstaged/untracked changes hold. Code cannot identify semantically unrelated same-file hunks; Orchestrator reads diff.
114
114
 
@@ -120,11 +120,11 @@ Never rewrite QA fingerprints after commit. Separate post-commit observations de
120
120
 
121
121
  [ARC role policy: contract begin]
122
122
  Generated from lib/policy/role-policy.json; do not edit this managed section manually.
123
- - [git.orchestrator-accept-commit] Only Orchestrator accepts work and performs 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 separate user commit approval. Reports, passing checks and Reviewer opinions do not replace acceptance. Preserve unrelated changes and ownership; verify the resulting SHA, content, HEAD and remaining changes. Existing small-task direct and plan-omission paths remain unchanged.
123
+ - [git.orchestrator-accept-commit] Only Orchestrator accepts work and performs Git mutations. One approved top-level plan task becomes one focused implementation commit after criteria, required checks and findings are satisfied. Orchestrator accepts, then includes that task's own progress records made after task completion (checkboxes, notes, results, evidence and status) with its implementation work in that commit, without a separate docs/fixup commit or planning-commit amendment for those records. Exclude other tasks and preserve the no-change path without empty commits. Orchestrator commits without separate user commit approval. Reports, passing checks and Reviewer opinions do not replace acceptance. Preserve unrelated changes and ownership; verify the resulting SHA, content, HEAD and remaining changes. Existing small-task direct and plan-omission paths remain unchanged.
124
124
  - [review.significant-no-plan] Significant/high-risk work without a plan follows Implementer → QA and required QA rechecks → Reviewer of the final full change → Orchestrator acceptance. Do not omit Reviewer because no plan exists. This adds no plan obligation.
125
125
  - [review.significant-plan] Significant/high-risk plan work follows Implementer → required fresh QA → Orchestrator acceptance and focused commit for each task. 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 gate. Preserve required checks and necessary finding rechecks.
126
- - [review.final-plan-recheck] Final overall Reviewer findings on plan work, including behavior findings, follow Implementer → Reviewer without QA reassignment until resolved. This exception applies only at the final plan stage. Preserve required QA and QA failure rechecks before the initial final review and outside this exception.
127
- - [planning.plan-amend] Mechanical plan progress records during approved execution need no new user approval. Changes to goals, scope, criteria, method, risk, dependencies or required verification need revised-version approval and preparation before affected work. In both cases Orchestrator amends the original planning-document commit at a safe boundary, with no separate document or fixup commit. Preserve actual approval chronology, recoverable old/new content, hashes, versions and SHA mappings; never authorize past work retroactively. Rewrite only unpublished, unshared local linear history with clear ownership and no merges. Unknown publication/ownership, unexpected state or replay conflicts stop rewriting; no force push or fallback document commit. Preserve implementation task boundaries and revalidate affected evidence. Follow planning, handoff-prep, commit and verification for the full contract.
126
+ - [review.final-plan-recheck] Complete required QA and QA failure rechecks before the initial final overall Reviewer review. Once that review begins on plan work, every final Reviewer finding, including behavior, follows Implementer → Reviewer without QA reassignment until resolved. Keep corrections uncommitted through Reviewer rechecks, then accept and create one focused follow-up commit. Separate QA findings follow Implementer → QA. Preserve required QA outside this final Reviewer exception.
127
+ - [planning.plan-amend] Task progress records preserving the approved contract need no new user approval; Orchestrator includes the completed task's own records in its accepted implementation commit, without amending the original planning-document commit, creating history mappings or making a separate docs/fixup commit for them; record classification, reason and actual time as applicable. Spec/plan content changes other than task progress records require applicable approval and preparation; changes to goals, scope, criteria, method, risk, dependencies or required verification need revised-version approval and preparation before affected work. For these content changes Orchestrator MUST amend the original planning-document commit at a safe boundary; never create a separate docs or fixup commit. For these non-progress content amendments, preserve actual approval chronology, recoverable old/new content, hashes, versions and old→new SHA mappings; never authorize past work retroactively. For these amendments rewrite only unpublished, unshared local linear history with clear ownership and no merges. Unknown publication/ownership, unexpected state or replay conflicts stop rewriting; no force push or fallback document commit. Preserve implementation task boundaries and revalidate affected evidence. This obligation does not authorize amending implementation commits or rewriting history generally. Follow planning, handoff-prep, commit and verification for the full contract.
128
128
  - [platform.codex] Role restrictions are prompt-level contracts, not a filesystem sandbox. ARC supplies no native observer hook or role-specific Git guard. Existing shell capabilities are retained because static read access after shell reduction has not been verified; Implementer and QA need shell for approved checks.
129
129
  [ARC role policy: contract end]
130
130
 
@@ -8,6 +8,8 @@ import {classifyGitCommand} from '../git-query.mjs';
8
8
  const text=v=>typeof v==='string'&&v.length>0;
9
9
  const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
10
10
  const supported=new Set(['Read','Glob','Grep','Bash','Write','Edit','MultiEdit','Agent']);
11
+ // A bridge child carries this marker; its Hook events are observation-only and never recorded.
12
+ const bridgeChild=context=>text((context?.env??process.env).ARC_BRIDGE_CHILD);
11
13
  const deny=reason=>({decision:'deny',reason,ruleIds:['runtime.claude'],proposedTransition:null});
12
14
  /** Host-verified support for this installed version is required. A config value
13
15
  * alone cannot establish hook failure blocking; provider wiring belongs to T6. */
@@ -42,11 +44,13 @@ export function renderClaudeDecision(decision){
42
44
  * timeout, hosted/specialized paths and existing write_stdin are outside it. */
43
45
  export async function runClaudeGate(input,context={}){
44
46
  if(input?.hook_event_name==='PostToolUse'){
47
+ if(bridgeChild(context))return {};
45
48
  // Result recording cannot authorize assignment/start or prevent a completed call.
46
49
  try{if(input.session_id===context.sessionRef&&input.tool_use_id===context.toolUseId&&text(context.actorRef)&&typeof context.recordToolResult==='function')await context.recordToolResult(structuredClone(input));}catch{}
47
50
  return {};
48
51
  }
49
52
  if(input?.hook_event_name==='SubagentStart'){
53
+ if(bridgeChild(context))return {};
50
54
  // SubagentStart cannot prevent startup. Only a trusted provider can correlate
51
55
  // agent_id with a pending assignment; tool/event agent_type is not authority.
52
56
  try{
@@ -7,6 +7,8 @@ import {runGate} from '../gate.mjs';
7
7
  const text=v=>typeof v==='string'&&v.length>0;
8
8
  const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
9
9
  const supported=new Set(['Read','Glob','Grep','Bash','Write','Edit','MultiEdit','exec_command','apply_patch','Agent','spawn_agent']);
10
+ // A bridge child carries this marker; its Hook events are observation-only and never recorded.
11
+ const bridgeChild=context=>text((context?.env??process.env).ARC_BRIDGE_CHILD);
10
12
  const deny=reason=>({decision:'deny',reason,ruleIds:['runtime.codex'],proposedTransition:null});
11
13
  /** Context is a trusted host dependency, never deserialized from stdin/tool_input.
12
14
  * describeTool must parse the complete tool invocation conservatively, and supply
@@ -32,6 +34,7 @@ export function renderCodexDecision(decision){
32
34
  * timeout, hosted/specialized paths and existing write_stdin are outside it. */
33
35
  export async function runCodexGate(input,context={}){
34
36
  if(input?.hook_event_name==='SubagentStart'){
37
+ if(bridgeChild(context))return {};
35
38
  // SubagentStart cannot prevent startup. Only a trusted provider can correlate
36
39
  // agent_id with a pending assignment; tool/event agent_type is not authority.
37
40
  try{
@@ -6,7 +6,9 @@ import {observeCooperativeTarget,validateObservedTarget,validateWorkflowId,workf
6
6
  import {saveDurableState} from './store.mjs';
7
7
  export const COOPERATIVE_RUNTIME_MODULES=Object.freeze([
8
8
  'cli.mjs','command.mjs','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','schema.mjs','operations.mjs','gate.mjs','adapters/codex.mjs','adapters/claude.mjs','capabilities.mjs','identity.mjs','git-query.mjs','target-preparation.mjs'
9
+ 'scope.mjs','store.mjs','git-evidence.mjs','assignment.mjs','verification.mjs','acceptance.mjs','external.mjs','schema.mjs','operations.mjs','gate.mjs','adapters/codex.mjs','adapters/claude.mjs','capabilities.mjs','identity.mjs','git-query.mjs','target-preparation.mjs',
10
+ 'local-cli.mjs','role-routing-config.mjs','role-routing.mjs','role-bridge.mjs',
11
+ 'role-dispatch-policy.mjs','role-dispatch-store.mjs','role-bridge-args.mjs','role-observe.mjs','role-supervisor.mjs'
10
12
  ]);
11
13
  export const cooperativeCoverage=()=>({enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false});
12
14
  export function commandResult({workflowId,state,input,decision='allow',ruleId='cooperative.recorded',persisted=false,...extra}){
@@ -16,7 +18,7 @@ export async function cooperativeVersions(){
16
18
  const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
17
19
  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
20
  const runtime=await Promise.all(COOPERATIVE_RUNTIME_MODULES.map(file=>fs.readFile(new URL(file,import.meta.url))));
19
- return {policy:'1',runtime:'cooperative-6',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
21
+ return {policy:'1',runtime:'cooperative-8',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
20
22
  }
21
23
  export async function initializeCooperativeWorkflow({cwd,workflowId,input,observe=observeCooperativeTarget,storage={}}){
22
24
  validateWorkflowId(workflowId);validateCooperativeCommand({command:'init',input});
@@ -1,13 +1,19 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import os from 'node:os';
3
4
  import {initializeCooperativeWorkflow,commandResult} from './bootstrap.mjs';
4
5
  import {runCooperativeCommand} from './cooperative.mjs';
5
6
  import {validateWorkflowId} from './scope.mjs';
7
+ import {prepareRoleDispatch,routingStatus,invalidRoutingRequest} from './role-routing.mjs';
8
+ import {runBridgeDispatch,recordRoleObservation,resumeRoleDispatch,cancelRoleDispatch,heldRoutingResult} from './role-bridge.mjs';
6
9
  export async function runWorkflowCommand(args,io={}){
7
- const output=io.output??process.stdout;let workflowId=null;
10
+ const output=io.output??process.stdout;let workflowId=null,isRouting=false;
8
11
  try{
9
12
  const [command,...rest]=args,options={};
10
- if(!['init','record','status','reconcile','prepare','result'].includes(command))throw Error('Expected workflow command');
13
+ isRouting=['routing-status','prepare-dispatch','run-dispatch','observe','resume','cancel'].includes(command);
14
+ if(!['init','record','status','reconcile','prepare','result'].includes(command)&&!isRouting)throw Error('Expected workflow command');
15
+ // A bridge child must not drive routing itself: the supervisor sets ARC_BRIDGE_CHILD for the child CLI process tree.
16
+ if(isRouting&&(io.env??process.env).ARC_BRIDGE_CHILD){output.write(JSON.stringify({workflowId:null,...invalidRoutingRequest({}),message:'Routing commands are not available inside a bridge child.'})+'\n');return 2;}
11
17
  for(let i=0;i<rest.length;i+=2){const key=rest[i];if(!['--cwd','--workflow','--input'].includes(key)||options[key]!==undefined||typeof rest[i+1]!=='string')throw Error('Invalid workflow option');options[key]=rest[i+1];}
12
18
  const cwd=options['--cwd'];workflowId=options['--workflow'];validateWorkflowId(workflowId);
13
19
  if(typeof cwd!=='string'||!path.isAbsolute(cwd)||path.normalize(cwd)!==cwd)throw Error('Absolute workspace required');
@@ -15,7 +21,18 @@ export async function runWorkflowCommand(args,io={}){
15
21
  // Check/review, commit and external intents are recorded for the operator.
16
22
  // Actual Git mutations remain Orchestrator actions; reconciliation observes their results.
17
23
  const input=command==='status'?undefined:JSON.parse(io.input??fs.readFileSync(0,'utf8'));
18
- const result=await(command==='init'?initializeCooperativeWorkflow({cwd,workflowId,input}):runCooperativeCommand({cwd,workflowId,command,input}));
24
+ let result;
25
+ if(isRouting){
26
+ if(!input||typeof input!=='object'||Array.isArray(input))throw Error('Invalid routing input');
27
+ const context={cwd,userHome:os.homedir(),env:process.env,workflowId,hostPlatform:input.hostPlatform,executionEnvironment:input.executionEnvironment};
28
+ const keys=Object.keys(input),allowed={'routing-status':[['hostPlatform','executionEnvironment'],[]],'prepare-dispatch':[['hostPlatform','executionEnvironment','role','expectedRevision','requestId','taskId'],['allowedPaths']],'run-dispatch':[['hostPlatform','executionEnvironment','dispatchId','brief'],[]],observe:[['hostPlatform','executionEnvironment','dispatchId'],['waitMs','event','nativeAgentId']],resume:[['hostPlatform','executionEnvironment','dispatchId','brief'],[]],cancel:[['hostPlatform','executionEnvironment','dispatchId'],[]]}[command];
29
+ if(allowed&&(allowed[0].some(key=>!Object.hasOwn(input,key))||keys.some(key=>!allowed[0].includes(key)&&!allowed[1].includes(key))))result=invalidRoutingRequest(context);
30
+ else result=command==='routing-status'?await routingStatus({context}):command==='prepare-dispatch'?await prepareRoleDispatch({context,assignment:{role:input.role,requestId:input.requestId,taskId:input.taskId,...(Object.hasOwn(input,'allowedPaths')?{allowedPaths:input.allowedPaths}:{})},expectedRevision:input.expectedRevision}):command==='run-dispatch'?await runBridgeDispatch({context,dispatchId:input.dispatchId,brief:input.brief}):command==='observe'?await recordRoleObservation({context,dispatchId:input.dispatchId,...(Object.hasOwn(input,'waitMs')?{waitMs:input.waitMs}:{}),...(Object.hasOwn(input,'event')?{event:input.event}:{}),...(Object.hasOwn(input,'nativeAgentId')?{nativeAgentId:input.nativeAgentId}:{})}):command==='resume'?await resumeRoleDispatch({context,dispatchId:input.dispatchId,brief:input.brief}):await cancelRoleDispatch({context,dispatchId:input.dispatchId});
31
+ result={workflowId,...result};
32
+ }else result=await(command==='init'?initializeCooperativeWorkflow({cwd,workflowId,input}):runCooperativeCommand({cwd,workflowId,command,input}));
19
33
  output.write(JSON.stringify(result)+'\n');return result.decision==='deny'?2:result.decision==='hold'?3:0;
20
- }catch(error){output.write(JSON.stringify(commandResult({workflowId,decision:'hold',ruleId:'cooperative.error',error:error.message}))+'\n');return 1;}
34
+ }catch(error){
35
+ const result=isRouting?{workflowId:null,...heldRoutingResult('activation_unverified','Provide a valid routing request and verify the active configuration and installed markers.')}:commandResult({workflowId,decision:'hold',ruleId:'cooperative.error',error:error.message});
36
+ output.write(JSON.stringify(result)+'\n');return 1;
37
+ }
21
38
  }
@@ -0,0 +1,248 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import { StringDecoder } from 'node:string_decoder';
4
+ import { spawn } from 'node:child_process';
5
+ import { DEFAULT_POLICY } from './role-dispatch-policy.mjs';
6
+
7
+ const environments = new WeakMap();
8
+ export function resolveConfigHome(platform, { userHome, env = {}, cwd } = {}) {
9
+ if (!['codex', 'claude'].includes(platform)) throw Error('Target must be codex or claude');
10
+ if (typeof userHome !== 'string' || !path.isAbsolute(userHome) || !userHome.trim()) throw Error('userHome must be an absolute user directory');
11
+ userHome = path.resolve(userHome);
12
+ if (!env || typeof env !== 'object') throw Error('env must be an environment object');
13
+ const expand = value => value === '~' ? userHome : value.startsWith('~/') ? path.join(userHome, value.slice(2)) : value;
14
+ let home;
15
+ if (platform === 'codex') {
16
+ const raw = env.CODEX_HOME;
17
+ if (raw !== undefined && (typeof raw !== 'string' || !raw.trim())) throw Error('CODEX_HOME is empty or invalid');
18
+ const expanded = expand(raw ?? path.join(userHome, '.codex'));
19
+ if (path.isAbsolute(expanded)) home = path.resolve(expanded);
20
+ else { const base = cwd ?? process.cwd(); if (typeof base !== 'string' || !path.isAbsolute(base)) throw Error('cwd must be absolute for relative CODEX_HOME'); home = path.resolve(base, expanded); }
21
+ } else {
22
+ home = path.join(userHome, '.claude'); const raw = env.CLAUDE_CONFIG_DIR;
23
+ if (raw !== undefined && (typeof raw !== 'string' || !raw.trim() || !path.isAbsolute(expand(raw)) || path.resolve(expand(raw)) !== home)) throw Error('CLAUDE_CONFIG_DIR must select the default ~/.claude directory');
24
+ }
25
+ if (home === '/' || home === userHome) throw Error('Target home must not be the filesystem or user-home root');
26
+ return home;
27
+ }
28
+ export function resolveLocalCli(platform, { cwd, userHome, env = process.env } = {}) {
29
+ if (!['codex', 'claude'].includes(platform)) return { platform, reason: 'unsupported_platform' };
30
+ let home;
31
+ try {
32
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd) || path.resolve(cwd) !== cwd || !fs.statSync(cwd).isDirectory()) return { platform, reason: 'invalid_cwd' };
33
+ home = resolveConfigHome(platform, { cwd, userHome, env });
34
+ } catch { return { platform, reason: 'invalid_context' }; }
35
+ const dirs = typeof env.PATH === 'string' ? env.PATH.split(path.delimiter) : [];
36
+ let executable;
37
+ for (const dir of dirs) {
38
+ const candidate = path.resolve(cwd, dir || '.', platform);
39
+ try { if (fs.statSync(candidate).isFile()) { fs.accessSync(candidate, fs.constants.X_OK); executable = candidate; break; } } catch { /* continue PATH search */ }
40
+ }
41
+ if (!executable) return { platform, reason: 'cli_not_found' };
42
+ const context = Object.freeze({ platform, executable, cwd, configHome: home });
43
+ environments.set(context, Object.freeze({ ...env, [platform === 'codex' ? 'CODEX_HOME' : 'CLAUDE_CONFIG_DIR']: home }));
44
+ return context;
45
+ }
46
+ export function localCliEnvironment(context) { const env = environments.get(context); if (!env) throw Error('Invalid CLI context'); return { ...env }; }
47
+ /** Checks Codex authentication with refresh; only a token-presence boolean survives parsing. */
48
+ export async function probeCodexAuthStatus(context, { signal, timeoutMs = 10000 } = {}) {
49
+ const result = (authStatus, reason) => ({ platform: 'codex', authStatus, ...(reason ? { reason } : {}) });
50
+ if (!environments.has(context) || context.platform !== 'codex') return result('unknown', context?.reason ?? 'invalid_context');
51
+ if (signal?.aborted) return result('unknown', 'aborted');
52
+ let child;
53
+ try { child = spawn(context.executable, ['app-server'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['pipe', 'pipe', 'pipe'], shell: false }); }
54
+ catch { return result('unknown', 'cli_execution_error'); }
55
+ let closed = false, failure, pending, nextId = 0, buffer = '', outputBytes = 0;
56
+ const decoder = new StringDecoder('utf8');
57
+ let resolveClosed;
58
+ const closedPromise = new Promise(resolve => { resolveClosed = resolve; });
59
+ const fail = reason => { failure ??= reason; if (pending) { const {reject} = pending; pending = null; reject(); } };
60
+ const onClose = () => { closed = true; resolveClosed(); fail('cli_execution_error'); };
61
+ const onError = () => fail('cli_execution_error');
62
+ const onAbort = () => fail('aborted');
63
+ const countOutput = chunk => { outputBytes += chunk.length; if (outputBytes > 1048576) { fail('invalid_response'); return false; } return !failure; };
64
+ const classify = value => {
65
+ if (!value || typeof value !== 'object' || Array.isArray(value) || !(value.requiresOpenaiAuth === null || typeof value.requiresOpenaiAuth === 'boolean') ||
66
+ !(value.authMethod === null || typeof value.authMethod === 'string') ||
67
+ !(value.authToken === null || typeof value.authToken === 'string')) return result('unknown', 'invalid_response');
68
+ const hasToken = typeof value.authToken === 'string' && value.authToken.length > 0;
69
+ if (value.requiresOpenaiAuth === false || typeof value.authMethod === 'string' && hasToken) return result('authenticated');
70
+ if (value.authMethod === null) return result('unauthorized', 'not_logged_in');
71
+ if (value.authToken !== null) return result('unknown', 'invalid_response');
72
+ if (value.authMethod === 'chatgpt') return result('unauthorized', 'token_rejected');
73
+ if (['headers', 'agentIdentity', 'personalAccessToken'].includes(value.authMethod)) return result('authenticated');
74
+ return result('unknown', 'auth_unverified');
75
+ };
76
+ const onData = chunk => {
77
+ if (!countOutput(chunk)) { buffer = ''; return; }
78
+ buffer += decoder.write(chunk);
79
+ let newline;
80
+ while (!failure && (newline = buffer.indexOf('\n')) !== -1) {
81
+ let line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);
82
+ if (!line.trim()) continue;
83
+ let message;
84
+ try { message = JSON.parse(line); } catch { line = ''; buffer = ''; fail('invalid_response'); return; }
85
+ line = '';
86
+ if (message && typeof message === 'object' && !Array.isArray(message) &&
87
+ (Object.hasOwn(message, 'method') || !Object.hasOwn(message, 'id'))) { message = null; continue; }
88
+ if (!message || !pending || message.id !== pending.id) { message = null; fail('invalid_response'); return; }
89
+ if (Object.hasOwn(message, 'error')) { message = null; fail('status_command_failed'); return; }
90
+ if (!Object.hasOwn(message, 'result')) { message = null; fail('invalid_response'); return; }
91
+ const value = pending.method === 'initialize'
92
+ ? (message.result && typeof message.result === 'object' && !Array.isArray(message.result) && typeof message.result.userAgent === 'string' && message.result.userAgent.length > 0 ? true : false)
93
+ : classify(message.result);
94
+ message = null;
95
+ const {resolve} = pending; pending = null; resolve(value);
96
+ }
97
+ };
98
+ const onStderr = chunk => { countOutput(chunk); };
99
+ child.on('close', onClose); child.on('error', onError);
100
+ child.stdout.on('data', onData); child.stderr.on('data', onStderr);
101
+ for (const stream of [child.stdin, child.stdout, child.stderr]) stream.on('error', onError);
102
+ signal?.addEventListener('abort', onAbort, { once: true });
103
+ if (signal?.aborted) onAbort();
104
+ const timer = setTimeout(() => fail('timeout'), Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
105
+ const send = message => { if (failure || closed) throw new Error('Codex authentication unavailable'); child.stdin.write(JSON.stringify(message) + '\n'); };
106
+ const request = (method, params) => new Promise((resolve, reject) => {
107
+ if (failure || closed) { reject(); return; }
108
+ const id = ++nextId; pending = {id, method, resolve, reject};
109
+ try { send({id, method, params}); } catch { fail('cli_execution_error'); }
110
+ });
111
+ let authentication;
112
+ try {
113
+ if (!await request('initialize', {clientInfo: {name: 'arc', title: 'ARC', version: '1.0.0'}})) fail('invalid_response');
114
+ send({method: 'initialized', params: {}});
115
+ authentication = await request('getAuthStatus', {includeToken: true, refreshToken: true});
116
+ if (failure) authentication = result('unknown', failure);
117
+ } catch { authentication = result('unknown', failure ?? 'cli_execution_error'); }
118
+ finally {
119
+ clearTimeout(timer); signal?.removeEventListener('abort', onAbort);
120
+ buffer = ''; pending = null;
121
+ try { child.stdin.end(); } catch { /* cleanup only */ }
122
+ if (!closed) { try { child.kill('SIGTERM'); } catch { /* still wait for close */ } }
123
+ const wait = async ms => {
124
+ if (closed) return true;
125
+ let timerId;
126
+ const done = await Promise.race([closedPromise.then(() => true), new Promise(resolve => { timerId = setTimeout(() => resolve(false), ms); })]);
127
+ clearTimeout(timerId); return done;
128
+ };
129
+ if (!await wait(1000)) {
130
+ try { child.kill('SIGKILL'); } catch { /* bounded cleanup */ }
131
+ if (!await wait(1000)) authentication = result('unknown', 'cli_execution_error');
132
+ }
133
+ child.stdout.removeListener('data', onData); child.stderr.removeListener('data', onStderr);
134
+ child.removeListener('close', onClose);
135
+ // Keep error guards on streams until destruction, including late pipe errors.
136
+ for (const stream of [child.stdin, child.stdout, child.stderr]) stream.destroy();
137
+ }
138
+ return authentication;
139
+ }
140
+ /** Checks local Codex login state without starting app-server or refreshing credentials. */
141
+ export async function probeCodexLoginStatus(context, { signal, timeoutMs = 10000 } = {}) {
142
+ const result = (authStatus, reason) => ({ platform: 'codex', authStatus, ...(reason ? { reason } : {}) });
143
+ if (!environments.has(context) || context.platform !== 'codex') return result('unknown', context?.reason ?? 'invalid_context');
144
+ if (signal?.aborted) return result('unknown', 'aborted');
145
+ let child;
146
+ try { child = spawn(context.executable, ['login', 'status'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
147
+ catch { return result('unknown', 'status_command_failed'); }
148
+ let closed = false, stderr = '', outputBytes = 0, timer, resolveClosed;
149
+ const closedPromise = new Promise(resolve => { resolveClosed = resolve; });
150
+ let finish;
151
+ const authentication = new Promise(resolve => { finish = resolve; });
152
+ const fail = reason => finish(result('unknown', reason));
153
+ const onError = () => fail('status_command_failed');
154
+ const onAbort = () => fail('aborted');
155
+ const countOutput = chunk => {
156
+ outputBytes += chunk.length;
157
+ if (outputBytes > 65536) { stderr = ''; fail('status_command_failed'); return false; }
158
+ return true;
159
+ };
160
+ const onStdout = chunk => { countOutput(chunk); };
161
+ const onStderr = chunk => { if (countOutput(chunk)) stderr += chunk.toString(); };
162
+ const onClose = (code, exitSignal) => {
163
+ closed = true; resolveClosed();
164
+ finish(exitSignal ? result('unknown', 'status_command_failed') : code === 0 ? result('authenticated') :
165
+ code === 1 && stderr.trim() === 'Not logged in' ? result('unauthorized', 'not_logged_in') : result('unknown', 'status_command_failed'));
166
+ };
167
+ child.on('error', onError); child.on('close', onClose);
168
+ child.stdout.on('data', onStdout); child.stderr.on('data', onStderr);
169
+ for (const stream of [child.stdout, child.stderr]) stream.on('error', onError);
170
+ signal?.addEventListener('abort', onAbort, { once: true });
171
+ timer = setTimeout(() => fail('timeout'), Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
172
+ if (signal?.aborted) onAbort();
173
+ const value = await authentication;
174
+ clearTimeout(timer); signal?.removeEventListener('abort', onAbort);
175
+ if (!closed) { try { child.kill('SIGTERM'); } catch { /* bounded cleanup */ } }
176
+ const wait = async ms => {
177
+ if (closed) return true;
178
+ let timerId;
179
+ const done = await Promise.race([closedPromise.then(() => true), new Promise(resolve => { timerId = setTimeout(() => resolve(false), ms); })]);
180
+ clearTimeout(timerId); return done;
181
+ };
182
+ if (!await wait(1000)) {
183
+ try { child.kill('SIGKILL'); } catch { /* bounded cleanup */ }
184
+ await wait(1000);
185
+ }
186
+ child.stdout.removeListener('data', onStdout); child.stderr.removeListener('data', onStderr);
187
+ child.removeListener('close', onClose);
188
+ child.stdout.destroy(); child.stderr.destroy();
189
+ return value;
190
+ }
191
+ export async function probePlatformAuth(context, { signal, timeoutMs = 10000 } = {}) {
192
+ const platform = context?.platform;
193
+ const result = (authStatus, reason) => ({ platform, authStatus, ...(reason ? { reason } : {}) });
194
+ if (platform !== 'claude') return result('unknown', 'invalid_context');
195
+ if (!environments.has(context)) return result('unknown', context?.reason ?? 'invalid_context');
196
+ if (signal?.aborted) return result('unknown', 'aborted');
197
+ return new Promise(resolve => {
198
+ let child, output = '', stderr = '', overflow = false, done = false, reason;
199
+ const finish = value => { if (done) return; done = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); resolve(value); };
200
+ const abort = () => { reason = 'aborted'; child?.kill(); finish(result('unknown', reason)); };
201
+ const timer = setTimeout(() => { reason = 'timeout'; child?.kill(); finish(result('unknown', reason)); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
202
+ signal?.addEventListener('abort', abort, { once: true });
203
+ try { child = spawn(context.executable, ['auth', 'status', '--json'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
204
+ catch { finish(result('unknown', 'cli_execution_error')); return; }
205
+ child.stdout.on('data', chunk => { if (output.length + chunk.length > 65536) overflow = true; else if (!overflow) output += chunk.toString(); });
206
+ child.stderr.on('data', chunk => { if (stderr.length + chunk.length > 65536) overflow = true; else if (!overflow) stderr += chunk.toString(); });
207
+ child.on('error', () => finish(result('unknown', 'cli_execution_error')));
208
+ child.on('close', (code, exitSignal) => {
209
+ if (exitSignal || overflow) return finish(result('unknown', overflow ? 'invalid_response' : 'cli_execution_error'));
210
+ let parsed; try { parsed = JSON.parse(output); } catch { return finish(result('unknown', 'invalid_response')); }
211
+ if (parsed?.loggedIn === true && code === 0) return finish(result('authenticated'));
212
+ if (parsed?.loggedIn === false && code === 1) return finish(result('unauthorized', 'not_logged_in'));
213
+ finish(result('unknown', 'status_mismatch'));
214
+ });
215
+ if (signal?.aborted) abort();
216
+ });
217
+ }
218
+ export function compareVersions(a, b) {
219
+ const left = String(a).split('.').map(Number), right = String(b).split('.').map(Number);
220
+ for (let i = 0; i < Math.max(left.length, right.length); i += 1) { const x = left[i] ?? 0, y = right[i] ?? 0; if (x !== y) return x < y ? -1 : 1; }
221
+ return 0;
222
+ }
223
+ /** Runs `<cli> --version`; keeps only the parsed version, never the raw output. */
224
+ export async function probeCliVersion(context, { signal, timeoutMs = 10000, policy = DEFAULT_POLICY } = {}) {
225
+ const platform = context?.platform;
226
+ const result = (version, supported, reason) => ({ version, supported, ...(reason ? { reason } : {}) });
227
+ if (!environments.has(context) || signal?.aborted) return result(null, false, 'cli_execution_error');
228
+ return new Promise(resolve => {
229
+ let child, output = '', overflow = false, done = false;
230
+ const finish = value => { if (done) return; done = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); resolve(value); };
231
+ const abort = () => { child?.kill(); finish(result(null, false, 'cli_execution_error')); };
232
+ const timer = setTimeout(() => { child?.kill(); finish(result(null, false, 'timeout')); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
233
+ signal?.addEventListener('abort', abort, { once: true });
234
+ try { child = spawn(context.executable, ['--version'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
235
+ catch { finish(result(null, false, 'cli_execution_error')); return; }
236
+ child.stdout.on('data', chunk => { if (output.length + chunk.length > 65536) overflow = true; else if (!overflow) output += chunk.toString(); });
237
+ child.stderr.on('data', chunk => { if (chunk.length > 65536) overflow = true; });
238
+ child.on('error', () => finish(result(null, false, 'cli_execution_error')));
239
+ child.on('close', (code, exitSignal) => {
240
+ if (exitSignal || code !== 0 || overflow) return finish(result(null, false, 'cli_execution_error'));
241
+ const version = /\d+\.\d+\.\d+/.exec(output)?.[0] ?? null;
242
+ if (!version) return finish(result(null, false, 'version_unparsed'));
243
+ const range = policy?.supportedVersions?.[platform];
244
+ const supported = Boolean(range) && compareVersions(version, range.min) >= 0 && compareVersions(version, range.below) < 0;
245
+ finish(supported ? result(version, true) : result(version, false, 'version_unsupported'));
246
+ });
247
+ });
248
+ }