@yunhozz/arc 0.4.5 → 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 (79) hide show
  1. package/MANIFEST.sha256 +78 -73
  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 +4 -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 +4 -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 +5 -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 +4 -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/grok-sandbox.mjs +74 -0
  53. package/lib/runtime/role-bridge.mjs +10 -1
  54. package/lib/runtime/role-dispatch-policy.mjs +7 -1
  55. package/lib/runtime/role-observe.mjs +401 -13
  56. package/lib/runtime/role-routing.mjs +6 -0
  57. package/lib/runtime/role-supervisor.mjs +285 -33
  58. package/lib/tui/app.mjs +3 -39
  59. package/lib/tui/interface.mjs +40 -0
  60. package/lib/tui/setup.mjs +27 -16
  61. package/lib/watch/args.mjs +12 -27
  62. package/lib/watch/dispatch.mjs +2 -2
  63. package/lib/watch/index.mjs +38 -26
  64. package/lib/watch/markdown.mjs +232 -0
  65. package/lib/watch/menu.mjs +43 -0
  66. package/lib/watch/model.mjs +7 -3
  67. package/lib/watch/render.mjs +28 -67
  68. package/lib/watch/scope.mjs +1 -5
  69. package/lib/watch/status-line.mjs +2 -4
  70. package/lib/watch/text-width.mjs +43 -0
  71. package/lib/watch/watcher.mjs +17 -36
  72. package/package.json +1 -1
  73. package/shared/skill/runtime/grok-sandbox.mjs +74 -0
  74. package/shared/skill/runtime/role-bridge.mjs +10 -1
  75. package/shared/skill/runtime/role-dispatch-policy.mjs +7 -1
  76. package/shared/skill/runtime/role-observe.mjs +401 -13
  77. package/shared/skill/runtime/role-policy.json +1 -1
  78. package/shared/skill/runtime/role-routing.mjs +6 -0
  79. package/shared/skill/runtime/role-supervisor.mjs +285 -33
@@ -7,9 +7,10 @@ import fsp from 'node:fs/promises';
7
7
  import path from 'node:path';
8
8
  import readline from 'node:readline';
9
9
  import zlib from 'node:zlib';
10
- import {execFile} from 'node:child_process';
10
+ import {execFile, spawnSync} from 'node:child_process';
11
11
  import {promisify} from 'node:util';
12
12
  import {DEFAULT_POLICY, CATALOG_MODEL_ALIASES} from './role-dispatch-policy.mjs';
13
+ import {observeCooperativeTarget} from './scope.mjs';
13
14
 
14
15
  const execFileAsync = promisify(execFile);
15
16
  const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
@@ -243,16 +244,37 @@ const gitEnv = () => {
243
244
  const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.toUpperCase().startsWith('GIT_')));
244
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'});
245
246
  };
246
- 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';
247
252
  try {
248
- 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);
249
254
  return stdout;
250
255
  } catch (error) {
251
256
  if (allowFailure) return null;
257
+ if (allowUnsupportedZ && error.code === 129 && /^error: unknown (?:switch|option) `-?z'(?:\r?\n|$)/.test(error.stderr)) return null;
252
258
  throw Error(`Git observation failed: ${args[0]}${error.code ? ` (${error.code})` : ''}`);
253
259
  }
254
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
+ }
255
269
  const sha256 = value => crypto.createHash('sha256').update(value).digest('hex');
270
+
271
+ /** Resolve the worktree root for a cwd that may be a subdirectory. */
272
+ export async function resolveWorktree(cwd) {
273
+ const result = spawnSync('git', ['--no-pager', 'rev-parse', '--show-toplevel'], {cwd, env: gitEnv(), encoding: 'utf8', timeout: 10000});
274
+ if (result.error || result.status !== 0 || !result.stdout.endsWith('\n')) throw Error('Worktree root unavailable');
275
+ return observeCooperativeTarget(result.stdout.slice(0, -1));
276
+ }
277
+
256
278
  async function contentDigest(filename) {
257
279
  let stat;
258
280
  try { stat = await fsp.lstat(filename); } catch (error) { return error.code === 'ENOENT' ? sha256('deleted') : sha256('unreadable'); }
@@ -264,11 +286,252 @@ async function contentDigest(filename) {
264
286
  });
265
287
  }
266
288
 
267
- /** 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. */
289
+ const missingTree = error => error.code === 'ENOENT' || error.code === 'ENOTDIR';
290
+ const CONTROL_TREE_LIMIT = 1000;
291
+ const controlStat = filename => fsp.lstat(filename).catch(error => {
292
+ if (missingTree(error)) return null;
293
+ throw error;
294
+ });
295
+ const sameControlEntry = (stat, current) => current?.dev === stat.dev && current?.ino === stat.ino;
296
+ const entryIntact = async (filename, stat) => sameControlEntry(stat, await controlStat(filename));
297
+ const rootIntact = async () => true;
298
+
299
+ async function controlFileState(filename, {project, stat, parentIntact = rootIntact} = {}) {
300
+ let handle, bytes, digest;
301
+ let intact = parentIntact;
302
+ try {
303
+ if (!await parentIntact()) return 'changed';
304
+ stat ??= await controlStat(filename);
305
+ if (!stat) return sha256('deleted');
306
+ intact = async () => await parentIntact() && await entryIntact(filename, stat);
307
+ if (!await intact()) return 'changed';
308
+ if (stat.isSymbolicLink()) {
309
+ const target = await fsp.readlink(filename);
310
+ return await intact() ? `symlink:${target}` : 'changed';
311
+ }
312
+ if (!stat.isFile()) return sha256('directory');
313
+
314
+ // Refuse a replacement symlink and verify the opened file before reading bytes.
315
+ const {O_RDONLY, O_NOFOLLOW, O_NONBLOCK} = fs.constants;
316
+ handle = await fsp.open(filename, O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
317
+ if (!sameControlEntry(stat, await handle.stat()) || !await intact()) return 'changed';
318
+ if (project) {
319
+ bytes = await handle.readFile();
320
+ } else {
321
+ const hash = crypto.createHash('sha256');
322
+ for await (const chunk of handle.createReadStream({autoClose: false})) hash.update(chunk);
323
+ digest = hash.digest('hex');
324
+ }
325
+ if (!await intact()) return 'changed';
326
+ } catch {
327
+ return await intact().catch(() => true) ? sha256('unreadable') : 'changed';
328
+ } finally {
329
+ if (handle) await handle.close();
330
+ }
331
+ const projection = project ? project(bytes) : null;
332
+ return projection === null ? `${digest ?? sha256(bytes)}:${stat.dev}:${stat.ino}` : sha256('projection:' + projection);
333
+ }
334
+
335
+ async function snapshotControlTree(root, label) {
336
+ const entries = new Map();
337
+ const walk = async (dir, prefix, stat, parentIntact) => {
338
+ const intact = async () => await parentIntact() && await entryIntact(dir, stat);
339
+ const markChanged = () => {
340
+ for (const entry of entries.keys()) if (entry.startsWith(prefix + '/')) entries.delete(entry);
341
+ entries.set(prefix, 'changed');
342
+ };
343
+ if (!await intact()) return markChanged();
344
+ let names;
345
+ try { names = await fsp.readdir(dir); } catch (error) {
346
+ if (missingTree(error)) return markChanged();
347
+ const stillIntact = prefix === label ? await intact() : await intact().catch(() => true);
348
+ if (!stillIntact) return markChanged();
349
+ if (prefix !== label) {
350
+ entries.set(prefix + '/', 'unreadable');
351
+ return;
352
+ }
353
+ throw error;
354
+ }
355
+ if (!await intact()) return markChanged();
356
+ for (const name of names) {
357
+ if (name.endsWith('.lock')) continue;
358
+ if (!await intact()) return markChanged();
359
+ const filename = path.join(dir, name), entry = `${prefix}/${name}`;
360
+ let state;
361
+ try { state = await controlStat(filename); } catch {
362
+ entries.set(entry, sha256('unreadable'));
363
+ }
364
+ if (state?.isDirectory()) {
365
+ entries.set(entry + '/', `directory:${state.dev}:${state.ino}`);
366
+ if (entries.size <= CONTROL_TREE_LIMIT) await walk(filename, entry, state, intact);
367
+ } else if (state) {
368
+ entries.set(entry, await controlFileState(filename, {stat: state, parentIntact: intact}));
369
+ }
370
+ if (entries.size > CONTROL_TREE_LIMIT) break;
371
+ }
372
+ if (!await intact()) markChanged();
373
+ };
374
+
375
+ const stat = await controlStat(root);
376
+ if (!stat) return entries;
377
+ if (!stat.isDirectory()) return new Map([[label, await controlFileState(root, {stat})]]);
378
+ await walk(root, label, stat, rootIntact);
379
+ return entries.size > CONTROL_TREE_LIMIT ? new Map([[label, 'overflow']]) : entries;
380
+ }
381
+
382
+ async function snapshotWorktreeControlDirectory(worktree, name, files, entries) {
383
+ const dir = path.join(worktree, name), label = `worktree:${name}/`;
384
+ let stat;
385
+ try { stat = await controlStat(dir); } catch {
386
+ entries.set(label, sha256('unreadable'));
387
+ return;
388
+ }
389
+ if (stat && !stat.isDirectory()) {
390
+ entries.set(label, await controlFileState(dir, {stat}));
391
+ return;
392
+ }
393
+ const intact = async () => stat ? await entryIntact(dir, stat) : (await controlStat(dir)) === null;
394
+ const states = [];
395
+ for (const file of files) {
396
+ states.push(stat ? await controlFileState(path.join(dir, file), {parentIntact: intact}) : sha256('deleted'));
397
+ }
398
+ if (!await intact()) entries.set(label, 'changed');
399
+ else files.forEach((file, i) => entries.set(label + file, states[i]));
400
+ }
401
+
402
+ async function extraControlFileState({path: filename, project}) {
403
+ const parent = path.dirname(filename);
404
+ const stat = await controlStat(parent).catch(() => undefined);
405
+ if (stat === undefined) return sha256('unreadable');
406
+ if (!stat) return sha256('deleted');
407
+
408
+ const parentIntact = () => entryIntact(parent, stat).catch(() => false);
409
+ if (stat.isSymbolicLink()) {
410
+ const target = await fsp.readlink(parent).catch(() => null);
411
+ if (!await parentIntact()) return 'parent-changed';
412
+ return target === null ? sha256('unreadable') : `parent-symlink:${target}`;
413
+ }
414
+ if (!stat.isDirectory()) return 'parent-not-directory';
415
+ const state = await controlFileState(filename, {project, parentIntact});
416
+ return await parentIntact() ? state : 'parent-changed';
417
+ }
418
+
419
+ const CLAUDE_SAFE_ALLOW_TOOLS = new Set(['bash', 'read', 'grep', 'glob', 'webfetch', 'websearch']);
420
+
421
+ function claudeSettingsScopeReason(bytes) {
422
+ let settings;
423
+ try { settings = JSON.parse(bytes.toString('utf8')); } catch { return 'invalid JSON'; }
424
+ if (!isObject(settings)) return null;
425
+ if (Object.hasOwn(settings, 'hooks')) return 'hooks';
426
+ if (Object.hasOwn(settings, 'sandbox')) return 'sandbox';
427
+ const {permissions} = settings;
428
+ if (!isObject(permissions)) return null;
429
+ if (permissions.additionalDirectories?.length > 0) return 'permissions.additionalDirectories';
430
+ if (Object.hasOwn(permissions, 'allow')) {
431
+ const {allow} = permissions;
432
+ if (!Array.isArray(allow) || allow.some(rule =>
433
+ typeof rule !== 'string' || !CLAUDE_SAFE_ALLOW_TOOLS.has(rule.split('(', 1)[0].trim().toLowerCase())
434
+ )) return 'permissions.allow';
435
+ }
436
+ if (Object.hasOwn(permissions, 'defaultMode')) return 'permissions.defaultMode';
437
+ return null;
438
+ }
439
+
440
+ /** Check Claude project and local settings before starting a writing bridge. */
441
+ export async function claudeProjectSettingsWidenScope(worktree) {
442
+ for (const label of ['.claude/settings.json', '.claude/settings.local.json']) {
443
+ let scopeReason;
444
+ const state = await extraControlFileState({path: path.join(worktree, label), project: bytes => {
445
+ scopeReason = claudeSettingsScopeReason(bytes);
446
+ return 'claude-settings-read';
447
+ }}).catch(() => 'unreadable');
448
+ if (state === sha256('deleted')) continue;
449
+ if (state === sha256('projection:claude-settings-read')) {
450
+ if (scopeReason) return `${label}: ${scopeReason}`;
451
+ continue;
452
+ }
453
+ if (state === sha256('directory') || state.startsWith('symlink:')) return `${label}: not a regular file`;
454
+ return `${label}: settings path could not be verified`;
455
+ }
456
+ return null;
457
+ }
458
+
459
+ /** Snapshot of selected Git, worktree and optional platform control files. */
460
+ export async function snapshotControlFiles({gitCommonDir, gitDir, worktree, extra = []}) {
461
+ if (![gitCommonDir, gitDir, worktree].every(dir => typeof dir === 'string' && path.isAbsolute(dir))) {
462
+ throw Error('Control snapshot requires absolute Git and worktree paths');
463
+ }
464
+ if (!(await fsp.lstat(gitCommonDir)).isDirectory()) throw Error('Git common directory is not a directory');
465
+ const files = [
466
+ {label: 'git:config', path: path.join(gitCommonDir, 'config')},
467
+ {label: 'git:config.worktree', path: path.join(gitDir, 'config.worktree')},
468
+ ];
469
+ const entries = new Map();
470
+ for (const file of files) entries.set(file.label, await controlFileState(file.path));
471
+ await snapshotWorktreeControlDirectory(worktree, '.claude', ['settings.json', 'settings.local.json'], entries);
472
+ await snapshotWorktreeControlDirectory(worktree, '.codex', ['config.toml'], entries);
473
+ for (const file of extra) entries.set(file.label, await extraControlFileState(file));
474
+ for (const tree of ['hooks', 'info']) {
475
+ for (const [label, state] of await snapshotControlTree(path.join(gitCommonDir, tree), `git:${tree}`)) entries.set(label, state);
476
+ }
477
+ return entries;
478
+ }
479
+
480
+ export function allowedPathsCoverControl(allowedPaths) {
481
+ return allowedPaths.some(entry => {
482
+ const normalized = path.posix.normalize(entry).replace(/\/$/, '').toLowerCase();
483
+ return normalized.startsWith('.git/') || ['.', '.git', '.claude', '.claude/settings.json', '.claude/settings.local.json', '.codex', '.codex/config.toml'].includes(normalized);
484
+ });
485
+ }
486
+
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. */
268
530
  export async function snapshotWorktree(worktree) {
269
- const root = (await git(worktree, ['rev-parse', '--show-toplevel'])).trim();
531
+ const root = await realpathOrOriginal((await git(worktree, ['rev-parse', '--show-toplevel'])).replace(/\n$/, ''));
270
532
  const head = (await git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], {allowFailure: true}))?.trim() || null;
271
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;
272
535
  const refs = {};
273
536
  for (const line of (await git(root, ['for-each-ref', '--format=%(refname) %(objectname)'])).split('\n')) {
274
537
  const at = line.lastIndexOf(' ');
@@ -283,18 +546,143 @@ export async function snapshotWorktree(worktree) {
283
546
  entries.set(file, `${code}:${await contentDigest(path.join(root, file))}`);
284
547
  if (code.includes('R') || code.includes('C')) { const origin = tokens[++i]; if (origin) entries.set(origin, `${code}:${sha256('deleted')}`); }
285
548
  }
286
- 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;
287
563
  }
288
564
 
289
565
  const allowedBy = (allowedPaths, file) => allowedPaths.some(entry => entry.endsWith('/') ? file.startsWith(entry) : file === entry);
290
- /** 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. Git-ignored paths are not observed. */
291
- export function detectViolations({role, allowedPaths, before, after}) {
292
- 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);
293
643
  const refsBefore = before.refs ?? {}, refsAfter = after.refs ?? {};
294
- 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
+ }
295
659
  const allowed = (role === 'arc_implementer' || role === 'arc_qa') && Array.isArray(allowedPaths) ? allowedPaths : [];
296
660
  const changed = new Set();
297
- for (const file of new Set([...before.entries.keys(), ...after.entries.keys()])) if (before.entries.get(file) !== after.entries.get(file)) changed.add(file);
298
- const changedPaths = [...changed].filter(file => !allowedBy(allowed, file)).sort();
299
- return {reason: headChanged || refsChanged || changedPaths.length ? 'permission_violation_observed' : null, changedPaths, headChanged, refsChanged};
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();
668
+ const controlBefore = before.control ?? new Map(), controlAfter = after.control ?? new Map();
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;
300
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",
@@ -9,6 +9,7 @@ import {resolveConfigHome, resolveLocalCli, probePlatformAuth, probeCodexAuthSta
9
9
  import {ROUTING_ROLES, parseRoleRoutingConfig} from './role-routing-config.mjs';
10
10
  import {DEFAULT_POLICY, HOST_SANDBOX_GATES, reason, profileName, revisionTag, hostGateReasons, bridgeGateReasons, environmentReasons, initialClaims, capabilityReasons} from './role-dispatch-policy.mjs';
11
11
  import {NON_TERMINAL_STATES, createLease, listLeases, pruneTerminalLeases, readHostLimits} from './role-dispatch-store.mjs';
12
+ import {allowedPathsCoverControl, claudeProjectSettingsWidenScope, resolveWorktree} from './role-observe.mjs';
12
13
 
13
14
  const exact=(value,keys)=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
14
15
  const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
@@ -239,6 +240,11 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
239
240
  let config;try{config=await readActivation(homes,expectedRevision,{anchorHome,host,runtimePlatforms});}catch{result.reasons=[reason('activation_unverified')];return;}
240
241
  const requested=config.roles[role],route=requested.platform===host?'native':'bridge';
241
242
  result.requested={...requested};result.route=route;result.profileName=profileName(requested.platform,role,{runtimePlatforms});
243
+ if(route==='bridge'&&allowedPathsCoverControl(assignment.allowedPaths??[])){result.reasons=[reason('permission_scope_unverified')];return;}
244
+ if(route==='bridge'&&requested.platform==='claude'&&(role==='arc_implementer'||role==='arc_qa')){
245
+ const target=typeof context.cwd==='string'?await resolveWorktree(context.cwd).catch(()=>null):null;
246
+ if(!target||await claudeProjectSettingsWidenScope(target.realpath)){result.reasons=[reason('permission_scope_unverified')];return;}
247
+ }
242
248
  const capabilities=capabilityReasons({hostPlatform:host,targetPlatform:requested.platform,route,runtimePlatforms});
243
249
  if(capabilities.length){result.reasons=capabilities.map(reason);return;}
244
250
  await pruneTerminalLeases(anchorHome,{now,retentionMs:policy.leaseRetentionMs,runtimePlatforms});