@yunhozz/arc 0.5.6 → 0.6.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 (130) hide show
  1. package/MANIFEST.sha256 +124 -110
  2. package/README.md +37 -113
  3. package/claude/agents/arc-architect.md +44 -0
  4. package/claude/agents/arc-implementer.md +2 -2
  5. package/claude/agents/arc-planner.md +5 -5
  6. package/claude/agents/arc-reviewer.md +1 -1
  7. package/claude/agents/arc-scouter.md +1 -1
  8. package/claude/agents/arc-tester.md +1 -1
  9. package/claude/skill/SKILL.md +6 -6
  10. package/claude/skill/models.toml +5 -1
  11. package/claude/skill/references/arc-visual-companion.md +2 -21
  12. package/claude/skill/references/commit.md +5 -32
  13. package/claude/skill/references/coordination.md +29 -134
  14. package/claude/skill/references/git-recovery.md +3 -3
  15. package/claude/skill/references/handoff-prep.md +9 -24
  16. package/claude/skill/references/handoff.md +19 -108
  17. package/claude/skill/references/limits.md +4 -15
  18. package/claude/skill/references/planning.md +32 -119
  19. package/claude/skill/references/verification.md +17 -119
  20. package/claude/skill/references/worktree-creation.md +1 -1
  21. package/claude/skill/scripts/model_config.py +24 -11
  22. package/codex/agents/arc-architect.md +36 -0
  23. package/codex/agents/{arc-implementer.toml → arc-implementer.md} +10 -5
  24. package/codex/agents/{arc-planner.toml → arc-planner.md} +14 -7
  25. package/codex/agents/{arc-reviewer.toml → arc-reviewer.md} +13 -4
  26. package/codex/agents/{arc-scouter.toml → arc-scouter.md} +13 -4
  27. package/codex/agents/{arc-tester.toml → arc-tester.md} +13 -4
  28. package/codex/skill/SKILL.md +6 -6
  29. package/codex/skill/models.toml +5 -1
  30. package/codex/skill/references/arc-visual-companion.md +3 -27
  31. package/codex/skill/references/commit.md +5 -32
  32. package/codex/skill/references/coordination.md +25 -131
  33. package/codex/skill/references/git-recovery.md +2 -7
  34. package/codex/skill/references/handoff-prep.md +9 -24
  35. package/codex/skill/references/handoff.md +19 -108
  36. package/codex/skill/references/limits.md +5 -16
  37. package/codex/skill/references/planning.md +32 -119
  38. package/codex/skill/references/verification.md +16 -118
  39. package/codex/skill/scripts/apply-models.py +5 -5
  40. package/codex/skill/scripts/model_config.py +23 -12
  41. package/gemini/GEMINI.md +1 -1
  42. package/gemini/agents/arc-architect.md +39 -0
  43. package/gemini/agents/arc-implementer.md +1 -1
  44. package/gemini/agents/arc-planner.md +4 -4
  45. package/gemini/instructions.md +1 -1
  46. package/gemini/skill/SKILL.md +6 -6
  47. package/gemini/skill/models.toml +5 -1
  48. package/gemini/skill/references/arc-visual-companion.md +2 -21
  49. package/gemini/skill/references/commit.md +5 -32
  50. package/gemini/skill/references/coordination.md +32 -137
  51. package/gemini/skill/references/git-recovery.md +3 -3
  52. package/gemini/skill/references/handoff-prep.md +9 -24
  53. package/gemini/skill/references/handoff.md +19 -108
  54. package/gemini/skill/references/limits.md +4 -15
  55. package/gemini/skill/references/planning.md +32 -119
  56. package/gemini/skill/references/verification.md +17 -119
  57. package/grok/AGENTS.md +1 -1
  58. package/grok/agents/arc-architect.md +39 -0
  59. package/grok/agents/arc-implementer.md +1 -1
  60. package/grok/agents/arc-planner.md +4 -4
  61. package/grok/instructions.md +1 -1
  62. package/grok/skill/SKILL.md +5 -5
  63. package/grok/skill/models.toml +5 -1
  64. package/grok/skill/references/arc-visual-companion.md +2 -21
  65. package/grok/skill/references/commit.md +5 -32
  66. package/grok/skill/references/coordination.md +30 -135
  67. package/grok/skill/references/git-recovery.md +3 -3
  68. package/grok/skill/references/handoff-prep.md +9 -24
  69. package/grok/skill/references/handoff.md +19 -108
  70. package/grok/skill/references/limits.md +4 -15
  71. package/grok/skill/references/planning.md +32 -119
  72. package/grok/skill/references/verification.md +17 -119
  73. package/lib/installer/global-config.mjs +1 -1
  74. package/lib/installer/manifest.mjs +20 -3
  75. package/lib/installer/role-routing.mjs +6 -3
  76. package/lib/installer/targets.mjs +1 -1
  77. package/lib/installer/upgrade-state.mjs +3 -2
  78. package/lib/models/config.mjs +22 -5
  79. package/lib/models/profiles.mjs +6 -1
  80. package/lib/platforms/agent-templates.mjs +1 -0
  81. package/lib/platforms/codex.mjs +2 -0
  82. package/lib/platforms/formats/codex-markdown.mjs +58 -0
  83. package/lib/platforms/formats/gemini-markdown.mjs +3 -2
  84. package/lib/platforms/formats/grok-markdown.mjs +3 -2
  85. package/lib/platforms/formats/markdown.mjs +3 -2
  86. package/lib/platforms/formats/toml.mjs +3 -2
  87. package/lib/policy/placement.mjs +1 -1
  88. package/lib/policy/render.mjs +6 -5
  89. package/lib/policy/role-policy.json +36 -7
  90. package/lib/prompts/agent-fragments.json +107 -24
  91. package/lib/prompts/render.mjs +69 -19
  92. package/lib/runtime/adapters/codex.mjs +1 -1
  93. package/lib/runtime/evaluate.mjs +4 -3
  94. package/lib/runtime/identity.mjs +1 -1
  95. package/lib/runtime/operations.mjs +2 -2
  96. package/lib/runtime/role-bridge-args.mjs +5 -3
  97. package/lib/runtime/role-bridge.mjs +24 -2
  98. package/lib/runtime/role-dispatch-policy.mjs +2 -1
  99. package/lib/runtime/role-dispatch-store.mjs +44 -1
  100. package/lib/runtime/role-observe.mjs +12 -4
  101. package/lib/runtime/role-routing-config.mjs +9 -4
  102. package/lib/runtime/role-supervisor.mjs +16 -2
  103. package/lib/tui/diagram.mjs +2 -3
  104. package/lib/tui/setup.mjs +13 -11
  105. package/lib/watch/labels.mjs +1 -1
  106. package/lib/watch/model.mjs +2 -2
  107. package/lib/watch/render.mjs +2 -2
  108. package/package.json +1 -1
  109. package/scripts/update-manifest.mjs +1 -1
  110. package/shared/skill/references/arc-visual-companion-common.md +39 -0
  111. package/shared/skill/references/commit-common.md +45 -0
  112. package/shared/skill/references/coordination-common.md +200 -0
  113. package/shared/skill/references/git-recovery-common.md +15 -0
  114. package/shared/skill/references/handoff-common.md +182 -0
  115. package/shared/skill/references/handoff-prep-common.md +53 -0
  116. package/shared/skill/references/limits-common.md +34 -0
  117. package/shared/skill/references/planning-common.md +185 -0
  118. package/shared/skill/references/verification-common.md +172 -0
  119. package/shared/skill/runtime/adapters/codex.mjs +1 -1
  120. package/shared/skill/runtime/evaluate.mjs +4 -3
  121. package/shared/skill/runtime/identity.mjs +1 -1
  122. package/shared/skill/runtime/operations.mjs +2 -2
  123. package/shared/skill/runtime/role-bridge-args.mjs +5 -3
  124. package/shared/skill/runtime/role-bridge.mjs +24 -2
  125. package/shared/skill/runtime/role-dispatch-policy.mjs +2 -1
  126. package/shared/skill/runtime/role-dispatch-store.mjs +44 -1
  127. package/shared/skill/runtime/role-observe.mjs +12 -4
  128. package/shared/skill/runtime/role-policy.json +36 -7
  129. package/shared/skill/runtime/role-routing-config.mjs +9 -4
  130. package/shared/skill/runtime/role-supervisor.mjs +16 -2
@@ -5,7 +5,8 @@ import fsp from 'node:fs/promises';
5
5
  import path from 'node:path';
6
6
  import {DEFAULT_POLICY, HOST_SANDBOX_GATES, reason, profileName, bridgeGateReasons, environmentReasons, capabilityReasons} from './role-dispatch-policy.mjs';
7
7
  import {displayRoutingRole} from './role-routing-config.mjs';
8
- import {readLease, writeLease, listLeases, readHostLimits, NON_TERMINAL_STATES, readHeartbeat, requestCancel, clearCancel, TERMINAL_STATES, validateLease} from './role-dispatch-store.mjs';
8
+ import {readLease, writeLease, listLeases, readHostLimits, NON_TERMINAL_STATES, readHeartbeat, requestCancel, clearCancel, TERMINAL_STATES, validateLease, readWorktreeRecord, writeWorktreeRecord, removeWorktreeRecord, worktreeWriters} from './role-dispatch-store.mjs';
9
+ import {pathsOverlap} from './role-observe.mjs';
9
10
  import {withRoutingLock, readActivation, readRevision, authenticate, resolveRuntimeHomes, locateAnchorHome, probeHomeWritable} from './role-routing.mjs';
10
11
  import {SUPERVISOR_IMPLEMENTATIONS, startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation, reapRecordedDescendants, reapRecordedHostServices} from './role-supervisor.mjs';
11
12
 
@@ -39,6 +40,18 @@ const residualOf=error=>Array.isArray(error?.residualPaths)?error.residualPaths:
39
40
  const hold=(context,dispatchId,code,error)=>{const result=blank(context,dispatchId,'hold',code);const residual=residualOf(error);if(residual)result.residualPaths=residual;return result;};
40
41
  const classifyLock=error=>{const code=error?.code==='ARC_ROUTING_LOCK_RELEASE'&&error.failure?error.failure.code:error?.code;return code==='ARC_HOST_SANDBOX'?'host_sandbox_blocked':'activation_unverified';};
41
42
 
43
+ async function overlapHold({anchorHome,lease,worktree,runtimePlatforms}){
44
+ const leases=await listLeases(anchorHome,{runtimePlatforms});
45
+ const records=new Map();
46
+ for(const item of leases){
47
+ if(item.route==='bridge'&&(item.role==='arc_implementer'||item.role==='arc_tester')){
48
+ records.set(item.dispatchId,await readWorktreeRecord(anchorHome,item.dispatchId));
49
+ }
50
+ }
51
+ const owners=worktreeWriters({leases,records,dispatchId:lease.dispatchId,worktree,terminalSinceMs:null});
52
+ return owners.some(owner=>pathsOverlap(owner.allowedPaths,lease.allowedPaths));
53
+ }
54
+
42
55
  /** Starts the detached supervisor for a reserved bridge lease; the supervisor, not this function, spawns the child. */
43
56
  export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now(),policy=DEFAULT_POLICY,startSupervisor:starter=startSupervisor,observeToolContext}={}){
44
57
  if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.')||typeof brief!=='string'){return blank(context,dispatchId,'deny','invalid_request');}
@@ -59,6 +72,7 @@ export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now()
59
72
  const capabilities=capabilityReasons({hostPlatform:lease.hostPlatform,targetPlatform:platform,route:lease.route,runtimePlatforms});
60
73
  if(capabilities.length){result=blank(context,dispatchId,'hold',capabilities[0]);return;}
61
74
  let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
75
+ if(await overlapHold({anchorHome,lease,worktree:target.realpath,runtimePlatforms})){result=blank(context,dispatchId,'hold','allowed_paths_overlap');return;}
62
76
  const directory=artifactDirectory(target,lease.workflowId,dispatchId),resultPath=path.join(directory,'result.md');
63
77
  let invocation;try{invocation=await buildBridgeInvocation({lease,config,homes,worktree:target.realpath,resultPath,userHome:context.userHome,env:context.env??process.env,target,runtimePlatforms,policy,observeToolContext});}catch(error){result=blank(context,dispatchId,'hold',error.reasonCode??'activation_unverified');return;}
64
78
  await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(directory,0o700);
@@ -68,6 +82,7 @@ export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now()
68
82
  if(!probe.ok){result=hold(context,dispatchId,probe.code,probe);return;}
69
83
  }
70
84
  let supervisor;
85
+ await writeWorktreeRecord(anchorHome,dispatchId,{segment:lease.segment,worktree:target.realpath});
71
86
  try{supervisor=await starter({codexHome:anchorHome,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
72
87
  catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
73
88
  const next=await writeLease(anchorHome,{...lease,state:'starting',supervisor,argsDigest:invocation.argsDigest,resultPath},{now,runtimePlatforms});
@@ -196,6 +211,7 @@ export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(
196
211
  if(limits&&(await listLeases(anchorHome,{runtimePlatforms})).filter(item=>item.route==='bridge'&&NON_TERMINAL_STATES.includes(item.state)).length+1>limits.maxConcurrent)codes.add('capacity_exhausted');
197
212
  if(codes.size){result=blank(context,dispatchId,'hold','activation_unverified');result.reasons=[...codes].map(reason);return;}
198
213
  let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
214
+ if(await overlapHold({anchorHome,lease,worktree:target.realpath,runtimePlatforms})){result=blank(context,dispatchId,'hold','allowed_paths_overlap');return;}
199
215
  const segment=lease.segment+1,directory=segmentDirectory(target,lease.workflowId,dispatchId,segment),resultPath=path.join(directory,'result.md');
200
216
  let invocation;try{invocation=await buildBridgeInvocation({lease:{...lease,segment},config,homes,worktree:target.realpath,resultPath,userHome:context.userHome,env:context.env??process.env,target,runtimePlatforms,policy,supervisorImplementations,observeToolContext});}catch(error){result=blank(context,dispatchId,'hold',error.reasonCode??'activation_unverified');return;}
201
217
  await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(path.dirname(directory),0o700);await fsp.chmod(directory,0o700);
@@ -204,10 +220,16 @@ export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(
204
220
  const probe=await probeHomeWritable(homes[platform]);
205
221
  if(!probe.ok){result=hold(context,dispatchId,probe.code,probe);return;}
206
222
  }
223
+ const previousRecord=await readWorktreeRecord(anchorHome,dispatchId);
224
+ await writeWorktreeRecord(anchorHome,dispatchId,{segment,worktree:target.realpath});
207
225
  await clearCancel(anchorHome,dispatchId);
208
226
  let supervisor;
209
227
  try{supervisor=await starter({codexHome:anchorHome,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
210
- catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
228
+ catch{
229
+ if(previousRecord)await writeWorktreeRecord(anchorHome,dispatchId,previousRecord);
230
+ else await removeWorktreeRecord(anchorHome,dispatchId);
231
+ result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;
232
+ }
211
233
  const claims=lease.claims?{...lease.claims,terminal:{level:'unverified',source:'none'}}:null;
212
234
  const next=await writeLease(anchorHome,{...lease,state:'starting',supervisor,child:null,argsDigest:invocation.argsDigest,resultPath,segment,claims,reasons:[]},{now,runtimePlatforms});
213
235
  result={...view(next,'allow'),segment};
@@ -41,7 +41,7 @@ export const effectiveClaudeSandboxSettings = policy => policy?.gates?.G1 === 'p
41
41
  export const CATALOG_MODEL_ALIASES = Object.freeze(['fable', 'opus', 'sonnet', 'haiku']);
42
42
  export const CODEX_DELEGATION_CALL_NAMES = Object.freeze(['spawn_agent', 'wait_agent']);
43
43
  export const DESKTOP_CHECKLIST_PASSED = Object.freeze({'claude-desktop': false, 'codex-desktop': false});
44
- export const ROLE_TIMEOUT_MINUTES = Object.freeze({arc_scouter: 20, arc_planner: 20, arc_implementer: 60, arc_tester: 60, arc_reviewer: 20});
44
+ export const ROLE_TIMEOUT_MINUTES = Object.freeze({arc_scouter: 20, arc_architect: 20, arc_planner: 20, arc_implementer: 60, arc_tester: 60, arc_reviewer: 20});
45
45
  export const HEARTBEAT_MS = 5000;
46
46
  export const SUPERVISOR_LOST_MS = 30000;
47
47
  export const OBSERVE_MAX_WAIT_MS = 540000;
@@ -86,6 +86,7 @@ export const RELEASE_CONDITIONS = Object.freeze({
86
86
  environment_unverified: `Desktop hosts are held in this release. If this session is not running inside a Desktop app (for example a terminal or IDE terminal session), declare a CLI environment (${cliEnvironments}) instead; otherwise use a CLI host or a later ARC update that changes the support status.`,
87
87
  host_sandbox_blocked: 'Allow the host to write the anchor home and keep a detached supervisor alive, with explicit user approval.',
88
88
  capacity_exhausted: 'Finish or release active bridge executions, or raise the host limits.',
89
+ allowed_paths_overlap: 'Wait until the started bridge dispatch whose allowedPaths overlap in the same worktree reaches a terminal state, resolving it first when it is unknown, or prepare a new dispatch with non-overlapping allowedPaths; then run or resume again.',
89
90
  permission_scope_unverified: 'Update ARC and verify enforcement of the role permissions and approved scope before starting.',
90
91
  native_profile_reload_unverified: 'Verify that the host session loaded the requested profile revision.',
91
92
  revision_changed: 'Re-run routing-status and prepare a new dispatch under the current revision.',
@@ -77,6 +77,7 @@ export async function writeLease(codexHome, lease, {now = Date.now(), runtimePla
77
77
  return value;
78
78
  }
79
79
  const HEARTBEAT_SUFFIX = '.heartbeat.json';
80
+ const WORKTREE_SUFFIX = '.worktree';
80
81
  const leaseFiles = async codexHome => {
81
82
  try { return (await fsp.readdir(dispatchDirectory(codexHome))).filter(name => name.endsWith('.json') && !name.endsWith(HEARTBEAT_SUFFIX) && !name.startsWith('.')).sort(); }
82
83
  catch (error) { if (error.code === 'ENOENT') return []; throw error; }
@@ -97,7 +98,7 @@ export async function pruneTerminalLeases(codexHome, {now = Date.now(), retentio
97
98
  const updated = Date.parse(lease.updatedAt);
98
99
  if (!TERMINAL_STATES.includes(lease.state) || !Number.isFinite(updated) || now - updated <= retentionMs) continue;
99
100
  await fsp.unlink(file); removed += 1;
100
- for (const extra of [`${lease.dispatchId}${HEARTBEAT_SUFFIX}`, `${lease.dispatchId}.cancel`]) await fsp.unlink(path.join(dispatchDirectory(codexHome), extra)).catch(() => {});
101
+ for (const suffix of [HEARTBEAT_SUFFIX, '.cancel', WORKTREE_SUFFIX]) await fsp.unlink(sidecarPath(codexHome, lease.dispatchId, suffix)).catch(() => {});
101
102
  } catch { errors += 1; }
102
103
  }
103
104
  return {removed, errors};
@@ -117,6 +118,48 @@ export function readHostLimits(hostHome) {
117
118
  }
118
119
 
119
120
  const sidecarPath = (codexHome, dispatchId, suffix) => path.join(dispatchDirectory(codexHome), `${path.basename(leasePath(codexHome, dispatchId), '.json')}${suffix}`);
121
+ const validWorktree = (segment, worktree) => Number.isInteger(segment) && segment >= 0 && typeof worktree === 'string' && path.isAbsolute(worktree);
122
+
123
+ /** Records the worktree for one segment while the caller holds the routing lock. */
124
+ export async function writeWorktreeRecord(codexHome, dispatchId, {segment, worktree}) {
125
+ if (!validWorktree(segment, worktree)) throw Error('Invalid worktree record');
126
+ const target = sidecarPath(codexHome, dispatchId, WORKTREE_SUFFIX);
127
+ const temp = path.join(dispatchDirectory(codexHome), `.${dispatchId}.${crypto.randomUUID()}.wt.tmp`);
128
+ try {
129
+ const handle = await fsp.open(temp, 'wx', 0o600);
130
+ try { await handle.writeFile(JSON.stringify({version: 1, dispatchId, segment, worktree}) + '\n'); } finally { await handle.close(); }
131
+ await fsp.rename(temp, target);
132
+ } catch (error) { await fsp.unlink(temp).catch(() => {}); throw error; }
133
+ }
134
+
135
+ export async function readWorktreeRecord(codexHome, dispatchId) {
136
+ try {
137
+ const value = JSON.parse(await fsp.readFile(sidecarPath(codexHome, dispatchId, WORKTREE_SUFFIX), 'utf8'));
138
+ if (!isObject(value) || Object.keys(value).length !== 4 || value.version !== 1 ||
139
+ value.dispatchId !== dispatchId || !validWorktree(value.segment, value.worktree)) return null;
140
+ return value;
141
+ } catch { return null; }
142
+ }
143
+
144
+ export async function removeWorktreeRecord(codexHome, dispatchId) {
145
+ try { await fsp.unlink(sidecarPath(codexHome, dispatchId, WORKTREE_SUFFIX)); }
146
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
147
+ }
148
+
149
+ export function worktreeWriters({leases, records, dispatchId, worktree, terminalSinceMs, excludeUnknown = false}) {
150
+ const writers = leases.filter(lease => {
151
+ if (lease.dispatchId === dispatchId || lease.route !== 'bridge' ||
152
+ (lease.role !== 'arc_implementer' && lease.role !== 'arc_tester') || !lease.allowedPaths.length) return false;
153
+ if (excludeUnknown && lease.state === 'unknown') return false;
154
+ const record = records.get(lease.dispatchId);
155
+ if (!record || record.segment !== lease.segment || record.worktree !== worktree) return false;
156
+ return (lease.state !== 'reserved' && NON_TERMINAL_STATES.includes(lease.state)) ||
157
+ (terminalSinceMs !== null && TERMINAL_STATES.includes(lease.state) && Date.parse(lease.updatedAt) >= terminalSinceMs);
158
+ });
159
+ return writers.sort((a, b) => a.dispatchId < b.dispatchId ? -1 : a.dispatchId > b.dispatchId ? 1 : 0)
160
+ .map(({dispatchId, allowedPaths}) => ({dispatchId, allowedPaths}));
161
+ }
162
+
120
163
  /** The supervisor alone writes its heartbeat; no routing lock is needed because the file is replaced atomically and holds no lease state. */
121
164
  export async function writeHeartbeat(codexHome, dispatchId, {at, pid}) {
122
165
  if (!Number.isFinite(at) || !Number.isInteger(pid) || pid <= 0) throw Error('Invalid heartbeat');
@@ -568,6 +568,8 @@ function otherWorktreeBranches(before, after) {
568
568
  }
569
569
 
570
570
  const allowedBy = (allowedPaths, file) => allowedPaths.some(entry => entry.endsWith('/') ? file.startsWith(entry) : file === entry);
571
+ export const pathsOverlap = (a, b) => a.some(file => allowedBy(b, file)) || b.some(file => allowedBy(a, file));
572
+ const byPath = (a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
571
573
  const hasBranchRefs = (before, after) => before.branchRef !== undefined && after.branchRef !== undefined;
572
574
  const branchChanged = (before, after) => hasBranchRefs(before, after)
573
575
  ? before.branchRef !== after.branchRef
@@ -638,7 +640,7 @@ export async function observeHeadAdvance(root, before, after, role, allowedPaths
638
640
  * commits. Ordinary worktree snapshots omit Git-ignored paths. Control files
639
641
  * are compared regardless of role and allowedPaths.
640
642
  */
641
- export function detectViolations({role, allowedPaths, before, after, headAdvance}) {
643
+ export function detectViolations({role, allowedPaths, before, after, headAdvance, otherOwners = []}) {
642
644
  const branchSwitched = branchChanged(before, after);
643
645
  const headMoved = before.head !== after.head;
644
646
  const targetBranch = before.branchRef;
@@ -663,8 +665,12 @@ export function detectViolations({role, allowedPaths, before, after, headAdvance
663
665
  }
664
666
  const allowed = (role === 'arc_implementer' || role === 'arc_tester') && Array.isArray(allowedPaths) ? allowedPaths : [];
665
667
  const changed = new Set();
668
+ const attributedPaths = [];
666
669
  for (const file of new Set([...before.entries.keys(), ...after.entries.keys()])) {
667
- if (before.entries.get(file) !== after.entries.get(file) && !allowedBy(allowed, file)) changed.add(file);
670
+ if (before.entries.get(file) === after.entries.get(file) || allowedBy(allowed, file)) continue;
671
+ const owners = otherOwners.filter(owner => allowedBy(owner.allowedPaths, file)).map(owner => owner.dispatchId).sort();
672
+ if (owners.length) attributedPaths.push({path: file, owners});
673
+ else changed.add(file);
668
674
  }
669
675
  if (headAdvance?.state === 'rejected') {
670
676
  for (const file of headAdvance.outOfScopePaths ?? []) changed.add(file);
@@ -679,15 +685,17 @@ export function detectViolations({role, allowedPaths, before, after, headAdvance
679
685
  }
680
686
  const reason = headChanged || refsChanged || changedPaths.length || controlChanged.length ? 'permission_violation_observed' : null;
681
687
  const toleratedCommitPaths = acceptedAdvance ? [...headAdvance.paths].sort() : [];
682
- return {reason, changedPaths, headChanged, refsChanged, controlChanged: controlChanged.sort(), toleratedRefs: toleratedRefs.sort(), toleratedControl, toleratedCommitPaths};
688
+ return {reason, changedPaths, headChanged, refsChanged, controlChanged: controlChanged.sort(), toleratedRefs: toleratedRefs.sort(), toleratedControl, toleratedCommitPaths, attributedPaths: attributedPaths.sort(byPath)};
683
689
  }
684
690
 
685
- export function toleratedRecord({toleratedRefs = [], toleratedControl = [], toleratedCommitPaths = []} = {}) {
691
+ export function toleratedRecord({toleratedRefs = [], toleratedControl = [], toleratedCommitPaths = [], attributedPaths = []} = {}) {
686
692
  const record = {};
687
693
  for (const [key, names] of [['refs', toleratedRefs], ['control', toleratedControl], ['commitPaths', toleratedCommitPaths]]) {
688
694
  if (!names.length) continue;
689
695
  record[key] = [...names].sort().slice(0, 100);
690
696
  if (names.length > 100) record.truncated = true;
691
697
  }
698
+ if (attributedPaths.length) record.attributed = [...attributedPaths].sort(byPath).slice(0, 100);
699
+ if (attributedPaths.length > 100) record.truncated = true;
692
700
  return Object.keys(record).length ? record : null;
693
701
  }
@@ -9,9 +9,13 @@
9
9
  "id": "scouter",
10
10
  "description": "Read assigned static material and report sources and limits."
11
11
  },
12
+ {
13
+ "id": "architect",
14
+ "description": "Return design, start summary and spec drafts to Orchestrator."
15
+ },
12
16
  {
13
17
  "id": "planner",
14
- "description": "Return design, spec and plan drafts to Orchestrator."
18
+ "description": "Return plan drafts to Orchestrator."
15
19
  },
16
20
  {
17
21
  "id": "implementer",
@@ -32,6 +36,7 @@
32
36
  "roles": [
33
37
  "orchestrator",
34
38
  "scouter",
39
+ "architect",
35
40
  "planner",
36
41
  "implementer",
37
42
  "tester",
@@ -59,6 +64,7 @@
59
64
  "id": "git.specialists-deny",
60
65
  "roles": [
61
66
  "scouter",
67
+ "architect",
62
68
  "planner",
63
69
  "implementer",
64
70
  "tester",
@@ -121,6 +127,7 @@
121
127
  "roles": [
122
128
  "orchestrator",
123
129
  "scouter",
130
+ "architect",
124
131
  "planner",
125
132
  "implementer",
126
133
  "tester",
@@ -151,6 +158,7 @@
151
158
  "roles": [
152
159
  "orchestrator",
153
160
  "scouter",
161
+ "architect",
154
162
  "planner",
155
163
  "implementer",
156
164
  "tester",
@@ -186,7 +194,7 @@
186
194
  "role-ownership"
187
195
  ],
188
196
  "authority": "orchestrator",
189
- "text": "Assign design/brainstorming drafts and first complete spec/plan drafts only to Planner and implementation/configuration/test edits to Implementer. Orchestrator saves and reviews complete spec/plan drafts and directly revises the same document when needed. Missing or failed first drafts do not transfer initial authorship. New product decisions outside approved scope require user input before revision. Orchestrator owns approval requests, preparation, scheduling, evidence, acceptance and completion. Direct implementation remains limited to the existing small, low-risk path. Use a fresh Implementer per top-level task and a fresh Tester per task requiring Tester; Tester findings alone do not create a new task. Record each plan task's current Implementer conversation ID, status, last result and reuse/replacement decision in the canonical handoff record. While approved scope, workspace, ownership and assignment context remain valid, send same-task corrections, rework and rechecks as follow-up work in that conversation; use the current Tester for Tester findings and required Tester rechecks. Once final overall Reviewer review begins on plan work, Reviewer findings, including behavior, repeat Implementer → Reviewer without Tester reassignment until resolved; separate Tester findings remain Implementer → Tester. A completed or idle turn, partial implementation, failed result, missing brief, division by step or file, or Tester/Reviewer finding alone is not a reason to replace the Implementer. Before a same-task replacement, record the prior conversation ID and status, allowed reason and supporting evidence; hold if the reason is not established. Record the new ID after a successful call; reconcile an uncertain result before another assignment. Replace or restart a role only for invalid/unavailable context or a changed task boundary, except that an approved plan or acceptance-criteria amendment requires a fresh Implementer even within the same task. Before Implementer reuse, refresh actual workspace, branch/HEAD and change state. For Tester findings and required Tester rechecks, Tester reruns reproduction and invalidated related checks and reports actor, target state, outcomes and limits. Preserve task-boundary acceptance and the final plan Reviewer correction exception.",
197
+ "text": "Assign design/brainstorming drafts and first complete spec drafts only to Architect, first complete plan drafts only to Planner, and implementation/configuration/test edits to Implementer. Orchestrator saves and reviews complete spec/plan drafts and directly revises the same document when needed. Missing or failed first drafts do not transfer initial authorship. New product decisions outside approved scope require user input before revision. Orchestrator owns approval requests, preparation, scheduling, evidence, acceptance and completion. Direct implementation remains limited to the existing small, low-risk path. Use a fresh Implementer per top-level task and a fresh Tester per task requiring Tester; Tester findings alone do not create a new task. Record each plan task's current Implementer conversation ID, status, last result and reuse/replacement decision in the canonical handoff record. While approved scope, workspace, ownership and assignment context remain valid, send same-task corrections, rework and rechecks as follow-up work in that conversation; use the current Tester for Tester findings and required Tester rechecks. Once final overall Reviewer review begins on plan work, Reviewer findings, including behavior, repeat Implementer → Reviewer without Tester reassignment until resolved; separate Tester findings remain Implementer → Tester. A completed or idle turn, partial implementation, failed result, missing brief, division by step or file, or Tester/Reviewer finding alone is not a reason to replace the Implementer. Before a same-task replacement, record the prior conversation ID and status, allowed reason and supporting evidence; hold if the reason is not established. Record the new ID after a successful call; reconcile an uncertain result before another assignment. Replace or restart a role only for invalid/unavailable context or a changed task boundary, except that an approved plan or acceptance-criteria amendment requires a fresh Implementer even within the same task. Before Implementer reuse, refresh actual workspace, branch/HEAD and change state. For Tester findings and required Tester rechecks, Tester reruns reproduction and invalidated related checks and reports actor, target state, outcomes and limits. Preserve task-boundary acceptance and the final plan Reviewer correction exception.",
190
198
  "controls": {
191
199
  "codex": "prompt",
192
200
  "claude": "prompt",
@@ -216,6 +224,27 @@
216
224
  "grok": "prompt"
217
225
  }
218
226
  },
227
+ {
228
+ "id": "role.architect-draft-only",
229
+ "roles": [
230
+ "architect"
231
+ ],
232
+ "effect": "allow",
233
+ "operations": [
234
+ "draft-response"
235
+ ],
236
+ "evidence": [
237
+ "prepared-target-evidence"
238
+ ],
239
+ "authority": "orchestrator",
240
+ "text": "Return design/brainstorming drafts, start summaries and complete first spec drafts with dependencies, criteria, holds and verification needs in the response. During initial drafting and revisions, report progress only to Orchestrator: briefly state the stage, feedback being applied, actual blocker or next step, without draft prose or excerpts. Return the complete first draft and self-review for Orchestrator review; Orchestrator directly revises the same spec when needed. Raw responses may appear in app/tool surfaces; prompt policy cannot hide them. DO NOT save documents, implement, run checks, prepare targets, request user approval or decide acceptance. The first required document draft uses the verified source and selected target intent before target preparation. Require a verified prepared target before saving or handoff. Route decisions to Orchestrator.",
241
+ "controls": {
242
+ "codex": "prompt",
243
+ "claude": "prompt",
244
+ "gemini": "prompt",
245
+ "grok": "prompt"
246
+ }
247
+ },
219
248
  {
220
249
  "id": "role.planner-draft-only",
221
250
  "roles": [
@@ -230,7 +259,7 @@
230
259
  "approved-spec-before-dependent-plan"
231
260
  ],
232
261
  "authority": "orchestrator",
233
- "text": "Return design/brainstorming drafts and complete first spec/plan drafts with dependencies, criteria, holds and verification needs in the response. During initial drafting and revisions, report progress only to Orchestrator: briefly state the stage, feedback being applied, actual blocker or next step, without draft prose or excerpts. Return the complete first draft and self-review for Orchestrator review; Orchestrator directly revises the same spec or plan when needed. Raw responses may appear in app/tool surfaces; prompt policy cannot hide them. DO NOT save documents, implement, run checks, prepare targets, request user approval or decide acceptance. The first required document draft uses the verified source and selected target intent before target preparation. Require a verified prepared target before saving or handoff. Route decisions to Orchestrator.",
262
+ "text": "Return complete first plan drafts with dependencies, criteria, holds and verification needs in the response. During initial drafting and revisions, report progress only to Orchestrator: briefly state the stage, feedback being applied, actual blocker or next step, without draft prose or excerpts. Return the complete first draft and self-review for Orchestrator review; Orchestrator directly revises the same plan when needed. Raw responses may appear in app/tool surfaces; prompt policy cannot hide them. DO NOT save documents, implement, run checks, prepare targets, request user approval or decide acceptance. The first required document draft uses the verified source and selected target intent before target preparation. Require a verified prepared target before saving or handoff. Route decisions to Orchestrator.",
234
263
  "controls": {
235
264
  "codex": "prompt",
236
265
  "claude": "prompt",
@@ -400,11 +429,10 @@
400
429
  "evidence": [
401
430
  "non-progress-content-change-classification",
402
431
  "actual-approval-chronology",
403
- "approved-revision-content-hash",
404
- "plan-revision-trailers"
432
+ "approved-revision-content-hash"
405
433
  ],
406
434
  "authority": "orchestrator",
407
- "text": "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. Plan-level progress records preserving the approved contract also need no new user approval and alone never trigger the standalone docs(plan) closing commit. 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, or plan-level progress records carried by that commit, and that no pending revision remains. Follow planning, handoff-prep, commit and verification for the full contract.",
435
+ "text": "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. Plan-level progress records preserving the approved contract also need no new user approval and alone never trigger the standalone docs(plan) closing commit. 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 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, or plan-level progress records carried by that commit, and that no pending revision remains. Follow planning, handoff-prep, commit and verification for the full contract.",
408
436
  "controls": {
409
437
  "codex": "prompt",
410
438
  "claude": "prompt",
@@ -428,7 +456,7 @@
428
456
  "preceding-approval"
429
457
  ],
430
458
  "authority": "orchestrator",
431
- "text": "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 only within the design/brainstorming stage while its role, context and source remain valid, except that on the Architectural path that Planner continues as the spec Planner after start confirmation through a spec-stage delta brief; use a fresh Planner instance for each plan stage, and for an Architectural spec stage when that Planner is unavailable or its role, context or source is no longer valid, whose initial brief contains every required field, saved document paths and approved versions (for the Architectural plan stage, the reviewed spec path, version and SHA-256). 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, follow planning.md's design conversation: each Planner response is exactly one of one question, 2–3 approaches with a recommendation and a selection question, one design section with a confirmation question, or the final design (Architectural: the start summary). Ask one question at a time only when the answer changes the outcome and is not already answered; otherwise state the judgment and its reason. Ask an open question about the user's reason before offering options. A clear request may receive a short design for approval at once; when the user says to proceed, stop asking and list the remaining author judgments in the final design or start summary. Relay user answers verbatim and mark added interpretation separately. Every call needs a new user answer or new evidence; without progress, report the blocked criterion, observed facts and needed decision, and hold. Conversation responses use no correction opportunity. Orchestrator reviews the final design once with the fixed checklist, including decision-inventory completeness and no ambiguous scope wording, and sends one consolidated correction using changed fields only. On the Architectural path the start summary receives no consolidated correction; Orchestrator checks its decision inventory and scope notation before presenting it, and the spec draft takes Orchestrator's review and direct revision. 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. For Bounded work, obtain design approval before plan drafting. For Architectural work, obtain one start confirmation (scope and explicit target; no design document or design approval) before spec drafting, let the design Planner continue as the spec Planner (a fresh spec Planner when it is unavailable or invalid), then draft the plan with a fresh Planner, assigning the plan Planner only after the spec is saved and reviewed and its path, version and SHA-256 are fixed; NEVER draft them concurrently; then obtain one combined spec+plan approval. Bounded work has no spec stage; required plans keep their own approval. 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.",
459
+ "text": "Follow planning.md's drafting preparation and review procedure for the drafting role (Architect or Planner), including preflight, ledger, evidence classification, target preparation, preceding approvals, provenance and reference gates. Before drafting-role 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 Architect instance only within the design/brainstorming stage while its role, context and source remain valid, except that on the Architectural path that Architect continues as the spec author after start confirmation through a spec-stage delta brief; use a fresh Planner instance for each plan stage, reusing it only for a budget-hold delta within that stage, and a fresh Architect for an Architectural spec stage when that Architect is unavailable or its role, context or source is no longer valid; each fresh instance's initial brief contains every required field, saved document paths and approved versions (for the Architectural plan stage, the reviewed spec path, version and SHA-256). 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. Reconfirm affected inputs when source, target or scope changed. The drafting role 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, follow planning.md's design conversation: each Architect response is exactly one of one question, 2–3 approaches with a recommendation and a selection question, one design section with a confirmation question, or the final design (Architectural: the start summary). Ask one question at a time only when the answer changes the outcome and is not already answered; otherwise state the judgment and its reason. Ask an open question about the user's reason before offering options. For a clear request, Architect MAY return a short design for approval at once; when the user says to proceed, stop asking and list the remaining author judgments in the final design or start summary. Relay user answers verbatim and mark added interpretation separately. Every call needs a new user answer or new evidence; without progress, report the blocked criterion, observed facts and needed decision, and hold. Conversation responses use no correction opportunity. Orchestrator reviews the final design once with the fixed checklist, including decision-inventory completeness and no ambiguous scope wording, and sends one consolidated correction using changed fields only. On the Architectural path the start summary receives no consolidated correction; Orchestrator checks its decision inventory and scope notation before presenting it, and the spec draft takes Orchestrator's review and direct revision. 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 Architect or Planner only for reformatting, re-expression, save errors or patch-application errors; Orchestrator handles these. Evaluate separate substantive work under the normal drafting-role gate. For Bounded work, Architect drafts the short design; obtain design approval before a fresh Planner drafts any required plan. For Architectural work, obtain one start confirmation (scope and explicit target; no design document or design approval) before spec drafting, let the design Architect continue as the spec author (a fresh Architect when it is unavailable or invalid), then draft the plan with a fresh Planner, assigning the Planner only after the spec is saved and reviewed and its path, version and SHA-256 are fixed; NEVER draft them concurrently; then obtain one combined spec+plan approval. Bounded work has no spec stage; required plans keep their own approval. Add no fixed call cap or profile call-count conditions, and NEVER accept an incomplete draft. Keep user progress brief and based on drafting-role status without relaying draft content. At approval, present the integrated, saved and reviewed Markdown without repeating its body in chat.",
432
460
  "controls": {
433
461
  "codex": "prompt",
434
462
  "claude": "prompt",
@@ -690,6 +718,7 @@
690
718
  "roles": [
691
719
  "orchestrator",
692
720
  "scouter",
721
+ "architect",
693
722
  "planner",
694
723
  "implementer",
695
724
  "tester",
@@ -1,8 +1,8 @@
1
1
  import {runtimeRegistryOf} from './platform-registry.mjs';
2
2
 
3
- export const ROUTING_ROLES = Object.freeze(['arc_scouter', 'arc_planner', 'arc_implementer', 'arc_tester', 'arc_reviewer']);
3
+ export const ROUTING_ROLES = Object.freeze(['arc_scouter', 'arc_architect', 'arc_planner', 'arc_implementer', 'arc_tester', 'arc_reviewer']);
4
4
  export const LEGACY_ROUTING_ROLES = Object.freeze({arc_qa: 'arc_tester'});
5
- export const ROUTING_CONFIG_VERSION = 3;
5
+ export const ROUTING_CONFIG_VERSION = 4;
6
6
  const validText = value => typeof value === 'string' && value.length > 0 && value === value.trim() && !/[\p{Cc}\u2028\u2029]/u.test(value);
7
7
  const exact = (value, keys) => value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key));
8
8
  const v1Platforms = Object.freeze(['codex', 'claude']);
@@ -22,13 +22,18 @@ export function validRoleValues(platform, model, effort, {runtimePlatforms} = {}
22
22
  }
23
23
  export function validateRoleRoutingConfig(config, opts = {}) {
24
24
  const keys = ['version', 'revision', 'platforms', 'roles'];
25
- if (!(exact(config, keys) || (config?.version === 1 && exact(config, ['version', 'revision', 'roles']))) || ![1, 2, ROUTING_CONFIG_VERSION].includes(config.version) || !validText(config.revision)) throw Error('Invalid role routing configuration');
25
+ if (!(exact(config, keys) || (config?.version === 1 && exact(config, ['version', 'revision', 'roles']))) || ![1, 2, 3, ROUTING_CONFIG_VERSION].includes(config.version) || !validText(config.revision)) throw Error('Invalid role routing configuration');
26
26
  let roles = config.roles;
27
27
  if (roles && typeof roles === 'object' && !Array.isArray(roles) && Object.hasOwn(roles, 'arc_qa')) {
28
- if (config.version === ROUTING_CONFIG_VERSION || Object.hasOwn(roles, 'arc_tester')) throw Error('Invalid role routing configuration');
28
+ if (config.version >= 3 || Object.hasOwn(roles, 'arc_tester')) throw Error('Invalid role routing configuration');
29
29
  roles = Object.fromEntries(Object.entries(roles).map(([role, fields]) => [Object.hasOwn(LEGACY_ROUTING_ROLES, role) ? LEGACY_ROUTING_ROLES[role] : role, fields]));
30
30
  }
31
+ if (config.version < ROUTING_CONFIG_VERSION && roles && typeof roles === 'object' && !Array.isArray(roles)
32
+ && !Object.hasOwn(roles, 'arc_architect') && Object.hasOwn(roles, 'arc_planner')) {
33
+ roles = {...roles, arc_architect: structuredClone(roles.arc_planner)};
34
+ }
31
35
  if (!exact(roles, ROUTING_ROLES)) throw Error('Invalid role routing configuration');
36
+ roles = Object.fromEntries(ROUTING_ROLES.map(role => [role, roles[role]]));
32
37
  const registry = runtimeRegistryOf(opts);
33
38
  const platforms = config.version === 1 && !Object.hasOwn(config, 'platforms') ? [...v1Platforms] : config.platforms;
34
39
  if (!Array.isArray(platforms) || platforms.length < 2 || new Set(platforms).size !== platforms.length || platforms.some(id => !registry.isPlatformId(id))) throw Error('Invalid role routing platforms');
@@ -11,7 +11,7 @@ import {GROK_CONTRACT, normalizeGrokStreamEvent, evaluateGrokObservation} from '
11
11
  import {GROK_SANDBOX_RELATIVE, grokSandboxProfileName, renderGrokSandboxProfile, grokProfileCovered, inspectGrokProfileSlot, checkGrokHome, createGrokSandboxProfile, verifyGrokSandboxProfile, removeGrokSandboxProfile, grokEventsBaseline, readGrokProfileApplied, grokConfigSecurityProjection} from './grok-sandbox.mjs';
12
12
  import {GEMINI_CONTRACT, normalizeGeminiStreamEvent, evaluateGeminiObservation} from './gemini-stream.mjs';
13
13
  import {CODEX_PROFILE_SANDBOX_TYPE, DEFAULT_POLICY, DESCENDANT_LIMIT, DESCENDANT_SAMPLE_MS, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
14
- import {readLease, writeLease, writeHeartbeat, cancelRequested, dispatchDirectory, TERMINAL_STATES} from './role-dispatch-store.mjs';
14
+ import {readLease, writeLease, writeHeartbeat, cancelRequested, dispatchDirectory, TERMINAL_STATES, listLeases, readWorktreeRecord, worktreeWriters} from './role-dispatch-store.mjs';
15
15
  import {withRoutingLock, readActivation, resolveRuntimeHomes} from './role-routing.mjs';
16
16
  import {resolveLocalCli, localCliEnvironment} from './local-cli.mjs';
17
17
  import {parseCompositeProfile, buildBridgeArgs, argsDigest, ROLE_BRIDGE_PERMISSIONS} from './role-bridge-args.mjs';
@@ -743,6 +743,7 @@ export async function runSupervisor(options) {
743
743
  control: await snapshotControlFiles({gitCommonDir: target.gitCommonDir, gitDir: target.gitDir, worktree: target.realpath, extra}),
744
744
  });
745
745
  let before;
746
+ const sinceMs = Date.now();
746
747
  try { before = await snapshot(); } catch { return await failWithProfileCleanup('execution_failed'); }
747
748
 
748
749
  if (invocation.promptFile) {
@@ -925,9 +926,22 @@ export async function runSupervisor(options) {
925
926
  }
926
927
 
927
928
  let after = null;
929
+ const otherOwners = await locked(async () => {
930
+ const worktree = target.realpath;
931
+ const own = await readWorktreeRecord(codexHome, dispatchId);
932
+ if (own?.segment !== lease.segment || own.worktree !== worktree) return [];
933
+ const leases = await listLeases(codexHome, {runtimePlatforms});
934
+ const records = new Map();
935
+ for (const item of leases) {
936
+ if (item.dispatchId !== dispatchId && item.route === 'bridge' && (item.role === 'arc_implementer' || item.role === 'arc_tester')) {
937
+ records.set(item.dispatchId, await readWorktreeRecord(codexHome, item.dispatchId));
938
+ }
939
+ }
940
+ return worktreeWriters({leases, records, dispatchId, worktree, terminalSinceMs: sinceMs, excludeUnknown: true});
941
+ }).catch(() => []);
928
942
  try { after = await snapshot(); } catch { after = null; }
929
943
  const headAdvance = after ? await observeHeadAdvance(target.realpath, before, after, lease.role, lease.allowedPaths) : null;
930
- const violations = after ? detectViolations({role: lease.role, allowedPaths: lease.allowedPaths, before, after, headAdvance}) : {reason: null, changedPaths: [], headChanged: false, refsChanged: false, controlChanged: [], toleratedRefs: [], toleratedControl: [], toleratedCommitPaths: []};
944
+ const violations = after ? detectViolations({role: lease.role, allowedPaths: lease.allowedPaths, before, after, headAdvance, otherOwners}) : {reason: null, changedPaths: [], headChanged: false, refsChanged: false, controlChanged: [], toleratedRefs: [], toleratedControl: [], toleratedCommitPaths: [], attributedPaths: []};
931
945
  const codes = [];
932
946
  if (state.mismatch) codes.push(state.mismatch);
933
947
  if (state.internal) codes.push(state.internal);