@tnunamak/dalan 0.7.0 → 0.8.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/PROTOCOL.md +2 -0
  4. package/README.md +68 -28
  5. package/bin/dalan.mjs +1 -1
  6. package/bin/dot-worker.mjs +13 -2
  7. package/contracts/adapter-qualification.schema.json +170 -0
  8. package/docs/chatgpt-worker-onboarding.md +1 -1
  9. package/docs/local-agent-requester.md +46 -0
  10. package/docs/manual-setup.md +1 -1
  11. package/docs/operations.md +2 -2
  12. package/docs/service-setup.md +40 -17
  13. package/docs/setup-reference.md +1 -1
  14. package/docs/t3-question-relationship.md +43 -0
  15. package/docs/t3-reverse-control.md +12 -8
  16. package/docs/t3-wake-fence-r4.md +42 -0
  17. package/docs/test-suite-isolation.md +204 -0
  18. package/docs/worker-clients.md +3 -1
  19. package/package.json +5 -2
  20. package/qualification/README.md +13 -0
  21. package/qualification/mcp.json +121 -0
  22. package/qualification/protocol-v0.json +127 -0
  23. package/src/admin-socket.mjs +2 -1
  24. package/src/answer-journal.mjs +200 -0
  25. package/src/auth-check.mjs +8 -2
  26. package/src/cli-help.mjs +4 -3
  27. package/src/destinations/index.mjs +6 -0
  28. package/src/destinations/none.mjs +3 -0
  29. package/src/destinations/t3.mjs +63 -6
  30. package/src/execution.mjs +20 -2
  31. package/src/follow-current.mjs +4 -2
  32. package/src/gozar-routes.mjs +4 -3
  33. package/src/host-budget.mjs +17 -11
  34. package/src/host-execution-policy.mjs +2 -2
  35. package/src/host-stop-reverify.mjs +6 -4
  36. package/src/integrator.mjs +3 -1
  37. package/src/server.mjs +62 -12
  38. package/src/service-launchd.mjs +28 -8
  39. package/src/service-migrate-workers.mjs +12 -2
  40. package/src/service.mjs +52 -16
  41. package/src/store.mjs +77 -14
  42. package/src/submission-policy.mjs +8 -4
  43. package/src/t3.mjs +21 -2
  44. package/src/tool-registry.mjs +54 -8
  45. package/src/workers.mjs +4 -3
  46. package/src/workspace.mjs +94 -15
package/src/workspace.mjs CHANGED
@@ -96,13 +96,15 @@ function safePath(dir,p,existing=false) { p=relative(p); let cursor=dir; for(con
96
96
  // alias (docs/PRIVATE-NOTE.TXT, a decomposed "é") that a case-insensitive or normalizing filesystem (macOS APFS) opens as
97
97
  // the excluded file is excluded too. On case-sensitive Linux this over-excludes a differently-cased sibling: that fails closed.
98
98
  export const canonicalPath=p=>p.split('/').map(part=>part.normalize('NFC').toLowerCase()).join('/');
99
- export const isExcludedPath=(p,excluded)=>excluded.has(canonicalPath(p));
99
+ export const isExcludedPath=(p,excluded)=>{const parts=canonicalPath(p).split('/');return parts.some((_,i)=>excluded.has(parts.slice(0,i+1).join('/')));};
100
100
  function scopeOf(assignment) {
101
101
  const raw=assignment.scope_paths, excluded=new Set((assignment.scope_excluded||[]).map(d=>canonicalPath(d.path)));
102
102
  const scope=Array.isArray(raw)&&raw.length?raw.map(p=>String(p).replace(/^\.\//,'').replace(/\/$/,'')):[];
103
103
  const paths=!scope.length||scope.includes('.')?null:scope;
104
104
  const outputs=outputsOf(assignment);
105
- return paths||excluded.size||outputs.size?{paths,excluded,outputs}:null;
105
+ const sensitive=assignment.execution_scope==='implementation'&&!paths&&excluded.size?sensitivePolicyPaths():null;
106
+ if(sensitive?.error) throw new Error('sensitive_policy_unavailable');
107
+ return paths||excluded.size||outputs.size?{paths,excluded,outputs,sensitive}:null;
106
108
  }
107
109
  // output_paths: new files the job may create. They are readable and writable once they exist, and are the only writable
108
110
  // files of a read-only assignment. Submit proved they are absent at the pinned revision and not sensitive.
@@ -115,7 +117,7 @@ function existsAtHead(dir,file) {
115
117
  if(r.error||r.status!==0) throw new Error(`git ls-tree failed: ${(r.stderr||r.error?.message||'').slice(0,200)}`);
116
118
  return r.stdout.length>0;
117
119
  }
118
- const inScope=(p,scope)=>!scope||(!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded);
120
+ const inScope=(p,scope)=>!scope||(!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded)&&(!scope.sensitive||!isSensitiveRepoPath(p,scope.sensitive.paths));
119
121
  // A directory that holds a scope entry may be listed so the walk can reach it.
120
122
  const leadsToScope=(p,scope)=>!scope||!scope.paths||inScope(p,scope)||scope.paths.some(s=>s.startsWith(`${p}/`))||[...scope.outputs].some(o=>o.startsWith(`${p}/`));
121
123
  function outputDirectoryHint(file,outputs) {
@@ -219,8 +221,9 @@ const GENERATED_EXCLUDES=[...GENERATED_DIRS].map(name=>`:(exclude,glob)**/${name
219
221
  // environment, so symlinks are stored as links and never followed, and a path behind a symlinked directory is not read. New objects go to
220
222
  // `scratch`, a throw-away directory, never into the mirror. Returns the tree id, or null with a reason when git could not read everything
221
223
  // (an unreadable tracked file, an unreadable untracked directory, a timeout, a skip-worktree or assume-unchanged index entry, a missing
222
- // index): then the receipt says the observation is unavailable instead of hashing a placeholder. The whole call has a 120 s deadline.
223
- export async function treeDigest(dir,scratch) {
224
+ // index): then the receipt says the observation is unavailable instead of hashing a placeholder. Explicitly withheld, absent
225
+ // skip-worktree entries are omitted from the private digest index. The whole call has a 120 s deadline.
226
+ export async function treeDigest(dir,scratch,withheldPaths=[]) {
224
227
  const own=!scratch;if(own) fs.mkdirSync(path.join(root,'run'),{recursive:true,mode:0o700});scratch??=fs.mkdtempSync(path.join(root,'run','digest-'));
225
228
  try {
226
229
  const base=gitEnv(),deadline=Date.now()+DIGEST_DEADLINE_MS,left=()=>Math.max(1000,deadline-Date.now());
@@ -239,7 +242,18 @@ export async function treeDigest(dir,scratch) {
239
242
  // Index flags that tell git not to look at the worktree (skip-worktree, assume-unchanged) would hide changes from `add -u`.
240
243
  const flags=await gitAsync2(dir,['ls-files','-v','-z'],env,left());
241
244
  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)}`};
242
- if(flags.stdout.split('\0').some(record=>record&&(record[0]==='S'||/[a-z]/.test(record[0])))) return {sha256:null,reason:'index_flags_present'};
245
+ const withheld=new Set(withheldPaths),omitted=[];
246
+ for(const record of flags.stdout.split('\0').filter(Boolean)) {
247
+ const file=record.slice(2);
248
+ if(record[0]==='S'&&withheld.has(file)&&!pathExistsOrThrow(absBytes(dir,file))) omitted.push(file);
249
+ else if(record[0]==='S'||/[a-z]/.test(record[0])) return {sha256:null,reason:'index_flags_present'};
250
+ }
251
+ // Only this private index drops verified absent exclusions. The workspace
252
+ // index retains its flags so physical withholding is never a worker patch.
253
+ if(omitted.length) {
254
+ const removed=await gitAsyncInput(dir,['update-index','--force-remove','-z','--stdin'],env,Buffer.from(omitted.join('\0')+'\0'));
255
+ if(removed.status!==0) return {sha256:null,reason:'withheld_index_removal_failed'};
256
+ }
243
257
  const deleted=await gitAsync2(dir,['ls-files','--deleted','-z'],env,left());
244
258
  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)}`};
245
259
  for(const file of deleted.stdout.split('\0').filter(Boolean)) {
@@ -358,6 +372,63 @@ export function sensitiveMasks(dir,repo,copyDir) {
358
372
  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`);
359
373
  return {paths:maskedPaths,sourceExemptions,policyError:policy.error};
360
374
  }
375
+ // Excluded implementation files never enter the runner's source tree. Skip-worktree
376
+ // keeps these deliberate omissions out of the worker's patch without reading blobs.
377
+ function withholdExcludedPaths(dir,assignment) {
378
+ if(assignment.execution_scope!=='implementation'||!assignment.scope_paths?.includes('.')||!assignment.scope_excluded?.length) return;
379
+ const excluded=assignment.scope_excluded.map(entry=>relative(entry.path));
380
+ for(const file of excluded) {
381
+ const parent=path.posix.dirname(file);
382
+ if(parent!=='.') safePath(dir,parent);
383
+ fs.rmSync(path.join(dir,file),{force:true});
384
+ // Prune empty ancestors too: a sensitive directory name must not remain in
385
+ // the execution checkout after its last withheld file is removed.
386
+ for(let ancestor=parent;ancestor!=='.';ancestor=path.posix.dirname(ancestor)) {
387
+ try { fs.rmdirSync(path.join(dir,ancestor)); }
388
+ catch(error) { if(error.code==='ENOTEMPTY'||error.code==='EEXIST') break;if(error.code!=='ENOENT') throw error; }
389
+ }
390
+ }
391
+ const tracked=new Set(git(['-C',dir,'ls-files','-z']).split('\0').filter(Boolean));
392
+ const omitted=excluded.filter(file=>tracked.has(file));
393
+ if(omitted.length) git(['-C',dir,'update-index','--skip-worktree','--',...omitted]);
394
+ }
395
+ function excludedPathsAbsent(dir,assignment) {
396
+ if(!assignment.scope_excluded?.length) return false;
397
+ if(!dir) return false;
398
+ const policy=sensitivePolicyPaths();
399
+ if(policy.error) return false;
400
+ for(const entry of assignment.scope_excluded) {
401
+ const file=relative(entry.path),parent=path.posix.dirname(file);
402
+ if(parent!=='.') safePath(dir,parent);
403
+ try { fs.lstatSync(path.join(dir,file));return false; } catch(error) { if(error.code!=='ENOENT') return false; }
404
+ }
405
+ // Check the current policy too, including ignored and generated files. A new
406
+ // sensitive file or policy change invalidates the proof rather than unmasking it.
407
+ const walk=base=>fs.readdirSync(path.join(dir,base),{withFileTypes:true}).every(entry=>{
408
+ if(entry.name==='.git') return true;
409
+ const file=base?`${base}/${entry.name}`:entry.name;
410
+ if(isSensitiveRepoPath(file,policy.paths)) return false;
411
+ return !entry.isDirectory()||walk(file);
412
+ });
413
+ return walk('');
414
+ }
415
+ // The same proof as excludedPathsAbsent, made from the pinned tree for callers with no checkout. Withholding removes exactly the paths in
416
+ // scope_excluded, so the proof holds when no other path in the tree (or any directory above it) is sensitive under the current policy.
417
+ // A sensitive file the record does not list, a malformed record, an unreadable tree or an unreadable policy all give false.
418
+ function excludedPathsAccountedAtBase(mirror,assignment) {
419
+ if(!assignment.scope_excluded?.length) return false;
420
+ const policy=sensitivePolicyPaths();
421
+ if(policy.error) return false;
422
+ const listed=spawnSync('git',['-C',mirror,'ls-tree','-r','-z','--name-only','--full-tree',assignmentInput(assignment).base_sha],{encoding:'utf8',timeout:10000,maxBuffer:64*1024*1024,env:gitEnv()});
423
+ if(listed.error||listed.status!==0) return false;
424
+ let excluded;
425
+ // A malformed persisted entry is not proof; refuse instead of throwing from claim or get.
426
+ try { excluded=new Set(assignment.scope_excluded.map(entry=>relative(entry.path))); } catch { return false; }
427
+ return listed.stdout.split('\0').filter(file=>file&&!excluded.has(file)).every(file=>{
428
+ const parts=file.split('/');
429
+ return parts.every((_,i)=>!isSensitiveRepoPath(parts.slice(0,i+1).join('/'),policy.paths));
430
+ });
431
+ }
361
432
  // A list shown in the receipt: the first `shown` names, the true total, and a flag when the preview is shorter than the total.
362
433
  const preview=(list,shown)=>list===null?null:({preview:list.slice(0,shown),total:list.length,truncated:list.length>shown});
363
434
  // The lists go to one bounded artifact; null when every list is empty. The cap counts the serialized JSON, envelope and separators
@@ -454,10 +525,11 @@ export class Workspace {
454
525
  row=this.store.db.prepare('SELECT * FROM workspaces WHERE request_id=?').get(requestId);
455
526
  }
456
527
  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');
528
+ withholdExcludedPaths(dir,ctx.a.assignment);
457
529
  if(!row.initial_patch_applied) {
458
530
  if(ctx.input.input_patch) {
459
531
  const reverse=spawnSync('git',['-C',dir,'apply','--reverse','--check','-'],{input:ctx.input.input_patch,encoding:'utf8',timeout:10000,env:gitEnv()});
460
- if(reverse.status!==0) applyPatchToTree(dir,ctx.input.input_patch);
532
+ if(reverse.status!==0) applyPatchToTree(dir,ctx.input.input_patch,scopeOf(ctx.a.assignment));
461
533
  }
462
534
  this.store.db.prepare('UPDATE workspaces SET initial_patch_applied=1 WHERE request_id=?').run(requestId);
463
535
  }
@@ -704,8 +776,11 @@ export class Workspace {
704
776
  .run(id,requestId,claimId,kind,file,bytes.length,sha(bytes),1,new Date().toISOString(),this.retention(requestId),claimId,requestId);
705
777
  return {artifact_id:id,size:bytes.length,sha256:sha(bytes),kind};
706
778
  }
779
+ mirrorFor(input,worker='dot') {
780
+ return fs.existsSync(mirrorPath(input.github_repo,{worker}))?mirrorPath(input.github_repo,{worker}):prepareGithubRepo(input,{worker});
781
+ }
707
782
  availableChecksFor(assignment,worker='dot') {
708
- const input=assignmentInput(assignment),mirror=fs.existsSync(mirrorPath(input.github_repo,{worker}))?mirrorPath(input.github_repo,{worker}):prepareGithubRepo(input,{worker});
783
+ const input=assignmentInput(assignment),mirror=this.mirrorFor(input,worker);
709
784
  return withCheckMetadata(mirror,input.base_sha,dir=>availableChecks(input.github_repo,dir));
710
785
  }
711
786
  // Catalog data is response enrichment; keep it from discarding a committed claim or finish snapshot.
@@ -715,9 +790,12 @@ export class Workspace {
715
790
  const repo=assignment.inputs[0].github_repo;
716
791
  const declared=dir?availableChecks(repo,dir):this.availableChecksFor(assignment,worker);
717
792
  if(execution!=='host') return {available_checks:declared};
718
- const baseRefusal=hostCheckRefusal(assignment);
793
+ // Without a checkout (claim, get) the persisted exclusion record is checked against the pinned tree. A check still
794
+ // proves physical absence in its own checkout before it launches.
795
+ const absent=dir?excludedPathsAbsent(dir,assignment):excludedPathsAccountedAtBase(this.mirrorFor(assignmentInput(assignment),worker),assignment);
796
+ const baseRefusal=hostCheckRefusal(assignment,null,null,null,absent);
719
797
  const readiness=hostReadiness();
720
- const candidates=baseRefusal||!readiness.ready?[]:declared.filter(id=>!hostCheckRefusal(assignment,repo,id));
798
+ const candidates=baseRefusal||!readiness.ready?[]:declared.filter(id=>!hostCheckRefusal(assignment,repo,id,null,absent));
721
799
  const reason=baseRefusal||(!readiness.ready?readiness.reason:null)||(!candidates.length?'host_check_not_allowlisted: no permitted owner-configured check is runnable':null);
722
800
  return {available_checks:candidates,host_execution_available:candidates.length>0,host_execution_unavailable_reason:reason};
723
801
  } catch(error) {
@@ -727,7 +805,7 @@ export class Workspace {
727
805
  }
728
806
  }
729
807
  checkMetadataFor(assignment,worker='dot') {
730
- const input=assignmentInput(assignment),mirror=fs.existsSync(mirrorPath(input.github_repo,{worker}))?mirrorPath(input.github_repo,{worker}):prepareGithubRepo(input,{worker});
808
+ const input=assignmentInput(assignment),mirror=this.mirrorFor(input,worker);
731
809
  return checkSpecsAt(input.github_repo,mirror,input.base_sha);
732
810
  }
733
811
  // What the bridge itself observed about one host check, and nothing more. The receipt identifies the candidate source: git's view of
@@ -787,7 +865,8 @@ export class Workspace {
787
865
  if(execution!=='host') return refuse();
788
866
  // Refuse before resolving worker-controlled check metadata or launching either phase.
789
867
  const inputForPolicy=assignmentInput(context.a.assignment);
790
- const refusal=hostCheckRefusal(context.a.assignment,inputForPolicy.github_repo,checkId);
868
+ const prepared=context.a.assignment.scope_excluded?.length?this.ensure(requestId,claimId,subject,true,worker):null;
869
+ const refusal=hostCheckRefusal(context.a.assignment,inputForPolicy.github_repo,checkId,null,excludedPathsAbsent(prepared?.dir,context.a.assignment));
791
870
  if(refusal) return refuse(refusal);
792
871
  const readiness=hostReadiness();
793
872
  if(!readiness.ready) return refuse(`host_execution (${readiness.reason})`);
@@ -846,13 +925,13 @@ export class Workspace {
846
925
  const backend=hostBackend();let evidenceMs=0;
847
926
  const timed=async fn=>{const t=Date.now();try{return await fn();}finally{evidenceMs+=Date.now()-t;}};
848
927
  fs.mkdirSync(path.join(root,'run'),{recursive:true,mode:0o700});scratch=fs.mkdtempSync(path.join(root,'run','digest-'));
849
- const firstSnap=await timed(()=>treeDigest(dir,scratch));
928
+ const firstSnap=await timed(()=>treeDigest(dir,scratch,a.assignment.scope_excluded?.map(entry=>entry.path)));
850
929
  const sourceCopyDir=path.join(scratch,'source-exemptions');fs.mkdirSync(sourceCopyDir,{mode:0o700});
851
930
  const masked=sensitiveMasks(dir,input.github_repo,sourceCopyDir);
852
931
  // One service reservation and one cumulative envelope cover preparation,
853
932
  // install and check. Mutations stay in the private tmpfs execution copy.
854
933
  assertCurrentAuthority();
855
- const launchRefusal=hostCheckRefusal(this.store.get(requestId).assignment,input.github_repo,checkId,spec);
934
+ const launchRefusal=hostCheckRefusal(this.store.get(requestId).assignment,input.github_repo,checkId,spec,excludedPathsAbsent(dir,this.store.get(requestId).assignment));
856
935
  if(launchRefusal) throw new Error(launchRefusal);
857
936
  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:()=>{
858
937
  try { assertCurrentAuthority(); return false; } catch { return true; }
@@ -939,7 +1018,7 @@ export class Workspace {
939
1018
  async runConfined(requestId,dir,command,spec,{cancelled,checkRunId,repo=null,checkId=null,expectedSpec=null}={}) {
940
1019
  // Policy is rechecked at the only launch boundary; repository metadata
941
1020
  // cannot opt the operator in or bypass the whole-repository read grant.
942
- const refusal=hostCheckRefusal(this.store.get(requestId).assignment,repo,checkId,expectedSpec);
1021
+ const refusal=hostCheckRefusal(this.store.get(requestId).assignment,repo,checkId,expectedSpec,excludedPathsAbsent(dir,this.store.get(requestId).assignment));
943
1022
  if(refusal) throw new Error(refusal);
944
1023
  const budgets=parseHostBudget(spec.host_budget);
945
1024
  budgets.wall_ms=Math.min(budgets.wall_ms,spec.timeout_ms??budgets.wall_ms);