@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,2158 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import {createHash, randomBytes, randomUUID} from 'node:crypto';
5
+ import {execFile, spawn} from 'node:child_process';
6
+ import {setTimeout as delay} from 'node:timers/promises';
7
+ import {fileURLToPath} from 'node:url';
8
+ import {getPlatform} from './platform-registry.mjs';
9
+ import {inspectPath, within} from './scope.mjs';
10
+ import {
11
+ buildReport, compareRuns, isolationPasses, originalTestSpelling, PARSER_SCHEMA_VERSION, summarizeCommand, validateRegexSpec
12
+ } from './test-results.mjs';
13
+
14
+ export const VERIFY_COMMANDS = Object.freeze(['verify-start', 'verify-status', 'verify-compare', 'verify-rerun', 'verify-cleanup']);
15
+ export const HEARTBEAT_INTERVAL_MS = 2000;
16
+ export const HEARTBEAT_STALE_MS = 15000;
17
+ export const LOAD_SAMPLE_MS = 30000;
18
+ export const DEFAULT_TIMEOUT_MS = 3600000;
19
+ export const MAX_TIMEOUT_MS = 21600000;
20
+ export const KILL_GRACE_MS = 10000;
21
+ export const RAW_STREAM_CAP = 64 * 1024 * 1024;
22
+ export const GLOB_FILE_LIMIT = 100000;
23
+ export const TOOL_VERSION_TIMEOUT_MS = 30000;
24
+ export const ENV_BASE_ALLOWLIST = Object.freeze(['PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_ALL', 'TZ', 'PYTHONDONTWRITEBYTECODE']);
25
+ export const LOAD_START_RATIO = 0.5;
26
+ export const LOAD_SAMPLE_RATIO = 1.5;
27
+ export const RERUN_DEFAULT_LIMIT = 3;
28
+ export const RERUN_MAX_LIMIT = 10;
29
+ export const DEFAULT_TOP_N = 10;
30
+ export const MAX_TOP_N = 100;
31
+ export const MAX_WAIT_MS = 600000;
32
+
33
+ const RUN_ID = /^\d{8}T\d{6}Z-[0-9a-f]{8}$/;
34
+ const REVISION = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
35
+ const CACHE_KEY = /^[0-9a-f]{64}$/;
36
+ const BLOCKED_CHILD_ENV = new Set(['ARC_BRIDGE_CHILD', 'NODE_TEST_CONTEXT']);
37
+ const SANDBOX_MODES = ['none', 'sandboxed', 'escalated', 'unknown'];
38
+ const RUNTIME_FILES = ['verify-cli.mjs', 'final-verify.mjs', 'test-results.mjs', 'node-test-reporter.mjs'];
39
+ const REPORTER = new URL('./node-test-reporter.mjs', import.meta.url);
40
+ const LOCKFILES = new Set([
41
+ 'package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lock', 'bun.lockb',
42
+ 'Cargo.lock', 'Gemfile.lock', 'Pipfile.lock', 'poetry.lock', 'uv.lock', 'composer.lock',
43
+ 'go.sum', 'go.work.sum', 'gradle.lockfile', 'flake.lock', 'packages.lock.json',
44
+ ]);
45
+ const terminal = state => state === 'succeeded' || state === 'failed';
46
+ const nowIso = () => new Date().toISOString();
47
+
48
+ export class VerifyError extends Error {
49
+ constructor(code, decision = 'deny', extra = {}) {
50
+ super(extra.message ?? code);
51
+ this.code = code;
52
+ this.result = {...extra, code, decision};
53
+ }
54
+ }
55
+
56
+ function expect(condition, message) {
57
+ if (!condition) throw new VerifyError('invalid_request', 'deny', {message});
58
+ }
59
+
60
+ function exact(value, required, optional = []) {
61
+ expect(value && typeof value === 'object' && [null, Object.prototype].includes(Object.getPrototypeOf(value)), 'Expected an object');
62
+ expect(required.every(key => Object.hasOwn(value, key)) && Object.keys(value).every(key => required.includes(key) || optional.includes(key)),
63
+ 'Invalid object keys');
64
+ }
65
+
66
+ function string(value) {
67
+ expect(typeof value === 'string' && !value.includes('\0'), 'Expected a string without NUL');
68
+ return value;
69
+ }
70
+
71
+ function nonempty(value) {
72
+ expect(string(value).length > 0, 'Expected a nonempty string');
73
+ return value;
74
+ }
75
+
76
+ function list(value, map) {
77
+ expect(Array.isArray(value), 'Expected an array');
78
+ return value.map(map);
79
+ }
80
+
81
+ function oneOf(value, choices) {
82
+ expect(choices.includes(value), 'Invalid enum value');
83
+ return value;
84
+ }
85
+
86
+ function integer(value, min, max) {
87
+ expect(Number.isSafeInteger(value) && value >= min && value <= max, 'Integer out of range');
88
+ return value;
89
+ }
90
+
91
+ function boolean(value) {
92
+ expect(typeof value === 'boolean', 'Expected a boolean');
93
+ return value;
94
+ }
95
+
96
+ function tagged(value, pattern) {
97
+ expect(pattern.test(nonempty(value)), 'Invalid identifier');
98
+ return value;
99
+ }
100
+
101
+ function optional(record, key, validate, fallback) {
102
+ return Object.hasOwn(record, key) ? validate(record[key]) : fallback;
103
+ }
104
+
105
+ function envName(value) {
106
+ expect(/^[^=]+$/.test(nonempty(value)), 'Invalid environment variable name');
107
+ return value;
108
+ }
109
+
110
+ function envMap(value) {
111
+ expect(value && typeof value === 'object' && [null, Object.prototype].includes(Object.getPrototypeOf(value)), 'Expected an environment object');
112
+ return Object.fromEntries(Object.entries(value).map(([name, item]) => [envName(name), string(item)]));
113
+ }
114
+
115
+ function relativePath(value) {
116
+ nonempty(value);
117
+ expect(!path.posix.isAbsolute(value) && !path.win32.isAbsolute(value) && !/^[a-z]:/i.test(value) &&
118
+ !value.includes('\\') && !value.split('/').some(segment => segment === '..' || segment.toLowerCase() === '.git'), 'Expected a path inside the worktree');
119
+ return path.posix.normalize(value).replace(/\/$/, '');
120
+ }
121
+
122
+ function absolutePath(value) {
123
+ expect(path.isAbsolute(nonempty(value)), 'Expected an absolute path');
124
+ return path.resolve(value);
125
+ }
126
+
127
+ function worktreeCwd(value) {
128
+ nonempty(value);
129
+ if (value === '{worktree}') return value;
130
+ const prefix = '{worktree}/';
131
+ const relative = relativePath(value.startsWith(prefix) ? value.slice(prefix.length) : value);
132
+ return relative === '.' ? '{worktree}' : prefix + relative;
133
+ }
134
+
135
+ function commandArg(value) {
136
+ if (typeof value === 'string') return string(value);
137
+ exact(value, ['glob']);
138
+ return {glob: relativePath(value.glob)};
139
+ }
140
+
141
+ function validateResults(results) {
142
+ exact(results, ['format'], ['path', 'stream', 'pattern', 'statusMap']);
143
+ const {format} = results;
144
+ oneOf(format, ['none', 'tap', 'junit-xml', 'regex']);
145
+ if (format === 'none') {
146
+ exact(results, ['format']);
147
+ return {format};
148
+ }
149
+ if (format !== 'regex') {
150
+ const hasPath = Object.hasOwn(results, 'path');
151
+ exact(results, ['format', hasPath ? 'path' : 'stream']);
152
+ return hasPath ? {format, path: relativePath(results.path)} : {format, stream: oneOf(results.stream, ['stdout', 'stderr'])};
153
+ }
154
+ exact(results, ['format', 'stream', 'pattern', 'statusMap']);
155
+ exact(results.statusMap, ['pass', 'fail', 'skip'], ['fileError']);
156
+ const validated = {
157
+ format, stream: oneOf(results.stream, ['stdout', 'stderr', 'both']), pattern: string(results.pattern),
158
+ statusMap: Object.fromEntries(Object.entries(results.statusMap).map(([key, values]) => [key, list(values, string)]))
159
+ };
160
+ try {
161
+ validateRegexSpec(validated);
162
+ } catch (error) {
163
+ throw new VerifyError('invalid_request', 'deny', {message: error.message});
164
+ }
165
+ return validated;
166
+ }
167
+
168
+ function validateTask(task, command = false) {
169
+ exact(task, command ? ['id', 'executable', 'args', 'results'] : ['executable', 'args'],
170
+ command ? ['cwd', 'env', 'timeoutMs', 'isolate'] : ['cwd', 'env', 'timeoutMs']);
171
+ const {executable, args} = task;
172
+ const validated = {
173
+ executable: nonempty(executable), args: list(args, command ? commandArg : string),
174
+ cwd: optional(task, 'cwd', worktreeCwd, '{worktree}'), env: optional(task, 'env', envMap, {}),
175
+ timeoutMs: optional(task, 'timeoutMs', value => integer(value, 1, MAX_TIMEOUT_MS), DEFAULT_TIMEOUT_MS)
176
+ };
177
+ if (!command) return validated;
178
+ validated.id = tagged(task.id, /^[a-z0-9][a-z0-9_-]{0,31}$/);
179
+ validated.results = validateResults(task.results);
180
+ if (Object.hasOwn(task, 'isolate')) {
181
+ exact(task.isolate, ['args']);
182
+ validated.isolate = {args: list(task.isolate.args, string)};
183
+ }
184
+ return validated;
185
+ }
186
+
187
+ function validateStart(input) {
188
+ exact(input, ['hostPlatform', 'executionEnvironment', 'sandboxMode', 'role', 'revision', 'commands', 'keyInputs', 'detach'],
189
+ ['prepare', 'seedFiles', 'declaredConcurrent', 'snapshotWorkingTree']);
190
+ const {hostPlatform, executionEnvironment, sandboxMode, role, revision, keyInputs} = input;
191
+ expect(getPlatform(hostPlatform)?.executionEnvironments.includes(executionEnvironment), 'Host and execution environment mismatch');
192
+ oneOf(role, ['baseline', 'head']);
193
+ const snapshotWorkingTree = optional(input, 'snapshotWorkingTree', boolean, false);
194
+ expect(!snapshotWorkingTree || role === 'head', 'Snapshot requires a head run');
195
+ const commands = list(input.commands, task => validateTask(task, true));
196
+ expect(commands.length > 0 && new Set(commands.map(task => task.id)).size === commands.length, 'Expected unique command IDs');
197
+ exact(keyInputs, ['envNames', 'toolVersionCommands', 'dependencyPaths', 'artifactPaths']);
198
+ const prepare = optional(input, 'prepare', tasks => list(tasks, task => validateTask(task)), []);
199
+ const seedFiles = optional(input, 'seedFiles', seeds => list(seeds, seed => {
200
+ exact(seed, ['source', 'dest']);
201
+ return {source: absolutePath(seed.source), dest: relativePath(seed.dest)};
202
+ }), []);
203
+ expect(new Set(seedFiles.map(seed => seed.dest)).size === seedFiles.length && seedFiles.every(seed => seed.dest !== '.'),
204
+ 'Expected distinct seed destinations');
205
+ return {
206
+ hostPlatform, executionEnvironment, sandboxMode: oneOf(sandboxMode, SANDBOX_MODES), role,
207
+ revision: tagged(revision, REVISION), commands, prepare, seedFiles,
208
+ detach: boolean(input.detach), snapshotWorkingTree, declaredConcurrent: optional(input, 'declaredConcurrent', boolean, false),
209
+ keyInputs: {
210
+ envNames: [...new Set(list(keyInputs.envNames, envName))].sort(),
211
+ toolVersionCommands: list(keyInputs.toolVersionCommands, tool => {
212
+ exact(tool, ['executable', 'args']);
213
+ return {executable: nonempty(tool.executable), args: list(tool.args, string)};
214
+ }),
215
+ dependencyPaths: [...new Set(list(keyInputs.dependencyPaths, absolutePath))].sort(),
216
+ artifactPaths: [...new Set(list(keyInputs.artifactPaths, relativePath))].sort()
217
+ }
218
+ };
219
+ }
220
+
221
+ export function validateVerifyInput(command, input) {
222
+ const runId = value => tagged(value, RUN_ID);
223
+ if (command === 'verify-start') return validateStart(input);
224
+ if (command === 'verify-status') {
225
+ exact(input, ['runId'], ['waitMs']);
226
+ return {runId: runId(input.runId), waitMs: optional(input, 'waitMs', value => integer(value, 0, MAX_WAIT_MS), 0)};
227
+ }
228
+ if (command === 'verify-compare') {
229
+ exact(input, ['baseRunId', 'headRunId'], ['topN']);
230
+ return {baseRunId: runId(input.baseRunId), headRunId: runId(input.headRunId),
231
+ topN: optional(input, 'topN', value => integer(value, 1, MAX_TOP_N), DEFAULT_TOP_N)};
232
+ }
233
+ if (command === 'verify-rerun') {
234
+ exact(input, ['runId', 'testId', 'attempt', 'sandboxMode'], ['limit']);
235
+ return {
236
+ runId: runId(input.runId), testId: nonempty(input.testId), attempt: integer(input.attempt, 1, Number.MAX_SAFE_INTEGER),
237
+ sandboxMode: oneOf(input.sandboxMode, SANDBOX_MODES), limit: optional(input, 'limit', value => integer(value, 1, RERUN_MAX_LIMIT), RERUN_DEFAULT_LIMIT)
238
+ };
239
+ }
240
+ expect(command === 'verify-cleanup', 'Expected verify command');
241
+ const byRun = Boolean(input && Object.hasOwn(input, 'runId'));
242
+ exact(input, ['dryRun', byRun ? 'runId' : 'cacheKey']);
243
+ return {dryRun: boolean(input.dryRun), ...(byRun ? {runId: runId(input.runId)} : {cacheKey: tagged(input.cacheKey, CACHE_KEY)})};
244
+ }
245
+
246
+ export function canonicalJson(value) {
247
+ if (Array.isArray(value)) return '[' + value.map(canonicalJson).join(',') + ']';
248
+ if (value && typeof value === 'object') {
249
+ return '{' + Object.keys(value).sort().map(key => JSON.stringify(key) + ':' + canonicalJson(value[key])).join(',') + '}';
250
+ }
251
+ return JSON.stringify(value);
252
+ }
253
+
254
+ export function sha256Hex(data) {
255
+ return createHash('sha256').update(data).digest('hex');
256
+ }
257
+
258
+ const hashJson = value => sha256Hex(canonicalJson(value));
259
+ const posixPath = value => value.split(path.sep).join('/');
260
+
261
+ function globExpression(pattern) {
262
+ let patternRegex = '';
263
+ for (let i = 0; i < pattern.length; i++) {
264
+ const char = pattern[i];
265
+ if (char === '*' && pattern[i + 1] === '*') {
266
+ if (pattern[i + 2] === '/' && (i === 0 || pattern[i - 1] === '/')) {
267
+ patternRegex += '(?:[^/]+/)*';
268
+ i += 2;
269
+ } else {
270
+ patternRegex += '[\\s\\S]*';
271
+ i++;
272
+ }
273
+ } else if (char === '*') patternRegex += '[^/]*';
274
+ else if (char === '?') patternRegex += '[^/]';
275
+ else patternRegex += char.replace(/[|\\{}()[\]^$+.]/g, '\\$&');
276
+ }
277
+ return new RegExp('^' + patternRegex + '(?![\\s\\S])', 'u');
278
+ }
279
+
280
+ export function expandGlob(pattern, trackedPaths) {
281
+ const matches = globExpression(pattern);
282
+ return trackedPaths.filter(filename => matches.test(filename)).sort();
283
+ }
284
+
285
+ export function buildChildEnv({parentEnv = process.env, envNames = [], extraEnv = {}} = {}) {
286
+ const entries = new Map();
287
+ for (const key of [...ENV_BASE_ALLOWLIST, ...envNames]) {
288
+ if (Object.hasOwn(parentEnv, key) && typeof parentEnv[key] === 'string') entries.set(key, parentEnv[key]);
289
+ }
290
+ for (const [key, value] of Object.entries(extraEnv)) entries.set(key, value);
291
+ return Object.fromEntries([...entries].filter(([key]) => !BLOCKED_CHILD_ENV.has(key.toUpperCase())));
292
+ }
293
+
294
+ export function classifyLoad({platform, cpus, startLoadavg, samples = [], overlaps = [], declaredConcurrent = false, samplesMissing = false}) {
295
+ if (samplesMissing || !Array.isArray(startLoadavg) || !startLoadavg.length || !Number.isFinite(startLoadavg[0]) || !cpus ||
296
+ (platform === 'win32' && startLoadavg.every(value => value === 0))) return 'unknown';
297
+ if (declaredConcurrent || overlaps.length || startLoadavg[0] / cpus >= LOAD_START_RATIO ||
298
+ samples.some(sample => sample.loadavg[0] > cpus * LOAD_SAMPLE_RATIO)) return 'contended';
299
+ return 'quiet';
300
+ }
301
+
302
+ function allow(payload) {
303
+ return {decision: 'allow', code: 'ok', ...payload};
304
+ }
305
+
306
+ function storageError(error, extra = {}) {
307
+ return new VerifyError('storage_unavailable', 'hold', {...extra, message: error.message});
308
+ }
309
+
310
+ function isSandboxError(error) {
311
+ return /operation not permitted|permission denied|sandbox/i.test(error.message) || ['EACCES', 'EPERM'].includes(error.code);
312
+ }
313
+
314
+ function verifyErrorResult(error) {
315
+ if (error instanceof VerifyError) return error.result;
316
+ throw error;
317
+ }
318
+
319
+ export async function dispatchVerify(command, ctx) {
320
+ if (command === 'verify-start') return verifyStart(ctx);
321
+ if (command === 'verify-status') return verifyStatus(ctx);
322
+ if (command === 'verify-compare') return verifyCompare(ctx);
323
+ if (command === 'verify-rerun') return verifyRerun(ctx);
324
+ if (command === 'verify-cleanup') return verifyCleanup(ctx);
325
+ return new VerifyError('invalid_request').result;
326
+ }
327
+
328
+ function gitRunner(env, envNames = [], internalEnv = {}) {
329
+ const allowed = buildChildEnv({parentEnv: env, envNames});
330
+ const gitEnv = Object.fromEntries(Object.entries(allowed).filter(([key]) => !key.toUpperCase().startsWith('GIT_')));
331
+ Object.assign(gitEnv, {GIT_OPTIONAL_LOCKS: '0', GIT_NO_REPLACE_OBJECTS: '1', GIT_NO_LAZY_FETCH: '1', GIT_TERMINAL_PROMPT: '0'});
332
+ return (cwd, args) => new Promise((resolve, reject) => {
333
+ execFile('git', ['--no-pager', '-c', 'core.fsmonitor=false', ...args], {
334
+ cwd, env: {...gitEnv, ...internalEnv}, shell: false, encoding: 'utf8', maxBuffer: RAW_STREAM_CAP
335
+ }, (error, stdout, stderr) => {
336
+ if (error && typeof error.code !== 'number') reject(error);
337
+ else resolve({status: error?.code ?? 0, stdout, stderr});
338
+ });
339
+ });
340
+ }
341
+
342
+ async function gitOutput(run, cwd, args, accepted = [0]) {
343
+ const result = await run(cwd, args);
344
+ if (!accepted.includes(result.status)) throw Error(result.stderr.trim() || 'Git failed: ' + args.join(' '));
345
+ return result.stdout;
346
+ }
347
+
348
+ async function getStorage(cwd, git) {
349
+ try {
350
+ const common = (await gitOutput(git, cwd, ['rev-parse', '--git-common-dir'])).replace(/\r?\n$/, '');
351
+ const commonDir = fs.realpathSync(path.resolve(cwd, common));
352
+ return {commonDir, store: path.join(commonDir, 'arc', 'verify')};
353
+ } catch (error) {
354
+ throw storageError(error);
355
+ }
356
+ }
357
+
358
+ function makeDirectory(directory, recursive = false) {
359
+ fs.mkdirSync(directory, {mode: 0o700, recursive});
360
+ }
361
+
362
+ function atomicWrite(filename, data) {
363
+ const temp = filename + '.' + randomBytes(8).toString('hex') + '.tmp';
364
+ const fd = fs.openSync(temp, 'wx', 0o600);
365
+ try {
366
+ try {
367
+ fs.writeFileSync(fd, data);
368
+ fs.fsyncSync(fd);
369
+ } finally {
370
+ fs.closeSync(fd);
371
+ }
372
+ fs.renameSync(temp, filename);
373
+ } catch (error) {
374
+ fs.rmSync(temp, {force: true});
375
+ throw error;
376
+ }
377
+ }
378
+
379
+ function writeJson(filename, data) {
380
+ atomicWrite(filename, JSON.stringify(data) + '\n');
381
+ }
382
+
383
+ function readJson(filename) {
384
+ const st = fs.lstatSync(filename);
385
+ if (!st.isFile()) throw Error('Expected a regular JSON file');
386
+ return JSON.parse(fs.readFileSync(filename, 'utf8'));
387
+ }
388
+
389
+ function appendJson(filename, data) {
390
+ const fd = fs.openSync(filename, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_APPEND | (fs.constants.O_NOFOLLOW ?? 0), 0o600);
391
+ try {
392
+ fs.writeFileSync(fd, JSON.stringify(data) + '\n');
393
+ fs.fsyncSync(fd);
394
+ } finally {
395
+ fs.closeSync(fd);
396
+ }
397
+ }
398
+
399
+ function machineIdentity(store, {create = true} = {}) {
400
+ const filename = path.join(store, 'machine.json');
401
+ let machine;
402
+ let fd;
403
+ try {
404
+ if (create) fd = fs.openSync(filename, 'wx', 0o600);
405
+ } catch (error) {
406
+ if (error.code !== 'EEXIST') throw error;
407
+ }
408
+ if (fd === undefined) machine = readJson(filename);
409
+ else {
410
+ try {
411
+ machine = {randomId: randomUUID()};
412
+ fs.writeFileSync(fd, JSON.stringify(machine) + '\n');
413
+ fs.fsyncSync(fd);
414
+ } finally {
415
+ fs.closeSync(fd);
416
+ }
417
+ }
418
+ if (!/^[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/.test(machine.randomId)) throw Error('Invalid machine identifier');
419
+ const cpus = os.cpus();
420
+ return hashJson([machine.randomId, os.hostname(), os.platform(), os.arch(), cpus[0]?.model ?? '', cpus.length,
421
+ os.totalmem(), os.userInfo().uid, fs.realpathSync(os.homedir())]);
422
+ }
423
+
424
+ function makeRunId() {
425
+ return nowIso().replace(/[:-]/g, '').replace(/\.\d{3}Z$/, 'Z') + '-' + randomBytes(4).toString('hex');
426
+ }
427
+
428
+ function executablePath(executable, env, cwd) {
429
+ const candidates = path.isAbsolute(executable) ? [executable] :
430
+ (env.PATH?.split(path.delimiter) ?? []).map(directory => path.resolve(cwd, directory, executable));
431
+ for (const candidate of candidates) {
432
+ const extensions = process.platform === 'win32' && !path.extname(candidate) ? ['', '.exe', '.com'] : [''];
433
+ for (const extension of extensions) {
434
+ try {
435
+ const file = fs.realpathSync(candidate + extension);
436
+ fs.accessSync(file, fs.constants.X_OK);
437
+ if (fs.statSync(file).isFile()) return file;
438
+ } catch (error) {
439
+ if (!['ENOENT', 'EACCES', 'ENOTDIR', 'EPERM', 'ELOOP'].includes(error.code)) throw error;
440
+ }
441
+ }
442
+ }
443
+ throw new VerifyError('executable_not_found', 'deny', {message: 'Executable not found: ' + executable});
444
+ }
445
+
446
+ function normalizeWorktreePrefix(value, worktree) {
447
+ if (value === worktree) return '{worktree}';
448
+ const prefix = worktree + path.sep;
449
+ return value.startsWith(prefix) ? '{worktree}/' + posixPath(value.slice(prefix.length)) : value;
450
+ }
451
+
452
+ function resolveTask(task, cwd, environment, trackedPaths, reporter, addReason, globLimit) {
453
+ const env = {...environment, ...buildChildEnv({parentEnv: {}, extraEnv: task.env})};
454
+ const worktreeLookup = !path.isAbsolute(task.executable) && env.PATH?.split(path.delimiter).some(directory =>
455
+ directory.includes('{worktree}') || !path.isAbsolute(directory));
456
+ const executable = worktreeLookup ? task.executable : executablePath(task.executable, env, cwd);
457
+ const expandedFiles = [];
458
+ const args = task.args.flatMap(arg => {
459
+ if (typeof arg === 'string') return [arg.replaceAll('{arcNodeReporter}', () => reporter)];
460
+ const files = expandGlob(arg.glob, trackedPaths);
461
+ if (!files.length) throw new VerifyError('glob_empty', 'hold', {message: arg.glob});
462
+ if (files.length > globLimit) addReason('glob_over_limit');
463
+ expandedFiles.push(...files);
464
+ return files;
465
+ });
466
+ return {...task, executable, args, env, expandedFiles};
467
+ }
468
+
469
+ async function readRevision(git, cwd, revision, addReason) {
470
+ let commit;
471
+ try {
472
+ commit = (await gitOutput(git, cwd, ['rev-parse', '--verify', revision + '^{commit}'])).trim();
473
+ } catch {
474
+ throw new VerifyError('unknown_revision');
475
+ }
476
+ let tree = null;
477
+ const entries = new Map();
478
+ try {
479
+ tree = (await gitOutput(git, cwd, ['rev-parse', '--verify', commit + '^{tree}'])).trim();
480
+ } catch {
481
+ addReason('git_metadata_unavailable');
482
+ }
483
+ try {
484
+ for (const entry of (await gitOutput(git, cwd, ['ls-tree', '-rz', tree ?? commit])).split('\0')) {
485
+ if (!entry) continue;
486
+ const tab = entry.indexOf('\t');
487
+ const [mode, type, oid] = entry.slice(0, tab).split(' ');
488
+ entries.set(entry.slice(tab + 1), {mode, type, oid});
489
+ }
490
+ } catch {
491
+ addReason('git_metadata_unavailable');
492
+ return {commit, tree, entries: null};
493
+ }
494
+ return {commit, tree, entries};
495
+ }
496
+
497
+ export async function createSnapshot({cwd, head, runDir}, {env = process.env, envNames = [], beforeSnapshotWriteTree} = {}) {
498
+ const index = path.join(runDir, 'snapshot.index');
499
+ const git = gitRunner(env, envNames, {GIT_INDEX_FILE: index});
500
+ try {
501
+ const root = (await gitOutput(git, cwd, ['rev-parse', '--show-toplevel'])).replace(/\r?\n$/, '');
502
+ const read = args => gitOutput(git, root, args);
503
+ const writeIndex = async args => {
504
+ try {
505
+ return await read(args);
506
+ } finally {
507
+ // Git can replace the index with a new file created under its umask.
508
+ if (pathStat(index)) fs.chmodSync(index, 0o600);
509
+ }
510
+ };
511
+ await writeIndex(['read-tree', head]);
512
+ await writeIndex(['add', '-A', '--', '.']);
513
+ await beforeSnapshotWriteTree?.();
514
+ const tree = (await writeIndex(['write-tree'])).trim();
515
+ const date = (await read(['show', '-s', '--format=%cI', head])).trim();
516
+ const commitGit = gitRunner(env, envNames, {
517
+ GIT_AUTHOR_NAME: 'arc-verify', GIT_AUTHOR_EMAIL: 'arc-verify',
518
+ GIT_COMMITTER_NAME: 'arc-verify', GIT_COMMITTER_EMAIL: 'arc-verify',
519
+ GIT_AUTHOR_DATE: date, GIT_COMMITTER_DATE: date
520
+ });
521
+ const commit = (await gitOutput(commitGit, root, ['-c', 'commit.gpgSign=false', '-c', 'i18n.commitEncoding=UTF-8',
522
+ 'commit-tree', tree, '-p', head, '-m', 'arc-verify snapshot'])).trim();
523
+ const names = (await read(['diff-tree', '-r', '--no-renames', '--name-status', '-z', head, tree])).split('\0');
524
+ const included = [];
525
+ for (let i = 0; i + 1 < names.length; i += 2) included.push({status: names[i], path: names[i + 1]});
526
+ const ignored = (await read(['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'])).split('\0').filter(Boolean);
527
+ const submodules = (await read(['status', '--porcelain=v2', '-z', '--no-renames', '--ignore-submodules=none'])).split('\0')
528
+ .map(record => /^1 \S+ S.([M.][U.])(?: \S+){5} ([\s\S]+)$/.exec(record))
529
+ .filter(record => record && record[1] !== '..')
530
+ .map(record => record[2]);
531
+ return {commit, tree, included, excluded: {ignored, submodules}};
532
+ } catch (error) {
533
+ throw new VerifyError('snapshot_failed', 'hold', {runId: path.basename(runDir), message: error.message});
534
+ }
535
+ }
536
+
537
+ async function worktreeRevisionFiles(git, runCwd, input) {
538
+ if (input.seedFiles.length || input.commands.some(task => task.args.some(arg => typeof arg !== 'string'))) {
539
+ // Git can still enumerate the isolated index when tree inspection is unavailable.
540
+ const paths = (await gitOutput(git, runCwd, ['ls-files', '-z', '--cached'])).split('\0').filter(Boolean);
541
+ return new Map(paths.map(filename => [filename, null]));
542
+ }
543
+ return new Map();
544
+ }
545
+
546
+ function readSeeds(input, cwd, entries) {
547
+ const base = fs.realpathSync(cwd);
548
+ return input.seedFiles.map(({source, dest}) => {
549
+ const overlaps = other => other === dest || other.startsWith(dest + '/') || dest.startsWith(other + '/');
550
+ if ([...entries.keys()].some(overlaps)) throw new VerifyError('seed_conflicts_tracked');
551
+ expect(!input.seedFiles.some(seed => seed.dest !== dest && overlaps(seed.dest)), 'Seed destinations overlap');
552
+ let data;
553
+ try {
554
+ const resolved = fs.realpathSync(source);
555
+ if (!within(base, resolved) || resolved.split(path.sep).some(part => part.toLowerCase() === '.git') ||
556
+ !fs.statSync(resolved).isFile()) throw Error('Seed source must be a regular file in the checkout');
557
+ data = fs.readFileSync(resolved);
558
+ } catch (error) {
559
+ throw new VerifyError('invalid_request', 'deny', {message: error.message});
560
+ }
561
+ return {dest, data};
562
+ });
563
+ }
564
+
565
+ function pathStat(filename) {
566
+ try {
567
+ return fs.lstatSync(filename);
568
+ } catch (error) {
569
+ if (['ENOENT', 'ENOTDIR'].includes(error.code)) return null;
570
+ throw error;
571
+ }
572
+ }
573
+
574
+ function pathDigest(filename, root, relative) {
575
+ const stat = pathStat(filename);
576
+ if (!stat) return 'absent';
577
+ const resolved = fs.realpathSync(filename);
578
+ if (!within(root, resolved)) throw Error('Hash input escapes its root');
579
+ if (stat.isSymbolicLink()) return sha256Hex(posixPath(fs.readlinkSync(filename)));
580
+ if (stat.isFile()) {
581
+ const bytes = fs.readFileSync(filename);
582
+ return sha256Hex(Buffer.concat([Buffer.from(relative + '\0' + stat.mode.toString(8) + '\0'), bytes]));
583
+ }
584
+ if (!stat.isDirectory()) throw Error('Hash input is not a regular file or directory');
585
+ const children = fs.readdirSync(filename).sort().map(name => {
586
+ const child = relative === '.' ? name : relative + '/' + name;
587
+ return [name, pathDigest(path.join(filename, name), root, child)];
588
+ });
589
+ return hashJson(children);
590
+ }
591
+
592
+ function attemptKeyInput(addReason, reason, read) {
593
+ try {
594
+ return read();
595
+ } catch {
596
+ addReason(reason);
597
+ return null;
598
+ }
599
+ }
600
+
601
+ function dependencyDigest(filename) {
602
+ const stat = pathStat(filename);
603
+ if (!stat) return 'absent';
604
+ const root = stat.isDirectory() ? fs.realpathSync(filename) : fs.realpathSync(path.dirname(filename));
605
+ return pathDigest(filename, root, path.basename(filename));
606
+ }
607
+
608
+ function dependences(paths, entries, cwd, addReason) {
609
+ const expected = new Set(paths.filter(filename => within(cwd, filename)).map(filename => posixPath(path.relative(cwd, filename))));
610
+ const blobs = [...entries].filter(([filename, entry]) =>
611
+ entry?.type === 'blob' && (LOCKFILES.has(path.posix.basename(filename)) || expected.has(filename) ||
612
+ [...expected].some(directory => filename.startsWith(directory + '/')))).map(([filename, entry]) => [filename, entry.oid]);
613
+ return {
614
+ blobs,
615
+ external: paths.map(filename => [posixPath(filename), attemptKeyInput(addReason, 'path_hash_failed', () => dependencyDigest(filename))])
616
+ };
617
+ }
618
+
619
+ function tempIdentity(directory) {
620
+ const real = fs.realpathSync(directory);
621
+ return {path: posixPath(real), type: fs.statfsSync(real).type};
622
+ }
623
+
624
+ async function readGitMetadata(git, cwd) {
625
+ const version = (await gitOutput(git, cwd, ['--version'])).trim();
626
+ const result = await git(cwd, ['config', '--get-regexp', '^filter\\.']);
627
+ if (result.status !== 0 && !(result.status === 1 && !result.stderr && !result.stdout)) {
628
+ throw Error(result.stderr || 'Failed to read Git filter configuration');
629
+ }
630
+ return {version, filterConfig: sha256Hex(result.stdout)};
631
+ }
632
+
633
+ function readRuntimeIdentity() {
634
+ return {
635
+ files: Object.fromEntries(RUNTIME_FILES.map(name => [name, sha256Hex(fs.readFileSync(new URL('./' + name, import.meta.url)))])),
636
+ parserSchemaVersion: PARSER_SCHEMA_VERSION
637
+ };
638
+ }
639
+
640
+ function materializeTask(task, worktree) {
641
+ const replace = value => value.replaceAll('{worktree}', () => worktree);
642
+ return {
643
+ ...task, args: task.args.map(replace), cwd: path.normalize(replace(task.cwd)),
644
+ env: Object.fromEntries(Object.entries(task.env).map(([key, value]) => [key, replace(value)]))
645
+ };
646
+ }
647
+
648
+ function runChild(task, {rawCap = RAW_STREAM_CAP, killGraceMs = KILL_GRACE_MS, onSpawn} = {}) {
649
+ return new Promise((resolve, reject) => {
650
+ const groupKill = process.platform !== 'win32';
651
+ const started = performance.now();
652
+ const child = spawn(task.executable, task.args, {
653
+ cwd: task.cwd, env: task.env, shell: false, detached: groupKill, stdio: ['ignore', 'pipe', 'pipe']
654
+ });
655
+ const buffers = {stdout: [], stderr: []};
656
+ let remaining = rawCap;
657
+ let truncated = false;
658
+ let timedOut = false;
659
+ let close;
660
+ let grace;
661
+ let error;
662
+ const send = signal => {
663
+ try {
664
+ if (groupKill) return process.kill(-child.pid, signal);
665
+ return child.kill(signal);
666
+ } catch (failure) {
667
+ if (failure.code !== 'ESRCH') error ??= failure;
668
+ return false;
669
+ }
670
+ };
671
+ const capture = stream => data => {
672
+ if (data.length > remaining) truncated = true;
673
+ if (remaining > 0) buffers[stream].push(Buffer.from(data.subarray(0, remaining)));
674
+ remaining = Math.max(remaining - data.length, 0);
675
+ };
676
+ child.stdout.on('data', capture('stdout'));
677
+ child.stderr.on('data', capture('stderr'));
678
+ child.on('error', failure => { error ??= failure; });
679
+ if (child.pid !== undefined) {
680
+ try {
681
+ onSpawn?.({pid: child.pid, groupKill});
682
+ } catch (failure) {
683
+ error ??= failure;
684
+ }
685
+ }
686
+ const timeout = setTimeout(() => {
687
+ if (!child.pid) return;
688
+ timedOut = true;
689
+ if (send('SIGTERM')) {
690
+ grace = setTimeout(() => {
691
+ send('SIGKILL');
692
+ grace = undefined;
693
+ if (close) finish();
694
+ }, killGraceMs);
695
+ }
696
+ }, task.timeoutMs);
697
+ function finish() {
698
+ clearTimeout(timeout);
699
+ clearTimeout(grace);
700
+ if (error) reject(error);
701
+ else resolve({
702
+ buffers: {stdout: Buffer.concat(buffers.stdout), stderr: Buffer.concat(buffers.stderr)},
703
+ exit: {...close, timedOut}, groupKill, truncated, wallMs: performance.now() - started
704
+ });
705
+ }
706
+ child.once('close', (code, signal) => {
707
+ close = {code, signal};
708
+ if (!grace || !groupKill || !send(0)) finish();
709
+ });
710
+ });
711
+ }
712
+
713
+ function versionCommand(task, {cwd, env, timeoutMs}, reporter) {
714
+ return {
715
+ executable: executablePath(task.executable, env, cwd),
716
+ args: task.args.map(arg => arg.replaceAll('{arcNodeReporter}', () => reporter)),
717
+ cwd, env, timeoutMs
718
+ };
719
+ }
720
+
721
+ async function versionDigests(tasks, {cwd, worktree, addReason, internal}) {
722
+ const versions = [];
723
+ for (const task of tasks) {
724
+ const runnable = worktree ? materializeTask({...task, cwd: '{worktree}'}, worktree) : {...task, cwd};
725
+ try {
726
+ const result = await runChild(runnable, internal);
727
+ if (result.exit.code !== 0 || result.exit.timedOut || result.truncated) addReason('tool_version_failed');
728
+ const summarize = buffer => worktree
729
+ ? buffer.toString('utf8').split('\n').map(line => normalizeWorktreePrefix(line, worktree)).join('\n')
730
+ : buffer;
731
+ versions.push({
732
+ executable: posixPath(task.executable), args: task.args, exitCode: result.exit.code,
733
+ stdout: sha256Hex(summarize(result.buffers.stdout)), stderr: sha256Hex(summarize(result.buffers.stderr))
734
+ });
735
+ } catch {
736
+ addReason('tool_version_failed');
737
+ versions.push({executable: posixPath(task.executable), args: task.args, exitCode: null});
738
+ }
739
+ }
740
+ return versions;
741
+ }
742
+
743
+ function phase1Task(task, worktree) {
744
+ const executable = worktree ? normalizeWorktreePrefix(task.executable, worktree) : task.executable;
745
+ return {...task, executable: posixPath(executable)};
746
+ }
747
+
748
+ async function statusEntries(git, worktree, all = false) {
749
+ const args = ['status', '--porcelain=v1', '-z', '--ignored'];
750
+ if (all) args.push('--untracked-files=all');
751
+ const records = (await gitOutput(git, worktree, args)).split('\0');
752
+ const entries = [];
753
+ for (let i = 0; i < records.length; i++) {
754
+ if (!records[i]) continue;
755
+ const status = records[i].slice(0, 2);
756
+ const filename = records[i].slice(3);
757
+ entries.push({status, path: filename, ...(/[RC]/.test(status) ? {from: records[++i]} : {})});
758
+ }
759
+ return entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
760
+ }
761
+
762
+ function topLevelIgnored(entries) {
763
+ return [...new Set(entries.filter(entry => entry.status === '!!').map(entry => entry.path.split('/')[0]))].sort();
764
+ }
765
+
766
+ function matchingWorktreePaths(pattern, root, limit, addReason) {
767
+ if (!/[*?]/.test(pattern)) return [pattern];
768
+ const prefix = pattern.slice(0, pattern.search(/[*?]/)).split('/').slice(0, -1).join('/');
769
+ const start = path.resolve(root, prefix);
770
+ const matches = globExpression(pattern);
771
+ const found = [];
772
+ function visit(directory, relative) {
773
+ if (!within(root, fs.realpathSync(directory))) throw Error('Glob escapes its root');
774
+ for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {
775
+ if (entry.name.toLowerCase() === '.git') continue;
776
+ const filename = relative ? relative + '/' + entry.name : entry.name;
777
+ if (matches.test(filename)) {
778
+ found.push(filename);
779
+ if (found.length > limit) {
780
+ addReason('glob_over_limit');
781
+ return;
782
+ }
783
+ }
784
+ if (entry.isDirectory()) visit(path.join(directory, entry.name), filename);
785
+ if (found.length > limit) return;
786
+ }
787
+ }
788
+ if (fs.existsSync(start)) visit(start, prefix);
789
+ return found.sort();
790
+ }
791
+
792
+ function artifactDigests(patterns, worktree, limit, addReason) {
793
+ const paths = new Set();
794
+ for (const pattern of patterns) {
795
+ const matches = attemptKeyInput(addReason, 'path_hash_failed', () => matchingWorktreePaths(pattern, worktree, limit, addReason));
796
+ for (const filename of matches?.length ? matches : [pattern]) paths.add(filename);
797
+ }
798
+ return [...paths].sort().map(relative => [relative, attemptKeyInput(addReason, 'path_hash_failed', () => {
799
+ const filename = path.resolve(worktree, relative);
800
+ if (relative !== '.') return pathDigest(filename, worktree, relative);
801
+ const children = fs.readdirSync(worktree).filter(name => name !== '.git').sort();
802
+ return hashJson(children.map(name => [name, pathDigest(path.join(worktree, name), worktree, name)]));
803
+ })]);
804
+ }
805
+
806
+ function worktreeFile(worktree, relative, {followSymlinks = false} = {}) {
807
+ if (path.isAbsolute(relative)) return null;
808
+ const filename = path.resolve(worktree, relative);
809
+ if (!within(worktree, filename)) return null;
810
+ try {
811
+ if (!followSymlinks) {
812
+ let entry = worktree;
813
+ for (const component of path.relative(worktree, filename).split(path.sep)) {
814
+ entry = path.join(entry, component);
815
+ const stat = fs.lstatSync(entry, {bigint: true});
816
+ if (stat.isSymbolicLink()) return {stat};
817
+ if (entry === filename) return stat.isFile() ? {resolved: filename, stat} : null;
818
+ if (!stat.isDirectory()) return null;
819
+ }
820
+ return null;
821
+ }
822
+ const resolved = fs.realpathSync(filename);
823
+ if (!within(worktree, resolved)) return null;
824
+ const stat = fs.lstatSync(resolved, {bigint: true});
825
+ return stat.isFile() ? {resolved, stat} : null;
826
+ } catch (error) {
827
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error;
828
+ return null;
829
+ }
830
+ }
831
+
832
+ function symlinkedWorktreePath(worktree, relative) {
833
+ return Boolean(worktreeFile(worktree, relative)?.stat.isSymbolicLink());
834
+ }
835
+
836
+ function findResultFiles(resultPath, worktree, limit, addReason) {
837
+ return matchingWorktreePaths(resultPath, worktree, limit, addReason).flatMap(relative => {
838
+ const file = worktreeFile(worktree, relative, {followSymlinks: true});
839
+ return file ? [{relative, ...file}] : [];
840
+ });
841
+ }
842
+
843
+ const resultFileVersion = ({resolved, stat}) => [resolved, stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join('\0');
844
+
845
+ function readResultFiles(matches, {raw, id, runId} = {}) {
846
+ const files = [];
847
+ for (const {relative, resolved} of matches) {
848
+ let bytes;
849
+ try {
850
+ bytes = fs.readFileSync(resolved);
851
+ } catch (error) {
852
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error;
853
+ continue;
854
+ }
855
+ if (raw) {
856
+ const copy = path.join(raw, id + '.results', relative);
857
+ try {
858
+ makeDirectory(path.dirname(copy), true);
859
+ atomicWrite(copy, bytes);
860
+ } catch (error) {
861
+ throw storageError(error, {runId});
862
+ }
863
+ }
864
+ files.push({text: bytes.toString('utf8')});
865
+ }
866
+ return files;
867
+ }
868
+
869
+ function summarizeTaskOutput({results, output, worktree, worktreeAlias, files, allowEmpty}) {
870
+ return summarizeCommand({
871
+ format: results.format, results, resultFiles: files,
872
+ ctx: {
873
+ worktree, worktreeAlias,
874
+ fileExists: relative => Boolean(worktreeFile(worktree, relative)?.stat.isFile()),
875
+ fileIsSymlink: relative => symlinkedWorktreePath(worktree, relative)
876
+ },
877
+ streams: Object.fromEntries(Object.entries(output.buffers).map(([key, bytes]) => [key, bytes.toString('utf8')])),
878
+ exit: output.exit, truncated: output.truncated, allowEmpty
879
+ });
880
+ }
881
+
882
+ function cacheEligible(result) {
883
+ return Array.isArray(result?.commands) && result.commands.length > 0 && result.commands.every(({summary}) =>
884
+ summary && !summary.timedOut && Array.isArray(summary.incomplete) && summary.incomplete.length === 0);
885
+ }
886
+
887
+ async function cacheLookup(store, run) {
888
+ if (!run.cacheable || run.role !== 'baseline') return null;
889
+ const dir = path.join(store, 'cache', run.cacheKey);
890
+ const filename = path.join(dir, 'record.json');
891
+ try {
892
+ await inspectPath(dir, {missing: true, directory: true});
893
+ if (!pathStat(filename)) return null;
894
+ const record = readJson(filename);
895
+ if (record.cacheKey !== run.cacheKey || !RUN_ID.test(record.runId) || !CACHE_KEY.test(record.resultSha256)) throw Error('Invalid record');
896
+ if (record.loadClass !== 'quiet') return null;
897
+ const previousDir = path.join(store, 'runs', record.runId);
898
+ await inspectPath(previousDir, {directory: true});
899
+ const previous = readJson(path.join(previousDir, 'run.json'));
900
+ if (previous.state !== 'succeeded' || previous.role !== 'baseline' || previous.load?.class !== 'quiet' ||
901
+ !previous.cacheable || previous.cacheKey !== run.cacheKey) return null;
902
+ const resultFile = path.join(previousDir, 'result.json');
903
+ if (!fs.lstatSync(resultFile).isFile()) throw Error('Expected a regular result file');
904
+ const bytes = fs.readFileSync(resultFile);
905
+ if (sha256Hex(bytes) !== record.resultSha256) throw Error('Result hash mismatch');
906
+ const result = JSON.parse(bytes.toString('utf8'));
907
+ if (!cacheEligible(result)) return null;
908
+ return {runId: record.runId, bytes, result, resultSha256: record.resultSha256};
909
+ } catch {
910
+ run.cacheMissReason = 'cache_corrupt';
911
+ return null;
912
+ }
913
+ }
914
+
915
+ async function validateStorePath(directory, {create = false} = {}) {
916
+ try {
917
+ await inspectPath(directory, {missing: true, directory: true});
918
+ if (create) makeDirectory(directory, true);
919
+ } catch (error) {
920
+ throw storageError(error);
921
+ }
922
+ }
923
+
924
+ async function recordHistory(store, run, resultSha256, result) {
925
+ const cacheDir = path.join(store, 'cache', run.cacheKey ?? run.cacheKeyPhase1);
926
+ const byPhase1 = path.join(store, 'cache', 'by-phase1');
927
+ await validateStorePath(cacheDir, {create: true});
928
+ await validateStorePath(byPhase1, {create: true});
929
+ const entry = {runId: run.runId, role: run.role, state: run.state, loadClass: run.load.class, resultSha256};
930
+ appendJson(path.join(cacheDir, 'history.jsonl'), entry);
931
+ appendJson(path.join(byPhase1, run.cacheKeyPhase1 + '.jsonl'), {...entry, cacheKey: run.cacheKey});
932
+ if (run.role === 'baseline' && run.state === 'succeeded' && run.cacheable && !run.cacheHit &&
933
+ run.load.class === 'quiet' && cacheEligible(result)) {
934
+ writeJson(path.join(cacheDir, 'record.json'), {
935
+ cacheKey: run.cacheKey, runId: run.runId, resultSha256, loadClass: run.load.class, createdAt: nowIso()
936
+ });
937
+ }
938
+ }
939
+
940
+ function statusPayload(run, heartbeat, result) {
941
+ return allow({
942
+ runId: run.runId, role: run.role ?? null, state: run.state, revision: run.revision ?? null,
943
+ commit: run.commit ?? null, tree: run.tree ?? null, cacheKeyPhase1: run.cacheKeyPhase1 ?? null,
944
+ cacheKey: run.cacheKey ?? null, cacheable: run.cacheable ?? null, uncacheableReasons: run.uncacheableReasons ?? [],
945
+ cacheHit: run.cacheHit ?? false, ...(run.reusedFrom ? {reusedFrom: run.reusedFrom} : {}),
946
+ ...(run.cacheMissReason ? {cacheMissReason: run.cacheMissReason} : {}),
947
+ ...(run.snapshot ? {snapshot: run.snapshot} : {}),
948
+ queuedBehind: run.queuedBehind ?? [], worktree: run.worktree ?? null, phases: run.phases ?? [],
949
+ load: run.load ?? null, heartbeatAt: heartbeat?.at ?? null, pid: run.pid ?? heartbeat?.pid ?? null,
950
+ children: (run.children ?? []).filter(child => run.state !== 'unknown' || !child.endedAt),
951
+ ...(run.failure ? {failure: run.failure} : {}),
952
+ ignoredAfterPrepare: run.ignoredAfterPrepare ?? [],
953
+ summary: result ? {commands: result.commands.map(({id, expandedFiles, summary}) => ({
954
+ id, expandedFiles, exitCode: summary.exitCode, signal: summary.signal, timedOut: summary.timedOut,
955
+ wallMs: summary.wallMs, tests: summary.counts, incomplete: summary.incomplete
956
+ }))} : null
957
+ });
958
+ }
959
+
960
+ function readHeartbeat(dir) {
961
+ try { return readJson(path.join(dir, 'heartbeat.json')); } catch { return null; }
962
+ }
963
+
964
+ function heartbeatAlive(heartbeat, now, staleMs = HEARTBEAT_STALE_MS) {
965
+ const at = Date.parse(heartbeat?.at);
966
+ return Number.isFinite(at) && now - at <= staleMs;
967
+ }
968
+
969
+ function readRunStatus(dir, runId, now, staleMs) {
970
+ if (!pathStat(dir)) throw new VerifyError('unknown_run');
971
+ const heartbeat = readHeartbeat(dir);
972
+ const run = readStoredRun(dir, runId);
973
+ let result = null;
974
+ if (!['queued', 'preparing', 'running', 'succeeded', 'failed'].includes(run?.state)) {
975
+ return statusPayload({runId, state: 'unknown'}, heartbeat, null);
976
+ }
977
+ if (run.state === 'succeeded') {
978
+ try {
979
+ const saved = readJson(path.join(dir, 'result.json'));
980
+ if (Array.isArray(saved.commands) && saved.commands.every(command => command?.summary)) result = saved;
981
+ } catch {}
982
+ } else if (!terminal(run.state) && !heartbeatAlive(heartbeat, now, staleMs)) {
983
+ run.state = 'unknown';
984
+ if (run.load) run.load.class = 'unknown';
985
+ }
986
+ return statusPayload(run, heartbeat, result);
987
+ }
988
+
989
+ export async function verifyStatus({cwd, input, env = process.env, now = Date.now}, internal = {}) {
990
+ try {
991
+ const {runId, waitMs} = validateVerifyInput('verify-status', input);
992
+ const {store} = await getStorage(cwd, gitRunner(env));
993
+ const dir = path.join(store, 'runs', runId);
994
+ if (!pathStat(dir)) throw new VerifyError('unknown_run');
995
+ await validateStorePath(dir);
996
+ const expires = performance.now() + waitMs;
997
+ const clock = typeof now === 'function' ? now : () => Number(now);
998
+ for (;;) {
999
+ const status = readRunStatus(dir, runId, clock(), internal.heartbeatStaleMs);
1000
+ const remaining = expires - performance.now();
1001
+ if (terminal(status.state) || status.state === 'unknown' || remaining <= 0) return status;
1002
+ await delay(Math.min(remaining, 200));
1003
+ }
1004
+ } catch (error) {
1005
+ return verifyErrorResult(error);
1006
+ }
1007
+ }
1008
+
1009
+ class RunFailure extends Error {
1010
+ constructor(code, details) {
1011
+ super(code + (details ? ': ' + details : ''));
1012
+ this.code = code;
1013
+ }
1014
+ }
1015
+
1016
+ async function createWorktree({git, cwd, commonDir, run, persist, internal}) {
1017
+ const {runId} = run;
1018
+ const paths = ownedWorktreePaths(commonDir, runId);
1019
+ const {root, parent, directory, repoHash, worktree, worktreeAlias, noHooks, owner} = paths;
1020
+ const safety = {runId, code: 'unsafe_temp_path', lstat: internal.lstat ?? fs.lstatSync};
1021
+ try {
1022
+ verifyWorktreeAncestors(root, safety);
1023
+ createWorktreeDirectory(root, safety, true);
1024
+ createWorktreeDirectory(parent, safety, true);
1025
+ createWorktreeDirectory(directory, safety);
1026
+ makeDirectory(noHooks);
1027
+ writeJson(owner, {tool: 'arc-verify', runId, repoHash, commonDir, createdAt: nowIso()});
1028
+ } catch (error) {
1029
+ if (error instanceof VerifyError) throw error;
1030
+ throw storageError(error, {runId});
1031
+ }
1032
+ run.worktree = {path: worktree, state: 'creating'};
1033
+ persist();
1034
+ try {
1035
+ await gitOutput(git, cwd, ['-c', 'core.hooksPath=' + noHooks, 'worktree', 'add', '--detach', '--lock', '--reason',
1036
+ 'arc-verify:' + run.runId, worktree, run.commit]);
1037
+ } catch (error) {
1038
+ if (isSandboxError(error)) {
1039
+ throw new VerifyError('host_sandbox_blocked', 'hold', {runId: run.runId, message: error.message});
1040
+ }
1041
+ throw new RunFailure('worktree_create_failed', error.message);
1042
+ }
1043
+ run.worktree.state = 'retained';
1044
+ verifyWorktreeDirectory(worktree, safety, {checkMode: false});
1045
+ try {
1046
+ fs.chmodSync(worktree, 0o700);
1047
+ } catch (error) {
1048
+ throw unsafeWorktreePath(worktree, safety, error);
1049
+ }
1050
+ verifyWorktreeDirectory(worktree, safety);
1051
+ await internal.afterCreate?.(run.worktree.path);
1052
+ try {
1053
+ if ((await gitOutput(git, worktree, ['rev-parse', 'HEAD'])).trim() !== run.commit) throw new RunFailure('worktree_oid_mismatch');
1054
+ if ((await statusEntries(git, worktree, true)).length) throw new RunFailure('worktree_unclean');
1055
+ } catch (error) {
1056
+ if (error instanceof RunFailure) throw error;
1057
+ throw new RunFailure('worktree_unclean', error.message);
1058
+ }
1059
+ return {worktree, worktreeAlias};
1060
+ }
1061
+
1062
+ async function seedWorktree(seeds, worktree, git) {
1063
+ if (!seeds.length) return;
1064
+ try {
1065
+ for (const {dest, data} of seeds) {
1066
+ const filename = path.join(worktree, dest);
1067
+ if (pathStat(filename)) throw Error('Seed destination exists');
1068
+ makeDirectory(path.dirname(filename), true);
1069
+ atomicWrite(filename, data);
1070
+ }
1071
+ const expected = seeds.map(seed => seed.dest).sort();
1072
+ const entries = await statusEntries(git, worktree, true);
1073
+ if (entries.some(({status}) => status !== '??') || canonicalJson(entries.map(({path}) => path)) !== canonicalJson(expected)) {
1074
+ throw Error('Worktree does not contain only the requested untracked seeds');
1075
+ }
1076
+ } catch (error) {
1077
+ throw new RunFailure('worktree_unclean', error.message);
1078
+ }
1079
+ }
1080
+
1081
+ function resolveTaskCwd(cwd, worktree, runId) {
1082
+ try {
1083
+ const realCwd = fs.realpathSync(cwd);
1084
+ expect(within(worktree, realCwd) && fs.statSync(realCwd).isDirectory(), 'Command cwd must be inside the worktree');
1085
+ return realCwd;
1086
+ } catch (error) {
1087
+ throw new VerifyError('invalid_request', 'deny', {runId, message: error.message});
1088
+ }
1089
+ }
1090
+
1091
+ function bindWorktreeExecutable(task, worktree, runId) {
1092
+ if (path.isAbsolute(task.executable)) return task;
1093
+ const runnable = materializeTask(task, worktree);
1094
+ const cwd = resolveTaskCwd(runnable.cwd, worktree, runId);
1095
+ return {...task, executable: executablePath(task.executable, runnable.env, cwd)};
1096
+ }
1097
+
1098
+ async function runTask(task, {worktree, phase, id, run, raw, persist, internal}) {
1099
+ const runnable = materializeTask(task, worktree);
1100
+ runnable.cwd = resolveTaskCwd(runnable.cwd, worktree, run.runId);
1101
+ let result;
1102
+ let activeChild;
1103
+ try {
1104
+ result = await runChild(runnable, {
1105
+ ...internal, onSpawn: child => {
1106
+ activeChild = {...child, phase, id};
1107
+ run.children.push(activeChild);
1108
+ persist();
1109
+ }
1110
+ });
1111
+ } catch (error) {
1112
+ if (error instanceof VerifyError) throw error;
1113
+ throw new RunFailure(phase === 'prepare' ? 'prepare_failed' : 'command_spawn_failed', error.message);
1114
+ } finally {
1115
+ if (activeChild) activeChild.endedAt = nowIso();
1116
+ }
1117
+ try {
1118
+ for (const [stream, bytes] of Object.entries(result.buffers)) atomicWrite(path.join(raw, id + '.' + stream), bytes);
1119
+ } catch (error) {
1120
+ throw storageError(error, {runId: run.runId});
1121
+ }
1122
+ return result;
1123
+ }
1124
+
1125
+ function makeLoad(input, loadavg) {
1126
+ const load = {cpus: os.cpus().length, start: {loadavg: loadavg()}, samples: [], overlaps: [],
1127
+ declaredConcurrent: input.declaredConcurrent};
1128
+ refreshLoadClass(load);
1129
+ return load;
1130
+ }
1131
+
1132
+ function refreshLoadClass(load) {
1133
+ load.class = classifyLoad({...load, platform: os.platform(), startLoadavg: load.start.loadavg});
1134
+ }
1135
+
1136
+ function queueLockState(filename, hostname) {
1137
+ let stat;
1138
+ let owner;
1139
+ try {
1140
+ stat = fs.lstatSync(filename, {bigint: true});
1141
+ owner = readJson(filename);
1142
+ } catch (error) {
1143
+ return error.code === 'ENOENT' ? {} : {reason: 'Queue lock is unreadable: ' + error.message};
1144
+ }
1145
+ if (!owner || !Number.isSafeInteger(owner.pid) || owner.pid <= 0 || typeof owner.hostname !== 'string' ||
1146
+ !owner.hostname || typeof owner.createdAt !== 'string' || !Number.isFinite(Date.parse(owner.createdAt))) {
1147
+ return {reason: 'Queue lock owner metadata is unreadable'};
1148
+ }
1149
+ if (owner.hostname !== hostname) return {reason: 'Queue lock owner is on another host: ' + owner.hostname};
1150
+ try {
1151
+ process.kill(owner.pid, 0);
1152
+ return {reason: 'Queue lock owner is still running: ' + owner.pid};
1153
+ } catch (error) {
1154
+ if (error.code !== 'ESRCH') return {reason: 'Queue lock owner could not be verified: ' + error.message};
1155
+ const identity = hashJson([String(stat.dev), String(stat.ino), String(stat.ctimeNs), owner]).slice(0, 24);
1156
+ return {identity};
1157
+ }
1158
+ }
1159
+
1160
+ function publishQueueOwner(filename, hostname) {
1161
+ const temporary = filename + '.' + randomBytes(8).toString('hex') + '.tmp';
1162
+ writeJson(temporary, {pid: process.pid, hostname, createdAt: nowIso()});
1163
+ try {
1164
+ // Publish only after the complete owner JSON has been flushed.
1165
+ fs.linkSync(temporary, filename);
1166
+ return true;
1167
+ } catch (error) {
1168
+ if (error.code !== 'EEXIST') throw error;
1169
+ return false;
1170
+ } finally {
1171
+ try { fs.unlinkSync(temporary); } catch { /* Leftover staging files do not participate in locking. */ }
1172
+ }
1173
+ }
1174
+
1175
+ function reclaimQueueLock(filename, identity, hostname) {
1176
+ const deadClaims = [];
1177
+ for (let attempt = 0; ; attempt++) {
1178
+ // One recoverer can inspect and unlink this generation. A dead recoverer leaves
1179
+ // its slot behind so contenders agree on the next exclusive claim.
1180
+ const claim = filename + '.recover-' + identity + '-' + attempt;
1181
+ const previous = queueLockState(claim, hostname);
1182
+ if (previous.identity) {
1183
+ deadClaims.push(claim);
1184
+ continue;
1185
+ }
1186
+ if (previous.reason) return previous.reason;
1187
+ if (!publishQueueOwner(claim, hostname)) return 'Queue lock recovery is in progress';
1188
+ try {
1189
+ if (queueLockState(filename, hostname).identity === identity) fs.unlinkSync(filename);
1190
+ return null;
1191
+ } finally {
1192
+ for (const deadClaim of deadClaims) fs.rmSync(deadClaim, {force: true});
1193
+ fs.unlinkSync(claim);
1194
+ }
1195
+ }
1196
+ }
1197
+
1198
+ async function withOperationLock(filename, action, waitMs = HEARTBEAT_STALE_MS) {
1199
+ const hostname = os.hostname();
1200
+ const deadline = performance.now() + waitMs;
1201
+ for (;;) {
1202
+ let reason;
1203
+ try {
1204
+ const owner = queueLockState(filename, hostname);
1205
+ if (owner.identity) reason = reclaimQueueLock(filename, owner.identity, hostname);
1206
+ else if (owner.reason) reason = owner.reason;
1207
+ else if (publishQueueOwner(filename, hostname)) break;
1208
+ } catch (error) {
1209
+ throw storageError(error);
1210
+ }
1211
+ const remaining = deadline - performance.now();
1212
+ if (remaining <= 0 && reason) throw storageError(Error(reason));
1213
+ if (reason) await delay(Math.min(25, remaining));
1214
+ }
1215
+ try {
1216
+ return await action();
1217
+ } finally {
1218
+ try {
1219
+ fs.unlinkSync(filename);
1220
+ } catch (error) {
1221
+ throw storageError(error);
1222
+ }
1223
+ }
1224
+ }
1225
+
1226
+ function withQueueLock(store, action, waitMs) {
1227
+ return withOperationLock(path.join(store, 'queue.lock'), action, waitMs);
1228
+ }
1229
+
1230
+ function readStoredRun(dir, id) {
1231
+ try {
1232
+ const run = readJson(path.join(dir, 'run.json'));
1233
+ if (run.runId === id) return run;
1234
+ } catch {}
1235
+ return null;
1236
+ }
1237
+
1238
+ function runIds(runsDir) {
1239
+ return fs.readdirSync(runsDir, {withFileTypes: true})
1240
+ .filter(entry => entry.isDirectory() && RUN_ID.test(entry.name)).map(entry => entry.name).sort();
1241
+ }
1242
+
1243
+ function activeRun(runsDir, id, now, staleMs) {
1244
+ const dir = path.join(runsDir, id);
1245
+ const run = readStoredRun(dir, id);
1246
+ return ['queued', 'preparing', 'running'].includes(run?.state) && heartbeatAlive(readHeartbeat(dir), now, staleMs);
1247
+ }
1248
+
1249
+ function recordOverlaps(run, runsDir, staleMs) {
1250
+ const now = Date.now();
1251
+ for (const id of runIds(runsDir)) {
1252
+ if (id === run.runId || run.load.overlaps.includes(id)) continue;
1253
+ const dir = path.join(runsDir, id);
1254
+ const other = readStoredRun(dir, id);
1255
+ if (!other?.executionStartedAt || (run.executionEndedAt && other.executionStartedAt >= run.executionEndedAt)) continue;
1256
+ const heartbeat = other.executionEndedAt ? null : readHeartbeat(dir);
1257
+ const overlaps = other.executionEndedAt
1258
+ ? other.executionEndedAt > run.executionStartedAt
1259
+ : heartbeatAlive(heartbeat, now, staleMs) || heartbeat?.at > run.executionStartedAt;
1260
+ if (overlaps) run.load.overlaps.push(id);
1261
+ }
1262
+ run.load.overlaps.sort();
1263
+ }
1264
+
1265
+ function resolveRunCommands(input, entries, {cwd, environment, reporter, globLimit, addReason}) {
1266
+ const trackedPaths = [...entries.keys()];
1267
+ return input.commands.map(task => resolveTask(task, cwd, environment, trackedPaths, reporter, addReason, globLimit));
1268
+ }
1269
+
1270
+ async function preflight({cwd, input, environment, git, store, revision, internal, addReason}) {
1271
+ const {envNames, toolVersionCommands, dependencyPaths} = input.keyInputs;
1272
+ const keyEnvironment = Object.fromEntries([...new Set([...Object.keys(environment), ...envNames])]
1273
+ .filter(key => !BLOCKED_CHILD_ENV.has(key.toUpperCase()))
1274
+ .map(key => [key, Object.hasOwn(environment, key) ? environment[key] : 'absent']));
1275
+ const absentEnvNames = Object.keys(keyEnvironment).filter(key => !Object.hasOwn(environment, key));
1276
+ const globLimit = internal.globLimit ?? GLOB_FILE_LIMIT;
1277
+ const reporter = fs.realpathSync(REPORTER);
1278
+ const prep = input.prepare.map(task => resolveTask(task, cwd, environment, [], reporter, addReason, globLimit));
1279
+ const commands = revision.entries ? resolveRunCommands(input, revision.entries, {cwd, environment, reporter, globLimit, addReason}) : null;
1280
+ const seeds = revision.entries ? readSeeds(input, cwd, revision.entries) : null;
1281
+ const versionTasks = toolVersionCommands.map(task => versionCommand(task, {
1282
+ cwd, env: environment, timeoutMs: internal.toolVersionTimeoutMs ?? TOOL_VERSION_TIMEOUT_MS
1283
+ }, reporter));
1284
+ const inWorktree = task => task.args.some(arg => arg.includes('{worktree}'));
1285
+ const deferredVersions = versionTasks.filter(inWorktree);
1286
+ await validateStorePath(store, {create: true});
1287
+ const versions = await versionDigests(versionTasks.filter(task => !inWorktree(task)), {cwd: store, addReason, internal});
1288
+ const dependencies = dependences(dependencyPaths, revision.entries ?? new Map(), cwd, addReason);
1289
+ const tempDirectories = new Set([environment.TMPDIR ?? os.tmpdir(),
1290
+ ...[...input.commands, ...input.prepare].map(task => task.env.TMPDIR).filter(value => value !== undefined && !value.includes('{worktree}'))]);
1291
+ const tmpdir = [...tempDirectories].map(directory =>
1292
+ attemptKeyInput(addReason, 'tmpdir_unavailable', () => tempIdentity(path.resolve(cwd, directory))));
1293
+ const gitMetadata = await readGitMetadata(git, cwd).catch(() => {
1294
+ addReason('git_metadata_unavailable');
1295
+ return null;
1296
+ });
1297
+ const phase1 = {
1298
+ commit: revision.commit, tree: revision.tree, seeds: seeds?.map(seed => [seed.dest, sha256Hex(seed.data)]) ?? input.seedFiles,
1299
+ os: {platform: os.platform(), arch: os.arch(), release: os.release()}, nodeVersion: process.version,
1300
+ toolVersionCommands: versions, dependencies, env: keyEnvironment, absentEnvNames, tmpdir,
1301
+ hostPlatform: input.hostPlatform, executionEnvironment: input.executionEnvironment, sandboxMode: input.sandboxMode,
1302
+ git: gitMetadata, runtime: readRuntimeIdentity()
1303
+ };
1304
+ return {prep, seeds, commands, deferredVersions, phase1, keyEnvironment, globLimit};
1305
+ }
1306
+
1307
+ function phase1Key(phase1, commands, prep, worktree) {
1308
+ return hashJson({
1309
+ ...phase1, commands: commands.map(task => phase1Task(task, worktree)),
1310
+ prepare: prep.map(task => phase1Task(task, worktree))
1311
+ });
1312
+ }
1313
+
1314
+ function seedDigest(seeds) {
1315
+ return hashJson(seeds.map(({dest, data}) => [dest, sha256Hex(data)]));
1316
+ }
1317
+
1318
+ async function getRunDirectory(store, runId) {
1319
+ const directory = path.join(store, 'runs', runId);
1320
+ if (!pathStat(directory)) throw new VerifyError('unknown_run');
1321
+ await validateStorePath(directory);
1322
+ return directory;
1323
+ }
1324
+
1325
+ function loadCommandRun(directory, runId) {
1326
+ const run = readStoredRun(directory, runId);
1327
+ const states = ['queued', 'preparing', 'running'];
1328
+ const state = terminal(run?.state) ||
1329
+ states.includes(run?.state) && heartbeatAlive(readHeartbeat(directory), Date.now()) ? run.state : 'unknown';
1330
+ return {run, state};
1331
+ }
1332
+
1333
+ function readRunResult(directory, runId, expectedHash) {
1334
+ try {
1335
+ const filename = path.join(directory, 'result.json');
1336
+ if (!fs.lstatSync(filename).isFile()) throw Error('Expected a regular result file');
1337
+ const bytes = fs.readFileSync(filename);
1338
+ if (expectedHash && sha256Hex(bytes) !== expectedHash) throw Error('Result hash mismatch');
1339
+ const result = JSON.parse(bytes);
1340
+ if (!Array.isArray(result.commands) || !result.commands.every(command =>
1341
+ Array.isArray(command?.summary?.tests) && Array.isArray(command.summary.incomplete) &&
1342
+ Array.isArray(command.expandedFiles))) throw Error('Invalid command result');
1343
+ return result;
1344
+ } catch (error) {
1345
+ throw new VerifyError('run_unknown', 'hold', {runId, message: error.message});
1346
+ }
1347
+ }
1348
+
1349
+ function readJsonLines(filename) {
1350
+ try {
1351
+ const stat = pathStat(filename);
1352
+ if (!stat) return [];
1353
+ if (!stat.isFile()) throw Error('Expected a regular JSONL file');
1354
+ return fs.readFileSync(filename, 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line));
1355
+ } catch (error) {
1356
+ throw storageError(error);
1357
+ }
1358
+ }
1359
+
1360
+ async function readComparisonHistory(store, runs) {
1361
+ const history = [];
1362
+ for (const cacheKey of new Set(runs.map(run => run.cacheKey).filter(key => CACHE_KEY.test(key)))) {
1363
+ const directory = path.join(store, 'cache', cacheKey);
1364
+ await validateStorePath(directory);
1365
+ for (const {runId, state, loadClass, resultSha256} of readJsonLines(path.join(directory, 'history.jsonl'))) {
1366
+ if (state !== 'succeeded') continue;
1367
+ if (!RUN_ID.test(runId) || !CACHE_KEY.test(resultSha256)) throw storageError(Error('Invalid history entry'));
1368
+ const runDirectory = await getRunDirectory(store, runId);
1369
+ const {commands} = readRunResult(runDirectory, runId, resultSha256);
1370
+ history.push({cacheKey, runId, loadClass, commands});
1371
+ }
1372
+ }
1373
+ return history;
1374
+ }
1375
+
1376
+ function readRunReruns(directory) {
1377
+ return readJsonLines(path.join(directory, 'reruns.jsonl'));
1378
+ }
1379
+
1380
+ function reportConditions(run) {
1381
+ const {input, machineId, recording} = run;
1382
+ const temp = recording?.tmpdir;
1383
+ return {
1384
+ machineId, os: recording?.os ?? null, node: recording?.node ?? null,
1385
+ sandboxMode: input.sandboxMode, hostPlatform: input.hostPlatform, executionEnvironment: input.executionEnvironment,
1386
+ tmpdir: {realpath: temp?.path ?? null, fsType: temp?.type ?? null},
1387
+ envNames: input.keyInputs.envNames,
1388
+ prepareDigest: recording?.prepareDigest ?? hashJson(input.prepare),
1389
+ seedDigest: recording?.seedDigest ?? (input.seedFiles.length ? null : seedDigest([]))
1390
+ };
1391
+ }
1392
+
1393
+ export async function verifyCompare({cwd, input, env = process.env}) {
1394
+ try {
1395
+ const {baseRunId, headRunId, topN} = validateVerifyInput('verify-compare', input);
1396
+ const {store, commonDir} = await getStorage(cwd, gitRunner(env));
1397
+ const ids = [baseRunId, headRunId];
1398
+ const directories = await Promise.all(ids.map(id => getRunDirectory(store, id)));
1399
+ const runs = ids.map((id, i) => {
1400
+ const {run, state} = loadCommandRun(directories[i], id);
1401
+ if (state !== 'succeeded') {
1402
+ const code = {failed: 'run_failed', unknown: 'run_unknown'}[state] ?? 'run_incomplete';
1403
+ throw new VerifyError(code, 'hold', {runId: id});
1404
+ }
1405
+ return run;
1406
+ });
1407
+ const [base, head] = runs;
1408
+ if (base.role !== 'baseline' || head.role !== 'head') throw new VerifyError('role_mismatch', 'hold');
1409
+ const repoHash = sha256Hex(commonDir).slice(0, 16);
1410
+ if (!base.machineId || base.machineId !== head.machineId ||
1411
+ runs.some(run => run.repoHash !== undefined && run.repoHash !== repoHash) ||
1412
+ ['hostPlatform', 'sandboxMode'].some(key => base.input[key] !== head.input[key])) {
1413
+ throw new VerifyError('execution_mismatch', 'hold');
1414
+ }
1415
+ const templates = run => hashJson(Object.fromEntries(run.input.commands.map(command => [command.id, command])));
1416
+ if (templates(base) !== templates(head)) throw new VerifyError('command_set_mismatch', 'hold');
1417
+ const conditions = reportConditions(head);
1418
+ const prior = reportConditions(base);
1419
+ if (prior.prepareDigest !== conditions.prepareDigest || conditions.seedDigest === null ||
1420
+ prior.seedDigest !== conditions.seedDigest) throw new VerifyError('prepare_mismatch', 'hold');
1421
+
1422
+ const [baseResult, headResult] = runs.map((run, i) => ({...run, ...readRunResult(directories[i], run.runId)}));
1423
+ const history = await readComparisonHistory(store, runs);
1424
+ const reruns = directories.flatMap((directory, i) => readRunReruns(directory).map(({commandId, testId, ...attempt}) =>
1425
+ ({runId: ids[i], commandId, testId, attempts: [{...attempt, runId: ids[i]}]})));
1426
+ const comparison = compareRuns({base: baseResult, head: headResult, history, reruns});
1427
+ const {json, md} = buildReport({
1428
+ base: baseResult, head: headResult, comparison, conditions, phases: head.phases, topN, generatedAt: nowIso()
1429
+ });
1430
+ const reports = path.join(store, 'reports');
1431
+ await validateStorePath(reports, {create: true});
1432
+ const prefix = path.join(reports, baseRunId + '..' + headRunId);
1433
+ const reportJson = prefix + '.json';
1434
+ const reportMd = prefix + '.md';
1435
+ try {
1436
+ writeJson(reportJson, json);
1437
+ atomicWrite(reportMd, md);
1438
+ } catch (error) {
1439
+ throw storageError(error);
1440
+ }
1441
+ const counts = Object.fromEntries(Object.entries(comparison).filter(([, value]) => Array.isArray(value))
1442
+ .map(([key, values]) => [key, values.length]));
1443
+ return allow({reportJson, reportMd, verdict: comparison.verdict, counts});
1444
+ } catch (error) {
1445
+ return verifyErrorResult(error);
1446
+ }
1447
+ }
1448
+
1449
+ export async function verifyRerun({cwd, input, env = process.env}) {
1450
+ try {
1451
+ const {runId, testId, attempt, sandboxMode, limit} = validateVerifyInput('verify-rerun', input);
1452
+ const {store, commonDir} = await getStorage(cwd, gitRunner(env));
1453
+ const directory = await getRunDirectory(store, runId);
1454
+ const {run, state} = loadCommandRun(directory, runId);
1455
+ const hold = code => new VerifyError(code, 'hold', {runId});
1456
+ if (state !== 'succeeded') throw hold('run_incomplete');
1457
+ let currentMachine;
1458
+ try { currentMachine = machineIdentity(store, {create: false}); } catch (error) { throw storageError(error, {runId}); }
1459
+ if (!run.machineId || run.machineId !== currentMachine || run.input.sandboxMode !== sandboxMode) {
1460
+ throw hold('execution_mismatch');
1461
+ }
1462
+ const {commands} = readRunResult(directory, runId);
1463
+ const matches = commands.flatMap(({id, summary}) => summary.tests.filter(test => test.testId === testId)
1464
+ .map(test => ({id, test})));
1465
+ expect(matches.length === 1, 'testId must identify exactly one test in the run');
1466
+ const [{id, test}] = matches;
1467
+ const command = run.input.commands.find(command => command.id === id);
1468
+ expect(command, 'Missing command template');
1469
+ const request = {runId, testId, attempt, limit};
1470
+ if (!command.isolate) return allow({...request, runStatus: 'not-run', reason: 'no_isolation_template',
1471
+ attempts: [], passesInIsolation: null});
1472
+
1473
+ return await withOperationLock(path.join(directory, 'worktree-operation.lock'), async () => {
1474
+ const current = readStoredRun(directory, runId);
1475
+ const {worktree, worktreeAlias} = ownedWorktreePaths(commonDir, runId);
1476
+ if (current?.state !== 'succeeded' || current.worktree?.path !== worktree || !pathStat(worktree)) {
1477
+ throw hold('run_incomplete');
1478
+ }
1479
+ await verifyOwnedPath(current, worktree, false);
1480
+ const attempts = readRunReruns(directory).filter(entry => entry.commandId === id && entry.testId === testId)
1481
+ .map(({attempt, status, ms}) => ({attempt, status, ms}));
1482
+ if (attempt !== attempts.length + 1) throw new VerifyError('attempt_out_of_order');
1483
+ if (attempt > limit) throw new VerifyError('rerun_limit');
1484
+
1485
+ const originalEnv = run.recording
1486
+ ? Object.fromEntries(Object.entries(run.keyEnvironment).filter(([key]) => !run.recording.absentEnvNames.includes(key)))
1487
+ : buildChildEnv({parentEnv: env, envNames: run.input.keyInputs.envNames});
1488
+ const reporter = fs.realpathSync(REPORTER);
1489
+ const task = resolveTask({...command, args: []}, cwd, originalEnv, [], reporter, () => {}, GLOB_FILE_LIMIT);
1490
+ const runnable = materializeTask(task, worktree);
1491
+ const worktreePaths = [worktree, worktreeAlias];
1492
+ const isolateName = test.isolationNameParts?.map(part =>
1493
+ typeof part === 'number' ? worktreePaths[part] : part).join('') ?? test.name;
1494
+ const values = {
1495
+ file: test.file, name: isolateName, namePattern: '^' + isolateName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '$',
1496
+ testId, worktree, arcNodeReporter: reporter
1497
+ };
1498
+ runnable.args = command.isolate.args.map(arg =>
1499
+ arg.replace(/\{(file|name|namePattern|testId|worktree|arcNodeReporter)\}/g, (_, name) => values[name]));
1500
+ runnable.cwd = resolveTaskCwd(runnable.cwd, worktree, runId);
1501
+ if (!path.isAbsolute(runnable.executable)) runnable.executable = executablePath(runnable.executable, runnable.env, runnable.cwd);
1502
+ const {results} = command;
1503
+ let resultsOverLimit = false;
1504
+ const findFiles = () => results.path ? findResultFiles(results.path, worktree, GLOB_FILE_LIMIT,
1505
+ () => { resultsOverLimit = true; }) : [];
1506
+ // The original command or an earlier attempt may have left reports in this worktree.
1507
+ const previous = new Map(findFiles().map(file => [file.relative, resultFileVersion(file)]));
1508
+ let output;
1509
+ try {
1510
+ output = await runChild(runnable);
1511
+ } catch (error) {
1512
+ if (isSandboxError(error)) throw new VerifyError('host_sandbox_blocked', 'hold', {runId, message: error.message});
1513
+ throw error;
1514
+ }
1515
+ const files = readResultFiles(findFiles().filter(file => resultFileVersion(file) !== previous.get(file.relative)));
1516
+ const summary = summarizeTaskOutput({results, output, worktree, worktreeAlias, files, allowEmpty: true});
1517
+ const spelling = originalTestSpelling(test);
1518
+ const target = summary.tests.find(candidate => candidate.file === test.file && candidate.suite === test.suite &&
1519
+ candidate.name === test.name && originalTestSpelling(candidate) === spelling);
1520
+ const status = resultsOverLimit || summary.incomplete.length ? 'incomplete' : target?.status ?? 'no_match';
1521
+ const record = {attempt, status, ms: output.wallMs};
1522
+ try {
1523
+ appendJson(path.join(directory, 'reruns.jsonl'), {commandId: id, testId, ...record});
1524
+ } catch (error) {
1525
+ throw storageError(error, {runId});
1526
+ }
1527
+ attempts.push(record);
1528
+ const runStatus = status === 'passed' || status === 'failed' ? status : 'inconclusive';
1529
+ return allow({...request, runStatus, attempts, passesInIsolation: isolationPasses(attempts)});
1530
+ });
1531
+ } catch (error) {
1532
+ return verifyErrorResult(error);
1533
+ }
1534
+ }
1535
+
1536
+ function ownedWorktreePaths(commonDir, runId) {
1537
+ let temporary;
1538
+ let temporaryAlias;
1539
+ try {
1540
+ temporaryAlias = os.tmpdir();
1541
+ temporary = fs.realpathSync(temporaryAlias);
1542
+ } catch (error) { throw storageError(error, {runId}); }
1543
+ const repoHash = sha256Hex(commonDir).slice(0, 16);
1544
+ const root = path.join(temporary, 'arc-verify');
1545
+ const parent = path.join(root, repoHash);
1546
+ const directory = path.join(parent, runId);
1547
+ return {repoHash, root, parent, directory, worktree: path.join(directory, 'wt'),
1548
+ worktreeAlias: path.resolve(temporaryAlias, 'arc-verify', repoHash, runId, 'wt'),
1549
+ owner: path.join(directory, 'owner.json'), noHooks: path.join(directory, 'no-hooks')};
1550
+ }
1551
+
1552
+ async function verifyOwnedPath(run, worktree, missing) {
1553
+ const deny = new VerifyError('not_tool_owned', 'deny', {runId: run.runId});
1554
+ if (run.worktree?.path !== worktree) throw deny;
1555
+ try {
1556
+ await inspectPath(worktree, {directory: true, missing});
1557
+ if (missing && !pathStat(worktree)) return false;
1558
+ if (fs.realpathSync(worktree) === worktree) return true;
1559
+ throw deny;
1560
+ } catch {
1561
+ throw deny;
1562
+ }
1563
+ }
1564
+
1565
+ function unsafeWorktreePath(directory, {code, runId}, error) {
1566
+ return new VerifyError(code, 'hold', {runId, path: directory, ...(error ? {message: error.message} : {})});
1567
+ }
1568
+
1569
+ function verifyWorktreeDirectory(directory, safety, {ancestor = false, missing = false, checkMode = true} = {}) {
1570
+ let stat;
1571
+ try {
1572
+ stat = safety.lstat(directory, {throwIfNoEntry: false});
1573
+ } catch (error) {
1574
+ throw unsafeWorktreePath(directory, safety, error);
1575
+ }
1576
+ if (!stat && missing) return false;
1577
+ if (!stat?.isDirectory()) throw unsafeWorktreePath(directory, safety);
1578
+ const uid = process.geteuid?.();
1579
+ const {uid: owner, mode} = stat;
1580
+ const safe = ancestor
1581
+ ? (owner === uid || owner === 0) && ((mode & 0o022) === 0 || (mode & 0o1000) !== 0)
1582
+ : owner === uid && (!checkMode || (mode & 0o7777) === 0o700);
1583
+ if (!safe) throw unsafeWorktreePath(directory, safety);
1584
+ return true;
1585
+ }
1586
+
1587
+ function verifyWorktreeAncestors(root, safety) {
1588
+ const ancestors = [];
1589
+ for (let directory = path.dirname(root); ; directory = path.dirname(directory)) {
1590
+ ancestors.push(directory);
1591
+ if (path.dirname(directory) === directory) break;
1592
+ }
1593
+ for (const directory of ancestors.reverse()) verifyWorktreeDirectory(directory, safety, {ancestor: true});
1594
+ }
1595
+
1596
+ function createWorktreeDirectory(directory, safety, allowExisting = false) {
1597
+ try {
1598
+ makeDirectory(directory);
1599
+ fs.chmodSync(directory, 0o700);
1600
+ } catch (error) {
1601
+ if (error.code !== 'EEXIST') throw error;
1602
+ if (!allowExisting) throw unsafeWorktreePath(directory, safety, error);
1603
+ }
1604
+ verifyWorktreeDirectory(directory, safety);
1605
+ }
1606
+
1607
+ function verifyCleanupPathSafety(paths, runId, lstat, {missing = false} = {}) {
1608
+ const safety = {runId, code: 'cleanup_unsafe_path', lstat};
1609
+ verifyWorktreeAncestors(paths.root, safety);
1610
+ for (const directory of [paths.root, paths.parent, paths.directory, paths.worktree]) {
1611
+ if (!verifyWorktreeDirectory(directory, safety, {missing})) return;
1612
+ }
1613
+ }
1614
+
1615
+ function verifyWorktreeOwner(paths, runId) {
1616
+ let owner;
1617
+ try { owner = readJson(paths.owner); } catch {}
1618
+ if (owner?.tool !== 'arc-verify' || owner.runId !== runId || owner.repoHash !== paths.repoHash) {
1619
+ throw new VerifyError('not_tool_owned', 'deny', {runId});
1620
+ }
1621
+ }
1622
+
1623
+ function checkCleanupState({run, state}, runId) {
1624
+ if (terminal(state)) return;
1625
+ if (state !== 'unknown') throw new VerifyError('run_active', 'hold', {runId});
1626
+ if (Number.isSafeInteger(run?.pid) && run.pid > 0) {
1627
+ try { process.kill(run.pid, 0); } catch (error) { if (error.code === 'ESRCH') return; }
1628
+ }
1629
+ throw new VerifyError('run_unknown', 'hold', {runId});
1630
+ }
1631
+
1632
+ function nestedWorktreeError(runId, nestedPaths, message) {
1633
+ return new VerifyError('nested_worktree', 'hold', {runId, nestedPaths: [...nestedPaths].sort(),
1634
+ ...(message ? {message} : {})});
1635
+ }
1636
+
1637
+ async function listCleanupWorktrees(git, cwd, worktree, runId) {
1638
+ try {
1639
+ const output = await gitOutput(git, cwd, ['worktree', 'list', '--porcelain', '-z']);
1640
+ const entries = output.trimEnd().split('\0\0').filter(Boolean).map(record =>
1641
+ Object.fromEntries(record.split('\0').map(line => {
1642
+ const separator = line.indexOf(' ');
1643
+ return separator === -1 ? [line, ''] : [line.slice(0, separator), line.slice(separator + 1)];
1644
+ })));
1645
+ if (!entries.length || !entries.every(entry => path.isAbsolute(entry.worktree ?? ''))) {
1646
+ throw Error('Invalid Git worktree list');
1647
+ }
1648
+ return entries;
1649
+ } catch (error) {
1650
+ throw nestedWorktreeError(runId, [worktree], error.message);
1651
+ }
1652
+ }
1653
+
1654
+ function verifyWorktreeRegistration(entries, worktree, run, lock) {
1655
+ const matches = entries.slice(1).filter(entry => entry.worktree === worktree);
1656
+ const [entry] = matches;
1657
+ if (matches.length !== 1 || !Object.hasOwn(entry, 'detached') || Object.hasOwn(entry, 'prunable') ||
1658
+ !REVISION.test(run.commit) || entry.HEAD !== run.commit || entry.locked !== lock) {
1659
+ throw new VerifyError('not_tool_owned', 'deny', {runId: run.runId});
1660
+ }
1661
+ }
1662
+
1663
+ function checkNestedWorktrees(entries, worktree, runId) {
1664
+ const found = new Set();
1665
+ const directories = [worktree];
1666
+ let directory = worktree;
1667
+ try {
1668
+ const physicalWorktree = fs.realpathSync.native(worktree);
1669
+ for (const {worktree: registered} of entries) {
1670
+ if (registered === worktree) continue;
1671
+ if (within(worktree, registered)) {
1672
+ found.add(registered);
1673
+ continue;
1674
+ }
1675
+ directory = registered;
1676
+ try {
1677
+ const physical = fs.realpathSync.native(registered);
1678
+ if (within(physicalWorktree, physical)) found.add(physical);
1679
+ } catch (error) {
1680
+ if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error;
1681
+ }
1682
+ }
1683
+ while ((directory = directories.pop()) !== undefined) {
1684
+ const marker = name => fs.statSync(path.join(directory, name), {throwIfNoEntry: false});
1685
+ const hasGitMarker = directory !== worktree && pathStat(path.join(directory, '.git'));
1686
+ const hasBareMarkers = marker('HEAD')?.isFile() && marker('objects')?.isDirectory() && marker('refs')?.isDirectory();
1687
+ if (hasGitMarker || hasBareMarkers) {
1688
+ found.add(directory);
1689
+ continue;
1690
+ }
1691
+ for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {
1692
+ if (entry.name !== '.git' && entry.isDirectory()) directories.push(path.join(directory, entry.name));
1693
+ }
1694
+ }
1695
+ } catch (error) {
1696
+ found.add(directory ?? worktree);
1697
+ throw nestedWorktreeError(runId, found, error.message);
1698
+ }
1699
+ if (found.size) throw nestedWorktreeError(runId, found);
1700
+ }
1701
+
1702
+ function cleanupResponse(dryRun, targets, removed, residualPaths, state) {
1703
+ return {dryRun, targets, removed: [...removed], residualPaths, cleanup: {state}};
1704
+ }
1705
+
1706
+ function checkpointCleanup(filename, run, removed, residualPaths) {
1707
+ try {
1708
+ run.cleanup = {state: residualPaths.length ? 'partial' : 'complete', removed: [...removed], residualPaths};
1709
+ writeJson(filename, run);
1710
+ } catch (error) {
1711
+ throw storageError(error, {runId: run.runId, removed: [...removed], residualPaths});
1712
+ }
1713
+ }
1714
+
1715
+ async function cleanupRunWorktree({cwd, git, commonDir, directory, run, dryRun, lstat}) {
1716
+ const {runId} = run;
1717
+ if (!run.worktree) return allow(cleanupResponse(dryRun, [], [], [], 'complete'));
1718
+ const paths = ownedWorktreePaths(commonDir, runId);
1719
+ const {worktree, owner, noHooks} = paths;
1720
+ if (run.worktree.path !== worktree) throw new VerifyError('not_tool_owned', 'deny', {runId});
1721
+ verifyCleanupPathSafety(paths, runId, lstat, {missing: true});
1722
+ const exists = await verifyOwnedPath(run, worktree, true);
1723
+ const removed = new Set((run.cleanup?.removed ?? []).filter(item => [worktree, owner, noHooks, paths.directory].includes(item)));
1724
+ const alreadyRemoved = removed.has(worktree);
1725
+ if (exists && alreadyRemoved) throw new VerifyError('not_tool_owned', 'deny', {runId});
1726
+ const targets = alreadyRemoved ? [] : [{kind: 'worktree', path: worktree}];
1727
+ const residualPaths = [];
1728
+ const runFile = path.join(directory, 'run.json');
1729
+ function partial(message) {
1730
+ if (!dryRun) checkpointCleanup(runFile, run, removed, residualPaths);
1731
+ throw new VerifyError('cleanup_partial', 'hold', {
1732
+ ...cleanupResponse(dryRun, targets, removed, residualPaths, 'partial'), runId, ...(message ? {message} : {})
1733
+ });
1734
+ }
1735
+
1736
+ if (!exists && !alreadyRemoved) {
1737
+ // A registration with a missing directory needs operator action, never a global prune.
1738
+ residualPaths.push(worktree);
1739
+ partial();
1740
+ }
1741
+ const lock = 'arc-verify:' + runId;
1742
+ if (!alreadyRemoved) {
1743
+ verifyWorktreeOwner(paths, runId);
1744
+ const entries = await listCleanupWorktrees(git, cwd, worktree, runId);
1745
+ verifyWorktreeRegistration(entries, worktree, run, lock);
1746
+ checkNestedWorktrees(entries, worktree, runId);
1747
+ }
1748
+ if (dryRun) return allow(cleanupResponse(true, targets, [], run.cleanup?.residualPaths ?? [],
1749
+ run.cleanup?.state ?? 'pending'));
1750
+
1751
+ if (!alreadyRemoved) {
1752
+ try {
1753
+ await gitOutput(git, cwd, ['worktree', 'unlock', worktree]);
1754
+ } catch (error) {
1755
+ residualPaths.push(worktree);
1756
+ partial(error.message);
1757
+ }
1758
+ try {
1759
+ const entries = await listCleanupWorktrees(git, cwd, worktree, runId);
1760
+ verifyCleanupPathSafety(paths, runId, lstat);
1761
+ await verifyOwnedPath(run, worktree, false);
1762
+ verifyWorktreeOwner(paths, runId);
1763
+ verifyWorktreeRegistration(entries, worktree, run, undefined);
1764
+ // Git has no atomic guard for a nested registration created between this scan and remove.
1765
+ checkNestedWorktrees(entries, worktree, runId);
1766
+ verifyCleanupPathSafety(paths, runId, lstat);
1767
+ await gitOutput(git, cwd, ['worktree', 'remove', '--force', worktree]);
1768
+ } catch (error) {
1769
+ let lockRestoreError;
1770
+ try {
1771
+ await verifyOwnedPath(run, worktree, false);
1772
+ verifyWorktreeOwner(paths, runId);
1773
+ const entries = await listCleanupWorktrees(git, cwd, worktree, runId);
1774
+ verifyWorktreeRegistration(entries, worktree, run, undefined);
1775
+ await gitOutput(git, cwd, ['worktree', 'lock', '--reason', lock, worktree]);
1776
+ } catch (restoreError) {
1777
+ lockRestoreError = restoreError.message;
1778
+ }
1779
+ if (error instanceof VerifyError) {
1780
+ if (lockRestoreError) error.result.lockRestoreError = lockRestoreError;
1781
+ throw error;
1782
+ }
1783
+ residualPaths.push(worktree);
1784
+ partial(lockRestoreError ? error.message + '; lock restoration: ' + lockRestoreError : error.message);
1785
+ }
1786
+ removed.add(worktree);
1787
+ checkpointCleanup(runFile, run, removed, [owner, noHooks, paths.directory]);
1788
+ }
1789
+
1790
+ verifyCleanupPathSafety(paths, runId, lstat, {missing: true});
1791
+ if (await verifyOwnedPath(run, worktree, true)) throw new VerifyError('not_tool_owned', 'deny', {runId});
1792
+ for (const [item, remove] of [[owner, fs.unlinkSync], [noHooks, fs.rmdirSync], [paths.directory, fs.rmdirSync]]) {
1793
+ if (removed.has(item)) continue;
1794
+ try {
1795
+ remove(item);
1796
+ removed.add(item);
1797
+ } catch (error) {
1798
+ if (error.code !== 'ENOENT') residualPaths.push(item);
1799
+ }
1800
+ }
1801
+ if (residualPaths.length) partial();
1802
+ for (const parent of [paths.parent, paths.root]) {
1803
+ try { fs.rmdirSync(parent); } catch (error) {
1804
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) residualPaths.push(parent);
1805
+ }
1806
+ }
1807
+ if (residualPaths.length) partial();
1808
+ checkpointCleanup(runFile, run, removed, []);
1809
+ return allow(cleanupResponse(false, targets, removed, [], 'complete'));
1810
+ }
1811
+
1812
+ async function cleanupCacheRecord(store, cacheKey, dryRun) {
1813
+ const directory = path.join(store, 'cache', cacheKey);
1814
+ await validateStorePath(directory);
1815
+ const record = path.join(directory, 'record.json');
1816
+ try {
1817
+ const stat = pathStat(record);
1818
+ if (!stat) return allow(cleanupResponse(dryRun, [], [], [], 'complete'));
1819
+ if (!stat.isFile()) throw Error('Expected a regular cache record');
1820
+ const targets = [{kind: 'cache-record', path: record}];
1821
+ if (dryRun) return allow(cleanupResponse(true, targets, [], [], 'pending'));
1822
+ fs.renameSync(record, path.join(directory, 'record.removed.json'));
1823
+ return allow(cleanupResponse(false, targets, [record], [], 'complete'));
1824
+ } catch (error) {
1825
+ throw storageError(error);
1826
+ }
1827
+ }
1828
+
1829
+ export async function verifyCleanup({cwd, input, env = process.env}, {lstat = fs.lstatSync} = {}) {
1830
+ try {
1831
+ const {dryRun, runId, cacheKey} = validateVerifyInput('verify-cleanup', input);
1832
+ const git = gitRunner(env);
1833
+ const {store, commonDir} = await getStorage(cwd, git);
1834
+ if (cacheKey) return await cleanupCacheRecord(store, cacheKey, dryRun);
1835
+ const directory = await getRunDirectory(store, runId);
1836
+ const current = loadCommandRun(directory, runId);
1837
+ checkCleanupState(current, runId);
1838
+ if (dryRun) return await cleanupRunWorktree({cwd, git, commonDir, directory, run: current.run, dryRun, lstat});
1839
+ return await withOperationLock(path.join(directory, 'worktree-operation.lock'), async () => {
1840
+ const current = loadCommandRun(directory, runId);
1841
+ checkCleanupState(current, runId);
1842
+ return cleanupRunWorktree({cwd, git, commonDir, directory, run: current.run, dryRun, lstat});
1843
+ });
1844
+ } catch (error) {
1845
+ return verifyErrorResult(error);
1846
+ }
1847
+ }
1848
+
1849
+ export async function verifyStart({cwd, input, env = process.env}, internal = {}) {
1850
+ try {
1851
+ input = validateVerifyInput('verify-start', input);
1852
+ return await startRun({cwd: path.resolve(cwd), input, env, internal});
1853
+ } catch (error) {
1854
+ return verifyErrorResult(error);
1855
+ }
1856
+ }
1857
+
1858
+ async function startRun({cwd, input, env, internal}) {
1859
+ const reasons = new Set();
1860
+ const addReason = reason => reasons.add(reason);
1861
+ if (input.sandboxMode === 'unknown') addReason('sandbox_mode_unknown');
1862
+ const {envNames} = input.keyInputs;
1863
+ const git = gitRunner(env, envNames);
1864
+ const environment = buildChildEnv({parentEnv: env, envNames});
1865
+ const {store, commonDir} = await getStorage(cwd, git);
1866
+ let revision = await readRevision(git, cwd, input.revision, addReason);
1867
+ const runId = makeRunId();
1868
+ const runsDir = path.join(store, 'runs');
1869
+ const runDir = path.join(runsDir, runId);
1870
+ async function createRunDir() {
1871
+ await validateStorePath(runsDir, {create: true});
1872
+ try {
1873
+ makeDirectory(runDir);
1874
+ makeDirectory(path.join(runDir, 'raw'));
1875
+ } catch (error) {
1876
+ throw storageError(error, {runId});
1877
+ }
1878
+ }
1879
+ let snapshot;
1880
+ if (input.snapshotWorkingTree) {
1881
+ if ((await gitOutput(git, cwd, ['rev-parse', '--verify', '-q', 'HEAD'], [0, 1])).trim() !== input.revision) {
1882
+ throw new VerifyError('revision_mismatch');
1883
+ }
1884
+ await createRunDir();
1885
+ snapshot = await createSnapshot({cwd, head: revision.commit, runDir}, {env, envNames,
1886
+ beforeSnapshotWriteTree: internal.beforeSnapshotWriteTree});
1887
+ revision = await readRevision(git, cwd, snapshot.commit, addReason);
1888
+ }
1889
+ const context = await preflight({cwd, input, environment, git, store, revision, internal, addReason});
1890
+ if (!snapshot) await createRunDir();
1891
+ const {prep, seeds, commands, deferredVersions, phase1, keyEnvironment, globLimit} = context;
1892
+ const needsWorktreeKey = !commands || [...prep, ...commands].some(task => !path.isAbsolute(task.executable));
1893
+ const hasPhase2 = prep.length > 0 || deferredVersions.length > 0 || input.keyInputs.artifactPaths.length > 0;
1894
+ const execution = {cwd, prep, seeds, commands, deferredVersions, phase1, globLimit, needsWorktreeKey, hasPhase2};
1895
+ const {run, heartbeat} = await withQueueLock(store, async () => {
1896
+ const machineId = attemptKeyInput(addReason, 'machine_identity_unavailable', () => machineIdentity(store));
1897
+ phase1.machineId = machineId;
1898
+ const cacheKeyPhase1 = needsWorktreeKey ? null : phase1Key(phase1, commands, prep);
1899
+ const now = Date.now();
1900
+ const queuedBehind = runIds(runsDir).filter(id => activeRun(runsDir, id, now, internal.heartbeatStaleMs));
1901
+ const run = {
1902
+ schemaVersion: 1, runId, role: input.role, state: queuedBehind.length ? 'queued' : 'preparing',
1903
+ revision: input.revision, commit: revision.commit, tree: revision.tree, ...(snapshot ? {snapshot} : {}),
1904
+ input, cacheKeyPhase1, cacheKey: hasPhase2 ? null : cacheKeyPhase1,
1905
+ cacheable: !reasons.size, uncacheableReasons: [...reasons], cacheHit: 'pending', worktree: null,
1906
+ phases: [], load: makeLoad(input, internal.loadavg ?? os.loadavg), pid: process.pid, children: [],
1907
+ ignoredAfterPrepare: [], queuedBehind, keyEnvironment, machineId,
1908
+ repoHash: sha256Hex(commonDir).slice(0, 16),
1909
+ recording: {
1910
+ os: phase1.os, node: phase1.nodeVersion, tmpdir: phase1.tmpdir[0],
1911
+ prepareDigest: hashJson(input.prepare), seedDigest: seeds ? seedDigest(seeds) : null,
1912
+ absentEnvNames: phase1.absentEnvNames
1913
+ }
1914
+ };
1915
+ if (input.detach) {
1916
+ // Pin the preflight inputs so detach does not repeat tool probes or reread seed files.
1917
+ run.runner = {...execution, seeds: seeds?.map(({dest, data}) => ({dest, data: data.toString('base64')})) ?? null};
1918
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--run', runDir],
1919
+ {detached: true, stdio: 'ignore', shell: false, env: environment, cwd: runDir});
1920
+ try {
1921
+ await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); });
1922
+ } catch (error) {
1923
+ if (isSandboxError(error)) throw new VerifyError('host_sandbox_blocked', 'hold', {runId, message: error.message});
1924
+ throw error;
1925
+ }
1926
+ child.unref();
1927
+ run.pid = child.pid;
1928
+ }
1929
+ const heartbeat = {at: nowIso(), pid: run.pid};
1930
+ try {
1931
+ writeJson(path.join(runDir, 'heartbeat.json'), heartbeat);
1932
+ writeJson(path.join(runDir, 'run.json'), run);
1933
+ } catch (error) {
1934
+ throw storageError(error, {runId});
1935
+ }
1936
+ return {run, heartbeat};
1937
+ }, internal.queueLockWaitMs);
1938
+
1939
+ if (input.detach) return statusPayload(run, heartbeat, null);
1940
+ return executeRun({run, runDir, store, commonDir, git, environment, execution, internal});
1941
+ }
1942
+
1943
+ export async function runRunner(runDir) {
1944
+ if (!path.isAbsolute(runDir) || !RUN_ID.test(path.basename(runDir)) || path.basename(path.dirname(runDir)) !== 'runs') {
1945
+ throw Error('Invalid runner directory');
1946
+ }
1947
+ await validateStorePath(runDir);
1948
+ const store = path.dirname(path.dirname(runDir));
1949
+ // The parent registers the child PID before releasing the admission lock.
1950
+ const run = await withQueueLock(store, () => readStoredRun(runDir, path.basename(runDir)));
1951
+ if (run?.pid !== process.pid || !run.runner || !['queued', 'preparing'].includes(run.state)) throw Error('Invalid runner handoff');
1952
+ const execution = run.runner;
1953
+ delete run.runner;
1954
+ execution.seeds = execution.seeds?.map(({dest, data}) => ({dest, data: Buffer.from(data, 'base64')})) ?? null;
1955
+ const {envNames} = run.input.keyInputs;
1956
+ const git = gitRunner(process.env, envNames);
1957
+ const environment = buildChildEnv({envNames});
1958
+ const commonDir = path.dirname(path.dirname(store));
1959
+ await executeRun({run, runDir, store, commonDir, git, environment, execution, internal: {}});
1960
+ }
1961
+
1962
+ async function executeRun({run, runDir, store, commonDir, git, environment, execution, internal}) {
1963
+ const {runId, input} = run;
1964
+ const {cwd, prep, seeds, commands, deferredVersions, phase1, globLimit, needsWorktreeKey, hasPhase2} = execution;
1965
+ const reasons = new Set(run.uncacheableReasons);
1966
+ const addReason = reason => reasons.add(reason);
1967
+ const raw = path.join(runDir, 'raw');
1968
+ const runFile = path.join(runDir, 'run.json');
1969
+ const heartbeatFile = path.join(runDir, 'heartbeat.json');
1970
+ const resultFile = path.join(runDir, 'result.json');
1971
+ const runsDir = path.dirname(runDir);
1972
+ const loadavg = internal.loadavg ?? os.loadavg;
1973
+ const staleMs = internal.heartbeatStaleMs;
1974
+
1975
+ let heartbeat;
1976
+ let heartbeatError;
1977
+ function beat() {
1978
+ try {
1979
+ heartbeat = {at: nowIso(), pid: process.pid};
1980
+ writeJson(heartbeatFile, heartbeat);
1981
+ } catch (error) {
1982
+ heartbeatError ??= storageError(error, {runId});
1983
+ }
1984
+ }
1985
+
1986
+ function persist() {
1987
+ if (heartbeatError) throw heartbeatError;
1988
+ run.cacheable = reasons.size === 0;
1989
+ run.uncacheableReasons = [...reasons];
1990
+ refreshLoadClass(run.load);
1991
+ try {
1992
+ writeJson(runFile, run);
1993
+ } catch (error) {
1994
+ throw storageError(error, {runId});
1995
+ }
1996
+ }
1997
+
1998
+ let currentPhase = 'preflight';
1999
+ async function phase(name, action) {
2000
+ currentPhase = name;
2001
+ const started = performance.now();
2002
+ const step = {name, startedAt: nowIso(), endedAt: null, ms: null};
2003
+ run.phases.push(step);
2004
+ persist();
2005
+ try {
2006
+ return await action();
2007
+ } finally {
2008
+ step.endedAt = nowIso();
2009
+ step.ms = performance.now() - started;
2010
+ persist();
2011
+ }
2012
+ }
2013
+
2014
+ let result = null;
2015
+ let resultSha256 = null;
2016
+ let hit;
2017
+ let hold;
2018
+ beat();
2019
+ persist();
2020
+ const heartbeatTimer = setInterval(beat, internal.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS);
2021
+ let loadTimer;
2022
+ try {
2023
+ if (input.detach) {
2024
+ const {store: actualStore} = await getStorage(cwd, git);
2025
+ if (actualStore !== store) throw new RunFailure('worktree_create_failed', 'Runner storage does not match checkout');
2026
+ }
2027
+ if (run.state === 'queued') {
2028
+ currentPhase = 'queue';
2029
+ for (;;) {
2030
+ if (heartbeatError) throw heartbeatError;
2031
+ const now = Date.now();
2032
+ if (!run.queuedBehind.some(id => activeRun(runsDir, id, now, staleMs))) break;
2033
+ await delay(200);
2034
+ }
2035
+ run.state = 'preparing';
2036
+ run.load = makeLoad(input, loadavg);
2037
+ }
2038
+ run.executionStartedAt = nowIso();
2039
+ recordOverlaps(run, runsDir, staleMs);
2040
+ loadTimer = setInterval(() => {
2041
+ try {
2042
+ run.load.samples.push({at: nowIso(), loadavg: loadavg(), freemem: os.freemem()});
2043
+ recordOverlaps(run, runsDir, staleMs);
2044
+ persist();
2045
+ } catch (error) {
2046
+ heartbeatError ??= error instanceof VerifyError ? error : storageError(error, {runId});
2047
+ }
2048
+ }, internal.sampleMs ?? LOAD_SAMPLE_MS);
2049
+ if (!hasPhase2 && !needsWorktreeKey) hit = await phase('cache', () => cacheLookup(store, run));
2050
+ if (!hit) {
2051
+ const {worktree, worktreeAlias} = await phase('worktree', () => createWorktree({git, cwd, commonDir, run, persist, internal}));
2052
+ const entries = commands ? null : await worktreeRevisionFiles(git, worktree, input);
2053
+ let executionCommands = commands ?? resolveRunCommands(input, entries, {
2054
+ cwd, environment, reporter: fs.realpathSync(REPORTER), globLimit, addReason
2055
+ });
2056
+ await phase('prepare', async () => {
2057
+ const actualSeeds = seeds ?? readSeeds(input, cwd, entries);
2058
+ if (run.recording) run.recording.seedDigest = seedDigest(actualSeeds);
2059
+ await seedWorktree(actualSeeds, worktree, git);
2060
+ const before = topLevelIgnored(await statusEntries(git, worktree));
2061
+ for (const [index, task] of prep.entries()) {
2062
+ const resolved = bindWorktreeExecutable(task, worktree, runId);
2063
+ prep[index] = resolved;
2064
+ const output = await runTask(resolved, {worktree, phase: 'prepare', id: 'prepare.' + (index + 1), run, raw, persist, internal});
2065
+ if (output.exit.code !== 0 || output.exit.timedOut) throw new RunFailure('prepare_failed');
2066
+ }
2067
+ const after = await statusEntries(git, worktree);
2068
+ if (after.some(({status}) => status !== '??' && status !== '!!')) throw new RunFailure('prepare_dirtied_tree');
2069
+ run.ignoredAfterPrepare = topLevelIgnored(after).filter(filename => !before.includes(filename));
2070
+ if (needsWorktreeKey) {
2071
+ executionCommands = executionCommands.map(task => bindWorktreeExecutable(task, worktree, runId));
2072
+ run.cacheKeyPhase1 = phase1Key(phase1, executionCommands, prep, worktree);
2073
+ run.cacheKey = run.cacheKeyPhase1;
2074
+ }
2075
+ if (hasPhase2) {
2076
+ const versions = await versionDigests(deferredVersions, {worktree, addReason, internal});
2077
+ const artifacts = artifactDigests(input.keyInputs.artifactPaths, worktree, globLimit, addReason);
2078
+ const phase2 = hashJson({artifacts, versions, status: hashJson(after)});
2079
+ run.cacheKey = sha256Hex(run.cacheKeyPhase1 + phase2);
2080
+ }
2081
+ });
2082
+ if (hasPhase2 || needsWorktreeKey) hit = await phase('cache', () => cacheLookup(store, run));
2083
+ if (!hit) {
2084
+ run.state = 'running';
2085
+ result = await phase('commands', async () => {
2086
+ const summaries = [];
2087
+ for (const task of executionCommands) {
2088
+ const output = await runTask(task, {worktree, phase: 'commands', id: task.id, run, raw, persist, internal});
2089
+ const {id, results, expandedFiles} = task;
2090
+ const files = results.path
2091
+ ? readResultFiles(findResultFiles(results.path, worktree, globLimit, addReason), {raw, id, runId}) : [];
2092
+ const summary = summarizeTaskOutput({results, output, worktree, worktreeAlias, files});
2093
+ if (output.truncated && results.format === 'none') summary.incomplete.push({scope: 'command', reason: 'output_truncated'});
2094
+ summaries.push({id, format: results.format, expandedFiles, summary: {...summary, wallMs: output.wallMs, groupKill: output.groupKill}});
2095
+ }
2096
+ try { run.statusAfterCommands = await statusEntries(git, worktree); } catch { run.statusAfterCommands = null; }
2097
+ return {commands: summaries};
2098
+ });
2099
+ }
2100
+ }
2101
+ currentPhase = 'result';
2102
+ if (hit) {
2103
+ run.reusedFrom = hit.runId;
2104
+ result = hit.result;
2105
+ }
2106
+ run.cacheHit = Boolean(hit);
2107
+ const bytes = hit?.bytes ?? Buffer.from(JSON.stringify(result) + '\n');
2108
+ try {
2109
+ atomicWrite(resultFile, bytes);
2110
+ } catch (error) {
2111
+ throw storageError(error, {runId});
2112
+ }
2113
+ resultSha256 = hit?.resultSha256 ?? sha256Hex(bytes);
2114
+ run.state = 'succeeded';
2115
+ } catch (error) {
2116
+ const expected = error instanceof VerifyError || error instanceof RunFailure;
2117
+ if (error instanceof VerifyError) hold = error;
2118
+ run.state = 'failed';
2119
+ run.cacheHit = false;
2120
+ run.failure = expected ? {code: error.code, phase: currentPhase} :
2121
+ {code: 'runner_error', phase: currentPhase, message: error?.message ?? String(error)};
2122
+ if (run.worktree) run.worktree.state = 'retained';
2123
+ } finally {
2124
+ clearInterval(loadTimer);
2125
+ }
2126
+ try {
2127
+ if (run.executionStartedAt) {
2128
+ run.executionEndedAt = nowIso();
2129
+ recordOverlaps(run, runsDir, staleMs);
2130
+ refreshLoadClass(run.load);
2131
+ }
2132
+ beat();
2133
+ if (!heartbeatError && run.cacheKeyPhase1 && hold?.code !== 'storage_unavailable') {
2134
+ await recordHistory(store, run, resultSha256, result);
2135
+ }
2136
+ persist();
2137
+ } catch (error) {
2138
+ const failure = error instanceof VerifyError ? error : storageError(error, {runId});
2139
+ run.state = 'failed';
2140
+ run.failure = {code: failure.code, phase: 'storage'};
2141
+ if (!heartbeatError) persist();
2142
+ throw failure;
2143
+ } finally {
2144
+ clearInterval(heartbeatTimer);
2145
+ }
2146
+ if (hold) throw hold;
2147
+ return statusPayload(run, heartbeat, run.state === 'succeeded' ? result : null);
2148
+ }
2149
+
2150
+ if (process.argv[1] && fs.realpathSync(process.argv[1], {throwIfNoEntry: false}) === fileURLToPath(import.meta.url) &&
2151
+ process.argv[2] === '--run') {
2152
+ try {
2153
+ await runRunner(process.argv[3]);
2154
+ } catch (error) {
2155
+ process.stderr.write(error.message + '\n');
2156
+ process.exitCode = 1;
2157
+ }
2158
+ }