@tnunamak/dalan 0.7.0 → 0.8.1

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 (55) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/CONTRIBUTING.md +4 -0
  3. package/PROTOCOL.md +8 -0
  4. package/README.md +68 -28
  5. package/bin/dalan.mjs +1 -1
  6. package/bin/dot-worker.mjs +115 -16
  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 +4 -3
  12. package/docs/pull-workers.md +1 -0
  13. package/docs/relationships.md +13 -0
  14. package/docs/service-setup.md +40 -17
  15. package/docs/setup-reference.md +1 -1
  16. package/docs/t3-integration.md +2 -0
  17. package/docs/t3-question-relationship.md +43 -0
  18. package/docs/t3-reverse-control.md +12 -8
  19. package/docs/t3-wake-fence-r4.md +42 -0
  20. package/docs/test-suite-isolation.md +205 -0
  21. package/docs/usage.md +14 -2
  22. package/docs/worker-clients.md +3 -1
  23. package/package.json +6 -3
  24. package/qualification/README.md +13 -0
  25. package/qualification/mcp.json +121 -0
  26. package/qualification/protocol-v0.json +127 -0
  27. package/src/admin-socket.mjs +2 -1
  28. package/src/answer-journal.mjs +200 -0
  29. package/src/auth-check.mjs +8 -2
  30. package/src/claim-command-ledger.mjs +3 -2
  31. package/src/cli-help.mjs +19 -10
  32. package/src/destinations/index.mjs +6 -0
  33. package/src/destinations/none.mjs +3 -0
  34. package/src/destinations/t3.mjs +63 -6
  35. package/src/execution.mjs +20 -2
  36. package/src/follow-current.mjs +4 -2
  37. package/src/gozar-routes.mjs +4 -3
  38. package/src/host-budget.mjs +17 -11
  39. package/src/host-execution-policy.mjs +2 -2
  40. package/src/host-stop-reverify.mjs +6 -4
  41. package/src/inbox.mjs +13 -3
  42. package/src/integrator.mjs +3 -1
  43. package/src/lifecycle.mjs +60 -2
  44. package/src/patch-apply.mjs +74 -13
  45. package/src/server.mjs +210 -34
  46. package/src/service-launchd.mjs +28 -8
  47. package/src/service-migrate-workers.mjs +12 -2
  48. package/src/service.mjs +52 -16
  49. package/src/status-summary.mjs +3 -0
  50. package/src/store.mjs +300 -34
  51. package/src/submission-policy.mjs +8 -4
  52. package/src/t3.mjs +21 -2
  53. package/src/tool-registry.mjs +54 -8
  54. package/src/workers.mjs +22 -3
  55. package/src/workspace.mjs +94 -15
@@ -391,6 +391,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
391
391
  }
392
392
  }
393
393
  }
394
+ const repositoryImplementation=rendered.execution_scope==='implementation'&&scope.includes('.');
394
395
  const dropped=[];let narrowedScope=null;
395
396
  const firstPass=mentionedPaths(text,scope);
396
397
  for(const file of firstPass) {
@@ -516,10 +517,13 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
516
517
  if(rest.length) error.suggested_scope_paths=rest;
517
518
  throw error;
518
519
  }
519
- // A directory scope can hold a sensitive file the submitter never named. With excludeSensitive those files leave the scope
520
- // (it only narrows) and the reason is recorded; without it the whole submit fails, as before. A path the submitter named
521
- // (a scope entry, a brief mention, a diff file) is never dropped quietly.
520
+ // Repository-wide implementation scopes withhold unnamed sensitive files physically.
521
+ // Other scopes retain the explicit read-only exclusion option. Named paths and patch
522
+ // paths still refuse above and below; exclusions grant no access to those files.
522
523
  for(const file of scan.files.filter(f=>within(f,scope)&&!scope.includes(f))) {
524
+ if(repositoryImplementation&&isSensitiveRepoPath(file,p.sensitive_paths)) {
525
+ dropped.push({path:file,reason:sensitiveReason(file)});continue;
526
+ }
523
527
  try { inspectPath(file); }
524
528
  catch(error) {
525
529
  if(!/^(?:hard sensitive path exclusion|sensitive scope path): /.test(error.message)) throw error;
@@ -535,7 +539,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
535
539
  for(const file of scan.symlinks||[]) if(within(file,scope)&&!scope.includes(file)&&excludeSensitive&&rendered.execution_scope!=='implementation') dropped.push({path:file,reason:'symlink (the workspace never follows symlinks)'});
536
540
  // A scope whose narrowing needs more than maxNarrowedEntries entries is refused (fail closed): keeping the broad scope
537
541
  // would rest on an exact-path exclusion that a case or Unicode alias on a case-insensitive filesystem can miss.
538
- if(dropped.length) narrowedScope=narrowScope(scope,[...new Set([...scan.files,...scan.diffFiles])],dropped.map(d=>d.path));
542
+ if(dropped.length) narrowedScope=repositoryImplementation?scope:narrowScope(scope,[...new Set([...scan.files,...scan.diffFiles])],dropped.map(d=>d.path));
539
543
  for(const file of scan.symlinks||[]) if(within(file,narrowedScope??scope)&&!dropped.some(d=>d.path===file)) throw new Error(`symlink in repository scope: ${file}`);
540
544
  if(input.input_patch) {
541
545
  if(/^new (?:file )?mode 120000$/m.test(input.input_patch)) throw new Error('symlink in input patch scope');
package/src/t3.mjs CHANGED
@@ -179,12 +179,31 @@ export async function inspectThread(threadId, environmentId) {
179
179
  const data=await inspectMetadata(threadId);
180
180
  if (!data?.thread || data.thread.id!==threadId || data.thread.deletedAt ||
181
181
  !environmentId || !data.runtime?.environmentId || data.runtime.environmentId!==environmentId) return {state:'unavailable'};
182
- return classifyThread(data.thread);
182
+ return {...classifyThread(data.thread),generation:threadGeneration(data.thread,data.runtime.environmentId)};
183
+ }
184
+ // T3 has no 'stopped' run status. thread.stop and run.interrupt both leave the latest run 'interrupted', and inspect shows
185
+ // nothing else that tells them apart (measured on T3 4643: docs/t3-wake-fence-r4.md). A wake after either starts a new run.
186
+ // So a latest run in one of these states holds the wake. A held wake over-fences a plain interrupt: it costs a held wake, never a wrong one.
187
+ // A 'failed' run errored on its own, and a wake that restarts it is how a crashed or usage-limited parent resumes, so it is runnable.
188
+ export const runnableRunStatuses=['completed','running','failed'];
189
+ export const heldRunStatuses=['interrupted','cancelled','canceled'];
190
+ // The parent generation: the thread, its environment and the latest run seen in one inspect.
191
+ export const threadGeneration=(thread,environmentId)=>({threadId:thread.id,environmentId,runId:thread.latestRun?.runId??null,ordinal:Number.isInteger(thread.latestRun?.ordinal)?thread.latestRun.ordinal:null});
192
+ // Best-effort check of the generation recorded at submit against the one seen now. It catches a different thread or
193
+ // environment and a thread whose runs went backwards. It cannot see stop-then-resume: that needs a stopSeq from T3.
194
+ export function generationDrift(recorded,current) {
195
+ if(!recorded||!current) return null;
196
+ if(recorded.threadId!==current.threadId||recorded.environmentId!==current.environmentId) return 'parent thread or environment changed since submit';
197
+ if(Number.isInteger(recorded.ordinal)&&(!Number.isInteger(current.ordinal)||current.ordinal<recorded.ordinal)) return `parent runs went back since submit (run ${recorded.ordinal} to ${current.ordinal??'none'})`;
198
+ return null;
183
199
  }
184
200
  export function classifyThread(thread) {
185
201
  if(thread.deletedAt) return {state:'deleted'};
186
202
  if(thread.archivedAt) return {state:'archived'};
187
- if(['stopped','cancelled','canceled','failed'].includes(thread.latestRun?.status)) return {state:'stopped'};
203
+ const runStatus=thread.latestRun?.status;
204
+ if(heldRunStatuses.includes(runStatus)) return {state:'held',reason:`latest run ${runStatus}`};
205
+ // Fail closed: only a status Dalan knows to be runnable lets a wake through. A thread with no run yet has none to check.
206
+ if(thread.latestRun&&!runnableRunStatuses.includes(runStatus)) return {state:'held',reason:`latest run status ${JSON.stringify(runStatus??null)} is not recognized`};
188
207
  if(['stopped','settled','archived','deleted','cancelled','canceled'].includes(thread.status)) return {state:thread.status};
189
208
  if(thread.status==='active') return {state:'active'};
190
209
  return {state:'uncertain_lifecycle'};
@@ -14,7 +14,8 @@ const refuse = (code, message) => { throw new RegistryError(code, message); };
14
14
 
15
15
  const NAME = /^[a-z][a-z0-9_]{0,63}$/;
16
16
  const WORKER = /^[a-z][a-z0-9_-]{0,31}$/;
17
- const RESERVED = new Set(['list_tools', 'call_tool_read', 'call_tool_write']);
17
+ const T3_NAMES = new Set(['t3_thread_list','t3_thread_read','t3_thread_wait','t3_thread_create','t3_thread_send','t3_thread_set']);
18
+ const RESERVED = new Set(['list_tools', 'call_tool_read', 'call_tool_write', ...T3_NAMES]);
18
19
  const FORBIDDEN_KIND = /(delete|overwrite|unlink|truncate|wipe|destroy|remove)/i;
19
20
  const FORBIDDEN_WORD = /^(delete|overwrite|remove|unlink|truncate|wipe|destroy|rm|rmdir|erase|replace)$/i;
20
21
  // The longest a handler may run (the t3-post command timeout), and the lease a pending reservation holds: that timeout plus
@@ -67,7 +68,7 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
67
68
  const toolClass = row => handlers[JSON.parse(row.handler).kind]?.effectClass ?? row.class;
68
69
  const callerHash = (row, worker) => sha256(canonical({
69
70
  name: row.name, description: row.description, input_schema: JSON.parse(row.input_schema), class: toolClass(row), handler: JSON.parse(row.handler),
70
- caller: worker, grants: db.prepare('SELECT tool FROM tool_grants WHERE worker=? ORDER BY tool').all(worker).map(g => g.tool),
71
+ caller: worker, grants: db.prepare('SELECT tool,scope FROM tool_grants WHERE worker=? ORDER BY tool').all(worker),
71
72
  }));
72
73
  // Owner views retain the registration/audit definition hash; only worker views pin caller grants.
73
74
  // Never bind an absent owner caller to the worker-specific SQLite query.
@@ -138,18 +139,21 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
138
139
  record({ kind: enabled ? 'enable' : 'disable', tool: name, outcome: 'ok', schema_hash: row.schema_hash });
139
140
  });
140
141
  }
141
- function grantChange(kind, name, worker) {
142
+ function grantChange(kind, name, worker, scope) {
142
143
  const row = getTool(name);
143
144
  if (!row) refuse('unknown_tool', `tool "${String(name).slice(0, 64)}" is not registered`);
144
145
  if (typeof worker !== 'string' || !WORKER.test(worker)) refuse('invalid_tool', 'worker must be a worker name');
146
+ if(scope !== undefined && scope !== null && (!scope || Object.keys(scope).join() !== 'threads' || !Array.isArray(scope.threads) || scope.threads.some(id=>typeof id!=='string'||!id||id.length>128))) refuse('invalid_tool', 'scope must be {threads: [thread IDs]}');
147
+ if(scope!==undefined && scope!==null && JSON.parse(row.handler).kind!=='t3_control') refuse('invalid_tool','thread scope applies only to T3 control grants');
145
148
  atomically(() => {
146
- if (kind === 'grant') db.prepare('INSERT OR IGNORE INTO tool_grants(tool,worker,granted_at) VALUES(?,?,?)').run(name, worker, iso(now()));
149
+ if (kind === 'grant' && scope === undefined) db.prepare('INSERT OR IGNORE INTO tool_grants(tool,worker,granted_at) VALUES(?,?,?)').run(name,worker,iso(now()));
150
+ else if (kind === 'grant') db.prepare('INSERT INTO tool_grants(tool,worker,granted_at,scope) VALUES(?,?,?,?) ON CONFLICT(tool,worker) DO UPDATE SET scope=excluded.scope').run(name, worker, iso(now()), scope===null?null:JSON.stringify(scope));
147
151
  else { db.prepare('DELETE FROM tool_grants WHERE tool=? AND worker=?').run(name, worker); dropQueued(name, worker); }
148
152
  bump();
149
153
  record({ kind, tool: name, worker, outcome: 'ok', schema_hash: row.schema_hash });
150
154
  });
151
155
  }
152
- const grant = (name, worker) => grantChange('grant', name, worker);
156
+ const grant = (name, worker, scope) => grantChange('grant', name, worker, scope);
153
157
  const revoke = (name, worker) => grantChange('revoke', name, worker);
154
158
 
155
159
  function list() {
@@ -161,7 +165,7 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
161
165
  }
162
166
  function listTools(worker) {
163
167
  const name = workerName(worker);
164
- const tools = typeof name !== 'string' ? [] : db.prepare('SELECT t.* FROM registered_tools t JOIN tool_grants g ON g.tool=t.name WHERE g.worker=? AND t.enabled=1 ORDER BY t.name').all(name).map(row => view(row, name));
168
+ const tools = typeof name !== 'string' ? [] : db.prepare("SELECT t.* FROM registered_tools t JOIN tool_grants g ON g.tool=t.name WHERE g.worker=? AND t.enabled=1 AND json_extract(t.handler,'$.kind')!='t3_control' ORDER BY t.name").all(name).map(row => view(row, name));
165
169
  return { registry_version: registryVersion(), tools };
166
170
  }
167
171
  function lastChange() {
@@ -227,7 +231,7 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
227
231
  done('replay_unfinished', new RegistryError('in_progress', `an earlier call with this idempotency_key is in progress; retry later with the same key in about ${seconds} s`));
228
232
  };
229
233
  const unavailable = outcome => done(outcome, new RegistryError('tool_unavailable', 'tool unavailable'));
230
- if (!row) unavailable('unknown_tool');
234
+ if (!row || JSON.parse(row.handler).kind==='t3_control') unavailable('unknown_tool');
231
235
  if (typeof name !== 'string' || !db.prepare('SELECT 1 FROM tool_grants WHERE tool=? AND worker=?').get(row.name, name)) unavailable('not_granted');
232
236
  if (row.enabled !== 1) unavailable('disabled');
233
237
  if (callClass !== toolClass(row)) done('wrong_class', new RegistryError('wrong_class', 'wrong class for this tool; see list_tools'));
@@ -299,7 +303,49 @@ export function createToolRegistry({ store, now = Date.now, handlers = {}, audit
299
303
  return { ok: true, result: capped };
300
304
  }
301
305
 
302
- return { register, remove, grant, revoke, list, listTools, registryVersion, callTool, setEnabled, lastChange };
306
+ // Internal registrations share the existing grant/revoke/enable policy, but are never dispatch tools.
307
+ // Provision a worker once: restarting must not restore a revoked grant.
308
+ function initializeT3Grants(names, workers) {
309
+ atomically(()=>{
310
+ // Older registries allowed these names. Never turn an ordinary tool into an
311
+ // implicit grant while upgrading; leave it untouched for operator resolution.
312
+ for(const name of names) {
313
+ if(!T3_NAMES.has(name)) refuse('invalid_tool','unknown T3 authority tool');
314
+ const existing=getTool(name);
315
+ if(existing && JSON.parse(existing.handler).kind!=='t3_control') refuse('reserved_tool_conflict',`registered tool ${name} conflicts with T3 authority; remove or rename it before enabling T3 tools`);
316
+ }
317
+ for(const name of names) {
318
+ const definition={name,description:'Job-scoped T3 authority',input_schema:{type:'object',properties:{},additionalProperties:false},
319
+ class:['t3_thread_list','t3_thread_read','t3_thread_wait'].includes(name)?'read':'write',handler:{kind:'t3_control'}};
320
+ db.prepare(`INSERT OR IGNORE INTO registered_tools(name,description,input_schema,class,handler,schema_hash,created_at)
321
+ VALUES(?,?,?,?,?,?,?)`).run(name,definition.description,JSON.stringify(definition.input_schema),definition.class,JSON.stringify(definition.handler),schemaHash(definition),iso(now()));
322
+ }
323
+ for(const worker of workers) {
324
+ const key=`t3_initialized:${worker}`;
325
+ if(db.prepare('SELECT 1 FROM tool_registry_meta WHERE key=?').get(key)) continue;
326
+ for(const name of names) grant(name,worker);
327
+ db.prepare('INSERT INTO tool_registry_meta(key,value) VALUES(?,1)').run(key);
328
+ }
329
+ });
330
+ }
331
+ function t3Threads(tool, principal) {
332
+ // The legacy local principal also resolves to a worker; it has no owner bypass.
333
+ const row=db.prepare("SELECT g.scope FROM tool_grants g JOIN registered_tools t ON t.name=g.tool WHERE g.tool=? AND g.worker=? AND t.enabled=1 AND json_extract(t.handler,'$.kind')='t3_control'").get(tool,principal.worker);
334
+ if(!row) refuse('tool_unavailable','tool unavailable');
335
+ const scope=row.scope===null?null:JSON.parse(row.scope);
336
+ if(scope!==null&&(!Array.isArray(scope.threads)||Object.keys(scope).join()!=='threads')) refuse('tool_unavailable','tool unavailable');
337
+ const threads=new Set();
338
+ for(const claim of db.prepare(`SELECT c.*,a.delivery FROM claims c JOIN assignments a USING(request_id)
339
+ WHERE c.worker=? AND c.subject=? AND c.state='active' AND a.status='claimed'`).all(principal.worker,principal.subject)) {
340
+ if(store.leaseExpired(claim)||!claim.delivery?.startsWith('t3:')) continue;
341
+ try { store.assertWorkerConnection(claim.request_id,claim.claim_id,principal.subject,principal.worker,principal.builtin?(principal.connection_id??''):null); }
342
+ catch { continue; }
343
+ const thread=claim.delivery.slice(3);
344
+ if(scope===null||scope.threads.includes(thread)) threads.add(thread);
345
+ }
346
+ return threads;
347
+ }
348
+ return { register, remove, grant, revoke, list, listTools, registryVersion, callTool, setEnabled, lastChange, initializeT3Grants, t3Threads };
303
349
  }
304
350
 
305
351
  // ---- t3_post: the owner_message handler ----------------------------------------------------------------------------
package/src/workers.mjs CHANGED
@@ -6,12 +6,29 @@ import path from 'node:path';
6
6
  import { randomUUID, createHash } from 'node:crypto';
7
7
  import { DatabaseSync } from 'node:sqlite';
8
8
  import { writeAtomic } from './as-files.mjs';
9
- import { parseExecution } from './execution.mjs';
9
+ import { parseExecution, ADAPTER_QUALIFICATIONS } from './execution.mjs';
10
10
 
11
11
  const fail=message=>{throw new Error(`workers: ${message}`);};
12
12
  const object=(v,keys)=>{if(!v||typeof v!=='object'||Array.isArray(v)||Object.keys(v).some(k=>!keys.includes(k))) fail(`expected object with keys ${keys.join(', ')}`);};
13
13
  const text=v=>{if(typeof v!=='string'||!v||v.length>2048) fail('connection fields must be non-empty strings');return v;};
14
14
  const legacyWorker={connections:[],capabilities:new Set(['t3']),guidance:'resume'};
15
+ // Enrollment never revives an ended relationship. A new relationship requires an explicit future transition.
16
+ export function ensureWorkerRelationship(db,worker,pattern='outbound_only') {
17
+ db.prepare(`INSERT INTO relationships(relationship_id,my_roles,counterpart_ref,pattern,continuity,onward,created_at)
18
+ SELECT ?,?,?,?,?,?,? WHERE NOT EXISTS (SELECT 1 FROM relationships WHERE counterpart_ref=?)`)
19
+ .run(`rel_${randomUUID()}`,JSON.stringify(['requester']),worker,pattern,'unknown','none',new Date().toISOString(),worker);
20
+ }
21
+ // finish_handoff: true | {wait_ms}. A finishing worker is handed its next job in the reply, or waits up to wait_ms for one.
22
+ // ChatGPT documents no tool-call timeout and users report about 60 s, so the wait stays well below that.
23
+ export const FINISH_HANDOFF_WAIT_MS=20000, FINISH_HANDOFF_MAX_WAIT_MS=45000;
24
+ function parseFinishHandoff(value,name) {
25
+ if(value===undefined||value===false) return null;
26
+ if(value===true) return {waitMs:FINISH_HANDOFF_WAIT_MS};
27
+ object(value,['wait_ms']);
28
+ const waitMs=value.wait_ms===undefined?FINISH_HANDOFF_WAIT_MS:value.wait_ms;
29
+ if(!Number.isInteger(waitMs)||waitMs<0||waitMs>FINISH_HANDOFF_MAX_WAIT_MS) fail(`${name}.finish_handoff.wait_ms must be an integer from 0 to ${FINISH_HANDOFF_MAX_WAIT_MS}`);
30
+ return {waitMs};
31
+ }
15
32
  const repoPart=/^[A-Za-z0-9_.-]+$/;
16
33
  function validRepoName(repo) {
17
34
  if(typeof repo!=='string'||repo.split('/').length!==2) return false;
@@ -62,7 +79,9 @@ export function parseWorkers(value,{builtin=false,builtinConnectionIds}={}) {
62
79
  if(name==='pool'||name==='unknown') fail(`worker name "${name}" is reserved and unsupported`);
63
80
  if(!/^[a-z][a-z0-9_-]{0,31}$/.test(name)) fail('invalid worker name');
64
81
  if(Object.hasOwn(config??{},'pool')) fail(`${name}.pool is not supported`);
65
- object(config,['connections','capabilities','guidance','repos','repo_access','denied_repos','destination','workspaceAllowed']);
82
+ object(config,['connections','capabilities','guidance','repos','repo_access','denied_repos','destination','workspaceAllowed','adapter','finish_handoff']);
83
+ const finishHandoff=parseFinishHandoff(config.finish_handoff,name);
84
+ if(Object.hasOwn(config,'adapter')&&(typeof config.adapter!=='string'||!Object.hasOwn(ADAPTER_QUALIFICATIONS,config.adapter))) fail(`${name}.adapter must name a qualified adapter: ${Object.keys(ADAPTER_QUALIFICATIONS).join(', ')}`);
66
85
  const repoSettings=normalizeRepoSettings(config,name);
67
86
  if(config.guidance!==undefined&&config.guidance!=='resume') fail(`${name}.guidance may only be "resume"`);
68
87
  if(builtin&&config.connections!==undefined&&!(Array.isArray(config.connections)&&!config.connections.length)) fail(`${name}.connections must be absent in built-in mode; connections are recorded by dalan connect approve`);
@@ -81,7 +100,7 @@ export function parseWorkers(value,{builtin=false,builtinConnectionIds}={}) {
81
100
  if(config.workspaceAllowed!==undefined&&typeof config.workspaceAllowed!=='boolean') fail(`${name}.workspaceAllowed must be boolean`);
82
101
  const caps=config.capabilities??[];
83
102
  if(!Array.isArray(caps)||caps.some(c=>c!=='t3')) fail('capabilities may only contain t3');
84
- workers.set(name,{connections,capabilities:new Set(caps),...(config.workspaceAllowed!==undefined?{workspaceAllowed:config.workspaceAllowed}:{}),...(config.guidance?{guidance:config.guidance}:{}),...repoSettings,
103
+ workers.set(name,{connections,capabilities:new Set(caps),...(config.adapter!==undefined?{adapter:config.adapter}:{}),...(config.workspaceAllowed!==undefined?{workspaceAllowed:config.workspaceAllowed}:{}),...(config.guidance?{guidance:config.guidance}:{}),...(finishHandoff?{finishHandoff}:{}),...repoSettings,
85
104
  ...(Object.hasOwn(config,'destination')?{destination:parseDestinationDeclaration(config.destination)}:{})});
86
105
  }
87
106
  if(!workers.size) fail('workers must not be empty');
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);