@tnunamak/dalan 0.9.10 → 0.9.11

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.
@@ -0,0 +1,143 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { artifactSecretRule, hasCredentialFieldText, hasSecretContent, redactOutput } from './redaction.mjs';
3
+ import { localAttachmentPublicationRestriction } from './local-attachment-result.mjs';
4
+
5
+ const prefix='CHECKPOINT v1: ';
6
+ export const isRecoveryCheckpoint=note=>typeof note==='string'&&note.startsWith(prefix);
7
+ const digest=bytes=>createHash('sha256').update(bytes).digest('hex');
8
+ const fail=code=>{throw Object.assign(new Error(code),{code});};
9
+ const id=v=>typeof v==='string'&&/^art_[A-Za-z0-9_-]{8,128}$/.test(v);
10
+
11
+ export function migrateWorkRecovery(db) {
12
+ db.exec(`CREATE TABLE IF NOT EXISTS work_checkpoints(
13
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
14
+ request_id TEXT NOT NULL REFERENCES assignments(request_id) ON DELETE CASCADE,
15
+ worker TEXT NOT NULL, epoch INTEGER NOT NULL, operation TEXT NOT NULL, intent TEXT NOT NULL,
16
+ summary TEXT NOT NULL, artifact_refs TEXT NOT NULL, accepted_at TEXT NOT NULL,
17
+ UNIQUE(request_id,epoch,operation)
18
+ );
19
+ CREATE INDEX IF NOT EXISTS work_checkpoint_latest ON work_checkpoints(request_id,worker,seq);`);
20
+ }
21
+ function parse(note) {
22
+ let value;
23
+ try { value=JSON.parse(note.slice(prefix.length)); } catch { fail('invalid_work_checkpoint'); }
24
+ if(!value||Object.keys(value).sort().join(',')!=='artifact_ids,key,summary'||
25
+ typeof value.key!=='string'||!/^[A-Za-z0-9_-]{1,80}$/.test(value.key)||
26
+ typeof value.summary!=='string'||!value.summary.trim()||Buffer.byteLength(value.summary)>2048||
27
+ /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value.summary)||
28
+ !Array.isArray(value.artifact_ids)||value.artifact_ids.length>4||
29
+ value.artifact_ids.some(v=>!id(v))||new Set(value.artifact_ids).size!==value.artifact_ids.length)
30
+ fail('invalid_work_checkpoint');
31
+ if(hasSecretContent(value.summary)||hasCredentialFieldText(value.summary)||artifactSecretRule(Buffer.from(value.summary)))
32
+ fail('work_checkpoint_withheld');
33
+ return value;
34
+ }
35
+ export function saveWorkCheckpoint(store,context,note) {
36
+ const {db}=store;
37
+ if(!db.isTransaction)fail('transaction_required');
38
+ const {work,claimId,subject,worker,connectionId}=context;
39
+ const claim=store.assertClaim(work,claimId,subject,worker);
40
+ store.assertMutationConnection(work,claim,connectionId);
41
+ if(db.prepare('SELECT status FROM assignments WHERE request_id=?').get(work)?.status!=='claimed')
42
+ fail('work_checkpoint_not_active');
43
+ const value=parse(note);
44
+ const intent=digest(JSON.stringify([value.summary,value.artifact_ids]));
45
+ const previous=db.prepare('SELECT seq,intent,accepted_at FROM work_checkpoints WHERE request_id=? AND epoch=? AND operation=?')
46
+ .get(work,claim.epoch,value.key);
47
+ if(previous) {
48
+ if(previous.intent!==intent)fail('work_checkpoint_key_conflict');
49
+ return {recorded:true,checkpoint:{sequence:previous.seq,accepted_at:previous.accepted_at,epoch:claim.epoch},duplicate:true};
50
+ }
51
+ const sealed=db.prepare("SELECT id,sha256,size FROM artifacts WHERE request_id=? AND id=? AND kind='upload' AND sealed=1 AND origin_claim_id=? AND origin_epoch=?");
52
+ const artifacts=value.artifact_ids.map(ref=>{
53
+ const found=sealed.get(work,ref,claimId,claim.epoch);
54
+ if(!found||!/^[a-f0-9]{64}$/.test(found.sha256??'')||!Number.isSafeInteger(found.size)||found.size<0)
55
+ fail('work_checkpoint_artifact_not_bound');
56
+ return {artifact_id:found.id,sha256:found.sha256,size:found.size};
57
+ });
58
+ const accepted_at=store.stamp();
59
+ const saved=db.prepare('INSERT INTO work_checkpoints(request_id,worker,epoch,operation,intent,summary,artifact_refs,accepted_at) VALUES(?,?,?,?,?,?,?,?)')
60
+ .run(work,worker,claim.epoch,value.key,intent,value.summary,JSON.stringify(artifacts),accepted_at);
61
+ // Keep the ordinary progress log useful without duplicating private checkpoint
62
+ // content into the unfenced legacy get projection or its notifications.
63
+ store.progressInTransaction(work,claimId,'A continuation checkpoint was accepted.',subject,false,worker);
64
+ return {recorded:true,checkpoint:{sequence:Number(saved.lastInsertRowid),accepted_at,epoch:claim.epoch},duplicate:false};
65
+ }
66
+
67
+ const priorMaxBytes=8*1024;
68
+ function priorWorkReference(store,work,grant) {
69
+ const {db}=store;
70
+ // A mere common worker, shared policy relationship, request string, or
71
+ // copied brief has no disclosure authority. Only the sealed follow edge
72
+ // under the same continuing handle is considered.
73
+ const edge=db.prepare(`SELECT f.prior_id,a.relationship_id,p.relationship_id AS prior_relationship,
74
+ a.target_worker,p.target_worker AS prior_worker,p.status AS prior_status,
75
+ r.counterpart_ref,r.ended_at
76
+ FROM job_follows f
77
+ JOIN assignments a ON a.request_id=f.request_id
78
+ JOIN assignments p ON p.request_id=f.prior_id
79
+ JOIN continuing_subagent_jobs c ON c.request_id=f.request_id
80
+ JOIN continuing_subagent_jobs d ON d.request_id=f.prior_id AND d.subagent_id=c.subagent_id
81
+ LEFT JOIN relationships r ON r.relationship_id=a.relationship_id
82
+ WHERE f.request_id=?`).get(work);
83
+ if(!edge)return undefined;
84
+ const omit=reason=>({kind:'prior_result_omitted',reason,runtime_state:'not_resumed'});
85
+ if(!edge.relationship_id||edge.relationship_id!==edge.prior_relationship||edge.ended_at!==null||
86
+ edge.counterpart_ref!==grant.worker||edge.target_worker!==grant.worker||edge.prior_worker!==grant.worker||
87
+ typeof grant.connection_id!=='string'||!grant.connection_id)
88
+ return omit('recipient_unavailable');
89
+ // The same exact recipient can reuse a result from a selected text brief.
90
+ // A repository snapshot still requires its own disclosure binding.
91
+ if(localAttachmentPublicationRestriction(db,work,{includeLocalText:false}))
92
+ return omit('unpublished_lineage_withheld');
93
+ const receipt=db.prepare(`SELECT p.request_id,p.receipt_id,p.claim_id,p.summary,p.result,p.outcome,
94
+ p.created_at,c.subject,c.worker,c.connection_id
95
+ FROM reports p JOIN claims c ON c.request_id=p.request_id AND c.claim_id=p.claim_id
96
+ WHERE p.request_id=? AND p.late=0`).get(edge.prior_id);
97
+ if(edge.prior_status!=='finished'||!receipt||receipt.outcome!=='completed'||
98
+ typeof receipt.summary!=='string'||typeof receipt.result!=='string'||!receipt.result.length)
99
+ return omit('unavailable');
100
+ if(receipt.worker!==grant.worker||receipt.subject!==grant.subject||receipt.connection_id!==grant.connection_id)
101
+ return omit('recipient_unavailable');
102
+ const maxGate=Buffer.byteLength(receipt.summary)+Buffer.byteLength(receipt.result);
103
+ if(maxGate>priorMaxBytes)return omit('size_limit');
104
+ const source={summary:receipt.summary,result:receipt.result};
105
+ if(hasSecretContent(source)||Object.values(source).some(text=>hasCredentialFieldText(text)||
106
+ artifactSecretRule(Buffer.from(text))||text.includes('[redacted secret]'))||
107
+ JSON.stringify(redactOutput(source))!==JSON.stringify(source))
108
+ return omit('redaction');
109
+ try {
110
+ if(!store.liveHeldClaim(work,grant.claim_id,grant.subject,grant.worker))return undefined;
111
+ store.assertMutationConnection(work,grant,grant.connection_id);
112
+ } catch {return undefined;}
113
+ const hasArtifacts=!!db.prepare('SELECT 1 FROM artifacts WHERE request_id=? AND sealed=1 LIMIT 1').get(edge.prior_id);
114
+ return {kind:'prior_result_reference',request_id:receipt.request_id,receipt_id:receipt.receipt_id,
115
+ issuer:'worker_report_accepted',...source,runtime_state:'not_resumed',
116
+ ...(hasArtifacts?{omissions:['artifact_delivery_not_verified']}:{}),
117
+ };
118
+ }
119
+
120
+ export function projectWorkRecovery(store,work,grant=null) {
121
+ const {db}=store;
122
+ const status=db.prepare('SELECT status FROM assignments WHERE request_id=?').get(work)?.status;
123
+ if(status==='finished'){
124
+ const receipt=db.prepare('SELECT receipt_id,outcome FROM reports WHERE request_id=?').get(work);
125
+ return receipt?{kind:'completed_result',...receipt}:{kind:'completed_result_unavailable'};
126
+ }
127
+ if(!status||status==='cancelled')return null;
128
+ const latest=grant?db.prepare('SELECT * FROM work_checkpoints WHERE request_id=? AND worker=? AND epoch<=? ORDER BY seq DESC LIMIT 1')
129
+ .get(work,grant.worker,grant.epoch):null;
130
+ const questionRows=grant?db.prepare('SELECT question_id,epoch,purpose FROM job_questions WHERE request_id=? AND worker=? AND answered_at IS NULL ORDER BY rowid DESC LIMIT 12')
131
+ .all(work,grant.worker):[];
132
+ const present=db.prepare('SELECT 1 FROM artifacts WHERE request_id=? AND id=? AND sealed=1 AND sha256=? AND size=?');
133
+ const artifacts=latest?JSON.parse(latest.artifact_refs).map(a=>({...a,
134
+ availability:present.get(work,a.artifact_id,a.sha256,a.size)?'owner_artifact_lookup_required':'retained_artifact_unavailable'})):[];
135
+ const predecessor=grant?priorWorkReference(store,work,grant):undefined;
136
+ return {kind:'open_work',claim_epoch:grant?.epoch??null,...(predecessor?{predecessor}:{}),
137
+ prior_runtime_stop:'not_observed_by_bridge_lease',
138
+ checkpoint:latest?{summary:latest.summary,accepted_at:latest.accepted_at,epoch:latest.epoch,sequence:latest.seq,
139
+ evidence:'worker_report_accepted',artifacts}:null,
140
+ context_availability:!grant?'current_claim_required':latest?'checkpoint_only_no_runtime_state':'no_accepted_checkpoint',
141
+ questions:questionRows.map(({question_id,epoch,purpose})=>({question_id,purpose,epoch,
142
+ state:epoch===grant.epoch?'open':'requires_new_question'}))};
143
+ }
@@ -33,3 +33,28 @@ export function parseWorkerSession(session, nowMs) {
33
33
  if (end - start > SESSION_MAX_MS) throw new Error('invalid session: longer than 24 hours is not a hosted session');
34
34
  return { started_at: new Date(start).toISOString(), ended_at: new Date(end).toISOString(), duration_ms: end - start };
35
35
  }
36
+
37
+ // Requester views reuse stored, redacted evidence. Keep the raw bounded record in get --json;
38
+ // display only a small inert preview so a worker tail cannot create new report headings.
39
+ const RUN_PREVIEW_BYTES = 512;
40
+ const quoteText = value => JSON.stringify(value).replace(/[\u007f-\u009f\u2028\u2029]/gu,
41
+ c => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'));
42
+ const oneLine = value => /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u.test(value) ? quoteText(value) : value;
43
+
44
+ export function workerRunEvidenceLines(row) {
45
+ const runs = (row.worker_runs ?? []).slice(0, WORKER_RUNS_MAX);
46
+ const lines = [];
47
+ if ((runs.length || row.worker_run_limit) && row.report?.receipt_id)
48
+ lines.push(`Result receipt: ${oneLine(row.report.receipt_id)}`);
49
+ if (runs.length) {
50
+ lines.push(`worker runs (worker_reported, not checked by the bridge): ${runs.map(run => `${oneLine(run.command)} exit ${run.exit_code}`).join('; ')}`);
51
+ runs.forEach((run, index) => {
52
+ if (!run.output_tail) return;
53
+ const bytes = Buffer.from(run.output_tail);
54
+ const preview = bytes.subarray(Math.max(0, bytes.length - RUN_PREVIEW_BYTES)).toString();
55
+ lines.push(` output ${index + 1} (quoted worker data${bytes.length > RUN_PREVIEW_BYTES ? '; tail preview truncated' : ''}): ${quoteText(preview)}`);
56
+ });
57
+ }
58
+ if (row.worker_run_limit) lines.push(`worker run limit (worker_reported): ${oneLine(row.worker_run_limit)}`);
59
+ return lines;
60
+ }
package/src/workspace.mjs CHANGED
@@ -200,12 +200,13 @@ export function validateIntegrationPatch(dir,patch,assignment) {
200
200
  }
201
201
  return files;
202
202
  }
203
- function newFilePatchHint(file,scope) {
203
+ function newFilePatchHint(file,scope,implementation=false) {
204
204
  const creatable = scope?.outputs?.has(file) === true;
205
- return `${file}: ${creatable?'creatable (listed in output_paths)':'not creatable (not listed in output_paths)'}; for an absent file use these headers: diff --git a/${file} b/${file}, new file mode 100644, --- /dev/null, +++ b/${file}`;
205
+ const status=creatable?'creatable (listed in output_paths)':implementation?'within the writable implementation scope; a valid new-file hunk can create its parent directory':'not creatable (not listed in output_paths)';
206
+ return `${file}: ${status}; for an absent file use these headers: diff --git a/${file} b/${file}, new file mode 100644, --- /dev/null, +++ b/${file}`;
206
207
  }
207
208
 
208
- function normalizeGrantedNewFiles(dir,patch,scope) {
209
+ function normalizeGrantedNewFiles(dir,patch,scope,implementation) {
209
210
  return patch.split(/(?=^diff --git )/m).map(section=>{
210
211
  const lines=section.split('\n');
211
212
  const match=/^diff --git a\/(.+) b\/(.+)$/.exec(lines[0]);
@@ -224,19 +225,19 @@ function normalizeGrantedNewFiles(dir,patch,scope) {
224
225
  if(scope?.outputs?.has(file)) throw new Error(`patch rejected: ${file} already exists; use an ordinary edit hunk for an existing file`);
225
226
  return section; // an ordinary zero-context insertion into a tracked file
226
227
  }
227
- if(!scope?.outputs?.has(file)) throw new Error(`patch rejected: ${newFilePatchHint(file,scope)}`);
228
+ if(!scope?.outputs?.has(file)) throw new Error(`patch rejected: ${newFilePatchHint(file,scope,implementation)}`);
228
229
  return [lines[0],'new file mode 100644','--- /dev/null',`+++ b/${file}`,...lines.slice(first)].join('\n');
229
230
  }).join('');
230
231
  }
231
232
 
232
- function applyPatchToTree(dir,patch,scope=null) {
233
+ function applyPatchToTree(dir,patch,scope=null,implementation=false) {
233
234
  if(Buffer.byteLength(patch)>262144) throw new Error('patch too large');
234
235
  const files=patchPaths(patch);
235
236
  for(const p of files) requireScope(p,scope);
236
237
  for(const p of files) safePath(dir,p);
237
- const normalized=normalizeGrantedNewFiles(dir,patch,scope);
238
+ const normalized=normalizeGrantedNewFiles(dir,patch,scope,implementation);
238
239
  const check=spawnSync('git',['-C',dir,'apply','--check','-'],{input:normalized,encoding:'utf8',timeout:10000,env:gitEnv()});
239
- if(check.status!==0) throw new Error(`patch rejected: ${(check.stderr||'').slice(0,200)} ${files.slice(0,3).map(file=>newFilePatchHint(file,scope)).join('; ')}`);
240
+ if(check.status!==0) throw new Error(`patch rejected: ${(check.stderr||'').slice(0,200)} ${files.slice(0,3).map(file=>newFilePatchHint(file,scope,implementation)).join('; ')}`);
240
241
  const applied=spawnSync('git',['-C',dir,'apply','-'],{input:normalized,encoding:'utf8',timeout:10000,env:gitEnv()});
241
242
  if(applied.status!==0) throw new Error(`patch apply failed: ${(applied.stderr||'').slice(0,200)}`);
242
243
  for(const p of files) {const f=path.join(dir,p);if(fs.existsSync(f))safePath(dir,p,true);}
@@ -804,7 +805,7 @@ export class Workspace {
804
805
  // patch with no error. Refuse it here instead. A tracked file under such a name is not new and is not refused (see restoreOutsideWritable).
805
806
  const generatedNew=patchPaths(patch).filter(file=>isGenerated(file)&&!existsAtHead(dir,file));
806
807
  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}.`);
807
- 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}; }
808
+ 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),a.assignment.execution_scope==='implementation');this.noteIgnoredWritten(requestId,dir,changed);return changed;});return {files,diff_sha256:this.diff(dir,input.base_sha).sha256}; }
808
809
  // Paths a patch wrote that git ignores are outside the candidate source (a check can still run them). They are listed, not refused,
809
810
  // and kept beside the workspace (never inside it) until the next receipt carries them.
810
811
  ignoredWrittenFile(requestId) { return path.join(worktrees,`${requestId}.ignored-written.json`); }
@@ -1031,7 +1032,10 @@ export class Workspace {
1031
1032
  const repo=assignment.inputs[0].github_repo;
1032
1033
  const declared=dir?availableChecks(repo,dir):this.availableChecksFor(assignment,worker);
1033
1034
  if(execution!=='host') return {available_checks:declared,
1034
- available_check_runnable:Object.fromEntries(declared.map(id=>[id,{runnable:false,reason:'host_execution_unavailable'}]))};
1035
+ available_check_runnable:Object.fromEntries(declared.map(id=>[id,{runnable:false,reason:'host_execution_unavailable'}])),
1036
+ host_check_availability:{execution,cause:'job_execution_mode',
1037
+ worker_action:'If you can edit, return the workspace_result patch and say which tests ran.',
1038
+ owner_action:'Verify the sealed patch in an authorized checkout, or submit a new job with host execution.'}};
1035
1039
  const namedRequested=assignment.execution_scope==='implementation'&&Array.isArray(assignment.checks)&&assignment.checks.length>0;
1036
1040
  const defaultSpec=namedRequested?(dir?detectCheck(repo,dir):this.checkMetadataFor(assignment,worker)?.default):null;
1037
1041
  const named=namedRequested&&defaultSpec?assignment.checks.flatMap((_,index)=>{
@@ -1063,7 +1067,10 @@ export class Workspace {
1063
1067
  id,{runnable:!refusal,reason:refusal?(noHostCode??refusalCode(refusal)):null},
1064
1068
  ]));
1065
1069
  return {available_checks:available,available_check_runnable,...(available.length?{available_check_details:details,check_guidance:CHECK_GUIDANCE}:{}),
1066
- host_execution_available:runnable,host_execution_unavailable_reason:reason};
1070
+ host_execution_available:runnable,host_execution_unavailable_reason:reason,
1071
+ host_check_availability:{execution,cause:runnable?'ready':noHost&&readinessRefusal&&!baseRefusal?'host_readiness':'check_policy_or_configuration',
1072
+ ...(!runnable?{worker_action:'Return the patch and say which checks did not run.',
1073
+ owner_action:'Review the reported host readiness or check authorization before retrying; the job already requests host execution.'}:{})}};
1067
1074
  } catch(error) {
1068
1075
  if(!String(error?.message??'').includes('check metadata')) throw error;
1069
1076
  if(execution==='host'&&assignment.execution_scope!=='implementation') throw error;