@tnunamak/dalan 0.8.5 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,8 @@ import os from 'node:os';
8
8
  import { workGrantProblem } from './publication-authority.mjs';
9
9
  import { writableScope } from './workspace.mjs';
10
10
 
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 });
11
+ const git = (dir, args, input, env, encoding = 'utf8', timeout) => spawnSync((env ?? process.env).DALAN_GIT || 'git',
12
+ ['-C', dir, ...args], { input, encoding, maxBuffer: 64 * 1024 * 1024, env, timeout, killSignal: timeout ? 'SIGKILL' : undefined });
12
13
 
13
14
  const materializeName = '[A-Za-z0-9][A-Za-z0-9_.-]*';
14
15
  const materializeRepo = new RegExp('^' + materializeName + '/' + materializeName + '$');
@@ -60,9 +61,56 @@ export function materializeDecision(grant, repo, requestId, authority) {
60
61
  }
61
62
 
62
63
 
64
+ function publicationError(publicationCode, message, cause) {
65
+ return Object.assign(new Error(message,{cause}),{publicationCode});
66
+ }
67
+
68
+ export function publicationFailureText(error) {
69
+ if(error?.publicationCode==='deadline') return 'publication deadline reached';
70
+ if(error?.publicationCode==='identity') return 'draft identity or state changed; publication not verified';
71
+ if(error?.publicationCode==='authority') return 'publication authority changed';
72
+ return 'could not verify publication';
73
+ }
74
+
75
+ function publicationBudget(timeoutMs) {
76
+ // Bound the publication stages and Git cleanup. Local filesystem cleanup
77
+ // still runs after those deadlines.
78
+ if(!Number.isSafeInteger(timeoutMs)||timeoutMs<1) throw new Error('invalid publication deadline');
79
+ const end=performance.now()+timeoutMs;
80
+ const workEnd=end-Math.min(2000,Math.floor(timeoutMs/5));
81
+ const deadline=()=>publicationError('deadline','materialize timed out');
82
+ function remaining(cleanup=false) {
83
+ const time=Math.floor((cleanup?end:workEnd)-performance.now());
84
+ if(time<1) throw deadline();
85
+ return time;
86
+ }
87
+ return {
88
+ remaining,
89
+ git(dir,args,input,env,encoding) {
90
+ const result=git(dir,args,input,env,encoding,Math.min(10000,remaining()));
91
+ if(result.error?.code==='ETIMEDOUT') throw deadline();
92
+ return result;
93
+ },
94
+ async read(fn) {
95
+ const timeout=remaining();
96
+ const abort=new AbortController();
97
+ let timer;
98
+ const expired=new Promise((_,reject)=>{
99
+ timer=setTimeout(()=>{ reject(deadline()); abort.abort(); },timeout);
100
+ });
101
+ try {
102
+ const result=await Promise.race([Promise.resolve().then(()=>fn(abort.signal)),expired]);
103
+ remaining();
104
+ return result;
105
+ }
106
+ finally { clearTimeout(timer); }
107
+ },
108
+ };
109
+ }
110
+
63
111
  // Shared owner-side publication path. Approval and formatting belong to the caller.
64
112
  export async function materialize({id, got, dir, grantFile, download, recheck,
65
- dryRun=false, approve=false, standingOnly=false, fetchBase=false}) {
113
+ dryRun=false, approve=false, standingOnly=false, fetchBase=false, timeoutMs=30000}) {
66
114
  const grant=readMaterializeGrant(grantFile);
67
115
  if(got.status!=='finished'||got.revised_by) throw new Error('materialize needs a current, finished result');
68
116
  const ev=got.report?.workspace_evidence, art=ev?.patch_artifact, inputs=got.assignment?.inputs;
@@ -74,11 +122,13 @@ export async function materialize({id, got, dir, grantFile, download, recheck,
74
122
  const decision=materializeDecision(grant,repo,id,got.publication_authority);
75
123
  const result={request_id:id,repo,base_sha,files:[],decision,published:false,branch:decision.branch,reason:decision.reason};
76
124
  if(standingOnly && !decision.push) return result;
77
- const temp=fs.mkdtempSync(path.join(os.tmpdir(),'dalan-materialize-'));
125
+ const budget=publicationBudget(timeoutMs);
126
+ const temp=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'dalan-materialize-')));
127
+ let failure, cleanupPending=false;
78
128
  try {
79
- const body=Buffer.from(await download(art));
129
+ const body=Buffer.from(await budget.read(signal=>download(art,{signal})));
80
130
  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);
131
+ result.files=listPatchFiles(temp,body,undefined,budget.git);
82
132
  // The patch may touch only what the work was allowed to change. Anything else is kept as a patch and never pushed.
83
133
  const inScope=got.assignment?.execution_scope?writableScope(got.assignment):null;
84
134
  const outside=inScope?result.files.filter(file=>!inScope(file)):[];
@@ -91,21 +141,31 @@ export async function materialize({id, got, dir, grantFile, download, recheck,
91
141
  const title=String(got.assignment?.title ?? 'Dalan patch '+id).split(/\r?\n/,1)[0].trim().slice(0,240) || 'Dalan patch '+id;
92
142
  const summary=String(got.report?.summary ?? 'Patch for Dalan assignment '+id+'.').slice(0,30000);
93
143
  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();
144
+ repo,branch:decision.branch,title,summary,fetchBase,budget,
145
+ rememberCleanup:()=>{ cleanupPending=true; },recheck:async(phase='push')=>{
146
+ const current=await budget.read(signal=>recheck({signal}));
96
147
  const after=phase==='pr' ? 'the branch was pushed, so it exists, but no draft pull request was opened' : 'nothing pushed';
97
148
  if(current.status!=='finished'||current.revised_by||current.report?.workspace_evidence?.patch_artifact?.sha256!==art.sha256) {
98
149
  throw new Error('materialize result changed before publication; '+after);
99
150
  }
100
151
  const currentDecision=materializeDecision(readMaterializeGrant(grantFile),repo,id,current.publication_authority);
101
152
  if(!currentDecision.push && !(currentDecision.needs_approval && approve)) {
102
- throw new Error('materialize authority changed before publication ('+currentDecision.reason+'); '+after);
153
+ throw publicationError('authority','materialize authority changed before publication ('+currentDecision.reason+'); '+after);
103
154
  }
104
155
  }}));
105
156
  }
106
157
  result.published=!!result.pr_url;
107
158
  return result;
108
- } finally { fs.rmSync(temp,{recursive:true,force:true}); }
159
+ } catch(error) {
160
+ failure=error;
161
+ throw error;
162
+ } finally {
163
+ if(!cleanupPending) {
164
+ try { fs.rmSync(temp,{recursive:true,force:true}); }
165
+ catch { cleanupPending=true; }
166
+ }
167
+ if(cleanupPending) (failure??result).cleanup_pending=true;
168
+ }
109
169
  }
110
170
 
111
171
  // Only a matching GitHub push URL is eligible. Match the exact path, not a substring
@@ -116,18 +176,19 @@ function githubPushRepo(url) {
116
176
  return (ssh?.[1] ?? absolute?.[1])?.replace(/\.git$/i, '').toLowerCase();
117
177
  }
118
178
 
119
- export async function materializePatch({dir, temp, body, sha256, baseSha, repo, branch, title, summary, recheck, fetchBase=false}) {
179
+ async function materializePatch({dir, temp, body, sha256, baseSha, repo, branch, title, summary, recheck, fetchBase, budget, rememberCleanup}) {
120
180
  if(typeof dir!=='string' || !path.isAbsolute(dir)) throw new Error('materialize requires a checkout directory');
121
181
  const ref = 'refs/heads/' + branch;
122
182
  if (!materializeRepo.test(repo) || !/^dalan\/[-\w]{8,128}$/.test(branch) || !/^[a-f0-9]{40}$/.test(baseSha)) {
123
183
  throw new Error('materialize needs a pinned GitHub repo and a scoped branch');
124
184
  }
125
- const run = (program, cwd, args, label) => {
126
- const r = spawnSync(program, args, {cwd, encoding:'utf8', maxBuffer:1024*1024, timeout:10000, killSignal:'SIGKILL'});
127
- if(r.error || r.status!==0) throw new Error('materialize: '+label+(r.error?.code === 'ETIMEDOUT' ? ' could not run (timed out)' : ' failed'+(r.status==null?'':' (exit '+r.status+')')));
185
+ const run = (program, cwd, args, label, cleanup) => {
186
+ const r = spawnSync(program, args, {cwd, encoding:'utf8', maxBuffer:1024*1024, timeout:Math.min(10000,budget.remaining(cleanup)), killSignal:'SIGKILL'});
187
+ if(r.error?.code==='ETIMEDOUT') throw publicationError('deadline','materialize: '+label+' could not run (timed out)',r.error);
188
+ if(r.error || r.status!==0) throw new Error('materialize: '+label+' failed'+(r.status==null?'':' (exit '+r.status+')'));
128
189
  return r.stdout.trim();
129
190
  };
130
- const gitCmd = (cwd, args, label) => run(process.env.DALAN_GIT || 'git',cwd,['-c','core.hooksPath=/dev/null', ...args],label);
191
+ const gitCmd = (cwd, args, label, cleanup) => run(process.env.DALAN_GIT || 'git',cwd,['-c','core.hooksPath=/dev/null', ...args],label,cleanup);
131
192
  const ghRepo = 'github.com/' + repo;
132
193
  const ghCmd = (args, label) => run(process.env.DALAN_GH || 'gh',dir,args,label);
133
194
  // Require a real checkout, including when it is a linked worktree.
@@ -139,7 +200,7 @@ export async function materializePatch({dir, temp, body, sha256, baseSha, repo,
139
200
  }
140
201
  if (urls.size !== 1) throw new Error('materialize requires one matching GitHub push URL');
141
202
  const [[, remote]] = urls;
142
- if(fetchBase && git(dir,['cat-file','-e',baseSha+'^{commit}']).status!==0) {
203
+ if(fetchBase && budget.git(dir,['cat-file','-e',baseSha+'^{commit}']).status!==0) {
143
204
  // Fetch only from the already matched push URL, even if the remote's fetch URL differs.
144
205
  gitCmd(dir,['fetch','--no-tags',remote,baseSha],'fetch pinned base commit');
145
206
  }
@@ -147,16 +208,19 @@ export async function materializePatch({dir, temp, body, sha256, baseSha, repo,
147
208
  if(!targetBase || targetBase===branch) throw new Error('materialize cannot target the default branch for a push');
148
209
  gitCmd(dir,['check-ref-format','refs/heads/'+targetBase],'verify repository default branch');
149
210
  const worktree = path.join(temp,'checkout');
150
- gitCmd(dir,['worktree','add','--detach',worktree,baseSha],'create detached worktree');
151
- let failure;
211
+ // The receipt survives a failed removal. It names only this checkout and its linked worktree.
212
+ fs.writeFileSync(path.join(temp,'cleanup.json'),JSON.stringify({checkout:dir,worktree}),{mode:0o600,flag:'wx'});
213
+ let branchState, draftAttempted = false;
152
214
  try {
153
- applyPatch({dir:worktree, patch:body, sha256, baseSha});
215
+ gitCmd(dir,['worktree','add','--detach',worktree,baseSha],'create detached worktree');
216
+ applyPatch({dir:worktree, patch:body, sha256, baseSha, runGit:budget.git});
154
217
  gitCmd(worktree,['add','-A','--','.'],'stage patch');
155
218
  gitCmd(worktree,['commit','--no-gpg-sign','-m','Materialize '+branch],'commit patch with local identity');
156
219
  const tip = gitCmd(worktree,['ls-remote','--heads',remote,ref],'inspect scoped remote branch');
157
220
  if(tip) {
158
221
  const cols=tip.split(/\s+/);
159
222
  if(cols.length!==2 || !/^[a-f0-9]{40}$/.test(cols[0]) || cols[1]!==ref) throw new Error('materialize received an invalid remote ref');
223
+ branchState = 'observed';
160
224
  gitCmd(worktree,['fetch','--no-tags','--no-write-fetch-head',remote,cols[0]],'read the existing scoped branch');
161
225
  const existing=gitCmd(worktree,['show','-s','--format=%P %T',cols[0]],'read existing branch tree');
162
226
  const candidate=gitCmd(worktree,['show','-s','--format=%P %T','HEAD'],'read candidate tree');
@@ -164,12 +228,17 @@ export async function materializePatch({dir, temp, body, sha256, baseSha, repo,
164
228
  }
165
229
  await recheck('push');
166
230
  // 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');
231
+ if (!tip) {
232
+ branchState = 'push_unconfirmed';
233
+ gitCmd(worktree,['push','--no-follow-tags','--force-with-lease='+ref+':',remote,'HEAD:'+ref],'create scoped remote branch');
234
+ branchState = 'push_succeeded';
235
+ }
168
236
  const expectedHead=tip ? tip.split(/\s+/)[0] : gitCmd(worktree,['rev-parse','HEAD'],'read published commit');
169
237
  let pr_url;
170
238
  try {
171
239
  // The push can finish after the owner changes or withdraws approval.
172
240
  await recheck('pr');
241
+ draftAttempted = true;
173
242
  try {
174
243
  pr_url=ghCmd(['pr','create','--repo',ghRepo,'--draft','--base',targetBase,'--head',branch,
175
244
  '--title',title,'--body',summary],'open draft pull request');
@@ -190,32 +259,40 @@ export async function materializePatch({dir, temp, body, sha256, baseSha, repo,
190
259
  '--jq','.head.repo.full_name + " " + .head.sha + " " + .head.ref + " " + .base.repo.full_name + " " + .base.ref + " " + .state + " " + (.draft|tostring)'],'verify draft repository and head');
191
260
  const [headRepo,headSha,headRef,baseRepo,baseRef,prState,isDraft,...extra]=prHead.split(/\s+/);
192
261
  if(headRepo?.toLowerCase()!==repo.toLowerCase() || headSha!==expectedHead || headRef!==branch || baseRepo?.toLowerCase()!==repo.toLowerCase() || baseRef!==targetBase || prState!=='open' || isDraft!=='true' || extra.length) {
193
- throw new Error('draft identity or state changed; publication not verified');
262
+ throw publicationError('identity','draft identity or state changed; publication not verified');
194
263
  }
195
264
 
196
265
  } catch(error) {
197
- throw new Error('materialize branch '+branch+' exists; draft pull request not confirmed. '+error.message);
266
+ throw Object.assign(new Error('materialize branch '+branch+' exists; draft pull request not confirmed. '+error.message,
267
+ {cause:error}),{publicationCode:error.publicationCode});
198
268
  }
199
269
  // The existing scoped branch may have an equivalent tree under a different
200
270
  // commit. Report its actual commit, and refuse success if the ref moved.
201
271
  const remoteHead=gitCmd(worktree,['ls-remote','--heads',remote,ref],'verify published head');
202
272
  const [head,remoteRef,...extra]=remoteHead.split(/\s+/);
203
273
  if(head!==expectedHead || remoteRef!==ref || extra.length) {
204
- throw new Error('materialize published head changed; draft may exist, publication not verified');
274
+ throw publicationError('identity','materialize published head changed; draft may exist, publication not verified');
205
275
  }
276
+ budget.remaining();
206
277
  return {branch,pr_url,verified_head_sha:head};
207
- } catch(error) {
208
- failure=error;
278
+ } catch (error) {
279
+ if (branchState) error.remote_effect = {branch, branch_state:branchState, draft_attempted:draftAttempted};
209
280
  throw error;
210
281
  } finally {
211
- try {gitCmd(dir,['worktree','remove','--force',worktree],'remove temporary worktree');}
212
- catch(error) { if(!failure) throw error; }
282
+ try { gitCmd(dir,['worktree','remove','--force',worktree],'remove temporary worktree',true); }
283
+ catch {
284
+ // A failed add or remove may leave a registration without a worktree directory.
285
+ try {
286
+ const records=gitCmd(dir,['worktree','list','--porcelain','-z'],'check temporary worktree registration',true);
287
+ if(records.split('\0').includes('worktree '+worktree)) rememberCleanup();
288
+ } catch { rememberCleanup(); }
289
+ }
213
290
  }
214
291
  }
215
292
 
216
293
  // git apply from a subdirectory can silently skip root-relative paths.
217
- export function worktreeRoot(dir, env) {
218
- const root = git(dir, ['rev-parse', '--show-toplevel'], undefined, env, 'buffer');
294
+ export function worktreeRoot(dir, env, runGit=git) {
295
+ const root = runGit(dir, ['rev-parse', '--show-toplevel'], undefined, env, 'buffer');
219
296
  return root.status === 0 ? decodePatchPathOutput(root.stdout).replace(/\r?\n$/, '') : null;
220
297
  }
221
298
 
@@ -264,13 +341,13 @@ function restore(snap) {
264
341
 
265
342
  // 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,
266
343
  // else the reason in one sentence.
267
- export function baseProblem(dir, baseSha, env) {
344
+ export function baseProblem(dir, baseSha, env, runGit=git) {
268
345
  if (!/^[0-9a-f]{40,64}$/.test(baseSha ?? '')) return 'the job records no base commit';
269
- const head = git(dir, ['rev-parse', '--verify', 'HEAD'], undefined, env);
346
+ const head = runGit(dir, ['rev-parse', '--verify', 'HEAD'], undefined, env);
270
347
  if (head.status !== 0) return `${dir} is not a git checkout with a HEAD`;
271
- const known = git(dir, ['cat-file', '-e', `${baseSha}^{commit}`], undefined, env);
348
+ const known = runGit(dir, ['cat-file', '-e', `${baseSha}^{commit}`], undefined, env);
272
349
  if (known.status !== 0) return `base ${baseSha.slice(0, 12)} is not in this checkout; use a checkout that already contains it`;
273
- const anc = git(dir, ['merge-base', '--is-ancestor', baseSha, 'HEAD'], undefined, env);
350
+ const anc = runGit(dir, ['merge-base', '--is-ancestor', baseSha, 'HEAD'], undefined, env);
274
351
  if (anc.status === 1) return `base ${baseSha.slice(0, 12)} is not an ancestor of HEAD ${head.stdout.trim().slice(0, 12)}; the patch was built on a different line of history`;
275
352
  return anc.status === 0 ? null : `could not compare base and HEAD: ${anc.stderr.trim()}`;
276
353
  }
@@ -283,8 +360,8 @@ export function decodePatchPathOutput(bytes) {
283
360
  }
284
361
 
285
362
  // The files a patch names, renames as old and new, read from the patch alone (no check against the tree).
286
- function patchPaths(dir, body, env, direction) {
287
- const numstat = git(dir, ['apply', '--numstat', '-z', ...direction, '-'], body, env, 'buffer');
363
+ function patchPaths(dir, body, env, direction, runGit) {
364
+ const numstat = runGit(dir, ['apply', '--numstat', '-z', ...direction, '-'], body, env, 'buffer');
288
365
  if (numstat.error || numstat.status !== 0) throw new Error(`git apply --numstat failed: ${(numstat.stderr?.toString('utf8') || numstat.error?.message || '').trim().slice(0, 300)}`);
289
366
  const records = decodePatchPathOutput(numstat.stdout).split('\0');
290
367
  const files = [];
@@ -305,31 +382,37 @@ function patchPaths(dir, body, env, direction) {
305
382
  return files;
306
383
  }
307
384
 
308
- export function listPatchFiles(dir, body, env) {
385
+ export function listPatchFiles(dir, body, env, runGit=git) {
309
386
  // Some git apply versions report only the destination in forward numstat.
310
387
  // Ask the same parser in reverse too, so rollback captures both endpoints
311
388
  // without interpreting a human-readable rename summary or its quoting.
312
- return [...new Set([...patchPaths(dir, body, env, []), ...patchPaths(dir, body, env, ['--reverse'])])];
389
+ return [...new Set([...patchPaths(dir, body, env, [], runGit), ...patchPaths(dir, body, env, ['--reverse'], runGit)])];
313
390
  }
314
391
 
315
392
  // Checks the digest, the base and `git apply --check`, then applies. Preflight failures touch nothing; a failed apply
316
393
  // 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
317
394
  // the checks and the file list and writes nothing, so a caller can take an authorization between the check and the write.
318
- export function applyPatch({ dir, patch, sha256, baseSha, env, checkOnly = false }) {
395
+ export function applyPatch({ dir, patch, sha256, baseSha, env, checkOnly = false, runGit=git }) {
319
396
  const body = Buffer.from(patch);
320
397
  if (sha256 && createHash('sha256').update(body).digest('hex') !== sha256) throw new Error('patch sha256 does not match the recorded evidence; not applied');
321
- const problem = baseProblem(dir, baseSha, env);
398
+ const problem = baseProblem(dir, baseSha, env, runGit);
322
399
  if (problem) throw new Error(`not applied: ${problem}`);
323
- dir = worktreeRoot(dir, env);
400
+ dir = worktreeRoot(dir, env, runGit);
324
401
  if (!dir) throw new Error('not applied: could not resolve the repository worktree top level');
325
- const check = git(dir, ['apply', '--check', '-'], body, env);
402
+ const check = runGit(dir, ['apply', '--check', '-'], body, env);
326
403
  if (check.status !== 0) throw new Error(`not applied: git apply --check failed: ${(check.stderr || '').trim().slice(0, 300)}`);
327
- const files = listPatchFiles(dir, body, env);
404
+ const files = listPatchFiles(dir, body, env, runGit);
328
405
  if (checkOnly) return files;
329
406
  // git apply checks everything first but writes file by file, so a write error can leave some files changed. Keep what it
330
407
  // 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.
331
408
  const before = snapshot(dir, files);
332
- const run = git(dir, ['apply', '-'], body, env);
409
+ let run;
410
+ try { run = runGit(dir, ['apply', '-'], body, env); }
411
+ catch(error) {
412
+ const failed=restore(before);
413
+ if(failed.length) throw new Error(`git apply stopped and ${failed.join(', ')} could not be restored`,{cause:error});
414
+ throw error;
415
+ }
333
416
  if (run.status !== 0) {
334
417
  const failed = restore(before), reason = (run.stderr || run.error?.message || '').trim().slice(0, 300);
335
418
  throw new Error(failed.length