@yunhozz/arc 0.4.6 → 0.4.7

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 (75) hide show
  1. package/MANIFEST.sha256 +74 -69
  2. package/README.md +35 -51
  3. package/claude/agents/arc-implementer.md +2 -2
  4. package/claude/agents/arc-planner.md +1 -1
  5. package/claude/agents/arc-qa.md +1 -1
  6. package/claude/agents/arc-reviewer.md +1 -1
  7. package/claude/agents/arc-scouter.md +1 -1
  8. package/claude/skill/references/coordination.md +2 -2
  9. package/claude/skill/references/handoff-prep.md +5 -0
  10. package/claude/skill/references/handoff.md +2 -2
  11. package/claude/skill/references/planning.md +2 -2
  12. package/claude/skill/references/verification.md +16 -3
  13. package/claude/skill/references/worktree-creation.md +2 -2
  14. package/codex/agents/arc-implementer.toml +1 -1
  15. package/codex/agents/arc-planner.toml +1 -1
  16. package/codex/agents/arc-qa.toml +1 -1
  17. package/codex/agents/arc-reviewer.toml +1 -1
  18. package/codex/agents/arc-scouter.toml +1 -1
  19. package/codex/skill/references/coordination.md +2 -2
  20. package/codex/skill/references/handoff-prep.md +5 -0
  21. package/codex/skill/references/handoff.md +2 -2
  22. package/codex/skill/references/planning.md +2 -2
  23. package/codex/skill/references/verification.md +15 -2
  24. package/gemini/agents/arc-implementer.md +2 -2
  25. package/gemini/agents/arc-planner.md +1 -1
  26. package/gemini/agents/arc-qa.md +1 -1
  27. package/gemini/agents/arc-reviewer.md +1 -1
  28. package/gemini/agents/arc-scouter.md +1 -1
  29. package/gemini/skill/references/coordination.md +3 -3
  30. package/gemini/skill/references/handoff-prep.md +5 -0
  31. package/gemini/skill/references/handoff.md +2 -2
  32. package/gemini/skill/references/planning.md +2 -2
  33. package/gemini/skill/references/verification.md +16 -3
  34. package/gemini/skill/references/worktree-creation.md +2 -2
  35. package/grok/agents/arc-implementer.md +2 -2
  36. package/grok/agents/arc-planner.md +1 -1
  37. package/grok/agents/arc-qa.md +1 -1
  38. package/grok/agents/arc-reviewer.md +1 -1
  39. package/grok/agents/arc-scouter.md +1 -1
  40. package/grok/skill/references/coordination.md +2 -2
  41. package/grok/skill/references/handoff-prep.md +5 -0
  42. package/grok/skill/references/handoff.md +2 -2
  43. package/grok/skill/references/planning.md +2 -2
  44. package/grok/skill/references/verification.md +16 -3
  45. package/grok/skill/references/worktree-creation.md +2 -2
  46. package/lib/cli/root.mjs +1 -1
  47. package/lib/management/reapply.mjs +117 -0
  48. package/lib/management/update.mjs +59 -5
  49. package/lib/npm/upgrade.mjs +6 -2
  50. package/lib/policy/role-policy.json +1 -1
  51. package/lib/prompts/agent-fragments.json +5 -5
  52. package/lib/runtime/role-bridge.mjs +10 -1
  53. package/lib/runtime/role-dispatch-policy.mjs +4 -0
  54. package/lib/runtime/role-observe.mjs +192 -14
  55. package/lib/runtime/role-supervisor.mjs +268 -23
  56. package/lib/tui/app.mjs +3 -39
  57. package/lib/tui/interface.mjs +40 -0
  58. package/lib/tui/setup.mjs +27 -16
  59. package/lib/watch/args.mjs +12 -27
  60. package/lib/watch/dispatch.mjs +2 -2
  61. package/lib/watch/index.mjs +38 -26
  62. package/lib/watch/markdown.mjs +232 -0
  63. package/lib/watch/menu.mjs +43 -0
  64. package/lib/watch/model.mjs +7 -3
  65. package/lib/watch/render.mjs +28 -67
  66. package/lib/watch/scope.mjs +1 -5
  67. package/lib/watch/status-line.mjs +2 -4
  68. package/lib/watch/text-width.mjs +43 -0
  69. package/lib/watch/watcher.mjs +17 -36
  70. package/package.json +1 -1
  71. package/shared/skill/runtime/role-bridge.mjs +10 -1
  72. package/shared/skill/runtime/role-dispatch-policy.mjs +4 -0
  73. package/shared/skill/runtime/role-observe.mjs +192 -14
  74. package/shared/skill/runtime/role-policy.json +1 -1
  75. package/shared/skill/runtime/role-supervisor.mjs +268 -23
@@ -13,11 +13,9 @@ function watchShimmerIntensity(index, tick) {
13
13
  return Math.max(0, 1 - Math.abs(index - c) / R) ** 2;
14
14
  }
15
15
 
16
- export function watchLocationLabel({mode, dir, session, home}) {
16
+ export function watchLocationLabel({dir, home}) {
17
17
  let label = dir;
18
- if (session) label = `session ${session}`;
19
- else if (mode === 'all') label = 'all directories';
20
- else if (dir === home) label = '~';
18
+ if (dir === home) label = '~';
21
19
  else if (home && dir.startsWith(home + path.sep)) label = '~' + dir.slice(home.length);
22
20
  return sanitizeText(label);
23
21
  }
@@ -0,0 +1,43 @@
1
+ const graphemes = new Intl.Segmenter(undefined, {granularity:'grapheme'});
2
+ const zeroWidth = /^[\u0300-\u036f\u200b-\u200f\ufe00-\ufe0f]+$/u;
3
+ const wide = /[\u1100-\u115f\u2e80-\u303e\u3041-\u33ff\u3400-\u4dbf\u4e00-\u9fff\ua000-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6\u{1f300}-\u{1f64f}\u{1f900}-\u{1f9ff}\u{20000}-\u{3fffd}]/u;
4
+ function graphemeWidth(text) {
5
+ if (zeroWidth.test(text)) return 0;
6
+ if (wide.test(text) || /\p{Emoji_Presentation}/u.test(text) || (/[\u200d\ufe0f]/u.test(text) && /\p{Extended_Pictographic}/u.test(text))) return 2;
7
+ return 1;
8
+ }
9
+
10
+ export function displayWidth(text) {
11
+ let width = 0;
12
+ for (const {segment} of graphemes.segment(text)) width += graphemeWidth(segment);
13
+ return width;
14
+ }
15
+
16
+ // Return UTF-16 offsets so styled callers can wrap before adding SGR codes.
17
+ export function wrapLineRanges(text, avail, {preserveWhitespace = false} = {}) {
18
+ const parts = Array.from(graphemes.segment(text), ({segment, index}) => ({segment, index, width:graphemeWidth(segment)}));
19
+ const lines = [];
20
+ let start = 0;
21
+ while (start < parts.length) {
22
+ let end = start, cols = 0, space = -1, hasContent = false;
23
+ while (end < parts.length && cols + parts[end].width <= avail) {
24
+ if (parts[end].segment === ' ') { if (hasContent) space = end; }
25
+ else hasContent = true;
26
+ cols += parts[end++].width;
27
+ }
28
+ if (!preserveWhitespace && parts[end]?.segment === ' ' && hasContent) space = end;
29
+ const useSpace = !preserveWhitespace && end < parts.length && space >= 0;
30
+ const overflows = end === start;
31
+ const pieceEnd = useSpace ? space : Math.max(start + 1, end);
32
+ const from = parts[start].index;
33
+ const to = parts[pieceEnd]?.index ?? text.length;
34
+ if (preserveWhitespace || text.slice(from, to).trim()) lines.push({from, to, overflows});
35
+ start = useSpace ? space + 1 : pieceEnd;
36
+ }
37
+ return lines.length ? lines : [{from:0, to:0}];
38
+ }
39
+
40
+ export function wrapLine(text, avail) {
41
+ if (avail <= 0) return [text];
42
+ return wrapLineRanges(text, avail).map(({from, to}) => text.slice(from, to));
43
+ }
@@ -1,6 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import fsp from 'node:fs/promises';
3
- import {WATCH_LIMITS as L, MESSAGE_KINDS} from './model.mjs';
3
+ import {WATCH_LIMITS as L, MESSAGE_KINDS, classifyMessageKind} from './model.mjs';
4
4
  import {sanitizeText, sanitizeMessage, isVisible} from './policy.mjs';
5
5
  import {topLabel, childLabel, dispatchLabel, roleFromName} from './labels.mjs';
6
6
  import {createCodexState, normalizeCodexLine, codexLineCwd} from './normalize-codex.mjs';
@@ -18,15 +18,15 @@ import {GIT_ALLOWED} from './git.mjs';
18
18
  export function createWatcher({options, homes, scope: initialScope, git, now, registry = DEFAULT_PLATFORM_REGISTRY, dependencies = {}}) {
19
19
  const {readClaudeHead: claudeHead = readClaudeHead, readCodexMeta: codexMeta = readCodexMeta,
20
20
  lstat = fsp.lstat, maxKnown = L.maxKnown, createClaudeDiscovery: claudeDiscovery = createClaudeDiscovery, createDispatchIndex: dispatchIndex = createDispatchIndex} = dependencies;
21
- const platforms = options.platforms ?? ['codex','claude'];
22
- const session = options.session ?? null, verbose = Boolean(options.verbose);
21
+ const platforms = options.platforms ?? registry.byDisplayOrder().filter(d => d.capabilities.watch.state==='verified').map(d => d.id);
22
+ const verbose = Boolean(options.verbose);
23
23
  const tailCount = options.tail ?? L.defaultTail;
24
24
  let scope = initialScope, closed = false, started = false;
25
- let lastDiscovery = -Infinity, lastRefresh = now(), capped = false, waiting = false;
25
+ let lastDiscovery = -Infinity, lastRefresh = now(), capped = false;
26
26
  const followed = new Map(), pending = new Map(), ignored = new Map(), detached = new Map();
27
27
  const seenAtStart = new Map(), heads = new Map(), metas = new Map(), agentMetas = new Map(), childLists = new Map();
28
28
  const known = new Map(), latestCwds = new Map();
29
- const compressed = new Set(), missingDispatch = new Set(), repos = new Map();
29
+ const compressed = new Set(), missingDispatch = new Set();
30
30
  const rootsByCwd = new Map(), gitTopByCwd = new Map(), shellRoots = new Map();
31
31
  const nestedChecks = new Map(), nestedFailures = new Map();
32
32
  let lastNestedRefresh = -Infinity;
@@ -38,7 +38,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
38
38
  const debug = (out, text) => { if (verbose) out.push(notice(text)); };
39
39
  const sort = events => events.sort((a,b) => (Date.parse(a.ts) || 0) - (Date.parse(b.ts) || 0));
40
40
  const clean = event => {
41
- const e = {...event};
41
+ const e = {...event,kind:classifyMessageKind(event)};
42
42
  if (e.text !== undefined) e.text = MESSAGE_KINDS.includes(e.kind) ? sanitizeMessage(e.text) : sanitizeText(e.text);
43
43
  if (e.tool !== undefined) e.tool = sanitizeText(e.tool);
44
44
  if (e.skill !== undefined) e.skill = sanitizeText(e.skill);
@@ -47,18 +47,14 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
47
47
  if (e.paths) e.paths = e.paths.map(sanitizeText);
48
48
  return e;
49
49
  };
50
- const selectedDispatch = ref => !session || ref.dispatchId === session || ref.sessionIds.includes(session);
51
- const dispatchInScope = ref => ref.inScope && (scope.kind==='all' || scope.kind==='session'
52
- || (ref.cwd ? inScope(scope,ref.cwd) : [...followed.values()].some(row=>ref.sessionIds.includes(row.id) && cwdInScope(row.cwd))));
53
- const allowedDispatch = ref => dispatchInScope(ref) && selectedDispatch(ref);
50
+ const dispatchInScope = ref => ref.inScope && (ref.cwd ? inScope(scope,ref.cwd)
51
+ : [...followed.values()].some(row=>ref.sessionIds.includes(row.id) && cwdInScope(row.cwd)));
54
52
  function mapped(row) {
55
53
  const ref = dispatch.bySession(row.id);
56
- return ref && ref.inScope && (scope.kind==='all' || scope.kind==='session'
57
- || (ref.cwd ? inScope(scope,ref.cwd) : cwdInScope(row.cwd))) ? ref : null;
54
+ return ref && ref.inScope && (ref.cwd ? inScope(scope,ref.cwd) : cwdInScope(row.cwd)) ? ref : null;
58
55
  }
59
56
  const selectedRoot = cwd => path.resolve(cwd)===scope.roots[0] || realPath(cwd)===scope.roots[0];
60
57
  function cwdInScope(cwd) {
61
- if (scope.kind==='all' || scope.kind==='session') return true;
62
58
  if (!cwd || !inScope(scope,cwd)) return false;
63
59
  return scope.kind!=='repo' || selectedRoot(cwd) || nestedChecks.get(cwd)?.inside===true;
64
60
  }
@@ -102,7 +98,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
102
98
  return {resolved:!row.parentId,desktop};
103
99
  }
104
100
  function lineGate(row) {
105
- return scope.kind==='all' || scope.kind==='session' || Boolean(mapped(row)) || cwdInScope(row.cwd);
101
+ return Boolean(mapped(row)) || cwdInScope(row.cwd);
106
102
  }
107
103
  async function setCwd(row, cwd, out) {
108
104
  row.state.cwd=cwd;
@@ -173,7 +169,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
173
169
  }
174
170
  for (const e of normalized) {
175
171
  if (['turn_end','turn_failed'].includes(e.kind)) row.active = false;
176
- else if (['turn_start','user','agent','reasoning','command','tool','tool_failed','file_change','file_create','file_delete','spawn','approval'].includes(e.kind)) row.active = true;
172
+ else if (MESSAGE_KINDS.includes(e.kind) || ['turn_start','reasoning','command','tool','tool_failed','file_change','file_create','file_delete','spawn','approval'].includes(e.kind)) row.active = true;
177
173
  if (!inside) continue;
178
174
  if (e.kind==='command' && e.skillOnly && !verbose) continue;
179
175
  const shell = shellRoots.get(row.gitTop);
@@ -202,18 +198,12 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
202
198
  row.held=[]; delete row.holdUntil;
203
199
  }
204
200
  }
205
- async function rememberRepo(cwd) {
206
- if (scope.kind !== 'all' && scope.kind !== 'session') return;
207
- if (repos.has(cwd) || repos.size >= L.maxRepos) return;
208
- repos.set(cwd, await git(cwd,GIT_ALLOWED[1]));
209
- }
210
201
  async function scanDispatch() {
211
- const dirs = [...new Set([scope.gitCommonDir,...repos.values()].filter(Boolean).map(s=>s.trim()))];
212
- return dispatch.scan({gitCommonDirs:dirs,includeAllLeases:scope.kind==='all'||scope.kind==='session'});
202
+ return dispatch.scan({gitCommonDirs:scope.gitCommonDir ? [scope.gitCommonDir] : []});
213
203
  }
214
204
  function dispatchEvents(updates, startup, out) {
215
205
  for (const {ref,first} of updates) {
216
- if (!allowedDispatch(ref)) continue;
206
+ if (!dispatchInScope(ref)) continue;
217
207
  if (startup && (tailCount === 0 || now()-Date.parse(ref.updatedAt) > L.historyWindowMs || !Number.isFinite(Date.parse(ref.updatedAt)))) continue;
218
208
  const followedRow = [...followed.values()].find(row=>ref.sessionIds.includes(row.id));
219
209
  const platform = ref.childPlatform ?? followedRow?.platform;
@@ -230,13 +220,11 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
230
220
  function eligible(row) {
231
221
  if (!platforms.includes(row.platform) || row.origin === 'Codex Desktop') return false;
232
222
  if (row.parentId) {
233
- if (scope.kind==='all' || scope.kind==='session') return followed.has(row.parentId);
234
223
  const chain=ancestry(row);
235
224
  if (chain.desktop) {ignored.set(row.file,row.size);return false;}
236
225
  return chain.resolved && anyCwdInScope(row);
237
226
  }
238
227
  const ref = mapped(row);
239
- if (session) return row.id === session || Boolean(ref && selectedDispatch(ref));
240
228
  return Boolean(ref) || anyCwdInScope(row);
241
229
  }
242
230
  async function attach(row, startup, out) {
@@ -366,7 +354,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
366
354
  }
367
355
  async function discover(startup, out) {
368
356
  const rows=[];
369
- let updates = scope.kind === 'all' || scope.kind === 'session' ? null : await scanDispatch();
357
+ const updates = await scanDispatch();
370
358
  for (const file of pending.keys()) if (!await details(file)) pending.delete(file);
371
359
  if (homes.codex && platforms.includes('codex')) {
372
360
  for (const item of await codexCandidates(startup)) {
@@ -409,10 +397,6 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
409
397
  }
410
398
  }
411
399
  }
412
- for (const row of rows) {
413
- await rememberRepo(row.cwd);
414
- }
415
- updates ??= await scanDispatch();
416
400
  rows.sort((a,b)=>b.mtimeMs-a.mtimeMs||a.file.localeCompare(b.file));
417
401
  let remaining=rows.filter(row=> {
418
402
  if (followed.has(row.id) || ignored.get(row.file)===row.size) return false;
@@ -448,8 +432,8 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
448
432
  }
449
433
  for (const row of remaining) {
450
434
  const chain=ancestry(row);
451
- const missingParent=scope.kind==='all'||scope.kind==='session' ? !followed.has(row.parentId) : !chain.resolved;
452
- if ((scope.kind==='repo'||scope.kind==='dir') && row.parentId && (!missingParent || chain.desktop)) pending.delete(row.file);
435
+ const missingParent=!chain.resolved;
436
+ if (row.parentId && (!missingParent || chain.desktop)) pending.delete(row.file);
453
437
  if (row.parentId && row.origin!=='Codex Desktop' && missingParent && !chain.desktop) {
454
438
  const wait=pending.get(row.file) ?? {...row,until:now()+L.holdMs};
455
439
  if (now()>=wait.until) {pending.delete(row.file);ignored.set(row.file,row.size);debug(out,`parent session not found for ${row.id}`);}
@@ -466,9 +450,6 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
466
450
  emit(row,[],out);
467
451
  }
468
452
  dispatchEvents(updates,startup,out);
469
- if (session && !waiting && ![...followed.values()].some(row=>row.id===session||mapped(row)?.dispatchId===session) && !dispatch.byId(session)?.inScope) {
470
- debug(out,`waiting for session ${session}`);waiting=true;
471
- }
472
453
  lastDiscovery=now();
473
454
  }
474
455
  async function poll(out) {
@@ -574,7 +555,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
574
555
  const storeDir = store.kind === 'none' && homes.codex && registry.isPlatformId('codex')
575
556
  ? path.join(homes.codex, 'arc-role-dispatch') : store.dir;
576
557
  dispatch = dispatchIndex({storeDir});
577
- const description=session?`session ${session}`:scope.kind==='repo'?`scope ${scope.roots[0]} (${scope.roots.length} worktrees)`:scope.kind==='dir'?`scope ${scope.roots[0]}`:'scope all';
558
+ const description=`scope ${scope.roots[0]}`+(scope.kind==='repo'?` (${scope.roots.length} worktrees)`:'');
578
559
  const out=[];
579
560
  if (store.kind === 'ambiguous') out.push(notice('dispatch store ambiguous'));
580
561
  await discover(true,out);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yunhozz/arc",
3
- "version": "0.4.6",
3
+ "version": "0.4.7",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org/"
@@ -6,7 +6,7 @@ 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 {readLease, writeLease, listLeases, readHostLimits, NON_TERMINAL_STATES, readHeartbeat, requestCancel, clearCancel, TERMINAL_STATES, validateLease} from './role-dispatch-store.mjs';
8
8
  import {withRoutingLock, readActivation, readRevision, authenticate, resolveRuntimeHomes, locateAnchorHome, probeHomeWritable} from './role-routing.mjs';
9
- import {SUPERVISOR_IMPLEMENTATIONS, startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation} from './role-supervisor.mjs';
9
+ import {SUPERVISOR_IMPLEMENTATIONS, startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation, reapRecordedDescendants} from './role-supervisor.mjs';
10
10
 
11
11
  export const heldRoutingResult=(code,releaseCondition)=>({decision:'hold',routeStatus:'held',supportStatus:'unverified',route:null,executionEnvironment:null,hostPlatform:null,role:null,requested:null,authentication:null,reasons:[{code,releaseCondition}]});
12
12
 
@@ -233,6 +233,14 @@ export async function cancelRoleDispatch({context,dispatchId,now=Date.now(),poli
233
233
  if(!killed&&Date.now()>=begin+graceMs){signalGroup(pid,'SIGKILL');killed=true;}
234
234
  await sleep(25);gone=!groupExists(pid);
235
235
  }
236
+ let escapes={};
237
+ if(!direct.lease.supervisor||!processAlive(direct.lease.supervisor)){
238
+ try{
239
+ const target=await resolveWorktree(context.cwd);
240
+ const directory=segmentDirectory(target,direct.lease.workflowId,dispatchId,direct.lease.segment??0);
241
+ escapes=await reapRecordedDescendants(directory,direct.lease,{graceMs});
242
+ }catch{/* A missing worktree does not change the group cancellation result. */}
243
+ }
236
244
  if(!gone)result=view(direct.lease,'hold');
237
245
  else{
238
246
  try{
@@ -248,6 +256,7 @@ export async function cancelRoleDispatch({context,dispatchId,now=Date.now(),poli
248
256
  else return hold(context,dispatchId,classifyLock(error),error);
249
257
  }
250
258
  }
259
+ if(result&&escapes.escapedDescendants)result={...result,...escapes};
251
260
  }
252
261
  if(residual)result.residualPaths=residual;
253
262
  return result;
@@ -40,11 +40,15 @@ export const OBSERVE_MAX_WAIT_MS = 540000;
40
40
  export const BRIEF_MAX_BYTES = 262144;
41
41
  export const EVENTS_MAX_BYTES = 4194304;
42
42
  export const CANCEL_GRACE_MS = 10000;
43
+ export const DESCENDANT_SAMPLE_MS = 1000;
44
+ export const DESCENDANT_LIMIT = 256;
43
45
  export const LOCK_RETRY_MS = 2000;
44
46
  export const LEASE_RETENTION_MS = 2592000000;
45
47
  export const PROBE_TIMEOUT_MS = 10000;
46
48
 
47
49
  export const DEFAULT_POLICY = Object.freeze({
50
+ descendantSampleMs: DESCENDANT_SAMPLE_MS,
51
+ descendantLimit: DESCENDANT_LIMIT,
48
52
  gates: BRIDGE_GATE_RESULTS,
49
53
  claudeSandboxSettings: CLAUDE_SANDBOX_SETTINGS,
50
54
  codexDelegationCallNames: CODEX_DELEGATION_CALL_NAMES,
@@ -244,15 +244,28 @@ const gitEnv = () => {
244
244
  const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.toUpperCase().startsWith('GIT_')));
245
245
  return Object.assign(env, {GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : '/dev/null', GIT_OPTIONAL_LOCKS: '0', GIT_NO_REPLACE_OBJECTS: '1', GIT_NO_LAZY_FETCH: '1', GIT_TERMINAL_PROMPT: '0'});
246
246
  };
247
- const git = async (cwd, args, {allowFailure = false} = {}) => {
247
+ const runGit = (cwd, args, env = gitEnv()) =>
248
+ execFileAsync('git', ['--no-optional-locks', '--no-pager', '-c', 'core.fsmonitor=false', ...args], {cwd, env, encoding: 'utf8', timeout: 60000, maxBuffer: 256 * 1024 * 1024});
249
+ const git = async (cwd, args, {allowFailure = false, allowUnsupportedZ = false} = {}) => {
250
+ const env = gitEnv();
251
+ if (allowUnsupportedZ) env.LC_ALL = 'C';
248
252
  try {
249
- const {stdout} = await execFileAsync('git', ['--no-pager', '-c', 'core.fsmonitor=false', ...args], {cwd, env: gitEnv(), encoding: 'utf8', timeout: 60000, maxBuffer: 256 * 1024 * 1024});
253
+ const {stdout} = await runGit(cwd, args, env);
250
254
  return stdout;
251
255
  } catch (error) {
252
256
  if (allowFailure) return null;
257
+ if (allowUnsupportedZ && error.code === 129 && /^error: unknown (?:switch|option) `-?z'(?:\r?\n|$)/.test(error.stderr)) return null;
253
258
  throw Error(`Git observation failed: ${args[0]}${error.code ? ` (${error.code})` : ''}`);
254
259
  }
255
260
  };
261
+ async function gitExitCode(cwd, args) {
262
+ try {
263
+ await runGit(cwd, args);
264
+ return 0;
265
+ } catch (error) {
266
+ return typeof error.code === 'number' ? error.code : null;
267
+ }
268
+ }
256
269
  const sha256 = value => crypto.createHash('sha256').update(value).digest('hex');
257
270
 
258
271
  /** Resolve the worktree root for a cwd that may be a subdirectory. */
@@ -471,11 +484,54 @@ export function allowedPathsCoverControl(allowedPaths) {
471
484
  });
472
485
  }
473
486
 
474
- /** Snapshot of HEAD, branch, every ref (name and object) and every changed or untracked path; paths are relative to the worktree root even when worktree is a subdirectory. */
487
+ const realpathOrOriginal = filename => fsp.realpath(filename).catch(() => filename);
488
+
489
+ async function snapshotWorktreeBranches(root) {
490
+ const args = ['worktree', 'list', '--porcelain'];
491
+ const nulOutput = await git(root, [...args, '-z'], {allowUnsupportedZ: true});
492
+ const fallback = nulOutput === null;
493
+ const raw = nulOutput ?? await git(root, args);
494
+ const separator = fallback ? '\n' : '\0';
495
+ const recordSeparator = separator.repeat(2);
496
+ if (!raw.endsWith(recordSeparator)) return null;
497
+ const branches = new Map();
498
+ for (const record of raw.slice(0, -recordSeparator.length).split(recordSeparator)) {
499
+ const [header, ...attributes] = record.split(separator);
500
+ const filename = header.slice(9);
501
+ if (!header.startsWith('worktree ') || !path.isAbsolute(filename)) return null;
502
+ let branch;
503
+ let prunable = false;
504
+ for (const attribute of attributes) {
505
+ const ref = /^branch (refs\/heads\/[^ \x00-\x1f\x7f]+)$/.exec(attribute);
506
+ if (ref || attribute === 'detached' || attribute === 'bare') {
507
+ if (branch !== undefined) return null;
508
+ branch = ref ? ref[1] : null;
509
+ } else if (/^prunable(?: |$)/.test(attribute)) {
510
+ prunable = true;
511
+ } else if (!/^HEAD (?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(attribute) &&
512
+ !/^locked(?: |$)/.test(attribute)) {
513
+ return null;
514
+ }
515
+ }
516
+ if (branch === undefined) return null;
517
+ const resolved = await fsp.realpath(filename).catch(() => null);
518
+ if (fallback && !prunable) {
519
+ const stat = resolved && await fsp.stat(resolved).catch(() => null);
520
+ if (!stat?.isDirectory()) return null;
521
+ }
522
+ const worktree = resolved ?? filename;
523
+ if (branches.has(worktree)) return null;
524
+ branches.set(worktree, branch);
525
+ }
526
+ return Object.fromEntries(branches);
527
+ }
528
+
529
+ /** Snapshot of HEAD, branch, refs, registered worktree branches and changed or untracked paths relative to the worktree root. */
475
530
  export async function snapshotWorktree(worktree) {
476
- const root = (await git(worktree, ['rev-parse', '--show-toplevel'])).trim();
531
+ const root = await realpathOrOriginal((await git(worktree, ['rev-parse', '--show-toplevel'])).replace(/\n$/, ''));
477
532
  const head = (await git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], {allowFailure: true}))?.trim() || null;
478
533
  const branch = (await git(root, ['symbolic-ref', '--quiet', '--short', 'HEAD'], {allowFailure: true}))?.trim() || null;
534
+ const branchRef = (await git(root, ['symbolic-ref', '--quiet', 'HEAD'], {allowFailure: true}))?.trim() || null;
479
535
  const refs = {};
480
536
  for (const line of (await git(root, ['for-each-ref', '--format=%(refname) %(objectname)'])).split('\n')) {
481
537
  const at = line.lastIndexOf(' ');
@@ -490,21 +546,143 @@ export async function snapshotWorktree(worktree) {
490
546
  entries.set(file, `${code}:${await contentDigest(path.join(root, file))}`);
491
547
  if (code.includes('R') || code.includes('C')) { const origin = tokens[++i]; if (origin) entries.set(origin, `${code}:${sha256('deleted')}`); }
492
548
  }
493
- return {head, branch, refs, entries};
549
+ return {head, branch, branchRef, refs, entries, worktreeRoot: root, worktreeBranches: await snapshotWorktreeBranches(root)};
550
+ }
551
+
552
+ function otherWorktreeBranches(before, after) {
553
+ const branches = new Set();
554
+ for (const snapshot of [before, after]) {
555
+ if (typeof snapshot.worktreeRoot !== 'string' || !isObject(snapshot.worktreeBranches) ||
556
+ !Object.hasOwn(snapshot.worktreeBranches, snapshot.worktreeRoot) ||
557
+ snapshot.branchRef === undefined || snapshot.worktreeBranches[snapshot.worktreeRoot] !== snapshot.branchRef) return new Set();
558
+ for (const [root, branch] of Object.entries(snapshot.worktreeBranches)) {
559
+ if (root !== before.worktreeRoot && root !== after.worktreeRoot && branch !== null) branches.add(branch);
560
+ }
561
+ }
562
+ return branches;
494
563
  }
495
564
 
496
565
  const allowedBy = (allowedPaths, file) => allowedPaths.some(entry => entry.endsWith('/') ? file.startsWith(entry) : file === entry);
497
- /** Implementer and QA may change only allowedPaths (QA: none when empty or missing); read-only roles may change nothing; any HEAD, branch or ref change (created, deleted or moved) is a violation. Ordinary worktree snapshots omit Git-ignored paths; control files are compared regardless of allowedPaths and role. */
498
- export function detectViolations({role, allowedPaths, before, after}) {
499
- const headChanged = before.head !== after.head || before.branch !== after.branch;
566
+ const hasBranchRefs = (before, after) => before.branchRef !== undefined && after.branchRef !== undefined;
567
+ const branchChanged = (before, after) => hasBranchRefs(before, after)
568
+ ? before.branchRef !== after.branchRef
569
+ : before.branch !== after.branch;
570
+
571
+ function branchRefMatchesHeads(before, after) {
572
+ const ref = before.branchRef;
573
+ return typeof ref === 'string' && ref.startsWith('refs/heads/') && ref === after.branchRef &&
574
+ before.refs?.[ref] === before.head && after.refs?.[ref] === after.head;
575
+ }
576
+
577
+ /** Check whether the target branch advanced through a bounded range of allowed commits. */
578
+ export async function observeHeadAdvance(root, before, after, role, allowedPaths) {
579
+ const reject = why => ({state: 'rejected', why});
580
+ try {
581
+ if (branchChanged(before, after)) return reject('branch_switched');
582
+ if (before.head === after.head) return {state: 'none'};
583
+ const detached = hasBranchRefs(before, after) ? before.branchRef === null : !before.branch;
584
+ if (detached) return reject('detached');
585
+ if (!before.head || !after.head) return reject('unborn');
586
+ if (!branchRefMatchesHeads(before, after)) return reject('branch_ref_mismatch');
587
+
588
+ const ancestry = await gitExitCode(root, ['merge-base', '--is-ancestor', before.head, after.head]);
589
+ if (ancestry === 1) return reject('not_fast_forward');
590
+ if (ancestry !== 0) return reject('git_failed');
591
+
592
+ const range = `${before.head}..${after.head}`;
593
+ if (await git(root, ['rev-list', '--min-parents=2', range])) return reject('merge_commit');
594
+ const count = (await git(root, ['rev-list', '--count', range])).trim();
595
+ if (!/^\d+$/.test(count)) return reject('invalid_output');
596
+ const commits = Number(count);
597
+ if (commits > 100) return reject('too_many_commits');
598
+
599
+ const rawPaths = await git(root, ['log', '--no-renames', '--name-only', '-z', '--format=', range]);
600
+ if (rawPaths && !rawPaths.endsWith('\0')) return reject('invalid_output');
601
+ const uniquePaths = new Set();
602
+ for (const token of rawPaths.split('\0')) {
603
+ const file = token.replace(/^\n/, '');
604
+ if (!file) continue;
605
+ if (file.includes('\n')) return reject('invalid_output');
606
+ uniquePaths.add(file);
607
+ if (uniquePaths.size > 10000) return reject('too_many_paths');
608
+ }
609
+ const paths = [...uniquePaths].sort();
610
+ const allowed = Array.isArray(allowedPaths) ? allowedPaths : [];
611
+ if (role === 'arc_implementer' || (role === 'arc_qa' && allowed.length)) {
612
+ const outOfScopePaths = paths.filter(file => !allowedBy(allowed, file));
613
+ if (outOfScopePaths.length) return {...reject('out_of_scope'), outOfScopePaths};
614
+ }
615
+ return {state: 'advance', branch: before.branchRef, commits, paths};
616
+ } catch {
617
+ return reject('git_failed');
618
+ }
619
+ }
620
+
621
+ /**
622
+ * A verified target branch fast-forward, remote-tracking ref changes, new
623
+ * tags, refs checked out by other registered worktrees and changes to
624
+ * git:info/refs are tolerated and returned separately from violations.
625
+ * Other HEAD changes and branch switches are violations.
626
+ * Any other ref creation, deletion or movement is a violation.
627
+ * Implementer and QA may change only allowedPaths in the worktree; with an
628
+ * empty or missing list they may change no worktree paths. Fast-forward
629
+ * commit paths must stay within allowedPaths for Implementer and for QA with a
630
+ * non-empty list; QA with an empty or missing list, like read-only roles, may
631
+ * land a verified fast-forward touching any path.
632
+ * Read-only roles may change no worktree paths beyond verified fast-forward
633
+ * commits. Ordinary worktree snapshots omit Git-ignored paths. Control files
634
+ * are compared regardless of role and allowedPaths.
635
+ */
636
+ export function detectViolations({role, allowedPaths, before, after, headAdvance}) {
637
+ const branchSwitched = branchChanged(before, after);
638
+ const headMoved = before.head !== after.head;
639
+ const targetBranch = before.branchRef;
640
+ const acceptedAdvance = !branchSwitched && headMoved && headAdvance?.state === 'advance' &&
641
+ headAdvance.branch === targetBranch && Array.isArray(headAdvance.paths) && branchRefMatchesHeads(before, after);
642
+ const headChanged = branchSwitched || (headMoved && !acceptedAdvance);
500
643
  const refsBefore = before.refs ?? {}, refsAfter = after.refs ?? {};
501
- const refsChanged = [...new Set([...Object.keys(refsBefore), ...Object.keys(refsAfter)])].some(name => refsBefore[name] !== refsAfter[name]);
644
+ const otherBranches = otherWorktreeBranches(before, after);
645
+ const toleratedRefs = [];
646
+ let refsChanged = false;
647
+ for (const name of new Set([...Object.keys(refsBefore), ...Object.keys(refsAfter)])) {
648
+ if (refsBefore[name] === refsAfter[name]) continue;
649
+ if (name === targetBranch) {
650
+ if (acceptedAdvance) toleratedRefs.push(name);
651
+ else refsChanged = true;
652
+ } else if (name.startsWith('refs/remotes/') || (name.startsWith('refs/tags/') && !Object.hasOwn(refsBefore, name)) ||
653
+ (name.startsWith('refs/heads/') && otherBranches.has(name))) {
654
+ toleratedRefs.push(name);
655
+ } else {
656
+ refsChanged = true;
657
+ }
658
+ }
502
659
  const allowed = (role === 'arc_implementer' || role === 'arc_qa') && Array.isArray(allowedPaths) ? allowedPaths : [];
503
660
  const changed = new Set();
504
- for (const file of new Set([...before.entries.keys(), ...after.entries.keys()])) if (before.entries.get(file) !== after.entries.get(file)) changed.add(file);
505
- const changedPaths = [...changed].filter(file => !allowedBy(allowed, file)).sort();
661
+ for (const file of new Set([...before.entries.keys(), ...after.entries.keys()])) {
662
+ if (before.entries.get(file) !== after.entries.get(file) && !allowedBy(allowed, file)) changed.add(file);
663
+ }
664
+ if (headAdvance?.state === 'rejected') {
665
+ for (const file of headAdvance.outOfScopePaths ?? []) changed.add(file);
666
+ }
667
+ const changedPaths = [...changed].sort();
506
668
  const controlBefore = before.control ?? new Map(), controlAfter = after.control ?? new Map();
507
- const controlChanged = [...new Set([...controlBefore.keys(), ...controlAfter.keys()])]
508
- .filter(label => controlBefore.get(label) !== controlAfter.get(label)).sort();
509
- return {reason: headChanged || refsChanged || changedPaths.length || controlChanged.length ? 'permission_violation_observed' : null, changedPaths, headChanged, refsChanged, controlChanged};
669
+ const controlChanged = [], toleratedControl = [];
670
+ for (const label of new Set([...controlBefore.keys(), ...controlAfter.keys()])) {
671
+ if (controlBefore.get(label) === controlAfter.get(label)) continue;
672
+ if (label === 'git:info/refs') toleratedControl.push(label);
673
+ else controlChanged.push(label);
674
+ }
675
+ const reason = headChanged || refsChanged || changedPaths.length || controlChanged.length ? 'permission_violation_observed' : null;
676
+ const toleratedCommitPaths = acceptedAdvance ? [...headAdvance.paths].sort() : [];
677
+ return {reason, changedPaths, headChanged, refsChanged, controlChanged: controlChanged.sort(), toleratedRefs: toleratedRefs.sort(), toleratedControl, toleratedCommitPaths};
678
+ }
679
+
680
+ export function toleratedRecord({toleratedRefs = [], toleratedControl = [], toleratedCommitPaths = []} = {}) {
681
+ const record = {};
682
+ for (const [key, names] of [['refs', toleratedRefs], ['control', toleratedControl], ['commitPaths', toleratedCommitPaths]]) {
683
+ if (!names.length) continue;
684
+ record[key] = [...names].sort().slice(0, 100);
685
+ if (names.length > 100) record.truncated = true;
686
+ }
687
+ return Object.keys(record).length ? record : null;
510
688
  }
@@ -379,7 +379,7 @@
379
379
  "reviewer-findings"
380
380
  ],
381
381
  "authority": "orchestrator",
382
- "text": "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.",
382
+ "text": "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 and new failures from final verification, which may run concurrently with the final Reviewer, follow Implementer → QA; Reviewer evidence for affected files then needs a refreshed-diff recheck. Preserve required QA outside this final Reviewer exception.",
383
383
  "controls": {
384
384
  "codex": "prompt",
385
385
  "claude": "prompt",