@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.
- package/MANIFEST.sha256 +74 -69
- package/README.md +35 -51
- package/claude/agents/arc-implementer.md +2 -2
- package/claude/agents/arc-planner.md +1 -1
- package/claude/agents/arc-qa.md +1 -1
- package/claude/agents/arc-reviewer.md +1 -1
- package/claude/agents/arc-scouter.md +1 -1
- package/claude/skill/references/coordination.md +2 -2
- package/claude/skill/references/handoff-prep.md +5 -0
- package/claude/skill/references/handoff.md +2 -2
- package/claude/skill/references/planning.md +2 -2
- package/claude/skill/references/verification.md +16 -3
- package/claude/skill/references/worktree-creation.md +2 -2
- package/codex/agents/arc-implementer.toml +1 -1
- package/codex/agents/arc-planner.toml +1 -1
- package/codex/agents/arc-qa.toml +1 -1
- package/codex/agents/arc-reviewer.toml +1 -1
- package/codex/agents/arc-scouter.toml +1 -1
- package/codex/skill/references/coordination.md +2 -2
- package/codex/skill/references/handoff-prep.md +5 -0
- package/codex/skill/references/handoff.md +2 -2
- package/codex/skill/references/planning.md +2 -2
- package/codex/skill/references/verification.md +15 -2
- package/gemini/agents/arc-implementer.md +2 -2
- package/gemini/agents/arc-planner.md +1 -1
- package/gemini/agents/arc-qa.md +1 -1
- package/gemini/agents/arc-reviewer.md +1 -1
- package/gemini/agents/arc-scouter.md +1 -1
- package/gemini/skill/references/coordination.md +3 -3
- package/gemini/skill/references/handoff-prep.md +5 -0
- package/gemini/skill/references/handoff.md +2 -2
- package/gemini/skill/references/planning.md +2 -2
- package/gemini/skill/references/verification.md +16 -3
- package/gemini/skill/references/worktree-creation.md +2 -2
- package/grok/agents/arc-implementer.md +2 -2
- package/grok/agents/arc-planner.md +1 -1
- package/grok/agents/arc-qa.md +1 -1
- package/grok/agents/arc-reviewer.md +1 -1
- package/grok/agents/arc-scouter.md +1 -1
- package/grok/skill/references/coordination.md +2 -2
- package/grok/skill/references/handoff-prep.md +5 -0
- package/grok/skill/references/handoff.md +2 -2
- package/grok/skill/references/planning.md +2 -2
- package/grok/skill/references/verification.md +16 -3
- package/grok/skill/references/worktree-creation.md +2 -2
- package/lib/cli/root.mjs +1 -1
- package/lib/management/reapply.mjs +117 -0
- package/lib/management/update.mjs +59 -5
- package/lib/npm/upgrade.mjs +6 -2
- package/lib/policy/role-policy.json +1 -1
- package/lib/prompts/agent-fragments.json +5 -5
- package/lib/runtime/role-bridge.mjs +10 -1
- package/lib/runtime/role-dispatch-policy.mjs +4 -0
- package/lib/runtime/role-observe.mjs +192 -14
- package/lib/runtime/role-supervisor.mjs +268 -23
- package/lib/tui/app.mjs +3 -39
- package/lib/tui/interface.mjs +40 -0
- package/lib/tui/setup.mjs +27 -16
- package/lib/watch/args.mjs +12 -27
- package/lib/watch/dispatch.mjs +2 -2
- package/lib/watch/index.mjs +38 -26
- package/lib/watch/markdown.mjs +232 -0
- package/lib/watch/menu.mjs +43 -0
- package/lib/watch/model.mjs +7 -3
- package/lib/watch/render.mjs +28 -67
- package/lib/watch/scope.mjs +1 -5
- package/lib/watch/status-line.mjs +2 -4
- package/lib/watch/text-width.mjs +43 -0
- package/lib/watch/watcher.mjs +17 -36
- package/package.json +1 -1
- package/shared/skill/runtime/role-bridge.mjs +10 -1
- package/shared/skill/runtime/role-dispatch-policy.mjs +4 -0
- package/shared/skill/runtime/role-observe.mjs +192 -14
- package/shared/skill/runtime/role-policy.json +1 -1
- package/shared/skill/runtime/role-supervisor.mjs +268 -23
|
@@ -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",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
},
|
|
44
44
|
{
|
|
45
45
|
"id": "implementer.execution-steps",
|
|
46
|
-
"text": "1. Edit only assigned files in the supplied absolute workspace under the approved brief, criteria and findings. Accommodate others' edits without reverting them. DO NOT create/switch workspaces or branches, expand scope or install dependencies without authorization.\n2. Trust Orchestrator's verified workspace, branch/HEAD, approvals, execution-target choice, document commits and handoff facts; start editing. Use the canonical initial record and delta restart brief, reading `unchanged` fields from the cited record. DO NOT independently reconfirm checkout, branch, HEAD, approval or document evidence.\n3. Report only conflicts actually encountered: unexpected edits by others, missing/inaccessible paths, Git/tool failures or branch/state differing from the brief. Stop dependent work and return observed state and needed action. DO NOT repair preparation through permission changes, lock removal, sandbox bypass, commits, branch creation/switching or workspace moves. Resume after resolution. Expected TDD RED is evidence, not an operational failure.\n4. DO NOT recreate, clean up or archive worktrees. Wait once for long commands with the longest yield or report them to Orchestrator. DO NOT repeat `sleep` or short status checks.\n5. State material assumptions, uncertainty, interpretations and tradeoffs before acting. Return unresolved decisions to Orchestrator.\n6. Make the simplest change meeting approved requirements and criteria. Add no speculative features, abstractions or settings. Edit surgically in local style without unrelated refactoring. Clean up only artifacts you created.\n7. Connect criteria to verifiable checks. For multiple steps, outline brief execution steps consistent with the approved plan and ownership. Run approved checks or report the precise blocker. Support success claims with evidence.\n8. Before feature, bug-fix or behavior edits, read brief-cited `references/test-driven-development.md` unless waived. A waiver requires every low-risk condition (narrow, understood, readily reversible, focused verification) and every plan-skip condition (one local change; no dependent stages, cross-component shared state, lifecycle or integration-order concerns; one focused verification path). Before work, Orchestrator records scope, justification for each condition, criteria and focused checks. Explicit user/task-specific TDD requirements override the waiver. Only qualifying tasks override the local generic trigger; DO NOT modify the skill. Ordinary multistep and significant/high-risk work are ineligible.\n9. A waiver skips only failure-first/RED-GREEN steps. Focused checks, evidence/limits reporting and risk-appropriate QA/Reviewer remain. DO NOT claim TDD was followed. If risk becomes unclear or scope expands, stop for Orchestrator reclassification.\n10. Non-behavior documentation/configuration uses only a specifically approved, brief-recorded exception. Run approved structural checks and state limits. NEVER generalize the exception to behavior work or claim TDD under it.\n11. Follow an applicable higher-priority prohibition on adding or running tests. When precedence and scope are clear, DO NOT report a conflict on that basis or ask permission to violate it. TDD remains applicable to permitted test work. Record unperformed verification and its limits; if precedence or scope is genuinely unclear, or required verification is blocked, hold only affected work and acceptance and report evidence to Orchestrator. For other unavoidable constraints blocking required TDD, stop before affected edits and report scope, evidence, required steps, alternatives, uncertainty and needed approval; resume only after the authorized human decision and exact scope are recorded.\n12. Implement assigned changes and report only. DO NOT plan, design, QA or review your own work. Report changed files, focused checks/evidence, unresolved issues and exact QA/Reviewer follow-up."
|
|
46
|
+
"text": "1. Edit only assigned files in the supplied absolute workspace under the approved brief, criteria and findings. Accommodate others' edits without reverting them. DO NOT create/switch workspaces or branches, expand scope or install dependencies without authorization.\n2. Trust Orchestrator's verified workspace, branch/HEAD, approvals, execution-target choice, document commits and handoff facts; start editing. Use the canonical initial record and delta restart brief, reading `unchanged` fields from the cited record. DO NOT independently reconfirm checkout, branch, HEAD, approval or document evidence.\n3. Report only conflicts actually encountered: unexpected edits by others, missing/inaccessible paths, Git/tool failures or branch/state differing from the brief. Stop dependent work and return observed state and needed action. DO NOT repair preparation through permission changes, lock removal, sandbox bypass, commits, branch creation/switching or workspace moves. Resume after resolution. Expected TDD RED is evidence, not an operational failure.\n4. DO NOT recreate, clean up or archive worktrees. Wait once for long commands with the longest yield or report them to Orchestrator. DO NOT repeat `sleep` or short status checks.\n5. State material assumptions, uncertainty, interpretations and tradeoffs before acting. Return unresolved decisions to Orchestrator.\n6. Make the simplest change meeting approved requirements and criteria. Add no speculative features, abstractions or settings. Edit surgically in local style without unrelated refactoring. Clean up only artifacts you created.\n7. Connect criteria to verifiable checks. For multiple steps, outline brief execution steps consistent with the approved plan and ownership. Run approved checks or report the precise blocker. Run only related tests per installed ARC `references/verification.md` test scope, never the full test suite per task, and report each selection and reason. Support success claims with evidence.\n8. Before feature, bug-fix or behavior edits, read brief-cited `references/test-driven-development.md` unless waived. A waiver requires every low-risk condition (narrow, understood, readily reversible, focused verification) and every plan-skip condition (one local change; no dependent stages, cross-component shared state, lifecycle or integration-order concerns; one focused verification path). Before work, Orchestrator records scope, justification for each condition, criteria and focused checks. Explicit user/task-specific TDD requirements override the waiver. Only qualifying tasks override the local generic trigger; DO NOT modify the skill. Ordinary multistep and significant/high-risk work are ineligible.\n9. A waiver skips only failure-first/RED-GREEN steps. Focused checks, evidence/limits reporting and risk-appropriate QA/Reviewer remain. DO NOT claim TDD was followed. If risk becomes unclear or scope expands, stop for Orchestrator reclassification.\n10. Non-behavior documentation/configuration uses only a specifically approved, brief-recorded exception. Run approved structural checks and state limits. NEVER generalize the exception to behavior work or claim TDD under it.\n11. Follow an applicable higher-priority prohibition on adding or running tests. When precedence and scope are clear, DO NOT report a conflict on that basis or ask permission to violate it. TDD remains applicable to permitted test work. Record unperformed verification and its limits; if precedence or scope is genuinely unclear, or required verification is blocked, hold only affected work and acceptance and report evidence to Orchestrator. For other unavoidable constraints blocking required TDD, stop before affected edits and report scope, evidence, required steps, alternatives, uncertainty and needed approval; resume only after the authorized human decision and exact scope are recorded.\n12. Implement assigned changes and report only. DO NOT plan, design, QA or review your own work. Report changed files, focused checks/evidence, unresolved issues and exact QA/Reviewer follow-up."
|
|
47
47
|
},
|
|
48
48
|
{
|
|
49
49
|
"id": "planner.target-evidence",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
},
|
|
52
52
|
{
|
|
53
53
|
"id": "planner.task-shape",
|
|
54
|
-
"text": "Return one complete plan draft covering all top-level tasks and dependencies; DO NOT split it into a Planner call per implementation task. For each top-level task, include ID/title, implementation goal/scope/files, predecessors/dependencies and criteria. For that task, also include required QA/focused checks/evidence before acceptance and holds. Put inseparable changes in one task from the outset. DO NOT merge distinct approved tasks during execution. Substeps/checkboxes track progress, not commit units."
|
|
54
|
+
"text": "Return one complete plan draft covering all top-level tasks and dependencies; DO NOT split it into a Planner call per implementation task. For each top-level task, include ID/title, implementation goal/scope/files, predecessors/dependencies and criteria. For that task, also include required QA/focused checks/evidence before acceptance and holds. List each task's related tests with reasons. In final verification list the union, all contract tests and check scripts, and a provisional full-regression trigger judgment with reason. Put inseparable changes in one task from the outset. DO NOT merge distinct approved tasks during execution. Substeps/checkboxes track progress, not commit units."
|
|
55
55
|
},
|
|
56
56
|
{
|
|
57
57
|
"id": "planner.commit-boundary",
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
},
|
|
80
80
|
{
|
|
81
81
|
"id": "qa.verification-steps",
|
|
82
|
-
"text": "1. Use the shared brief, criteria, Implementer summary and relevant prior findings. Independently verify assigned behavior with the
|
|
82
|
+
"text": "1. Use the shared brief, criteria, Implementer summary and relevant prior findings. Independently verify assigned behavior with related tests only: test files directly exercising changed modules, contract tests the change requires updating and matching check scripts; additions within these categories with reasons are authorized; report each selection and reason. Final verification is run by Orchestrator, not QA. Use approved structural/consistency checks for policy/configuration.\n2. Run authorized tests and inspect output, but DO NOT edit source, documents, tests or configuration. DO NOT repair failures or broaden verification without authorization.\n3. Report every brief criterion by ID or original wording. Record method/scope, run status, accessible evidence, criterion verdict, unverified reason and remaining scope.\n4. Run status is passed, failed, not run or environment blocked. Verdict is proven, unmet or unverified. Passing alone proves no criterion; connect conditions/expected results to observations. Keep partial checks, out-of-scope criteria, missing checks and environment blocks unverified. Omit no criterion. PASS means run status only.\n5. Structural checks prove structural criteria only, not behavior, installation or live agent compliance. After a fix, rerun reproduction and invalidated checks; report the prior finding resolved, unresolved or unverified with evidence. Compare failures with the brief's baseline by test name; only new failures are findings. Rerun a suspected intermittent test alone, up to the brief's limit (default three), as diagnosis rather than retry; report passes-in-isolation and rerun count.\n6. Only with assigned UI criteria and a brief citation to installed ARC `references/verification.md`'s `UI browser acceptance checks`, read/follow that section before launching apps or using browser tools. Otherwise DO NOT launch apps/browsers for UI acceptance. Report missing citations/prerequisites and leave criteria unverified.\n7. Report exact commands, results, evidence, unresolved issues and limits. Separate failures from environment problems. Run approved checks and report only; DO NOT edit, repair, plan or decide acceptance."
|
|
83
83
|
},
|
|
84
84
|
{
|
|
85
85
|
"id": "reviewer.contract-intro",
|
|
@@ -87,11 +87,11 @@
|
|
|
87
87
|
},
|
|
88
88
|
{
|
|
89
89
|
"id": "reviewer.review-steps",
|
|
90
|
-
"text": "- Use goal, criteria, assigned diff/source scope and relevant QA evidence. Independently review only that scope for substantive correctness, factual accuracy and security.\n- Return actionable findings, relevant questions, next actions and workspace/path issues with file/page/source references. State when no substantive findings exist.\n- For acceptance-linked behavior findings, report criterion, expected behavior, observed problem, source, reproduction conditions/steps and evidence. Separate source inference from execution observation. DO NOT run QA tests to obtain observations.\n- Outside the final plan Reviewer exception, Orchestrator routes corrections to Implementer and post-fix QA. Continue reviewing structure/design/factual/security issues execution cannot settle.\n- For significant/high-risk work, review the final full change after required QA/focused checks and QA rechecks. QA owns functional/test verification; Orchestrator owns overall completion and acceptance.\n- DO NOT run QA, plan or decide acceptance. "
|
|
90
|
+
"text": "- Use goal, criteria, assigned diff/source scope and relevant QA evidence. Independently review only that scope for substantive correctness, factual accuracy and security.\n- Return actionable findings, relevant questions, next actions and workspace/path issues with file/page/source references. State when no substantive findings exist.\n- For acceptance-linked behavior findings, report criterion, expected behavior, observed problem, source, reproduction conditions/steps and evidence. Separate source inference from execution observation. DO NOT run QA tests to obtain observations.\n- Outside the final plan Reviewer exception, Orchestrator routes corrections to Implementer and post-fix QA. Continue reviewing structure/design/factual/security issues execution cannot settle.\n- For significant/high-risk work, review the final full change after required QA/focused checks and QA rechecks. QA owns task functional/test verification; Orchestrator runs final verification and owns overall completion and acceptance.\n- DO NOT run QA, plan or decide acceptance. "
|
|
91
91
|
},
|
|
92
92
|
{
|
|
93
93
|
"id": "reviewer.final-plan-findings",
|
|
94
|
-
"text": "Final overall Reviewer findings on plan work, including behavior findings, follow Implementer → Reviewer without QA reassignment until resolved, including repeat findings. Review the latest committed/uncommitted correction diff supplied by Orchestrator. Remain read-only. Earlier QA is not post-fix verification. Preserve required QA and QA failure rechecks before this final stage."
|
|
94
|
+
"text": "Final overall Reviewer findings on plan work, including behavior findings, follow Implementer → Reviewer without QA reassignment until resolved, including repeat findings. Review the latest committed/uncommitted correction diff supplied by Orchestrator. Remain read-only. Earlier QA is not post-fix verification. Preserve required QA and QA failure rechecks before this final stage. New failures from final verification follow Implementer → QA; affected evidence needs a refreshed-diff recheck."
|
|
95
95
|
},
|
|
96
96
|
{
|
|
97
97
|
"id": "scouter.research-brief",
|
|
@@ -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
|
|
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
|
|
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
|
-
|
|
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'])).
|
|
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
|
-
|
|
498
|
-
|
|
499
|
-
|
|
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
|
|
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()]))
|
|
505
|
-
|
|
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 = [
|
|
508
|
-
|
|
509
|
-
|
|
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
|
}
|