@tnunamak/dalan 0.8.1 → 0.8.3

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 (124) hide show
  1. package/CHANGELOG.md +61 -2
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +8 -12
  4. package/bin/dalan.mjs +25 -4
  5. package/bin/dot-acp-agent.mjs +572 -76
  6. package/bin/dot-alert.mjs +9 -3
  7. package/bin/dot-deadman.mjs +3 -1
  8. package/bin/dot-heartbeat.mjs +14 -7
  9. package/bin/dot-pr-reviewer.mjs +3 -31
  10. package/bin/dot-worker.mjs +121 -34
  11. package/contracts/adapter-qualification.schema.json +94 -7
  12. package/docs/chatgpt-worker-onboarding.md +1 -1
  13. package/docs/codex-to-muse.md +2 -2
  14. package/docs/connect-chatgpt.md +1 -1
  15. package/docs/connection-longevity.md +2 -2
  16. package/docs/dalan-upgrade.md +8 -5
  17. package/docs/deadman.md +4 -0
  18. package/docs/design/authority-matrix.md +18 -0
  19. package/docs/design/failure-table.md +87 -0
  20. package/docs/design/identities.md +22 -0
  21. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  22. package/docs/design/reuse-ledger.md +75 -0
  23. package/docs/design/target-architecture-v2.md +434 -0
  24. package/docs/local-agent-mcp.md +14 -0
  25. package/docs/local-agent-requester.md +2 -1
  26. package/docs/manual-setup.md +1 -1
  27. package/docs/operations.md +77 -14
  28. package/docs/pull-workers.md +11 -1
  29. package/docs/service-setup.md +10 -10
  30. package/docs/t3-integration.md +4 -2
  31. package/docs/t3-reverse-control.md +5 -5
  32. package/docs/test-suite-isolation.md +7 -6
  33. package/docs/trials/chatgpt-agent.md +47 -0
  34. package/docs/trials/claude-code-requester.md +68 -0
  35. package/docs/trials/muse.md +46 -0
  36. package/docs/usage.md +21 -7
  37. package/docs/worker-clients.md +1 -1
  38. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  39. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  40. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  41. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  42. package/package.json +4 -3
  43. package/packages/job-core/protocol/canonical.mjs +45 -7
  44. package/packages/job-core/transitions.mjs +4 -2
  45. package/scripts/upgrade-drain.mjs +96 -8
  46. package/scripts/worker-bridge-setup.mjs +215 -120
  47. package/src/ack-ledger.mjs +7 -1
  48. package/src/acp-bridge.mjs +256 -28
  49. package/src/admin-socket.mjs +32 -3
  50. package/src/alerts.mjs +17 -8
  51. package/src/answer-journal-retention.mjs +82 -0
  52. package/src/answer-journal.mjs +6 -4
  53. package/src/as-store.mjs +51 -6
  54. package/src/as.mjs +27 -5
  55. package/src/catalog-switch-inventory.mjs +70 -0
  56. package/src/check-response.mjs +4 -1
  57. package/src/cli-help.mjs +14 -3
  58. package/src/cli-name.mjs +13 -1
  59. package/src/connect-cli.mjs +159 -4
  60. package/src/deadman.mjs +8 -5
  61. package/src/delivery.mjs +2 -19
  62. package/src/destinations/index.mjs +75 -14
  63. package/src/drain-runner.mjs +5 -1
  64. package/src/follow-current.mjs +3 -1
  65. package/src/get-summary.mjs +11 -2
  66. package/src/git-env.mjs +1 -1
  67. package/src/gozar-routes.mjs +313 -94
  68. package/src/host-budget-storage.py +56 -6
  69. package/src/host-budget.mjs +98 -15
  70. package/src/host-execution-policy.mjs +17 -6
  71. package/src/legacy-names.mjs +0 -2
  72. package/src/lifecycle.mjs +44 -9
  73. package/src/loopback-probe.mjs +46 -0
  74. package/src/mcp-outcome.mjs +3 -1
  75. package/src/mcp-sse.mjs +2 -1
  76. package/src/mcp-stdio.mjs +192 -30
  77. package/src/patch-apply.mjs +212 -7
  78. package/src/phase-trace.mjs +73 -0
  79. package/src/prepared-go-modules.mjs +127 -0
  80. package/src/prepared-node-modules.mjs +225 -38
  81. package/src/prepared-pnpm.mjs +276 -0
  82. package/src/prepared-store-prune.mjs +52 -0
  83. package/src/projects.mjs +59 -7
  84. package/src/protocol-artifact-commands.mjs +28 -0
  85. package/src/protocol-finish.mjs +3 -2
  86. package/src/publication-authority.mjs +22 -0
  87. package/src/publish-plan.mjs +2 -2
  88. package/src/pull-queue.mjs +55 -20
  89. package/src/read-api.mjs +127 -0
  90. package/src/redaction.mjs +173 -0
  91. package/src/rejections.mjs +19 -3
  92. package/src/route-custody.mjs +90 -0
  93. package/src/route-publication.mjs +50 -0
  94. package/src/route-setup.mjs +184 -0
  95. package/src/schema-subset.mjs +5 -3
  96. package/src/server.mjs +503 -98
  97. package/src/service-launchd.mjs +5 -1
  98. package/src/service-update-lock.mjs +7 -4
  99. package/src/service-update-runtime.mjs +136 -21
  100. package/src/service-update.mjs +207 -51
  101. package/src/service.mjs +276 -77
  102. package/src/setup.mjs +48 -25
  103. package/src/signal.mjs +1 -1
  104. package/src/status-evidence.mjs +18 -5
  105. package/src/store.mjs +876 -120
  106. package/src/submission-policy.mjs +257 -56
  107. package/src/t3-control.mjs +1 -1
  108. package/src/t3.mjs +14 -8
  109. package/src/terminal-safe.mjs +9 -7
  110. package/src/tool-registry.mjs +134 -41
  111. package/src/try-exposure.mjs +53 -86
  112. package/src/try-hosted.mjs +257 -70
  113. package/src/try.mjs +48 -22
  114. package/src/work-order.mjs +11 -6
  115. package/src/worker-instructions.mjs +26 -4
  116. package/src/worker-runs.mjs +35 -0
  117. package/src/workers.mjs +34 -7
  118. package/src/workspace.mjs +354 -54
  119. package/systemd/dot-deadman.service +3 -1
  120. package/docs/dot-pr-reviewer.config.example.json +0 -9
  121. package/docs/pr-head-reviewer.md +0 -70
  122. package/src/pr-head-reviewer.mjs +0 -596
  123. package/systemd/dot-pr-reviewer.service +0 -11
  124. package/systemd/dot-pr-reviewer.timer +0 -10
package/src/workspace.mjs CHANGED
@@ -8,11 +8,14 @@ import { spawnSync, spawn } from 'node:child_process';
8
8
  import { createHash, randomUUID } from 'node:crypto';
9
9
  import { checkOutcome } from './lifecycle.mjs';
10
10
  import { checkResponse } from './check-response.mjs';
11
- import { secretContent, isSensitiveRepoPath, isSourceExemptionPath, sensitivePolicyPaths } from './submission-policy.mjs';
12
- import { argvTestFiles, assignmentInput, prepareGithubRepo, detectCheck, detectCheckWithOrigin, availableChecks, workspaceCheck, mirrorPath, withCheckMetadata, checkSpecsAt } from './projects.mjs';
11
+ import { secretContent, isSensitiveRepoPath, withheldRepoPath, isSourceExemptionPath, sensitivePolicyPaths } from './submission-policy.mjs';
12
+ import { argvTestFiles, assignmentInput, assignmentNamedCheck, isNamedCheck, prepareGithubRepo, detectCheck, detectCheckWithOrigin, availableChecks, workspaceCheck, mirrorPath, withCheckMetadata, checkSpecsAt, checkSummary } from './projects.mjs';
13
13
  import { hostBackend, hostReadiness, capabilityNotAvailable, TRUST, withEvidence } from './execution.mjs';
14
14
  import { redactSecrets, redactOutput, privateKeyHeader } from './redaction.mjs';
15
15
  import { hostCheckRefusal, hostCheckAuthorization } from './host-execution-policy.mjs';
16
+ import { resolvePreparedNodeModules, prepareNodeModulesInChild, unsupportedDependencies, localInputFiles } from './prepared-node-modules.mjs';
17
+ import { resolvePreparedGoModules, prepareGoModulesInChild, goModulesUnsupported } from './prepared-go-modules.mjs';
18
+ import { resolvePreparedPnpm, preparePnpmInChild, pnpmUnsupported, pnpmInputFiles } from './prepared-pnpm.mjs';
16
19
  import { ownerReportArtifactBytes } from './owner-report-artifact.mjs';
17
20
  import { withCheckCoverage } from './check-coverage.mjs';
18
21
  import { runHostBudget, parseHostBudget } from './host-budget.mjs';
@@ -28,6 +31,7 @@ const WORKSPACE_RETENTION_MS=6*3600000;
28
31
  const declaredOrNamedTestPaths=spec=>spec.test_paths??argvTestFiles(spec.argv);
29
32
  // First declared (not detected) test path absent from the checkout, or null. A path that resolves outside the checkout counts as absent.
30
33
  function missingDeclaredTestPath(dir,spec,origin) {
34
+ if(origin?.from==='requester_declared') return missingNamedTarget(dir,spec);
31
35
  if(origin?.from!=='owner_config'&&origin?.from!=='workspace_file') return null;
32
36
  let root;try{root=fs.realpathSync(dir);}catch{return null;}
33
37
  for(const p of spec.test_paths??[]) {
@@ -37,6 +41,17 @@ function missingDeclaredTestPath(dir,spec,origin) {
37
41
  }
38
42
  return null;
39
43
  }
44
+ // A named command promises a regular tracked or declared output file. Do not
45
+ // follow file or directory symlinks at execution time, even inside the tree.
46
+ function missingNamedTarget(dir,spec) {
47
+ const name=spec?.test_paths?.[0];
48
+ if (!name) return 'missing named entry';
49
+ try {
50
+ const root=fs.realpathSync(dir), target=path.join(root,name);
51
+ if (fs.lstatSync(target).isFile() && fs.realpathSync(target)===target) return null;
52
+ } catch {}
53
+ return name;
54
+ }
40
55
  const yieldLoop=()=>new Promise(resolve=>setImmediate(resolve));
41
56
  function pathExistsOrThrow(file) {
42
57
  try { fs.lstatSync(file); return true; }
@@ -80,12 +95,24 @@ const worktrees=path.join(root,'worktrees'), artifacts=path.join(root,'artifacts
80
95
  // Scoped, calm errors for a workspace that is closed to this claim. Each names the request and says only that request is affected.
81
96
  // Callers match `error`, not the prose. Same JSON-in-message shape as review_mode_read_only.
82
97
  const coded=(error,message)=>new Error(JSON.stringify({error,message}));
98
+ // A skip reason stored as evidence and shown to the caller is a stable code, never a raw error: git and fs errors carry absolute
99
+ // paths, and coded errors carry a JSON body. Short plain messages without path or JSON characters pass through.
100
+ export const checkSkipReason=error=>{
101
+ const message=String(error?.message??'');
102
+ if(!message) return 'check_before_finish_error';
103
+ try { const parsed=JSON.parse(message); if(typeof parsed?.error==='string'&&/^[a-z][a-z0-9_]*$/.test(parsed.error)) return parsed.error; } catch {}
104
+ const prefix=/^([a-z][a-z0-9_]+):/.exec(message);
105
+ if(prefix) return prefix[1];
106
+ if(message.length<=200&&!/[/{}\\]/.test(message)) return message;
107
+ return 'check_before_finish_error';
108
+ };
83
109
  function closedWorkspace(a,requestId,claimId,claimEpoch,currentEpoch) {
84
110
  if(a.status==='finished') return coded('assignment_finished',`assignment ${requestId} is finished; its workspace closed when it finished. This affects only ${requestId}; your other assignments are unchanged.`);
85
111
  if(a.cancelled_at||a.status==='cancelled') return coded('assignment_cancelled',`assignment ${requestId} was cancelled${a.cancelled_reason?` (cancelled_reason: ${a.cancelled_reason})`:''}; its workspace is closed. This affects only ${requestId}; your other assignments are unchanged.`);
86
112
  if(a.status==='claimed'&&claimEpoch!==undefined&&currentEpoch!==undefined&&claimEpoch!==currentEpoch) return coded('claim_superseded',`claim ${claimId} for ${requestId} was superseded by epoch ${currentEpoch}; stop using this claim. This affects only ${requestId}.`);
87
113
  return coded('assignment_not_claimed',`assignment ${requestId} is not claimed (status ${a.status}); its workspace is not open. This affects only ${requestId}.`);
88
114
  }
115
+ const CHECK_GUIDANCE='run_check runs a listed check in the bridge sandbox on this claim\'s workspace, with your applied patches. It does not run on your machine. Call run_check with check_id (not check or name) after apply_patch and before finish. Its receipt is bridge-verified evidence; a test you ran yourself is not. available_check_details says what each id runs. If you finish with a patch and have not run the default check on it, the bridge runs default itself before it stores your report.';
89
116
  function git(args,opts={}) { const r=spawnSync('git',args,{encoding:'utf8',timeout:10000,maxBuffer:12*1024*1024,...opts,env:gitEnv(opts.env)}); if(r.error||r.status!==0) throw new Error(`git failed: ${(r.stderr||r.error?.message||'').slice(0,300)}`); return r.stdout; }
90
117
  function relative(p,allowDot=false) { if (allowDot && (p===undefined||p==='')) return ''; if(typeof p!=='string'||!p||Buffer.byteLength(p)>1024||p.includes('\0')||path.isAbsolute(p)||p.split('/').some(x=>!x||x==='.'||x==='..'||x==='.git'||x.includes('\\'))) throw new Error('invalid project-relative path'); return p; }
91
118
  function safePath(dir,p,existing=false) { p=relative(p); let cursor=dir; for(const part of p.split('/')) { cursor=path.join(cursor,part); try { if(fs.lstatSync(cursor).isSymbolicLink()) throw new Error('symlink traversal denied'); } catch(e) { if(e.code!=='ENOENT') throw e; if(existing) throw new Error('file not found'); } } return cursor; }
@@ -102,7 +129,7 @@ function scopeOf(assignment) {
102
129
  const scope=Array.isArray(raw)&&raw.length?raw.map(p=>String(p).replace(/^\.\//,'').replace(/\/$/,'')):[];
103
130
  const paths=!scope.length||scope.includes('.')?null:scope;
104
131
  const outputs=outputsOf(assignment);
105
- const sensitive=assignment.execution_scope==='implementation'&&!paths&&excluded.size?sensitivePolicyPaths():null;
132
+ const sensitive=assignment.execution_scope==='implementation'&&excluded.size?sensitivePolicyPaths():null;
106
133
  if(sensitive?.error) throw new Error('sensitive_policy_unavailable');
107
134
  return paths||excluded.size||outputs.size?{paths,excluded,outputs,sensitive}:null;
108
135
  }
@@ -117,7 +144,7 @@ function existsAtHead(dir,file) {
117
144
  if(r.error||r.status!==0) throw new Error(`git ls-tree failed: ${(r.stderr||r.error?.message||'').slice(0,200)}`);
118
145
  return r.stdout.length>0;
119
146
  }
120
- const inScope=(p,scope)=>!scope||(!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded)&&(!scope.sensitive||!isSensitiveRepoPath(p,scope.sensitive.paths));
147
+ const inScope=(p,scope)=>!scope||(!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded)&&(!scope.sensitive||scope.paths?.includes(p)||!isSensitiveRepoPath(p,scope.sensitive.paths));
121
148
  // A directory that holds a scope entry may be listed so the walk can reach it.
122
149
  const leadsToScope=(p,scope)=>!scope||!scope.paths||inScope(p,scope)||scope.paths.some(s=>s.startsWith(`${p}/`))||[...scope.outputs].some(o=>o.startsWith(`${p}/`));
123
150
  function outputDirectoryHint(file,outputs) {
@@ -162,14 +189,44 @@ export function validateIntegrationPatch(dir,patch,assignment) {
162
189
  }
163
190
  return files;
164
191
  }
192
+ function newFilePatchHint(file,scope) {
193
+ const creatable = scope?.outputs?.has(file) === true;
194
+ return `${file}: ${creatable?'creatable (listed in output_paths)':'not creatable (not listed in output_paths)'}; for an absent file use these headers: diff --git a/${file} b/${file}, new file mode 100644, --- /dev/null, +++ b/${file}`;
195
+ }
196
+
197
+ function normalizeGrantedNewFiles(dir,patch,scope) {
198
+ return patch.split(/(?=^diff --git )/m).map(section=>{
199
+ const lines=section.split('\n');
200
+ const match=/^diff --git a\/(.+) b\/(.+)$/.exec(lines[0]);
201
+ if(!match||match[1]!==match[2]) return section; // patchPaths already rejected unsafe headers
202
+ const file=match[1],first=lines.findIndex(line=>line.startsWith('@@ '));
203
+ if(first<3) return section;
204
+ // Do not rewrite mode changes, binary data, deletion, context-bearing or mixed hunks.
205
+ const headers=lines.slice(1,first);
206
+ if(headers.at(-2)!==`--- a/${file}`||headers.at(-1)!==`+++ b/${file}`||
207
+ headers.slice(0,-2).some(line=>!/^index [0-9a-f]+\.\.[0-9a-f]+(?: 100644)?$/.test(line))) return section;
208
+ const hunks=lines.slice(first).filter(line=>line.startsWith('@@'));
209
+ if(!hunks.length||!hunks.every(line=>/^@@ -0,0 \+\d+(?:,\d+)? @@(?:.*)$/.test(line))) return section;
210
+ if(lines.slice(first).some(line=>line!==''&&!line.startsWith('@@ ')&&!line.startsWith('+')&&line!=='\')) return section;
211
+ const exists=fs.existsSync(path.join(dir,file))||existsAtHead(dir,file);
212
+ if(exists) {
213
+ if(scope?.outputs?.has(file)) throw new Error(`patch rejected: ${file} already exists; use an ordinary edit hunk for an existing file`);
214
+ return section; // an ordinary zero-context insertion into a tracked file
215
+ }
216
+ if(!scope?.outputs?.has(file)) throw new Error(`patch rejected: ${newFilePatchHint(file,scope)}`);
217
+ return [lines[0],'new file mode 100644','--- /dev/null',`+++ b/${file}`,...lines.slice(first)].join('\n');
218
+ }).join('');
219
+ }
220
+
165
221
  function applyPatchToTree(dir,patch,scope=null) {
166
222
  if(Buffer.byteLength(patch)>262144) throw new Error('patch too large');
167
223
  const files=patchPaths(patch);
168
224
  for(const p of files) requireScope(p,scope);
169
225
  for(const p of files) safePath(dir,p);
170
- const check=spawnSync('git',['-C',dir,'apply','--check','-'],{input:patch,encoding:'utf8',timeout:10000,env:gitEnv()});
171
- if(check.status!==0) throw new Error(`patch rejected: ${(check.stderr||'').slice(0,200)}`);
172
- const applied=spawnSync('git',['-C',dir,'apply','-'],{input:patch,encoding:'utf8',timeout:10000,env:gitEnv()});
226
+ const normalized=normalizeGrantedNewFiles(dir,patch,scope);
227
+ const check=spawnSync('git',['-C',dir,'apply','--check','-'],{input:normalized,encoding:'utf8',timeout:10000,env:gitEnv()});
228
+ if(check.status!==0) throw new Error(`patch rejected: ${(check.stderr||'').slice(0,200)} ${files.slice(0,3).map(file=>newFilePatchHint(file,scope)).join('; ')}`);
229
+ const applied=spawnSync('git',['-C',dir,'apply','-'],{input:normalized,encoding:'utf8',timeout:10000,env:gitEnv()});
173
230
  if(applied.status!==0) throw new Error(`patch apply failed: ${(applied.stderr||'').slice(0,200)}`);
174
231
  for(const p of files) {const f=path.join(dir,p);if(fs.existsSync(f))safePath(dir,p,true);}
175
232
  return files;
@@ -208,6 +265,9 @@ const absBytes=(dir,name)=>Buffer.concat([Buffer.from(dir+path.sep),nameBytes(na
208
265
  // An untracked file above the cap, or one that cannot be read, is left out of the diff and named in `omissions` ({path,size,reason}).
209
266
  // The diff stays bounded: the cap keeps `git diff --binary` output (base85, about 1.25x) well under its 12 MiB buffer.
210
267
  const UNTRACKED_FILE_CAP=8*2**20, UNTRACKED_FILE_COUNT=200, DIFF_TOTAL_CAP=24*2**20;
268
+ // The check the bridge runs for a patch the worker did not check, and how long finish waits for it (the host wall budget is 180 s).
269
+ class FinishCheckPending extends Error { constructor() { super('the default check is still running; call finish again when it ends'); } }
270
+ const CHECK_BEFORE_FINISH='default', CHECK_BEFORE_FINISH_WAIT_MS=Number(process.env.DALAN_FINISH_CHECK_WAIT_MS)||330000;
211
271
  const DIGEST_DEADLINE_MS=120000, CHANGED_PATHS_SHOWN=100, PREVIEW_SHOWN=25, DETAIL_ARTIFACT_CAP=2**20;
212
272
  // What every receipt says it does not identify. Fixed text: no counts and no walk, so there is no partial number to misread.
213
273
  export const NOT_IDENTIFIED='Ignored files, generated or dependency directories (node_modules, .venv, target, __pycache__, build output), unreadable or special files, content conversions (eol and ident attributes), nested repositories and submodule paths, and anything outside git\'s view of the workspace are not identified by this receipt. A check can read and execute them.';
@@ -375,7 +435,7 @@ export function sensitiveMasks(dir,repo,copyDir) {
375
435
  // Excluded implementation files never enter the runner's source tree. Skip-worktree
376
436
  // keeps these deliberate omissions out of the worker's patch without reading blobs.
377
437
  function withholdExcludedPaths(dir,assignment) {
378
- if(assignment.execution_scope!=='implementation'||!assignment.scope_paths?.includes('.')||!assignment.scope_excluded?.length) return;
438
+ if(assignment.execution_scope!=='implementation'||!assignment.scope_excluded?.length) return;
379
439
  const excluded=assignment.scope_excluded.map(entry=>relative(entry.path));
380
440
  for(const file of excluded) {
381
441
  const parent=path.posix.dirname(file);
@@ -390,32 +450,38 @@ function withholdExcludedPaths(dir,assignment) {
390
450
  }
391
451
  const tracked=new Set(git(['-C',dir,'ls-files','-z']).split('\0').filter(Boolean));
392
452
  const omitted=excluded.filter(file=>tracked.has(file));
393
- if(omitted.length) git(['-C',dir,'update-index','--skip-worktree','--',...omitted]);
453
+ if(omitted.length) git(['-C',dir,'update-index','--skip-worktree','-z','--stdin'],{input:omitted.join('\0')+'\0'});
394
454
  }
395
- function excludedPathsAbsent(dir,assignment) {
455
+ export function excludedPathsAbsent(dir,assignment) {
396
456
  if(!assignment.scope_excluded?.length) return false;
397
457
  if(!dir) return false;
398
- const policy=sensitivePolicyPaths();
399
- if(policy.error) return false;
400
- for(const entry of assignment.scope_excluded) {
401
- const file=relative(entry.path),parent=path.posix.dirname(file);
402
- if(parent!=='.') safePath(dir,parent);
403
- try { fs.lstatSync(path.join(dir,file));return false; } catch(error) { if(error.code!=='ENOENT') return false; }
458
+ try {
459
+ const policy=sensitivePolicyPaths();
460
+ if(policy.error) return false;
461
+ for(const entry of assignment.scope_excluded) {
462
+ const file=relative(entry.path),parent=path.posix.dirname(file);
463
+ if(parent!=='.') safePath(dir,parent);
464
+ try { fs.lstatSync(path.join(dir,file));return false; } catch(error) { if(error.code!=='ENOENT') return false; }
465
+ }
466
+ // Check the current policy too, including ignored and generated files. A new
467
+ // sensitive file or policy change invalidates the proof rather than unmasking it.
468
+ const walk=base=>fs.readdirSync(path.join(dir,base),{withFileTypes:true}).every(entry=>{
469
+ if(entry.name==='.git') return true;
470
+ const file=base?`${base}/${entry.name}`:entry.name;
471
+ const directory=entry.isDirectory();
472
+ if(withheldRepoPath(file,policy.paths,{directory})) return false;
473
+ return !directory||walk(file);
474
+ });
475
+ return walk('');
476
+ } catch {
477
+ // An unreadable path cannot prove that excluded sensitive data is absent.
478
+ return false;
404
479
  }
405
- // Check the current policy too, including ignored and generated files. A new
406
- // sensitive file or policy change invalidates the proof rather than unmasking it.
407
- const walk=base=>fs.readdirSync(path.join(dir,base),{withFileTypes:true}).every(entry=>{
408
- if(entry.name==='.git') return true;
409
- const file=base?`${base}/${entry.name}`:entry.name;
410
- if(isSensitiveRepoPath(file,policy.paths)) return false;
411
- return !entry.isDirectory()||walk(file);
412
- });
413
- return walk('');
414
480
  }
415
481
  // The same proof as excludedPathsAbsent, made from the pinned tree for callers with no checkout. Withholding removes exactly the paths in
416
- // scope_excluded, so the proof holds when no other path in the tree (or any directory above it) is sensitive under the current policy.
482
+ // scope_excluded, so the proof holds when no other file in the pinned tree is withheld under the current policy.
417
483
  // A sensitive file the record does not list, a malformed record, an unreadable tree or an unreadable policy all give false.
418
- function excludedPathsAccountedAtBase(mirror,assignment) {
484
+ export function excludedPathsAccountedAtBase(mirror,assignment) {
419
485
  if(!assignment.scope_excluded?.length) return false;
420
486
  const policy=sensitivePolicyPaths();
421
487
  if(policy.error) return false;
@@ -424,10 +490,7 @@ function excludedPathsAccountedAtBase(mirror,assignment) {
424
490
  let excluded;
425
491
  // A malformed persisted entry is not proof; refuse instead of throwing from claim or get.
426
492
  try { excluded=new Set(assignment.scope_excluded.map(entry=>relative(entry.path))); } catch { return false; }
427
- return listed.stdout.split('\0').filter(file=>file&&!excluded.has(file)).every(file=>{
428
- const parts=file.split('/');
429
- return parts.every((_,i)=>!isSensitiveRepoPath(parts.slice(0,i+1).join('/'),policy.paths));
430
- });
493
+ return listed.stdout.split('\0').filter(file=>file&&!excluded.has(file)).every(file=>!withheldRepoPath(file,policy.paths));
431
494
  }
432
495
  // A list shown in the receipt: the first `shown` names, the true total, and a flag when the preview is shorter than the total.
433
496
  const preview=(list,shown)=>list===null?null:({preview:list.slice(0,shown),total:list.length,truncated:list.length>shown});
@@ -453,8 +516,20 @@ function runtimeVersions() {
453
516
  return runtimeCache={node:process.version,bwrap:fs.existsSync('/usr/bin/bwrap')?first('/usr/bin/bwrap',['--version']):null,pasta:pasta?{path:pasta,version:first(pasta,['--version'])}:null};
454
517
  }
455
518
 
519
+ const UNSUPPORTED_MEMO_MAX=256;
520
+ export function summarizeCheckAvailability(ownerIds,named,noHost,namedMissing,refusalFor) {
521
+ const refusals=named.map(([id])=>noHost||refusalFor(id));
522
+ const namedDetails=Object.fromEntries(named.map(([id,spec],index)=>[
523
+ id,checkSummary(spec)+(refusals[index]?` (not runnable: ${refusals[index]})`:''),
524
+ ]));
525
+ const runnable=ownerIds.length>0||refusals.some(refusal=>!refusal);
526
+ const reason=runnable?null:noHost||namedMissing||refusals[0]||
527
+ 'host_check_not_allowlisted: no permitted owner-configured check is runnable';
528
+ return {namedDetails,runnable,reason};
529
+ }
530
+
456
531
  export class Workspace {
457
- constructor(store,recover=true,{freeBytes,checkResponseOptions,stopReverify}={}) { this.checkResponseOptions=checkResponseOptions;this.stopReverify=stopReverify; if(freeBytes) this.freeBytes=freeBytes; this.store=store;this.activeChecks=new Set();this.checkEffects=new Map();fs.mkdirSync(worktrees,{recursive:true,mode:0o700});fs.mkdirSync(artifacts,{recursive:true,mode:0o700});fs.mkdirSync(caches,{recursive:true,mode:0o700});if(recover) this.sweepDigestScratch();if(recover) store.transaction(()=>{ for(const job of store.db.prepare("SELECT id,request_id,claim_id,check_id FROM check_jobs WHERE status='running'").all()) { store.db.prepare("UPDATE check_jobs SET status='interrupted',stop_verified=NULL,finished_at=? WHERE id=?").run(new Date().toISOString(),job.id); store.lifecycle(job.request_id,'check_failed','system',checkOutcome({...job,status:'interrupted'})[1],{claim_id:job.claim_id}); } });if(recover) this.reconcileHostStops(); }
532
+ constructor(store,recover=true,{freeBytes,checkResponseOptions,stopReverify}={}) { this.checkResponseOptions=checkResponseOptions;this.stopReverify=stopReverify; if(freeBytes) this.freeBytes=freeBytes; this.store=store;this.activeChecks=new Set();this.autoChecked=new Set();this.checkEffects=new Map();this.cleanupInFlight=new Set();fs.mkdirSync(worktrees,{recursive:true,mode:0o700});fs.mkdirSync(artifacts,{recursive:true,mode:0o700});fs.mkdirSync(caches,{recursive:true,mode:0o700});if(recover) this.sweepDigestScratch();if(recover) store.transaction(()=>{ for(const job of store.db.prepare("SELECT id,request_id,claim_id,check_id FROM check_jobs WHERE status='running'").all()) { store.db.prepare("UPDATE check_jobs SET status='interrupted',stop_verified=NULL,finished_at=? WHERE id=?").run(new Date().toISOString(),job.id); store.lifecycle(job.request_id,'check_failed','system',checkOutcome({...job,status:'interrupted'})[1],{claim_id:job.claim_id}); } });if(recover) this.reconcileHostStops(); }
458
533
  // Only called after expiry/revocation: the host supervisor observes loss of
459
534
  // authority and stops the whole unit. Await its receipt and discarded output.
460
535
  async quiesce(requestId) {
@@ -535,7 +610,27 @@ export class Workspace {
535
610
  }
536
611
  return {...ctx,dir};
537
612
  }
538
- list(requestId,claimId,subject,p='',limit=200,worker='dot',cursor='') { const {dir,a}=this.ensure(requestId,claimId,subject,false,worker),scope=scopeOf(a.assignment);relative(p,true);if(p&&!leadsToScope(p,scope)) throw new Error(`path outside scope_paths: ${p}`);if(p) safePath(dir,p,true);const listed=guardedFiles(dir,p,limit,scope,cursor);return listed.truncated?{files:listed.files,truncated:true,next_cursor:listed.files.at(-1)}:{files:listed.files,truncated:false}; }
613
+ list(requestId,claimId,subject,p='',limit=200,worker='dot',cursor='') {
614
+ const {dir,a}=this.ensure(requestId,claimId,subject,false,worker),scope=scopeOf(a.assignment);
615
+ relative(p,true);
616
+ if(p&&!leadsToScope(p,scope)) throw new Error(`path outside scope_paths: ${p}`);
617
+ const missing=p&&!fs.lstatSync(safePath(dir,p),{throwIfNoEntry:false});
618
+ const outputs=outputsOf(a.assignment);
619
+ const creatable=(!cursor||missing)&&outputs.size?[...outputs].filter(output=>{
620
+ if(!inScope(output,scope)||(p&&!output.startsWith(p+'/'))) return false;
621
+ try { fs.lstatSync(safePath(dir,output)); return false; }
622
+ catch(error) { return error.code==='ENOENT'; }
623
+ }).sort():undefined;
624
+ if(missing) {
625
+ if(!creatable?.length) throw new Error('file not found');
626
+ if(cursor) throw new Error('cursor not found: list again from the start');
627
+ return {files:[],truncated:false,creatable};
628
+ }
629
+ const listed=guardedFiles(dir,p,limit,scope,cursor);
630
+ const reply=listed.truncated?{files:listed.files,truncated:true,next_cursor:listed.files.at(-1)}:{files:listed.files,truncated:false};
631
+ if(creatable) reply.creatable=creatable;
632
+ return reply;
633
+ }
539
634
  read(requestId,claimId,subject,p,start=1,max=200,worker='dot') { const {dir,a}=this.ensure(requestId,claimId,subject,false,worker);relative(p);requireScope(p,scopeOf(a.assignment));const file=safePath(dir,p,true);requireScope(realRelative(dir,file,p),scopeOf(a.assignment));const st=fs.statSync(file);if(!st.isFile()||st.size>1024*1024) throw new Error('file not readable');const whole=fs.readFileSync(file,'utf8');
540
635
  // Names no longer gate code files (submission-policy codeFile), so content does: every secret value is replaced before the line window and the 32 KiB cut, so no fragment of one reaches the worker. `redacted` tells the worker a value was masked.
541
636
  const {text:clean,redacted}=redactSecrets(whole);
@@ -707,6 +802,42 @@ export class Workspace {
707
802
  if(await this.freeBytes()>=minFreeBytes()) return;
708
803
  await this.cleanupExpired();
709
804
  }
805
+ // One terminal row's leftovers, removed the same way for the sweep and the finish path: the dependency cache,
806
+ // the checkout (`git worktree remove --force` from its mirror), the ignored-written record, and the workspaces
807
+ // row. `cacheOnly` is the sweep's rule that a cache serves nothing once its row is terminal, even while the
808
+ // checkout is still retained for its owner. Returns 'cache' or 'removed' for what this call took, or null
809
+ // when there is nothing to do (no row, no mirror, an active check, or another caller already cleaning this
810
+ // request). Idempotent: a row already gone is a no-op. A failure throws and the caller logs it and leaves the
811
+ // row to the hourly sweep; a tampered path is an integrity error (cleanup_integrity) that aborts the sweep.
812
+ async removeTerminalWorkspace(requestId,{cacheOnly=false}={}) {
813
+ if(this.activeChecks.has(requestId)) return null;
814
+ // Only a terminal assignment loses its tree. A late or audit-only finish can be recorded while a replacement grant is live.
815
+ if(!this.store.db.prepare("SELECT 1 FROM assignments WHERE request_id=? AND status IN ('finished','cancelled')").get(requestId)) return null;
816
+ if(!cacheOnly&&this.cleanupInFlight.has(requestId)) return null;
817
+ if(!cacheOnly) this.cleanupInFlight.add(requestId);
818
+ try {
819
+ const row=this.store.db.prepare('SELECT path FROM workspaces WHERE request_id=?').get(requestId);
820
+ if(!row) return null;
821
+ const expectedPath=path.join(worktrees,requestId);
822
+ let treeAbsent=false;
823
+ if(!cacheOnly&&row.path===expectedPath&&path.dirname(expectedPath)===worktrees&&path.basename(expectedPath)===requestId) {
824
+ try { fs.lstatSync(expectedPath); }
825
+ catch(error) { treeAbsent=error.code==='ENOENT'&&fs.lstatSync(worktrees,{throwIfNoEntry:false})?.isDirectory()===true; }
826
+ }
827
+ const mirror=treeAbsent?null:savedWorkspaceMirror(row.path,requestId);
828
+ if(!treeAbsent&&!mirror) return null;
829
+ const cache=path.join(caches,requestId);
830
+ if(fs.existsSync(cache)) { await removeCache(cache); if(!fs.existsSync(cache)&&cacheOnly) return 'cache'; }
831
+ if(cacheOnly) return null;
832
+ if(row.path!==expectedPath) throw Object.assign(new Error('workspace cleanup path mismatch'),{request_id:requestId,cleanup_integrity:true});
833
+ if(treeAbsent&&(pathExistsOrThrow(row.path)||fs.lstatSync(worktrees,{throwIfNoEntry:false})?.isDirectory()!==true)) return null;
834
+ if(!treeAbsent&&pathExistsOrThrow(row.path)) await gitAsync(['-C',mirror,'worktree','remove','--force',row.path]);
835
+ // Keep the row until the sidecar is gone, so the sweep can retry after the tree is removed.
836
+ fs.rmSync(this.ignoredWrittenFile(requestId),{force:true});
837
+ this.store.db.prepare('DELETE FROM workspaces WHERE request_id=?').run(requestId);
838
+ return 'removed';
839
+ } finally { if(!cacheOnly) this.cleanupInFlight.delete(requestId); }
840
+ }
710
841
  async sweepExpired(log) {
711
842
  const now=new Date().toISOString(),summary={artifacts_removed:0,workspaces_removed:0,caches_removed:0,shared_caches_removed:0,mirrors_removed:0,pressure:false,errors:0},db=this.store.db;
712
843
  const failed=(entry,error)=>{summary.errors++;log({kind:'artifact_cleanup_error',...entry,reason:error.message});};
@@ -718,6 +849,28 @@ export class Workspace {
718
849
  try{await fs.promises.unlink(row.path);}catch(e){if(e.code!=='ENOENT'){failed({artifact_id:row.id},e);continue;}}
719
850
  db.prepare('DELETE FROM artifacts WHERE id=?').run(row.id);summary.artifacts_removed++;
720
851
  }
852
+ const orphanCutoff=Date.parse(now)-24*60*60*1000;
853
+ const artifactIndexed=db.prepare('SELECT 1 FROM artifacts WHERE id=? OR path=? LIMIT 1');
854
+ let entries=[];
855
+ try { entries=await fs.promises.readdir(artifacts,{withFileTypes:true}); }
856
+ catch(error) { if(error.code!=='ENOENT') failed({scope:'orphan_artifacts'},error); }
857
+ for(let i=0;i<entries.length;i++) {
858
+ if(i%100===0) await yieldLoop();
859
+ const item=entries[i],id=item.name;
860
+ if(!item.isFile()||!/^art_[a-zA-Z0-9_-]{8,128}$/.test(id)) continue;
861
+ const file=path.join(artifacts,id);
862
+ try {
863
+ // Artifact writers hold this same database write transaction from file creation to index insertion.
864
+ const removed=this.store.transaction(()=>{
865
+ if(artifactIndexed.get(id,file)) return false;
866
+ const info=fs.lstatSync(file);
867
+ if(!info.isFile()||info.mtimeMs>orphanCutoff) return false;
868
+ fs.unlinkSync(file);
869
+ return true;
870
+ });
871
+ if(removed) summary.artifacts_removed++;
872
+ } catch(error) { if(error.code!=='ENOENT') failed({artifact_id:id},error); }
873
+ }
721
874
  const terminal=`SELECT w.request_id,w.path,a.payload,a.status,a.cancelled_at,r.created_at finished_at,
722
875
  w.fetched_at
723
876
  FROM workspaces w JOIN assignments a USING(request_id) LEFT JOIN reports r USING(request_id)
@@ -734,20 +887,18 @@ export class Workspace {
734
887
  // State can change across awaits: re-read the row and the active checks right before acting.
735
888
  const idle=()=>{const row=current.get(requestId);return row&&!this.activeChecks.has(requestId)?row:null;};
736
889
  let row=idle(); if(!row) continue;
737
- let mirror=savedWorkspaceMirror(row.path,requestId);if(!mirror) continue;
738
890
  try {
739
891
  // A finished assignment cannot be claimed again; its patch and report remain in artifacts. Retaining each checkout for
740
- // 14 days can consume disk. Keep it 6 h, or less once the owner fetched the result (any read, peek included) or disk is low.
892
+ // 14 days can consume disk. Keep it 6 h, or less once the owner fetched the result (any read, peek included) or disk is
893
+ // low. The finish path removes a tree at the moment its finish commits, so a row still here is one that call could not take.
741
894
  const terminalAt=terminalTime(row);
742
895
  const expired=terminalAt&&terminalAt+WORKSPACE_RETENTION_MS<=Date.now();
743
896
  // The dependency cache serves only a claimed assignment's checks. Remove it as soon as the assignment is terminal,
744
897
  // even when the checkout remains available for the owner to fetch its result.
745
- const cache=path.join(caches,row.request_id);if(fs.existsSync(cache)) { await removeCache(cache);if(!fs.existsSync(cache)) summary.caches_removed++; }
898
+ if((await this.removeTerminalWorkspace(requestId,{cacheOnly:true}))==='cache') summary.caches_removed++;
746
899
  if(!expired&&!row.fetched_at) { if(!pressure) continue; if(!(pressure=await this.freeBytes()<minFree)) continue; if(!(row=idle())) continue; }
747
- if(row.path!==path.join(worktrees,row.request_id)) throw Object.assign(new Error('workspace cleanup path mismatch'),{request_id:requestId,summary});
748
- if(pathExistsOrThrow(row.path)) await gitAsync(['-C',mirror,'worktree','remove','--force',row.path]);
749
- db.prepare('DELETE FROM workspaces WHERE request_id=?').run(row.request_id);fs.rmSync(this.ignoredWrittenFile(row.request_id),{force:true});summary.workspaces_removed++;
750
- } catch(error) { if(error.summary) throw error;failed({request_id:requestId},error); }
900
+ if((await this.removeTerminalWorkspace(requestId))==='removed') summary.workspaces_removed++;
901
+ } catch(error) { if(error.cleanup_integrity) throw error;failed({request_id:requestId},error); }
751
902
  }
752
903
  summary.caches_removed+=await this.sweepOrphanCaches();
753
904
  if(!pressure) summary.shared_caches_removed+=await this.sweepSharedCaches(false);
@@ -789,21 +940,77 @@ export class Workspace {
789
940
  try {
790
941
  const repo=assignment.inputs[0].github_repo;
791
942
  const declared=dir?availableChecks(repo,dir):this.availableChecksFor(assignment,worker);
792
- if(execution!=='host') return {available_checks:declared};
943
+ if(execution!=='host') return {available_checks:declared,
944
+ available_check_runnable:Object.fromEntries(declared.map(id=>[id,{runnable:false,reason:'host_execution_unavailable'}]))};
945
+ const namedRequested=assignment.execution_scope==='implementation'&&Array.isArray(assignment.checks)&&assignment.checks.length>0;
946
+ const defaultSpec=namedRequested?(dir?detectCheck(repo,dir):this.checkMetadataFor(assignment,worker)?.default):null;
947
+ const named=namedRequested&&defaultSpec?assignment.checks.flatMap((_,index)=>{
948
+ const id=`named/${index+1}`, spec=assignmentNamedCheck(assignment,id,defaultSpec);
949
+ return spec?[[id,spec]]:[];
950
+ }):[];
793
951
  // Without a checkout (claim, get) the persisted exclusion record is checked against the pinned tree. A check still
794
952
  // proves physical absence in its own checkout before it launches.
795
953
  const absent=dir?excludedPathsAbsent(dir,assignment):excludedPathsAccountedAtBase(this.mirrorFor(assignmentInput(assignment),worker),assignment);
796
954
  const baseRefusal=hostCheckRefusal(assignment,null,null,null,absent);
797
955
  const readiness=hostReadiness();
798
- const candidates=baseRefusal||!readiness.ready?[]:declared.filter(id=>!hostCheckRefusal(assignment,repo,id,null,absent));
799
- const reason=baseRefusal||(!readiness.ready?readiness.reason:null)||(!candidates.length?'host_check_not_allowlisted: no permitted owner-configured check is runnable':null);
800
- return {available_checks:candidates,host_execution_available:candidates.length>0,host_execution_unavailable_reason:reason};
956
+ // Every host check looks up prepared dependencies for the whole checkout, so a lockfile the host cannot prepare
957
+ // (workspaces, local dependencies) fails them all: say so here instead of offering checks that cannot run.
958
+ const unsupported=baseRefusal||!readiness.ready?null:this.dependenciesUnsupported(assignment,dir,worker);
959
+ const readinessRefusal=!readiness.ready?(readiness.reason||'host execution unavailable'):null;
960
+ const noHost=baseRefusal||readinessRefusal||(unsupported?`dependencies_unsupported: ${unsupported}; run_check cannot run in this repository`:null);
961
+ const refusalCode=refusal=>refusal.match(/^([a-z][a-z0-9_]*)(?::|$)/)?.[1]??'host_execution_unavailable';
962
+ const noHostCode=baseRefusal?refusalCode(baseRefusal):readinessRefusal?'host_execution_unavailable':unsupported?'dependencies_unsupported':null;
963
+ const ownerIds=namedRequested?declared.filter(id=>!isNamedCheck(id)):declared;
964
+ const ownerRefusals=new Map(ownerIds.map(id=>[id,noHost||hostCheckRefusal(assignment,repo,id,null,absent)]));
965
+ const candidates=ownerIds.filter(id=>!ownerRefusals.get(id));
966
+ const namedMissing=namedRequested&&!defaultSpec?'named_check_default_missing: configure a default check before declaring checks':null;
967
+ const available=[...candidates,...named.map(([id])=>id)];
968
+ const namedRefusals=new Map(named.map(([id])=>[id,noHost||hostCheckRefusal(assignment,repo,id,null,absent)]));
969
+ const {namedDetails,runnable,reason}=summarizeCheckAvailability(candidates,named,noHost,namedMissing,id=>namedRefusals.get(id));
970
+ const details={...(candidates.length?this.checkDetails(assignment,repo,candidates,dir,worker):{}),...namedDetails};
971
+ // Report every declared check, even when unavailable on this host; leave the runnable list unchanged.
972
+ const available_check_runnable=Object.fromEntries([...ownerRefusals,...namedRefusals].map(([id,refusal])=>[
973
+ id,{runnable:!refusal,reason:refusal?(noHostCode??refusalCode(refusal)):null},
974
+ ]));
975
+ return {available_checks:available,available_check_runnable,...(available.length?{available_check_details:details,check_guidance:CHECK_GUIDANCE}:{}),
976
+ host_execution_available:runnable,host_execution_unavailable_reason:reason};
801
977
  } catch(error) {
802
978
  if(!String(error?.message??'').includes('check metadata')) throw error;
803
979
  if(execution==='host'&&assignment.execution_scope!=='implementation') throw error;
804
- return {available_checks:[],available_checks_error:'invalid check metadata',...(execution==='host'?{host_execution_available:false,host_execution_unavailable_reason:'invalid check metadata'}:{})};
980
+ return {available_checks:[],available_check_runnable:{},available_checks_error:'invalid check metadata',...(execution==='host'?{host_execution_available:false,host_execution_unavailable_reason:'invalid check metadata'}:{})};
805
981
  }
806
982
  }
983
+ // The reason this repository's manifest and lockfile cannot be prepared on the host, or null. Best effort: unreadable input is not a reason.
984
+ // claim and get pass no checkout, so this reads the pinned base: a worker's later edit of the lockfile is not seen here, and run_check
985
+ // (which prepares only a lockfile identical to the base) still refuses it with its own error.
986
+ dependenciesUnsupported(assignment,dir,worker='dot') {
987
+ try {
988
+ if(dir) {
989
+ const read=file=>{try{return fs.readFileSync(path.join(dir,file));}catch{return null;}};
990
+ return unsupportedDependencies(read('package.json'),read('package-lock.json'))??goModulesUnsupported(read('go.mod'),read('go.work'))??pnpmUnsupported(read);
991
+ }
992
+ // The pinned base commit never changes, so its verdict is memoised (most recently used 256 kept): claim and get poll often,
993
+ // and reading and parsing a multi-megabyte lockfile each time blocks the bridge's event loop.
994
+ const input=assignmentInput(assignment),key=`${input.github_repo}@${input.base_sha}`,memo=this.unsupportedMemo??=new Map();
995
+ if(memo.has(key)) { const hit=memo.get(key);memo.delete(key);memo.set(key,hit);return hit; }
996
+ const mirror=this.mirrorFor(input,worker);
997
+ git(['-C',mirror,'cat-file','-e',`${input.base_sha}^{commit}`]); // no commit yet: throw, so a missing mirror is never memoised as "supported"
998
+ const show=file=>{try{return git(['-C',mirror,'show',`${input.base_sha}:${file}`],{encoding:'buffer'});}catch{return null;}};
999
+ const verdict=unsupportedDependencies(show('package.json'),show('package-lock.json'))??goModulesUnsupported(show('go.mod'),show('go.work'))??pnpmUnsupported(show);
1000
+ memo.set(key,verdict);
1001
+ while(memo.size>UNSUPPORTED_MEMO_MAX) memo.delete(memo.keys().next().value);
1002
+ return verdict;
1003
+ } catch { return null; }
1004
+ }
1005
+ // id -> what run_check runs. Best effort: a check whose definition cannot be read is listed without a summary, never withheld.
1006
+ checkDetails(assignment,repo,ids,dir,worker) {
1007
+ let specs=null;
1008
+ try { specs=dir?null:this.checkMetadataFor(assignment,worker); } catch {}
1009
+ return Object.fromEntries(ids.map(id=>{
1010
+ let spec=null;try { spec=dir?detectCheck(repo,dir,id):specs?.[id]; } catch {}
1011
+ return [id,spec?checkSummary(spec):'no summary available'];
1012
+ }));
1013
+ }
807
1014
  checkMetadataFor(assignment,worker='dot') {
808
1015
  const input=assignmentInput(assignment),mirror=this.mirrorFor(input,worker);
809
1016
  return checkSpecsAt(input.github_repo,mirror,input.base_sha);
@@ -815,7 +1022,7 @@ export class Workspace {
815
1022
  const inputSnap=checkInput||installInput||candidateInput,diffPaths=changed??inputDiff?.paths??[];
816
1023
  const differs=inputSnap.sha256&&baseTree?inputSnap.sha256!==baseTree:diffPaths.length>0?true:'unknown';
817
1024
  const mutated=inputSnap.sha256&&(rawPost??post).sha256?inputSnap.sha256!==(rawPost??post).sha256:null;
818
- const source=origin.from==='owner_config'?'owner_config':baseSpec&&JSON.stringify(baseSpec)===JSON.stringify(spec)?'base':'modified';
1025
+ const source=origin.from==='owner_config'?'owner_config':origin.from==='requester_declared'?'requester_declared':baseSpec&&JSON.stringify(baseSpec)===JSON.stringify(spec)?'base':'modified';
819
1026
  const omissionsIn=inputDiff?.omissions??[],omissionsPost=postDiff?.omissions??[];
820
1027
  const unverified=Object.entries(stops||{}).filter(([,x])=>!x?.verified).map(([phaseName,x])=>`${phaseName} (${x?.reason??'no stop record'})`);
821
1028
  const evidence={schema:3,output_redaction_version:1,execution:'host',trust:TRUST.bridge,repo:input.github_repo,base_sha:input.base_sha,base_tree_sha256:baseTree,
@@ -876,14 +1083,18 @@ export class Workspace {
876
1083
  if(row?.claim_id===claimId&&row.check_id===checkId&&workspace&&row.diff_sha256===this.diff(workspace.path,workspace.base_sha).sha256) return {check_run_id:row.id,status:'running'};
877
1084
  throw new Error('check already running');
878
1085
  }
879
- const {dir,input,claim,a}=this.ensure(requestId,claimId,subject,false,worker),origin=detectCheckWithOrigin(input.github_repo,dir,checkId),spec=origin?.spec;
1086
+ const {dir,input,claim,a}=this.ensure(requestId,claimId,subject,false,worker);
1087
+ const named=isNamedCheck(checkId)&&Array.isArray(a.assignment.checks)&&a.assignment.checks.length>0;
1088
+ const namedAuthorization=named?hostCheckAuthorization(input.github_repo,checkId,null,a.assignment):null;
1089
+ if(namedAuthorization?.refusal) return refuse(namedAuthorization.refusal);
1090
+ const origin=named?{spec:namedAuthorization.spec,from:'requester_declared'}:detectCheckWithOrigin(input.github_repo,dir,checkId),spec=origin?.spec;
880
1091
  if(!spec) { this.store.transaction(()=>this.store.lifecycle(requestId,'check_skipped',`worker:${subject}`,`check_id=${checkId};no_check_configured`,{claim_id:claimId})); return {check_id:checkId,skipped:true,reason:'no_check_configured',available_checks:availableChecks(input.github_repo,dir)}; }
881
1092
  let currentAvailable;
882
1093
  try { currentAvailable=availableChecks(input.github_repo,dir); }
883
1094
  catch { return refuse('host_check_metadata_unavailable: current check metadata cannot be read'); }
884
- if(!currentAvailable.includes(checkId)) return refuse('host_check_not_available: this check is not in the current metadata catalog');
885
- const ownerAuthorization=hostCheckAuthorization(input.github_repo,checkId,spec);
886
- if(origin.from!=='owner_config'||ownerAuthorization.refusal) return refuse(ownerAuthorization.refusal||'host_check_owner_definition_required: this check has no current owner-configured definition');
1095
+ if(!named&&!currentAvailable.includes(checkId)) return refuse('host_check_not_available: this check is not in the current metadata catalog');
1096
+ const ownerAuthorization=hostCheckAuthorization(input.github_repo,checkId,spec,a.assignment);
1097
+ if((!named&&origin.from!=='owner_config')||ownerAuthorization.refusal) return refuse(ownerAuthorization.refusal||'host_check_owner_definition_required: this check has no current owner-configured definition');
887
1098
  // A declared test path that is not in this checkout would make the command run a different set than the check promises: refuse before anything runs.
888
1099
  const missingTestPath=missingDeclaredTestPath(dir,spec,origin);
889
1100
  if(missingTestPath) {
@@ -893,13 +1104,13 @@ export class Workspace {
893
1104
  }
894
1105
  // The same definition resolved from the base commit alone: equal means the candidate did not change what the check is.
895
1106
  let baseSpec=null;
896
- try{baseSpec=withCheckMetadata(savedWorkspaceMirror(dir,requestId),input.base_sha,base=>detectCheck(input.github_repo,base,checkId));}catch{}
1107
+ try{baseSpec=named?ownerAuthorization.spec:withCheckMetadata(savedWorkspaceMirror(dir,requestId),input.base_sha,base=>detectCheck(input.github_repo,base,checkId));}catch{}
897
1108
  // The owner definition and budget authorize execution. A repository edit
898
1109
  // may lower that budget, but cannot replace the owner command or raise any limit.
899
1110
  let authorizedBudget,candidateBudget;
900
1111
  try {
901
1112
  authorizedBudget=parseHostBudget(ownerAuthorization.spec.host_budget);
902
- const candidateSpec=workspaceCheck(input.github_repo,dir,checkId);
1113
+ const candidateSpec=workspaceCheck(input.github_repo,dir,named?'default':checkId);
903
1114
  candidateBudget=candidateSpec?.host_budget?parseHostBudget(candidateSpec.host_budget):authorizedBudget;
904
1115
  } catch{return capabilityNotAvailable(execution,'host_budget_missing: declare a valid host_budget in owner configuration');}
905
1116
  const jobBudget=Object.fromEntries(Object.entries(authorizedBudget).map(([key,value])=>[key,Math.min(value,candidateBudget[key])]));
@@ -933,6 +1144,7 @@ export class Workspace {
933
1144
  assertCurrentAuthority();
934
1145
  const launchRefusal=hostCheckRefusal(this.store.get(requestId).assignment,input.github_repo,checkId,spec,excludedPathsAbsent(dir,this.store.get(requestId).assignment));
935
1146
  if(launchRefusal) throw new Error(launchRefusal);
1147
+ await this.prepareDependencies(dir,input.base_sha);assertCurrentAuthority();
936
1148
  const hosted=await this.runConfined(requestId,dir,spec.argv,{...spec,host_budget:jobBudget,maskPaths:masked.paths,sourceExemptions:masked.sourceExemptions},{checkRunId,repo:input.github_repo,checkId,expectedSpec:spec,cancelled:()=>{
937
1149
  try { assertCurrentAuthority(); return false; } catch { return true; }
938
1150
  }});
@@ -996,10 +1208,71 @@ export class Workspace {
996
1208
  });
997
1209
  this.reconcileHostStops(requestId);
998
1210
  return {check_run_id:checkRunId,status:'failed',error:error.message};
999
- } finally {if(scratch) fs.rmSync(scratch,{recursive:true,force:true});this.activeChecks.delete(requestId);this.checkEffects.delete(requestId);} })();
1211
+ } finally {try{if(scratch) fs.rmSync(scratch,{recursive:true,force:true});}finally{this.activeChecks.delete(requestId);this.checkEffects.delete(requestId);}} })();
1000
1212
  this.checkEffects.set(requestId,work);
1001
1213
  return checkResponse(work,{check_run_id:checkRunId,status:'running'},this.checkResponseOptions);
1002
1214
  }
1215
+ // A patch must not reach finish unchecked. When the worker finishes an implementation job on a host repository with a diff and
1216
+ // no check has run on that exact diff, the bridge runs the owner's `default` check itself and waits for it, so a check_passed or
1217
+ // check_failed event exists whether or not the worker remembered run_check. A check that cannot start or that fails leaves the
1218
+ // worker's report as it was, with a claim-bound reason when no check ran. Only a check still running after the wait stops
1219
+ // this finish, with a retryable error: the snapshot cannot be taken while a check runs, and the next finish picks the check up.
1220
+ async checkBeforeFinish(requestId,claimId,subject,worker='dot',{waitMs=CHECK_BEFORE_FINISH_WAIT_MS}={}) {
1221
+ const a=this.store.get(requestId);
1222
+ if(a.status!=='claimed'||a.assignment.execution_scope!=='implementation'||!a.assignment.inputs?.some(input=>input.github_repo)) return null;
1223
+ let diffSha=null;
1224
+ const covered=()=>this.store.db.prepare("SELECT 1 FROM check_jobs j JOIN check_runs r ON r.id=j.id WHERE j.request_id=? AND j.claim_id=? AND j.diff_sha256=? AND j.status='completed' AND r.phase='check' LIMIT 1").get(requestId,claimId,diffSha);
1225
+ const skipped=reason=>{
1226
+ this.store.transaction(()=>{
1227
+ this.store.assertClaim(requestId,claimId,subject,worker);
1228
+ const detail=redactOutput(String(reason)).slice(0,200);
1229
+ // A worker refusal already describes a skipped check unless a later check actually started.
1230
+ const recent=this.store.db.prepare("SELECT type,reason FROM lifecycle_events WHERE request_id=? AND claim_id=? AND (type='check_started' OR (type='check_skipped' AND substr(reason,1,9)='check_id=')) ORDER BY id DESC LIMIT 1").get(requestId,claimId);
1231
+ if(recent?.type==='check_skipped') return;
1232
+ // A retried finish with a different reason must still be recorded.
1233
+ const last=this.store.db.prepare("SELECT reason FROM lifecycle_events WHERE request_id=? AND claim_id=? AND type='check_skipped' AND substr(reason,1,9)<>'check_id=' ORDER BY id DESC LIMIT 1").get(requestId,claimId);
1234
+ if(last?.reason!==detail) this.store.lifecycle(requestId,'check_skipped',`worker:${subject}`,detail,{claim_id:claimId});
1235
+ });
1236
+ return null;
1237
+ };
1238
+ try {
1239
+ // waitMs bounds the whole step. A check still running when it ends would make the finish snapshot throw 'check still running'
1240
+ // with no hint what to do, so say so plainly: the check keeps going and the next finish picks it up, so nothing is lost.
1241
+ const began=Date.now();
1242
+ const settle=async()=>{
1243
+ const work=this.checkEffects.get(requestId);
1244
+ if(!work||!this.activeChecks.has(requestId)) return;
1245
+ let timer;
1246
+ try { await Promise.race([work.catch(()=>{}),new Promise(resolve=>{timer=setTimeout(resolve,Math.max(0,waitMs-(Date.now()-began)));})]); } finally { clearTimeout(timer); }
1247
+ if(this.activeChecks.has(requestId)) throw new FinishCheckPending();
1248
+ };
1249
+ // A check the worker started (any check id) must end first, whether or not the bridge would start one itself: the snapshot
1250
+ // below cannot be taken while any check runs.
1251
+ await settle();
1252
+ // Only host jobs get a bridge check; say so before materializing a worktree whose errors would hide this reason.
1253
+ if(a.execution!=='host') return skipped('execution_not_host');
1254
+ const {dir,input}=this.ensure(requestId,claimId,subject,true,worker);
1255
+ const diff=this.diff(dir,input.base_sha,this.diffFilter(a.assignment),this.diffScope(a));
1256
+ // Covered means a check ran to its check phase on this diff: a job that ended in the install phase, or never completed, shows no test result.
1257
+ diffSha=diff.sha256;
1258
+ if(covered()) return null;
1259
+ if(!diff.paths.length) return skipped('no_changes');
1260
+ if(!availableChecks(input.github_repo,dir).includes(CHECK_BEFORE_FINISH)) return skipped('no_default_check');
1261
+ // One automatic attempt per diff: when that attempt ended without a completed result, a retried finish stores the report
1262
+ // rather than start the same check again.
1263
+ const attempt=`${requestId}:${claimId}:${diff.sha256}`;
1264
+ if(this.autoChecked.has(attempt)) return skipped('auto_check_already_attempted');
1265
+ this.autoChecked.add(attempt);
1266
+ const started=await this.check(requestId,claimId,subject,CHECK_BEFORE_FINISH,worker);
1267
+ await settle();
1268
+ return {check_id:CHECK_BEFORE_FINISH,started:started?.check_run_id??null};
1269
+ } catch(error) {
1270
+ if(error instanceof FinishCheckPending) throw error;
1271
+ // Cleanup may throw after check() has already persisted a completed result.
1272
+ if(covered()) return null;
1273
+ return skipped(checkSkipReason(error));
1274
+ }
1275
+ }
1003
1276
  // Classify original output before redacting metadata and storing the row atomically;
1004
1277
  // preview truncation must not discard skipped-segment metadata.
1005
1278
  recordCheckResult(result,output,checkedDiff=result.diff_sha256) {
@@ -1015,11 +1288,37 @@ export class Workspace {
1015
1288
  });
1016
1289
  return saved;
1017
1290
  }
1291
+ // A check looks dependencies up in the owner's prepared store by lockfile hash. When this workspace still carries the
1292
+ // pinned base commit's package.json and lockfile (the owner's trust decision: the repository and check are allowlisted),
1293
+ // an absent entry is built once here instead of failing every check with an owner-only recovery command. A changed
1294
+ // manifest or lock is the worker's own input, so it is never installed here: the check fails as before.
1295
+ async prepareDependencies(dir,baseSha) {
1296
+ const unchangedFromBase=files=>files.every(file=>{
1297
+ let pinned;try{pinned=git(['-C',dir,'show',`${baseSha}:${file}`],{encoding:'buffer'});}catch{return false;}
1298
+ try{return fs.readFileSync(path.join(dir,file)).equals(pinned);}catch{return false;}
1299
+ });
1300
+ const unprepared=resolve=>{try{resolve(dir);return false;}catch(error){return error.code==='dependencies_unprepared';}};
1301
+ // Workspace manifests and local tarballs are inputs of the prepared tree too: each must equal the pinned base.
1302
+ const localFiles=()=>{try{return localInputFiles(fs.readFileSync(path.join(dir,'package-lock.json')));}catch{return [];}};
1303
+ if(unprepared(resolvePreparedNodeModules)&&unchangedFromBase(['package.json','package-lock.json'])&&unchangedFromBase(localFiles())) await prepareNodeModulesInChild(dir);
1304
+ // A pnpm repository: pnpm-lock.yaml, the root and importer manifests must equal the pinned base; pnpm-workspace.yaml may be absent from the base, and then must be absent here.
1305
+ const pnpmInputs=()=>{try{return pnpmInputFiles(fs.readFileSync(path.join(dir,'pnpm-lock.yaml')));}catch{return null;}};
1306
+ const yamlInBase=(()=>{try{git(['-C',dir,'cat-file','-e',`${baseSha}:pnpm-workspace.yaml`]);return true;}catch{return false;}})();
1307
+ const pnpmFiles=pnpmInputs();
1308
+ if(pnpmFiles&&unprepared(resolvePreparedPnpm)&&unchangedFromBase(yamlInBase?[...pnpmFiles,'pnpm-workspace.yaml']:pnpmFiles)&&(yamlInBase||!fs.existsSync(path.join(dir,'pnpm-workspace.yaml')))) await preparePnpmInChild(dir);
1309
+ // A Go repository: the module cache and toolchain come from go.mod and go.sum alone, under the same pinned-base rule. go.sum may be absent from the base, and then must be absent here.
1310
+ const sumInBase=(()=>{try{git(['-C',dir,'cat-file','-e',`${baseSha}:go.sum`]);return true;}catch{return false;}})();
1311
+ if(unprepared(resolvePreparedGoModules)&&unchangedFromBase(sumInBase?['go.mod','go.sum']:['go.mod'])&&(sumInBase||!fs.existsSync(path.join(dir,'go.sum')))) await prepareGoModulesInChild(dir);
1312
+ }
1018
1313
  async runConfined(requestId,dir,command,spec,{cancelled,checkRunId,repo=null,checkId=null,expectedSpec=null}={}) {
1019
1314
  // Policy is rechecked at the only launch boundary; repository metadata
1020
1315
  // cannot opt the operator in or bypass the whole-repository read grant.
1021
1316
  const refusal=hostCheckRefusal(this.store.get(requestId).assignment,repo,checkId,expectedSpec,excludedPathsAbsent(dir,this.store.get(requestId).assignment));
1022
1317
  if(refusal) throw new Error(refusal);
1318
+ if(isNamedCheck(checkId)&&Array.isArray(this.store.get(requestId).assignment.checks)&&this.store.get(requestId).assignment.checks.length>0) {
1319
+ const missing=missingNamedTarget(dir,expectedSpec);
1320
+ if(missing) throw new Error(`check_test_path_missing: ${missing}`);
1321
+ }
1023
1322
  const budgets=parseHostBudget(spec.host_budget);
1024
1323
  budgets.wall_ms=Math.min(budgets.wall_ms,spec.timeout_ms??budgets.wall_ms);
1025
1324
  budgets.output_bytes=Math.min(budgets.output_bytes,spec.output_bytes??budgets.output_bytes);
@@ -1042,6 +1341,7 @@ export class Workspace {
1042
1341
  // A diff git cannot produce (an unreadable path) is reported as unavailable instead of failing the whole result.
1043
1342
  let diff,diffError=null;try{diff=this.diff(dir,input.base_sha,this.diffFilter(a.assignment),this.diffScope(a));}catch(error){if(error.outputViolation||error.scopeViolation) throw error;diffError=error.message;diff={patch:'',sha256:null,bytes:0,omissions:[],paths:[]};}
1044
1343
  const checks=this.store.db.prepare('SELECT j.id check_run_id,j.status,j.check_id,CASE WHEN j.status=\'completed\' THEN COALESCE(r.diff_sha256,j.diff_sha256) ELSE j.diff_sha256 END diff_sha256,j.error,j.output_preview,r.phase,r.exit_code,r.timed_out,r.output_artifact_id,r.output_sha256,r.duration_ms,r.evidence FROM check_jobs j LEFT JOIN check_runs r ON r.id=j.id WHERE j.request_id=? ORDER BY j.started_at').all(requestId).map(withEvidence).map(check=>({...check,id:check.check_run_id,applies_to_current_diff:diff.sha256!==null&&(check.evidence?check.evidence.input_diff_sha256:check.diff_sha256)===diff.sha256,matches_current_diff:diff.sha256!==null&&(check.evidence?check.evidence.input_diff_sha256:check.diff_sha256)===diff.sha256}));
1344
+ const checks_skipped=this.store.db.prepare("SELECT reason,at FROM lifecycle_events WHERE request_id=? AND claim_id=? AND type='check_skipped' ORDER BY id").all(requestId,claimId).map(({reason,at})=>({reason:redactOutput(String(reason).replace(/^check_id=[^;]*;/,'')).slice(0,200),at}));
1045
1345
  let display=redactSecrets(diff.patch).text;
1046
1346
  if(/^GIT binary patch$/m.test(diff.patch)) display='[binary diff withheld; owner patch required]';
1047
1347
  if(diff.patch) {
@@ -1052,7 +1352,7 @@ export class Workspace {
1052
1352
  if(privateKeyHeader.test(full)) display='[redacted secret: diff contains private key material; owner patch required]';
1053
1353
  } catch { display='[diff preview unavailable: complete secret scan failed]'; }
1054
1354
  }
1055
- return redactOutput({base_sha:input.base_sha,head_sha:input.head_sha||null,execution:a.execution,...(checks.some(c=>c.evidence)?{not_identified:NOT_IDENTIFIED}:{}),output_redaction_version:1,diff_sha256:diff.sha256,...(diffError?{diff_unavailable:diffError}:{}),diff_bytes:diff.bytes,diff_omissions:diff.omissions.slice(0,CHANGED_PATHS_SHOWN),diff_omissions_total:diff.omissions.length,diff_preview:display.slice(0,32768),diff_preview_applicable:false,...this.availableChecksResponse(a.assignment,dir,a.execution),checks,artifacts});
1355
+ return redactOutput({base_sha:input.base_sha,head_sha:input.head_sha||null,execution:a.execution,...(checks.some(c=>c.evidence)?{not_identified:NOT_IDENTIFIED}:{}),output_redaction_version:1,diff_sha256:diff.sha256,...(diffError?{diff_unavailable:diffError}:{}),diff_bytes:diff.bytes,diff_omissions:diff.omissions.slice(0,CHANGED_PATHS_SHOWN),diff_omissions_total:diff.omissions.length,diff_preview:display.slice(0,32768),diff_preview_applicable:false,...this.availableChecksResponse(a.assignment,dir,a.execution),checks,checks_skipped,artifacts});
1056
1356
  }
1057
1357
  snapshot(requestId,claimId,subject,worker='dot') {
1058
1358
  const rollback=[];