@yunhozz/arc 0.4.6 → 0.5.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 (93) hide show
  1. package/MANIFEST.sha256 +89 -76
  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/models.toml +7 -7
  9. package/claude/skill/references/coordination.md +6 -2
  10. package/claude/skill/references/handoff-prep.md +5 -0
  11. package/claude/skill/references/handoff.md +2 -2
  12. package/claude/skill/references/planning.md +2 -2
  13. package/claude/skill/references/verification.md +21 -3
  14. package/claude/skill/references/worktree-creation.md +2 -2
  15. package/codex/agents/arc-implementer.toml +1 -1
  16. package/codex/agents/arc-planner.toml +1 -1
  17. package/codex/agents/arc-qa.toml +1 -1
  18. package/codex/agents/arc-reviewer.toml +1 -1
  19. package/codex/agents/arc-scouter.toml +1 -1
  20. package/codex/skill/models.toml +5 -5
  21. package/codex/skill/references/coordination.md +6 -2
  22. package/codex/skill/references/handoff-prep.md +5 -0
  23. package/codex/skill/references/handoff.md +2 -2
  24. package/codex/skill/references/planning.md +2 -2
  25. package/codex/skill/references/verification.md +20 -2
  26. package/gemini/agents/arc-implementer.md +3 -3
  27. package/gemini/agents/arc-planner.md +2 -2
  28. package/gemini/agents/arc-qa.md +2 -2
  29. package/gemini/agents/arc-reviewer.md +2 -2
  30. package/gemini/agents/arc-scouter.md +2 -2
  31. package/gemini/skill/models.toml +6 -6
  32. package/gemini/skill/references/coordination.md +7 -3
  33. package/gemini/skill/references/handoff-prep.md +5 -0
  34. package/gemini/skill/references/handoff.md +2 -2
  35. package/gemini/skill/references/planning.md +2 -2
  36. package/gemini/skill/references/verification.md +21 -3
  37. package/gemini/skill/references/worktree-creation.md +2 -2
  38. package/grok/agents/arc-implementer.md +2 -2
  39. package/grok/agents/arc-planner.md +1 -1
  40. package/grok/agents/arc-qa.md +1 -1
  41. package/grok/agents/arc-reviewer.md +1 -1
  42. package/grok/agents/arc-scouter.md +1 -1
  43. package/grok/skill/references/coordination.md +6 -2
  44. package/grok/skill/references/handoff-prep.md +5 -0
  45. package/grok/skill/references/handoff.md +2 -2
  46. package/grok/skill/references/planning.md +2 -2
  47. package/grok/skill/references/verification.md +21 -3
  48. package/grok/skill/references/worktree-creation.md +2 -2
  49. package/lib/cli/postinstall.mjs +1 -1
  50. package/lib/cli/root.mjs +1 -1
  51. package/lib/installer/runtime-assets.mjs +5 -1
  52. package/lib/management/reapply.mjs +117 -0
  53. package/lib/management/update.mjs +59 -5
  54. package/lib/models/catalog-gemini.mjs +4 -1
  55. package/lib/models/gemini-models.json +4 -0
  56. package/lib/npm/upgrade.mjs +6 -2
  57. package/lib/policy/role-policy.json +1 -1
  58. package/lib/prompts/agent-fragments.json +5 -5
  59. package/lib/runtime/final-verify.mjs +2158 -0
  60. package/lib/runtime/node-test-reporter.mjs +81 -0
  61. package/lib/runtime/platform-registry.mjs +1 -1
  62. package/lib/runtime/role-bridge.mjs +10 -1
  63. package/lib/runtime/role-dispatch-policy.mjs +4 -0
  64. package/lib/runtime/role-observe.mjs +192 -14
  65. package/lib/runtime/role-supervisor.mjs +268 -23
  66. package/lib/runtime/test-results.mjs +736 -0
  67. package/lib/runtime/verify-cli.mjs +60 -0
  68. package/lib/tui/app.mjs +7 -41
  69. package/lib/tui/interface.mjs +40 -0
  70. package/lib/tui/render.mjs +1 -1
  71. package/lib/tui/setup.mjs +27 -16
  72. package/lib/watch/args.mjs +12 -27
  73. package/lib/watch/dispatch.mjs +2 -2
  74. package/lib/watch/index.mjs +38 -26
  75. package/lib/watch/markdown.mjs +232 -0
  76. package/lib/watch/menu.mjs +54 -0
  77. package/lib/watch/model.mjs +7 -3
  78. package/lib/watch/render.mjs +28 -67
  79. package/lib/watch/scope.mjs +1 -5
  80. package/lib/watch/status-line.mjs +2 -4
  81. package/lib/watch/text-width.mjs +43 -0
  82. package/lib/watch/watcher.mjs +17 -36
  83. package/package.json +1 -1
  84. package/shared/skill/runtime/final-verify.mjs +2158 -0
  85. package/shared/skill/runtime/node-test-reporter.mjs +81 -0
  86. package/shared/skill/runtime/platform-registry.mjs +1 -1
  87. package/shared/skill/runtime/role-bridge.mjs +10 -1
  88. package/shared/skill/runtime/role-dispatch-policy.mjs +4 -0
  89. package/shared/skill/runtime/role-observe.mjs +192 -14
  90. package/shared/skill/runtime/role-policy.json +1 -1
  91. package/shared/skill/runtime/role-supervisor.mjs +268 -23
  92. package/shared/skill/runtime/test-results.mjs +736 -0
  93. package/shared/skill/runtime/verify-cli.mjs +60 -0
@@ -0,0 +1,81 @@
1
+ import {isAbsolute, relative} from 'node:path';
2
+
3
+ const entities = {
4
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;',
5
+ '\t': '&#9;', '\n': '&#10;', '\r': '&#13;'
6
+ };
7
+
8
+ function escapeAttribute(value) {
9
+ return String(value ?? '')
10
+ .replace(/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/gu, '\uFFFD')
11
+ .replace(/[&<>"'\t\n\r]/g, char => entities[char]);
12
+ }
13
+
14
+ function attribute(name, value) {
15
+ return ' ' + name + '="' + escapeAttribute(value) + '"';
16
+ }
17
+
18
+ function failureMessage(error) {
19
+ return error?.cause?.message ?? error?.message ?? '';
20
+ }
21
+
22
+ function isFileFailure({file, name, nesting}, failed, children) {
23
+ return failed && nesting === 0 && !children.length && isAbsolute(file ?? '') &&
24
+ (name === file || name === relative(process.cwd(), file));
25
+ }
26
+
27
+ function writeTestcase({name, file, details, skip, todo}, failed) {
28
+ const attrs = attribute('name', name) + attribute('file', file) + attribute('time', details.duration_ms / 1000);
29
+ if (todo) return '<testcase' + attrs + '><skipped message="todo"/></testcase>\n';
30
+ if (skip) return '<testcase' + attrs + '><skipped/></testcase>\n';
31
+ if (failed) {
32
+ return '<testcase' + attrs + '><failure' + attribute('message', failureMessage(details.error)) + '/></testcase>\n';
33
+ }
34
+ return '<testcase' + attrs + '/>\n';
35
+ }
36
+
37
+ function* writeResult({data, failed, children}) {
38
+ const {name, file, details} = data;
39
+ if (isFileFailure(data, failed, children)) {
40
+ yield '<testsuite' + attribute('name', name) + attribute('file', file) + ' errors="1">' +
41
+ '<error' + attribute('message', failureMessage(details?.error)) + '/></testsuite>\n';
42
+ return;
43
+ }
44
+
45
+ const isSuite = details?.type === 'suite';
46
+ if (children.length || isSuite) {
47
+ const ownFailure = failed && details?.error?.failureType !== 'subtestsFailed';
48
+ if (ownFailure && !isSuite) yield writeTestcase(data, true);
49
+ yield '<testsuite' + attribute('name', name) + '>\n';
50
+ if (ownFailure && isSuite) {
51
+ yield '<error' + attribute('message', failureMessage(details?.error)) + '/>\n';
52
+ }
53
+ for (const child of children) yield* writeResult(child);
54
+ yield '</testsuite>\n';
55
+ return;
56
+ }
57
+
58
+ yield writeTestcase(data, failed);
59
+ }
60
+
61
+ export default async function* arcNodeReporter(source) {
62
+ yield '<?xml version="1.0" encoding="UTF-8"?>\n<testsuites>\n';
63
+ const files = new Map();
64
+ for await (const {type, data} of source) {
65
+ if (type === 'test:start') {
66
+ if (!files.has(data.file)) files.set(data.file, []);
67
+ files.get(data.file)[data.nesting] = {name: data.name, children: []};
68
+ } else if (type === 'test:pass' || type === 'test:fail') {
69
+ const stack = files.get(data.file);
70
+ const started = stack?.[data.nesting];
71
+ const children = started?.name === data.name ? started.children : [];
72
+ if (started) stack.length = data.nesting;
73
+ const result = {data, failed: type === 'test:fail', children};
74
+ const parent = stack?.[data.nesting - 1];
75
+ if (parent) parent.children.push(result);
76
+ else yield* writeResult(result);
77
+ if (stack?.length === 0) files.delete(data.file);
78
+ }
79
+ }
80
+ yield '</testsuites>\n';
81
+ }
@@ -109,7 +109,7 @@ export const DEFAULT_PLATFORM_REGISTRY = createPlatformRegistry([
109
109
  {
110
110
  id: 'gemini', label: 'Gemini', displayOrder: 2, anchorOrder: 2,
111
111
  home: {env: 'GEMINI_CLI_HOME', resolve: context => resolveHome('gemini', context)},
112
- cli: {command: 'gemini', supportedVersions: '>=0.68.0 <0.69.0'},
112
+ cli: {command: 'gemini', supportedVersions: null},
113
113
  auth: {kind: 'none'},
114
114
  models: {effortField: 'effort'},
115
115
  profile: {
@@ -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",