@tnunamak/dalan 0.8.5 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.mjs CHANGED
@@ -25,7 +25,7 @@ import { sendWebhook, validSecret } from './webhooks.mjs';
25
25
  import { checkAlerts, publishAlert, redactNote } from './alerts.mjs';
26
26
  import { redactOutput, redactSinkText, redactLogEntry, registerSecret } from './redaction.mjs';
27
27
  import { isCrash, safeDiagnostic } from './diagnostic.mjs';
28
- import { Workspace, NOT_IDENTIFIED } from './workspace.mjs';
28
+ import { Workspace, NOT_IDENTIFIED, pinnedScopedSource, SCOPED_SOURCE_MAX_BYTES } from './workspace.mjs';
29
29
  import { captureOwnerReportArtifact } from './owner-report-artifact.mjs';
30
30
  import { loadBackgroundMaxInFlight, loadMainThreadIds, t3ReadToolsOff } from './limits.mjs';
31
31
  import { parseDelivery } from './delivery.mjs';
@@ -39,7 +39,7 @@ import { assertNoDeclaredConsumer, unprovenSource } from './consumers.mjs';
39
39
  import { preflightPR } from './pr-preflight.mjs';
40
40
  import { admitImplementation } from './check-readiness.mjs';
41
41
  import { parseExecution, parseRequiredCapabilities, admitHostExecution, admitAdapterCapabilities, ADAPTER_CAPABILITY_NAMES, withEvidence } from './execution.mjs';
42
- import { loadCapacity } from './projects.mjs';
42
+ import { assignmentInput, loadCapacity } from './projects.mjs';
43
43
  import { authConfig, assertPublicRouteAuth, isLoopbackBindHost, protectedResource, challenge, verifyBearer, needScope } from './auth.mjs';
44
44
  import { beginMcpOutcome, recordMcpResponse, pathShape, uaToken } from './mcp-outcome.mjs';
45
45
  import { lifecycleMetrics, retainLifecycle, controlScopeText } from './lifecycle.mjs';
@@ -146,11 +146,12 @@ if(legacyProfile&&!existingInstall&&!explicitLegacy) {
146
146
  console.error(`dalan: startup: no worker is configured (${workersFile} is missing); run \`dalan init --worker NAME\` to create one, or \`dalan init --legacy\` (or set DALAN_LEGACY_PROFILE=1) to keep the single-worker legacy profile`);
147
147
  process.exit(1);
148
148
  }
149
+ let quiescing=false;
149
150
  const store = new Store(path.join(dataDir, 'bridge.db'),{
150
151
  // The caller sees one fixed configuration error; the real one stays in this server's log.
151
152
  onConfigError:error=>log({kind:'destination_configuration_error',reason:inspect(error,CONFIG_ERROR_INSPECT)}),
152
153
  workers,destinationProfile:currentRepoPolicy,allowedDotSubjects:externalOauth?externalOauth.OAUTH_ALLOWED_SUBJECTS.split(','):['local-principal'],
153
- limits:redeliveryLimits,
154
+ limits:redeliveryLimits,admissionOpen:()=>!quiescing,
154
155
  ...(process.env.CONFORMANCE_CLOCK_FILE?{elapsedNow:Date.now,bootId:'conformance-clock'}:{}),
155
156
  skipExpireMs:(h=>Number.isFinite(h)&&h>0?h*3600000:undefined)(Number(readEnv('DALAN_SKIP_EXPIRE_HOURS'))),
156
157
  // Intentional service startup opts past Store's accidental-migration footgun guard.
@@ -177,12 +178,96 @@ const absentId=`req_${randomUUID()}`;
177
178
  if(store.hasAssignment(absentId)) throw new Error('absent gate id collision');
178
179
  const log = createRequestLog(path.join(stateDir, 'requests.jsonl'));
179
180
  const guardArtifactDownload = createArtifactDownloadGuard({log});
181
+ const scopedSourceChunk=18*1024;
180
182
  const phaseTrace = createPhaseTrace({ log });
181
183
  logShutdownSignals(log);
182
184
  // Registry definitions are discovered through list_tools. The native tools/list stays fixed.
185
+ // The job owns repository, pin and path policy. A grant pins those stored values without copying them.
186
+ const scopedInputIdentity = row => createHash('sha256')
187
+ .update(JSON.stringify([row.assignment, row.claim.epoch])).digest('hex');
183
188
  const t3PostHandler=createT3PostHandler({store,now:()=>store.nowMs()});
184
189
  const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
185
190
  t3_post:t3PostHandler,
191
+ scoped_input_artifact:{
192
+ effectClass:'read',
193
+ requireCurrentRead:true,
194
+ validateConfig(_config,{name}) {
195
+ if(name!==scopedInputRegistration.name) throw new RegistryError('invalid_tool','unknown scoped input tool');
196
+ },
197
+ prepareGrant({worker,scope}) {
198
+ const keys = Object.keys(scope).sort().join();
199
+ if (keys !== 'claim_id,expires_at,request_id')
200
+ throw new RegistryError('invalid_tool','scoped input grant requires request_id, claim_id and expires_at');
201
+ const requestId=id(scope.request_id),claimId=id(scope.claim_id,'claim_id');
202
+ const row=store.get(requestId);
203
+ const expires=typeof scope.expires_at==='string' ? Date.parse(scope.expires_at) : NaN;
204
+ if (row.status!=='claimed'||row.cancelled_at||!row.claim)
205
+ throw new RegistryError('invalid_tool','scoped input grant requires a live assignment claim');
206
+ const claim=store.assertClaim(requestId,claimId,row.claim.subject,worker);
207
+ store.assertMutationConnection(requestId,claim,claim.connection_id??null);
208
+ if (!Number.isFinite(expires)||expires<=store.nowMs()||expires>store.leaseDeadlineClockMs(claim))
209
+ throw new RegistryError('invalid_tool','scoped input grant expiry must be within the current claim lease');
210
+ const {inputs,scope_paths,execution_scope,paged_read_scope}=row.assignment;
211
+ const input=inputs?.[0];
212
+ if (execution_scope!=='read-only'||paged_read_scope||inputs?.length!==1||!input?.github_repo||
213
+ !/^[a-f0-9]{40}$/.test(input.base_sha??'')||(input.head_sha&&input.head_sha!==input.base_sha)||
214
+ !scope_paths?.length||scope_paths.includes('.'))
215
+ throw new RegistryError('invalid_tool','scoped input grant requires a pinned read-only assignment with explicit paths');
216
+ assertRepoAllowed(worker,row.assignment);
217
+ return {request_id:requestId,claim_id:claimId,expires_at:new Date(expires).toISOString(),assignment_digest:scopedInputIdentity(row)};
218
+ },
219
+ authorizeGrant(scope,args) {
220
+ if (scope.request_id!==args?.request_id||scope.claim_id!==args?.claim_id) return false;
221
+ try {
222
+ const row=store.get(scope.request_id);
223
+ return scope.assignment_digest===scopedInputIdentity(row);
224
+ } catch { return false; }
225
+ },
226
+ authorizeReplay({args,context}) {
227
+ const {worker,subject,builtin,connection_id}=context,connection=builtin?(connection_id??''):null;
228
+ const requestId=id(args.request_id),claimId=id(args.claim_id,'claim_id');
229
+ try {
230
+ if(!store.mayAct(worker,requestId)) throw new Error('assignment not found');
231
+ store.assertProtocolAvailable(requestId);
232
+ const row=store.get(requestId);
233
+ if(row.status!=='claimed'||row.cancelled_at) throw new Error('assignment is not claimed');
234
+ const claim=store.assertClaim(requestId,claimId,subject,worker);
235
+ store.assertMutationConnection(requestId,claim,connection);
236
+ if(row.assignment.paged_read_scope===true) throw new Error('paged read scope does not support artifacts');
237
+ if(!workspaceEnabled||!workerWorkspaceAllowed(worker,requestId)) throw new Error('capability_not_enabled');
238
+ assertRepoAllowed(worker,row.assignment);
239
+ return [requestId,claim.claim_id,claim.epoch,subject,connection];
240
+ } catch(error) { throw assignmentRegistryRefusal(error); }
241
+ },
242
+ run({args,context:{worker,subject},grantScope}) {
243
+ const requestId=id(args.request_id),claimId=id(args.claim_id,'claim_id');
244
+ const offset=args.offset??0;
245
+ if(offset%scopedSourceChunk!==0||(offset!==0&&!args.sha256)) throw new RegistryError('invalid_arguments','invalid scoped input offset');
246
+ try {
247
+ const {a,input,mirror}=workspace.context(requestId,claimId,subject,false,worker);
248
+ if(input.head_sha&&input.head_sha!==input.base_sha) throw new Error('scoped input requires the reviewed revision to match the base');
249
+ const {manifest,blobs}=pinnedScopedSource(mirror,a.assignment);
250
+ if(grantScope && manifest.files.some(file=>!a.assignment.scope_paths.includes(file.path)))
251
+ throw new Error('assignment grant requires exact scoped files');
252
+ if(!manifest.files.length) throw new Error('no approved scoped input files');
253
+ const files=manifest.files.map(file=>{
254
+ const bytes=blobs.get(file.path);
255
+ guardArtifactDownload({bytes,sha256:file.sha256,id:'scoped-input-file',requestId});
256
+ return {...file,data_base64:bytes.toString('base64')};
257
+ });
258
+ const bytes=Buffer.from(JSON.stringify({...manifest,files}));
259
+ if(bytes.length>SCOPED_SOURCE_MAX_BYTES) throw new Error('scoped input exceeds the download limit; use a smaller scope');
260
+ const hash=createHash('sha256').update(bytes).digest('hex');
261
+ guardArtifactDownload({bytes,sha256:hash,id:'scoped-input',requestId});
262
+ if(args.sha256!==undefined&&args.sha256!==hash) throw new Error('scoped input changed');
263
+ if(offset>=bytes.length) throw new Error('invalid scoped input offset');
264
+ const end=Math.min(offset+scopedSourceChunk,bytes.length);
265
+ const result={sha256:hash,size:bytes.length,offset,next_offset:end===bytes.length?null:end,data_base64:bytes.subarray(offset,end).toString('base64')};
266
+ if(JSON.stringify(redactOutput(result))!==JSON.stringify(result)) throw new Error('scoped input encoding refused');
267
+ return result;
268
+ } catch(error) { throw assignmentRegistryRefusal(error); }
269
+ },
270
+ },
186
271
  worker_refusal:{
187
272
  effectClass:'write',
188
273
  validateConfig(_config,{name}) {
@@ -321,6 +406,17 @@ function withAvailableChecks(response,workerSurface=false,worker='dot',subject=n
321
406
  // Worker-written text in an owner read is masked on the way out. The database keeps the exact text, so a retried finish
322
407
  // with the same body stays the same finish.
323
408
  const maskText=value=>typeof value==='string'?redactOutput(value):value;
409
+ function repositoryReadScope(assignment) {
410
+ if(assignment?.execution_scope!=='read-only'||(!Array.isArray(assignment.read_paths)&&assignment.paged_read_scope!==true)||!assignment.scope_paths?.length) return {};
411
+ // Older stored requests can predate pinned-input validation. Do not claim a verified scope for those rows.
412
+ let input;
413
+ try { input=assignmentInput(assignment); } catch { return {}; }
414
+ const {github_repo,base_sha,head_sha,input_patch}=input;
415
+ const scope=assignment.paged_read_scope===true
416
+ ?{file_count:assignment.scope_paths.length,paged:true}
417
+ :{scope_paths:assignment.scope_paths};
418
+ return {repository_scope:{github_repo,base_sha,...(head_sha?{head_sha}:{}),...scope,...(input_patch?{includes_local_patch:true}:{})}};
419
+ }
324
420
  function maskedForOwner(response) {
325
421
  const out={...response};
326
422
  if(out.report) out.report={...out.report,summary:maskText(out.report.summary),result:maskText(out.report.result)};
@@ -513,6 +609,13 @@ const scopeFor=name=>t3ReadTools.has(name)||readTools.has(name)?'dalan.read':'da
513
609
  // Same name mapping as the protected-resource metadata and the 401 challenge, so all three surfaces agree.
514
610
  const advertisedScope=name=>wireScope(scopeFor(name),legacyScopeNames(oauth));
515
611
  if(oauth) for(const item of tools) item.securitySchemes=[{type:'oauth2',scopes:[advertisedScope(item.name)]}];
612
+ // Existing clients may still report these fields. Keep the frozen discovery schemas stable.
613
+ const advertisedTools=['stable','legacy-v46'].includes(catalogProfile)?tools.map(tool=>{
614
+ if(tool.name!=='finish') return tool;
615
+ const properties=Object.fromEntries(Object.entries(tool.inputSchema.properties)
616
+ .filter(([field])=>!['runs','session','run_limit'].includes(field)));
617
+ return {...tool,inputSchema:{...tool.inputSchema,properties}};
618
+ }):tools;
516
619
  // During an update, refuse a changed catalog before either listener can expose it.
517
620
  const catalogGuardFile=path.join(configDir,'service-catalog.json');
518
621
  if(fs.existsSync(catalogGuardFile)) {
@@ -521,7 +624,7 @@ if(fs.existsSync(catalogGuardFile)) {
521
624
  const guard=JSON.parse(fs.readFileSync(catalogGuardFile,'utf8'));
522
625
  const normalize=value=>Array.isArray(value)?value.map(normalize):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(key=>[key,normalize(value[key])])):value;
523
626
  const ordered=catalogs=>Object.fromEntries(Object.keys(catalogs).sort().map(worker=>[worker,[...catalogs[worker]].sort((a,b)=>a.name.localeCompare(b.name))]));
524
- const actual=Object.fromEntries([...workers.workers.keys()].map(worker=>[worker,catalogProfile==='legacy-v46'?tools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,worker,'t3')):tools]));
627
+ const actual=Object.fromEntries([...workers.workers.keys()].map(worker=>[worker,catalogProfile==='legacy-v46'?advertisedTools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,worker,'t3')):advertisedTools]));
525
628
  if(guard.version!==packageVersion||JSON.stringify(normalize(ordered(guard.catalogs??{})))!==JSON.stringify(normalize(ordered(actual))))throw new Error('service catalog guard mismatch');
526
629
  }
527
630
  const refusalRegistration={
@@ -534,9 +637,15 @@ const refusalRegistration={
534
637
  const refusalFinish={inputSchema:schema({
535
638
  ...refusalRegistration.inputSchema.properties,result:message,summary:message,outcome:{type:'string',enum:[PROVIDER_REFUSAL]},
536
639
  },['request_id','claim_id','result','outcome'])};
640
+ const scopedInputRegistration={
641
+ name:'fetch_scoped_input',
642
+ description:'Read the approved pinned files for this live assignment. Concatenate decoded data_base64 chunks until next_offset is null. For later calls pass that offset and the first sha256. Verify the assembled artifact hash before using the files. Omit idempotency_key.',
643
+ class:'read',handler:{kind:'scoped_input_artifact'},
644
+ inputSchema:schema({request_id:string,claim_id:string,offset:{type:'integer',minimum:0,maximum:SCOPED_SOURCE_MAX_BYTES},sha256:hashField},['request_id','claim_id']),
645
+ };
537
646
  if(toolNames.has('list_tools')) {
538
647
  const specs=[...questionDefinitions.map(definition=>({...definition,class:'write',handler:{kind:'worker_question'}})),refusalRegistration];
539
- for(const name of toolRegistry.initializeWorkerTools(specs,workers.workers.keys()))
648
+ for(const name of [...toolRegistry.initializeWorkerTools(specs,workers.workers.keys()),...toolRegistry.initializeWorkerTools([scopedInputRegistration],[])])
540
649
  log({kind:'worker_tool_registration_conflict',tool:name});
541
650
  }
542
651
  function assignmentRegistryRefusal(error) {
@@ -623,8 +732,8 @@ function breakWaitReply(breakId,requestIds,note) {
623
732
  request_ids:requestIds,artifact_ids:[],...store.breakForecast(breakId)};
624
733
  }
625
734
  function activeBreakWait(row) {
626
- if(row?.target_worker!=='dot'||!['queued','claimed'].includes(row.status)) return null;
627
- const active=store.holdingBreak();
735
+ if(!row||!['queued','claimed'].includes(row.status)) return null;
736
+ const active=store.holdingBreak(row.target_worker??'dot');
628
737
  return active?breakWaitReply(active.id,[row.request_id],'The worker is on a usage break.'):null;
629
738
  }
630
739
  function waitSummary(requestId, attention=null) {
@@ -773,23 +882,40 @@ async function attachWaiter(req,res,requestId,timeoutMs,consume=true) {
773
882
  waiters.set(requestId,waiter);
774
883
  notifyAttachedWaiter(requestId);
775
884
  }
885
+ function logPendingReply(reply,{worker,subject},callId,batch={}) {
886
+ log({kind:'list_pending_result',call_id:callId,worker,subject,free_lanes:reply.free_lanes,claims_accepted:reply.claims_accepted,
887
+ total:reply.assignments.length,request_ids:reply.assignments.slice(0,20).map(item=>item.request_id),...batch});
888
+ }
889
+
776
890
  // Put the next acquisition before job detail, including after progress and finish.
777
891
  // Derive it after the call (and any finish handoff) so it describes remaining capacity.
778
- function batchCapacityReply(name,reply,principal) {
779
- if(!batchClaimProfile||!['list_pending','claim','progress','finish'].includes(name)) return reply;
892
+ function batchCapacityReply(name,reply,principal,callId) {
893
+ if(!['list_pending','claim','progress','finish'].includes(name)) return reply;
894
+ const recordListing=name==='list_pending'&&!!callId;
895
+ if(!batchClaimProfile) {
896
+ if(recordListing) logPendingReply(reply,principal,callId);
897
+ return reply;
898
+ }
780
899
  const {worker,subject}=principal;
781
- const {free_lanes}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
782
- const ready_queued=store.listPending(worker,{batch:true}).filter(item=>!item.blocked).length;
900
+ const {free_lanes,ready,available,reservedId}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
901
+ const ready_queued=ready.length;
783
902
  const hint=store.claimHint(worker);
784
- const hintFree=hint===null?Infinity:Math.max(0,hint-store.recentClaimCount(worker));
785
- const next=Math.min(free_lanes,ready_queued,8,hintFree);
786
- const next_action=quiescing?restartQuiesceText:store.paused()?'Claims are paused; call list_pending again later.':
787
- next>0?`claim with next=${next} now`:
788
- free_lanes===0?'Continue held work and finish one before claiming more.':
789
- ready_queued>0&&hintFree===0?'Lanes are free but the claim hint is full; claim again when the hint allows more.':
790
- 'No ready queued work; call list_pending again later.';
903
+ const hintFree=hint===null?Infinity:Math.max(Number(!!reservedId),hint-store.recentClaimCount(worker));
904
+ const next=Math.min(available,ready_queued,8,hintFree);
905
+ const [reason,next_action]=quiescing?['quiescing',restartQuiesceText]:
906
+ store.paused()?['paused','Claims are paused; call list_pending again later.']:
907
+ next>0?['ready',`claim with next=${next} now`]:
908
+ available===0?['lanes_full','Continue held work and finish one before claiming more.']:
909
+ ready_queued>0&&hintFree===0?['hint_full','Lanes are free but the claim hint is full; claim again when the hint allows more.']:
910
+ ['no_ready_work','No ready queued work; call list_pending again later.'];
791
911
  const {next_action:previousAction,free_lanes:previousFree,...rest}=reply;
792
- return {next_action,free_lanes,ready_queued,...rest};
912
+ const response={next_action,free_lanes,ready_queued,...rest};
913
+ if(recordListing) {
914
+ const recommended=reason==='ready'?next:0;
915
+ logPendingReply(response,principal,callId,{ready_queued,dispatch_reason:reason,recommended_claims:recommended,
916
+ ready_head_ids:ready.slice(0,recommended).map(item=>item.request_id)});
917
+ }
918
+ return response;
793
919
  }
794
920
  // Result guidance only; tool descriptions stay fixed.
795
921
  const batchGuidance='Follow next_action for any additional acquisition; use a fresh acquisition_id for each new batch.';
@@ -1050,7 +1176,7 @@ async function submitPolicy(body,req,dryRun) {
1050
1176
  return {...result,execution,excluded_workers:excludedWorkers};
1051
1177
  }
1052
1178
 
1053
- let quiescing=false,admittedInFlight=0;
1179
+ let admittedInFlight=0;
1054
1180
  const restartQuiesceText='bridge_quiescing: bridge paused for a restart; retry after it reopens.';
1055
1181
  function quiesceStatus() {
1056
1182
  return {on:quiescing,admitted_in_flight:admittedInFlight,delivery_in_flight:delivering?1:0,...store.quiesceCounts()};
@@ -1197,24 +1323,24 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1197
1323
  catch(e) { if(e instanceof RegistryError) throw new Error(e.message.startsWith(e.code)?e.message:`${e.code}: ${e.message}`); throw e; }
1198
1324
  }
1199
1325
  case 'list_pending': {
1200
- const {free_lanes,worker_max_claims}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1326
+ const {free_lanes,worker_max_claims,reserved_request_id}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1201
1327
  const assignments=store.listPending(worker);
1202
- store.recordListed(assignments,free_lanes,worker,!quiescing);
1328
+ store.recordListed(assignments,free_lanes+Number(!!reserved_request_id),worker,!quiescing);
1203
1329
  phaseTrace.listed(assignments.map(x=>x.request_id));
1204
- log({kind:'list_pending_result',subject,free_lanes,total:assignments.length,request_ids:assignments.slice(0,20).map(x=>x.request_id)});
1205
1330
  const hint=store.claimHint(worker),baseGuidance=hint===null?listGuidance:hintGuidance(hint);
1206
1331
  const guidance=workers.workers.get(worker)?.guidance==='resume'?`${baseGuidance} ${resumeNudge(store.resumeIdleMs()||undefined)}`:baseGuidance;
1207
1332
  // Say outright whether a claim would be accepted now: a worker that once saw a pause refusal must not keep listing without claiming.
1208
1333
  const claims_accepted=!quiescing&&!store.paused();
1209
- const next=claims_accepted?store.nextQueued(free_lanes,null,worker):{};
1334
+ const next=claims_accepted?store.nextQueued(free_lanes,null,worker,{reservedId:reserved_request_id??null}):{};
1210
1335
  const claimsNote=claims_accepted?'':quiescing?restartQuiesceText:'Claims are paused (temporary): do not claim now; call list_pending again later and claim once claims_accepted is true.';
1211
- return {assignments,policy_work:policyPage(worker),attention:store.attention(subject,worker),free_lanes,...(worker_max_claims===undefined?{}:{worker_max_claims}),claims_accepted,...(claims_accepted?next:{next_action:claimsNote}),guidance};
1336
+ return {assignments,policy_work:policyPage(worker),attention:store.attention(subject,worker),free_lanes,...(worker_max_claims===undefined?{}:{worker_max_claims}),claims_accepted,...(claims_accepted&&reserved_request_id?{reserved_request_id}:{}),...(claims_accepted?next:{next_action:claimsNote}),guidance};
1212
1337
  }
1213
1338
  case 'claim': {
1214
1339
  if(Object.hasOwn(a,'next')) {
1215
1340
  const claimant=str(a.claimant,'claimant',128);
1216
1341
  const lanes=()=>store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity).free_lanes;
1217
- const {claims,retry}=await store.claimBatch({next:a.next,available:lanes(),worker,subject,connectionId,claimant,acquisitionId:a.acquisition_id,leaseMs:a.lease_ms},
1342
+ const {available}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1343
+ const {claims,retry}=await store.claimBatch({next:a.next,available,worker,subject,connectionId,claimant,acquisitionId:a.acquisition_id,leaseMs:a.lease_ms},
1218
1344
  (request_id,acquisition_id,mode)=>signal?.aborted?null:tool('claim',{request_id,claimant,acquisition_id,...(a.lease_ms===undefined?{}:{lease_ms:a.lease_ms})},principal,undefined,signal,mode));
1219
1345
  return {claims,...(retry?{retry:true}:{}),free_lanes:lanes()};
1220
1346
  }
@@ -1245,8 +1371,8 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1245
1371
  const claimed=store.claim(requestId,claimant,subject,claimCapacity,preflight,worker,a.acquisition_id,a.lease_ms,ctx,principal.builtin?(principal.connection_id??''):null,batchMode);
1246
1372
  const grant=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
1247
1373
  if(!retry) phaseTrace.claimed({requestId,worker,subject,claimId:claimed.claim_id,handoff:String(a.acquisition_id??'').startsWith(HANDOFF_ACQUISITION_PREFIX),createdAt:store.db.prepare('SELECT created_at FROM assignments WHERE request_id=?').get(requestId)?.created_at});
1248
- const {free_lanes,queued}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1249
- return withAvailableChecks({...claimed,lease_expires_at:claimed.lease_expires_at??store.leaseExpiresAt(grant),queued_after_claim:queued,free_lanes,...store.nextQueued(free_lanes,requestId,worker),guidance:`${claimed.guidance} ${store.claimHint(worker)===null?(batchClaimProfile?claimMoreGuidance:plainClaimGuidance(free_lanes,queued)):hintMoreGuidance(store.claimHint(worker))}`},true,worker,subject,workspaceAllowed);
1374
+ const {free_lanes,queued,reserved_request_id}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1375
+ return withAvailableChecks({...claimed,lease_expires_at:claimed.lease_expires_at??store.leaseExpiresAt(grant),queued_after_claim:queued,free_lanes,...store.nextQueued(free_lanes,requestId,worker,{reservedId:reserved_request_id??null}),guidance:`${claimed.guidance} ${store.claimHint(worker)===null?(batchClaimProfile?claimMoreGuidance:plainClaimGuidance(free_lanes,queued)):hintMoreGuidance(store.claimHint(worker))}`},true,worker,subject,workspaceAllowed);
1250
1376
  }
1251
1377
  case 'renew_claim': {
1252
1378
  if(!strictJob) throw new Error('renew_claim requires a protocol job');
@@ -1286,12 +1412,15 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1286
1412
  store.assertFinishClaim(requestId,claimId,subject,worker);
1287
1413
  // A replaced or revoked connection learns connection_not_live before any question or artifact error. Read-only; expired and foreign claims return early.
1288
1414
  workspaceFence();
1415
+ store.applyFacadeWithdrawal(requestId);
1289
1416
  const existing=store.db.prepare('SELECT 1 FROM reports WHERE request_id=?').get(requestId);
1290
1417
  let captureEvidence=null;
1291
1418
  const workerRuns=parseWorkerRuns(a.runs,a.run_limit,redactOutput), workerSession=parseWorkerSession(a.session,store.nowMs());
1292
1419
  if(!existing) {
1293
1420
  store.assertQuestionsResolved(requestId,claimId,a.outcome);
1294
1421
  const request=store.get(requestId);
1422
+ const pagedRead=request.assignment.paged_read_scope===true;
1423
+ if(pagedRead&&a.artifact_ids?.length) throw new Error('paged read scope does not support artifacts');
1295
1424
  const needsWorkspace=workspaceEnabled&&(a.artifact_ids?.length||request.assignment.execution_scope==='implementation'||request.assignment.output_paths?.length);
1296
1425
  const assignmentNeedsWorkspace=request.assignment.execution_scope==='implementation'||request.assignment.output_paths?.length;
1297
1426
  const requiredWorkspaceEvidence=!!(a.artifact_ids?.length||request.assignment.output_paths?.length);
@@ -1313,7 +1442,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1313
1442
  if(workerWorkspaceEnabled&&request.status==='claimed'&&a.outcome==='completed') { await workspace.checkBeforeFinish(requestId,claimId,subject,worker);workspaceFence(); }
1314
1443
  if(workerWorkspaceEnabled&&request.status==='claimed'&&(request.assignment.execution_scope==='implementation'||request.assignment.output_paths?.length))
1315
1444
  captureEvidence=onRollback=>workspace.snapshotInTransaction(requestId,claimId,subject,worker,onRollback);
1316
- if(request.status==='claimed'&&request.assignment.execution_scope==='read-only') {
1445
+ if(!pagedRead&&request.status==='claimed'&&request.assignment.execution_scope==='read-only') {
1317
1446
  const archiveWorkspace=workspace??new Workspace(store,false),snapshot=captureEvidence;
1318
1447
  captureEvidence=onRollback=>{
1319
1448
  const base=snapshot?snapshot(onRollback):null;
@@ -1322,7 +1451,13 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1322
1451
  };
1323
1452
  }
1324
1453
  }
1325
- if(!existing) { store.recordWorkerRuns(requestId,claimId,workerRuns);store.recordWorkerSession(worker,subject,workerSession); }
1454
+ if(!existing) {
1455
+ const capture=captureEvidence;
1456
+ captureEvidence=onRollback=>{
1457
+ store.recordWorkerRuns(requestId,claimId,workerRuns);store.recordWorkerSession(worker,subject,workerSession);
1458
+ return capture?.(onRollback)??null;
1459
+ };
1460
+ }
1326
1461
  const receipt=store.finish(requestId,claimId,a.outcome,str(a.summary,'summary',4096),str(a.result,'result',256*1024),subject,null,worker,commandContext('finish',{artifact_ids:a.artifact_ids??[]}),captureEvidence,connectionId);
1327
1462
  if(receipt.deferred) return {...receipt,...repaired.marks};
1328
1463
  if(crashAt('after_report_persistence',a.request_id)) process.exit(73);
@@ -1391,7 +1526,7 @@ function publicErrorText(error,what) {
1391
1526
  log({kind:'request_error',what,error_id:errorId,detail:safeDiagnostic(error?.stack??error,4000)});
1392
1527
  return `Error executing ${what} (error id ${errorId}; details are in the request log)`;
1393
1528
  }
1394
- async function dispatch(message,principal,signal) {
1529
+ async function dispatch(message,principal,signal,callId) {
1395
1530
  const p=message.params??{};
1396
1531
  switch(message.method) {
1397
1532
  case 'server/discover': return {ttlMs:0,cacheScope:'private',supportedVersions:['2026-07-28'],capabilities:{tools:{},events:{}},_meta:{'io.modelcontextprotocol/serverInfo':serverInfo}};
@@ -1399,8 +1534,8 @@ async function dispatch(message,principal,signal) {
1399
1534
  case 'ping': return {};
1400
1535
  // Modern catalogs are process-wide. A worker's capability controls tools/call authority, not its cached schemas.
1401
1536
  // legacy-v46 keeps its pinned per-worker surface for compatibility.
1402
- case 'tools/list': return {ttlMs:0,cacheScope:'private',tools:catalogProfile==='legacy-v46'?tools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,principal.worker,'t3')):tools};
1403
- case 'tools/call': { try { return {content:[{type:'text',text:JSON.stringify(redactOutput(batchCapacityReply(p.name,await tool(p.name,p.arguments??{},principal,notifyTools.has(p.name)?p._meta:undefined,signal),principal)))}],isError:false}; } catch(e) { const error={content:[{type:'text',text:publicErrorText(e,`tool ${toolNames.has(p.name)?p.name:'unknown'}`)}],isError:true};if(oauth&&e.message==='insufficient_scope')error._meta={'mcp/www_authenticate':[[challenge(oauth,scopeFor(p.name)),'error="insufficient_scope"','error_description="Required scope is missing"'].join(', ')]};return error; } }
1537
+ case 'tools/list': return {ttlMs:0,cacheScope:'private',tools:catalogProfile==='legacy-v46'?advertisedTools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,principal.worker,'t3')):advertisedTools};
1538
+ case 'tools/call': { try { return {content:[{type:'text',text:JSON.stringify(redactOutput(batchCapacityReply(p.name,await tool(p.name,p.arguments??{},principal,notifyTools.has(p.name)?p._meta:undefined,signal),principal,callId)))}],isError:false}; } catch(e) { const error={content:[{type:'text',text:publicErrorText(e,`tool ${toolNames.has(p.name)?p.name:'unknown'}`)}],isError:true};if(oauth&&e.message==='insufficient_scope')error._meta={'mcp/www_authenticate':[[challenge(oauth,scopeFor(p.name)),'error="insufficient_scope"','error_description="Required scope is missing"'].join(', ')]};return error; } }
1404
1539
  case 'events/list': return {events:[event]};
1405
1540
  case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
1406
1541
  case 'events/unsubscribe': { if(oauth)needScope(principal,'dalan.read');if(!validEventParams(p)) throw new Error('invalid subscription'); store.unsubscribe(subId(p.delivery.url,principal.subject,principal.worker)); return {}; }
@@ -1446,7 +1581,7 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
1446
1581
  const eventStream=readEnv('DALAN_TRIAL_SSE')==='1'&&req.method==='POST'&&acceptsMcpEventStream(req.headers.accept)?beginMcpEventStream(res):null;
1447
1582
  // A tool that waits (finish with finish_handoff) stops when the client leaves, so nothing is claimed for nobody.
1448
1583
  const clientGone=new AbortController();res.once('close',()=>clientGone.abort());if(res.destroyed)clientGone.abort();
1449
- try { json(res,200,{jsonrpc:'2.0',id:rpc.id,result:{resultType:'complete',...await dispatch(rpc,principal,clientGone.signal)}},eventStream); }
1584
+ try { json(res,200,{jsonrpc:'2.0',id:rpc.id,result:{resultType:'complete',...await dispatch(rpc,principal,clientGone.signal,outcome.state.call_id)}},eventStream); }
1450
1585
  catch(e) { json(res,200,rpcError(rpc.id,e.code||-32602,publicErrorText(e,'request'),e.data),eventStream); }
1451
1586
  // Response-byte accounting for the throttle and the break ledger; the response is already written, so a failure only logs.
1452
1587
  if(outcome.state.tool) try { store.recordResponseBytes(principal.subject,outcome.state.tool,outcome.state.response_bytes,principal.worker); } catch(e) { log({kind:'response_bytes_error',call_id:outcome.state.call_id,reason:e.message}); }
@@ -1488,7 +1623,7 @@ const adminServer=http.createServer(async(req,res)=>{
1488
1623
  if(body.assignment?.request_id===absentId) throw new Error('invalid assignment');
1489
1624
  const commandKey=body.command_key===undefined?null:body.command_key;
1490
1625
  const supersedes=body.supersedes===undefined?null:body.supersedes;
1491
- // {prior_id, prior_token}: this job corrects that one. Shape and authority are checked by the Store, in the submit transaction.
1626
+ // The Store checks correction authority before preview, and again in the submit transaction.
1492
1627
  const revises=body.revises===undefined?null:body.revises;
1493
1628
  const follows=body.follows===undefined?null:body.follows;
1494
1629
  const destinationRevision=body.destination_revision??null;
@@ -1534,6 +1669,7 @@ const adminServer=http.createServer(async(req,res)=>{
1534
1669
  const dryRun=url.pathname==='/submit-preview';
1535
1670
  if(body.dry_run!==undefined&&typeof body.dry_run!=='boolean') throw new Error('invalid dry_run');
1536
1671
  if(body.assignment&&Object.hasOwn(body.assignment,'scope_excluded')) throw new Error('assignment declares scope_excluded; only the bridge records what it dropped from a scope');
1672
+ if(body.assignment&&Object.hasOwn(body.assignment,'paged_read_scope')) throw new Error('only the bridge can record a paged read scope');
1537
1673
  const declaredSource=body.meta?.source??'agent';
1538
1674
  for(const [value,label] of [[body,'submit request'],[body.meta,'meta'],[body.assignment,'assignment']]) assertNoDeclaredConsumer(value,label,declaredSource);
1539
1675
  const meta=normalizeMeta(body.meta);
@@ -1561,18 +1697,32 @@ const adminServer=http.createServer(async(req,res)=>{
1561
1697
  // Reject immutable retry conflicts using the persisted binding before any external destination inspection.
1562
1698
  // A matching retry still validates the current destination below; this does not accept stale environment evidence.
1563
1699
  store.checkRetry(submitted,delivery,existingRequest?.environment_id,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises,follows,body.caller_waiting);
1700
+ const assignedWorker=storedTarget??target??'dot';
1701
+ const requiredAdapterCapabilities=jobExecution==='host'
1702
+ ?requiredCapabilities?.filter(name=>ADAPTER_CAPABILITY_NAMES.includes(name))
1703
+ :requiredCapabilities;
1704
+ const admitWorkerAdapter=()=>{
1705
+ const adapter=workers.workers.get(assignedWorker)?.adapter;
1706
+ const registryQuestions=adapter==='registry-questions-v1'&&requiredAdapterCapabilities?.includes('identified_questions')
1707
+ &&toolRegistry.hasWorkerTools(assignedWorker,questionDefinitions,{kind:'worker_question'});
1708
+ admitAdapterCapabilities(adapter,requiredAdapterCapabilities,catalogProfile,{registryQuestions});
1709
+ };
1564
1710
  let order=null;
1565
1711
  if(isNew) {
1712
+ // checkRetry has already verified the prior owner's capability and the active worker.
1713
+ const priorAssignment=revises?.require_active_prior===true?store.get(revises.prior_id).assignment:null;
1714
+ const inheritedExclusions=priorAssignment?.scope_excluded;
1566
1715
  order=await compileWorkOrder({assignment:payload,review:body.review===true,priority:body.background===true?'background':'normal',jobExecution,requiredCapabilities,meta,maxQueued:body.max_queued??null,deferQueued:body.defer_queued??null,
1567
1716
  excludeSensitive:body.exclude_sensitive===true,sensitiveScopeOverride:body.sensitive_scope_override??null,target:target??'dot'},{
1568
1717
  render:renderAssignment,
1569
1718
  admitExecution:(p,r)=>{
1570
- const adapterRequired=r.jobExecution==='host'?r.requiredCapabilities?.filter(name=>ADAPTER_CAPABILITY_NAMES.includes(name)):r.requiredCapabilities;
1571
- admitAdapterCapabilities(workers.workers.get(storedTarget??target??'dot')?.adapter,adapterRequired,catalogProfile);
1719
+ admitWorkerAdapter();
1572
1720
  // No usable executor, or a required capability the backend does not declare verified: never degraded to a run without it.
1573
1721
  if(r.jobExecution==='host'&&(p.execution_scope==='implementation'||r.requiredCapabilities)) admitHostExecution(r.requiredCapabilities?.filter(name=>!ADAPTER_CAPABILITY_NAMES.includes(name)));
1574
1722
  },
1575
- validate:(p,{warnings})=>validateSubmissionAsync(p,{sensitiveScopeOverride:body.sensitive_scope_override??null,warnings,excludeSensitive:body.exclude_sensitive===true,review:body.review===true,worker:storedTarget??target??'dot'}),
1723
+ validate:(p,{warnings})=>validateSubmissionAsync(p,{sensitiveScopeOverride:body.sensitive_scope_override??null,warnings,excludeSensitive:body.exclude_sensitive===true,review:body.review===true,worker:storedTarget??target??'dot',inheritedExclusions,
1724
+ allowPagedReadScope:workspaceEnabled&&jobExecution==='none'&&!p.protocol,
1725
+ pagedReadPrior:priorAssignment?.paged_read_scope===true?priorAssignment:null}),
1576
1726
  admitReadiness:p=>{
1577
1727
  if(p.execution_scope!=='implementation') return null;
1578
1728
  const readiness=admitImplementation(p,{execution:jobExecution,worker:storedTarget??target??'dot'});
@@ -1581,7 +1731,7 @@ const adminServer=http.createServer(async(req,res)=>{
1581
1731
  },
1582
1732
  preflight:p=>preflightPR(p),
1583
1733
  // Advisory only, like Store.submit: a supersede target leaves the queued count unchanged. Store.submit rechecks it in its transaction.
1584
- state:r=>({paused:store.paused(),pause_reason:store.db.prepare('SELECT reason FROM operator_state WHERE id=1').get().reason,worker_break:(r.target==='dot'?store.holdingBreak():null),queued:store.db.prepare("SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND (valid_until IS NULL OR valid_until>?)").get(r.target,supersedes?.target_id??null,new Date(store.nowMs()).toISOString()).n,queued_same_priority:store.db.prepare("SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND priority=? AND (?=0 OR caller_waiting=1) AND request_id IS NOT ? AND (valid_until IS NULL OR valid_until>?)").get(r.target,body.background===true?'background':'normal',body.caller_waiting===true?1:0,supersedes?.target_id??null,new Date(store.nowMs()).toISOString()).n}),
1734
+ state:r=>({paused:store.paused(),pause_reason:store.db.prepare('SELECT reason FROM operator_state WHERE id=1').get().reason,worker_break:store.holdingBreak(r.target),queued:store.db.prepare("SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND (valid_until IS NULL OR valid_until>?)").get(r.target,supersedes?.target_id??null,new Date(store.nowMs()).toISOString()).n,queued_same_priority:store.db.prepare("SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND priority=? AND (?=0 OR caller_waiting=1) AND request_id IS NOT ? AND (valid_until IS NULL OR valid_until>?)").get(r.target,body.background===true?'background':'normal',body.caller_waiting===true?1:0,supersedes?.target_id??null,new Date(store.nowMs()).toISOString()).n}),
1585
1735
  kind:(r,p)=>r.meta?.task_kind??(r.review?'review':p.execution_scope??'unknown'),
1586
1736
  defaultValidity:(kind,r)=>store.defaultValidUntil(r.target,kind),
1587
1737
  retryAfterSeconds:r=>{const w=store.queueWaitsMs(r.target,r.meta?.task_kind??(r.review?'review':'unknown'));return w.length?Math.min(3600,Math.max(60,Math.round(w[Math.floor(w.length/2)]/1000))):300;},
@@ -1597,7 +1747,8 @@ const adminServer=http.createServer(async(req,res)=>{
1597
1747
  const disclosure=isNew?store.destinationSnapshot(target??'dot',jobExecution,payload):existingRequest.destination_approval?.snapshot??null;
1598
1748
  if(dryRun) {
1599
1749
  log({kind:'submit_dry_run',request_id:submitted.request_id,task_kind:meta.task_kind??null,source:meta.source??null,verdict:order?.verdict??'admissible',reason_codes:(order?.reasons??[]).map(r=>r.code),attempt_latency_ms:Date.now()-requestStartedAt});
1600
- return json(res,200,{dry_run:true,request_id:submitted.request_id,stored:false,...(payload?{admission:admission()}:{}),...(disclosure?{destination_disclosure:disclosure}:{}),...(order??{verdict:'admissible',reasons:[],duplicate:true}),...(order?.warnings?.length?{submission_warnings:order.warnings}:{})});
1750
+ const scope=!order||order.verdict==='admissible'?repositoryReadScope(existingRequest?.assignment??payload):{};
1751
+ return json(res,200,{dry_run:true,request_id:submitted.request_id,stored:false,...(payload?{admission:admission()}:{}),...(disclosure?{destination_disclosure:disclosure}:{}),...(order??{verdict:'admissible',reasons:[],duplicate:true}),...scope,...(order?.warnings?.length?{submission_warnings:order.warnings}:{})});
1601
1752
  }
1602
1753
  // Defer refuses only for a requester that opts in; both the CLI and HTTP API queue by default.
1603
1754
  if(order?.verdict==='defer'&&body.refuse_defer===true&&body.queue_anyway!==true) {
@@ -1608,6 +1759,15 @@ const adminServer=http.createServer(async(req,res)=>{
1608
1759
  const readiness=order?.check_readiness??null;
1609
1760
  const preflight=order?.preflight??null;
1610
1761
  const defaultValidity=order?.defaultValidity??null;
1762
+ // I/O can outlive a grant or an overlapping submit. Store.submit checks the immutable identity of any replay.
1763
+ if(!store.hasAssignment(payload.request_id)) {
1764
+ if(body.facade_submit_until!==undefined) {
1765
+ const until=body.facade_submit_until;
1766
+ if(!Number.isSafeInteger(until)||until>requestStartedAt+600_000) throw new Error('invalid facade submission deadline');
1767
+ if(until<=store.nowMs()) throw new Error('facade submission deadline expired');
1768
+ }
1769
+ admitWorkerAdapter();
1770
+ }
1611
1771
  const result=store.submit(payload,delivery,environmentId,owner,body.review===true,preflight,body.background===true?'background':'normal',meta,(()=>{const r=renderAssignment(submitted);return payload.brief!==r.brief||JSON.stringify(payload.scope_paths)!==JSON.stringify(r.scope_paths);})()?submitted:payload,body.max_queued??null,target,explicitExecution,workers.defaultExecution,requiredCapabilities,defaultValidity?.valid_until??null,commandKey,supersedes,destinationRevision,null,generation??null,body.relationship_id??null,revises,follows,body.caller_waiting);
1612
1772
  // Only a committed first replacement wakes the TARGET's already-attached waiter.
1613
1773
  if(supersedes&&!result.duplicate) {
@@ -1618,7 +1778,8 @@ const adminServer=http.createServer(async(req,res)=>{
1618
1778
  // A retry validates nothing, so the narrowing it reports comes from the stored assignment.
1619
1779
  const stored=result.duplicate?JSON.parse(store.db.prepare('SELECT payload FROM assignments WHERE request_id=?').get(payload.request_id).payload):payload;
1620
1780
  if(stored.scope_excluded?.length&&!result.duplicate) log({kind:'scope_excluded',request_id:payload.request_id,excluded:stored.scope_excluded});
1621
- return json(res,200,{...result,admission:admission(),execution:store.db.prepare('SELECT execution FROM assignments WHERE request_id=?').get(payload.request_id).execution,...(stored.scope_excluded?.length?{scope_excluded:stored.scope_excluded,scope_paths:stored.scope_paths}:{}),...(readiness?{check_readiness:readiness}:{}),...(submissionWarnings.length?{submission_warnings:submissionWarnings}:{})});
1781
+ const observedAdmission=store.admissionForQueuedRequest(payload.request_id)??admission();
1782
+ return json(res,200,{...result,admission:observedAdmission,execution:store.db.prepare('SELECT execution FROM assignments WHERE request_id=?').get(payload.request_id).execution,...repositoryReadScope(stored),...(stored.scope_excluded?.length?{scope_excluded:stored.scope_excluded,scope_paths:stored.scope_paths}:{}),...(readiness?{check_readiness:readiness}:{}),...(submissionWarnings.length?{submission_warnings:submissionWarnings}:{})});
1622
1783
  }
1623
1784
  if(url.pathname==='/admission'&&req.method==='GET') { const requestId=id(url.searchParams.get('id'));const row=store.db.prepare('SELECT cancelled_reason FROM assignments WHERE request_id=?').get(requestId)??store.pullQueue.row(requestId); return json(res,200,{exists:!!row,...(row?.cancelled_reason==='expired'?{cancelled_reason:'expired'}:{})}); }
1624
1785
  if(url.pathname==='/get') {
@@ -1630,6 +1791,7 @@ const adminServer=http.createServer(async(req,res)=>{
1630
1791
  store.recordFetched(requestId);
1631
1792
  // Read before recording consumption: the response then matches a peek read, which records no consumption.
1632
1793
  const got=maskedForOwner(withAvailableChecks(store.get(requestId)));
1794
+ Object.assign(got,repositoryReadScope(got.assignment));
1633
1795
  if(req.method==='GET'&&url.searchParams.get('admission')==='1'&&got.status==='queued') {
1634
1796
  const snapshot=store.admissionForQueuedRequest(requestId);
1635
1797
  if(snapshot) got.admission=snapshot;
@@ -1647,6 +1809,7 @@ const adminServer=http.createServer(async(req,res)=>{
1647
1809
  const row=store.db.prepare('SELECT request_id FROM artifacts WHERE id=? AND sealed=1').get(artifactId);
1648
1810
  if(!row) throw new Error('artifact not found');
1649
1811
  adminOwner(req,row.request_id);
1812
+ if(store.get(row.request_id).assignment.paged_read_scope===true) throw new Error('paged read scope does not support artifacts');
1650
1813
  const artifact=(workspace||new Workspace(store,false)).artifact(artifactId,row.request_id);
1651
1814
  try {
1652
1815
  guardArtifactDownload({id:artifactId,requestId:row.request_id,sha256:artifact.row.sha256,bytes:artifact.bytes});
@@ -1690,9 +1853,9 @@ const adminServer=http.createServer(async(req,res)=>{
1690
1853
  const states=body.items.map(item=>{
1691
1854
  const requestId=id(item?.id);
1692
1855
  try { store.owner(requestId,item.capability); } catch { return {request_id:requestId,error:'not_owned'}; }
1693
- const row=store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(requestId)??(store.pullQueue.row(requestId)?store.get(requestId):null);
1856
+ const row=store.db.prepare('SELECT status,target_worker FROM assignments WHERE request_id=?').get(requestId)??(store.pullQueue.row(requestId)?store.get(requestId):null);
1694
1857
  const blockers=store.db.prepare('SELECT note FROM progress WHERE request_id=? ORDER BY id').all(requestId).map(p=>p.note).filter(note=>/^\s*(?:BLOCKED:|QUESTION:)/im.test(note));
1695
- return {request_id:requestId,status:row.status,blocker_count:blockers.length,last_blocker:blockers.at(-1)??null,inbox:store.ownerInbox(requestId)};
1858
+ return {request_id:requestId,status:row.status,worker_break:!!activeBreakWait({...row,request_id:requestId}),blocker_count:blockers.length,last_blocker:blockers.at(-1)??null,inbox:store.ownerInbox(requestId)};
1696
1859
  });
1697
1860
  // Only evidence holds refill: a pause or an owner-confirmed break. throttled stays false for older readers.
1698
1861
  const paused=store.paused(), dotBreak=!!store.holdingBreak();
@@ -1710,7 +1873,7 @@ const adminServer=http.createServer(async(req,res)=>{
1710
1873
  if(action==='revoke') { toolRegistry.revoke(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:false}); }
1711
1874
  } catch(error) { if(error instanceof RegistryError) throw new Error(`${error.code}: ${error.message}`); throw error; }
1712
1875
  }
1713
- if(url.pathname==='/status') return json(res,200,{last_registry_change:toolRegistry.lastChange(),default_worker:workers.legacy ? 'dot' : workers.workers.size === 1 ? [...workers.workers.keys()][0] : null,...store.status({limits:redeliveryLimits,capacity:claimCapacity,backgroundMaxInFlight}),max_claimed_outer_assignments:claimCapacity,worker_lane_capacity:redeliveryLimits.laneCapacity,background_max_in_flight:backgroundMaxInFlight,owner_waiter_count:waiters.size+[...terminalWaiters.values()].reduce((sum,count)=>sum+count,0),loopback_probe:loopbackProbe?.snapshot()??null});
1876
+ if(url.pathname==='/status') return json(res,200,{last_registry_change:toolRegistry.lastChange(),default_worker:workers.legacy ? 'dot' : workers.workers.size === 1 ? [...workers.workers.keys()][0] : null,...store.status({limits:redeliveryLimits,capacity:claimCapacity,backgroundMaxInFlight}),max_claimed_outer_assignments:claimCapacity,worker_lane_capacity:redeliveryLimits.laneCapacity,background_max_in_flight:backgroundMaxInFlight,version:packageVersion,owner_waiter_count:waiters.size+[...terminalWaiters.values()].reduce((sum,count)=>sum+count,0),loopback_probe:loopbackProbe?.snapshot()??null});
1714
1877
  if(url.pathname==='/metrics'&&req.method==='GET') return json(res,200,lifecycleMetrics(store,{since:url.searchParams.get('since'),laneCapacity:redeliveryLimits.laneCapacity}));
1715
1878
  if(['/accept','/reject'].includes(url.pathname)&&req.method==='POST') {
1716
1879
  const requestId=id(body.id); adminOwner(req,requestId);
@@ -1741,7 +1904,14 @@ const adminServer=http.createServer(async(req,res)=>{
1741
1904
  if(url.pathname==='/note'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId); return json(res,200,store.note(requestId,body.text)); }
1742
1905
  if(url.pathname==='/answer'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId);const questionId=str(body.question_id,'question_id',128); requireOperatorForHumanQuestion(req,requestId,questionId);return json(res,200,store.answerQuestion(requestId,questionId,str(body.text,'text',4096),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability'])); }
1743
1906
  if(url.pathname==='/questions'&&req.method==='GET') { const requestId=id(url.searchParams.get('id'));adminOwner(req,requestId);return json(res,200,{request_id:requestId,questions:store.questions(requestId)}); }
1744
- if(url.pathname==='/tell'&&req.method==='POST') return json(res,200,store.tell(str(body.text,'text',4096),body.worker===undefined&&workers.workers.has('dot')?'dot':submitTarget(workers,body.worker)??assertTarget(workers,'dot')));
1907
+ if(url.pathname==='/tell'&&req.method==='POST') {
1908
+ const text=str(body.text,'text',4096);
1909
+ if(body.request_id!==undefined) {
1910
+ const worker=body.worker===undefined?null:assertTarget(workers,body.worker);
1911
+ return json(res,200,store.tell(text,worker,{requestId:id(body.request_id),capability:req.headers['x-owner-capability']}));
1912
+ }
1913
+ return json(res,200,store.tell(text,body.worker===undefined&&workers.workers.has('dot')?'dot':submitTarget(workers,body.worker)??assertTarget(workers,'dot')));
1914
+ }
1745
1915
  if(url.pathname==='/untell'&&req.method==='POST') return json(res,200,store.untell(id(body.message_id,'message_id'),body.worker===undefined?null:assertTarget(workers,body.worker)));
1746
1916
  if(url.pathname==='/relationships'&&req.method==='GET') { adminOperator(req); return json(res,200,{relationships:store.db.prepare('SELECT * FROM relationships ORDER BY created_at, rowid').all()}); }
1747
1917
  if(url.pathname==='/relationships/publish'&&req.method==='POST') {
@@ -1760,7 +1930,7 @@ const adminServer=http.createServer(async(req,res)=>{
1760
1930
  const currentWorkers=loadEffectiveOwnerWorkers(workersFile);
1761
1931
  const grants=[
1762
1932
  ...store.db.prepare("SELECT c.*,a.relationship_id FROM claims c JOIN assignments a USING(request_id) WHERE c.state='active' AND a.status='claimed'").all().filter(row=>!store.leaseExpired(row)).map(row=>({request_id:row.request_id,worker:row.worker,relationship_id:row.relationship_id,expires_at:store.leaseExpiresAt(row),enforcer:'claim_lease'})),
1763
- ...store.db.prepare('SELECT g.tool,g.worker,g.granted_at,g.scope FROM tool_grants g JOIN registered_tools t ON t.name=g.tool WHERE t.enabled=1').all().map(row=>({...row,scope:row.scope===null?null:JSON.parse(row.scope),enforcer:'tool_registry',expires_at:null})),
1933
+ ...toolRegistry.listGrants().map(row=>({...row,enforcer:'tool_registry'})),
1764
1934
  ...store.db.prepare('SELECT d.request_id,d.revision,d.approved_at,a.relationship_id FROM destination_approvals d JOIN assignments a USING(request_id)').all().map(row=>({...row,enforcer:'destination_approval',expires_at:null})),
1765
1935
  ...store.activeSubscriptions().map(({id,principal,worker,expires_at})=>({id,principal,worker,expires_at,enforcer:'subscription'})),
1766
1936
  ...store.db.prepare('SELECT request_id,relationship_id FROM assignments WHERE owner_hash IS NOT NULL').all().filter(row=>store.protocolListingLive(row.request_id)).map(row=>({...row,enforcer:'owner_capability',expires_at:store.getProtocol(row.request_id)?new Date(store.getProtocol(row.request_id).retain_until_ms).toISOString():null})),
@@ -1813,7 +1983,7 @@ const adminServer=http.createServer(async(req,res)=>{
1813
1983
  if(req.method==='POST') {
1814
1984
  if(typeof body.on!=='boolean')return json(res,400,{error:'on must be a boolean'});
1815
1985
  // Clear the old eligibility at entry too: an interrupted quiesce may never receive an off call.
1816
- if(body.on!==quiescing) store.restartSkipClock();
1986
+ if(body.on!==quiescing) store.restartSkipClock({releaseReservations:body.on});
1817
1987
  quiescing=body.on;
1818
1988
  }
1819
1989
  return json(res,200,quiesceStatus());
@@ -1826,6 +1996,28 @@ const adminServer=http.createServer(async(req,res)=>{
1826
1996
  runDrain();
1827
1997
  return json(res,200,{...result,scope:controlScopeText('detach',{ref:`claim:${result.abandoned.claim_id}@${result.abandoned.epoch}`})});
1828
1998
  }
1999
+ if(url.pathname==='/cancel-grace'&&req.method==='POST') {
2000
+ const requestId=id(body.id);
2001
+ const intent=id(body.intent,'intent');
2002
+ if(body.before_admission===true&&!store.hasAssignment(requestId)&&!store.pullQueue.row(requestId)&&['arm','keep','state'].includes(body.action)) {
2003
+ const token=str(req.headers['x-owner-capability'],'owner capability',128);
2004
+ if(token.length<32) throw new Error('invalid owner capability');
2005
+ return json(res,200,store.facadeWithdrawalBeforeAdmission(requestId,intent,body.action,token));
2006
+ }
2007
+ adminOwner(req,requestId);
2008
+ if(body.action==='arm') return json(res,200,store.armFacadeWithdrawal(requestId,intent));
2009
+ if(body.action==='keep') return json(res,200,store.keepFacadeWork(requestId,intent));
2010
+ if(body.action==='state') return json(res,200,{kept:!!store.facadeKeepReceipt(requestId,intent)});
2011
+ if(body.action==='settle') {
2012
+ const kept=!!store.facadeKeepReceipt(requestId,intent);
2013
+ const pending=!!store.db.prepare('SELECT 1 FROM facade_withdrawals WHERE request_id=? AND intent=?').get(requestId,intent);
2014
+ if(pending) store.applyFacadeWithdrawal(requestId);
2015
+ const status=store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(requestId)?.status;
2016
+ if(status==='cancelled') notifyAttachedWaiter(requestId);
2017
+ return json(res,200,{kept,pending,status});
2018
+ }
2019
+ throw new Error('invalid cancellation grace action');
2020
+ }
1829
2021
  if(url.pathname==='/cancel') {
1830
2022
  const requestId=id(body.id); adminOwner(req,requestId);
1831
2023
  // Read before the cancel: the scope text depends on whether a worker held the job.
@@ -1840,7 +2032,8 @@ const adminServer=http.createServer(async(req,res)=>{
1840
2032
  }
1841
2033
  if(url.pathname==='/break'&&req.method==='POST') {
1842
2034
  adminOperator(req);
1843
- if(body.clear===true) { const cleared=store.clearBreak(); sweepExpired(); return json(res,200,cleared); }
2035
+ const worker=body.worker===undefined?'dot':assertTarget(workers,body.worker);
2036
+ if(body.clear===true) { const cleared=store.clearBreak(worker); sweepExpired(); return json(res,200,cleared); }
1844
2037
  const time=field=>{
1845
2038
  const value=body[field];
1846
2039
  if(value==null) return value;
@@ -1848,7 +2041,7 @@ const adminServer=http.createServer(async(req,res)=>{
1848
2041
  throw new Error(`${field} must be an RFC 3339 time with offset`);
1849
2042
  return new Date(value).toISOString();
1850
2043
  };
1851
- const result=store.setBreak(str(body.reason,'reason',512),time('since'),time('until'));
2044
+ const result=store.setBreak(str(body.reason,'reason',512),time('since'),time('until'),worker);
1852
2045
  log({kind:'worker_break_set',source:'owner',since:result.since});
1853
2046
  return json(res,200,result);
1854
2047
  }
@@ -1858,7 +2051,11 @@ const adminServer=http.createServer(async(req,res)=>{
1858
2051
  adminOperator(req); if(body.clear!==true) throw new Error('learned accepts only {clear:true}');
1859
2052
  const result=store.clearLearnedLimits(); log({kind:'learned_limits_cleared',source:'owner',removed:result.removed}); return json(res,200,result);
1860
2053
  }
1861
- if(url.pathname==='/breaks'&&req.method==='GET') { adminOperator(req); return json(res,200,{worker_break:store.breakState(),breaks:store.breaks()}); }
2054
+ if(url.pathname==='/breaks'&&req.method==='GET') {
2055
+ adminOperator(req);
2056
+ const worker=url.searchParams.has('worker')?assertTarget(workers,url.searchParams.get('worker')):'dot';
2057
+ return json(res,200,{worker_break:store.breakState(worker),breaks:worker==='dot'?store.breaks():store.scopedBreaks(worker)});
2058
+ }
1862
2059
  if(url.pathname==='/verify-stops'&&req.method==='POST') {
1863
2060
  adminOperator(req);
1864
2061
  const requestId=body.id===undefined?undefined:id(body.id);
@@ -2012,6 +2209,13 @@ async function drain() {
2012
2209
  }
2013
2210
  function maintain() {
2014
2211
  try {
2212
+ for(const requestId of store.dueFacadeWithdrawals()) {
2213
+ try {
2214
+ if(!store.applyFacadeWithdrawal(requestId)) continue;
2215
+ const waiter=waiters.get(requestId);
2216
+ if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); }
2217
+ } catch(error) { log({kind:'facade_withdrawal_error',request_id:requestId,reason:error.message}); }
2218
+ }
2015
2219
  sweepExpired();
2016
2220
  sweepSkipped();
2017
2221
  sweepStaleLeases();