@tnunamak/dalan 0.8.0 → 0.8.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 +70 -1
- package/CONTRIBUTING.md +2 -0
- package/PROTOCOL.md +6 -0
- package/README.md +8 -12
- package/bin/dalan.mjs +25 -4
- package/bin/dot-acp-agent.mjs +572 -76
- package/bin/dot-alert.mjs +9 -3
- package/bin/dot-deadman.mjs +3 -1
- package/bin/dot-heartbeat.mjs +14 -7
- package/bin/dot-pr-reviewer.mjs +3 -31
- package/bin/dot-worker.mjs +215 -40
- package/contracts/adapter-qualification.schema.json +94 -7
- package/docs/chatgpt-worker-onboarding.md +1 -1
- package/docs/codex-to-muse.md +2 -2
- package/docs/connect-chatgpt.md +1 -1
- package/docs/connection-longevity.md +2 -2
- package/docs/dalan-upgrade.md +8 -5
- package/docs/deadman.md +4 -0
- package/docs/design/authority-matrix.md +18 -0
- package/docs/design/failure-table.md +87 -0
- package/docs/design/identities.md +22 -0
- package/docs/design/pnpm-prepared-dependencies.md +64 -0
- package/docs/design/reuse-ledger.md +75 -0
- package/docs/design/target-architecture-v2.md +434 -0
- package/docs/local-agent-mcp.md +14 -0
- package/docs/local-agent-requester.md +3 -2
- package/docs/manual-setup.md +1 -1
- package/docs/operations.md +78 -14
- package/docs/pull-workers.md +11 -0
- package/docs/relationships.md +13 -0
- package/docs/service-setup.md +10 -10
- package/docs/t3-integration.md +6 -2
- package/docs/t3-reverse-control.md +5 -5
- package/docs/t3-wake-fence-r4.md +1 -1
- package/docs/test-suite-isolation.md +8 -6
- package/docs/trials/chatgpt-agent.md +47 -0
- package/docs/trials/claude-code-requester.md +68 -0
- package/docs/trials/muse.md +46 -0
- package/docs/usage.md +35 -9
- package/docs/worker-clients.md +1 -1
- package/integrations/t3/acp-kit/src/errors.mjs +6 -2
- package/integrations/t3/acp-kit/src/lock.mjs +46 -17
- package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
- package/package.json +4 -3
- package/packages/job-core/protocol/canonical.mjs +45 -7
- package/packages/job-core/transitions.mjs +4 -2
- package/scripts/upgrade-drain.mjs +96 -8
- package/scripts/worker-bridge-setup.mjs +215 -120
- package/src/ack-ledger.mjs +7 -1
- package/src/acp-bridge.mjs +256 -28
- package/src/admin-socket.mjs +32 -3
- package/src/alerts.mjs +17 -8
- package/src/answer-journal-retention.mjs +82 -0
- package/src/answer-journal.mjs +6 -4
- package/src/as-store.mjs +51 -6
- package/src/as.mjs +27 -5
- package/src/catalog-switch-inventory.mjs +70 -0
- package/src/check-response.mjs +4 -1
- package/src/claim-command-ledger.mjs +3 -2
- package/src/cli-help.mjs +29 -10
- package/src/cli-name.mjs +13 -1
- package/src/connect-cli.mjs +159 -4
- package/src/deadman.mjs +8 -5
- package/src/delivery.mjs +2 -19
- package/src/destinations/index.mjs +75 -14
- package/src/drain-runner.mjs +5 -1
- package/src/follow-current.mjs +3 -1
- package/src/get-summary.mjs +11 -2
- package/src/git-env.mjs +1 -1
- package/src/gozar-routes.mjs +313 -94
- package/src/host-budget-storage.py +56 -6
- package/src/host-budget.mjs +98 -15
- package/src/host-execution-policy.mjs +17 -6
- package/src/inbox.mjs +13 -3
- package/src/legacy-names.mjs +0 -2
- package/src/lifecycle.mjs +104 -11
- package/src/loopback-probe.mjs +46 -0
- package/src/mcp-outcome.mjs +3 -1
- package/src/mcp-sse.mjs +2 -1
- package/src/mcp-stdio.mjs +192 -30
- package/src/patch-apply.mjs +285 -19
- package/src/phase-trace.mjs +73 -0
- package/src/prepared-go-modules.mjs +127 -0
- package/src/prepared-node-modules.mjs +225 -38
- package/src/prepared-pnpm.mjs +276 -0
- package/src/prepared-store-prune.mjs +52 -0
- package/src/projects.mjs +59 -7
- package/src/protocol-artifact-commands.mjs +28 -0
- package/src/protocol-finish.mjs +3 -2
- package/src/publication-authority.mjs +22 -0
- package/src/publish-plan.mjs +2 -2
- package/src/pull-queue.mjs +55 -20
- package/src/read-api.mjs +127 -0
- package/src/redaction.mjs +173 -0
- package/src/rejections.mjs +19 -3
- package/src/route-custody.mjs +90 -0
- package/src/route-publication.mjs +50 -0
- package/src/route-setup.mjs +184 -0
- package/src/schema-subset.mjs +5 -3
- package/src/server.mjs +619 -88
- package/src/service-launchd.mjs +5 -1
- package/src/service-update-lock.mjs +7 -4
- package/src/service-update-runtime.mjs +64 -19
- package/src/service-update.mjs +193 -48
- package/src/service.mjs +276 -77
- package/src/setup.mjs +48 -25
- package/src/signal.mjs +1 -1
- package/src/status-evidence.mjs +18 -5
- package/src/status-summary.mjs +3 -0
- package/src/store.mjs +1086 -127
- package/src/submission-policy.mjs +257 -56
- package/src/t3-control.mjs +1 -1
- package/src/t3.mjs +14 -8
- package/src/terminal-safe.mjs +9 -7
- package/src/tool-registry.mjs +134 -41
- package/src/try-exposure.mjs +53 -86
- package/src/try-hosted.mjs +257 -70
- package/src/try.mjs +48 -22
- package/src/work-order.mjs +11 -6
- package/src/worker-instructions.mjs +26 -4
- package/src/worker-runs.mjs +35 -0
- package/src/workers.mjs +49 -4
- package/src/workspace.mjs +354 -54
- package/systemd/dot-deadman.service +3 -1
- package/docs/dot-pr-reviewer.config.example.json +0 -9
- package/docs/pr-head-reviewer.md +0 -70
- package/src/pr-head-reviewer.mjs +0 -596
- package/systemd/dot-pr-reviewer.service +0 -11
- package/systemd/dot-pr-reviewer.timer +0 -10
package/src/patch-apply.mjs
CHANGED
|
@@ -2,13 +2,249 @@
|
|
|
2
2
|
// adapter's read-only check. Nothing here talks to the bridge.
|
|
3
3
|
import { spawnSync } from 'node:child_process';
|
|
4
4
|
import { createHash } from 'node:crypto';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import { workGrantProblem } from './publication-authority.mjs';
|
|
9
|
+
import { writableScope } from './workspace.mjs';
|
|
5
10
|
|
|
6
|
-
const git = (dir, args, input, env) => spawnSync('git', ['-C', dir, ...args], { input, encoding
|
|
11
|
+
const git = (dir, args, input, env, encoding = "utf8") => spawnSync((env ?? process.env).DALAN_GIT || 'git', ['-C', dir, ...args], { input, encoding, maxBuffer: 64 * 1024 * 1024, env });
|
|
12
|
+
|
|
13
|
+
const materializeName = '[A-Za-z0-9][A-Za-z0-9_.-]*';
|
|
14
|
+
const materializeRepo = new RegExp('^' + materializeName + '/' + materializeName + '$');
|
|
15
|
+
const materializeEntry = new RegExp('^(?:org:' + materializeName + '|repo:' + materializeName + '/' + materializeName + ')$');
|
|
16
|
+
const grantError = (local_code, message) => Object.assign(new Error(local_code + ': ' + message), {local_code});
|
|
17
|
+
|
|
18
|
+
export function readMaterializeGrant(file) {
|
|
19
|
+
let fd;
|
|
20
|
+
try {
|
|
21
|
+
fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
22
|
+
} catch (error) {
|
|
23
|
+
if (error.code === 'ENOENT') return null;
|
|
24
|
+
throw grantError('materialize_grant_unsafe', 'cannot safely open the owner grant file');
|
|
25
|
+
}
|
|
26
|
+
try {
|
|
27
|
+
const state = fs.fstatSync(fd);
|
|
28
|
+
if (!state.isFile() || typeof process.getuid !== 'function' || state.uid !== process.getuid() || (state.mode & 0o7777) !== 0o600) {
|
|
29
|
+
throw grantError('materialize_grant_unsafe', 'the owner grant must be a regular owner-owned mode 0600 file');
|
|
30
|
+
}
|
|
31
|
+
let parsed;
|
|
32
|
+
try {
|
|
33
|
+
if (state.size > 16 * 1024) throw new Error('too large');
|
|
34
|
+
parsed = JSON.parse(fs.readFileSync(fd, 'utf8'));
|
|
35
|
+
} catch {
|
|
36
|
+
throw grantError('materialize_grant_invalid', 'expected a small JSON grant document');
|
|
37
|
+
}
|
|
38
|
+
if (!parsed || typeof parsed !== 'object' || Object.keys(parsed).length !== 2 ||
|
|
39
|
+
!['standing', 'per_pr'].includes(parsed.mode) || !Array.isArray(parsed.grant) ||
|
|
40
|
+
!parsed.grant.every(entry => typeof entry === 'string' && materializeEntry.test(entry))) {
|
|
41
|
+
throw grantError('materialize_grant_invalid', 'expected mode standing or per_pr and exact org: or repo: entries');
|
|
42
|
+
}
|
|
43
|
+
return parsed;
|
|
44
|
+
} finally { fs.closeSync(fd); }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function materializeDecision(grant, repo, requestId, authority) {
|
|
48
|
+
if (typeof repo !== 'string' || !materializeRepo.test(repo) || !/^[-\w]{8,128}$/.test(requestId)) {
|
|
49
|
+
throw grantError('materialize_result_invalid', 'expected one exact repository and a valid request ID');
|
|
50
|
+
}
|
|
51
|
+
const [org] = repo.toLowerCase().split('/');
|
|
52
|
+
const installed = !!grant?.grant.some(entry => ['org:' + org, 'repo:' + repo.toLowerCase()].includes(entry.toLowerCase()));
|
|
53
|
+
// The install file may only narrow what the work's own grant allows; it cannot stand in for it.
|
|
54
|
+
const workProblem = installed ? workGrantProblem(authority, repo) : null;
|
|
55
|
+
const eligible = installed && !workProblem;
|
|
56
|
+
const push = eligible && grant.mode === 'standing';
|
|
57
|
+
const needs_approval = eligible && grant.mode === 'per_pr';
|
|
58
|
+
return { push, draft_pr: push, needs_approval, branch: 'dalan/' + requestId,
|
|
59
|
+
reason: push ? 'standing_grant' : needs_approval ? 'per_pr_approval_required' : workProblem ?? 'no_standing_grant' };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
// Shared owner-side publication path. Approval and formatting belong to the caller.
|
|
64
|
+
export async function materialize({id, got, dir, grantFile, download, recheck,
|
|
65
|
+
dryRun=false, approve=false, standingOnly=false, fetchBase=false}) {
|
|
66
|
+
const grant=readMaterializeGrant(grantFile);
|
|
67
|
+
if(got.status!=='finished'||got.revised_by) throw new Error('materialize needs a current, finished result');
|
|
68
|
+
const ev=got.report?.workspace_evidence, art=ev?.patch_artifact, inputs=got.assignment?.inputs;
|
|
69
|
+
if(!Array.isArray(inputs)||inputs.length!==1||!art?.artifact_id||!art.size||!/^[a-f0-9]{64}$/.test(art.sha256??'')) {
|
|
70
|
+
throw new Error('materialize needs one repository and a sealed patch');
|
|
71
|
+
}
|
|
72
|
+
const repo=inputs[0].github_repo, base_sha=ev.base_sha??inputs[0].base_sha;
|
|
73
|
+
if(!/^[a-f0-9]{40}$/.test(base_sha??'')) throw new Error('materialize needs a pinned base commit');
|
|
74
|
+
const decision=materializeDecision(grant,repo,id,got.publication_authority);
|
|
75
|
+
const result={request_id:id,repo,base_sha,files:[],decision,published:false,branch:decision.branch,reason:decision.reason};
|
|
76
|
+
if(standingOnly && !decision.push) return result;
|
|
77
|
+
const temp=fs.mkdtempSync(path.join(os.tmpdir(),'dalan-materialize-'));
|
|
78
|
+
try {
|
|
79
|
+
const body=Buffer.from(await download(art));
|
|
80
|
+
if(createHash('sha256').update(body).digest('hex')!==art.sha256||body.length!==art.size) throw new Error('materialize patch does not match the report');
|
|
81
|
+
result.files=listPatchFiles(temp,body);
|
|
82
|
+
// The patch may touch only what the work was allowed to change. Anything else is kept as a patch and never pushed.
|
|
83
|
+
const inScope=got.assignment?.execution_scope?writableScope(got.assignment):null;
|
|
84
|
+
const outside=inScope?result.files.filter(file=>!inScope(file)):[];
|
|
85
|
+
if(outside.length) {
|
|
86
|
+
result.decision={...decision,push:false,draft_pr:false,needs_approval:false,reason:'patch_outside_scope',outside_scope:outside};
|
|
87
|
+
result.reason='patch_outside_scope';
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
if(!dryRun && (decision.push || decision.needs_approval && approve)) {
|
|
91
|
+
const title=String(got.assignment?.title ?? 'Dalan patch '+id).split(/\r?\n/,1)[0].trim().slice(0,240) || 'Dalan patch '+id;
|
|
92
|
+
const summary=String(got.report?.summary ?? 'Patch for Dalan assignment '+id+'.').slice(0,30000);
|
|
93
|
+
Object.assign(result,await materializePatch({dir,temp,body,sha256:art.sha256,baseSha:base_sha,
|
|
94
|
+
repo,branch:decision.branch,title,summary,fetchBase,recheck:async(phase='push')=>{
|
|
95
|
+
const current=await recheck();
|
|
96
|
+
const after=phase==='pr' ? 'the branch was pushed, so it exists, but no draft pull request was opened' : 'nothing pushed';
|
|
97
|
+
if(current.status!=='finished'||current.revised_by||current.report?.workspace_evidence?.patch_artifact?.sha256!==art.sha256) {
|
|
98
|
+
throw new Error('materialize result changed before publication; '+after);
|
|
99
|
+
}
|
|
100
|
+
const currentDecision=materializeDecision(readMaterializeGrant(grantFile),repo,id,current.publication_authority);
|
|
101
|
+
if(!currentDecision.push && !(currentDecision.needs_approval && approve)) {
|
|
102
|
+
throw new Error('materialize authority changed before publication ('+currentDecision.reason+'); '+after);
|
|
103
|
+
}
|
|
104
|
+
}}));
|
|
105
|
+
}
|
|
106
|
+
result.published=!!result.pr_url;
|
|
107
|
+
return result;
|
|
108
|
+
} finally { fs.rmSync(temp,{recursive:true,force:true}); }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Only a matching GitHub push URL is eligible. Match the exact path, not a substring
|
|
112
|
+
// or an arbitrary remote helper. Do not use an implicit push refspec or default remote.
|
|
113
|
+
function githubPushRepo(url) {
|
|
114
|
+
const ssh = /^git@github\.com:([a-z0-9_.-]+\/[a-z0-9_.-]+)$/i.exec(url);
|
|
115
|
+
const absolute = /^(?:https:\/\/github\.com|ssh:\/\/git@github\.com)\/([a-z0-9_.-]+\/[a-z0-9_.-]+)$/i.exec(url);
|
|
116
|
+
return (ssh?.[1] ?? absolute?.[1])?.replace(/\.git$/i, '').toLowerCase();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function materializePatch({dir, temp, body, sha256, baseSha, repo, branch, title, summary, recheck, fetchBase=false}) {
|
|
120
|
+
if(typeof dir!=='string' || !path.isAbsolute(dir)) throw new Error('materialize requires a checkout directory');
|
|
121
|
+
const ref = 'refs/heads/' + branch;
|
|
122
|
+
if (!materializeRepo.test(repo) || !/^dalan\/[-\w]{8,128}$/.test(branch) || !/^[a-f0-9]{40}$/.test(baseSha)) {
|
|
123
|
+
throw new Error('materialize needs a pinned GitHub repo and a scoped branch');
|
|
124
|
+
}
|
|
125
|
+
const run = (program, cwd, args, label) => {
|
|
126
|
+
const r = spawnSync(program, args, {cwd, encoding:'utf8', maxBuffer:1024*1024});
|
|
127
|
+
if(r.error || r.status!==0) throw new Error('materialize: '+label+' failed'+(r.status==null?'':' (exit '+r.status+')'));
|
|
128
|
+
return r.stdout.trim();
|
|
129
|
+
};
|
|
130
|
+
const gitCmd = (cwd, args, label) => run(process.env.DALAN_GIT || 'git',cwd,['-c','core.hooksPath=/dev/null', ...args],label);
|
|
131
|
+
const ghRepo = 'github.com/' + repo;
|
|
132
|
+
const ghCmd = (args, label) => run(process.env.DALAN_GH || 'gh',dir,args,label);
|
|
133
|
+
// Require a real checkout, including when it is a linked worktree.
|
|
134
|
+
gitCmd(dir,['rev-parse','--show-toplevel'],'verify checkout');
|
|
135
|
+
const urls = new Map();
|
|
136
|
+
for(const remote of gitCmd(dir,['remote'],'list remotes').split(/\r?\n/).filter(Boolean)) {
|
|
137
|
+
const values = gitCmd(dir,['remote','get-url','--push','--all','--',remote],'read push URL').split(/\r?\n/);
|
|
138
|
+
if (values.length === 1 && githubPushRepo(values[0]) === repo.toLowerCase()) urls.set(remote,values[0]);
|
|
139
|
+
}
|
|
140
|
+
if (urls.size !== 1) throw new Error('materialize requires one matching GitHub push URL');
|
|
141
|
+
const [[, remote]] = urls;
|
|
142
|
+
if(fetchBase && git(dir,['cat-file','-e',baseSha+'^{commit}']).status!==0) {
|
|
143
|
+
// Fetch only from the already matched push URL, even if the remote's fetch URL differs.
|
|
144
|
+
gitCmd(dir,['fetch','--no-tags',remote,baseSha],'fetch pinned base commit');
|
|
145
|
+
}
|
|
146
|
+
const targetBase = ghCmd(['repo','view',ghRepo,'--json','defaultBranchRef','--jq','.defaultBranchRef.name'],'read repository default branch');
|
|
147
|
+
if(!targetBase || targetBase===branch) throw new Error('materialize cannot target the default branch for a push');
|
|
148
|
+
gitCmd(dir,['check-ref-format','refs/heads/'+targetBase],'verify repository default branch');
|
|
149
|
+
const worktree = path.join(temp,'checkout');
|
|
150
|
+
gitCmd(dir,['worktree','add','--detach',worktree,baseSha],'create detached worktree');
|
|
151
|
+
let failure;
|
|
152
|
+
try {
|
|
153
|
+
applyPatch({dir:worktree, patch:body, sha256, baseSha});
|
|
154
|
+
gitCmd(worktree,['add','-A','--','.'],'stage patch');
|
|
155
|
+
gitCmd(worktree,['commit','--no-gpg-sign','-m','Materialize '+branch],'commit patch with local identity');
|
|
156
|
+
const tip = gitCmd(worktree,['ls-remote','--heads',remote,ref],'inspect scoped remote branch');
|
|
157
|
+
if(tip) {
|
|
158
|
+
const cols=tip.split(/\s+/);
|
|
159
|
+
if(cols.length!==2 || !/^[a-f0-9]{40}$/.test(cols[0]) || cols[1]!==ref) throw new Error('materialize received an invalid remote ref');
|
|
160
|
+
gitCmd(worktree,['fetch','--no-tags','--no-write-fetch-head',remote,cols[0]],'read the existing scoped branch');
|
|
161
|
+
const existing=gitCmd(worktree,['show','-s','--format=%P %T',cols[0]],'read existing branch tree');
|
|
162
|
+
const candidate=gitCmd(worktree,['show','-s','--format=%P %T','HEAD'],'read candidate tree');
|
|
163
|
+
if(existing!==candidate) throw new Error('materialize will not replace the existing branch with different content');
|
|
164
|
+
}
|
|
165
|
+
await recheck('push');
|
|
166
|
+
// Expect absence at the server, even if another publisher races this push.
|
|
167
|
+
if(!tip) gitCmd(worktree,['push','--no-follow-tags','--force-with-lease='+ref+':',remote,'HEAD:'+ref],'create scoped remote branch');
|
|
168
|
+
let pr_url;
|
|
169
|
+
try {
|
|
170
|
+
// The push can finish after the owner changes or withdraws approval.
|
|
171
|
+
await recheck('pr');
|
|
172
|
+
try {
|
|
173
|
+
pr_url=ghCmd(['pr','create','--repo',ghRepo,'--draft','--base',targetBase,'--head',branch,
|
|
174
|
+
'--title',title,'--body',summary],'open draft pull request');
|
|
175
|
+
} catch(error) {
|
|
176
|
+
// A create call can fail after the draft was opened, and a replay can find the draft
|
|
177
|
+
// the first publication opened. Look for it before reporting failure.
|
|
178
|
+
try {
|
|
179
|
+
pr_url=ghCmd(['pr','list','--repo',ghRepo,'--state','open','--base',targetBase,'--head',branch,
|
|
180
|
+
'--json','url,isDraft','--jq','.[] | select(.isDraft) | .url'],'find existing draft pull request');
|
|
181
|
+
} catch { throw error; }
|
|
182
|
+
if(!pr_url) throw error;
|
|
183
|
+
}
|
|
184
|
+
const prefix='https://github.com/'+repo.toLowerCase()+'/pull/';
|
|
185
|
+
if(!pr_url.toLowerCase().startsWith(prefix) || !/^[1-9]\d*$/.test(pr_url.slice(prefix.length))) {
|
|
186
|
+
throw new Error('materialize did not receive the draft pull request URL');
|
|
187
|
+
}
|
|
188
|
+
} catch(error) {
|
|
189
|
+
throw new Error('materialize branch '+branch+' exists; draft pull request not confirmed. '+error.message);
|
|
190
|
+
}
|
|
191
|
+
return {branch,pr_url};
|
|
192
|
+
} catch(error) {
|
|
193
|
+
failure=error;
|
|
194
|
+
throw error;
|
|
195
|
+
} finally {
|
|
196
|
+
try {gitCmd(dir,['worktree','remove','--force',worktree],'remove temporary worktree');}
|
|
197
|
+
catch(error) { if(!failure) throw error; }
|
|
198
|
+
}
|
|
199
|
+
}
|
|
7
200
|
|
|
8
201
|
// git apply from a subdirectory can silently skip root-relative paths.
|
|
9
|
-
function worktreeRoot(dir, env) {
|
|
10
|
-
const root = git(dir, ['rev-parse', '--show-toplevel'], undefined, env);
|
|
11
|
-
return root.status === 0 ? root.stdout.replace(/\r?\n$/, '') : null;
|
|
202
|
+
export function worktreeRoot(dir, env) {
|
|
203
|
+
const root = git(dir, ['rev-parse', '--show-toplevel'], undefined, env, 'buffer');
|
|
204
|
+
return root.status === 0 ? decodePatchPathOutput(root.stdout).replace(/\r?\n$/, '') : null;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// What the patch can touch, read before it runs: each named file's bytes, mode or link target, or its absence, and the
|
|
208
|
+
// directories that do not exist yet (a new file may create them).
|
|
209
|
+
function snapshot(root, files) {
|
|
210
|
+
const entries = [], newDirs = new Set();
|
|
211
|
+
for (const file of new Set(files)) {
|
|
212
|
+
const target = path.join(root, file);
|
|
213
|
+
let stat = null;
|
|
214
|
+
try { stat = fs.lstatSync(target); } catch {}
|
|
215
|
+
if (!stat) {
|
|
216
|
+
entries.push({ target, absent: true });
|
|
217
|
+
for (let parent = path.dirname(target); parent.startsWith(root + path.sep) && !fs.existsSync(parent); parent = path.dirname(parent)) newDirs.add(parent);
|
|
218
|
+
} else if (stat.isSymbolicLink()) entries.push({ target, link: fs.readlinkSync(target) });
|
|
219
|
+
else if (stat.isFile()) entries.push({ target, data: fs.readFileSync(target), mode: stat.mode & 0o7777 });
|
|
220
|
+
else entries.push({ target, opaque: true });
|
|
221
|
+
}
|
|
222
|
+
return { entries, newDirs: [...newDirs].sort((a, b) => b.length - a.length) };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Puts every snapshotted file back. A file that already equals its snapshot is not rewritten, so a read-only directory
|
|
226
|
+
// that stopped the patch does not stop the restore. Returns the names it could not restore.
|
|
227
|
+
function restore(snap) {
|
|
228
|
+
const failed = [];
|
|
229
|
+
for (const entry of snap.entries) {
|
|
230
|
+
try {
|
|
231
|
+
let now = null;
|
|
232
|
+
try { now = fs.lstatSync(entry.target); } catch {}
|
|
233
|
+
if (entry.absent) { if (now) fs.rmSync(entry.target, { recursive: true, force: true }); }
|
|
234
|
+
else if (entry.link !== undefined) {
|
|
235
|
+
if (now?.isSymbolicLink() && fs.readlinkSync(entry.target) === entry.link) continue;
|
|
236
|
+
if (now) fs.rmSync(entry.target, { force: true });
|
|
237
|
+
fs.symlinkSync(entry.link, entry.target);
|
|
238
|
+
} else if (entry.data) {
|
|
239
|
+
if (now?.isFile() && (now.mode & 0o7777) === entry.mode && fs.readFileSync(entry.target).equals(entry.data)) continue;
|
|
240
|
+
if (now) fs.rmSync(entry.target, { force: true });
|
|
241
|
+
fs.mkdirSync(path.dirname(entry.target), { recursive: true });
|
|
242
|
+
fs.writeFileSync(entry.target, entry.data, { mode: entry.mode }); fs.chmodSync(entry.target, entry.mode);
|
|
243
|
+
}
|
|
244
|
+
} catch { failed.push(path.basename(entry.target)); }
|
|
245
|
+
}
|
|
246
|
+
for (const dir of snap.newDirs) { try { fs.rmdirSync(dir); } catch {} }
|
|
247
|
+
return failed;
|
|
12
248
|
}
|
|
13
249
|
|
|
14
250
|
// The patch must apply onto the job's base or a descendant of it, so HEAD has to contain base. Returns null when it does,
|
|
@@ -24,20 +260,18 @@ export function baseProblem(dir, baseSha, env) {
|
|
|
24
260
|
return anc.status === 0 ? null : `could not compare base and HEAD: ${anc.stderr.trim()}`;
|
|
25
261
|
}
|
|
26
262
|
|
|
27
|
-
//
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
const
|
|
37
|
-
if (
|
|
38
|
-
const
|
|
39
|
-
if (numstat.error || numstat.status !== 0) throw new Error(`git apply --numstat failed: ${(numstat.stderr || numstat.error?.message || '').trim().slice(0, 300)}`);
|
|
40
|
-
const records = numstat.stdout.split('\0');
|
|
263
|
+
// Refuse ambiguous byte sequences while inspection is still read-only.
|
|
264
|
+
export function decodePatchPathOutput(bytes) {
|
|
265
|
+
const decoded = bytes.toString('utf8');
|
|
266
|
+
if (!Buffer.from(decoded, 'utf8').equals(bytes)) throw new Error('not applied: patch path inspection is not valid UTF-8');
|
|
267
|
+
return decoded;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// The files a patch names, renames as old and new, read from the patch alone (no check against the tree).
|
|
271
|
+
function patchPaths(dir, body, env, direction) {
|
|
272
|
+
const numstat = git(dir, ['apply', '--numstat', '-z', ...direction, '-'], body, env, 'buffer');
|
|
273
|
+
if (numstat.error || numstat.status !== 0) throw new Error(`git apply --numstat failed: ${(numstat.stderr?.toString('utf8') || numstat.error?.message || '').trim().slice(0, 300)}`);
|
|
274
|
+
const records = decodePatchPathOutput(numstat.stdout).split('\0');
|
|
41
275
|
const files = [];
|
|
42
276
|
for (let index = 0; index < records.length; index++) {
|
|
43
277
|
const record = records[index];
|
|
@@ -53,8 +287,40 @@ export function applyPatch({ dir, patch, sha256, baseSha, env }) {
|
|
|
53
287
|
index += 2;
|
|
54
288
|
}
|
|
55
289
|
}
|
|
290
|
+
return files;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function listPatchFiles(dir, body, env) {
|
|
294
|
+
// Some git apply versions report only the destination in forward numstat.
|
|
295
|
+
// Ask the same parser in reverse too, so rollback captures both endpoints
|
|
296
|
+
// without interpreting a human-readable rename summary or its quoting.
|
|
297
|
+
return [...new Set([...patchPaths(dir, body, env, []), ...patchPaths(dir, body, env, ['--reverse'])])];
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Checks the digest, the base and `git apply --check`, then applies. Preflight failures touch nothing; a failed apply
|
|
301
|
+
// process restores the files it touched (a restore that itself fails is named in the error). Returns the list of touched file names. With checkOnly, it stops after
|
|
302
|
+
// the checks and the file list and writes nothing, so a caller can take an authorization between the check and the write.
|
|
303
|
+
export function applyPatch({ dir, patch, sha256, baseSha, env, checkOnly = false }) {
|
|
304
|
+
const body = Buffer.from(patch);
|
|
305
|
+
if (sha256 && createHash('sha256').update(body).digest('hex') !== sha256) throw new Error('patch sha256 does not match the recorded evidence; not applied');
|
|
306
|
+
const problem = baseProblem(dir, baseSha, env);
|
|
307
|
+
if (problem) throw new Error(`not applied: ${problem}`);
|
|
308
|
+
dir = worktreeRoot(dir, env);
|
|
309
|
+
if (!dir) throw new Error('not applied: could not resolve the repository worktree top level');
|
|
310
|
+
const check = git(dir, ['apply', '--check', '-'], body, env);
|
|
311
|
+
if (check.status !== 0) throw new Error(`not applied: git apply --check failed: ${(check.stderr || '').trim().slice(0, 300)}`);
|
|
312
|
+
const files = listPatchFiles(dir, body, env);
|
|
313
|
+
if (checkOnly) return files;
|
|
314
|
+
// git apply checks everything first but writes file by file, so a write error can leave some files changed. Keep what it
|
|
315
|
+
// may touch and put it back on any failure: the tree is the one it was, or the error names what could not be restored.
|
|
316
|
+
const before = snapshot(dir, files);
|
|
56
317
|
const run = git(dir, ['apply', '-'], body, env);
|
|
57
|
-
if (run.status !== 0)
|
|
318
|
+
if (run.status !== 0) {
|
|
319
|
+
const failed = restore(before), reason = (run.stderr || run.error?.message || '').trim().slice(0, 300);
|
|
320
|
+
throw new Error(failed.length
|
|
321
|
+
? `git apply failed after a clean check, and ${failed.join(', ')} could not be restored; the checkout is partially changed: ${reason}`
|
|
322
|
+
: `git apply failed after a clean check; every touched file was restored to its earlier content: ${reason}`);
|
|
323
|
+
}
|
|
58
324
|
return files;
|
|
59
325
|
}
|
|
60
326
|
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Where the time between "queued" and "claimed" goes, one log line per step (no schema, no behavior change):
|
|
2
|
+
// wake_delivery each wake webhook: queued-to-attempt time and how long the receiver took to answer
|
|
3
|
+
// claim_phase each new claim: the timestamps and gaps from submit to wake, wake to first listing, listing to claim
|
|
4
|
+
// claim_first_action the holder's first call on a fresh claim after the claim itself
|
|
5
|
+
// claim_silence the holder's next call after at least SILENCE_MS without one, and (final:true) its finish, whatever the gap
|
|
6
|
+
// Fresh claims and finish handoffs are told apart by `handoff`: a handoff claim has no wake and no listing of its own.
|
|
7
|
+
// Remembered state is in memory and bounded; a restart forgets it, and the lines then carry nulls, never wrong numbers.
|
|
8
|
+
export const SILENCE_MS=120000;
|
|
9
|
+
const iso=ms=>new Date(ms).toISOString();
|
|
10
|
+
const gap=(from,to)=>from==null||to==null?null:Math.round(to-from);
|
|
11
|
+
export function createPhaseTrace({log:write,now=Date.now,max=5000}) {
|
|
12
|
+
// Telemetry only: a failing log write (full disk, missing directory) must never change a tool result or a wake delivery.
|
|
13
|
+
const log=entry=>{try{write(entry);}catch{}};
|
|
14
|
+
const listed=new Map(),woke=new Map(),fresh=new Map(),active=new Map();
|
|
15
|
+
const remember=(map,key,value)=>{map.set(key,value);while(map.size>max)map.delete(map.keys().next().value);};
|
|
16
|
+
// Measurement only: how long a claim goes quiet between the holder's calls. A claim that ends by cancel or lease expiry
|
|
17
|
+
// makes no call, so its last silence is read offline from the last mcp_outcome line against claim_phase.
|
|
18
|
+
const silence=({requestId,tool,subject})=>{
|
|
19
|
+
const claim=active.get(requestId);
|
|
20
|
+
if(!claim||claim.subject!==subject) return;
|
|
21
|
+
const at=now(),silent=at-claim.last,final=tool==='finish';
|
|
22
|
+
if(silent>=SILENCE_MS||final) log({kind:'claim_silence',request_id:requestId,claim_id:claim.claimId,tool,silence_ms:Math.round(silent),
|
|
23
|
+
since:claim.calls?'previous_call':'claim',final,calls_before:claim.calls,claim_age_ms:Math.round(at-claim.claimedAt)});
|
|
24
|
+
if(final) active.delete(requestId);
|
|
25
|
+
else { claim.last=at;claim.calls++; }
|
|
26
|
+
};
|
|
27
|
+
return {
|
|
28
|
+
// A list_pending call showed these rows: keep the first time each one was seen.
|
|
29
|
+
listed(requestIds) {
|
|
30
|
+
const at=now();
|
|
31
|
+
for(const id of requestIds) if(!listed.has(id)) remember(listed,id,at);
|
|
32
|
+
},
|
|
33
|
+
// One wake webhook attempt. `attemptAt` is when the send began; `ackMs` is how long the receiver took to answer (null on a transport error).
|
|
34
|
+
wake({item,worker,attemptAt,ackMs,status,state}) {
|
|
35
|
+
const created=Date.parse(item.created_at);
|
|
36
|
+
log({kind:'wake_delivery',event_id:item.id,request_id:item.request_id??null,worker,wake_kind:item.wake_kind??null,state,http_status:status??null,
|
|
37
|
+
enqueued_at:item.created_at,attempt_at:iso(attemptAt),queued_to_attempt_ms:gap(created,attemptAt),ack_ms:ackMs==null?null:Math.round(ackMs)});
|
|
38
|
+
if(item.request_id&&state==='delivered'&&!woke.has(item.request_id)) remember(woke,item.request_id,{attemptAt,ackAt:ackMs==null?null:attemptAt+ackMs});
|
|
39
|
+
},
|
|
40
|
+
// A new claim was granted. `createdAt` is the assignment's submit time.
|
|
41
|
+
claimed({requestId,worker,subject,claimId,handoff,createdAt}) {
|
|
42
|
+
// A handoff claim has no wake and no listing of its own: whatever an earlier failed or lapsed attempt left behind is not its timing.
|
|
43
|
+
const at=now(),seen=handoff?null:listed.get(requestId)??null,wake=handoff?null:woke.get(requestId)??null,created=Date.parse(createdAt);
|
|
44
|
+
listed.delete(requestId);woke.delete(requestId);
|
|
45
|
+
// Send, answer and listing are separate stamps. A row listed before the answer came back (or before the send) has no known order: null, never a negative gap.
|
|
46
|
+
const wakeToListed=wake&&wake.ackAt!=null&&seen!=null&&seen>=wake.ackAt?gap(wake.ackAt,seen):null;
|
|
47
|
+
remember(fresh,requestId,{claimId,subject,at,handoff});
|
|
48
|
+
remember(active,requestId,{claimId,subject,claimedAt:at,last:at,calls:0});
|
|
49
|
+
log({kind:'claim_phase',request_id:requestId,worker,claim_id:claimId,handoff,created_at:createdAt,
|
|
50
|
+
wake_attempt_at:wake?iso(wake.attemptAt):null,first_listed_at:seen==null?null:iso(seen),claimed_at:iso(at),
|
|
51
|
+
submit_to_wake_ms:gap(created,wake?.attemptAt),wake_ack_ms:wake&&wake.ackAt!=null?Math.round(wake.ackAt-wake.attemptAt):null,
|
|
52
|
+
wake_to_listed_ms:wakeToListed,listed_to_claim_ms:gap(seen,at),submit_to_claim_ms:gap(created,at)});
|
|
53
|
+
},
|
|
54
|
+
// The server provides a snapshot taken before the successful progress write.
|
|
55
|
+
progress({requestId,claimId,claimedAt,first,note}) {
|
|
56
|
+
if(!first) return;
|
|
57
|
+
const stamp=/^dispatched_at=(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)(?=\s|$)/.exec(note)?.[1];
|
|
58
|
+
const sent=Date.parse(stamp), claimed=Date.parse(claimedAt);
|
|
59
|
+
if(!Number.isFinite(sent)||iso(sent)!==stamp.replace('Z','.000Z')) return;
|
|
60
|
+
const known=Number.isFinite(claimed);
|
|
61
|
+
log({kind:'claim_dispatch',source:'worker_note',request_id:requestId,claim_id:claimId,dispatched_at:stamp,
|
|
62
|
+
claimed_at:known?claimedAt:null,gap_ms:known&&claimed>=sent?gap(sent,claimed):null});
|
|
63
|
+
},
|
|
64
|
+
// Any worker call that names a request. The first one by the claimant after a fresh claim is the first action.
|
|
65
|
+
action({requestId,tool,subject}) {
|
|
66
|
+
silence({requestId,tool,subject});
|
|
67
|
+
const claim=fresh.get(requestId);
|
|
68
|
+
if(!claim||claim.subject!==subject) return;
|
|
69
|
+
fresh.delete(requestId);
|
|
70
|
+
log({kind:'claim_first_action',request_id:requestId,claim_id:claim.claimId,tool,handoff:claim.handoff,after_claim_ms:gap(claim.at,now())});
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { defaultPath } from './paths.mjs';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { spawnSync } from 'node:child_process';
|
|
7
|
+
import { pruneNodeStore } from './prepared-store-prune.mjs';
|
|
8
|
+
import { hash, failure, markUsed, readRegular, checkDirectory, checkParents, validateTree, freezeTree, thawTree, shellQuote, prepareInChild } from './prepared-node-modules.mjs';
|
|
9
|
+
|
|
10
|
+
// A Go repository's dependencies and its pinned toolchain live in one module cache, prepared on the host (with network)
|
|
11
|
+
// from go.mod and go.sum alone, then mounted read-only at the sandbox's GOMODCACHE. The sandbox has no network, so the cache
|
|
12
|
+
// is the only way a check can get the Go toolchain a go.mod asks for (`go 1.26.0` switches to golang.org/toolchain in this cache)
|
|
13
|
+
// and the modules it imports. Same trust rule as prepared node_modules: the key is the file hashes, never the worker's edits.
|
|
14
|
+
const GO = '/usr/bin/go';
|
|
15
|
+
const store = options => path.resolve(options.cacheDir ?? defaultPath(os.homedir(), '.dot-bridge/prepared-go-modules'));
|
|
16
|
+
const recovery = source => `dalan prepare-deps ${shellQuote(path.resolve(source))} --go`;
|
|
17
|
+
let hostGo;
|
|
18
|
+
const hostGoVersion = () => {
|
|
19
|
+
if (hostGo !== undefined) return hostGo;
|
|
20
|
+
const run = spawnSync(GO, ['env', 'GOVERSION'], { env: { PATH: '/usr/bin:/bin', HOME: os.tmpdir(), GOTOOLCHAIN: 'local', GOFLAGS: '' }, encoding: 'utf8', timeout: 20000 });
|
|
21
|
+
hostGo = run.status === 0 ? run.stdout.trim() : null;
|
|
22
|
+
return hostGo;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// Why the host cannot prepare this go.mod (null when it can). A local `replace` or a go.work file points outside go.mod and go.sum.
|
|
26
|
+
export function unsupportedGoModules(goMod) {
|
|
27
|
+
for (const match of String(goMod).matchAll(/=>\s*(\S+)/g)) if (/^(\.|\/)/.test(match[1])) return 'a local replace directive is unsupported';
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
function inputs(source) {
|
|
31
|
+
const root = path.resolve(source);
|
|
32
|
+
if (fs.realpathSync(root) !== root || !fs.lstatSync(root).isDirectory()) throw failure('dependencies_invalid', 'source directory must be canonical');
|
|
33
|
+
const mod = readRegular(path.join(root, 'go.mod'), true);
|
|
34
|
+
if (!mod) return null;
|
|
35
|
+
if (fs.existsSync(path.join(root, 'go.work'))) throw failure('dependencies_unsupported', 'go.work is unsupported');
|
|
36
|
+
const unsupported = unsupportedGoModules(mod.toString('utf8'));
|
|
37
|
+
if (unsupported) throw failure('dependencies_unsupported', unsupported);
|
|
38
|
+
const sum = readRegular(path.join(root, 'go.sum'), true) ?? Buffer.alloc(0);
|
|
39
|
+
const version = hostGoVersion();
|
|
40
|
+
if (!version) throw failure('dependencies_unsupported', `${GO} is unavailable on this host`);
|
|
41
|
+
const runtime = { go: version, platform: process.platform, arch: process.arch };
|
|
42
|
+
const identity = { go_mod_sha256: hash(mod), go_sum_sha256: hash(sum), runtime };
|
|
43
|
+
return { root, mod, sum, identity, name: hash(`${identity.go_mod_sha256}:${identity.go_sum_sha256}`), key: hash(JSON.stringify(runtime)) };
|
|
44
|
+
}
|
|
45
|
+
const entryPath = (base, input) => path.join(base, input.name, input.key);
|
|
46
|
+
function lookup(input, base) {
|
|
47
|
+
const entry = entryPath(base, input);
|
|
48
|
+
try {
|
|
49
|
+
checkParents(base); checkDirectory(base, true); checkDirectory(path.dirname(entry), true); checkDirectory(entry, true);
|
|
50
|
+
const metaPath = path.join(entry, 'metadata.json'), st = fs.lstatSync(metaPath);
|
|
51
|
+
if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o222)) throw new Error('bad metadata');
|
|
52
|
+
const metadata = JSON.parse(readRegular(metaPath));
|
|
53
|
+
if (JSON.stringify(metadata.identity) !== JSON.stringify(input.identity)) throw new Error('identity mismatch');
|
|
54
|
+
const treePath = path.join(entry, 'modcache'); validateTree(treePath);
|
|
55
|
+
markUsed(entry);
|
|
56
|
+
return { treePath, ...input.identity };
|
|
57
|
+
} catch {
|
|
58
|
+
throw failure('dependencies_unprepared', `missing or invalid preparation; owner recovery: ${recovery(input.root)}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
// Keep the newest N entries by last use; the rules (a day's grace, rename then delete an hour later) are those of the node_modules store.
|
|
62
|
+
export const pruneGoStore = (options = {}) => pruneNodeStore({ ...options, base: store(options) });
|
|
63
|
+
export function resolvePreparedGoModules(sourceDir, options = {}) {
|
|
64
|
+
const input = inputs(sourceDir);
|
|
65
|
+
return input ? lookup(input, store(options)) : null;
|
|
66
|
+
}
|
|
67
|
+
// For the offer filter: the reason from go.mod and the presence of go.work, null when there is no go.mod.
|
|
68
|
+
export function goModulesUnsupported(goMod, goWork) { return goMod ? (goWork ? 'go.work is unsupported' : unsupportedGoModules(goMod.toString('utf8'))) : null; }
|
|
69
|
+
|
|
70
|
+
export function prepareGoModules(sourceDir, options = {}) {
|
|
71
|
+
const input = inputs(sourceDir);
|
|
72
|
+
if (!input) throw failure('dependencies_invalid', 'root go.mod required');
|
|
73
|
+
const base = store(options);
|
|
74
|
+
fs.mkdirSync(base, { recursive: true, mode: 0o700 });
|
|
75
|
+
checkParents(base); checkDirectory(base, true);
|
|
76
|
+
fs.mkdirSync(path.join(base, input.name), { mode: 0o700, recursive: true }); checkDirectory(path.join(base, input.name), true);
|
|
77
|
+
const destination = entryPath(base, input);
|
|
78
|
+
if (fs.existsSync(destination)) {
|
|
79
|
+
try { return lookup(input, base); }
|
|
80
|
+
catch (error) { if (!options.replaceInvalid) throw error; }
|
|
81
|
+
}
|
|
82
|
+
const stage = fs.mkdtempSync(path.join(base, `.stage-${process.pid}-`));
|
|
83
|
+
try {
|
|
84
|
+
const work = path.join(stage, 'work'), cache = path.join(stage, 'modcache');
|
|
85
|
+
for (const dir of [work, cache, path.join(stage, 'home'), path.join(stage, 'gopath')]) fs.mkdirSync(dir, { mode: 0o700 });
|
|
86
|
+
// The go command records telemetry counters (and may start a helper) under HOME at exit; "off" keeps the stage quiet so removing it cannot race.
|
|
87
|
+
fs.mkdirSync(path.join(stage, 'home', '.config', 'go', 'telemetry'), { recursive: true, mode: 0o700 });
|
|
88
|
+
fs.writeFileSync(path.join(stage, 'home', '.config', 'go', 'telemetry', 'mode'), 'off\n', { mode: 0o600 });
|
|
89
|
+
fs.writeFileSync(path.join(work, 'go.mod'), input.mod, { mode: 0o600 });
|
|
90
|
+
fs.writeFileSync(path.join(work, 'go.sum'), input.sum, { mode: 0o600 });
|
|
91
|
+
const env = options.env ?? process.env;
|
|
92
|
+
const proxyEnv = Object.fromEntries(Object.entries(env).filter(([name]) => /^(LANG|NODE_EXTRA_CA_CERTS|SSL_CERT_FILE|GOPROXY|GOSUMDB|(https?|no)_proxy)$/i.test(name)));
|
|
93
|
+
// GOTOOLCHAIN=auto lets `go mod download` fetch the toolchain go.mod asks for into the same cache; -modcacherw lets us delete
|
|
94
|
+
// a failed stage. Nothing here runs repository code: download only fetches and verifies archives against go.sum.
|
|
95
|
+
const run = spawnSync(GO, ['mod', 'download'], { cwd: work, stdio: 'ignore', timeout: options.timeoutMs ?? 600000, env: { ...proxyEnv, PATH: '/usr/bin:/bin', HOME: path.join(stage, 'home'), GOPATH: path.join(stage, 'gopath'), GOMODCACHE: cache, GOFLAGS: '-modcacherw', GOWORK: 'off', GOTOOLCHAIN: 'auto' } });
|
|
96
|
+
if (run.error || run.status !== 0) {
|
|
97
|
+
const exit = run.error ? `error: ${run.error.message}` : run.signal ? `signal ${run.signal}` : `exit status ${run.status}`;
|
|
98
|
+
throw failure('dependencies_install_failed', `go mod download failed (${exit}); no preparation published`);
|
|
99
|
+
}
|
|
100
|
+
// A go.sum that download had to extend is incomplete: the sandbox build would fail on it, so publish nothing.
|
|
101
|
+
if (!fs.readFileSync(path.join(work, 'go.sum')).equals(input.sum)) throw failure('dependencies_install_failed', 'go.sum is incomplete for go.mod; no preparation published');
|
|
102
|
+
freezeTree(cache); validateTree(cache);
|
|
103
|
+
fs.writeFileSync(path.join(stage, 'metadata.json'), JSON.stringify({ identity: input.identity }) + '\n', { mode: 0o400 });
|
|
104
|
+
for (const name of ['work', 'home', 'gopath']) fs.rmSync(path.join(stage, name), { recursive: true, force: true });
|
|
105
|
+
if (fs.existsSync(destination)) {
|
|
106
|
+
try { return lookup(input, base); }
|
|
107
|
+
catch (error) { if (!options.replaceInvalid) throw error; }
|
|
108
|
+
// Keep the old inodes for any running read-only mount; the new bytes go to a new path.
|
|
109
|
+
fs.renameSync(destination, path.join(base, '.replaced-' + randomUUID()));
|
|
110
|
+
}
|
|
111
|
+
try { fs.renameSync(stage, destination); }
|
|
112
|
+
catch (error) { // another publisher won the race: reuse its entry when it is valid, otherwise report the original failure
|
|
113
|
+
try { return lookup(input, base); } catch { throw error; }
|
|
114
|
+
}
|
|
115
|
+
return lookup(input, base);
|
|
116
|
+
} finally {
|
|
117
|
+
if (fs.existsSync(stage)) { thawTree(stage); fs.rmSync(stage, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); }
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Same detached child the node preparation uses, so a minutes-long download does not stop the bridge's event loop.
|
|
122
|
+
export function prepareGoModulesInChild(sourceDir, { timeoutMs = 600000, env = process.env } = {}) {
|
|
123
|
+
const root = fs.realpathSync(sourceDir);
|
|
124
|
+
const input = inputs(root);
|
|
125
|
+
if (!input) return Promise.resolve(null);
|
|
126
|
+
return prepareInChild({ root, key: `go:${input.name}:${input.key}`, base: store({}), flags: ['--go'], timeoutMs, env });
|
|
127
|
+
}
|