@yunhozz/arc 0.3.4 → 0.4.0

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 (135) hide show
  1. package/MANIFEST.sha256 +133 -94
  2. package/README.md +56 -21
  3. package/claude/skill/SKILL.md +1 -1
  4. package/claude/skill/references/commit.md +10 -8
  5. package/claude/skill/references/coordination.md +6 -4
  6. package/claude/skill/references/handoff-prep.md +12 -12
  7. package/claude/skill/references/handoff.md +2 -0
  8. package/claude/skill/references/planning.md +8 -8
  9. package/claude/skill/references/verification.md +6 -6
  10. package/codex/skill/SKILL.md +1 -1
  11. package/codex/skill/references/commit.md +10 -8
  12. package/codex/skill/references/coordination.md +6 -4
  13. package/codex/skill/references/handoff-prep.md +12 -12
  14. package/codex/skill/references/handoff.md +2 -0
  15. package/codex/skill/references/planning.md +8 -8
  16. package/codex/skill/references/verification.md +6 -6
  17. package/gemini/GEMINI.md +8 -0
  18. package/gemini/agents/arc-implementer.md +37 -0
  19. package/gemini/agents/arc-planner.md +47 -0
  20. package/gemini/agents/arc-qa.md +37 -0
  21. package/gemini/agents/arc-reviewer.md +39 -0
  22. package/gemini/agents/arc-scouter.md +38 -0
  23. package/gemini/instructions.md +4 -0
  24. package/gemini/skill/SKILL.md +78 -0
  25. package/gemini/skill/models.toml +23 -0
  26. package/gemini/skill/references/arc-visual-companion.md +28 -0
  27. package/gemini/skill/references/commit.md +55 -0
  28. package/gemini/skill/references/coordination.md +149 -0
  29. package/gemini/skill/references/git-recovery.md +34 -0
  30. package/gemini/skill/references/handoff-prep.md +110 -0
  31. package/gemini/skill/references/handoff.md +227 -0
  32. package/gemini/skill/references/limits.md +31 -0
  33. package/gemini/skill/references/planning.md +168 -0
  34. package/gemini/skill/references/verification.md +155 -0
  35. package/gemini/skill/references/worktree-creation.md +8 -0
  36. package/lib/color/palette.mjs +6 -0
  37. package/lib/installer/acquisition.mjs +7 -5
  38. package/lib/installer/install-mode.mjs +49 -26
  39. package/lib/installer/install.mjs +3 -2
  40. package/lib/installer/manifest.mjs +20 -14
  41. package/lib/installer/plan.mjs +24 -21
  42. package/lib/installer/preset.mjs +9 -8
  43. package/lib/installer/role-routing.mjs +129 -77
  44. package/lib/installer/runtime-assets.mjs +2 -0
  45. package/lib/installer/runtime-config.mjs +3 -0
  46. package/lib/installer/skill-sources.mjs +4 -3
  47. package/lib/installer/superpowers.mjs +2 -1
  48. package/lib/installer/target-errors.mjs +1 -0
  49. package/lib/installer/targets.mjs +14 -6
  50. package/lib/installer/uninstall.mjs +5 -4
  51. package/lib/installer/upgrade-state.mjs +14 -10
  52. package/lib/installer/upgrade.mjs +9 -5
  53. package/lib/management/operations.mjs +91 -47
  54. package/lib/management/status.mjs +10 -8
  55. package/lib/management/update.mjs +8 -7
  56. package/lib/models/catalog-gemini.mjs +48 -0
  57. package/lib/models/catalog.mjs +27 -12
  58. package/lib/models/config.mjs +23 -22
  59. package/lib/models/gemini-models.json +12 -0
  60. package/lib/models/profiles.mjs +7 -5
  61. package/lib/models/static-catalog.mjs +13 -14
  62. package/lib/npm/upgrade.mjs +2 -2
  63. package/lib/platforms/availability.mjs +98 -0
  64. package/lib/platforms/claude.mjs +14 -0
  65. package/lib/platforms/codex.mjs +16 -0
  66. package/lib/platforms/formats/gemini-markdown.mjs +48 -0
  67. package/lib/platforms/formats/markdown.mjs +39 -0
  68. package/lib/platforms/formats/toml.mjs +39 -0
  69. package/lib/platforms/gemini.mjs +14 -0
  70. package/lib/platforms/index.mjs +27 -0
  71. package/lib/policy/placement.mjs +4 -4
  72. package/lib/policy/render.mjs +13 -8
  73. package/lib/policy/role-policy.json +40 -21
  74. package/lib/prompts/agent-fragments.json +71 -1
  75. package/lib/prompts/render.mjs +32 -11
  76. package/lib/runtime/bootstrap.mjs +1 -1
  77. package/lib/runtime/cooperative-schema.mjs +0 -23
  78. package/lib/runtime/cooperative.mjs +13 -34
  79. package/lib/runtime/evaluate.mjs +3 -69
  80. package/lib/runtime/gemini-stream.mjs +32 -0
  81. package/lib/runtime/git-evidence.mjs +0 -98
  82. package/lib/runtime/identity.mjs +2 -1
  83. package/lib/runtime/local-cli.mjs +14 -24
  84. package/lib/runtime/operations.mjs +2 -2
  85. package/lib/runtime/platform-registry.mjs +130 -0
  86. package/lib/runtime/role-bridge-args.mjs +57 -2
  87. package/lib/runtime/role-bridge.mjs +86 -65
  88. package/lib/runtime/role-dispatch-policy.mjs +17 -7
  89. package/lib/runtime/role-dispatch-store.mjs +20 -14
  90. package/lib/runtime/role-observe.mjs +1 -0
  91. package/lib/runtime/role-routing-config.mjs +36 -9
  92. package/lib/runtime/role-routing.mjs +62 -29
  93. package/lib/runtime/role-supervisor.mjs +114 -49
  94. package/lib/runtime/schema.mjs +5 -4
  95. package/lib/tui/app.mjs +37 -32
  96. package/lib/tui/custom-preset.mjs +114 -68
  97. package/lib/tui/derive-install-plan.mjs +19 -0
  98. package/lib/tui/diagram.mjs +68 -0
  99. package/lib/tui/mode.mjs +77 -0
  100. package/lib/tui/render.mjs +47 -16
  101. package/lib/tui/setup.mjs +167 -100
  102. package/lib/tui/terminal.mjs +9 -6
  103. package/lib/watch/anchor-store.mjs +44 -0
  104. package/lib/watch/dispatch.mjs +3 -3
  105. package/lib/watch/index.mjs +37 -24
  106. package/lib/watch/model.mjs +1 -0
  107. package/lib/watch/normalize-claude.mjs +50 -10
  108. package/lib/watch/normalize-codex.mjs +79 -5
  109. package/lib/watch/render.mjs +30 -13
  110. package/lib/watch/scope.mjs +2 -1
  111. package/lib/watch/status-line.mjs +51 -0
  112. package/lib/watch/tail.mjs +27 -0
  113. package/lib/watch/watcher.mjs +193 -53
  114. package/package.json +2 -1
  115. package/scripts/update-manifest.mjs +2 -2
  116. package/shared/skill/runtime/bootstrap.mjs +1 -1
  117. package/shared/skill/runtime/cooperative-schema.mjs +0 -23
  118. package/shared/skill/runtime/cooperative.mjs +13 -34
  119. package/shared/skill/runtime/evaluate.mjs +3 -69
  120. package/shared/skill/runtime/gemini-stream.mjs +32 -0
  121. package/shared/skill/runtime/git-evidence.mjs +0 -98
  122. package/shared/skill/runtime/identity.mjs +2 -1
  123. package/shared/skill/runtime/local-cli.mjs +14 -24
  124. package/shared/skill/runtime/operations.mjs +2 -2
  125. package/shared/skill/runtime/platform-registry.mjs +130 -0
  126. package/shared/skill/runtime/role-bridge-args.mjs +57 -2
  127. package/shared/skill/runtime/role-bridge.mjs +86 -65
  128. package/shared/skill/runtime/role-dispatch-policy.mjs +17 -7
  129. package/shared/skill/runtime/role-dispatch-store.mjs +20 -14
  130. package/shared/skill/runtime/role-observe.mjs +1 -0
  131. package/shared/skill/runtime/role-policy.json +40 -21
  132. package/shared/skill/runtime/role-routing-config.mjs +36 -9
  133. package/shared/skill/runtime/role-routing.mjs +62 -29
  134. package/shared/skill/runtime/role-supervisor.mjs +114 -49
  135. package/shared/skill/runtime/schema.mjs +5 -4
@@ -0,0 +1,155 @@
1
+ <a id="verification-and-acceptance"></a>
2
+ # Verification and acceptance
3
+
4
+ Behavior work follows meaningful failing test observation → minimal implementation → focused success → project suite. Report skill/test constraints before edits. Waivers need recorded narrow/understood/reversible scope, no dependent/cross-component lifecycle stages and one check path. Docs exceptions permit named structural checks only, never TDD claims. Report side effects within scope. Reviewer lacks Bash and requests runtime checks. Local tests prove neither remote models nor effort application. Policy prose needs independent role/approval review; text presence proves no compliance. Unexpected failure triggers diagnosis/holds; expected RED grants no unrelated repairs.
5
+
6
+ Read before verification design, QA/Reviewer assignment, correction rechecks or UI acceptance. QA/Reviewer use their profiles and brief-cited sections only. Design companions differ from UI acceptance.
7
+
8
+ **Evidence verdict:** Criteria are proven, unmet or unverified. Passing runs/reports/dispositions never convert unverified to proven; retain gaps.
9
+
10
+ <a id="visual-evidence-and-adjudication"></a>
11
+ ## Visual evidence and adjudication
12
+
13
+ Each criterion needs the exact approved source, version, approval and access state; IDs, properties and comparison method; and a link between output and revision. Implementer reporting does not replace fresh QA. Record pass/mismatch/unverified and connect to criterion verdicts; pass needs accessible supporting evidence. Missing linkage is unverified; visible difference is mismatch, separately, without inferring current branch UI. Hold comparison when materials are inaccessible or interpretation approval is missing.
14
+
15
+ Policy, generated-file and manifest checks prove structure, not role behavior, installed builds, Gemini CLI compliance or fidelity. Report changes, exclusions, checks run and omitted, criterion evidence and limits, and platform availability. Report baseline failures separately; independent progress does not relax checks.
16
+
17
+ <a id="risk-scaled-execution"></a>
18
+ ## Risk-scaled execution
19
+
20
+ The [fast gate](handoff.md#orchestrator-direct-path-for-small-tasks) references this risk definition; refresh affected evidence when inputs change and preserve independent verification boundaries.
21
+
22
+ Edits belong to Implementer except the [small direct path](handoff.md#orchestrator-direct-path-for-small-tasks). Orchestrator determines behavior, risk and minimum meaningful checks.
23
+
24
+ | Risk | Minimum flow |
25
+ |---|---|
26
+ | Small, low risk | Implementer or direct edit → Orchestrator focused checks → acceptance |
27
+ | Ordinary behavior | Implementer → independent QA → acceptance |
28
+ | Significant/high risk, no plan | Implementer → QA/rechecks → final full-change Reviewer → acceptance |
29
+ | Significant/high risk, plan | Per task Implementer → required fresh QA → acceptance/commit; final independent whole-change Reviewer once after all accepted tasks/required checks/rechecks |
30
+
31
+ Ordinary/significant tasks need fresh QA before acceptance. Low risk requires narrow/understood/reversible/focused-verifiable work. Ordinary behavior fails these without significant triggers. Shared role/behavior contracts/state, lifecycle/integration order, security/permissions, data loss/migration, public interfaces and costly install/deploy/rollback are significant. Substantial behavior/contracts are significant regardless of file count. Unclear risk requires investigation/higher flow. Environment failure waives no check or depth judgment.
32
+
33
+ - Task boundaries alone add no QA/review. Reviewer is never a plan-task/commit prerequisite. Plans review once at final relevant state after task acceptances/checks; no-plan Reviewer follows QA before acceptance.
34
+ - Preserve specific commitments. Risky unverified dependencies need QA/resolved or explicitly dispositioned findings before implementation.
35
+ - Reuse evidence only for matching scope/state/independence/freshness/flow position. Changes/failures/missing-conflicting evidence invalidate affected reuse.
36
+ - QA independently checks without edits. Reviewer performs no QA/planning/editing/delegation/completion decisions. Orchestrator routes fixes to Implementer and required QA rechecks; direct-check failures return to normal flow. Accept after findings/gaps resolved or dispositioned.
37
+ - Fresh-per-task applies to Implementer/QA, not Reviewer. Reuse Reviewer only with independence, valid context and refreshed scope/target/evidence, never an old verdict or waived timing/coverage.
38
+
39
+ Record which risk/instruction/approved obligations each check satisfies. DO NOT automatically assign QA/Reviewer for clear low-risk scope with sufficient evidence and no requirement. Metadata counts alone prove no significance; one permission/loss rule may. Vague file deletion is not low-risk evidence; reclassify installer/manifest impacts. Confirm cleanup targets unused, required materials intact, ignore patterns scoped and diff approved before focused-check-only acceptance.
40
+
41
+ Distinguish environment failures from code failures and report exact limits and gaps. Use Planner/Scouter only for unresolved planning/discovery. Reviewer covers substantial correctness/factual/security/data/interface risks. Orchestrator assigns support as needed. Claim only verified outputs. Read cited `references/test-driven-development.md`, preserving exceptions.
42
+
43
+ <a id="final-plan-reviewer-correction-loop"></a>
44
+ ### Final plan Reviewer correction loop
45
+
46
+ Only final overall Reviewer findings on plan work, including behavior, follow Implementer → Reviewer without QA reassignment until resolved. One initial full review permits necessary rechecks. Before it, risk checks/QA failures/unmet criteria still need Implementer → QA. No-plan flow remains unchanged.
47
+
48
+ Expanded scope/separate obligations/gaps hold affected work for resolution/approval. Orchestrator assigns/accepts; Reviewer stays read-only without QA/acceptance. NEVER present old QA as post-fix execution. Report actual actor/target/check/result/limits only.
49
+
50
+ <a id="evidence-after-plan-revision-commit"></a>
51
+ ## Evidence after plan revision commit
52
+
53
+ Verify every committed document blob against its latest approved content hash and full approved copy. If no progress records have been committed since approval, the SHA-256 of the committed document content (not the Git blob OID) MUST equal the latest approved `contentHash`. Otherwise the diff from the latest approved copy MUST contain only classified progress records belonging to that commit's task or committed for other tasks after approval (including R-8 separation). Record the SHA-256 of the expected content used for this comparison in the canonical record; NEVER overwrite approved copies. Verify each pending revision's status is `committed` and no pending revision remains before overall completion. Link commit SHA in the canonical record only, not the document. Preserve actual approval chronology; later committed content proves no earlier approval.
54
+
55
+ Existing commit evidence links remain valid because history is unchanged. For a contract revision, affected checks and rechecks MUST be rerun against the revised version. Stale evidence from plan-file changes requires refresh under existing rules. Preserve exact-HEAD/document/policy/fingerprint requirements; NEVER rewrite old fingerprints to suggest execution at a new state. Refresh briefs/gates before dependencies. Structure proves no live compliance.
56
+
57
+ <a id="task-acceptance-and-final-plan-acceptance"></a>
58
+ <a id="reviewer-timing-and-task-acceptance"></a>
59
+ ## Task acceptance and final plan acceptance
60
+
61
+ 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).
62
+
63
+ 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.
64
+
65
+ 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.
66
+
67
+ Orchestrator writes approved-base final base..HEAD diff/changed-file list to `<git-common-dir>/arc/review/<slug>.diff`, using handoff slug and absolute brief citation; inline if small/write denied. Reviewer reads artifact, not Git commands, stating limits.
68
+
69
+ <a id="ui-browser-acceptance-checks"></a>
70
+ ### UI browser acceptance checks
71
+
72
+ QA has no browser tool: launch/exercise apps/URLs through Bash only with assigned criteria/cited prerequisites, following installed browser-skill CLI guidance.
73
+
74
+ 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.
75
+
76
+ 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.
77
+
78
+ <a id="criterion-evidence-and-finding-handoff"></a>
79
+ ### Criterion evidence and finding handoff
80
+
81
+ Report every criterion by ID or wording: method/scope, run status, evidence, verdict, unverified reason/remaining scope. Run status: passed/failed/not run/environment blocked. Verdict: proven/unmet/unverified. Connect conditions/expectations to actual observations; partial/out-of-scope/missing/environment gaps stay unverified. PASS means run status only. Structure proves structure only.
82
+
83
+ Current-task failures/unmet criteria default to current Implementer/current QA under coordination context/boundary/amendment rules; findings alone create no task. Before Reviewer, rerun reproduction/invalidated checks, reporting actor/target/results/limits and prior finding resolved/unresolved/unverified with evidence. Repeat Implementer→QA if unresolved; QA reuse is no stale-evidence reuse. Environment/missing/out-of-scope are gaps, not presumed code defects; Reviewer cannot replace QA.
84
+
85
+ Reviewer behavior findings report criterion/expectation/problem/source/reproduction/evidence, separating source inference/execution. No QA execution. Outside final-plan exception route Implementer→QA; other Reviewer rechecks depend on scope/independence. Continue source review of structure/design/facts/security; observable security/interfaces may need both QA/Reviewer.
86
+
87
+ Accept from criterion verdicts/findings/rechecks/gaps, not overall run status. Disposition never proves unverified. Low-risk work also links each criterion to focused evidence.
88
+
89
+ <a id="completion-continuity"></a>
90
+ ## Completion continuity
91
+
92
+ Once approval/depth/target/handoff hold, continue execution/correction/reverification/required QA-Reviewer/disposition/acceptance/report. Preserve timing without new task-level gates. Reports/probes/commands never complete remaining approved scope. DO NOT make authorized execution an optional offer awaiting response. Probe-only ends at question/evidence/limits; combined work follows planning. Omission changes neither risk nor acceptance. Hold only actual affected conditions and report resume requirements. Structure proves no live compliance.
93
+
94
+ <a id="verification-lifecycle-in-the-cooperative-cli"></a>
95
+ ## Verification lifecycle in the cooperative CLI
96
+
97
+ Supported `workflow` is approved complete spec+plan. No-plan/small-task/omission is `cooperative.unsupported`, not policy violation/new documents. CLI executes no checks/Reviewer. Actors/results/verdicts are `operator-attested`, not identity/independence/semantic/enforcement proof.
98
+
99
+ 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.
100
+ 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.
101
+ 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.
102
+ 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.
103
+
104
+ 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.
105
+
106
+ 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.
107
+
108
+ Scope/document/approval records preserve history. `data.affectedTaskIds` invalidates those tasks/dependents and task/check/acceptance evidence; omitted IDs hold all. Final evidence becomes stale. Preserve unaffected independent evidence. Orchestrator determines semantic impact. Affected tasks need new current-scope approval/contracts before preparation, not revived old approvals; fresh checks/reviews/revalidation too. Current evidence supersedes failures without deletion. Acceptance/commit/completion stay Orchestrator decisions.
109
+
110
+ <a id="task-acceptance-and-focused-commit-reconciliation-in-the-cooperative-cli"></a>
111
+ ### Task acceptance and focused commit reconciliation in the cooperative CLI
112
+
113
+ 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.
114
+
115
+ 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.
116
+
117
+ Commit preparation references `arguments: {"acceptanceId": "acceptance requestId"}`. Check current approval/contract/QA/findings/index match acceptance and persist expected parent/tree/paths/residual paths. CLI stages/commits nothing. Orchestrator makes one matching focused commit.
118
+
119
+ Submit intentId/`actor.role: "orchestrator"` and `result: {"status": "succeeded", "messageRef": "actual result evidence", "data": {"commit": "full OID"}}` through reconcile/result. CLI rereads local object/parent/tree/paths/HEAD/index/residual changes. Only complete match updates target HEAD/committed. Preserve failed/unknown/mismatch/history; never arbitrary target updates. Same request/completed intent permits no repeated effect. Inspect/resolve/reconcile existing intent after failure.
120
+
121
+ NEVER rewrite QA fingerprints after commit. Separate post-commit observations detect changes. Final review needs current task evidence/final fingerprint. RuntimeHash drift keeps existing stale/hold without automatic version update.
122
+
123
+ [ARC role policy: contract begin]
124
+ Generated from lib/policy/role-policy.json; do not edit this managed section manually.
125
+ - [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; pending approved spec/plan revisions follow planning.plan-revision 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.
126
+ - [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.
127
+ - [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.
128
+ - [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.
129
+ - [planning.plan-revision] Task progress records (checkboxes, notes, results, evidence and status) preserving the approved contract need no new user approval; Orchestrator includes the completed task's own records in its accepted implementation commit and records classification, reason and actual time as applicable. All other spec/plan content changes, contract or mechanical, require applicable approval and preparation; changes to goals, scope, criteria, method, risk, dependencies or required verification need revised-version approval, preparation and holds on affected work before it continues, with a fresh Implementer for remaining work. After approval Orchestrator edits the same document, appends a revision-history row and leaves it uncommitted as an Orchestrator-owned pending revision, recording version, content hash, approval reference, actual time, classification, reason, affected tasks and the full approved content in the canonical handoff record. Orchestrator includes all pending revisions with Plan-Revision, Plan-Approved-At and Plan-Reason trailers in the accepted commit of the first top-level task executed or reconfirmed against the revised version, otherwise in a current task or final Reviewer follow-up commit; only when no implementation work remains before overall completion MAY it make one standalone docs(plan) closing commit without implementation files. Exclude revision hunks from commits of independent tasks accepted on a prior version, or hold that commit when separation is unsafe. NEVER amend or rewrite planning or implementation commits, create any other docs/fixup commit or authorize past work retroactively. After commit verify the committed document content matches the latest approved content apart from classified progress records of that commit's task or committed for other tasks after approval, and that no pending revision remains. Follow planning, handoff-prep, commit and verification for the full contract.
130
+ - [platform.gemini] Role restrictions are prompt-level contracts, not a filesystem sandbox. Native tool restriction fields, observer hooks and Git guards are unverified. Use only available authorized tools; ARC does not write Gemini settings.json.
131
+ [ARC role policy: contract end]
132
+
133
+ <a id="external-operations-and-recovery-in-the-cooperative-cli"></a>
134
+ ## External operations and recovery in the cooperative CLI
135
+
136
+ Three phases cover state/documents/assignment; scope/verification/acceptance/focused commits; external approval/results/audit recovery. Inspect nine areas/limits with `status.support`. Support is spec+plan `plan`, not no-plan/omission. CLI executes no native/provider/push/merge/deploy/publish calls.
137
+
138
+ Operator-confirmed approvals/results are `operator-attested`, `nativeVerified: false`, `remoteVerified: false`; no outside-call blocking or independent remote verification.
139
+
140
+ Record already confirmed external approval using `evidence: {kind: "external-approval", messageRef, data: {operation, scope, descriptor}}`. `scope` is unique absolute checkout paths. Local commit approval grants no external approval. Record exact action/scope/target and all descriptor fields:
141
+
142
+ | operation | descriptor fields |
143
+ |---|---|
144
+ | push | repository, destination, refspec, sourceOid, expectedRemoteOid |
145
+ | merge | repository, changeRef, targetRef, expectedTargetOid |
146
+ | deploy | service, project, environment, artifactId, destination |
147
+ | publish | service, namespace, name, version, artifactHash, destination |
148
+
149
+ Git OIDs are full lowercase 40/64-character hex; artifactHash is `sha256:<64-hex>`. Without remote observation OIDs are asserted expectations, not verified state. Destination is secret-free. No URL userinfo/query/fragment/password/token/credentials. Recognized secrets are rejected before persistence, but arbitrary-string secrecy cannot be guaranteed.
150
+
151
+ `prepare` accepts `{requestId, expectedRevision, actor: {id, role: "orchestrator"}, operation, arguments: {approvalRef, scope, descriptor}}`; approvalRef matches external approval messageRef. Persist only exact approval/scope/target/runtime versions with no unresolved effects. After `allow`/`persisted: true`, Orchestrator executes separately approved scope; CLI expands no authority.
152
+
153
+ `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.
154
+
155
+ 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.
@@ -0,0 +1,8 @@
1
+ <a id="gemini-managed-worktree-creation"></a>
2
+ # Gemini managed worktree creation
3
+
4
+ Follow the common [managed worktree contract](handoff-worktree.md) only after explicit user selection and verified preparation scope. Preserve the approved source/base, branch candidate, absent destination, unrelated changes and transfer evidence.
5
+
6
+ Gemini native attachment has not been verified. Do not substitute Claude EnterWorktree, invent an attachment call or treat Git registration as attachment evidence. Hold managed worktree creation until Orchestrator has an approved, verified attachment method. The current checkout remains available only after explicit target selection.
7
+
8
+ On failure or partial completion, stop dependent work, preserve actual state and return paths, branch/HEAD, registration, completed steps and required resolution. Never retry with a different name, remove a worktree, change permissions or bypass the sandbox.
@@ -0,0 +1,6 @@
1
+ const STOPS=[[178,245,214],[110,231,183],[52,211,153],[16,185,129]];
2
+ const mix=(from,to,t)=>from.map((value,index)=>Math.round(value+(to[index]-value)*t));
3
+ export function gradientAt(t){const position=Math.max(0,Math.min(1,Number(t)||0))*3,segment=Math.min(2,Math.floor(position));return mix(STOPS[segment],STOPS[segment+1],position-segment);}
4
+ export function shimmerIntensity(column,row,frame){const f=frame%36;if(f>=18)return 0;const c=-4+f*33.5/17,p=column+0.5*row;return Math.max(0,1-Math.abs(p-c)/3)**2;}
5
+ const rgb=color=>[0,1,2].map(index=>Math.max(0,Math.min(255,Math.round(Number(color[index])||0))));
6
+ export function toAnsi256(color){const [r,g,b]=rgb(color);return 16+36*Math.round(r/51)+6*Math.round(g/51)+Math.round(b/51);}
@@ -1,4 +1,5 @@
1
1
  import path from 'node:path';
2
+ import {installerRegistryOf} from '../platforms/index.mjs';
2
3
  import {spawn as nodeSpawn} from 'node:child_process';
3
4
  import {readCheckedFile,sameIdentity,typeOf} from './targets.mjs';
4
5
 
@@ -10,9 +11,10 @@ export class AcquisitionError extends Error{
10
11
  }
11
12
  const failure=message=>{throw new AcquisitionError(message);};
12
13
  function decode(bytes,stream){try{return new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes);}catch{failure(`Upstream Git returned non-UTF-8 ${stream}`);}}
13
- function environment(work){
14
+ function isolationEnvironment(work,platforms){return Object.assign({},...installerRegistryOf({platforms}).byAnchorOrder().map(descriptor=>descriptor.isolationEnv(work)));}
15
+ function environment(work,platforms){
14
16
  const result={};for(const key of ['PATH','LANG','LC_ALL'])if(process.env[key]!==undefined)result[key]=process.env[key];
15
- Object.assign(result,{CI:'1',DO_NOT_TRACK:'1',HOME:path.join(work,'home'),XDG_CONFIG_HOME:path.join(work,'config'),CODEX_HOME:path.join(work,'codex-runtime'),TMPDIR:path.join(work,'tmp'),XDG_STATE_HOME:path.join(work,'state'),npm_config_cache:path.join(work,'npm-cache'),npm_config_userconfig:path.join(work,'npm-userconfig'),npm_config_globalconfig:path.join(work,'npm-globalconfig'),npm_config_audit:'false',npm_config_fund:'false',npm_config_update_notifier:'false',GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:path.join(work,'gitconfig'),GIT_TERMINAL_PROMPT:'0',GIT_CONFIG_COUNT:'3',GIT_CONFIG_KEY_0:'core.hooksPath',GIT_CONFIG_VALUE_0:'/dev/null',GIT_CONFIG_KEY_1:'protocol.file.allow',GIT_CONFIG_VALUE_1:'never',GIT_CONFIG_KEY_2:'submodule.recurse',GIT_CONFIG_VALUE_2:'false'});
17
+ Object.assign(result,{CI:'1',DO_NOT_TRACK:'1',HOME:path.join(work,'home'),XDG_CONFIG_HOME:path.join(work,'config'),...isolationEnvironment(work,platforms),TMPDIR:path.join(work,'tmp'),XDG_STATE_HOME:path.join(work,'state'),npm_config_cache:path.join(work,'npm-cache'),npm_config_userconfig:path.join(work,'npm-userconfig'),npm_config_globalconfig:path.join(work,'npm-globalconfig'),npm_config_audit:'false',npm_config_fund:'false',npm_config_update_notifier:'false',GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:path.join(work,'gitconfig'),GIT_TERMINAL_PROMPT:'0',GIT_CONFIG_COUNT:'3',GIT_CONFIG_KEY_0:'core.hooksPath',GIT_CONFIG_VALUE_0:'/dev/null',GIT_CONFIG_KEY_1:'protocol.file.allow',GIT_CONFIG_VALUE_1:'never',GIT_CONFIG_KEY_2:'submodule.recurse',GIT_CONFIG_VALUE_2:'false'});
16
18
  return result;
17
19
  }
18
20
  function clearHeldDirectory(directory){
@@ -34,17 +36,17 @@ async function terminateGroup(child,completed,clock){
34
36
  try{await Promise.race([completed,grace]);if(groupExists(pid))await grace;if(groupExists(pid))signalGroup(pid,'SIGKILL');await groupGone(pid,clock);await completed;}
35
37
  finally{clock.clearTimeout(timer);}
36
38
  }
37
- export async function acquireExternalSkills({work,safeFs,spawn=nodeSpawn,signal,clock=defaultClock}){
39
+ export async function acquireExternalSkills({work,safeFs,spawn=nodeSpawn,signal,clock=defaultClock,platforms}){
38
40
  let root,owned=false,transferred=false,child,completed,timer,onAbort,termination;try{
39
41
  if(typeof work!=='string'||!path.isAbsolute(work)||path.normalize(work)!==work)failure('Acquisition work must be an absolute normalized directory');
40
42
  root=safeFs.openRoot(work);const identity=root.stat();if(root.readDir().length)failure('Acquisition work directory must be empty');owned=true;
41
43
  if(signal?.aborted)throw new AcquisitionError('External skill acquisition cancelled',{code:'ARC_ACQUISITION_CANCELLED'});
42
- for(const name of ['home','config','codex-runtime','npm-cache','state','tmp'])root.mkdir(name,0o700);
44
+ for(const name of ['home','config',...Object.values(isolationEnvironment(work,platforms)).map(directory=>path.relative(work,directory)),'npm-cache','state','tmp'])root.mkdir(name,0o700);
43
45
  for(const name of ['npm-userconfig','npm-globalconfig','gitconfig']){const file=root.openFile(name,{createExclusive:true,mode:0o600});file.close();}
44
46
  async function run(args){
45
47
  termination=undefined;
46
48
  const stdout=[],stderr=[];let startError;
47
- child=spawn('git',args,{cwd:work,env:environment(work),stdio:['ignore','pipe','pipe'],detached:true,shell:false});
49
+ child=spawn('git',args,{cwd:work,env:environment(work,platforms),stdio:['ignore','pipe','pipe'],detached:true,shell:false});
48
50
  completed=new Promise(resolve=>{child.stdout.on('data',bytes=>stdout.push(Buffer.from(bytes)));child.stderr.on('data',bytes=>stderr.push(Buffer.from(bytes)));child.once('error',error=>{startError=error;});child.once('close',(code,killedBy)=>resolve({code,killedBy}));});
49
51
  const interrupted=new Promise((resolve,reject)=>{timer=clock.setTimeout(()=>reject(new AcquisitionError('External skill acquisition timed out after 300 seconds',{code:'ARC_ACQUISITION_TIMEOUT'})),300000);onAbort=()=>reject(new AcquisitionError('External skill acquisition cancelled',{code:'ARC_ACQUISITION_CANCELLED'}));signal?.addEventListener('abort',onAbort,{once:true});if(signal?.aborted)onAbort();});
50
52
  const result=await Promise.race([completed,interrupted]);clock.clearTimeout(timer);termination=terminateGroup(child,completed,clock);await termination;
@@ -1,34 +1,57 @@
1
+ import {installerRegistryOf} from '../platforms/index.mjs';
2
+ import {createPlatformRegistry,standaloneProfileFile} from '../runtime/platform-registry.mjs';
1
3
  import path from 'node:path';
2
4
  import {inspectPath,TargetConfigurationError} from './targets.mjs';
3
- import {inspectCompositeRemoval} from './role-routing.mjs';
4
- import {parseRoleRoutingConfig} from '../runtime/role-routing-config.mjs';
5
- export function isOwnedStandaloneProfile(bytes,platform,role){
6
- if(!/^arc_(scouter|planner|implementer|qa|reviewer)$/.test(role))return false;
7
- const text=bytes.toString('utf8'),suffix=role.slice(4);
8
- if(!/^\[ARC role policy: contract begin\]\r?$/m.test(text))return false;
9
- if(platform==='claude'){
10
- const front=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);if(!front)return false;
11
- const names=front[1].match(/^name: .*\r?$/gm)??[];return names.length===1&&new RegExp(`^name: arc-${suffix}\\r?$`).test(names[0]);
12
- }
13
- if(platform!=='codex')return false;
14
- const names=text.match(/^name[ \t]*=.*\r?$/gm)??[];
15
- return names.length===1&&new RegExp(`^name[ \\t]*=[ \\t]*"arc_${suffix}"[ \\t]*(#.*)?\\r?$`).test(names[0]);
5
+ import {inspectCompositeRemoval,parseInstalledRoutingConfig,legacyAnchorPlatform} from './role-routing.mjs';
6
+ export function isOwnedStandaloneProfile(bytes,platform,role,context={}){
7
+ return installerRegistryOf(context).getPlatform(platform)?.profiles.isOwnedStandalone(bytes,role)??false;
16
8
  }
17
- export function inspectStandaloneProfile({safeFs,target,role,snapshot=new Map()}){
18
- const filename=path.join(target.home,'agents',`${role.replace('_','-')}.${target.platform==='codex'?'toml':'md'}`),file=inspectPath(safeFs,filename,{kind:'file',read:true,allowLeafLink:true,snapshot});
19
- return{path:filename,exists:file.exists,owned:file.exists&&snapshot.get(filename)?.type==='file'&&isOwnedStandaloneProfile(file.bytes,target.platform,role)};
9
+ export function inspectStandaloneProfile({safeFs,target,role,snapshot=new Map(),platforms}){
10
+ const descriptor=installerRegistryOf({platforms}).getPlatform(target.platform);
11
+ const filename=path.join(target.home,'agents',standaloneProfileFile(descriptor.runtime,role)),file=inspectPath(safeFs,filename,{kind:'file',read:true,allowLeafLink:true,snapshot});
12
+ return{path:filename,exists:file.exists,owned:file.exists&&snapshot.get(filename)?.type==='file'&&isOwnedStandaloneProfile(file.bytes,target.platform,role,{platforms})};
20
13
  }
21
- export function readInstallMode({safeFs,targets,snapshot=new Map()}){
22
- const active=path.join(targets.codex.home,'arc-role-platform-routing.json'),homes={},residualPaths=[];
23
- for(const platform of ['codex','claude']){
24
- const result=inspectCompositeRemoval({target:targets[platform],safeFs,activeConfigPath:active,snapshot});
25
- homes[platform]=result.residualPaths.length?'unverified':result.removals.length?'composite':'standalone';residualPaths.push(...result.residualPaths);
14
+ export function readInstallMode({safeFs,targets,unresolved=[],snapshot=new Map(),platforms}){
15
+ const registry=installerRegistryOf({platforms}),runtimePlatforms=createPlatformRegistry(registry.byAnchorOrder().map(descriptor=>descriptor.runtime));
16
+ const homes={},candidates=[],routing=new Map(),unresolvedIds=new Set(unresolved.map(item=>typeof item==='string'?item:item.platform));
17
+ for(const id of registry.platformIds()){
18
+ const target=targets[id];if(unresolvedIds.has(id)||!target){homes[id]='unresolved';continue;}
19
+ const active=path.join(target.home,'arc-role-platform-routing.json'),file=inspectPath(safeFs,active,{kind:'file',read:true,snapshot});
20
+ if(file.exists)candidates.push({id,path:active,bytes:file.bytes});
21
+ const marker=path.join(target.home,'arc-role-platform-routing.prepared.json'),found=inspectPath(safeFs,marker,{kind:'file',read:true,snapshot});
22
+ const paths=found.exists?[marker]:[],agents=path.join(target.home,'agents');
23
+ inspectPath(safeFs,agents,{kind:'directory',tree:true,allowLinks:true,snapshot});
24
+ for(const [filename,value]of snapshot)if(value&&path.dirname(filename)===agents&&path.basename(filename).startsWith('arc-routing-'))paths.push(filename);
25
+ routing.set(id,paths);homes[id]='standalone';
26
+ }
27
+ let config=null,participating=[],anchor=null;
28
+ const finish=(mode,residualPaths=[])=>({mode,platforms:participating,anchor,homes,config,residualPaths:[...new Set(residualPaths)]});
29
+ const unverified=()=>{
30
+ for(const id of Object.keys(homes))if(homes[id]!=='unresolved'&&(routing.get(id)?.length||candidates.some(candidate=>candidate.id===id)||participating.includes(id)))homes[id]='unverified';
31
+ return finish('unverified',[...candidates.map(candidate=>candidate.path),...[...routing.values()].flat()]);
32
+ };
33
+ if(!candidates.length)return[...routing.values()].some(paths=>paths.length)?unverified():finish('standalone');
34
+ if(candidates.length!==1)return unverified();
35
+ const active=candidates[0];
36
+ try{config=parseInstalledRoutingConfig(active.bytes.toString('utf8'),{runtimePlatforms});}catch{return unverified();}
37
+ participating=config.platforms;anchor=participating[0];
38
+ if(participating.some(id=>homes[id]==='unresolved'||!targets[id]))return unverified();
39
+ const legacyAnchor=targets[anchor].home!==path.dirname(active.path)&&active.id===legacyAnchorPlatform&&JSON.parse(active.bytes.toString('utf8')).version===1;
40
+ if(targets[anchor].home!==path.dirname(active.path)&&!legacyAnchor)return unverified();
41
+ if(legacyAnchor)anchor=active.id;
42
+ for(let i=0;i<participating.length;i++)for(let j=0;j<i;j++){
43
+ const a=targets[participating[i]].home,b=targets[participating[j]].home;
44
+ if(a===b||a.startsWith(b+path.sep)||b.startsWith(a+path.sep))return unverified();
45
+ }
46
+ for(const [id,paths]of routing)if(!participating.includes(id)&&paths.length)return unverified();
47
+ for(const id of participating){
48
+ const target=targets[id],result=inspectCompositeRemoval({target,safeFs,activeConfigPath:active.path,anchor:target.home===path.dirname(active.path),snapshot,runtimePlatforms});
49
+ if(result.residualPaths.length||!result.removals.length)return unverified();
50
+ if(routing.get(id).some(filename=>!result.removals.includes(filename)))return unverified();
26
51
  }
27
- const mode=homes.codex===homes.claude?homes.codex:'unverified';
28
- if(mode==='unverified')for(const [filename,value]of snapshot)if(value&&(/arc-role-platform-routing|arc-routing-/.test(filename)))residualPaths.push(filename);
29
- let config=null;if(mode==='composite')config=parseRoleRoutingConfig(inspectPath(safeFs,active,{kind:'file',read:true,snapshot}).bytes.toString('utf8'));
30
- return{mode,homes,config,residualPaths:[...new Set(residualPaths)]};
52
+ for(const id of participating)homes[id]='composite';
53
+ return {...finish('composite'),...(legacyAnchor?{legacyAnchor:true}:{})};
31
54
  }
32
55
  export function assertVerifiedInstallMode(options){
33
- const state=readInstallMode(options);if(state.mode==='unverified'){const error=new TargetConfigurationError('Claude & Codex configuration cannot be verified.');error.residualPaths=state.residualPaths;throw error;}return state;
56
+ const state=readInstallMode(options);if(state.mode==='unverified'){const error=new TargetConfigurationError('Mixed routing configuration cannot be verified.');error.residualPaths=state.residualPaths;throw error;}return state;
34
57
  }
@@ -1,8 +1,9 @@
1
1
  import {validatePlanSet} from './plan.mjs';
2
+ import {installerRegistryOf} from '../platforms/index.mjs';
2
3
  import {assertPlanSnapshot,applyTransaction} from './transaction.mjs';
3
4
  function pending(plan){return{platform:plan.target.platform,status:'not-started',rollback:'not-needed',residualPaths:[],error:null};}
4
- export async function installTargets(plans,{safeFs,signal,hooks={}}){
5
- const ordered=[...plans].sort((a,b)=>(a.target.platform==='codex'?0:1)-(b.target.platform==='codex'?0:1));const results=ordered.map(pending);let interrupted=false;
5
+ export async function installTargets(plans,{safeFs,signal,hooks={},platforms}){
6
+ const registry=installerRegistryOf({platforms}),ordered=[...plans].sort((a,b)=>registry.getPlatform(a.target.platform).runtime.anchorOrder-registry.getPlatform(b.target.platform).runtime.anchorOrder);const results=ordered.map(pending);let interrupted=false;
6
7
  let invalid=false;
7
8
  for(let index=0;index<ordered.length;index++){
8
9
  try{validatePlanSet([ordered[index]]);assertPlanSnapshot(ordered[index],{safeFs});}catch(error){results[index]={...results[index],status:'failed',error};invalid=true;}
@@ -1,4 +1,6 @@
1
1
  import {validateAgentTemplates} from '../prompts/render.mjs';
2
+ import {createInstallerRegistry,installerRegistryOf} from '../platforms/index.mjs';
3
+ import {createPlatformRegistry,standaloneProfileFile} from '../runtime/platform-registry.mjs';
2
4
  import {COOPERATIVE_RUNTIME_MODULES} from '../runtime/bootstrap.mjs';
3
5
  import {RUNTIME_MODULE_PATHS} from './runtime-assets.mjs';
4
6
  import {composeSkillSources} from './skill-sources.mjs';
@@ -6,13 +8,12 @@ import {POLICY_TARGETS,buildPolicyOutputs} from '../policy/render.mjs';
6
8
  import {validateFlatReferenceFiles} from './superpowers.mjs';
7
9
  import path from 'node:path';import crypto from 'node:crypto';import{loadModelConfig,resolveModelSettings,renderProfiles}from '../models/index.mjs';import{readCheckedFile,typeOf,sameIdentity,metadataOf}from './targets.mjs';
8
10
  export class PayloadValidationError extends Error{constructor(message,options){super(message,options);this.name='PayloadValidationError';this.code='ARC_PAYLOAD_VALIDATION';}}
9
- const MUTABLE=new Set(['codex/skill/models.toml','claude/skill/models.toml']);
10
11
  export const LOCAL_UPDATER_PATH='scripts/update-superpowers-local.sh';
11
- const ROOTS=['bin','lib','scripts','vendor','prebuilds','shared/skill','codex/skill','codex/agents','claude/skill','claude/agents'];
12
+ function payloadLayout(registry){const prefixes=registry.byAnchorOrder().map(descriptor=>descriptor.payloadPrefix);return{MUTABLE:new Set(prefixes.map(prefix=>`${prefix}/skill/models.toml`)),ROOTS:['bin','lib','scripts','vendor','prebuilds','shared/skill',...prefixes.flatMap(prefix=>[`${prefix}/skill`,`${prefix}/agents`])],TEMPLATES:registry.byAnchorOrder().flatMap(descriptor=>(descriptor.instructionTemplates??[]).map(name=>`${descriptor.payloadPrefix}/${name}`))};}
12
13
  const FIXED=['README.md','install.command','package.json','native/binding.c','native/binding.gyp'];
13
14
  function safeName(name){return typeof name==='string'&&name.length>0&&!name.includes('\\')&&!name.includes('\0')&&!name.startsWith('/')&&name.split('/').every(p=>p&&p!=='.'&&p!=='..')&&path.posix.normalize(name)===name;}
14
- function allowed(name){return FIXED.includes(name)||ROOTS.some(root=>name.startsWith(root+'/'));}
15
- export function renderManifest(files){return Buffer.from([...files].filter(([name])=>!MUTABLE.has(name)&&name!==LOCAL_UPDATER_PATH&&!name.split('/').includes('.DS_Store')).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([name,bytes])=>{if(!safeName(name)||!allowed(name)||!Buffer.isBuffer(bytes))throw Error('Invalid protected manifest file');return crypto.createHash('sha256').update(bytes).digest('hex')+' '+name+'\n';}).join(''));}
15
+ function allowed(name,roots,templates=[]){return FIXED.includes(name)||templates.includes(name)||roots.some(root=>name.startsWith(root+'/'));}
16
+ export function renderManifest(files,context={}){const{MUTABLE,ROOTS,TEMPLATES}=payloadLayout(installerRegistryOf(context));return Buffer.from([...files].filter(([name])=>!MUTABLE.has(name)&&name!==LOCAL_UPDATER_PATH&&!name.split('/').includes('.DS_Store')).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([name,bytes])=>{if(!safeName(name)||!allowed(name,ROOTS,TEMPLATES)||!Buffer.isBuffer(bytes))throw Error('Invalid protected manifest file');return crypto.createHash('sha256').update(bytes).digest('hex')+' '+name+'\n';}).join(''));}
16
17
  const LIFECYCLE_HOOKS=['preinstall','install','postinstall','prepublish','prepare','prepublishOnly','prepack','postpack','publish','postpublish','preuninstall','uninstall','postuninstall'];
17
18
  function sourcePayload(root,mode){
18
19
  if(!['auto','source','package'].includes(mode))throw Error('Invalid payload mode');if(mode==='package')return false;
@@ -24,10 +25,11 @@ function sourcePayload(root,mode){
24
25
  let pkg,lock;try{pkg=JSON.parse(readCheckedFile(root,'package.json').bytes);lock=JSON.parse(readCheckedFile(root,'package-lock.json').bytes);}catch{throw Error('Source package identity or lock is invalid');}
25
26
  const recorded=lock?.packages?.[''];if(pkg?.name!=='@yunhozz/arc'||!/^\d+\.\d+\.\d+$/.test(pkg.version)||lock.name!==pkg.name||lock.version!==pkg.version||recorded?.name!==pkg.name||recorded?.version!==pkg.version||LIFECYCLE_HOOKS.some(name=>Object.hasOwn(pkg.scripts??{},name))||Object.hasOwn(pkg.scripts??{},'build')||Object.hasOwn(pkg,'workspaces')||Object.hasOwn(recorded,'hasInstallScript'))throw Error('Source package identity or lifecycle contract is invalid');return true;
26
27
  }
27
- export function verifyPayload({packageRoot,safeFs,payloadMode='auto'}){
28
+ export function verifyPayload({packageRoot,safeFs,payloadMode='auto',platforms,runtimePlatforms}){
29
+ const registry=installerRegistryOf({platforms}),descriptors=registry.byAnchorOrder().filter(descriptor=>descriptor.runtime.capabilities.install.state==='verified'),{MUTABLE,ROOTS,TEMPLATES}=payloadLayout(registry);
28
30
  let root;try{
29
31
  root=safeFs.openRoot(packageRoot);const source=sourcePayload(root,payloadMode),manifest=readCheckedFile(root,'MANIFEST.sha256').bytes;let text;try{text=new TextDecoder('utf-8',{fatal:true}).decode(manifest);}catch{throw Error('Manifest is not UTF-8');}
30
- const listed=new Map();for(const line of text.split(/\r?\n/)){if(!line)continue;const m=/^([a-fA-F0-9]{64}) (.+)$/.exec(line);if(!m||!safeName(m[2]))throw Error('Malformed or escaping manifest path');const name=m[2];if(MUTABLE.has(name)||name===LOCAL_UPDATER_PATH||!allowed(name)||name.split('/').includes('.DS_Store')||listed.has(name))throw Error(`Duplicate, mutable or unexpected manifest entry: ${name}`);listed.set(name,m[1].toLowerCase());}
32
+ const listed=new Map();for(const line of text.split(/\r?\n/)){if(!line)continue;const m=/^([a-fA-F0-9]{64}) (.+)$/.exec(line);if(!m||!safeName(m[2]))throw Error('Malformed or escaping manifest path');const name=m[2];if(MUTABLE.has(name)||name===LOCAL_UPDATER_PATH||!allowed(name,ROOTS,TEMPLATES)||name.split('/').includes('.DS_Store')||listed.has(name))throw Error(`Duplicate, mutable or unexpected manifest entry: ${name}`);listed.set(name,m[1].toLowerCase());}
31
33
  const files=new Map(),snapshot=new Map();
32
34
  function walk(directory,prefix){const before=directory.stat();for(const name of directory.readDir()){
33
35
  const relative=prefix?prefix+'/'+name:name;const stat=directory.lstat(name),type=typeOf(stat);
@@ -38,8 +40,8 @@ export function verifyPayload({packageRoot,safeFs,payloadMode='auto'}){
38
40
  else throw Error(`Unsafe payload type: ${relative}`);
39
41
  }if(!sameIdentity(before,directory.stat()))throw Error('Payload directory changed while reading');}
40
42
  function select(relative,isTree){const parts=relative.split('/');let parent=root;const opened=[];try{for(const component of parts.slice(0,-1)){let st;try{st=parent.lstat(component);}catch(e){if(e.code==='ENOENT')return;throw e;}if(typeOf(st)!==0o040000)throw Error('Unsafe payload parent');const next=parent.openDir(component);if(!sameIdentity(st,next.stat())){next.close();throw Error('Payload parent changed');}opened.push(next);parent=next;}const name=parts.at(-1);let st;try{st=parent.lstat(name);}catch(e){if(e.code==='ENOENT')return;throw e;}if(isTree){if(typeOf(st)!==0o040000)throw Error('Payload root is not a directory');const sub=parent.openDir(name);try{if(!sameIdentity(st,sub.stat()))throw Error('Payload root changed');snapshot.set(relative,{...metadataOf(st),type:'directory'});walk(sub,relative);}finally{sub.close();}}else{if(typeOf(st)!==0o100000)throw Error('Payload file is not regular');const item=readCheckedFile(parent,name,st);if(!listed.has(relative)||crypto.createHash('sha256').update(item.bytes).digest('hex')!==listed.get(relative))throw Error(`Missing entry or hash mismatch: ${relative}`);files.set(relative,item.bytes);snapshot.set(relative,item.metadata);}}finally{for(const h of opened.reverse())h.close();}}
41
- for(const item of FIXED)select(item,false);for(const item of ROOTS)select(item,true);
42
- for(const platform of ['codex','claude'])composeSkillSources(files,platform);
43
+ for(const item of [...FIXED,...TEMPLATES])select(item,false);for(const item of ROOTS)select(item,true);
44
+ for(const {runtime:{id}}of descriptors)composeSkillSources(files,id,{platforms});
43
45
  const referenceTree=validateFlatReferenceFiles(files);
44
46
  for(const name of listed.keys())if(!files.has(name))throw Error(`Manifest entry is missing: ${name}`);
45
47
  const required=['lib/prompts/agent-fragments.json','lib/prompts/render.mjs','lib/policy/role-policy.json','lib/policy/render.mjs','scripts/update-role-policy.mjs','lib/limits.mjs','lib/installer/limits.mjs','lib/installer/runtime-config.mjs','README.md','install.command','package.json','bin/arc.mjs','lib/cli/root.mjs','lib/tui/app.mjs','lib/tui/terminal.mjs','lib/tui/render.mjs','lib/tui/setup.mjs','lib/management/operations.mjs','lib/management/status.mjs','lib/management/update.mjs','lib/management/workflow.mjs','lib/cli/postinstall.mjs','scripts/postinstall.mjs','lib/cli/upgrade.mjs','bin/arc-upgrade.mjs','lib/installer/shell-completion.mjs','lib/installer/manifest.mjs','lib/installer/targets.mjs','lib/installer/global-config.mjs','lib/installer/plan.mjs','lib/safe-fs/index.mjs','lib/safe-fs/native.mjs','lib/models/index.mjs','lib/models/config.mjs','lib/models/profiles.mjs','vendor/toml/LICENSE','vendor/toml/package.json','vendor/toml/provenance.json','vendor/toml/dist/index.js','prebuilds/index.json'];
@@ -47,16 +49,20 @@ export function verifyPayload({packageRoot,safeFs,payloadMode='auto'}){
47
49
  required.push('shared/skill/runtime/role-policy.json',...RUNTIME_MODULE_PATHS.map(name=>`shared/skill/runtime/${name.slice('lib/runtime/'.length)}`));
48
50
  for(const tuple of ['darwin-arm64','darwin-x64','linux-arm64-gnu','linux-x64-gnu'])required.push(`prebuilds/${tuple}/arc_safe_fs.node`);
49
51
  for(const name of [...COOPERATIVE_RUNTIME_MODULES,'role-policy.json'])required.push(`shared/skill/runtime/${name}`);
50
- const modelInputs={};for(const platform of ['codex','claude']){const base=`${platform}/skill`;required.push(`${base}/SKILL.md`,`${base}/models.toml`,`${base}/references/limits.md`);const profiles=new Map();for(const role of ['scouter','planner','implementer','qa','reviewer']){const name=`arc-${role}.${platform==='codex'?'toml':'md'}`,key=`${platform}/agents/${name}`;required.push(key);profiles.set(name,files.get(key));}modelInputs[platform]={models:files.get(`${base}/models.toml`),profiles};}
52
+ const modelInputs={};for(const {runtime,payloadPrefix}of descriptors){const base=`${payloadPrefix}/skill`;required.push(`${base}/SKILL.md`,`${base}/models.toml`,`${base}/references/limits.md`);const profiles=new Map();for(const role of ['scouter','planner','implementer','qa','reviewer']){const name=standaloneProfileFile(runtime,`arc_${role}`),key=`${payloadPrefix}/agents/${name}`;required.push(key);profiles.set(name,files.get(key));}modelInputs[runtime.id]={models:files.get(`${base}/models.toml`),profiles};}
53
+ for(const descriptor of descriptors)for(const name of descriptor.instructionTemplates??[])required.push(`${descriptor.payloadPrefix}/${name}`);
51
54
  for(const name of required)if(!files.has(name))throw Error(`Required runtime asset is missing: ${name}`);
52
55
  const agentRegistry=JSON.parse(files.get('lib/prompts/agent-fragments.json').toString('utf8'));
53
- const agentTemplates=new Map();for(const platform of ['codex','claude'])for(const [name,bytes] of modelInputs[platform].profiles)agentTemplates.set(`${platform}/agents/${name}`,bytes);
54
- validateAgentTemplates(agentTemplates,agentRegistry);
55
- const policyInputs=new Map(POLICY_TARGETS.map(({path:name})=>[name,files.get(name)]));
56
- const policyOutputs=buildPolicyOutputs(policyInputs,JSON.parse(files.get('lib/policy/role-policy.json').toString('utf8')));
56
+ const agentTemplates=new Map();for(const {runtime:{id},payloadPrefix}of descriptors)for(const [name,bytes] of modelInputs[id].profiles)agentTemplates.set(`${payloadPrefix}/agents/${name}`,bytes);
57
+ const payloadRuntime=createPlatformRegistry(descriptors.map(descriptor=>descriptor.runtime));
58
+ const payloadPlatforms=createInstallerRegistry({runtime:payloadRuntime,descriptors:descriptors.map(descriptor=>({...descriptor,runtime:payloadRuntime.getPlatform(descriptor.runtime.id)}))});
59
+ validateAgentTemplates(agentTemplates,agentRegistry,{platforms:payloadPlatforms});
60
+ const policyTargets=POLICY_TARGETS.filter(target=>descriptors.some(descriptor=>descriptor.runtime.id===target.platform));
61
+ const policyInputs=new Map(policyTargets.map(({path:name})=>[name,files.get(name)]));
62
+ const policyOutputs=buildPolicyOutputs(policyInputs,JSON.parse(files.get('lib/policy/role-policy.json').toString('utf8')),{platforms:[...new Set(policyTargets.map(target=>target.platform))]});
57
63
  for(const [name,bytes] of policyOutputs)if(!bytes.equals(files.get(name)))throw Error(`Stale role policy output: ${name}`);
58
64
  const vendor=JSON.parse(files.get('vendor/toml/provenance.json'));for(const name of Object.keys(vendor.files??{}))if(!safeName(name)||!files.has('vendor/toml/'+name))throw Error('Vendored runtime asset is missing');
59
- for(const platform of ['codex','claude']){const input=modelInputs[platform];const config=loadModelConfig(input.models,platform);renderProfiles(input.profiles,resolveModelSettings(config));modelInputs[platform]={models:Buffer.from(input.models),profiles:new Map([...input.profiles].map(([k,v])=>[k,Buffer.from(v)]))};}
65
+ for(const {runtime:{id},profiles}of descriptors){const input=modelInputs[id];const config=loadModelConfig(input.models,id,{runtimePlatforms});renderProfiles(input.profiles,resolveModelSettings(config,{runtimePlatforms}),{runtimePlatforms,renderProfile:profiles.render});modelInputs[id]={models:Buffer.from(input.models),profiles:new Map([...input.profiles].map(([k,v])=>[k,Buffer.from(v)]))};}
60
66
  return{packageRoot,files,modelInputs,agentRegistry,snapshot,referenceTree};
61
67
  }catch(cause){throw new PayloadValidationError(`Payload verification failed: ${cause.message}`,{cause});}finally{root?.close();}
62
68
  }
@@ -1,12 +1,13 @@
1
1
  import {inspectStandaloneProfile} from './install-mode.mjs';
2
+ import {installerRegistryOf} from '../platforms/index.mjs';
2
3
  import {renderAgentProfile} from '../prompts/render.mjs';
3
4
  import {PayloadValidationError} from './manifest.mjs';
4
5
  import {composeSkillSources} from './skill-sources.mjs';
5
6
  import{parseLanguage,serializeLanguage,renderLanguagePolicy,validateLanguage}from'./language.mjs';
6
- import{resolveLimits}from'../limits.mjs';import{parseLimits,serializeLimits}from'./limits.mjs';import{readRuntimeConcurrency,renderCodexConcurrency,renderClaudeConcurrency}from'./runtime-config.mjs';import{assertPlanSnapshot}from'./transaction.mjs';
7
+ import{resolveLimits}from'../limits.mjs';import{parseLimits,serializeLimits}from'./limits.mjs';import{assertPlanSnapshot}from'./transaction.mjs';
7
8
  import{validateModelConfig}from'../models/config.mjs';
8
9
  import{assertCatalogRoles}from'../models/catalog.mjs';
9
- import path from'node:path';import{loadModelConfig,withRoles,serializeModelConfig,renderProfiles,resolveModelSettings}from'../models/index.mjs';import{inspectPath,TargetConfigurationError}from'./targets.mjs';import{renderManagedBlock,renderWaitSettings,agentsBlockBody}from'./global-config.mjs';
10
+ import path from'node:path';import{loadModelConfig,withRoles,serializeModelConfig,renderProfiles,resolveModelSettings}from'../models/index.mjs';import{inspectPath,TargetConfigurationError}from'./targets.mjs';import{renderManagedBlock,agentsBlockBody}from'./global-config.mjs';
10
11
  function fail(message){throw new TargetConfigurationError(message);}
11
12
  export function previewLimits({target,safeFs}){
12
13
  const snapshot=new Map(),filename=path.join(target.home,'skills/arc/limits.toml');
@@ -20,34 +21,36 @@ export function previewLanguage({target,safeFs}){
20
21
  let existing=null;try{if(current.exists)existing=parseLanguage(current.bytes).language;}catch(cause){fail(`Invalid ARC language settings: ${cause.message}`);}
21
22
  return{existing,snapshot};
22
23
  }
23
- function renderModelAssets({payload,target,roles,modelConfig,language,verifiedCatalog}){
24
+ function renderModelAssets({payload,target,roles,modelConfig,language,verifiedCatalog,platforms,runtimePlatforms}){
24
25
  const input=payload.modelInputs[target.platform];if(!input)fail('Selected payload platform is unavailable');
25
- const base=modelConfig!==undefined?validateModelConfig(modelConfig):loadModelConfig(input.models,target.platform);
26
- if(roles!==undefined)assertCatalogRoles({platform:target.platform,roles,catalog:verifiedCatalog});
27
- const config=roles!==undefined?withRoles(base,roles):base;
28
- if(config.platform!==target.platform)fail('Model config platform does not match target');const settings=resolveModelSettings(config),profiles=renderProfiles(input.profiles,settings);try{for(const[name,bytes]of profiles){const expanded=renderAgentProfile(`${target.platform}/agents/${name}`,bytes,payload.agentRegistry);const final=renderLanguagePolicy(expanded,language);if(final.toString('utf8').includes('ARC_AGENT_FRAGMENT'))throw Error('Unresolved fragment marker');profiles.set(name,final);}const checked=renderProfiles(profiles,settings);if(checked.size!==profiles.size||[...profiles].some(([name,bytes],i)=>{const entry=[...checked][i];return !entry||entry[0]!==name||!entry[1].equals(bytes);}))throw Error('Final profile model settings changed');}catch(cause){throw new PayloadValidationError(`Payload profile rendering failed: ${cause.message}`,{cause});}const modelBytes=Buffer.from(serializeModelConfig(config));
26
+ const base=modelConfig!==undefined?validateModelConfig(modelConfig,{runtimePlatforms}):loadModelConfig(input.models,target.platform,{runtimePlatforms});
27
+ if(roles!==undefined)assertCatalogRoles({platform:target.platform,roles,catalog:verifiedCatalog,runtimePlatforms});
28
+ const config=roles!==undefined?withRoles(base,roles,{runtimePlatforms}):base;
29
+ if(config.platform!==target.platform)fail('Model config platform does not match target');const settings=resolveModelSettings(config,{runtimePlatforms}),profileOptions={runtimePlatforms,renderProfile:installerRegistryOf({platforms}).getPlatform(target.platform).profiles.render},profiles=renderProfiles(input.profiles,settings,profileOptions);try{for(const[name,bytes]of profiles){const expanded=renderAgentProfile(`${target.payloadPrefix??target.platform}/agents/${name}`,bytes,payload.agentRegistry,{platforms});const final=renderLanguagePolicy(expanded,language);if(final.toString('utf8').includes('ARC_AGENT_FRAGMENT'))throw Error('Unresolved fragment marker');profiles.set(name,final);}const checked=renderProfiles(profiles,settings,profileOptions);if(checked.size!==profiles.size||[...profiles].some(([name,bytes],i)=>{const entry=[...checked][i];return !entry||entry[0]!==name||!entry[1].equals(bytes);}))throw Error('Final profile model settings changed');}catch(cause){throw new PayloadValidationError(`Payload profile rendering failed: ${cause.message}`,{cause});}const modelBytes=Buffer.from(serializeModelConfig(config,{runtimePlatforms}));
29
30
  return{profiles,modelBytes};
30
31
  }
31
- export function renderStandaloneProfiles({payload,target,modelConfig,language}){return renderModelAssets({payload,target,modelConfig,language}).profiles;}
32
- function renderSkillPayload({payload,target,language,modelBytes,limits}){
33
- let skill;try{skill=composeSkillSources(payload.files,target.platform);}catch(cause){throw new PayloadValidationError(`Payload skill composition failed: ${cause.message}`,{cause});}
32
+ export function renderStandaloneProfiles({payload,target,modelConfig,language,platforms,runtimePlatforms}){return renderModelAssets({payload,target,modelConfig,language,platforms,runtimePlatforms}).profiles;}
33
+ function renderSkillPayload({payload,target,language,modelBytes,limits,platforms}){
34
+ let skill;try{skill=composeSkillSources(payload.files,target.platform,{platforms});}catch(cause){throw new PayloadValidationError(`Payload skill composition failed: ${cause.message}`,{cause});}
34
35
  skill.set('SKILL.md',renderLanguagePolicy(skill.get('SKILL.md'),language));skill.set('settings.toml',serializeLanguage(language));skill.set('models.toml',modelBytes);skill.set('limits.toml',serializeLimits(limits));
35
36
  return skill;
36
37
  }
37
- function renderNativeChanges({target,safeFs,snapshot,skipGlobal,preview,concurrentExplicit,limits,summary,language}){
38
+ function renderNativeChanges({target,safeFs,snapshot,skipGlobal,preview,concurrentExplicit,limits,summary,language,platforms}){
38
39
  const home=target.home;
39
40
  const globalChanges=[];
40
41
  if(limits.max_concurrent_subagents>limits.max_total_subagents)summary.push(`Effective concurrency is at most ${limits.max_total_subagents} for a fresh ARC session; it may be lower after cumulative use or due to native capacity.`);
41
42
  if(skipGlobal)summary.push('Native concurrency update skipped (--skip-global).');
42
43
  else for(const filename of target.globalPaths){
44
+ if(filename!==target.instructionPath&&!installerRegistryOf({platforms}).getPlatform(target.platform).runtimeConfig.renderConcurrency)continue;
43
45
  const current=inspectPath(safeFs,filename,{kind:'file',read:true,snapshot}),original=current.bytes??null;
44
46
  let rendered;
45
47
  if(filename===target.instructionPath)rendered=renderManagedBlock(original,agentsBlockBody(home,target.userHome,language,target.platform));
46
48
  else{
47
- let previous;try{previous=readRuntimeConcurrency(target.platform,original);}catch(cause){fail(`Invalid native configuration: ${cause.message}`);}
49
+ const runtimeConfig=installerRegistryOf({platforms}).getPlatform(target.platform).runtimeConfig;
50
+ let previous;try{previous=runtimeConfig.readConcurrency(original);}catch(cause){fail(`Invalid native configuration: ${cause.message}`);}
48
51
  if(preview.existing&&previous!==null&&previous!==preview.existing.max_concurrent_subagents&&!concurrentExplicit)fail(`Native concurrency drift at ${filename}; explicitly select --max-concurrent-subagents to update it`);
49
- let base=original;if(target.platform==='codex'){const wait=renderWaitSettings(original);base=wait.content??original;if(wait.content===null)summary.push(`${filename}: ${wait.action}`);}
50
- try{rendered=target.platform==='codex'?renderCodexConcurrency(base,limits.max_concurrent_subagents):renderClaudeConcurrency(base,limits.max_concurrent_subagents);}catch(cause){fail(`Cannot merge native concurrency: ${cause.message}`);}
52
+ let base=original;if(runtimeConfig.extraRender){const extra=runtimeConfig.extraRender(original);base=extra.content??original;if(extra.content===null)summary.push(`${filename}: ${extra.action}`);}
53
+ try{rendered=runtimeConfig.renderConcurrency(base,limits.max_concurrent_subagents);}catch(cause){fail(`Cannot merge native concurrency: ${cause.message}`);}
51
54
  summary.push(`${filename}: native concurrency ${previous??'missing'} -> ${limits.max_concurrent_subagents}`);
52
55
  }
53
56
  if(rendered.content!==null&&(original===null||!rendered.content.equals(original)))globalChanges.push({path:filename,original,content:rendered.content,action:rendered.action});
@@ -55,7 +58,7 @@ function renderNativeChanges({target,safeFs,snapshot,skipGlobal,preview,concurre
55
58
  }
56
59
  return globalChanges;
57
60
  }
58
- export function buildInstallPlan({payload,target,roles,profiles:profileMode='write',skipGlobal=false,safeFs,limits,concurrentExplicit=false,limitsPreview,language='en',languagePreview,modelConfig,verifiedCatalog}){
61
+ export function buildInstallPlan({payload,target,roles,profiles:profileMode='write',skipGlobal=false,safeFs,limits,concurrentExplicit=false,limitsPreview,language='en',languagePreview,modelConfig,verifiedCatalog,platforms,runtimePlatforms}){
59
62
  validateLanguage(language);
60
63
  if(languagePreview)assertPlanSnapshot({snapshot:languagePreview.snapshot},{safeFs});
61
64
  const languageState=languagePreview??previewLanguage({target,safeFs});
@@ -63,18 +66,18 @@ export function buildInstallPlan({payload,target,roles,profiles:profileMode='wri
63
66
  const preview=limitsPreview??previewLimits({target,safeFs});
64
67
  limits=resolveLimits({existing:preview.existing,overrides:limits??{}});
65
68
  const modelSnapshot=new Map();
66
- if(modelConfig===undefined&&roles===undefined){const installed=inspectPath(safeFs,path.join(target.home,'skills/arc/models.toml'),{kind:'file',read:true,snapshot:modelSnapshot});if(installed.exists)modelConfig=loadModelConfig(installed.bytes,target.platform);}
67
- const {profiles,modelBytes}=renderModelAssets({payload,target,roles,modelConfig,language,verifiedCatalog});
68
- const skill=renderSkillPayload({payload,target,language,modelBytes,limits});
69
+ if(modelConfig===undefined&&roles===undefined){const installed=inspectPath(safeFs,path.join(target.home,'skills/arc/models.toml'),{kind:'file',read:true,snapshot:modelSnapshot});if(installed.exists)modelConfig=loadModelConfig(installed.bytes,target.platform,{runtimePlatforms});}
70
+ const {profiles,modelBytes}=renderModelAssets({payload,target,roles,modelConfig,language,verifiedCatalog,platforms,runtimePlatforms});
71
+ const skill=renderSkillPayload({payload,target,language,modelBytes,limits,platforms});
69
72
  const snapshot=new Map(),home=target.home;const skills=path.join(home,'skills'),agents=path.join(home,'agents'),arc=path.join(skills,'arc');
70
73
  for(const name of [home,skills,agents])inspectPath(safeFs,name,{kind:'directory',snapshot});
71
74
  inspectPath(safeFs,arc,{kind:'directory',tree:true,allowLinks:true,snapshot});
72
75
  const profilePaths=[],profileWrites=new Map(),residualPaths=[];
73
- if(profileMode!=='omit')for(const [name,bytes]of profiles){const found=inspectStandaloneProfile({safeFs,target,role:name.split('.')[0].replace('-','_'),snapshot});if(found.exists&&!found.owned){residualPaths.push(found.path);continue;}profilePaths.push(found.path);profileWrites.set(name,bytes);}
76
+ if(profileMode!=='omit')for(const [name,bytes]of profiles){const found=inspectStandaloneProfile({safeFs,target,role:name.split('.')[0].replace('-','_'),snapshot,platforms});if(found.exists&&!found.owned){residualPaths.push(found.path);continue;}profilePaths.push(found.path);profileWrites.set(name,bytes);}
74
77
  const externalPaths=[],summary=['Verified packaged Superpowers references will be installed inside ARC'];
75
78
  summary.push(`ARC limits: total ${limits.max_total_subagents}; concurrent ${limits.max_concurrent_subagents} (policy: ${arc}/limits.toml)`);
76
- const globalChanges=renderNativeChanges({target,safeFs,snapshot,skipGlobal,preview,concurrentExplicit,limits,summary,language});
77
- const managedPaths=[arc,...profilePaths,...(skipGlobal?[]:target.globalPaths)];
79
+ const globalChanges=renderNativeChanges({target,safeFs,snapshot,skipGlobal,preview,concurrentExplicit,limits,summary,language,platforms});
80
+ const managedPaths=[arc,...profilePaths,...globalChanges.map(change=>change.path)];
78
81
  for(const [filename,metadata]of preview.snapshot)snapshot.set(filename,metadata);
79
82
  for(const [filename,metadata]of languageState.snapshot)snapshot.set(filename,metadata);
80
83
  summary.push(`ARC output language: ${language}`);
@@ -8,17 +8,18 @@ import {isDeepStrictEqual} from 'node:util';
8
8
  import {assertCatalogRoles} from '../models/catalog.mjs';
9
9
  import {validatePlanSet,renderStandaloneProfiles} from './plan.mjs';
10
10
  import {parseLanguage} from './language.mjs';
11
- export function buildPresetPlan({target,roles,safeFs,verifiedCatalog,payload,loadPayload}){
11
+ import {installerRegistryOf} from '../platforms/index.mjs';
12
+ export function buildPresetPlan({target,roles,safeFs,verifiedCatalog,payload,loadPayload,platforms,runtimePlatforms}){
12
13
  const snapshot=new Map(),modelsPath=path.join(target.home,'skills/arc/models.toml'),managedPaths=[modelsPath],residualPaths=[];
13
14
  const read=filename=>{const found=inspectPath(safeFs,filename,{kind:'file',read:true,snapshot});if(!found.exists)throw new TargetConfigurationError(`Installed ARC file missing: ${filename}`);return found.bytes;};
14
- const originalModels=read(modelsPath),config=loadModelConfig(originalModels,target.platform);
15
- if(roles!==undefined)assertCatalogRoles({platform:target.platform,roles,catalog:verifiedCatalog});
16
- const next=roles!==undefined?withRoles(config,roles):config,originalProfiles=new Map();
17
- for(const name of target.profileNames){const found=inspectStandaloneProfile({safeFs,target,role:name.split('.')[0].replace('-','_'),snapshot});if(!found.exists)throw new TargetConfigurationError(`Installed ARC file missing: ${found.path}`);if(!found.owned){residualPaths.push(found.path);continue;}originalProfiles.set(name,read(found.path));managedPaths.push(found.path);}
18
- const profileInputs=residualPaths.length?renderStandaloneProfiles({payload:payload??loadPayload(),target,modelConfig:next,language:parseLanguage(read(path.join(target.home,'skills/arc/settings.toml'))).language}):new Map();
15
+ const originalModels=read(modelsPath),config=loadModelConfig(originalModels,target.platform,{runtimePlatforms});
16
+ if(roles!==undefined)assertCatalogRoles({platform:target.platform,roles,catalog:verifiedCatalog,runtimePlatforms});
17
+ const next=roles!==undefined?withRoles(config,roles,{runtimePlatforms}):config,originalProfiles=new Map();
18
+ for(const name of target.profileNames){const found=inspectStandaloneProfile({safeFs,target,role:name.split('.')[0].replace('-','_'),snapshot,platforms});if(!found.exists)throw new TargetConfigurationError(`Installed ARC file missing: ${found.path}`);if(!found.owned){residualPaths.push(found.path);continue;}originalProfiles.set(name,read(found.path));managedPaths.push(found.path);}
19
+ const profileInputs=residualPaths.length?renderStandaloneProfiles({platforms,runtimePlatforms,payload:payload??loadPayload(),target,modelConfig:next,language:parseLanguage(read(path.join(target.home,'skills/arc/settings.toml'))).language}):new Map();
19
20
  for(const entry of originalProfiles)profileInputs.set(...entry);
20
- const profiles=renderProfiles(profileInputs,resolveModelSettings(next)),specs=[];
21
- if(readModelFileVersion(originalModels)<3||!isDeepStrictEqual(config.roles,next.roles))specs.push({path:modelsPath,bytes:Buffer.from(serializeModelConfig(next))});
21
+ const profiles=renderProfiles(profileInputs,resolveModelSettings(next,{runtimePlatforms}),{runtimePlatforms,renderProfile:installerRegistryOf({platforms}).getPlatform(target.platform).profiles.render}),specs=[];
22
+ if(readModelFileVersion(originalModels)<3||!isDeepStrictEqual(config.roles,next.roles))specs.push({path:modelsPath,bytes:Buffer.from(serializeModelConfig(next,{runtimePlatforms}))});
22
23
  for(const[name,bytes]of profiles)if(originalProfiles.has(name)&&!bytes.equals(originalProfiles.get(name)))specs.push({path:path.join(target.home,'agents',name),bytes});
23
24
  return{target,roles:next.roles,snapshot,managedPaths,residualPaths,externalPaths:[],specs};
24
25
  }