@tnunamak/dalan 0.0.0-stage → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +172 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +339 -0
- package/README.md +348 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +38 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +755 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/connect-chatgpt.md +78 -0
- package/docs/connection-longevity.md +37 -0
- package/docs/dalan-upgrade.md +242 -0
- package/docs/deadman.md +59 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +39 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +98 -0
- package/docs/operations.md +751 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +109 -0
- package/docs/pr-head-reviewer.md +54 -0
- package/docs/pr-preflight.md +26 -0
- package/docs/pull-workers.md +97 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +166 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +49 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +439 -0
- package/docs/worker-clients.md +285 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +65 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +412 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +497 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +172 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-slot.mjs +53 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +70 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1340 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3057 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +451 -0
- package/src/try-command.mjs +11 -0
- package/src/try.mjs +589 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +622 -0
- package/src/workspace.mjs +1058 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
|
@@ -0,0 +1,1058 @@
|
|
|
1
|
+
import { workspaceRoot } from './paths.mjs';
|
|
2
|
+
import { readEnv } from './env.mjs';
|
|
3
|
+
import {gitEnv} from './git-env.mjs';
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import { spawnSync, spawn } from 'node:child_process';
|
|
8
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
9
|
+
import { checkOutcome } from './lifecycle.mjs';
|
|
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';
|
|
13
|
+
import { hostBackend, hostReadiness, capabilityNotAvailable, TRUST, withEvidence } from './execution.mjs';
|
|
14
|
+
import { redactSecrets, redactOutput, privateKeyHeader } from './redaction.mjs';
|
|
15
|
+
import { hostCheckRefusal, hostCheckAuthorization } from './host-execution-policy.mjs';
|
|
16
|
+
import { ownerReportArtifactBytes } from './owner-report-artifact.mjs';
|
|
17
|
+
import { withCheckCoverage } from './check-coverage.mjs';
|
|
18
|
+
import { runHostBudget, parseHostBudget } from './host-budget.mjs';
|
|
19
|
+
import { readVerifiedHostStop, sealHostNotStarted } from './host-budget-receipts.mjs';
|
|
20
|
+
import { reverifyHostStop } from './host-stop-reverify.mjs';
|
|
21
|
+
|
|
22
|
+
const sha=b=>createHash('sha256').update(b).digest('hex');
|
|
23
|
+
const root=workspaceRoot();
|
|
24
|
+
const WORKSPACE_RETENTION_MS=6*3600000;
|
|
25
|
+
// Cleanup runs inside the live server, so every step is an awaited child process or fs.promises call:
|
|
26
|
+
// Synchronous cleanup can block restarts and periodic work; use asynchronous operations.
|
|
27
|
+
// What a check ran: its declared test_paths, else the test files its argv names.
|
|
28
|
+
const declaredOrNamedTestPaths=spec=>spec.test_paths??argvTestFiles(spec.argv);
|
|
29
|
+
// First declared (not detected) test path absent from the checkout, or null. A path that resolves outside the checkout counts as absent.
|
|
30
|
+
function missingDeclaredTestPath(dir,spec,origin) {
|
|
31
|
+
if(origin?.from!=='owner_config'&&origin?.from!=='workspace_file') return null;
|
|
32
|
+
let root;try{root=fs.realpathSync(dir);}catch{return null;}
|
|
33
|
+
for(const p of spec.test_paths??[]) {
|
|
34
|
+
if(p==='./...') continue;
|
|
35
|
+
try{const real=fs.realpathSync(path.join(root,p));if(real===root||real.startsWith(root+path.sep)) continue;}catch{}
|
|
36
|
+
return p;
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
const yieldLoop=()=>new Promise(resolve=>setImmediate(resolve));
|
|
41
|
+
function spawnAsync(cmd,args,timeout=60000,env=process.env) { return new Promise(resolve=>{ let stderr='';const child=spawn(cmd,args,{stdio:['ignore','ignore','pipe'],timeout,env});child.stderr.on('data',b=>{if(stderr.length<300)stderr+=b;});child.on('error',error=>resolve({status:null,stderr:error.message}));child.on('close',status=>resolve({status,stderr})); }); }
|
|
42
|
+
async function gitAsync(args) { const r=await spawnAsync('git',args,10000,gitEnv()); if(r.status!==0) throw new Error(`git failed: ${r.stderr.slice(0,300)}`); }
|
|
43
|
+
// Go and uv write their module caches read-only, so make the tree writable before removing it.
|
|
44
|
+
// A cache left behind costs disk space only, so a failure must not stop the rest of the cleanup.
|
|
45
|
+
async function removeCache(dir) {
|
|
46
|
+
if(!fs.existsSync(dir)) return;
|
|
47
|
+
await spawnAsync('chmod',['-R','u+w',dir]);
|
|
48
|
+
try{await fs.promises.rm(dir,{recursive:true,force:true});}catch(error){console.error(`cache cleanup failed for ${dir}: ${error.message}`);}
|
|
49
|
+
}
|
|
50
|
+
const MIN_FREE_BYTES_DEFAULT=30*2**30, IDLE_CACHE_MS=7*86400000, MIRROR_IDLE_MS=7*86400000, mirrors=path.join(root,'mirrors');
|
|
51
|
+
export function savedWorkspaceMirror(workspaceDir,requestId) {
|
|
52
|
+
try {
|
|
53
|
+
const pointer=fs.readFileSync(path.join(workspaceDir,'.git'),'utf8').trim();
|
|
54
|
+
if(!pointer.startsWith('gitdir: ')) return null;
|
|
55
|
+
const gitdir=path.resolve(workspaceDir,pointer.slice(8));
|
|
56
|
+
if(path.basename(gitdir)!==requestId||path.basename(path.dirname(gitdir))!=='worktrees') return null;
|
|
57
|
+
const common=path.dirname(path.dirname(gitdir));
|
|
58
|
+
if(!fs.statSync(common).isDirectory()) return null;
|
|
59
|
+
const actual=fs.realpathSync(common),allowed=fs.realpathSync(mirrors);
|
|
60
|
+
return actual.startsWith(allowed+path.sep)?actual:null;
|
|
61
|
+
} catch { return null; }
|
|
62
|
+
}
|
|
63
|
+
const minFreeBytes=()=>Number(readEnv('DALAN_MIN_FREE_BYTES')??MIN_FREE_BYTES_DEFAULT);
|
|
64
|
+
// Last-use clocks are file mtimes (no schema); touched at most once a minute.
|
|
65
|
+
function touch(file) { try { const t=new Date();if(t-fs.statSync(file).mtime<60000) return;fs.utimesSync(file,t,t); } catch { try{fs.closeSync(fs.openSync(file,'a'));}catch{} } }
|
|
66
|
+
// Remove a directory that a concurrent check or submit may want next: the rename is atomic and sync, so no one can start using it after
|
|
67
|
+
// the caller decided it was idle, and the slow delete runs on the tombstone.
|
|
68
|
+
async function evictDir(dir) { const tomb=`${dir}.evicting-${randomUUID().slice(0,8)}`;fs.renameSync(dir,tomb);await removeCache(tomb); }
|
|
69
|
+
// The npm content store can contain attacker-controlled bytes. Partition it by worker and hash the exact repo identity so workers
|
|
70
|
+
// and distinct repo strings never share writable cache state. Only _cacache is shared within that boundary.
|
|
71
|
+
const repoCacheKey=repo=>typeof repo!=='string'||!repo?null:`r-${sha(repo)}`;
|
|
72
|
+
const workerCacheKey=worker=>`w-${sha(String(worker))}`;
|
|
73
|
+
const npmCacheKey=(worker,repo)=>{const repoKey=repoCacheKey(repo);return repoKey?`${workerCacheKey(worker)}-${repoKey}`:null;};
|
|
74
|
+
const payloadRepo=payload=>{try{return JSON.parse(payload).inputs?.[0]?.github_repo;}catch{return undefined;}};
|
|
75
|
+
const worktrees=path.join(root,'worktrees'), artifacts=path.join(root,'artifacts'), caches=path.join(root,'caches'), sharedNpm=path.join(caches,'shared','npm');
|
|
76
|
+
// Scoped, calm errors for a workspace that is closed to this claim. Each names the request and says only that request is affected.
|
|
77
|
+
// Callers match `error`, not the prose. Same JSON-in-message shape as review_mode_read_only.
|
|
78
|
+
const coded=(error,message)=>new Error(JSON.stringify({error,message}));
|
|
79
|
+
function closedWorkspace(a,requestId,claimId,claimEpoch,currentEpoch) {
|
|
80
|
+
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.`);
|
|
81
|
+
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.`);
|
|
82
|
+
if(a.status==='claimed'&&claimEpoch!==undefined&¤tEpoch!==undefined&&claimEpoch!==currentEpoch) return coded('claim_superseded',`claim ${claimId} for ${requestId} was superseded by epoch ${currentEpoch}; stop using this claim. This affects only ${requestId}.`);
|
|
83
|
+
return coded('assignment_not_claimed',`assignment ${requestId} is not claimed (status ${a.status}); its workspace is not open. This affects only ${requestId}.`);
|
|
84
|
+
}
|
|
85
|
+
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; }
|
|
86
|
+
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; }
|
|
87
|
+
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; }
|
|
88
|
+
// scope_paths is the assignment's read/write allow-list (submission-policy `within`). No scope_paths, or the repo-wide
|
|
89
|
+
// scope ".", means unrestricted, as before. Entries are normalised the same way submission-policy normalises them.
|
|
90
|
+
// scope_excluded files (sensitive files a broad --exclude-sensitive scope keeps out) are denied inside any scope.
|
|
91
|
+
// Exclusions compare a canonical form: Unicode NFC, then toLowerCase (not full Unicode case folding), for every path component, so a case or normalization
|
|
92
|
+
// alias (docs/PRIVATE-NOTE.TXT, a decomposed "é") that a case-insensitive or normalizing filesystem (macOS APFS) opens as
|
|
93
|
+
// the excluded file is excluded too. On case-sensitive Linux this over-excludes a differently-cased sibling: that fails closed.
|
|
94
|
+
export const canonicalPath=p=>p.split('/').map(part=>part.normalize('NFC').toLowerCase()).join('/');
|
|
95
|
+
export const isExcludedPath=(p,excluded)=>excluded.has(canonicalPath(p));
|
|
96
|
+
function scopeOf(assignment) {
|
|
97
|
+
const raw=assignment.scope_paths, excluded=new Set((assignment.scope_excluded||[]).map(d=>canonicalPath(d.path)));
|
|
98
|
+
const scope=Array.isArray(raw)&&raw.length?raw.map(p=>String(p).replace(/^\.\//,'').replace(/\/$/,'')):[];
|
|
99
|
+
const paths=!scope.length||scope.includes('.')?null:scope;
|
|
100
|
+
const outputs=outputsOf(assignment);
|
|
101
|
+
return paths||excluded.size||outputs.size?{paths,excluded,outputs}:null;
|
|
102
|
+
}
|
|
103
|
+
// output_paths: new files the job may create. They are readable and writable once they exist, and are the only writable
|
|
104
|
+
// files of a read-only assignment. Submit proved they are absent at the pinned revision and not sensitive.
|
|
105
|
+
const outputsOf=assignment=>new Set(Array.isArray(assignment.output_paths)?assignment.output_paths:[]);
|
|
106
|
+
// An output path that already exists at the checkout's HEAD is an existing file, not a new one, whatever the patch does to it.
|
|
107
|
+
// A file the job created (absent at HEAD, present in the worktree) stays editable. `ls-tree` lists an entry for a file or
|
|
108
|
+
// directory named exactly `file`; any git failure throws rather than reading as "absent".
|
|
109
|
+
function existsAtHead(dir,file) {
|
|
110
|
+
const r=spawnSync('git',['-C',dir,'ls-tree','-z','HEAD','--',file],{encoding:'utf8',timeout:10000,maxBuffer:1024*1024,env:gitEnv()});
|
|
111
|
+
if(r.error||r.status!==0) throw new Error(`git ls-tree failed: ${(r.stderr||r.error?.message||'').slice(0,200)}`);
|
|
112
|
+
return r.stdout.length>0;
|
|
113
|
+
}
|
|
114
|
+
const inScope=(p,scope)=>!scope||(!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded);
|
|
115
|
+
// A directory that holds a scope entry may be listed so the walk can reach it.
|
|
116
|
+
const leadsToScope=(p,scope)=>!scope||!scope.paths||inScope(p,scope)||scope.paths.some(s=>s.startsWith(`${p}/`))||[...scope.outputs].some(o=>o.startsWith(`${p}/`));
|
|
117
|
+
function outputDirectoryHint(file,outputs) {
|
|
118
|
+
const parent=[...outputs].find(p=>file.startsWith(`${p}/`));
|
|
119
|
+
return parent?` output_paths entry ${parent} names one new file, not a directory. List each new file in output_paths (for example ${file}); ask the owner to resubmit with the exact file paths.`:'';
|
|
120
|
+
}
|
|
121
|
+
// The on-disk spelling of `file` relative to the worktree (native realpath returns the stored case on macOS), so the
|
|
122
|
+
// scope and exclusion checks see the real path as well as the requested one.
|
|
123
|
+
function realRelative(dir,file,fallback) { try { const rel=path.relative(fs.realpathSync.native(dir),fs.realpathSync.native(file)); return rel&&!rel.startsWith('..')&&!path.isAbsolute(rel)?rel.split(path.sep).join('/'):fallback; } catch { return fallback; } }
|
|
124
|
+
function requireScope(p,scope) { if(!inScope(p,scope)) throw new Error(`path outside scope_paths: ${p}${outputDirectoryHint(p,scope?.outputs??[])}`); }
|
|
125
|
+
// Walk from `start` and stop at `max` files. Large repos used to throw 'file tree limit' on every call,
|
|
126
|
+
// so the worker could not list anything; now it gets the first `max` files and truncated:true.
|
|
127
|
+
export function guardedFiles(dir,start='',max=2000,scope=null,after='') { const out=[];let truncated=false,passed=!after; function walk(base,depth) { if(out.length>=max) { truncated=true; return; } if(depth>16) { truncated=true; return; } const entries=fs.readdirSync(path.join(dir,base),{withFileTypes:true}).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0); for(const ent of entries) { if(out.length>=max) { truncated=true; return; } if(ent.name==='.git') continue; const rel=base?`${base}/${ent.name}`:ent.name; if(ent.isSymbolicLink()) continue; if(ent.isDirectory()) { if(leadsToScope(rel,scope)) walk(rel,depth+1); } else if(ent.isFile()&&inScope(rel,scope)) { if(!passed) { if(rel===after) passed=true; } else out.push(rel); } } } if(start&&!fs.lstatSync(path.join(dir,start)).isDirectory()) return {files:inScope(start,scope)?[start]:[],truncated:false}; walk(start,0); if(!passed) throw new Error('cursor not found: list again from the start'); return {files:out,truncated}; }
|
|
128
|
+
function patchPaths(patch) {
|
|
129
|
+
const found=[];let current=null,inHeader=false,oldHeader=false,newHeader=false;
|
|
130
|
+
for(const line of patch.split('\n')) {
|
|
131
|
+
if(line.startsWith('diff --git ')) {
|
|
132
|
+
if(current&&oldHeader!==newHeader) throw new Error('incomplete patch headers');
|
|
133
|
+
const match=/^diff --git a\/(.+) b\/(.+)$/.exec(line);
|
|
134
|
+
if(!match||match[1]!==match[2]||match[1].includes('"')||/[\x00-\x1f]/.test(match[1])) throw new Error('renames or quoted paths unsupported');
|
|
135
|
+
current=relative(match[1]);found.push(current);inHeader=true;oldHeader=false;newHeader=false;
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if(!current) {if(line.trim()) throw new Error('patch must start with diff --git');continue;}
|
|
139
|
+
if(line.startsWith('@@')||line==='GIT binary patch') inHeader=false;
|
|
140
|
+
if(!inHeader&&(line.startsWith('--- ')||line.startsWith('+++ '))) throw new Error('unexpected patch header');
|
|
141
|
+
if(inHeader&&line.startsWith('--- ')) {if(line!=='--- /dev/null'&&line!==`--- a/${current}`)throw new Error('patch header path mismatch');oldHeader=true;}
|
|
142
|
+
if(inHeader&&line.startsWith('+++ ')) {if(line!=='+++ /dev/null'&&line!==`+++ b/${current}`)throw new Error('patch header path mismatch');newHeader=true;}
|
|
143
|
+
if(/^(new file mode|old mode|new mode) (120000|160000)/.test(line)||/^(rename|copy) (from|to) /.test(line)) throw new Error('symlink, submodule or rename denied');
|
|
144
|
+
}
|
|
145
|
+
if(current&&oldHeader!==newHeader) throw new Error('incomplete patch headers');
|
|
146
|
+
if(!found.length||found.length>200) throw new Error('invalid patch file count');
|
|
147
|
+
return [...new Set(found)];
|
|
148
|
+
}
|
|
149
|
+
export function validateIntegrationPatch(dir,patch,assignment) {
|
|
150
|
+
const files=patchPaths(Buffer.from(patch).toString('utf8'));
|
|
151
|
+
const scope=scopeOf(assignment);
|
|
152
|
+
for(const file of files) {
|
|
153
|
+
requireScope(file,scope);
|
|
154
|
+
safePath(dir,file);
|
|
155
|
+
if(isGenerated(file)&&!existsAtHead(dir,file)) throw coded('generated_path',`${file} is a new file under a build-output directory`);
|
|
156
|
+
}
|
|
157
|
+
return files;
|
|
158
|
+
}
|
|
159
|
+
function applyPatchToTree(dir,patch,scope=null) {
|
|
160
|
+
if(Buffer.byteLength(patch)>262144) throw new Error('patch too large');
|
|
161
|
+
const files=patchPaths(patch);
|
|
162
|
+
for(const p of files) requireScope(p,scope);
|
|
163
|
+
for(const p of files) safePath(dir,p);
|
|
164
|
+
const check=spawnSync('git',['-C',dir,'apply','--check','-'],{input:patch,encoding:'utf8',timeout:10000,env:gitEnv()});
|
|
165
|
+
if(check.status!==0) throw new Error(`patch rejected: ${(check.stderr||'').slice(0,200)}`);
|
|
166
|
+
const applied=spawnSync('git',['-C',dir,'apply','-'],{input:patch,encoding:'utf8',timeout:10000,env:gitEnv()});
|
|
167
|
+
if(applied.status!==0) throw new Error(`patch apply failed: ${(applied.stderr||'').slice(0,200)}`);
|
|
168
|
+
for(const p of files) {const f=path.join(dir,p);if(fs.existsSync(f))safePath(dir,p,true);}
|
|
169
|
+
return files;
|
|
170
|
+
}
|
|
171
|
+
// Failures land at the end of test output; keep both ends within the 8 KiB preview.
|
|
172
|
+
function previewHeadTail(text,head=2048,tail=6144) {
|
|
173
|
+
if (text.length<=head+tail) return text;
|
|
174
|
+
return `${text.slice(0,head)}\n…[${text.length-head-tail} chars omitted; full output in the check artifact]…\n${text.slice(-tail)}`;
|
|
175
|
+
}
|
|
176
|
+
function maskedOutputNote(paths,output) {
|
|
177
|
+
if(!paths.length) return '';
|
|
178
|
+
const text=output.toLowerCase();
|
|
179
|
+
const mentioned=paths.filter(file=>text.includes(file.toLowerCase())||text.includes(path.posix.basename(file).toLowerCase()));
|
|
180
|
+
const ordered=[...mentioned,...paths.filter(file=>!mentioned.includes(file))],shown=[];
|
|
181
|
+
let size='masked as empty: '.length;
|
|
182
|
+
for(const file of ordered) {
|
|
183
|
+
const next=Buffer.byteLength(file)+(shown.length?2:0);
|
|
184
|
+
if(size+next>800) break;
|
|
185
|
+
shown.push(file);size+=next;
|
|
186
|
+
}
|
|
187
|
+
const omitted=paths.length-shown.length;
|
|
188
|
+
return `\nmasked as empty: ${shown.join(', ')}${omitted?`, plus ${omitted} masked path(s) listed in check evidence`:''}`;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Entries a check or install leaves behind that no patch carries: dependency and build caches.
|
|
192
|
+
const GENERATED_DIRS=new Set(['node_modules','.venv','target','__pycache__']);
|
|
193
|
+
const isGenerated=file=>file.split('/').some(part=>GENERATED_DIRS.has(part));
|
|
194
|
+
// File names are bytes. A name that is not valid UTF-8 cannot be a JS string without loss, so it is carried as `<non-utf8 HEX "shown">`:
|
|
195
|
+
// reversible (nameBytes), never equal to a scope path (so never writable), and readable in evidence and errors.
|
|
196
|
+
const RAW_NAME=/^<non-utf8 ([0-9a-f]+) /;
|
|
197
|
+
const decodeName=buf=>{try{return new TextDecoder('utf-8',{fatal:true}).decode(buf);}catch{return `<non-utf8 ${buf.toString('hex')} ${JSON.stringify(buf.toString('latin1'))}>`;}};
|
|
198
|
+
const nameBytes=name=>{const m=RAW_NAME.exec(name);return m?Buffer.from(m[1],'hex'):Buffer.from(name);};
|
|
199
|
+
const splitRaw=buf=>{const out=[];let start=0;for(let i=0;i<buf.length;i++) if(buf[i]===0){if(i>start) out.push(buf.subarray(start,i));start=i+1;}if(start<buf.length) out.push(buf.subarray(start));return out;};
|
|
200
|
+
const splitNames=buf=>splitRaw(buf).map(decodeName);
|
|
201
|
+
const absBytes=(dir,name)=>Buffer.concat([Buffer.from(dir+path.sep),nameBytes(name)]);
|
|
202
|
+
// 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}).
|
|
203
|
+
// The diff stays bounded: the cap keeps `git diff --binary` output (base85, about 1.25x) well under its 12 MiB buffer.
|
|
204
|
+
const UNTRACKED_FILE_CAP=8*2**20, UNTRACKED_FILE_COUNT=200, DIFF_TOTAL_CAP=24*2**20;
|
|
205
|
+
const DIGEST_DEADLINE_MS=120000, CHANGED_PATHS_SHOWN=100, PREVIEW_SHOWN=25, DETAIL_ARTIFACT_CAP=2**20;
|
|
206
|
+
// What every receipt says it does not identify. Fixed text: no counts and no walk, so there is no partial number to misread.
|
|
207
|
+
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.';
|
|
208
|
+
// Async git call for the receipt digests (the live server must not block). Always the isolated environment.
|
|
209
|
+
function gitAsync2(dir,args,env,timeout=120000) { if(readEnv('DALAN_TEST_GIT_VIEW')==='fail') return Promise.resolve({status:128,stdout:'',buffer:Buffer.alloc(0),stderr:'fatal: simulated git failure'}); if(readEnv('DALAN_TEST_GIT_VIEW')==='timeout') return Promise.resolve({status:null,stdout:'',buffer:Buffer.alloc(0),stderr:'timed out'}); return new Promise(resolve=>{ const out=[];let err='';const child=spawn('git',['-C',dir,...args],{stdio:['ignore','pipe','pipe'],timeout,env});child.stdout.on('data',b=>out.push(b));child.stderr.on('data',b=>{if(err.length<300)err+=b;});child.on('error',e=>resolve({status:null,stdout:'',stderr:e.message}));child.on('close',status=>{const buffer=Buffer.concat(out);resolve({status,stdout:buffer.toString('utf8'),buffer,stderr:err});}); }); }
|
|
210
|
+
const resolveFrom=(dir,p)=>path.isAbsolute(p)?p:path.join(dir,p);
|
|
211
|
+
// Dependency and build directories git is told to leave out of an `add -A`, the same ones the diff leaves out.
|
|
212
|
+
const GENERATED_EXCLUDES=[...GENERATED_DIRS].map(name=>`:(exclude,glob)**/${name}/**`);
|
|
213
|
+
// Digest of git's view of the workspace: the tracked files plus the untracked files that are not ignored, as git would commit them.
|
|
214
|
+
// Git computes it (a copy of the real index, `add -u` for tracked changes, `add -A` for new files, `write-tree`), with the isolated
|
|
215
|
+
// environment, so symlinks are stored as links and never followed, and a path behind a symlinked directory is not read. New objects go to
|
|
216
|
+
// `scratch`, a throw-away directory, never into the mirror. Returns the tree id, or null with a reason when git could not read everything
|
|
217
|
+
// (an unreadable tracked file, an unreadable untracked directory, a timeout, a skip-worktree or assume-unchanged index entry, a missing
|
|
218
|
+
// index): then the receipt says the observation is unavailable instead of hashing a placeholder. The whole call has a 120 s deadline.
|
|
219
|
+
export async function treeDigest(dir,scratch) {
|
|
220
|
+
const own=!scratch;if(own) fs.mkdirSync(path.join(root,'run'),{recursive:true,mode:0o700});scratch??=fs.mkdtempSync(path.join(root,'run','digest-'));
|
|
221
|
+
try {
|
|
222
|
+
const base=gitEnv(),deadline=Date.now()+DIGEST_DEADLINE_MS,left=()=>Math.max(1000,deadline-Date.now());
|
|
223
|
+
const at=async args=>(await gitAsync2(dir,args,base,Math.min(30000,left())));
|
|
224
|
+
const common=(await at(['rev-parse','--git-common-dir'])).stdout.trim(),indexSrc=(await at(['rev-parse','--git-path','index'])).stdout.trim();
|
|
225
|
+
if(!common||!indexSrc) return {sha256:null,reason:'git_view_unavailable'};
|
|
226
|
+
const objects=path.join(scratch,'objects');fs.mkdirSync(objects,{recursive:true});
|
|
227
|
+
const index=path.join(scratch,`index-${randomUUID()}`);
|
|
228
|
+
// A missing or unreadable index must not become an empty one: every file would then look new.
|
|
229
|
+
// The copy keeps the original index's mtime. Git's racy-stat rule (a file no older than the index may have changed within the same
|
|
230
|
+
// clock second without its size or mtime changing) compares file times with the index time; a copy stamped "now" would hide such a change.
|
|
231
|
+
try{const source=resolveFrom(dir,indexSrc);fs.copyFileSync(source,index);const st=fs.statSync(source);fs.utimesSync(index,st.atime,st.mtime);}catch(error){return {sha256:null,reason:`index_copy_failed: ${error.code||'error'}`};}
|
|
232
|
+
const env={...base,GIT_INDEX_FILE:index,GIT_OBJECT_DIRECTORY:objects,GIT_ALTERNATE_OBJECT_DIRECTORIES:path.join(resolveFrom(dir,common),'objects')};
|
|
233
|
+
// git reads a tracked file it cannot stat (inside a mode-000 directory, say) as deleted. A path that is absent for any reason other
|
|
234
|
+
// than not existing is unreadable, not deleted: no digest is promoted from it.
|
|
235
|
+
// Index flags that tell git not to look at the worktree (skip-worktree, assume-unchanged) would hide changes from `add -u`.
|
|
236
|
+
const flags=await gitAsync2(dir,['ls-files','-v','-z'],env,left());
|
|
237
|
+
if(flags.status!==0) return {sha256:null,reason:flags.status===null?'git_timeout_or_error':`git_could_not_read_a_file: ${flags.stderr.split('\n')[0].slice(0,160)}`};
|
|
238
|
+
if(flags.stdout.split('\0').some(record=>record&&(record[0]==='S'||/[a-z]/.test(record[0])))) return {sha256:null,reason:'index_flags_present'};
|
|
239
|
+
const deleted=await gitAsync2(dir,['ls-files','--deleted','-z'],env,left());
|
|
240
|
+
if(deleted.status!==0) return {sha256:null,reason:deleted.status===null?'git_timeout_or_error':`git_could_not_read_a_file: ${deleted.stderr.split('\n')[0].slice(0,160)}`};
|
|
241
|
+
for(const file of deleted.stdout.split('\0').filter(Boolean)) {
|
|
242
|
+
try{fs.lstatSync(path.join(dir,file));}catch(error){if(error.code==='ENOENT'||error.code==='ENOTDIR') continue;return {sha256:null,reason:`unreadable_path: ${error.code||'error'}`};}
|
|
243
|
+
}
|
|
244
|
+
for(const args of [['add','-u','--ignore-errors'],['add','-A','--',':/',...GENERATED_EXCLUDES]]) {
|
|
245
|
+
const r=await gitAsync2(dir,args,env,left());
|
|
246
|
+
// git only warns about an untracked directory it cannot open and exits 0: that is a partial view, not a clean one.
|
|
247
|
+
if(r.status===0&&/could not open directory|Permission denied/i.test(r.stderr)) return {sha256:null,reason:'partial_unreadable_untracked'};
|
|
248
|
+
if(r.status!==0) return {sha256:null,reason:r.status===null?`git_timeout_or_error: ${r.stderr.split('\n')[0].slice(0,160)}`:`git_could_not_read_a_file: ${r.stderr.split('\n')[0].slice(0,160)}`};
|
|
249
|
+
}
|
|
250
|
+
const tree=await gitAsync2(dir,['write-tree'],env,left());
|
|
251
|
+
fs.rmSync(index,{force:true});
|
|
252
|
+
return tree.status===0?{sha256:tree.stdout.trim(),reason:null,scratch}:{sha256:null,reason:'git_write_tree_failed'};
|
|
253
|
+
} finally { if(own) fs.rmSync(scratch,{recursive:true,force:true}); }
|
|
254
|
+
}
|
|
255
|
+
// Paths that differ between two tree ids made by treeDigest in the same scratch directory (or a tree of the mirror). Null when unknown.
|
|
256
|
+
async function treePathsChanged(dir,scratch,common,a,b) {
|
|
257
|
+
if(!a||!b) return null;
|
|
258
|
+
if(a===b) return [];
|
|
259
|
+
const env={...gitEnv(),GIT_OBJECT_DIRECTORY:path.join(scratch,'objects'),GIT_ALTERNATE_OBJECT_DIRECTORIES:path.join(common,'objects')};
|
|
260
|
+
const r=await gitAsync2(dir,['diff-tree','-r','--name-only','--no-renames','-z',a,b],env,60000);
|
|
261
|
+
return r.status===0?splitNames(r.buffer).sort():null;
|
|
262
|
+
}
|
|
263
|
+
// What a job may change, as a yes/no on a repository path. null means everything (an implementation job without a narrower scope_paths).
|
|
264
|
+
// Implementation: scope_paths and output_paths (minus scope_excluded). Read-only: output_paths only. This is the set apply_patch enforces.
|
|
265
|
+
export function writableScope(assignment) {
|
|
266
|
+
if(assignment.execution_scope==='implementation') {const scope=scopeOf(assignment);return scope?p=>inScope(p,scope):null;}
|
|
267
|
+
const outputs=outputsOf(assignment);return p=>outputs.has(p);
|
|
268
|
+
}
|
|
269
|
+
// git with a write to its stdin (checkout-index --stdin), never blocking the live server.
|
|
270
|
+
function gitAsyncInput(dir,args,env,input,timeout=60000) { return new Promise(resolve=>{ let err='';const child=spawn('git',['-C',dir,...args],{stdio:['pipe','ignore','pipe'],timeout,env});child.stderr.on('data',b=>{if(err.length<300)err+=b;});child.on('error',e=>resolve({status:null,stderr:e.message}));child.on('close',status=>resolve({status,stderr:err}));child.stdin.on('error',()=>{});child.stdin.end(input); }); }
|
|
271
|
+
// Put every path a command changed OUTSIDE the writable set back to its state in `preTree` (a tree made by treeDigest before the
|
|
272
|
+
// first phase ran). Git does it, with the isolated environment and no stash: the tree after the run is read with treeDigest, the paths
|
|
273
|
+
// that differ from `preTree` are listed with diff-tree, and
|
|
274
|
+
// - a path the command added is removed (empty directories it leaves behind are pruned, unless writable),
|
|
275
|
+
// - a path it changed or deleted is rewritten from `preTree` by `git checkout-index -f` on a temporary index read from that tree
|
|
276
|
+
// (content, mode and symlink as committed; a symlink that replaced a directory is replaced back).
|
|
277
|
+
// Generated directories (node_modules, ...) are never touched. Afterwards the tree is read again and must equal `preTree` outside the
|
|
278
|
+
// writable set; the paths that still differ come back in `error`. Returns {paths (restored, sorted), error, before, after}: the tree
|
|
279
|
+
// digests just before and after the restore (`after` is the digest of what stays). It does not throw for a git failure; the caller
|
|
280
|
+
// records `error` and result/finish refuse with scope_violation if anything out of scope is left.
|
|
281
|
+
export async function restoreOutsideWritable({dir,scratch,preTree,writable}) {
|
|
282
|
+
const before=await treeDigest(dir,scratch);
|
|
283
|
+
if(!before.sha256) return {paths:[],error:`post_run_tree_unavailable: ${before.reason}`,before,after:before};
|
|
284
|
+
let common;try{common=resolveFrom(dir,git(['-C',dir,'rev-parse','--git-common-dir']).trim());}catch(error){return {paths:[],error:error.message,before,after:before};}
|
|
285
|
+
const env={...gitEnv(),GIT_OBJECT_DIRECTORY:path.join(scratch,'objects'),GIT_ALTERNATE_OBJECT_DIRECTORIES:path.join(common,'objects')};
|
|
286
|
+
const listed=await gitAsync2(dir,['diff-tree','-r','--raw','--no-renames','-z',preTree,before.sha256],env,60000);
|
|
287
|
+
if(listed.status!==0) return {paths:[],error:`diff_tree_failed: ${listed.stderr.split('\n')[0].slice(0,160)}`,before,after:before};
|
|
288
|
+
// Tracked files under node_modules, target, ... are tracked files: they are in this list and restored like any other. Only untracked
|
|
289
|
+
// generated output is exempt, and treeDigest never adds that to a tree, so it is never listed.
|
|
290
|
+
const tokens=splitRaw(listed.buffer),entries=[];
|
|
291
|
+
for(let i=0;i+1<tokens.length;i+=2) if(tokens[i][0]===0x3a) entries.push({status:tokens[i].toString().split(' ')[4]?.[0],path:decodeName(tokens[i+1])});
|
|
292
|
+
const outside=entries.filter(entry=>!writable(entry.path));
|
|
293
|
+
if(!outside.length) return {paths:[],error:null,before,after:before};
|
|
294
|
+
const errors=[];
|
|
295
|
+
// A path is removed or written only below real directories: a symlinked ancestor is itself a listed change and is handled on its own.
|
|
296
|
+
const parentsOf=name=>{const bytes=nameBytes(name),out=[];for(let i=0;i<bytes.length;i++) if(bytes[i]===0x2f) out.push(bytes.subarray(0,i));return out;};
|
|
297
|
+
const realParents=name=>{for(const parent of parentsOf(name)){try{if(!fs.lstatSync(Buffer.concat([Buffer.from(dir+path.sep),parent])).isDirectory()) return false;}catch{return true;}}return true;};
|
|
298
|
+
for(const entry of outside.filter(e=>e.status==='A')) {
|
|
299
|
+
if(!realParents(entry.path)) continue;
|
|
300
|
+
try{fs.rmSync(absBytes(dir,entry.path),{recursive:true,force:true});}catch(error){errors.push(`${entry.path}: ${error.code||error.message}`);continue;}
|
|
301
|
+
for(const parent of parentsOf(entry.path).reverse()) {if(writable(decodeName(parent))) break;try{fs.rmdirSync(Buffer.concat([Buffer.from(dir+path.sep),parent]));}catch{break;}}
|
|
302
|
+
}
|
|
303
|
+
const rewrite=outside.filter(e=>e.status!=='A').map(e=>e.path);
|
|
304
|
+
if(rewrite.length) {
|
|
305
|
+
const index=path.join(scratch,`restore-index-${randomUUID()}`),withIndex={...env,GIT_INDEX_FILE:index};
|
|
306
|
+
try {
|
|
307
|
+
const read=await gitAsync2(dir,['read-tree',preTree],withIndex,60000);
|
|
308
|
+
if(read.status!==0) errors.push(`read_tree_failed: ${read.stderr.split('\n')[0].slice(0,160)}`);
|
|
309
|
+
else {
|
|
310
|
+
const out=await gitAsyncInput(dir,['checkout-index','-f','-z','--stdin'],withIndex,Buffer.concat(rewrite.flatMap(name=>[nameBytes(name),Buffer.from([0])])));
|
|
311
|
+
if(out.status!==0) errors.push(`checkout_index_failed: ${String(out.stderr).split('\n')[0].slice(0,160)}`);
|
|
312
|
+
}
|
|
313
|
+
} finally { fs.rmSync(index,{force:true}); }
|
|
314
|
+
}
|
|
315
|
+
const after=await treeDigest(dir,scratch);
|
|
316
|
+
let remaining=null;
|
|
317
|
+
if(after.sha256) {
|
|
318
|
+
const left=await treePathsChanged(dir,scratch,common,preTree,after.sha256);
|
|
319
|
+
remaining=left===null?null:left.filter(file=>!writable(file));
|
|
320
|
+
}
|
|
321
|
+
if(remaining===null) errors.push(`restore_unverified: ${after.reason||'diff_tree_failed'}`);
|
|
322
|
+
else if(remaining.length) errors.push(`restore_incomplete: ${remaining.slice(0,10).join(', ')}`);
|
|
323
|
+
return {paths:[...new Set(outside.map(e=>e.path))].sort(),error:errors.length?errors.join('; ').slice(0,500):null,before,after};
|
|
324
|
+
}
|
|
325
|
+
// Tracked (and untracked, not ignored) sensitive files in the checkout. The check sandbox lays an empty read-only file over each one,
|
|
326
|
+
// including symlinks, so a check cannot read their target or print their contents.
|
|
327
|
+
const MASK_LIMIT=1000;
|
|
328
|
+
export function sensitiveMasks(dir,repo,copyDir) {
|
|
329
|
+
const policy=sensitivePolicyPaths();
|
|
330
|
+
if(policy.error) throw new Error('sensitive_policy_unavailable: restore a valid mode-0600 submission policy');
|
|
331
|
+
const listed=git(['-C',dir,'ls-files','-z','--cached','--others','--exclude-standard'],{maxBuffer:64*1024*1024}).split('\0').filter(Boolean);
|
|
332
|
+
const paths=[...new Set(listed)].filter(file=>!isGenerated(file)&&isSensitiveRepoPath(file,policy.paths)).filter(file=>{try{const st=fs.lstatSync(path.join(dir,file));return st.isFile()||st.isSymbolicLink();}catch{return false;}}).sort();
|
|
333
|
+
const sourceExemptions=[];
|
|
334
|
+
for(const approval of policy.sourceExemptions||[]) {
|
|
335
|
+
if(approval.github_repo!==repo||!isSourceExemptionPath(approval.path)||!paths.includes(approval.path)) continue;
|
|
336
|
+
try {
|
|
337
|
+
const tracked=git(['-C',dir,'ls-files','-z','--error-unmatch','--',approval.path]).split('\0').filter(Boolean);
|
|
338
|
+
if(tracked.length!==1||tracked[0]!==approval.path) continue;
|
|
339
|
+
const full=path.join(dir,approval.path),before=fs.lstatSync(full);
|
|
340
|
+
if(!before.isFile()||before.isSymbolicLink()) continue;
|
|
341
|
+
const fd=fs.openSync(full,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW??0));
|
|
342
|
+
let contents;
|
|
343
|
+
try { const opened=fs.fstatSync(fd);if(!opened.isFile()||opened.ino!==before.ino||opened.dev!==before.dev||opened.size>16*1024*1024) continue;contents=fs.readFileSync(fd); }
|
|
344
|
+
finally { fs.closeSync(fd); }
|
|
345
|
+
const blobSha=createHash('sha1').update(`blob ${contents.length}\0`).update(contents).digest('hex');
|
|
346
|
+
if(blobSha!==approval.blob_sha||secretContent.test(contents.toString('utf8'))) continue;
|
|
347
|
+
const hostPath=path.join(copyDir,`${sourceExemptions.length}.source`);
|
|
348
|
+
fs.writeFileSync(hostPath,contents,{flag:'wx',mode:0o444});
|
|
349
|
+
sourceExemptions.push({path:approval.path,blob_sha:blobSha,hostPath});
|
|
350
|
+
} catch {}
|
|
351
|
+
}
|
|
352
|
+
const exempt=new Set(sourceExemptions.map(entry=>entry.path));
|
|
353
|
+
const maskedPaths=paths.filter(file=>!exempt.has(file));
|
|
354
|
+
if(maskedPaths.length>MASK_LIMIT) throw new Error(`sensitive_mask_limit: ${maskedPaths.length} sensitive files in the checkout (limit ${MASK_LIMIT}); a check cannot be confined around that many`);
|
|
355
|
+
return {paths:maskedPaths,sourceExemptions,policyError:policy.error};
|
|
356
|
+
}
|
|
357
|
+
// A list shown in the receipt: the first `shown` names, the true total, and a flag when the preview is shorter than the total.
|
|
358
|
+
const preview=(list,shown)=>list===null?null:({preview:list.slice(0,shown),total:list.length,truncated:list.length>shown});
|
|
359
|
+
// The lists go to one bounded artifact; null when every list is empty. The cap counts the serialized JSON, envelope and separators
|
|
360
|
+
// included. When a list does not fit, the artifact says "partial" and how much was kept; it never calls a cut list complete.
|
|
361
|
+
export function boundedDetail(lists,cap=DETAIL_ARTIFACT_CAP) {
|
|
362
|
+
const names=Object.keys(lists).filter(name=>lists[name]?.length);
|
|
363
|
+
if(!names.length) return null;
|
|
364
|
+
const kept=Object.fromEntries(names.map(name=>[name,lists[name].slice()]));
|
|
365
|
+
const build=()=>{const truncated={};for(const name of names) if(kept[name].length<lists[name].length) truncated[name]={kept:kept[name].length,total:lists[name].length};
|
|
366
|
+
return Buffer.from(JSON.stringify({schema:2,complete:Object.keys(truncated).length===0,note:Object.keys(truncated).length?'PARTIAL: the artifact size cap was reached; see truncated for what was kept':'complete lists',lists:kept,truncated}));};
|
|
367
|
+
let bytes=build();
|
|
368
|
+
while(bytes.length>cap) { const longest=names.reduce((x,y)=>kept[y].length>kept[x].length?y:x);if(!kept[longest].length) break;kept[longest].length=Math.floor(kept[longest].length*0.9)||0;bytes=build(); }
|
|
369
|
+
return bytes;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// Versions of what runs the check: the node binary bound into the sandbox, bwrap and pasta. Read once.
|
|
373
|
+
let runtimeCache=null;
|
|
374
|
+
function runtimeVersions() {
|
|
375
|
+
if(runtimeCache) return runtimeCache;
|
|
376
|
+
const first=(cmd,args)=>{try{const r=spawnSync(cmd,args,{encoding:'utf8',timeout:5000,env:{PATH:'/usr/bin:/bin'}});return (r.stdout||r.stderr||'').split('\n')[0].trim()||null;}catch{return null;}};
|
|
377
|
+
const pasta=['/usr/bin/pasta','/usr/local/bin/pasta'].find(f=>fs.existsSync(f));
|
|
378
|
+
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};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export class Workspace {
|
|
382
|
+
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(); }
|
|
383
|
+
// Only called after expiry/revocation: the host supervisor observes loss of
|
|
384
|
+
// authority and stops the whole unit. Await its receipt and discarded output.
|
|
385
|
+
async quiesce(requestId) {
|
|
386
|
+
await this.checkEffects.get(requestId);
|
|
387
|
+
this.reconcileHostStops(requestId);
|
|
388
|
+
}
|
|
389
|
+
// Restart loses the pipe and in-memory promises. Only the trusted service's
|
|
390
|
+
// immutable start + matching empty-cgroup stop can release that durable guard.
|
|
391
|
+
reconcileHostStops(requestId) {
|
|
392
|
+
const jobs=this.store.db.prepare("SELECT id,stop_evidence FROM check_jobs WHERE (? IS NULL OR request_id=?) AND status!='running' AND stop_verified IS NOT 1").all(requestId??null,requestId??null);
|
|
393
|
+
const results=[];
|
|
394
|
+
for(const job of jobs) {
|
|
395
|
+
const options={receiptDir:path.join(root,'host-receipts'),checkRunId:job.id};
|
|
396
|
+
// An unverified or missing stop is re-checked against fresh evidence: a changed boot id, or an inactive unit with an empty cgroup.
|
|
397
|
+
let stop=readVerifiedHostStop(options)??reverifyHostStop(options,this.stopReverify);
|
|
398
|
+
// Legacy invocations do not participate in admission sealing; absent
|
|
399
|
+
// evidence for them remains unknown. New ones cannot start after sealing.
|
|
400
|
+
if(!stop&&JSON.parse(job.stop_evidence??'null')?.host?.receipt_protocol===1) stop=sealHostNotStarted(options);
|
|
401
|
+
if(!stop) {results.push({check_run_id:job.id,verified:false});continue;}
|
|
402
|
+
results.push({check_run_id:job.id,verified:true,basis:stop.basis??null});
|
|
403
|
+
this.store.transaction(()=>{
|
|
404
|
+
const row=this.store.db.prepare('SELECT status,stop_verified FROM check_jobs WHERE id=?').get(job.id);
|
|
405
|
+
if(!row||row.status==='running'||row.stop_verified===1) return;
|
|
406
|
+
// Earlier partial-phase evidence cannot stand for this invocation's stop.
|
|
407
|
+
this.store.db.prepare('UPDATE check_jobs SET stop_verified=1,stop_evidence=? WHERE id=?').run(JSON.stringify({host:{verified:true,reason:stop.notStarted?'durable_host_admission_sealed':stop.reverified?'durable_systemd_control_group_reverified':'durable_systemd_control_group_stopped',invocation_id:stop.invocationId,remaining_pids:[]}}),job.id);
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
return results;
|
|
411
|
+
}
|
|
412
|
+
// Scratch directories of receipt digests left by a crash. Only old ones go, so a live check of another process is never touched.
|
|
413
|
+
sweepDigestScratch(maxAgeMs=3600000) {
|
|
414
|
+
const dir=path.join(root,'run');let names;try{names=fs.readdirSync(dir);}catch{return 0;}
|
|
415
|
+
let removed=0;
|
|
416
|
+
for(const name of names) { if(!name.startsWith('digest-')) continue;const full=path.join(dir,name);try{if(Date.now()-fs.statSync(full).mtimeMs>=maxAgeMs){fs.rmSync(full,{recursive:true,force:true});removed++;}}catch{} }
|
|
417
|
+
return removed;
|
|
418
|
+
}
|
|
419
|
+
context(requestId,claimId,subject,write=false,worker='dot',allowOutputs=false) {
|
|
420
|
+
if(!this.store.mayAct(worker,requestId)) throw new Error('assignment not found');
|
|
421
|
+
const a=this.store.get(requestId),claim=this.store.assertClaim(requestId,claimId,subject,worker);
|
|
422
|
+
if(a.status!=='claimed'||a.cancelled_at) throw closedWorkspace(a,requestId,claimId);
|
|
423
|
+
if(write&&a.assignment.execution_scope!=='implementation'&&!(allowOutputs&&outputsOf(a.assignment).size)) throw coded('read_only_assignment',`${requestId} is read-only (execution_scope ${a.assignment.execution_scope}); apply_patch is not allowed for it. This affects only this action on ${requestId}; reads and checks still work.`);
|
|
424
|
+
const input=assignmentInput(a.assignment);
|
|
425
|
+
const saved=this.store.db.prepare('SELECT claim_id,path FROM workspaces WHERE request_id=?').get(requestId);
|
|
426
|
+
let mirror=saved?.claim_id===claimId?savedWorkspaceMirror(saved.path,requestId):null;
|
|
427
|
+
if(!mirror) mirror=mirrorPath(input.github_repo,{worker});
|
|
428
|
+
if(!fs.existsSync(mirror)) mirror=prepareGithubRepo(input,{worker});
|
|
429
|
+
touch(path.join(mirror,'dot-last-used'));
|
|
430
|
+
const actual=git(['-C',mirror,'rev-parse','--verify',`${input.base_sha}^{commit}`]).trim();
|
|
431
|
+
if(actual!==input.base_sha) throw new Error('base SHA missing from local mirror');
|
|
432
|
+
return {a,claim,input,mirror};
|
|
433
|
+
}
|
|
434
|
+
ensure(requestId,claimId,subject,allowActive=false,worker='dot') {
|
|
435
|
+
if(this.activeChecks.has(requestId)&&!allowActive) throw new Error('check still running');
|
|
436
|
+
const ctx=this.context(requestId,claimId,subject,false,worker),dir=path.join(worktrees,requestId),checkoutSha=(ctx.a.assignment.execution_scope==='read-only'||ctx.a.review)&&ctx.input.head_sha?ctx.input.head_sha:ctx.input.base_sha;
|
|
437
|
+
let row=this.store.db.prepare('SELECT * FROM workspaces WHERE request_id=?').get(requestId);
|
|
438
|
+
if(!row) {
|
|
439
|
+
if(fs.existsSync(dir)) {
|
|
440
|
+
const pointer=fs.readFileSync(path.join(dir,'.git'),'utf8');
|
|
441
|
+
const common=path.join(ctx.mirror,'worktrees')+path.sep;
|
|
442
|
+
const listed=git(['-C',ctx.mirror,'worktree','list','--porcelain']).split('\n').includes(`worktree ${dir}`);
|
|
443
|
+
if(fs.realpathSync(dir)!==dir||!pointer.startsWith('gitdir: '+common)||!listed||git(['-C',dir,'rev-parse','HEAD']).trim()!==checkoutSha) throw new Error('unrecorded workspace mismatch');
|
|
444
|
+
} else {
|
|
445
|
+
git(['-C',ctx.mirror,'worktree','add','--detach',dir,checkoutSha]);
|
|
446
|
+
fs.chmodSync(dir,0o700);
|
|
447
|
+
}
|
|
448
|
+
this.store.db.prepare('INSERT INTO workspaces(request_id,claim_id,base_sha,path,created_at) VALUES(?,?,?,?,?)')
|
|
449
|
+
.run(requestId,claimId,ctx.input.base_sha,dir,new Date().toISOString());
|
|
450
|
+
row=this.store.db.prepare('SELECT * FROM workspaces WHERE request_id=?').get(requestId);
|
|
451
|
+
}
|
|
452
|
+
if(row.claim_id!==claimId||row.base_sha!==ctx.input.base_sha||row.path!==dir||git(['-C',dir,'rev-parse','HEAD']).trim()!==checkoutSha) throw new Error('workspace binding mismatch');
|
|
453
|
+
if(!row.initial_patch_applied) {
|
|
454
|
+
if(ctx.input.input_patch) {
|
|
455
|
+
const reverse=spawnSync('git',['-C',dir,'apply','--reverse','--check','-'],{input:ctx.input.input_patch,encoding:'utf8',timeout:10000,env:gitEnv()});
|
|
456
|
+
if(reverse.status!==0) applyPatchToTree(dir,ctx.input.input_patch);
|
|
457
|
+
}
|
|
458
|
+
this.store.db.prepare('UPDATE workspaces SET initial_patch_applied=1 WHERE request_id=?').run(requestId);
|
|
459
|
+
}
|
|
460
|
+
return {...ctx,dir};
|
|
461
|
+
}
|
|
462
|
+
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}; }
|
|
463
|
+
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');
|
|
464
|
+
// 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.
|
|
465
|
+
const {text:clean,redacted}=redactSecrets(whole);
|
|
466
|
+
const lines=clean.split('\n'),window=lines.slice(start-1,start-1+max);
|
|
467
|
+
let value=window.join('\n'),end=start+window.length-1;
|
|
468
|
+
const truncated=Buffer.byteLength(value)>32768;
|
|
469
|
+
if(truncated) {
|
|
470
|
+
const bytes=Buffer.from(value),newline=bytes.lastIndexOf(10,32768);
|
|
471
|
+
if(newline>=0) {
|
|
472
|
+
// Keep complete lines, without a delimiter that would imply a further line.
|
|
473
|
+
value=bytes.subarray(0,newline).toString('utf8');
|
|
474
|
+
} else {
|
|
475
|
+
// The first line alone exceeds the cap. Back up over a partial UTF-8 character.
|
|
476
|
+
let cut=32768;while((bytes[cut]&0xc0)===0x80) cut--;
|
|
477
|
+
value=bytes.subarray(0,cut).toString('utf8');
|
|
478
|
+
}
|
|
479
|
+
end=start+value.split('\n').length-1;
|
|
480
|
+
}
|
|
481
|
+
return {path:p,start_line:start,end_line:end,total_lines:lines.length,text:value,truncated,...(redacted?{redacted}:{})}; }
|
|
482
|
+
// `only` (the output_paths of a read-only assignment): the diff is the job's own change against the checkout (HEAD), and its
|
|
483
|
+
// exact changed-file set (both sides of any rename, deletions, mode changes, untracked files) must lie inside `only`. Git
|
|
484
|
+
// pathspecs are not used for this: they also match descendants of a path. Any other change refuses with output_paths_violation
|
|
485
|
+
// instead of riding along in the patch. An output that is a symlink refuses too.
|
|
486
|
+
diff(dir,base='HEAD',only=null,scope=null) {
|
|
487
|
+
if(only) {
|
|
488
|
+
base='HEAD';
|
|
489
|
+
const tracked=splitNames(git(['-C',dir,'diff','--name-only','-z','--no-renames',base],{encoding:'buffer'}));
|
|
490
|
+
const untracked=spawnSync('git',['-C',dir,'ls-files','--others','--exclude-standard','-z'],{timeout:10000,maxBuffer:64*1024*1024,env:gitEnv()});
|
|
491
|
+
if(untracked.status!==0) throw new Error('cannot enumerate untracked files');
|
|
492
|
+
const outside=[...new Set([...tracked,...splitNames(untracked.stdout)])].filter(file=>!only.has(file));
|
|
493
|
+
for(const file of only) {try{if(fs.lstatSync(path.join(dir,file)).isSymbolicLink()) outside.push(file);}catch(error){if(error.code!=='ENOENT'&&error.code!=='ENOTDIR') throw error;}}
|
|
494
|
+
if(outside.length) throw Object.assign(new Error(`output_paths_violation: the workspace changed files outside output_paths (${[...only].join(', ')}): ${[...new Set(outside)].sort().slice(0,10).join(', ')}. A read-only job may change only its declared output files, as regular files; remove the others.`),{outputViolation:true});
|
|
495
|
+
}
|
|
496
|
+
let patch=git(['-C',dir,'diff','--no-ext-diff','--no-textconv','--binary',base]);
|
|
497
|
+
const changed=new Set(splitNames(git(['-C',dir,'diff','--name-only','-z','--no-renames',base],{encoding:'buffer'})));
|
|
498
|
+
const others=spawnSync('git',['-C',dir,'ls-files','--others','--exclude-standard','-z'],{timeout:10000,maxBuffer:64*1024*1024,env:gitEnv()});
|
|
499
|
+
if(others.status!==0) throw new Error('cannot enumerate untracked files');
|
|
500
|
+
const files=splitNames(others.stdout).filter(file=>!isGenerated(file));
|
|
501
|
+
const omissions=[],omit=(file,size,reason)=>{omissions.push({path:file,size,reason});changed.add(file);};
|
|
502
|
+
for(const file of files.slice(UNTRACKED_FILE_COUNT)) omit(file,null,'too_many_untracked_files');
|
|
503
|
+
for(const file of files.slice(0,UNTRACKED_FILE_COUNT)) {
|
|
504
|
+
// A check runs inside this workspace and may leave or briefly create entries the worker never addresses by path: lock files
|
|
505
|
+
// that are symlinks, scratch dirs, temp files. They are not part of a patch (patchPaths refuses symlink modes), so an untracked
|
|
506
|
+
// symlink is left out of the diff instead of failing every read-only tool. Its parent directories are still checked, and
|
|
507
|
+
// read, list and apply_patch still refuse any symlink on a path they are given. An entry that vanished mid-run is skipped too.
|
|
508
|
+
// Anything else the diff cannot carry (too large, unreadable, not a regular file) is named in `omissions`, never thrown: one
|
|
509
|
+
// such file used to make diff throw, which lost the check result and every later workspace_result.
|
|
510
|
+
// A name that is not UTF-8 cannot be read back by this code as a string: name it as omitted (and, in a scoped job, out of scope), never skip it.
|
|
511
|
+
if(RAW_NAME.test(file)) {omit(file,null,'non_utf8_name');continue;}
|
|
512
|
+
let entry;
|
|
513
|
+
try{entry=fs.lstatSync(path.join(dir,file));}catch(error){if(error.code==='ENOENT') continue;throw error;}
|
|
514
|
+
if(entry.isSymbolicLink()) {if(path.dirname(file)!=='.') safePath(dir,path.dirname(file),true);continue;}
|
|
515
|
+
let source;try{source=safePath(dir,file,true);}catch(error){omit(file,entry.size,'unsafe_path');continue;}
|
|
516
|
+
if(!entry.isFile()) {omit(file,entry.size,'not_regular_file');continue;}
|
|
517
|
+
if(entry.size>UNTRACKED_FILE_CAP) {omit(file,entry.size,'too_large');continue;}
|
|
518
|
+
try{fs.accessSync(source,fs.constants.R_OK);}catch{omit(file,entry.size,'unreadable');continue;}
|
|
519
|
+
const result=spawnSync('git',['diff','--no-index','--no-ext-diff','--no-textconv','--binary','--','/dev/null',file],{cwd:dir,encoding:'utf8',timeout:10000,maxBuffer:12*1024*1024,env:gitEnv()});
|
|
520
|
+
if(result.error||result.status!==1) {if(!fs.existsSync(source)) continue;omit(file,entry.size,result.error?.code==='ENOBUFS'?'too_large':'diff_failed');continue;}
|
|
521
|
+
if(Buffer.byteLength(patch)+Buffer.byteLength(result.stdout)>DIFF_TOTAL_CAP) {omit(file,entry.size,'diff_total_cap');continue;}
|
|
522
|
+
patch+=result.stdout;changed.add(file);
|
|
523
|
+
}
|
|
524
|
+
// Defense in depth for implementation jobs: apply_patch and the post-check restore keep the diff inside scope_paths and output_paths,
|
|
525
|
+
// and this refuses a diff that still carries anything else. `changed` holds tracked changes (a tracked file under node_modules or target
|
|
526
|
+
// counts) and untracked files other than generated output; omitted files are in it too.
|
|
527
|
+
if(scope) {
|
|
528
|
+
const outside=[...changed].filter(file=>!inScope(file,scope)).sort();
|
|
529
|
+
if(outside.length) throw Object.assign(new Error(JSON.stringify({error:'scope_violation',message:`the workspace changed files outside scope_paths/output_paths: ${outside.slice(0,10).join(', ')}${outside.length>10?`, and ${outside.length-10} more`:''}. An implementation job may change only its scope_paths and output_paths. This job is stuck because of ${outside.length>3?`${outside.length} paths`:'these paths'}: no worker action can fix it (apply_patch cannot touch paths outside scope_paths). Tell the owner to cancel and resubmit the request. This affects only this request.`,paths:outside.slice(0,100),total:outside.length})),{scopeViolation:true,paths:outside});
|
|
530
|
+
}
|
|
531
|
+
return {patch,sha256:sha(patch),bytes:Buffer.byteLength(patch),omissions,paths:[...changed].sort()};
|
|
532
|
+
}
|
|
533
|
+
apply(requestId,claimId,subject,patch,worker='dot') { this.context(requestId,claimId,subject,true,worker,true);if(this.store.get(requestId).review) throw new Error(JSON.stringify({error:'review_mode_read_only',message:'apply_patch is disabled for review submissions; read files, run_check, and report findings with finish.'}));const {dir,input,a}=this.ensure(requestId,claimId,subject,false,worker);
|
|
534
|
+
// A read-only assignment with output_paths may write those files and nothing else: one other file refuses the whole patch.
|
|
535
|
+
if(a.assignment.execution_scope!=='implementation') {
|
|
536
|
+
const outputs=outputsOf(a.assignment),outside=patchPaths(patch).filter(file=>!outputs.has(file));
|
|
537
|
+
if(outside.length) throw coded('read_only_assignment',`${requestId} is read-only (execution_scope ${a.assignment.execution_scope}); apply_patch may only create or edit its output_paths (${[...outputs].join(', ')}). The patch also touches: ${outside.slice(0,10).join(', ')}.${outside.map(file=>outputDirectoryHint(file,outputs)).find(Boolean)||''} Nothing was applied. This affects only this action on ${requestId}.`);
|
|
538
|
+
// Submit proves output_paths are absent at the pinned revision; this proves it again for an assignment that skipped submit.
|
|
539
|
+
const existing=patchPaths(patch).filter(file=>existsAtHead(dir,file));
|
|
540
|
+
if(existing.length) throw coded('output_path_exists',`${existing[0]} already exists at the pinned revision, so it is not a new output file. output_paths declare NEW files only. Nothing was applied. This affects only this action on ${requestId}; choose another path.`);
|
|
541
|
+
}
|
|
542
|
+
// A new file under a generated-name directory is build output to diff(), which leaves it out of workspace_result and the finish
|
|
543
|
+
// patch with no error. Refuse it here instead. A tracked file under such a name is not new and is not refused (see restoreOutsideWritable).
|
|
544
|
+
const generatedNew=patchPaths(patch).filter(file=>isGenerated(file)&&!existsAtHead(dir,file));
|
|
545
|
+
if(generatedNew.length) throw coded('generated_path',`${generatedNew[0]} is a new file under a build-output directory. Files under node_modules/.venv/target/__pycache__ are treated as build output and are not included in the patch; choose another path. Nothing was applied. This affects only this action on ${requestId}.`);
|
|
546
|
+
const files=this.store.transaction(()=>{const current=this.store.get(requestId);this.store.assertClaim(requestId,claimId,subject,worker);if(current.status!=='claimed'||current.cancelled_at) throw closedWorkspace(current,requestId,claimId);const changed=applyPatchToTree(dir,patch,scopeOf(a.assignment));this.noteIgnoredWritten(requestId,dir,changed);return changed;});return {files,diff_sha256:this.diff(dir,input.base_sha).sha256}; }
|
|
547
|
+
// Paths a patch wrote that git ignores are outside the candidate source (a check can still run them). They are listed, not refused,
|
|
548
|
+
// and kept beside the workspace (never inside it) until the next receipt carries them.
|
|
549
|
+
ignoredWrittenFile(requestId) { return path.join(worktrees,`${requestId}.ignored-written.json`); }
|
|
550
|
+
noteIgnoredWritten(requestId,dir,files) {
|
|
551
|
+
const r=spawnSync('git',['-C',dir,'check-ignore','-z','--stdin'],{input:files.join('\0'),encoding:'utf8',timeout:10000,maxBuffer:4*1024*1024,env:gitEnv()});
|
|
552
|
+
// check-ignore exits 0 (some ignored), 1 (none) or 128 (error). An error is recorded, never read as "none ignored".
|
|
553
|
+
const failed=r.status!==0&&r.status!==1;
|
|
554
|
+
const ignored=r.status===0?r.stdout.split('\0').filter(Boolean):[];
|
|
555
|
+
if(!ignored.length&&!failed) return;
|
|
556
|
+
const before=this.readIgnoredWritten(requestId);
|
|
557
|
+
fs.writeFileSync(this.ignoredWrittenFile(requestId),JSON.stringify({paths:[...new Set([...before.paths,...ignored])].sort(),unavailable:failed?`git_check_ignore_failed: ${String(r.stderr||r.error?.message||'').split('\n')[0].slice(0,160)}`:before.unavailable}),{mode:0o600});
|
|
558
|
+
}
|
|
559
|
+
readIgnoredWritten(requestId) { try{const v=JSON.parse(fs.readFileSync(this.ignoredWrittenFile(requestId),'utf8'));return Array.isArray(v)?{paths:v,unavailable:null}:{paths:v.paths??[],unavailable:v.unavailable??null};}catch{return {paths:[],unavailable:null};} }
|
|
560
|
+
retention(requestId) {return new Date(Date.now()+14*86400000).toISOString();}
|
|
561
|
+
// Single-flight: an hourly tick during a long run gets the in-flight promise instead of a second sweep.
|
|
562
|
+
cleanupExpired({log=entry=>console.error(JSON.stringify(entry))}={}) { return this.cleanupRun??=this.sweepExpired(log).finally(()=>{this.cleanupRun=null;}); }
|
|
563
|
+
async freeBytes() { const s=await fs.promises.statfs(root); return Number(s.bavail)*Number(s.bsize); }
|
|
564
|
+
activeNpmCacheKeys() {
|
|
565
|
+
const keys=new Set();
|
|
566
|
+
const assignmentById=this.store.db.prepare('SELECT payload,target_worker FROM assignments WHERE request_id=?');
|
|
567
|
+
for(const id of this.activeChecks) { const row=assignmentById.get(id),key=npmCacheKey(row?.target_worker,payloadRepo(row?.payload)); if(key) keys.add(key); }
|
|
568
|
+
return keys;
|
|
569
|
+
}
|
|
570
|
+
// Shared worker/repo npm stores are regenerable. Drop each one with no running check, always under pressure, otherwise after 7 idle days.
|
|
571
|
+
// The idle test and the rename are one sync step, so a check starting later makes a fresh store instead of using one being deleted.
|
|
572
|
+
async sweepSharedCaches(all) {
|
|
573
|
+
let names,removed=0;try{names=await fs.promises.readdir(sharedNpm);}catch{return 0;}
|
|
574
|
+
for(const name of names) {
|
|
575
|
+
await yieldLoop();
|
|
576
|
+
const dir=path.join(sharedNpm,name);let idleMs;
|
|
577
|
+
try{idleMs=Date.now()-fs.statSync(dir).mtimeMs;}catch{continue;}
|
|
578
|
+
if(this.activeNpmCacheKeys().has(name)||!all&&!name.includes('.evicting-')&&idleMs<IDLE_CACHE_MS) continue;
|
|
579
|
+
try{await evictDir(dir);removed++;}catch(error){console.error(`shared cache cleanup failed for ${dir}: ${error.message}`);}
|
|
580
|
+
}
|
|
581
|
+
return removed;
|
|
582
|
+
}
|
|
583
|
+
// A bare mirror goes when no active assignment or live workspace uses it and it was unused for 7 days, or the disk is low
|
|
584
|
+
// (oldest first, until space is back). The clock starts when the first sweep sees a mirror without a marker.
|
|
585
|
+
async sweepMirrors(pressure,minFree) {
|
|
586
|
+
const db=this.store.db,inUse=new Set();
|
|
587
|
+
for(const row of db.prepare("SELECT request_id,payload,target_worker FROM assignments WHERE status IN ('queued','claimed')").all()) { try{inUse.add(mirrorPath(payloadRepo(row.payload),{worker:row.target_worker||'dot'}));}catch{} }
|
|
588
|
+
for(const row of db.prepare('SELECT request_id,path FROM workspaces').all()) { const common=savedWorkspaceMirror(row.path,row.request_id);if(common) inUse.add(common); }
|
|
589
|
+
const found=[];
|
|
590
|
+
const visit=async dir=>{
|
|
591
|
+
if(path.basename(dir).includes('.evicting-')) { await removeCache(dir);return; }
|
|
592
|
+
let entries;try{entries=await fs.promises.readdir(dir,{withFileTypes:true});}catch{return;}
|
|
593
|
+
if(path.basename(dir).endsWith('.git')&&entries.some(entry=>entry.name==='HEAD')) {
|
|
594
|
+
const marker=path.join(dir,'dot-last-used');let used;
|
|
595
|
+
try{used=fs.statSync(marker).mtimeMs;}catch{touch(marker);return;}
|
|
596
|
+
found.push({dir,used});
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
for(const entry of entries) if(entry.isDirectory()) await visit(path.join(dir,entry.name));
|
|
600
|
+
};
|
|
601
|
+
await visit(mirrors);
|
|
602
|
+
let removed=0;
|
|
603
|
+
for(const {dir,used} of found.sort((x,y)=>x.used-y.used)) {
|
|
604
|
+
await yieldLoop();
|
|
605
|
+
if(inUse.has(dir)) continue;
|
|
606
|
+
const stale=Date.now()-used>=MIRROR_IDLE_MS;
|
|
607
|
+
if(!stale) { if(!pressure) continue; if(!(pressure=await this.freeBytes()<minFree)) break; }
|
|
608
|
+
try{await evictDir(dir);removed++;}catch(error){console.error(`mirror cleanup failed for ${dir}: ${error.message}`);}
|
|
609
|
+
}
|
|
610
|
+
return removed;
|
|
611
|
+
}
|
|
612
|
+
// A per-assignment cache whose assignment is not queued or claimed (terminal, or its workspace row already gone) serves nothing.
|
|
613
|
+
async sweepOrphanCaches() {
|
|
614
|
+
let names;try{names=await fs.promises.readdir(caches);}catch{return 0;}
|
|
615
|
+
const live=this.store.db.prepare("SELECT 1 FROM assignments WHERE request_id=? AND status IN ('queued','claimed')");
|
|
616
|
+
let removed=0;
|
|
617
|
+
for(const name of names) {
|
|
618
|
+
await yieldLoop();
|
|
619
|
+
if(name==='shared'||name.startsWith('check-metadata-')||this.activeChecks.has(name)||live.get(name)) continue;
|
|
620
|
+
const dir=path.join(caches,name);
|
|
621
|
+
try{await removeCache(dir);if(!fs.existsSync(dir)) removed++;}catch(error){console.error(`cache cleanup failed for ${dir}: ${error.message}`);}
|
|
622
|
+
}
|
|
623
|
+
return removed;
|
|
624
|
+
}
|
|
625
|
+
// Called before a tool call that may create a workspace: if the disk is below the floor, free space first instead of waiting for the hourly sweep.
|
|
626
|
+
async makeRoom(requestId) {
|
|
627
|
+
if(this.store.db.prepare('SELECT 1 FROM workspaces WHERE request_id=?').get(requestId)) return;
|
|
628
|
+
if(await this.freeBytes()>=minFreeBytes()) return;
|
|
629
|
+
await this.cleanupExpired();
|
|
630
|
+
}
|
|
631
|
+
async sweepExpired(log) {
|
|
632
|
+
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;
|
|
633
|
+
const failed=(entry,error)=>{summary.errors++;log({kind:'artifact_cleanup_error',...entry,reason:error.message});};
|
|
634
|
+
const expiredArtifact=db.prepare('SELECT id,path FROM artifacts WHERE id=? AND retention_until IS NOT NULL AND retention_until<=?');
|
|
635
|
+
const artifactIds=db.prepare('SELECT id FROM artifacts WHERE retention_until IS NOT NULL AND retention_until<=?').all(now).map(row=>row.id);
|
|
636
|
+
for(let i=0;i<artifactIds.length;i++) {
|
|
637
|
+
if(i%100===0) await yieldLoop();
|
|
638
|
+
const row=expiredArtifact.get(artifactIds[i],now); if(!row) continue;
|
|
639
|
+
try{await fs.promises.unlink(row.path);}catch(e){if(e.code!=='ENOENT'){failed({artifact_id:row.id},e);continue;}}
|
|
640
|
+
db.prepare('DELETE FROM artifacts WHERE id=?').run(row.id);summary.artifacts_removed++;
|
|
641
|
+
}
|
|
642
|
+
const terminal=`SELECT w.request_id,w.path,a.payload,a.status,a.cancelled_at,r.created_at finished_at,
|
|
643
|
+
w.fetched_at
|
|
644
|
+
FROM workspaces w JOIN assignments a USING(request_id) LEFT JOIN reports r USING(request_id)
|
|
645
|
+
WHERE a.status IN ('finished','cancelled')`;
|
|
646
|
+
const current=db.prepare(`${terminal} AND w.request_id=?`);
|
|
647
|
+
const terminalTime=row=>Date.parse(row.status==='cancelled'?row.cancelled_at:row.finished_at)||0;
|
|
648
|
+
// Below the free-space floor, retention no longer protects terminal workspaces: drop idle shared caches, then evict oldest first until above it.
|
|
649
|
+
const minFree=minFreeBytes();
|
|
650
|
+
let pressure=await this.freeBytes()<minFree;
|
|
651
|
+
if(pressure) { summary.pressure=true;summary.shared_caches_removed=await this.sweepSharedCaches(true);pressure=await this.freeBytes()<minFree; }
|
|
652
|
+
const rows=db.prepare(terminal).all().sort((x,y)=>terminalTime(x)-terminalTime(y));
|
|
653
|
+
for(const {request_id:requestId} of rows) {
|
|
654
|
+
await yieldLoop();
|
|
655
|
+
// State can change across awaits: re-read the row and the active checks right before acting.
|
|
656
|
+
const idle=()=>{const row=current.get(requestId);return row&&!this.activeChecks.has(requestId)?row:null;};
|
|
657
|
+
let row=idle(); if(!row) continue;
|
|
658
|
+
let mirror=savedWorkspaceMirror(row.path,requestId);if(!mirror) continue;
|
|
659
|
+
try {
|
|
660
|
+
// A finished assignment cannot be claimed again; its patch and report remain in artifacts. Retaining each checkout for
|
|
661
|
+
// 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.
|
|
662
|
+
const terminalAt=terminalTime(row);
|
|
663
|
+
const expired=terminalAt&&terminalAt+WORKSPACE_RETENTION_MS<=Date.now();
|
|
664
|
+
// The dependency cache serves only a claimed assignment's checks. Remove it as soon as the assignment is terminal,
|
|
665
|
+
// even when the checkout remains available for the owner to fetch its result.
|
|
666
|
+
const cache=path.join(caches,row.request_id);if(fs.existsSync(cache)) { await removeCache(cache);if(!fs.existsSync(cache)) summary.caches_removed++; }
|
|
667
|
+
if(!expired&&!row.fetched_at) { if(!pressure) continue; if(!(pressure=await this.freeBytes()<minFree)) continue; if(!(row=idle())) continue; }
|
|
668
|
+
if(row.path!==path.join(worktrees,row.request_id)) throw Object.assign(new Error('workspace cleanup path mismatch'),{request_id:requestId,summary});
|
|
669
|
+
if(fs.existsSync(row.path)) await gitAsync(['-C',mirror,'worktree','remove','--force',row.path]);
|
|
670
|
+
db.prepare('DELETE FROM workspaces WHERE request_id=?').run(row.request_id);fs.rmSync(this.ignoredWrittenFile(row.request_id),{force:true});summary.workspaces_removed++;
|
|
671
|
+
} catch(error) { if(error.summary) throw error;failed({request_id:requestId},error); }
|
|
672
|
+
}
|
|
673
|
+
summary.caches_removed+=await this.sweepOrphanCaches();
|
|
674
|
+
if(!pressure) summary.shared_caches_removed+=await this.sweepSharedCaches(false);
|
|
675
|
+
summary.mirrors_removed=await this.sweepMirrors(pressure,minFree);
|
|
676
|
+
return summary;
|
|
677
|
+
}
|
|
678
|
+
saveArtifact(requestId,claimId,kind,bytes,id=`art_${randomUUID()}`) {
|
|
679
|
+
const rollback=[];
|
|
680
|
+
try { return this.store.transaction(()=>this.saveArtifactInTransaction(requestId,claimId,kind,bytes,id,cleanup=>rollback.push(cleanup))); }
|
|
681
|
+
catch(error) { for(const cleanup of rollback) cleanup();throw error; }
|
|
682
|
+
}
|
|
683
|
+
saveArtifactInTransaction(requestId,claimId,kind,bytes,id,onRollback) {
|
|
684
|
+
if(!this.store.db.isTransaction||typeof onRollback!=='function') throw new Error('artifact requires caller transaction and rollback cleanup');
|
|
685
|
+
if(kind==='owner-report') bytes=ownerReportArtifactBytes(bytes);
|
|
686
|
+
else if(kind!=='patch') bytes=Buffer.from(redactSecrets(bytes.toString('utf8')).text);
|
|
687
|
+
if(!/^art_[a-zA-Z0-9_-]{8,128}$/.test(id)) throw new Error('invalid artifact id');
|
|
688
|
+
const grant=this.store.db.prepare('SELECT subject,worker FROM claims WHERE request_id=? AND claim_id=?').get(requestId,claimId);
|
|
689
|
+
if(!grant) throw new Error('invalid claim');
|
|
690
|
+
this.store.assertClaim(requestId,claimId,grant.subject,grant.worker);
|
|
691
|
+
const current=this.store.get(requestId);
|
|
692
|
+
if(current.status!=='claimed'||current.cancelled_at) throw closedWorkspace(current,requestId,claimId);
|
|
693
|
+
const file=path.join(artifacts,id),fd=fs.openSync(file,'wx',0o600);
|
|
694
|
+
onRollback(()=>fs.rmSync(file,{force:true}));
|
|
695
|
+
try {fs.writeFileSync(fd,bytes);} finally {fs.closeSync(fd);}
|
|
696
|
+
this.store.db.prepare('INSERT INTO artifacts(id,request_id,claim_id,kind,path,size,sha256,sealed,created_at,retention_until,origin_claim_id,origin_epoch) VALUES(?,?,?,?,?,?,?,?,?,?,?,(SELECT epoch FROM claims WHERE request_id=?))')
|
|
697
|
+
.run(id,requestId,claimId,kind,file,bytes.length,sha(bytes),1,new Date().toISOString(),this.retention(requestId),claimId,requestId);
|
|
698
|
+
return {artifact_id:id,size:bytes.length,sha256:sha(bytes),kind};
|
|
699
|
+
}
|
|
700
|
+
availableChecksFor(assignment,worker='dot') {
|
|
701
|
+
const input=assignmentInput(assignment),mirror=fs.existsSync(mirrorPath(input.github_repo,{worker}))?mirrorPath(input.github_repo,{worker}):prepareGithubRepo(input,{worker});
|
|
702
|
+
return withCheckMetadata(mirror,input.base_sha,dir=>availableChecks(input.github_repo,dir));
|
|
703
|
+
}
|
|
704
|
+
// Catalog data is response enrichment; keep it from discarding a committed claim or finish snapshot.
|
|
705
|
+
// run_check uses the strict reader, so an invalid host check definition still cannot run.
|
|
706
|
+
availableChecksResponse(assignment,dir=null,execution='host',worker='dot') {
|
|
707
|
+
try {
|
|
708
|
+
const repo=assignment.inputs[0].github_repo;
|
|
709
|
+
const declared=dir?availableChecks(repo,dir):this.availableChecksFor(assignment,worker);
|
|
710
|
+
if(execution!=='host') return {available_checks:declared};
|
|
711
|
+
const baseRefusal=hostCheckRefusal(assignment);
|
|
712
|
+
const readiness=hostReadiness();
|
|
713
|
+
const candidates=baseRefusal||!readiness.ready?[]:declared.filter(id=>!hostCheckRefusal(assignment,repo,id));
|
|
714
|
+
const reason=baseRefusal||(!readiness.ready?readiness.reason:null)||(!candidates.length?'host_check_not_allowlisted: no permitted owner-configured check is runnable':null);
|
|
715
|
+
return {available_checks:candidates,host_execution_available:candidates.length>0,host_execution_unavailable_reason:reason};
|
|
716
|
+
} catch(error) {
|
|
717
|
+
if(!String(error?.message??'').includes('check metadata')) throw error;
|
|
718
|
+
if(execution==='host'&&assignment.execution_scope!=='implementation') throw error;
|
|
719
|
+
return {available_checks:[],available_checks_error:'invalid check metadata',...(execution==='host'?{host_execution_available:false,host_execution_unavailable_reason:'invalid check metadata'}:{})};
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
checkMetadataFor(assignment,worker='dot') {
|
|
723
|
+
const input=assignmentInput(assignment),mirror=fs.existsSync(mirrorPath(input.github_repo,{worker}))?mirrorPath(input.github_repo,{worker}):prepareGithubRepo(input,{worker});
|
|
724
|
+
return checkSpecsAt(input.github_repo,mirror,input.base_sha);
|
|
725
|
+
}
|
|
726
|
+
// What the bridge itself observed about one host check, and nothing more. The receipt identifies the candidate source: git's view of
|
|
727
|
+
// the workspace (tracked files plus untracked files that are not ignored) for the install input, the check input and the tree after
|
|
728
|
+
// the run, the diff against base, the changed paths and the definition source. `not_identified` states what it does not identify.
|
|
729
|
+
buildEvidence({input,spec,origin,baseSpec,backend,baseTree,installInput,checkInput,candidateInput,inputDiff,inputDiffError,changed,installChanged,mutatedPaths,post,rawPost,postDiff,postDiffError,receipt,phase,output,outputTruncated,stops,detailArtifact,workerIgnored,evidenceMs,detailTruncated,blocker,restoredPaths=[],restoreError=null,writeScope='unrestricted',masked={paths:[],policyError:null}}) {
|
|
730
|
+
const inputSnap=checkInput||installInput||candidateInput,diffPaths=changed??inputDiff?.paths??[];
|
|
731
|
+
const differs=inputSnap.sha256&&baseTree?inputSnap.sha256!==baseTree:diffPaths.length>0?true:'unknown';
|
|
732
|
+
const mutated=inputSnap.sha256&&(rawPost??post).sha256?inputSnap.sha256!==(rawPost??post).sha256:null;
|
|
733
|
+
const source=origin.from==='owner_config'?'owner_config':baseSpec&&JSON.stringify(baseSpec)===JSON.stringify(spec)?'base':'modified';
|
|
734
|
+
const omissionsIn=inputDiff?.omissions??[],omissionsPost=postDiff?.omissions??[];
|
|
735
|
+
const unverified=Object.entries(stops||{}).filter(([,x])=>!x?.verified).map(([phaseName,x])=>`${phaseName} (${x?.reason??'no stop record'})`);
|
|
736
|
+
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,
|
|
737
|
+
input_patch_sha256:input.input_patch?sha(input.input_patch):null,
|
|
738
|
+
phase,input_phase:checkInput?'check':installInput?'install':'not_started',...(blocker?{blocker}:{}),
|
|
739
|
+
input_tree_sha256:inputSnap.sha256,...(inputSnap.reason?{input_tree_unavailable:inputSnap.reason}:{}),
|
|
740
|
+
install_input_tree_sha256:installInput?.sha256??null,
|
|
741
|
+
...(installInput&&checkInput?{check_input_differs_from_install_input:installInput.sha256&&checkInput.sha256?installInput.sha256!==checkInput.sha256:'unknown',install_changed_paths:preview(installChanged,PREVIEW_SHOWN)}:{}),
|
|
742
|
+
input_diff_sha256:inputDiff?.sha256??null,...(inputDiffError?{input_diff_error:inputDiffError}:{}),
|
|
743
|
+
candidate_differs_from_base:differs,changed_paths:preview(diffPaths,CHANGED_PATHS_SHOWN),
|
|
744
|
+
diff_omissions:preview(omissionsIn,CHANGED_PATHS_SHOWN),
|
|
745
|
+
definition:{check_id:spec.id,source,sha256:sha(JSON.stringify(spec)),base_sha256:baseSpec?sha(JSON.stringify(baseSpec)):null},
|
|
746
|
+
argv:spec.argv,test_paths:declaredOrNamedTestPaths(spec),install_argv:spec.install_argv,timeout_ms:spec.timeout_ms,backend:{name:backend.name,version:backend.version,capabilities:backend.capabilities},
|
|
747
|
+
exit_code:receipt.exit.code,timed_out:receipt.timedOut,cancelled:receipt.cancelled,
|
|
748
|
+
output_sha256:sha(output),output_bytes:output.length,output_truncated:outputTruncated,sandbox_stop:stops,
|
|
749
|
+
post_run_tree_sha256:post.sha256,...(rawPost&&rawPost.sha256!==post.sha256?{post_run_tree_before_restore_sha256:rawPost.sha256}:{}),write_scope:writeScope,restored_out_of_scope_paths:preview(restoredPaths,PREVIEW_SHOWN),...(restoreError?{scope_restore_error:restoreError}:{}),masked_sensitive_paths:preview(masked.paths,PREVIEW_SHOWN),...(masked.policyError?{masked_sensitive_paths_policy_error:masked.policyError}:{}),sandbox_source_exemptions:(masked.sourceExemptions||[]).map(({path,blob_sha})=>({path,blob_sha})),...(post.reason?{post_run_tree_unavailable:post.reason}:{}),tree_mutated_by_check:mutated,tree_mutated_paths:preview(mutatedPaths,PREVIEW_SHOWN),
|
|
750
|
+
post_run_diff_sha256:postDiff?.sha256??null,...(postDiffError?{post_run_diff_error:postDiffError}:{}),post_run_diff_omissions:preview(omissionsPost,CHANGED_PATHS_SHOWN),
|
|
751
|
+
claims:{trusted_bridge_execution:phase==='not_started'?'No phase launch was observed.':`The bridge observed the command launch, the runtime versions, backend, capabilities, exit code, timeout and output digest. ${unverified.length?`Stop NOT verified: ${unverified.join('; ')}.`:'Stop verified for every phase.'}`,source_observation:'git\'s view of the workspace at phase boundaries. It is not proof of the executed bytes and not an immutable snapshot.'},
|
|
752
|
+
source_observation:inputSnap.sha256&&post.sha256&&(!installInput||checkInput)?'observed':'unavailable',
|
|
753
|
+
evidence_ms:evidenceMs,detail_artifact_id:detailArtifact?.artifact_id??null,...(detailTruncated?{detail_artifact_truncated:detailTruncated}:{}),worker_written_ignored_paths:preview(workerIgnored?.paths??[],PREVIEW_SHOWN),...(workerIgnored?.unavailable?{worker_written_ignored_paths_unavailable:workerIgnored.unavailable}:{}),runtime:runtimeVersions(),not_identified:NOT_IDENTIFIED};
|
|
754
|
+
const short=h=>h?h.slice(0,12):'unavailable';
|
|
755
|
+
evidence.observed=[
|
|
756
|
+
phase==='not_started'?'No phase was observed to start; the phase was not started or its launch receipt was lost.':`The bridge ran ${JSON.stringify(phase==='install'?spec.install_argv:spec.argv)} (phase ${phase}) confined by ${backend.name} v${backend.version}. The candidate source at the start of that phase had git tree ${short(inputSnap.sha256)}${inputSnap.reason?` (unavailable: ${inputSnap.reason})`:''} and a diff against base ${short(input.base_sha)} with digest ${short(inputDiff?.sha256)}.`,
|
|
757
|
+
installInput&&checkInput?(evidence.check_input_differs_from_install_input===true?`The install phase changed the candidate source before the check ran: ${installChanged?.slice(0,10).join(', ')}.`:evidence.check_input_differs_from_install_input===false?'The install phase left the candidate source unchanged.':''):'',
|
|
758
|
+
`The envelope ended with exit code ${receipt.exit.code}${receipt.timedOut?' after the time limit':''}${receipt.cancelled?' after a cancel':''}. The output has sha256 ${short(evidence.output_sha256)}${outputTruncated?' and was cut at the output cap':''}.`,
|
|
759
|
+
`The check definition (sha256 ${short(evidence.definition.sha256)}) came from ${source==='base'?'the base commit and is unchanged':source==='modified'?'the candidate source and differs from the base commit':'the owner configuration'}.`,
|
|
760
|
+
masked.outputNote||'',
|
|
761
|
+
differs===true?`The candidate source differs from base${diffPaths.length?` in ${diffPaths.length} path(s): ${diffPaths.slice(0,10).join(', ')}`:''}.`:differs===false?'The candidate source has the same git tree as base.':'Whether the candidate source differs from base is unknown.',
|
|
762
|
+
omissionsIn.length||omissionsPost.length?`${omissionsIn.length+omissionsPost.length} untracked file(s) were left out of the diff${detailArtifact?(detailTruncated?`; artifact ${detailArtifact.artifact_id} holds a partial list`:`; the complete list is in artifact ${detailArtifact.artifact_id}`):''}.`:'',
|
|
763
|
+
mutated?`The command changed the candidate source (git tree after the run ${short((rawPost??post).sha256)}).`:'',
|
|
764
|
+
restoredPaths.length?`The bridge restored ${restoredPaths.length} path(s) outside the job's writable scope (${writeScope==='output_paths'?'output_paths':'scope_paths and output_paths'}) to their pre-run state: ${restoredPaths.slice(0,10).join(', ')}.`:'',
|
|
765
|
+
restoreError?`Restoring paths outside the writable scope reported: ${restoreError}. workspace_result and finish refuse (scope_violation) while such paths remain changed; the job is then stuck and the owner must cancel and resubmit it.`:'',
|
|
766
|
+
masked.paths.length?`${masked.paths.length} sensitive path(s) were masked (read as empty, not writable) inside the sandbox: ${masked.paths.slice(0,10).join(', ')}. A check that needs one of them fails.`:'',
|
|
767
|
+
`Not identified: ${NOT_IDENTIFIED}`,
|
|
768
|
+
'This record states only what the bridge observed. A command or definition label does not show which program the command ran; owner review of the diff stays necessary.'].filter(Boolean).join(' ');
|
|
769
|
+
return evidence;
|
|
770
|
+
}
|
|
771
|
+
async check(requestId,claimId,subject,checkId,worker='dot') {
|
|
772
|
+
const context=this.context(requestId,claimId,subject,true,worker);
|
|
773
|
+
// Execution capability (design section 3): only a host job runs repository code on this host, and never without the executor.
|
|
774
|
+
const execution=this.store.db.prepare('SELECT execution FROM assignments WHERE request_id=?').get(requestId).execution;
|
|
775
|
+
const refuse=reason=>{
|
|
776
|
+
const result=capabilityNotAvailable(execution,reason);
|
|
777
|
+
this.store.transaction(()=>this.store.lifecycle(requestId,'check_skipped',`worker:${subject}`,`check_id=${checkId};${result.reason}`,{claim_id:claimId}));
|
|
778
|
+
return result;
|
|
779
|
+
};
|
|
780
|
+
if(execution!=='host') return refuse();
|
|
781
|
+
// Refuse before resolving worker-controlled check metadata or launching either phase.
|
|
782
|
+
const inputForPolicy=assignmentInput(context.a.assignment);
|
|
783
|
+
const refusal=hostCheckRefusal(context.a.assignment,inputForPolicy.github_repo,checkId);
|
|
784
|
+
if(refusal) return refuse(refusal);
|
|
785
|
+
const readiness=hostReadiness();
|
|
786
|
+
if(!readiness.ready) return refuse(`host_execution (${readiness.reason})`);
|
|
787
|
+
if(this.activeChecks.has(requestId)) {
|
|
788
|
+
const row=this.store.db.prepare("SELECT * FROM check_jobs WHERE request_id=? AND status='running' ORDER BY started_at DESC LIMIT 1").get(requestId);
|
|
789
|
+
const workspace=this.store.db.prepare('SELECT path,base_sha FROM workspaces WHERE request_id=?').get(requestId);
|
|
790
|
+
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'};
|
|
791
|
+
throw new Error('check already running');
|
|
792
|
+
}
|
|
793
|
+
const {dir,input,claim,a}=this.ensure(requestId,claimId,subject,false,worker),origin=detectCheckWithOrigin(input.github_repo,dir,checkId),spec=origin?.spec;
|
|
794
|
+
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)}; }
|
|
795
|
+
let currentAvailable;
|
|
796
|
+
try { currentAvailable=availableChecks(input.github_repo,dir); }
|
|
797
|
+
catch { return refuse('host_check_metadata_unavailable: current check metadata cannot be read'); }
|
|
798
|
+
if(!currentAvailable.includes(checkId)) return refuse('host_check_not_available: this check is not in the current metadata catalog');
|
|
799
|
+
const ownerAuthorization=hostCheckAuthorization(input.github_repo,checkId,spec);
|
|
800
|
+
if(origin.from!=='owner_config'||ownerAuthorization.refusal) return refuse(ownerAuthorization.refusal||'host_check_owner_definition_required: this check has no current owner-configured definition');
|
|
801
|
+
// 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.
|
|
802
|
+
const missingTestPath=missingDeclaredTestPath(dir,spec,origin);
|
|
803
|
+
if(missingTestPath) {
|
|
804
|
+
const error=`check_test_path_missing: ${missingTestPath}`;
|
|
805
|
+
this.store.transaction(()=>this.store.lifecycle(requestId,'check_failed','system',`check_id=${checkId};blocker=${error}`,{claim_id:claimId}));
|
|
806
|
+
return {check_id:checkId,status:'failed',blocker:'check_test_path_missing',error,test_paths:spec.test_paths};
|
|
807
|
+
}
|
|
808
|
+
// The same definition resolved from the base commit alone: equal means the candidate did not change what the check is.
|
|
809
|
+
let baseSpec=null;
|
|
810
|
+
try{baseSpec=withCheckMetadata(savedWorkspaceMirror(dir,requestId),input.base_sha,base=>detectCheck(input.github_repo,base,checkId));}catch{}
|
|
811
|
+
// The owner definition and budget authorize execution. A repository edit
|
|
812
|
+
// may lower that budget, but cannot replace the owner command or raise any limit.
|
|
813
|
+
let authorizedBudget,candidateBudget;
|
|
814
|
+
try {
|
|
815
|
+
authorizedBudget=parseHostBudget(ownerAuthorization.spec.host_budget);
|
|
816
|
+
const candidateSpec=workspaceCheck(input.github_repo,dir,checkId);
|
|
817
|
+
candidateBudget=candidateSpec?.host_budget?parseHostBudget(candidateSpec.host_budget):authorizedBudget;
|
|
818
|
+
} catch{return capabilityNotAvailable(execution,'host_budget_missing: declare a valid host_budget in owner configuration');}
|
|
819
|
+
const jobBudget=Object.fromEntries(Object.entries(authorizedBudget).map(([key,value])=>[key,Math.min(value,candidateBudget[key])]));
|
|
820
|
+
const checkRunId=`check_${randomUUID()}`;
|
|
821
|
+
// A diff that git cannot produce (an unreadable path) is recorded as unavailable; the check still runs and its row is kept.
|
|
822
|
+
let preDiff=null,preDiffError=null;try{preDiff=this.diff(dir,input.base_sha);}catch(error){preDiffError=error.message;}
|
|
823
|
+
const diffSha=preDiff?.sha256??'unavailable';
|
|
824
|
+
let baseTree=null;try{baseTree=git(['-C',dir,'rev-parse','--verify',`${input.base_sha}^{tree}`]).trim();}catch{}
|
|
825
|
+
const commonDir=resolveFrom(dir,git(['-C',dir,'rev-parse','--git-common-dir']).trim());
|
|
826
|
+
this.store.transaction(()=>{
|
|
827
|
+
this.store.db.prepare('INSERT INTO check_jobs(id,request_id,claim_id,check_id,diff_sha256,status,started_at,stop_evidence) VALUES(?,?,?,?,?,?,?,?)').run(checkRunId,requestId,claimId,checkId,diffSha,'running',new Date().toISOString(),JSON.stringify({host:{verified:false,receipt_protocol:1,reason:'durable_host_admission_pending'}}));
|
|
828
|
+
this.store.lifecycle(requestId,'check_started',`worker:${subject}`,`check_id=${checkId};check_run_id=${checkRunId}`,{claim_id:claimId});
|
|
829
|
+
});
|
|
830
|
+
// From here every mutation (apply_patch, a second check) is refused until the check ends, so the digest below is of the tree the command starts on.
|
|
831
|
+
this.activeChecks.add(requestId);
|
|
832
|
+
const work=(async()=>{ let scratch=null,hostInvoked=false; try {
|
|
833
|
+
const assertCurrentAuthority=()=>{
|
|
834
|
+
const assignment=this.store.get(requestId),currentClaim=this.store.assertClaim(requestId,claimId,subject,worker);
|
|
835
|
+
if(assignment.status!=='claimed'||assignment.cancelled_at||currentClaim.epoch!==claim.epoch) throw closedWorkspace(assignment,requestId,claimId,claim.epoch,currentClaim.epoch);
|
|
836
|
+
};
|
|
837
|
+
// Observe the host candidate once. The execution copy is private and
|
|
838
|
+
// deliberately not exported back into the host worktree.
|
|
839
|
+
const backend=hostBackend();let evidenceMs=0;
|
|
840
|
+
const timed=async fn=>{const t=Date.now();try{return await fn();}finally{evidenceMs+=Date.now()-t;}};
|
|
841
|
+
fs.mkdirSync(path.join(root,'run'),{recursive:true,mode:0o700});scratch=fs.mkdtempSync(path.join(root,'run','digest-'));
|
|
842
|
+
const firstSnap=await timed(()=>treeDigest(dir,scratch));
|
|
843
|
+
const sourceCopyDir=path.join(scratch,'source-exemptions');fs.mkdirSync(sourceCopyDir,{mode:0o700});
|
|
844
|
+
const masked=sensitiveMasks(dir,input.github_repo,sourceCopyDir);
|
|
845
|
+
// One service reservation and one cumulative envelope cover preparation,
|
|
846
|
+
// install and check. Mutations stay in the private tmpfs execution copy.
|
|
847
|
+
assertCurrentAuthority();
|
|
848
|
+
const launchRefusal=hostCheckRefusal(this.store.get(requestId).assignment,input.github_repo,checkId,spec);
|
|
849
|
+
if(launchRefusal) throw new Error(launchRefusal);
|
|
850
|
+
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:()=>{
|
|
851
|
+
try { assertCurrentAuthority(); return false; } catch { return true; }
|
|
852
|
+
}});
|
|
853
|
+
hostInvoked=!hosted.notStarted;
|
|
854
|
+
this.store.recordSandboxStop(checkRunId,'host',{...(hosted.notStarted?{verified:true,reason:'host_supervisor_not_started'}:hosted.stop),receipt_protocol:1});
|
|
855
|
+
assertCurrentAuthority(); // Discard output if authority expired while the host ran.
|
|
856
|
+
const install=hosted.phases.find(p=>p.name==='install')??null;
|
|
857
|
+
const check=hosted.phases.find(p=>p.name==='check')??null;
|
|
858
|
+
const installInput=install?firstSnap:null;
|
|
859
|
+
const checkInput=check?(install?{sha256:null,reason:'private_execution_copy_after_install'}:firstSnap):null;
|
|
860
|
+
const inputDiff=install?null:preDiff,inputDiffError=install?'private_execution_copy_after_install':preDiffError;
|
|
861
|
+
const blocker=hosted.error?redactSecrets(hosted.error).text:(!hosted.stop.verified?'host_stop_unverified':null);
|
|
862
|
+
if(install) this.store.recordSandboxStop(checkRunId,'install',hosted.stop);
|
|
863
|
+
if(check) this.store.recordSandboxStop(checkRunId,'check',hosted.stop);
|
|
864
|
+
const receipt={...(check||install),exit:hosted.exit,timedOut:hosted.timedOut,cancelled:hosted.cancelled};
|
|
865
|
+
const rawCombined=Buffer.concat([...(install?[Buffer.from('INSTALL\n'),install.bytes]:[]),...(check?[Buffer.from('\nCHECK\n'),check.bytes]:[])]);
|
|
866
|
+
const completedPhase=check||install,failed=completedPhase?.exit.code!==0||completedPhase?.timedOut||completedPhase?.cancelled;
|
|
867
|
+
const maskedNote=failed?maskedOutputNote(masked.paths,rawCombined.toString('utf8')):'';
|
|
868
|
+
const diagnostic=Buffer.from(redactSecrets(maskedNote).text);
|
|
869
|
+
const clean=Buffer.from(redactSecrets(rawCombined.toString('utf8')).text);
|
|
870
|
+
const outputCap=Math.min(spec.output_bytes,hosted.budgets.output_bytes);
|
|
871
|
+
const combined=diagnostic.length?Buffer.concat([clean.subarray(0,Math.max(0,outputCap-diagnostic.length)),diagnostic]):clean;
|
|
872
|
+
const output=combined.subarray(0,outputCap);
|
|
873
|
+
assertCurrentAuthority();
|
|
874
|
+
|
|
875
|
+
// The host worktree did not receive the execution copy's writes. Do not
|
|
876
|
+
// label host hashes as observations of that copy's phase/post-run tree.
|
|
877
|
+
const post={sha256:null,reason:'private_execution_copy_not_exported'},rawPost=null;
|
|
878
|
+
const postDiff=preDiff,postDiffError=preDiffError;
|
|
879
|
+
const checkedDiff=postDiff?.sha256??null,phase=check?'check':install?'install':'not_started',inputSnap=checkInput||installInput||firstSnap;
|
|
880
|
+
let changed=null,installChanged=null,mutatedPaths=null;
|
|
881
|
+
await timed(async()=>{
|
|
882
|
+
changed=await treePathsChanged(dir,scratch,commonDir,baseTree,inputSnap.sha256);
|
|
883
|
+
installChanged=installInput&&checkInput?await treePathsChanged(dir,scratch,commonDir,installInput.sha256,checkInput.sha256):null;
|
|
884
|
+
mutatedPaths=await treePathsChanged(dir,scratch,commonDir,inputSnap.sha256,(rawPost??post).sha256);
|
|
885
|
+
});
|
|
886
|
+
assertCurrentAuthority();
|
|
887
|
+
const artifact=this.saveArtifact(requestId,claimId,'check-output',output);
|
|
888
|
+
const workerIgnored=this.readIgnoredWritten(requestId);
|
|
889
|
+
const restoredPaths=[],evidenceArgs={rawPost,restoredPaths,restoreError:null,writeScope:'private_execution_copy',masked:{...masked,outputNote:maskedNote},input,spec,workerIgnored,origin,baseSpec,backend,baseTree,installInput,checkInput,candidateInput:firstSnap,inputDiff,inputDiffError,changed,installChanged,mutatedPaths,post,postDiff,postDiffError,receipt,phase,output,stops:{...(install?{install:install.stop}:{}),...(check?{check:check.stop}:{})},outputTruncated:rawCombined.length+diagnostic.length>outputCap||hosted.truncated,evidenceMs,blocker};
|
|
890
|
+
const detail=boundedDetail({changed_paths:changed??inputDiff?.paths??[],input_diff_omissions:inputDiff?.omissions??[],post_run_diff_omissions:postDiff?.omissions??[],install_changed_paths:installChanged??[],tree_mutated_paths:mutatedPaths??[],restored_out_of_scope_paths:restoredPaths,masked_sensitive_paths:masked.paths});
|
|
891
|
+
const detailArtifact=detail?this.saveArtifact(requestId,claimId,'check-evidence-detail',detail):null;
|
|
892
|
+
const detailParsed=detail?JSON.parse(detail.toString('utf8')):null,detailTruncated=detailParsed&&!detailParsed.complete?detailParsed.truncated:null;
|
|
893
|
+
const evidence=redactOutput(this.buildEvidence({...evidenceArgs,detailArtifact,detailTruncated}));
|
|
894
|
+
evidence.host_budget={dependencies:hosted.dependencies,limits:hosted.budgets,usage:hosted.usage,usage_complete:hosted.usage_complete,error:blocker,stop:hosted.stop};
|
|
895
|
+
evidence.execution_storage='private_tmpfs_copy_not_exported';
|
|
896
|
+
evidence.claims.source_observation='Host candidate observed before copying. Install/check mutations in the private execution copy are not exported or hashed by this receipt.';
|
|
897
|
+
evidence.observed+=' Execution used a private tmpfs copy; phase and post-run hashes of that copy are unavailable.';
|
|
898
|
+
const result={id:checkRunId,check_run_id:checkRunId,status:blocker?'failed':'completed',...(blocker?{blocker,error:blocker}:{}),request_id:requestId,claim_id:claimId,check_id:checkId,test_paths:evidence.test_paths,
|
|
899
|
+
phase,exit_code:receipt.exit.code,timed_out:receipt.timedOut,cancelled:receipt.cancelled,output_artifact_id:artifact.artifact_id,
|
|
900
|
+
output_sha256:artifact.sha256,diff_sha256:checkedDiff??diffSha,output_preview:previewHeadTail(redactSecrets(output.toString('utf8')).text),duration_ms:hosted.duration_ms,evidence_ms:evidenceMs,trust:evidence.trust,evidence};
|
|
901
|
+
const saved=this.recordCheckResult(result,rawCombined,checkedDiff);
|
|
902
|
+
this.reconcileHostStops(requestId);
|
|
903
|
+
return saved;
|
|
904
|
+
} catch(error) {
|
|
905
|
+
if(error.hostInvoked) hostInvoked=true;
|
|
906
|
+
if(!hostInvoked) this.store.recordSandboxStop(checkRunId,'host',{verified:true,reason:'host_not_started',receipt_protocol:1});
|
|
907
|
+
this.store.transaction(()=>{
|
|
908
|
+
this.store.db.prepare("UPDATE check_jobs SET status='failed',error=?,finished_at=? WHERE id=?").run(error.message,new Date().toISOString(),checkRunId);
|
|
909
|
+
this.store.lifecycle(requestId,'check_failed','system',checkOutcome({id:checkRunId,check_id:checkId,status:'failed'})[1],{claim_id:claimId});
|
|
910
|
+
});
|
|
911
|
+
this.reconcileHostStops(requestId);
|
|
912
|
+
return {check_run_id:checkRunId,status:'failed',error:error.message};
|
|
913
|
+
} finally {if(scratch) fs.rmSync(scratch,{recursive:true,force:true});this.activeChecks.delete(requestId);this.checkEffects.delete(requestId);} })();
|
|
914
|
+
this.checkEffects.set(requestId,work);
|
|
915
|
+
return checkResponse(work,{check_run_id:checkRunId,status:'running'},this.checkResponseOptions);
|
|
916
|
+
}
|
|
917
|
+
// Classify original output before redacting metadata and storing the row atomically;
|
|
918
|
+
// preview truncation must not discard skipped-segment metadata.
|
|
919
|
+
recordCheckResult(result,output,checkedDiff=result.diff_sha256) {
|
|
920
|
+
const saved=redactOutput(withCheckCoverage(result,output.toString('utf8')));
|
|
921
|
+
this.store.transaction(()=>{
|
|
922
|
+
const grant=this.store.db.prepare('SELECT subject,worker FROM claims WHERE request_id=? AND claim_id=?').get(saved.request_id,saved.claim_id);if(!grant) throw new Error('invalid claim');this.store.assertClaim(saved.request_id,saved.claim_id,grant.subject,grant.worker);const current=this.store.get(saved.request_id);if(current.status!=='claimed'||current.cancelled_at) throw closedWorkspace(current,saved.request_id,saved.claim_id);
|
|
923
|
+
this.store.db.prepare('INSERT INTO check_runs(id,request_id,claim_id,check_id,exit_code,timed_out,output_artifact_id,output_sha256,duration_ms,created_at,diff_sha256,phase,evidence) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)')
|
|
924
|
+
.run(saved.id,saved.request_id,saved.claim_id,saved.check_id,saved.exit_code,Number(saved.timed_out),saved.output_artifact_id,saved.output_sha256,saved.duration_ms,new Date().toISOString(),checkedDiff,saved.phase,JSON.stringify(saved.evidence));
|
|
925
|
+
this.store.db.prepare('UPDATE check_jobs SET status=?,error=?,output_preview=?,finished_at=? WHERE id=?')
|
|
926
|
+
.run(saved.status,saved.blocker??null,saved.output_preview,new Date().toISOString(),saved.id);
|
|
927
|
+
const [type,reason]=saved.blocker?['check_failed',`check_id=${saved.check_id};check_run_id=${saved.id};blocker=${saved.blocker}${saved.check_summary?';'+saved.check_summary:''}`]:checkOutcome(saved,saved);
|
|
928
|
+
this.store.lifecycle(saved.request_id,type,'system',reason,{claim_id:saved.claim_id});
|
|
929
|
+
});
|
|
930
|
+
return saved;
|
|
931
|
+
}
|
|
932
|
+
async runConfined(requestId,dir,command,spec,{cancelled,checkRunId,repo=null,checkId=null,expectedSpec=null}={}) {
|
|
933
|
+
// Policy is rechecked at the only launch boundary; repository metadata
|
|
934
|
+
// cannot opt the operator in or bypass the whole-repository read grant.
|
|
935
|
+
const refusal=hostCheckRefusal(this.store.get(requestId).assignment,repo,checkId,expectedSpec);
|
|
936
|
+
if(refusal) throw new Error(refusal);
|
|
937
|
+
const budgets=parseHostBudget(spec.host_budget);
|
|
938
|
+
budgets.wall_ms=Math.min(budgets.wall_ms,spec.timeout_ms??budgets.wall_ms);
|
|
939
|
+
budgets.output_bytes=Math.min(budgets.output_bytes,spec.output_bytes??budgets.output_bytes);
|
|
940
|
+
return runHostBudget({dir,budgets,...(checkRunId?{checkRunId,receiptDir:path.join(root,'host-receipts')}:{}),maskPaths:spec.maskPaths,sourceExemptions:spec.sourceExemptions,
|
|
941
|
+
phases:[...(spec.install_argv?[{name:'install',argv:spec.install_argv}]:[]),{name:'check',argv:command}],
|
|
942
|
+
cancelled:cancelled??(()=>this.store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(requestId)?.status!=='claimed')});
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// The files a diff of this assignment may carry: null (all) for implementation, the output_paths for read-only.
|
|
946
|
+
diffFilter(assignment) { return assignment.execution_scope!=='implementation'&&outputsOf(assignment).size?outputsOf(assignment):null; }
|
|
947
|
+
// The scope an implementation diff must stay inside (null: unrestricted, a read-only job, which diffFilter handles, or a review: its worktree is the PR head, so its diff against base is the PR's files).
|
|
948
|
+
diffScope(request) { return request.assignment.execution_scope==='implementation'&&!request.review?scopeOf(request.assignment):null; }
|
|
949
|
+
result(requestId,claimId,subject,worker='dot') {
|
|
950
|
+
if(!this.store.mayAct(worker,requestId)) throw new Error('assignment not found');
|
|
951
|
+
const a=this.store.get(requestId);this.store.assertClaim(requestId,claimId,subject,worker);
|
|
952
|
+
if(a.status!=='claimed'||a.cancelled_at) throw closedWorkspace(a,requestId,claimId);
|
|
953
|
+
const artifacts=this.store.db.prepare("SELECT COALESCE(client_artifact_id,id) id,size,sha256 FROM artifacts WHERE request_id=? AND claim_id=? AND kind='upload' AND sealed=1").all(requestId,claimId);
|
|
954
|
+
if(!a.assignment.inputs?.some(input=>input.github_repo)) return {checks:[],artifacts:artifacts};
|
|
955
|
+
const {dir,input}=this.ensure(requestId,claimId,subject,true,worker);
|
|
956
|
+
// A diff git cannot produce (an unreadable path) is reported as unavailable instead of failing the whole result.
|
|
957
|
+
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:[]};}
|
|
958
|
+
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}));
|
|
959
|
+
let display=redactSecrets(diff.patch).text;
|
|
960
|
+
if(/^GIT binary patch$/m.test(diff.patch)) display='[binary diff withheld; owner patch required]';
|
|
961
|
+
if(diff.patch) {
|
|
962
|
+
// Ordinary hunks may start inside a PEM body. Inspect complete tracked context
|
|
963
|
+
// before displaying any hunk; the owner-only patch and its digest stay intact.
|
|
964
|
+
try {
|
|
965
|
+
const full=git(['-C',dir,'diff','--no-ext-diff','--no-textconv','--unified=2147483647',this.diffFilter(a.assignment)?'HEAD':input.base_sha]);
|
|
966
|
+
if(privateKeyHeader.test(full)) display='[redacted secret: diff contains private key material; owner patch required]';
|
|
967
|
+
} catch { display='[diff preview unavailable: complete secret scan failed]'; }
|
|
968
|
+
}
|
|
969
|
+
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});
|
|
970
|
+
}
|
|
971
|
+
snapshot(requestId,claimId,subject,worker='dot') {
|
|
972
|
+
const rollback=[];
|
|
973
|
+
try {return this.store.transaction(()=>this.snapshotInTransaction(requestId,claimId,subject,worker,cleanup=>rollback.push(cleanup)));}
|
|
974
|
+
catch(error) {for(const cleanup of rollback)cleanup();throw error;}
|
|
975
|
+
}
|
|
976
|
+
snapshotInTransaction(requestId,claimId,subject,worker,onRollback) {
|
|
977
|
+
if(!this.store.db.isTransaction)throw new Error('snapshot requires a caller-owned transaction');
|
|
978
|
+
if(this.activeChecks.has(requestId))throw new Error('check still running');
|
|
979
|
+
const row=this.store.db.prepare('SELECT * FROM workspaces WHERE request_id=?').get(requestId);
|
|
980
|
+
if(!row)return null;
|
|
981
|
+
const result=this.result(requestId,claimId,subject,worker),request=this.store.get(requestId);
|
|
982
|
+
const diff=this.diff(row.path,result.base_sha,this.diffFilter(request.assignment),this.diffScope(request));
|
|
983
|
+
const patch=this.saveArtifactInTransaction(requestId,claimId,'patch',Buffer.from(diff.patch),`art_${randomUUID()}`,onRollback);
|
|
984
|
+
return {...result,artifacts:this.store.sealedUploads(requestId),patch_artifact:patch};
|
|
985
|
+
}
|
|
986
|
+
chunk(requestId,claimId,subject,id,offset,base64,final=false,expected,worker='dot',onMutation=null) {
|
|
987
|
+
return this.store.transaction(()=>this.chunkInTransaction(requestId,claimId,subject,id,offset,base64,final,expected,worker,onMutation));
|
|
988
|
+
}
|
|
989
|
+
chunkInTransaction(requestId,claimId,subject,id,offset,base64,final=false,expected,worker='dot',onMutation=null) {
|
|
990
|
+
if(!this.store.db.isTransaction) throw new Error('chunk requires a caller-owned transaction');
|
|
991
|
+
if(onMutation!==null&&typeof onMutation!=='function') throw new Error('invalid native upload callback');
|
|
992
|
+
if(!this.store.mayAct(worker,requestId)) throw new Error('assignment not found');
|
|
993
|
+
const a=this.store.get(requestId);this.store.assertClaim(requestId,claimId,subject,worker);
|
|
994
|
+
if(a.status!=='claimed'||a.cancelled_at) throw closedWorkspace(a,requestId,claimId);
|
|
995
|
+
if(typeof id!=='string'||!/^art_[a-zA-Z0-9_-]{8,128}$/.test(id)) throw new Error('invalid artifact_id: must match art_ followed by 8 to 128 letters, digits, _ or -');
|
|
996
|
+
if(!Number.isInteger(offset)||offset<0) throw new Error('invalid offset: must be a whole number, 0 or more, equal to the bytes stored so far');
|
|
997
|
+
if(typeof base64!=='string') throw new Error('invalid data_base64: must be a string (an empty string is allowed)');
|
|
998
|
+
if(!/^([A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(base64)) throw new Error('invalid data_base64: must be standard padded base64 (A-Z a-z 0-9 + /) without line breaks or white space');
|
|
999
|
+
const bytes=Buffer.from(base64,'base64');
|
|
1000
|
+
if(bytes.length>65536) throw new Error('chunk too large');
|
|
1001
|
+
const current=this.store.get(requestId);this.store.assertClaim(requestId,claimId,subject,worker);if(current.status!=='claimed'||current.cancelled_at) throw closedWorkspace(current,requestId,claimId);
|
|
1002
|
+
let row=this.store.db.prepare("SELECT * FROM artifacts WHERE request_id=? AND COALESCE(client_artifact_id,id)=? AND kind='upload'").get(requestId,id);
|
|
1003
|
+
const previous=row?{...row}:null;
|
|
1004
|
+
const publishMutation=duplicate=>{
|
|
1005
|
+
if(!onMutation) return;
|
|
1006
|
+
const native=this.store.db.prepare('SELECT * FROM artifacts WHERE id=?').get(row.id);
|
|
1007
|
+
const actual=fs.readFileSync(native.path);
|
|
1008
|
+
if(actual.length!==native.size) throw new Error('artifact integrity failure');
|
|
1009
|
+
const result=onMutation({row:native,duplicate,offset,chunkSize:bytes.length,chunkSha256:sha(actual.subarray(offset,offset+bytes.length)),size:actual.length,sha256:sha(actual),reference:native.id});
|
|
1010
|
+
if(result&&typeof result.then==='function') throw new Error('async native upload callback forbidden');
|
|
1011
|
+
};
|
|
1012
|
+
if(row&&row.claim_id!==claimId) throw new Error('artifact binding mismatch');
|
|
1013
|
+
if(!row) {
|
|
1014
|
+
if(offset!==0) throw new Error('wrong upload offset');
|
|
1015
|
+
const globalId='art_'+sha(Buffer.from(JSON.stringify([requestId,claimId,id]))).slice(0,48);
|
|
1016
|
+
if(this.store.db.prepare('SELECT 1 FROM artifacts WHERE id=?').get(globalId)) throw new Error('artifact id collision');
|
|
1017
|
+
const file=path.join(artifacts,globalId);
|
|
1018
|
+
this.store.db.prepare('INSERT INTO artifacts(id,request_id,claim_id,kind,path,size,sealed,created_at,retention_until,client_artifact_id,origin_claim_id,origin_epoch) VALUES(?,?,?,?,?,?,0,?,?,?,?,(SELECT epoch FROM claims WHERE request_id=?))')
|
|
1019
|
+
.run(globalId,requestId,claimId,'upload',file,0,new Date().toISOString(),this.retention(requestId),id,claimId,requestId);
|
|
1020
|
+
row=this.store.db.prepare('SELECT * FROM artifacts WHERE id=?').get(globalId);
|
|
1021
|
+
}
|
|
1022
|
+
if(!fs.existsSync(row.path)) {
|
|
1023
|
+
if(row.size!==0) throw new Error('upload file missing');
|
|
1024
|
+
fs.writeFileSync(row.path,Buffer.alloc(0),{flag:'wx',mode:0o600});
|
|
1025
|
+
}
|
|
1026
|
+
const readAt=position=>{const previous=Buffer.alloc(bytes.length),fd=fs.openSync(row.path,'r');try{fs.readSync(fd,previous,0,bytes.length,position);}finally{fs.closeSync(fd);}return previous;};
|
|
1027
|
+
if(row.sealed) {
|
|
1028
|
+
if(final&&typeof expected==='string'&&expected.toLowerCase()===row.sha256&&offset+bytes.length===row.size&&readAt(offset).equals(bytes)) {publishMutation(true);return {artifact_id:id,offset:row.size,sealed:true,sha256:row.sha256};}
|
|
1029
|
+
throw new Error('artifact sealed');
|
|
1030
|
+
}
|
|
1031
|
+
const actual=fs.statSync(row.path).size;
|
|
1032
|
+
if(actual<row.size) throw new Error('upload file truncated');
|
|
1033
|
+
if(actual>row.size) {
|
|
1034
|
+
const partial=actual-row.size;
|
|
1035
|
+
if(row.size+bytes.length>8*1024*1024) throw new Error('artifact too large');
|
|
1036
|
+
if(offset!==row.size||partial>bytes.length||!readAt(offset).subarray(0,partial).equals(bytes.subarray(0,partial))) throw new Error('interrupted upload differs; operator repair required');
|
|
1037
|
+
if(partial<bytes.length) {const fd=fs.openSync(row.path,'a');try{let written=partial;while(written<bytes.length)written+=fs.writeSync(fd,bytes,written,bytes.length-written);fs.fsyncSync(fd);}finally{fs.closeSync(fd);}}
|
|
1038
|
+
this.store.db.prepare('UPDATE artifacts SET size=? WHERE id=?').run(row.size+bytes.length,row.id);
|
|
1039
|
+
} else if(offset<row.size) {
|
|
1040
|
+
if(offset+bytes.length>row.size||!readAt(offset).equals(bytes)) throw new Error('conflicting chunk retry');
|
|
1041
|
+
} else if(offset===row.size) {
|
|
1042
|
+
if(row.size+bytes.length>8*1024*1024) throw new Error('artifact too large');
|
|
1043
|
+
const fd=fs.openSync(row.path,'a');try{let written=0;while(written<bytes.length)written+=fs.writeSync(fd,bytes,written,bytes.length-written);fs.fsyncSync(fd);}finally{fs.closeSync(fd);}
|
|
1044
|
+
this.store.db.prepare('UPDATE artifacts SET size=? WHERE id=?').run(row.size+bytes.length,row.id);
|
|
1045
|
+
} else throw new Error('wrong upload offset');
|
|
1046
|
+
const size=fs.statSync(row.path).size;
|
|
1047
|
+
if(final) {
|
|
1048
|
+
if(typeof expected!=='string'||!expected) throw new Error('final chunk needs sha256: the 64 hex digits of the whole file');
|
|
1049
|
+
expected=expected.toLowerCase();
|
|
1050
|
+
const digest=sha(fs.readFileSync(row.path));
|
|
1051
|
+
if(digest!==expected) throw new Error('artifact digest mismatch');
|
|
1052
|
+
this.store.db.prepare('UPDATE artifacts SET sha256=?,sealed=1 WHERE id=?').run(digest,row.id);
|
|
1053
|
+
}
|
|
1054
|
+
publishMutation(!!previous&&previous.size===size&&!!previous.sealed===final);
|
|
1055
|
+
return {artifact_id:id,offset:size,sealed:final,sha256:final?expected:null};
|
|
1056
|
+
}
|
|
1057
|
+
artifact(id,requestId) { this.store.assertProtocolAvailable(requestId);const row=this.store.db.prepare('SELECT * FROM artifacts WHERE id=? AND request_id=? AND sealed=1').get(id,requestId);if(!row) throw new Error('artifact not found');const bytes=fs.readFileSync(row.path);if(bytes.length!==row.size||sha(bytes)!==row.sha256) throw new Error('artifact integrity failure');return {row,bytes}; }
|
|
1058
|
+
}
|