@tnunamak/dalan 0.8.1 → 0.8.3

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 (124) hide show
  1. package/CHANGELOG.md +61 -2
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +8 -12
  4. package/bin/dalan.mjs +25 -4
  5. package/bin/dot-acp-agent.mjs +572 -76
  6. package/bin/dot-alert.mjs +9 -3
  7. package/bin/dot-deadman.mjs +3 -1
  8. package/bin/dot-heartbeat.mjs +14 -7
  9. package/bin/dot-pr-reviewer.mjs +3 -31
  10. package/bin/dot-worker.mjs +121 -34
  11. package/contracts/adapter-qualification.schema.json +94 -7
  12. package/docs/chatgpt-worker-onboarding.md +1 -1
  13. package/docs/codex-to-muse.md +2 -2
  14. package/docs/connect-chatgpt.md +1 -1
  15. package/docs/connection-longevity.md +2 -2
  16. package/docs/dalan-upgrade.md +8 -5
  17. package/docs/deadman.md +4 -0
  18. package/docs/design/authority-matrix.md +18 -0
  19. package/docs/design/failure-table.md +87 -0
  20. package/docs/design/identities.md +22 -0
  21. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  22. package/docs/design/reuse-ledger.md +75 -0
  23. package/docs/design/target-architecture-v2.md +434 -0
  24. package/docs/local-agent-mcp.md +14 -0
  25. package/docs/local-agent-requester.md +2 -1
  26. package/docs/manual-setup.md +1 -1
  27. package/docs/operations.md +77 -14
  28. package/docs/pull-workers.md +11 -1
  29. package/docs/service-setup.md +10 -10
  30. package/docs/t3-integration.md +4 -2
  31. package/docs/t3-reverse-control.md +5 -5
  32. package/docs/test-suite-isolation.md +7 -6
  33. package/docs/trials/chatgpt-agent.md +47 -0
  34. package/docs/trials/claude-code-requester.md +68 -0
  35. package/docs/trials/muse.md +46 -0
  36. package/docs/usage.md +21 -7
  37. package/docs/worker-clients.md +1 -1
  38. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  39. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  40. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  41. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  42. package/package.json +4 -3
  43. package/packages/job-core/protocol/canonical.mjs +45 -7
  44. package/packages/job-core/transitions.mjs +4 -2
  45. package/scripts/upgrade-drain.mjs +96 -8
  46. package/scripts/worker-bridge-setup.mjs +215 -120
  47. package/src/ack-ledger.mjs +7 -1
  48. package/src/acp-bridge.mjs +256 -28
  49. package/src/admin-socket.mjs +32 -3
  50. package/src/alerts.mjs +17 -8
  51. package/src/answer-journal-retention.mjs +82 -0
  52. package/src/answer-journal.mjs +6 -4
  53. package/src/as-store.mjs +51 -6
  54. package/src/as.mjs +27 -5
  55. package/src/catalog-switch-inventory.mjs +70 -0
  56. package/src/check-response.mjs +4 -1
  57. package/src/cli-help.mjs +14 -3
  58. package/src/cli-name.mjs +13 -1
  59. package/src/connect-cli.mjs +159 -4
  60. package/src/deadman.mjs +8 -5
  61. package/src/delivery.mjs +2 -19
  62. package/src/destinations/index.mjs +75 -14
  63. package/src/drain-runner.mjs +5 -1
  64. package/src/follow-current.mjs +3 -1
  65. package/src/get-summary.mjs +11 -2
  66. package/src/git-env.mjs +1 -1
  67. package/src/gozar-routes.mjs +313 -94
  68. package/src/host-budget-storage.py +56 -6
  69. package/src/host-budget.mjs +98 -15
  70. package/src/host-execution-policy.mjs +17 -6
  71. package/src/legacy-names.mjs +0 -2
  72. package/src/lifecycle.mjs +44 -9
  73. package/src/loopback-probe.mjs +46 -0
  74. package/src/mcp-outcome.mjs +3 -1
  75. package/src/mcp-sse.mjs +2 -1
  76. package/src/mcp-stdio.mjs +192 -30
  77. package/src/patch-apply.mjs +212 -7
  78. package/src/phase-trace.mjs +73 -0
  79. package/src/prepared-go-modules.mjs +127 -0
  80. package/src/prepared-node-modules.mjs +225 -38
  81. package/src/prepared-pnpm.mjs +276 -0
  82. package/src/prepared-store-prune.mjs +52 -0
  83. package/src/projects.mjs +59 -7
  84. package/src/protocol-artifact-commands.mjs +28 -0
  85. package/src/protocol-finish.mjs +3 -2
  86. package/src/publication-authority.mjs +22 -0
  87. package/src/publish-plan.mjs +2 -2
  88. package/src/pull-queue.mjs +55 -20
  89. package/src/read-api.mjs +127 -0
  90. package/src/redaction.mjs +173 -0
  91. package/src/rejections.mjs +19 -3
  92. package/src/route-custody.mjs +90 -0
  93. package/src/route-publication.mjs +50 -0
  94. package/src/route-setup.mjs +184 -0
  95. package/src/schema-subset.mjs +5 -3
  96. package/src/server.mjs +503 -98
  97. package/src/service-launchd.mjs +5 -1
  98. package/src/service-update-lock.mjs +7 -4
  99. package/src/service-update-runtime.mjs +136 -21
  100. package/src/service-update.mjs +207 -51
  101. package/src/service.mjs +276 -77
  102. package/src/setup.mjs +48 -25
  103. package/src/signal.mjs +1 -1
  104. package/src/status-evidence.mjs +18 -5
  105. package/src/store.mjs +876 -120
  106. package/src/submission-policy.mjs +257 -56
  107. package/src/t3-control.mjs +1 -1
  108. package/src/t3.mjs +14 -8
  109. package/src/terminal-safe.mjs +9 -7
  110. package/src/tool-registry.mjs +134 -41
  111. package/src/try-exposure.mjs +53 -86
  112. package/src/try-hosted.mjs +257 -70
  113. package/src/try.mjs +48 -22
  114. package/src/work-order.mjs +11 -6
  115. package/src/worker-instructions.mjs +26 -4
  116. package/src/worker-runs.mjs +35 -0
  117. package/src/workers.mjs +34 -7
  118. package/src/workspace.mjs +354 -54
  119. package/systemd/dot-deadman.service +3 -1
  120. package/docs/dot-pr-reviewer.config.example.json +0 -9
  121. package/docs/pr-head-reviewer.md +0 -70
  122. package/src/pr-head-reviewer.mjs +0 -596
  123. package/systemd/dot-pr-reviewer.service +0 -11
  124. package/systemd/dot-pr-reviewer.timer +0 -10
package/src/server.mjs CHANGED
@@ -3,6 +3,8 @@ import {routingPolicy,PULL_PAGE_PREFIX} from './pull-queue.mjs';
3
3
  import {inspect} from 'node:util';
4
4
  import { loopbackRequestAllowed } from './loopback.mjs';
5
5
  import { normalizeRequestHost } from './gozar-routes.mjs';
6
+ import { watchServicePublication } from './route-publication.mjs';
7
+ import { createPhaseTrace } from './phase-trace.mjs';
6
8
  import { defaultPath,workspaceRoot,rootWarnings } from './paths.mjs';
7
9
  import { readEnv } from './env.mjs';
8
10
  import http from 'node:http';
@@ -15,8 +17,10 @@ import path from 'node:path';
15
17
  import os from 'node:os';
16
18
  import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
17
19
  import { loadWorkers, loadEffectiveOwnerWorkers, hasInstalledDatabase, legacyMarkerPath, seedWorkerRepos, resolveWorker, hasCapability, assertTarget, submitTarget, ensureWorkerRelationship } from './workers.mjs';
18
- import { Store, QUESTION_PURPOSES, nonterminalOutcome, validateProtocol, loadRedeliveryLimits, resumeNudge } from './store.mjs';
19
- import {protocolArtifactChunk} from './protocol-artifact-commands.mjs';
20
+ import { parsePublishGrant } from './publication-authority.mjs';
21
+ import { parseWorkerRuns, parseWorkerSession } from './worker-runs.mjs';
22
+ import { Store, HANDOFF_ACQUISITION_PREFIX, QUESTION_PURPOSES, PROVIDER_REFUSAL, nonterminalOutcome, validateProtocol, loadRedeliveryLimits, resumeNudge, pausedClaimMessage } from './store.mjs';
23
+ import {createArtifactDownloadGuard,protocolArtifactChunk} from './protocol-artifact-commands.mjs';
20
24
  import { sendWebhook, validSecret } from './webhooks.mjs';
21
25
  import { checkAlerts, publishAlert, redactNote } from './alerts.mjs';
22
26
  import { redactOutput, redactSinkText, redactLogEntry, registerSecret } from './redaction.mjs';
@@ -41,12 +45,14 @@ import { beginMcpOutcome, recordMcpResponse, pathShape, uaToken } from './mcp-ou
41
45
  import { lifecycleMetrics, retainLifecycle, controlScopeText } from './lifecycle.mjs';
42
46
  import { normalizeMeta } from './objectives.mjs';
43
47
  import { createRequestLog } from './request-log.mjs';
48
+ import { createLoopbackProbe } from './loopback-probe.mjs';
44
49
  import { logShutdownSignals } from './shutdown-signal.mjs';
45
50
  import { ADVERTISED_SCOPES, legacyScopeNames, wireScope } from './scopes.mjs';
46
51
  import { acquireAsOwner, loadAsConfig, loadKeys } from './as-files.mjs';
47
52
  import { createSignal } from './signal.mjs';
48
- import { adminSocketPathError } from './admin-socket.mjs';
53
+ import { adminSocketPathError, adminSocketPath, ensureAdminSocketDir } from './admin-socket.mjs';
49
54
  import { createToolRegistry, createT3PostHandler, RegistryError } from './tool-registry.mjs';
55
+ import { WORKER_QUESTION_GUIDANCE } from './worker-instructions.mjs';
50
56
  import { createServiceVerifier } from '@tnunamak/gozar';
51
57
  import { acceptsMcpEventStream, beginMcpEventStream } from './mcp-sse.mjs';
52
58
 
@@ -57,7 +63,8 @@ const home = os.homedir();
57
63
  const configDir = defaultPath(home,'.config/dot-bridge');
58
64
  const dataDir = defaultPath(home,'.local/share/dot-bridge');
59
65
  const stateDir = defaultPath(home,'.local/state/dot-bridge');
60
- const socketPathError=adminSocketPathError(path.join(dataDir,'admin.sock'));
66
+ const socket=adminSocketPath(dataDir);
67
+ const socketPathError=adminSocketPathError(socket);
61
68
  if(socketPathError) throw socketPathError;
62
69
  const pathWarnings=rootWarnings(home); // Capture before startup creates any files.
63
70
  const loopback=readEnv('DALAN_LOOPBACK')==='1';
@@ -102,10 +109,11 @@ if(oauthMetadata) oauthMetadata.OAUTH_RESOURCE_METADATA=new URL(`/.well-known/oa
102
109
  const claimCapacity=loadCapacity();
103
110
  const backgroundMaxInFlight=loadBackgroundMaxInFlight();
104
111
  const catalogProfile=readEnv('DALAN_CATALOG_PROFILE')||'stable';
112
+ const batchClaimProfile=catalogProfile==='batch-claim-v1';
105
113
  const t3ToolsSetting=readEnv('DALAN_ENABLE_T3_TOOLS')??'0';
106
114
  if(!['0','1'].includes(t3ToolsSetting))throw new Error('DALAN_ENABLE_T3_TOOLS must be 0 or 1');
107
115
  const t3ToolsEnabled=t3ToolsSetting==='1';
108
- if(!['stable','questions-v1','protocol-v0','legacy-v46'].includes(catalogProfile)) throw new Error('DALAN_CATALOG_PROFILE must be stable, questions-v1 or protocol-v0; legacy-v46 is also supported');
116
+ if(!['stable','questions-v1','protocol-v0','legacy-v46','batch-claim-v1'].includes(catalogProfile)) throw new Error('DALAN_CATALOG_PROFILE must be stable, questions-v1, protocol-v0, legacy-v46 or batch-claim-v1');
109
117
  if(protocolServiceAdapters&&catalogProfile!=='protocol-v0')throw new Error('protocol dependencies require protocol-v0 profile');
110
118
  const port=Number(readEnv('DALAN_PORT')||8787);
111
119
  if(!Number.isInteger(port)||port<0||port>65535) { const error=new RangeError(`options.port should be >= 0 and < 65536. Received ${port}`); error.code='ERR_SOCKET_BAD_PORT'; throw error; }
@@ -167,12 +175,59 @@ if(t3ToolsEnabled) await loadT3Audit();
167
175
  // A valid but unallocated ID preserves each tool's existing absent-request errors. Never accept it as an owner target.
168
176
  const absentId=`req_${randomUUID()}`;
169
177
  if(store.hasAssignment(absentId)) throw new Error('absent gate id collision');
170
- const socket = path.join(dataDir, 'admin.sock');
171
178
  const log = createRequestLog(path.join(stateDir, 'requests.jsonl'));
179
+ const guardArtifactDownload = createArtifactDownloadGuard({log});
180
+ const phaseTrace = createPhaseTrace({ log });
172
181
  logShutdownSignals(log);
173
- // The owner-side tool registry. It has no MCP surface here: changing it never changes tools/list.
182
+ // Registry definitions are discovered through list_tools. The native tools/list stays fixed.
174
183
  const t3PostHandler=createT3PostHandler({store,now:()=>store.nowMs()});
175
- const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{t3_post:t3PostHandler},
184
+ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
185
+ t3_post:t3PostHandler,
186
+ worker_refusal:{
187
+ effectClass:'write',
188
+ validateConfig(_config,{name}) {
189
+ if(name!==refusalRegistration.name) throw new RegistryError('invalid_tool','unknown worker refusal tool');
190
+ },
191
+ async run({args,context}) {
192
+ let receipt;
193
+ try { receipt=await tool('finish',{...args,outcome:PROVIDER_REFUSAL},context,undefined,undefined,null,refusalFinish); }
194
+ catch(error) { throw assignmentRegistryRefusal(error); }
195
+ if(receipt?.deferred) throw new RegistryError('owner_notes_pending',receipt.guidance+' Read with get, then retry with the same idempotency_key.');
196
+ return receipt;
197
+ },
198
+ authorizeReplay({args,context}) {
199
+ const {worker,subject,builtin,connection_id}=context, connection=builtin?(connection_id??''):null;
200
+ try {
201
+ if(store.isProtocolJob(args.request_id)) throw new Error('provider refusal is unavailable for protocol jobs');
202
+ const claim=store.assertFinishClaim(args.request_id,args.claim_id,subject,worker);
203
+ store.assertMutationConnection(args.request_id,claim,connection);
204
+ } catch(error) { throw assignmentRegistryRefusal(error); }
205
+ return [subject,connection];
206
+ },
207
+ },
208
+ worker_question:{
209
+ effectClass:'write',
210
+ // The Store deduplicates question creation and answer consumption under the original grant.
211
+ recoverPendingWrite:true,
212
+ validateConfig(_config,{name}) {
213
+ if(!questionDefinitions.some(definition=>definition.name===name)) throw new RegistryError('invalid_tool','unknown worker question tool');
214
+ },
215
+ async run({tool:name,args,context}) {
216
+ try { return await tool(name,args,context,undefined,undefined,null,questionDefinitions.find(definition=>definition.name===name)); }
217
+ catch(error) { throw assignmentRegistryRefusal(error); }
218
+ },
219
+ authorizeReplay({args,context}) {
220
+ const {worker,subject,builtin,connection_id}=context;
221
+ try {
222
+ const claim=store.assertClaim(args.request_id,args.claim_id,subject,worker);
223
+ store.assertMutationConnection(args.request_id,claim,builtin?(connection_id??''):null);
224
+ if(store.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(args.request_id)?.status!=='claimed')
225
+ throw new Error('assignment is terminal');
226
+ } catch(error) { throw assignmentRegistryRefusal(error); }
227
+ return [subject,builtin?(connection_id??''):null];
228
+ },
229
+ },
230
+ },
176
231
  audit:entry=>log({kind:'tool_registry',...entry})});
177
232
  for(const warning of pathWarnings) {
178
233
  const entry={kind:'root_passed_over',...warning};
@@ -245,7 +300,9 @@ function withAvailableChecks(response,workerSurface=false,worker='dot',subject=n
245
300
  if(!workerSurface) artifacts.push(...store.db.prepare("SELECT id,kind,size,sha256 FROM artifacts WHERE request_id=? AND sealed=1 AND kind='owner-report' ORDER BY created_at,id").all(response.request_id));
246
301
  const checks=store.db.prepare("SELECT j.id check_run_id,j.check_id,CASE WHEN j.status='completed' THEN COALESCE(r.diff_sha256,j.diff_sha256) ELSE j.diff_sha256 END diff_sha256,j.status,j.error,j.output_preview,r.exit_code,r.timed_out,r.output_artifact_id,r.output_sha256,r.duration_ms,r.evidence FROM check_jobs j LEFT JOIN check_runs r ON r.id=j.id WHERE j.request_id=? ORDER BY j.started_at").all(response.request_id).map(withEvidence);
247
302
  const blocker=workerSurface?null:queuedRepositoryBlocker(response);
248
- const enriched={...response,artifacts,checks,...(blocker?{queue_blocker:blocker}:{}),...(checks.some(c=>c.evidence)?{not_identified:NOT_IDENTIFIED}:{})};
303
+ const questionGuidance=workerSurface&&response.claim_id&&response.assignment&&toolNames.has('list_tools')
304
+ ? {guidance:[response.guidance,WORKER_QUESTION_GUIDANCE].filter(Boolean).join(' ')}:{};
305
+ const enriched={...response,...questionGuidance,artifacts,checks,...(blocker?{queue_blocker:blocker}:{}),...(checks.some(c=>c.evidence)?{not_identified:NOT_IDENTIFIED}:{})};
249
306
  if(!workspaceEnabled||response.assignment?.execution_scope!=='implementation') return enriched;
250
307
  if(workerSurface&&workspaceAllowed===null) {
251
308
  try { workspaceAllowed=workerWorkspaceAllowed(worker,response.request_id); }
@@ -298,7 +355,7 @@ function publicWorkerGet(response) {
298
355
  }
299
356
  const questions=store.questions(response.request_id).map(({claim_id,subject,...question})=>question);
300
357
  if(questions.length) response={...response,questions};
301
- const {assignment,...rest}=response;
358
+ const {assignment,publication_authority,...rest}=response;
302
359
  const projected=rest.claim?{...rest,claim:Object.fromEntries(publicClaimFields.filter(key=>Object.hasOwn(rest.claim,key)).map(key=>[key,rest.claim[key]]))}:rest;
303
360
  const redacted=omitWorkerCapabilityKeys(projected);
304
361
  return Object.hasOwn(response,'assignment')?{...redacted,assignment}:redacted;
@@ -353,15 +410,18 @@ const message={type:'string',maxLength:262144};
353
410
  const bool={type:'boolean'};
354
411
  const maxT3WaitMs=catalogProfile==='legacy-v46'?120000:90000;
355
412
  const optionsArray={type:'array',items:string,maxItems:16};
413
+ const questionDefinitions = [
414
+ { name:'ask_question',description:'Ask an identified question under the current grant. The owner answers this question explicitly; ordinary notes do not answer it. Consume its answer before reporting completed. Set purpose to human_decision (a choice only a human may make), authentication (a sign-in only a human can complete) or tool_permission (a permission only a human may grant) when only a human may answer; no model can answer such a question for them.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128},text:{type:'string',minLength:1,maxLength:4096},purpose:{type:'string',enum:['clarification','human_decision','authentication','tool_permission']}},['request_id','claim_id','question_id','text']) },
415
+ { name:'consume_answer',description:'Read and durably consume the identified question answer under its original current grant. Refuses unanswered or stale-epoch questions.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128}},['request_id','claim_id','question_id']) },
416
+ ];
356
417
  const tools = [
357
418
  { name:'list_pending',description:'List up to 50 queued assignment IDs and titles.',inputSchema:schema({}) },
358
419
  { name:'claim',description:'Claim one immutable assignment and see available_checks before choosing run_check.check_id. lease_ms sets this grant’s duration, up to the owner-configured maximum. An exact live retry retains the grant and its stored duration.',inputSchema:schema({request_id:string,claimant:string,acquisition_id:{type:'string',minLength:1,maxLength:128,pattern:'^[A-Za-z0-9_-]+$'},lease_ms:{type:'integer',minimum:1,maximum:store.limits.leaseMs}},['request_id','claimant']) },
359
420
  { name:'get',description:'Read assignment, available_checks, cancellation, progress, report and delivery facts.',inputSchema:schema({request_id:string},['request_id']) },
360
421
  { name:'ack_message',description:'Acknowledge a lightweight message after reading it; no claim or finish is needed.',inputSchema:schema({message_id:string},['message_id']) },
361
422
  { name:'progress',description:'Append progress. Set blocker:true or start note with BLOCKED: or QUESTION: to forward a question to the owner thread. A note over 4096 bytes is cut.',inputSchema:schema({request_id:string,claim_id:string,note:message,blocker:bool},['request_id','claim_id','note']) },
362
- { name:'ask_question',description:'Ask an identified question under the current grant. The owner answers this question explicitly; ordinary notes do not answer it. Consume its answer before reporting completed. Set purpose to human_decision (a choice only a human may make), authentication (a sign-in only a human can complete) or tool_permission (a permission only a human may grant) when only a human may answer; no model can answer such a question for them.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128},text:{type:'string',minLength:1,maxLength:4096},purpose:{type:'string',enum:['clarification','human_decision','authentication','tool_permission']}},['request_id','claim_id','question_id','text']) },
363
- { name:'consume_answer',description:'Read and durably consume the identified question answer under its original current grant. Refuses unanswered or stale-epoch questions.',inputSchema:schema({request_id:string,claim_id:string,question_id:{type:'string',minLength:1,maxLength:128}},['request_id','claim_id','question_id']) },
364
- { name:'finish',description:'Store a terminal worker report; completion is not owner acceptance. summary is optional: when absent it is the first line of result, and one over 4096 bytes is cut.',inputSchema:schema({request_id:string,claim_id:string,outcome:{type:'string',enum:['completed','blocked','failed']},summary:message,result:{type:'string',maxLength:262144},artifact_ids:{type:'array',items:string,maxItems:8}},['request_id','claim_id','outcome','result']) },
423
+ ...questionDefinitions,
424
+ { name:'finish',description:'Store a terminal worker report; completion is not owner acceptance. summary is optional: when absent it is the first line of result, and one over 4096 bytes is cut.',inputSchema:schema({request_id:string,claim_id:string,outcome:{type:'string',enum:['completed','blocked','failed']},summary:message,result:{type:'string',maxLength:262144},artifact_ids:{type:'array',items:string,maxItems:8},runs:{type:'array',maxItems:8,items:{type:'object'}},session:{type:'object'},run_limit:{type:'string',maxLength:1024}},['request_id','claim_id','outcome','result']) },
365
425
  { name:'list_files',description:"List files in this assignment's checked-out repository workspace. Read-only; scoped to the assignment. When truncated is true, pass next_cursor as cursor to get the next page.",inputSchema:schema({request_id:string,claim_id:string,path:string,limit:{type:'integer',minimum:1,maximum:200},cursor:{type:'string',maxLength:1024}},['request_id','claim_id']) },
366
426
  { name:'read_file',description:"Read a file from this assignment's checked-out repository workspace. Read-only; scoped to the assignment. The result has end_line (the last line included) and truncated (true when the 32 KiB cap cut the requested window).",inputSchema:schema({request_id:string,claim_id:string,path:string,start_line:{type:'integer',minimum:1},max_lines:{type:'integer',minimum:1,maximum:200}},['request_id','claim_id','path']) },
367
427
  { name:'apply_patch',description:"Apply a unified diff to this assignment's private workspace copy. Changes stay local until the owner reviews them; nothing is pushed.",inputSchema:schema({request_id:string,claim_id:string,patch:{type:'string',maxLength:262144}},['request_id','claim_id','patch']) },
@@ -378,7 +438,18 @@ const tools = [
378
438
  { name:'list_tools',description:'Call this first to learn which tools you can use. Returns registry_version and each available tool with its description, input schema, class (read or write) and schema_hash.',inputSchema:schema({}) },
379
439
  { name:'call_tool_read',description:'Run an available read-only tool by name, as listed by list_tools. Pass its schema_hash from list_tools.',inputSchema:schema({tool:short,arguments:{type:'object',additionalProperties:true},schema_hash:hashField,idempotency_key:keyField},['tool','arguments']) },
380
440
  { name:'call_tool_write',description:'Run an available tool that changes state or sends something, by name, as listed by list_tools. Requires its schema_hash from list_tools and an idempotency_key that is new for each distinct request.',inputSchema:schema({tool:short,arguments:{type:'object',additionalProperties:true},schema_hash:hashField,idempotency_key:keyField},['tool','arguments','schema_hash','idempotency_key']) }
381
- ].filter(tool=>(catalogProfile!=='stable'||!['ask_question','consume_answer'].includes(tool.name))&&(t3ToolsEnabled||!tool.name.startsWith('t3_')));
441
+ ].filter(tool=>((catalogProfile!=='stable'&&!batchClaimProfile)||!['ask_question','consume_answer'].includes(tool.name))&&(t3ToolsEnabled||!tool.name.startsWith('t3_')));
442
+ if(batchClaimProfile) {
443
+ const claim=tools.find(item=>item.name==='claim');
444
+ claim.description+=' Use next (1 through 8) instead of request_id to claim several queued assignments with one acquisition_id. The reply contains claims and free_lanes.';
445
+ claim.inputSchema.properties.next={type:'integer',minimum:1,maximum:8};
446
+ claim.inputSchema.required=['claimant'];
447
+ // No top-level oneOf: several MCP hosts reject combinators at the schema root. validate() enforces exactly one of request_id or next.
448
+ // The stable catalog stays frozen: claim_id on get (heartbeat for that exact claim) is served only in this profile.
449
+ const get=tools.find(item=>item.name==='get');
450
+ get.description='Read assignment, available_checks, cancellation, progress, report and delivery facts; optional claim_id scopes heartbeat guidance.';
451
+ get.inputSchema.properties.claim_id=string;
452
+ }
382
453
  // Opt-in compatibility catalog only; grant and lease enforcement are unchanged.
383
454
  if(catalogProfile==='legacy-v46') {
384
455
  const names=new Set(['list_pending','claim','get','ack_message','progress','finish',
@@ -453,6 +524,25 @@ if(fs.existsSync(catalogGuardFile)) {
453
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]));
454
525
  if(guard.version!==packageVersion||JSON.stringify(normalize(ordered(guard.catalogs??{})))!==JSON.stringify(normalize(ordered(actual))))throw new Error('service catalog guard mismatch');
455
526
  }
527
+ const refusalRegistration={
528
+ name:'finish_provider_refusal',
529
+ description:'Finish a held assignment when the provider explicitly refuses it. Put the provider’s exact refusal text in result.',
530
+ class:'write',
531
+ handler:{kind:'worker_refusal'},
532
+ inputSchema:schema({request_id:string,claim_id:string,result:{type:'string',minLength:1,maxLength:8000}},['request_id','claim_id','result']),
533
+ };
534
+ const refusalFinish={inputSchema:schema({
535
+ ...refusalRegistration.inputSchema.properties,result:message,summary:message,outcome:{type:'string',enum:[PROVIDER_REFUSAL]},
536
+ },['request_id','claim_id','result','outcome'])};
537
+ if(toolNames.has('list_tools')) {
538
+ const specs=[...questionDefinitions.map(definition=>({...definition,class:'write',handler:{kind:'worker_question'}})),refusalRegistration];
539
+ for(const name of toolRegistry.initializeWorkerTools(specs,workers.workers.keys()))
540
+ log({kind:'worker_tool_registration_conflict',tool:name});
541
+ }
542
+ function assignmentRegistryRefusal(error) {
543
+ if(isCrash(error)) return error;
544
+ return new RegistryError('assignment_refused',publicErrorText(error,'worker assignment'));
545
+ }
456
546
  // A refusal that must stay tells the worker the next call and what to change; workers often do not retry a bare "invalid X".
457
547
  const argumentFixes={
458
548
  finish:{
@@ -461,7 +551,8 @@ const argumentFixes={
461
551
  artifact_ids:'artifact_ids must be at most 8 strings; call finish again with fewer ids',
462
552
  summary:'summary must be text; call finish again with a string or leave summary out'
463
553
  },
464
- progress:{note:'send note as 1 to 4096 bytes of text; call progress again with a shorter note'}
554
+ progress:{note:'send note as 1 to 4096 bytes of text; call progress again with a shorter note'},
555
+ run_check:{check_id:'send check_id, one id from available_check_details or available_checks (the argument is named check_id, not check or name); call run_check again'}
465
556
  };
466
557
  const SUMMARY_MAX=4096,NOTE_MAX=4096;
467
558
  const clipWithMarker=(text,max,marker)=>`${Store.clipBytes(text,max-Buffer.byteLength(marker))}${marker}`;
@@ -487,8 +578,7 @@ function repairArguments(name,args) {
487
578
  marks.summary_derived=true;
488
579
  return {args:{...args,summary:Store.clipBytes(first,SUMMARY_MAX)},marks};
489
580
  }
490
- function validate(name,args) {
491
- const definition=tools.find(x=>x.name===name); if(!definition) throw new Error('unknown tool');
581
+ function validate(name,args,definition=tools.find(x=>x.name===name)) { if(!definition) throw new Error('unknown tool');
492
582
  const refuse=(kind,field)=>{
493
583
  const fix=argumentFixes[name]?.[field];
494
584
  // repairArguments already derives a missing summary, so a summary that is still missing means the result cannot supply one.
@@ -497,8 +587,12 @@ function validate(name,args) {
497
587
  };
498
588
  if(!args||typeof args!=='object'||Array.isArray(args)) throw new Error('invalid arguments');
499
589
  const s=definition.inputSchema;
500
- for(const field of Object.keys(args)) if(!Object.hasOwn(s.properties,field)) throw new Error(`unknown field ${field}`);
590
+ for(const field of Object.keys(args)) if(!Object.hasOwn(s.properties,field)) throw new Error(name==='run_check'?`unknown field ${field}: ${argumentFixes.run_check.check_id}`:`unknown field ${field}`);
501
591
  for(const field of s.required) if(!Object.hasOwn(args,field)) throw refuse('missing',field);
592
+ if(name==='claim'&&batchClaimProfile) {
593
+ if(Object.hasOwn(args,'next')===Object.hasOwn(args,'request_id')) throw new Error('supply exactly one of request_id or next');
594
+ if(Object.hasOwn(args,'next')&&!Object.hasOwn(args,'acquisition_id')) throw refuse('missing','acquisition_id');
595
+ }
502
596
  // The schema no longer requires summary, but one must exist by now: repairArguments could not derive it when the result is blank.
503
597
  if(name==='finish'&&(args.summary===undefined||typeof args.summary==='string'&&!args.summary.trim())) throw refuse('missing','summary');
504
598
  for(const [field,value] of Object.entries(args)) {
@@ -508,7 +602,7 @@ function validate(name,args) {
508
602
  if(rule.type==='integer'&&(!Number.isInteger(value)||(rule.minimum!==undefined&&value<rule.minimum)||(rule.maximum!==undefined&&value>rule.maximum))) throw refuse('invalid',field);
509
603
  if(rule.type==='boolean'&&typeof value!=='boolean') throw refuse('invalid',field);
510
604
  if(rule.type==='object'&&(!value||typeof value!=='object'||Array.isArray(value))) throw refuse('invalid',field);
511
- if(rule.type==='array'&&(!Array.isArray(value)||value.length>rule.maxItems||value.some(x=>typeof x!=='string'))) throw refuse('invalid',field);
605
+ if(rule.type==='array'&&(!Array.isArray(value)||value.length>rule.maxItems||value.some(x=>rule.items?.type==='object'?(!x||typeof x!=='object'||Array.isArray(x)):typeof x!=='string'))) throw refuse('invalid',field);
512
606
  if(rule.enum&&!rule.enum.includes(value)||rule.pattern&&!new RegExp(rule.pattern).test(value)) throw refuse('invalid',field);
513
607
  }
514
608
  }
@@ -524,14 +618,25 @@ function artifactIdsFor(requestId, report) {
524
618
  for(const check of evidence?.checks??[]) if(check?.output_artifact_id) ids.add(check.output_artifact_id);
525
619
  return [...ids];
526
620
  }
621
+ function breakWaitReply(breakId,requestIds,note) {
622
+ return {status:'worker_break',break_id:breakId,report_summary:null,blocker_text:null,notice:maskText(note),
623
+ request_ids:requestIds,artifact_ids:[],...store.breakForecast(breakId)};
624
+ }
625
+ function activeBreakWait(row) {
626
+ if(row?.target_worker!=='dot'||!['queued','claimed'].includes(row.status)) return null;
627
+ const active=store.holdingBreak();
628
+ return active?breakWaitReply(active.id,[row.request_id],'The worker is on a usage break.'):null;
629
+ }
527
630
  function waitSummary(requestId, attention=null) {
528
631
  const row=store.get(requestId);
529
632
  const body=attention?.body?JSON.parse(attention.body):null, note=body?.note??null;
530
633
  // A usage-break notice: the request stays queued; the owner may do it elsewhere or wait again.
531
- if(body?.break_id) return {status:'worker_break',report_summary:null,blocker_text:null,notice:maskText(note),request_ids:body.request_ids,artifact_ids:[]};
634
+ if(body?.break_id) return breakWaitReply(body.break_id,body.request_ids,note);
532
635
  const status=row.status==='finished'?'finished':row.status==='cancelled'?'cancelled':/^\s*QUESTION:/im.test(note??'')?'question':'blocker';
533
636
  const failure=store.failureFields(requestId);
534
- return {status,report_summary:maskText(row.report?.summary??null),blocker_text:maskText(note),artifact_ids:artifactIdsFor(requestId,row.report),...(status==='cancelled'&&row.cancelled_reason?{cancelled_reason:row.cancelled_reason}:{}),failure_type:failure.failure_type,failure_type_source:failure.failure_type_source,...(failure.failure_type==='expired'?{expired:true}:{})};
637
+ const refusal=status==='finished'&&row.report?.outcome===PROVIDER_REFUSAL
638
+ ? {outcome:PROVIDER_REFUSAL,report_result:maskText(row.report.result)}:{};
639
+ return {status,...refusal,report_summary:maskText(row.report?.summary??null),blocker_text:maskText(note),artifact_ids:artifactIdsFor(requestId,row.report),...(status==='cancelled'&&row.cancelled_reason?{cancelled_reason:row.cancelled_reason}:{}),failure_type:failure.failure_type,failure_type_source:failure.failure_type_source,...(failure.failure_type==='expired'?{expired:true}:{})};
535
640
  }
536
641
  function notifyAttachedWaiter(requestId) {
537
642
  const waiter=waiters.get(requestId);
@@ -583,15 +688,63 @@ function sweepStaleLeases() {
583
688
  return ids;
584
689
  }
585
690
  const destinations=createDestinations({store,ackLedger,notify:notifyAttachedWaiter,log,crashAt,exit:code=>process.exit(code)});
691
+ // Each worker notification has one durable delivery owner. Extra HTTP waits
692
+ // observe the same terminal row without competing to settle that delivery.
693
+ const terminalWaiters=new Map();
694
+ function attachTerminalWaiter(req,res,requestId,timeoutMs,consume) {
695
+ const count=terminalWaiters.get(requestId)??0;
696
+ if(count>=7)return json(res,429,{error:'too many waits for this job'});
697
+ terminalWaiters.set(requestId,count+1);
698
+ const deadline=performance.now()+timeoutMs;
699
+ let timer,closed=false;
700
+ const detach=()=>{
701
+ if(closed)return;
702
+ closed=true;clearTimeout(timer);
703
+ const left=(terminalWaiters.get(requestId)??1)-1;
704
+ if(left)terminalWaiters.set(requestId,left);else terminalWaiters.delete(requestId);
705
+ req.off('aborted',detach);res.off('close',detach);
706
+ };
707
+ const poll=()=>{
708
+ if(closed)return;
709
+ let row=null;
710
+ try { row=store.get(requestId); } catch { /* retry until our own deadline */ }
711
+ if(['finished','cancelled'].includes(row?.status)) {
712
+ detach();
713
+ try {
714
+ store.recordFetched(requestId);if(consume)store.recordConsumed(requestId,'wait');
715
+ return json(res,200,waitSummary(requestId));
716
+ } catch { /* the finished row may no longer be readable */ }
717
+ return json(res,200,{status:'timeout',report_summary:null,blocker_text:null,artifact_ids:[]});
718
+ }
719
+ const left=deadline-performance.now();
720
+ if(left<=0) {
721
+ detach();
722
+ let workerBreak=null;
723
+ try { workerBreak=activeBreakWait(row); } catch { /* a failed break lookup still completes this wait */ }
724
+ return json(res,200,workerBreak??{status:'timeout',report_summary:null,blocker_text:null,artifact_ids:[]});
725
+ }
726
+ timer=setTimeout(poll,Math.min(200,left));timer.unref?.();
727
+ };
728
+ req.once('aborted',detach);res.once('close',detach);
729
+ if(req.aborted||res.destroyed)detach();else poll();
730
+ }
731
+
586
732
  async function attachWaiter(req,res,requestId,timeoutMs,consume=true) {
587
733
  const immediate=store.get(requestId);
588
734
  if(['finished','cancelled'].includes(immediate.status)) { store.recordFetched(requestId);if(consume) store.recordConsumed(requestId,'wait'); return json(res,200,waitSummary(requestId)); }
589
- if(waiters.has(requestId)) return json(res,409,{error:'waiter already attached'});
735
+ if(waiters.has(requestId))return attachTerminalWaiter(req,res,requestId,timeoutMs,consume);
590
736
  const queueBlocker=queuedRepositoryBlocker(immediate);
591
737
  if(queueBlocker) return json(res,200,{status:'blocker',report_summary:null,blocker_text:queueBlocker.message,artifact_ids:[],queue_blocker:queueBlocker});
592
738
  // `none` has no fallback delivery channel, so a newly attached waiter must
593
739
  // also observe attention recorded before it attached.
594
740
  const destination=await destinations.for(immediate.delivery_mode);
741
+ if(req.aborted||res.destroyed)return;
742
+ const current=store.get(requestId);
743
+ if(['finished','cancelled'].includes(current.status)) {
744
+ store.recordFetched(requestId);if(consume)store.recordConsumed(requestId,'wait');
745
+ return json(res,200,waitSummary(requestId));
746
+ }
747
+ if(waiters.has(requestId))return attachTerminalWaiter(req,res,requestId,timeoutMs,consume);
595
748
  const waiter={res,timer:null,consume,cursor:immediate.delivery_mode==='none'||destination.quietReason(immediate)?0:store.deliveryCursor(requestId)};
596
749
  const detach=()=>{
597
750
  if(waiters.get(requestId)!==waiter) return;
@@ -611,6 +764,8 @@ async function attachWaiter(req,res,requestId,timeoutMs,consume=true) {
611
764
  return json(res,200,waitSummary(requestId));
612
765
  }
613
766
  blocker=queuedRepositoryBlocker(row);
767
+ const workerBreak=!blocker&&activeBreakWait(row);
768
+ if(workerBreak) return json(res,200,workerBreak);
614
769
  } catch { /* the request may have expired while waiting */ }
615
770
  json(res,200,blocker?{status:'blocker',report_summary:null,blocker_text:blocker.message,artifact_ids:[],queue_blocker:blocker}:{status:'timeout',report_summary:null,blocker_text:null,artifact_ids:[]});
616
771
  },timeoutMs);
@@ -618,17 +773,45 @@ async function attachWaiter(req,res,requestId,timeoutMs,consume=true) {
618
773
  waiters.set(requestId,waiter);
619
774
  notifyAttachedWaiter(requestId);
620
775
  }
776
+ // Put the next acquisition before job detail, including after progress and finish.
777
+ // 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;
780
+ 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;
783
+ 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.';
791
+ const {next_action:previousAction,free_lanes:previousFree,...rest}=reply;
792
+ return {next_action,free_lanes,ready_queued,...rest};
793
+ }
621
794
  // Result guidance only; tool descriptions stay fixed.
622
- const listGuidance='Claim every listed assignment you can start now, up to free_lanes, in this turn. Do not claim one and stop. Never exceed free_lanes.';
623
- const claimMoreGuidance='If free_lanes > 0 and work is queued, claim more now.';
795
+ const batchGuidance='Follow next_action for any additional acquisition; use a fresh acquisition_id for each new batch.';
796
+ const listGuidance=batchClaimProfile?batchGuidance:'Claim every listed assignment you can start now, up to free_lanes, in this turn. Do not claim one and stop. Never exceed free_lanes.';
797
+ const claimMoreGuidance=batchClaimProfile?batchGuidance:'If free_lanes > 0 and work is queued, claim more now.';
798
+ function plainClaimGuidance(free, waiting) {
799
+ if(free===0) return 'All your lanes are busy. Finish a job before you claim another.';
800
+ if(waiting>0) return `${free} of your lanes are free and ${waiting} jobs are waiting. Claim again now, and keep claiming until free_lanes is 0 or no job is waiting. Start every job you claim in this turn.`;
801
+ return claimMoreGuidance;
802
+ }
803
+ // A worker with worker_claim_hint (limits.json) is told to hold a few claims, not every free lane: claims it drops when its run ends hold their lanes for a lease.
804
+ const hintGuidance=n=>batchClaimProfile?`${batchGuidance} Send progress at least every 3 minutes.`:`Hold at most ${n} claims at once, however many lanes are free: claim only as many listed assignments as ${n} minus the claims you already hold, and send progress at least every 3 minutes while you work. free_lanes is the bridge's limit, not your target.`;
805
+ const hintMoreGuidance=n=>batchClaimProfile?batchGuidance:`If you hold fewer than ${n} claims and work is queued, claim more now; at ${n}, finish one first.`;
624
806
  // A finishing lane takes the next queued item itself; an error on any claim means the list changed, so list again.
625
- const finishNextGuidance=next=>`Claim ${next[0].request_id} yourself before you end this run, then keep claiming up to free lanes. After any claim error such as assignment_expired, call list_pending and claim from that list.`;
807
+ const finishNextGuidance=next=>batchClaimProfile?batchGuidance:`Claim ${next[0].request_id} yourself before you end this run, then keep claiming up to free lanes. After any claim error such as assignment_expired, call list_pending and claim from that list.`;
626
808
  // A worker with finish_handoff gets its next job inside the finish reply, or waits a bounded time for work.
627
809
  // The claim is the worker's own `claim` call, run by the bridge: same policy, preflight, scope, pause, capacity and
628
810
  // connection checks, one claim per job. The claim carries acquisition_id handoff-<finished claim_id>, so a repeated
629
811
  // finish gets the same job back, and a second finish by the same claimant name, which would otherwise count as an
630
812
  // exact retry of the first claim, is refused that job and takes the next one.
631
- const HANDOFF_LEASE_MS=600000,HANDOFF_POLL_MS=500,HANDOFF_MAX_ATTEMPTS=5;
813
+ // The claim starts on a short idle lease: the worker's finish_handoff.idle_lease_ms (workers.mjs, at most 2 minutes).
814
+ const HANDOFF_POLL_MS=500,HANDOFF_MAX_ATTEMPTS=5,HANDOFF_PICK_WINDOW=64;
632
815
  const nap=(ms,signal)=>new Promise(resolve=>{
633
816
  const done=()=>{clearTimeout(timer);signal?.removeEventListener('abort',done);resolve();};
634
817
  const timer=setTimeout(done,ms);
@@ -644,56 +827,123 @@ async function handOffNextJob(args) {
644
827
  handoffsInFlight.set(key,run);
645
828
  return run;
646
829
  }
647
- // Returns {job}, {empty,waited_ms} or {} (no handoff: the caller keeps the old hint). Never throws: the finish is stored.
648
- async function runHandoff({principal,requestId,claimId,waitMs,signal}) {
830
+ // Returns {jobs}, {empty,waited_ms} or {} (no handoff: the caller keeps the old hint). Never throws: the finish is stored.
831
+ // A finish hands over up to maxJobs claimed jobs, never more than the free lanes: the first claim is keyed handoff-<claim_id>,
832
+ // the others handoff-<claim_id>-n<n>, so a repeated finish gets the same jobs back and takes no more.
833
+ async function runHandoff({principal,requestId,claimId,waitMs,maxJobs=1,idleLeaseMs,lease,onlyWhenEmpty=false,signal}) {
834
+ const jobs=[]; // claimed so far: an error after a claim must still report it, or the job idles until its lease ends
649
835
  try {
650
836
  const {worker,subject}=principal;
651
837
  const held=store.db.prepare('SELECT claimant FROM claims WHERE request_id=? AND claim_id=?').get(requestId,claimId);
652
838
  if(!held) return {};
653
- const acquisition_id=`handoff-${claimId}`,lease_ms=Math.min(HANDOFF_LEASE_MS,store.limits.leaseMs);
654
- const claim=async next=>{
839
+ const base=`${HANDOFF_ACQUISITION_PREFIX}${claimId}`,lease_ms=lease==='working'?store.handoffWorkingLeaseMs(worker):Math.min(idleLeaseMs,store.limits.leaseMs);
840
+ const acquisitionFor=n=>n===0?base:`${base}-n${n}`;
841
+ const claim=async(next,acquisition_id)=>{
655
842
  try {
656
843
  const job=await tool('claim',{request_id:next,claimant:held.claimant,acquisition_id,lease_ms},principal,undefined,signal);
657
- return job&&typeof job.error!=='string'&&job.claim_id?job:null;
844
+ return job&&typeof job.error!=='string'&&job.claim_id?{...job,already_claimed:true}:null;
658
845
  } catch { return null; }
659
846
  };
660
- // A repeated finish gets back the job its first reply carried. If that job is gone (finished, expired), this finish
661
- // already had its handoff: it takes no second job.
662
- const prior=store.db.prepare("SELECT c.request_id,c.state,a.status FROM claims c JOIN assignments a USING(request_id) WHERE c.worker=? AND c.subject=? AND c.acquisition_id=?").get(worker,subject,acquisition_id);
663
- if(prior) { const job=prior.state==='active'&&prior.status==='claimed'?await claim(prior.request_id):null; return job?{job}:{}; }
847
+ // A repeated finish gets back the jobs its first reply carried. A job that is gone (finished, expired) is not replaced:
848
+ // this finish already had its handoff.
849
+ const ids=Array.from({length:maxJobs},(_,n)=>acquisitionFor(n));
850
+ const priors=store.db.prepare(`SELECT c.request_id,c.state,c.acquisition_id,a.status FROM claims c JOIN assignments a USING(request_id) WHERE c.worker=? AND c.subject=? AND c.acquisition_id IN (${ids.map(()=>'?').join(',')}) ORDER BY c.claimed_at,c.rowid`).all(worker,subject,...ids);
851
+ if(priors.length) {
852
+ for(const prior of priors) { const job=prior.state==='active'&&prior.status==='claimed'?await claim(prior.request_id,prior.acquisition_id):null; if(job) jobs.push(job); }
853
+ return jobs.length?{jobs}:{};
854
+ }
664
855
  const started=Date.now(),tried=new Set();
665
856
  let sawQueued=false;
857
+ // only_when_empty: work queued at the finish is the worker's to claim; no handoff, and the finish is not held.
858
+ if(onlyWhenEmpty&&store.hasQueuedFor([worker])) return {};
859
+ // Rows whose last handoff lapsed untouched are left for the worker's own list_pending: the same rows were handed ten times and never started.
860
+ const pick=free=>(store.nextQueued(free,null,worker,{applyHint:false,handoffExclusions:tried}).next_queued??[]);
666
861
  for(;;) {
667
- if(signal?.aborted||store.paused()) return {};
862
+ if(signal?.aborted||store.paused()) return jobs.length?{jobs}:{};
668
863
  const {free_lanes}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
669
- if(free_lanes<=0) return {};
864
+ if(free_lanes<=0) return jobs.length?{jobs}:{};
670
865
  if(store.hasQueuedFor([worker])) {
671
866
  sawQueued=true;
672
- const pick=()=>(store.nextQueued(free_lanes+tried.size,null,worker).next_queued??[]).filter(x=>!tried.has(x.request_id));
673
867
  // A lost race or an unclaimable head moves on to the next job; an unclaimable queue ends in the old hint.
674
- for(let fresh=pick();fresh.length&&tried.size<HANDOFF_MAX_ATTEMPTS;fresh=pick()) {
868
+ // After the first job the same loop refills the other freed lanes, up to maxJobs and the free lanes.
869
+ for(let fresh=pick(free_lanes);fresh.length&&tried.size<HANDOFF_MAX_ATTEMPTS+maxJobs;) {
870
+ // A claim that errored after it committed leaves a grant under this slot's key. Settle that grant first: take it
871
+ // (an exact retry returns it) or stop. Never claim a different job against an unsettled slot.
872
+ const slot=acquisitionFor(jobs.length),stuck=store.db.prepare('SELECT request_id,state FROM claims WHERE worker=? AND subject=? AND acquisition_id=?').get(worker,subject,slot);
873
+ if(stuck) {
874
+ const job=stuck.state==='active'?await claim(stuck.request_id,slot):null;
875
+ if(!job) return jobs.length?{jobs}:{};
876
+ jobs.push(job); tried.add(stuck.request_id);
877
+ if(jobs.length>=maxJobs) return {jobs};
878
+ fresh=pick(store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity).free_lanes);
879
+ continue;
880
+ }
675
881
  tried.add(fresh[0].request_id);
676
- const job=await claim(fresh[0].request_id);
677
- if(job) return {job};
882
+ const job=await claim(fresh[0].request_id,slot);
883
+ if(job) { jobs.push(job); if(jobs.length>=maxJobs) return {jobs}; }
884
+ const left=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity).free_lanes;
885
+ if(left<=0) return jobs.length?{jobs}:{};
886
+ fresh=pick(left);
678
887
  }
679
- if(tried.size) return {};
888
+ // Only rows that lapsed untouched are queued: hand nothing and do not hold the finish; the old hint lists them.
889
+ if(jobs.length||tried.size||!pick(free_lanes).length) return jobs.length?{jobs}:{};
680
890
  }
681
891
  const left=started+waitMs-Date.now();
682
892
  if(left<=0) return sawQueued?{}:{empty:true,waited_ms:Date.now()-started};
683
893
  await nap(Math.min(HANDOFF_POLL_MS,left),signal);
684
894
  }
685
- } catch(error) { log({kind:'finish_handoff_error',request_id:requestId,reason:redactNote(String(error?.message??error))}); return {}; }
895
+ } catch(error) { log({kind:'finish_handoff_error',request_id:requestId,reason:redactNote(String(error?.message??error))}); return jobs.length?{jobs}:{}; }
686
896
  }
687
897
  async function finishReply(reply,{principal,requestId,claimId,signal}) {
898
+ const pausedReply = () => {
899
+ if (!store.paused() && !quiescing) return null;
900
+ const {next_queued,next_action,...rest}=reply;
901
+ return {...rest,guidance:quiescing?restartQuiesceText:pausedClaimMessage};
902
+ };
903
+ const paused=pausedReply();
904
+ if(paused) return paused;
688
905
  const setting=workers.workers.get(principal.worker)?.finishHandoff;
689
906
  if(setting&&reply.receipt_id&&!store.isProtocolJob(requestId)) {
690
- const {job,empty,waited_ms}=await handOffNextJob({principal,requestId,claimId,waitMs:setting.waitMs,signal});
691
- log({kind:'finish_handoff',request_id:requestId,next_request_id:job?.request_id??null,result:job?'claimed':empty?'empty':'none',waited_ms:waited_ms??0});
907
+ const {jobs,empty,waited_ms}=await handOffNextJob({principal,requestId,claimId,waitMs:setting.waitMs,maxJobs:setting.maxJobs,idleLeaseMs:setting.idleLeaseMs,lease:setting.lease,onlyWhenEmpty:setting.onlyWhenEmpty,signal}),job=jobs?.[0];
908
+ log({kind:'finish_handoff',request_id:requestId,next_request_id:job?.request_id??null,jobs:jobs?.length??0,result:job?'claimed':empty?'empty':'none',waited_ms:waited_ms??0});
692
909
  const {next_queued,next_action,...rest}=reply;
693
- if(job) return {...rest,next_job:job,guidance:`Your next job ${job.request_id} is already claimed for you; its claim result is in next_job. Work on it now, in this turn, and call finish for it. ${job.lease_expires_at?`Its lease ends at ${job.lease_expires_at}`:'Its lease is short'}; every tool call on it renews the lease.`};
694
- if(empty) return {...rest,queue_empty:true,waited_ms,guidance:waited_ms>=1000?`No job was queued for ${Math.round(waited_ms/1000)} seconds. Nothing is claimed for you. End this run; a new assignment wakes you.`:'No job is queued. Nothing is claimed for you. End this run; a new assignment wakes you.'};
910
+ if(job) {
911
+ const offers=jobs.map(j=>`${j.request_id} (lease ends ${j.lease_expires_at})`).join(', ');
912
+ const guidance=`Already claimed for you: ${offers}. ${batchClaimProfile?'Use next_action only for additional work.':'Do not call claim again.'} Use the supplied claim_id and send progress before its lease expires to renew to the normal working lease. Start the offered work now in this turn and call finish for each job when done.`;
913
+ if(setting.maxJobs>1) return {...rest,next_job:job,next_jobs:jobs,guidance};
914
+ return {...rest,next_job:job,guidance};
915
+ }
916
+ const pausedAfterWait=pausedReply();
917
+ if(pausedAfterWait) return pausedAfterWait;
918
+ if(empty) return {...rest,queue_empty:true,waited_ms,guidance:batchClaimProfile?`Nothing was handed off. ${batchGuidance}`:waited_ms>=1000?`No job was queued for ${Math.round(waited_ms/1000)} seconds. Nothing is claimed for you. End this run; a new assignment wakes you.`:'No job is queued. Nothing is claimed for you. End this run; a new assignment wakes you.'};
919
+ }
920
+ const hint=store.claimHint(principal.worker);
921
+ if (!reply.receipt_id || store.paused()) return reply;
922
+ const { free_lanes, queued } = store.laneState(principal.subject,principal.worker,redeliveryLimits.laneCapacity,claimCapacity);
923
+ const hintRoom = hint===null ? Infinity : Math.max(0,hint-store.recentClaimCount(principal.worker));
924
+ if (free_lanes<=0 || hintRoom===0) {
925
+ const {next_queued,next_action,...rest}=reply;
926
+ const guidance='Finish one in-flight assignment before claiming more.';
927
+ return {...rest,next_action:guidance,guidance};
695
928
  }
696
- return reply.next_queued?.length&&!store.paused()?{...reply,guidance:finishNextGuidance(reply.next_queued)}:reply;
929
+ if (!reply.next_queued?.length) return reply;
930
+ const oldest=reply.next_queued[0].request_id;
931
+ if (batchClaimProfile) return {...reply,guidance:batchGuidance};
932
+ return {...reply,...(Object.hasOwn(reply,'free_lanes')?{}:{free_lanes}),...(Object.hasOwn(reply,'queued_after_finish')?{}:{queued_after_finish:queued}),
933
+ guidance:hint!==null
934
+ ? `Claim the oldest listed assignment you can start now (${oldest}). ${hintGuidance(hint)} ${free_lanes} lanes are free and ${queued} jobs are waiting. After a claim error, call list_pending before trying again.`
935
+ : `Claim the oldest listed assignment you can start now (${oldest}), then keep claiming until free_lanes is 0 or no job is waiting: ${free_lanes} lanes are free and ${queued} jobs are waiting. After a claim error, call list_pending before trying again.`};
936
+ }
937
+ // The finish is committed and its receipt exists: the report, patch and check evidence are already artifacts, and
938
+ // no reader touches the tree afterwards (Workspace.result refuses a finished assignment; owner /get, /wait and
939
+ // /artifact read the store and the artifacts). Remove the finished checkout now, as a CI runner cleans its
940
+ // workspace at job end, instead of holding it for the 6-hour retention sweep. Not awaited: a slow or failed
941
+ // removal cannot delay or fail the finish reply; it logs artifact_cleanup_error and leaves the row, which the
942
+ // hourly sweep retries. A repeated finish finds no row and does nothing.
943
+ function cleanupFinishedWorkspace(requestId) {
944
+ if(!workspace) return;
945
+ void workspace.removeTerminalWorkspace(requestId)
946
+ .catch(error=>log({kind:'artifact_cleanup_error',request_id:requestId,reason:error.message}));
697
947
  }
698
948
  // A loader failure carries host paths or quotes the file. Every caller of this policy gets the Store's fixed error instead.
699
949
  function repoPolicyFor(assignment) {
@@ -739,7 +989,7 @@ const policyPage=(worker,cursor=null)=>store.pullQueue.list(worker,admitPolicyWo
739
989
  async function submitPolicy(body,req,dryRun) {
740
990
  if(req.method!=='POST')throw new Error('policy submit requires POST');
741
991
  if(body.background!==undefined&&typeof body.background!=='boolean'||body.review!==undefined&&typeof body.review!=='boolean'||body.allow_main!==undefined&&typeof body.allow_main!=='boolean')throw new Error('invalid policy submit flags');
742
- if(body.worker!==undefined||body.relationship_id!==undefined||body.command_key!==undefined||body.supersedes!==undefined||body.revises!==undefined||body.required_capabilities!==undefined||body.max_queued!==undefined||body.defer_queued!==undefined||body.destination_revision!==undefined) throw new Error('routing v1 cannot combine single-target, relationship, command, supersede, revise or capacity options');
992
+ if(body.worker!==undefined||body.relationship_id!==undefined||body.command_key!==undefined||body.supersedes!==undefined||body.revises!==undefined||body.follows!==undefined||body.caller_waiting!==undefined||body.required_capabilities!==undefined||body.max_queued!==undefined||body.defer_queued!==undefined||body.destination_revision!==undefined) throw new Error('routing v1 cannot combine single-target, relationship, command, supersede, revise or capacity options');
743
993
  if(!body.assignment||typeof body.assignment!=='object'||Array.isArray(body.assignment)||typeof body.assignment.request_id!=='string'||!/^[-\w]{8,128}$/.test(body.assignment.request_id)||body.assignment.request_id.startsWith(PULL_PAGE_PREFIX)) throw new Error('invalid assignment request_id');
744
994
  if(!Array.isArray(body.assignment.inputs)) throw new Error('invalid assignment inputs');
745
995
  if(body.assignment.schema_version!==1||typeof body.assignment.brief!=='string'||!body.assignment.brief.trim()||typeof body.assignment.expected_output!=='string'||typeof body.assignment.execution_scope!=='string')throw new Error('invalid assignment: needs schema_version 1, brief, inputs, expected_output and execution_scope');
@@ -775,45 +1025,65 @@ async function submitPolicy(body,req,dryRun) {
775
1025
  for(const worker of routing.allowed_workers)if(!dryRun)admitPolicyWorker(worker,payload,execution,approvals[worker]);
776
1026
  // Capture each candidate's relationship at the same transaction boundary as admission.
777
1027
  // Acquisition uses this binding, so ending it later does not revoke accepted work.
1028
+ const excludedWorkers=[];
778
1029
  const result=store.inTransaction(()=>{
779
1030
  const existing=store.pullQueue.row(identity.request_id);
780
1031
  if(existing) {
781
1032
  const saved=JSON.parse(existing.options);
782
1033
  if(Object.hasOwn(saved,'relationships')) options.relationships=saved.relationships;
783
- } else options.relationships=Object.fromEntries(routing.allowed_workers.map(worker=>[worker,store.relationshipForSubmission(worker)?.relationship_id??null]));
1034
+ } else {
1035
+ const relationships=[];
1036
+ for(const worker of routing.allowed_workers) {
1037
+ try { relationships.push([worker,store.relationshipForSubmission(worker)?.relationship_id??null]); }
1038
+ catch(error) {
1039
+ if(error.message!=='relationship_ended')throw error;
1040
+ excludedWorkers.push(worker);
1041
+ }
1042
+ }
1043
+ if(!relationships.length)throw new Error('relationship_ended');
1044
+ options.relationships=Object.fromEntries(relationships);
1045
+ }
784
1046
  return store.pullQueue.submit(payload,identity,options,routing,approvals,owner,{dryRun});
785
1047
  });
786
- if(dryRun)return {...result,destination_disclosures:disclosures};
1048
+ if(dryRun)return {...result,destination_disclosures:disclosures,excluded_workers:excludedWorkers};
787
1049
  log({kind:'policy_work_submitted',request_id:identity.request_id,work_order_id:result.work_order_id});
788
- return {...result,execution};
1050
+ return {...result,execution,excluded_workers:excludedWorkers};
1051
+ }
1052
+
1053
+ let quiescing=false,admittedInFlight=0;
1054
+ const restartQuiesceText='bridge_quiescing: bridge paused for a restart; retry after it reopens.';
1055
+ function quiesceStatus() {
1056
+ return {on:quiescing,admitted_in_flight:admittedInFlight,delivery_in_flight:delivering?1:0,...store.quiesceCounts()};
789
1057
  }
790
1058
 
791
1059
  // Record the call on the claim it names (one UPDATE); a thrown error or a structured {error} result is kept as the last tool error.
792
- async function tool(name,a,principal,notifyMeta,signal) {
793
- if(!toolNames.has(name)) throw new Error('unknown tool');
794
- // Refuse hidden names before audits, lease touches, sweeps or repository preparation.
795
- if(name==='claim'&&typeof a?.request_id==='string'&&store.hasAssignment(a.request_id)&&store.mayAct(principal.worker,a.request_id)&&
796
- !holdsLiveGrant(principal.worker,a.request_id,a.claimant,principal.subject,a.acquisition_id)) {
797
- assertRepoAllowed(principal.worker,store.get(a.request_id).assignment);
798
- }
1060
+ async function tool(name,a,principal,notifyMeta,signal,batchMode=null,registryDefinition=null) {
1061
+ if(!registryDefinition&&!toolNames.has(name)) throw new Error('unknown tool');
1062
+ if(quiescing&&toolAnnotations[name]?.readOnlyHint!==true) throw new Error(restartQuiesceText);
1063
+ admittedInFlight++;
799
1064
  let error=null;
800
1065
  try {
801
- const result=await dispatchTool(name,a,principal,notifyMeta,signal);
1066
+ if(name==='claim'&&typeof a?.request_id==='string'&&store.hasAssignment(a.request_id)&&store.mayAct(principal.worker,a.request_id)&&
1067
+ !holdsLiveGrant(principal.worker,a.request_id,a.claimant,principal.subject,a.acquisition_id)) {
1068
+ assertRepoAllowed(principal.worker,store.get(a.request_id).assignment);
1069
+ }
1070
+ const result=await dispatchTool(name,a,principal,notifyMeta,signal,batchMode,registryDefinition);
802
1071
  if(typeof result?.error==='string') error=redactNote(result.error);
803
1072
  return result;
804
1073
  } catch(e) { error=redactNote(String(e?.message??e)); if(e.destination&&typeof a?.request_id==='string')notifyAttachedWaiter(a.request_id); throw e; }
805
1074
  finally {
806
- const rid=a?.request_id;
807
- if(typeof rid==='string'&&rid!==absentId&&toolNames.has(name)&&!t3Tools.has(name)&&!notifyTools.has(name)) {
808
- try { store.recordToolActivity(rid,principal.subject,principal.worker,name,{workspace:disabled.has(name),error,connectionId:principal.builtin?(principal.connection_id??''):null}); } catch { /* activity is diagnostic; never fail the call */ }
809
- }
1075
+ try {
1076
+ const rid=a?.request_id;
1077
+ if(typeof rid==='string'&&rid!==absentId&&(registryDefinition||toolNames.has(name))&&!t3Tools.has(name)&&!notifyTools.has(name)) {
1078
+ try { store.recordToolActivity(rid,principal.subject,principal.worker,name,{workspace:disabled.has(name),error,connectionId:principal.builtin?(principal.connection_id??''):null}); } catch { /* activity is diagnostic; never fail the call */ }
1079
+ }
1080
+ } finally { admittedInFlight--; }
810
1081
  }
811
1082
  }
812
- async function dispatchTool(name,a,principal,notifyMeta,signal) {
1083
+ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,registryDefinition=null) {
813
1084
  const t3Audit=(t3Tools.has(name)||notifyTools.has(name))?await loadT3Audit():null;
814
1085
  if(t3Audit) t3Audit.admitT3Audit(store.db,principal.worker,principal.subject);
815
- store.recordWorkerCall(principal.subject,toolNames.has(name)?name:'unknown',principal.worker);
816
- sweepExpired();
1086
+ if(!registryDefinition) store.recordWorkerCall(principal.subject,toolNames.has(name)?name:'unknown',principal.worker);
817
1087
  if(t3Tools.has(name)||notifyTools.has(name)) {
818
1088
  // Denials carry only verified identity, tool and a fixed reason. Never prepare
819
1089
  // an argument-bearing audit until capability, scope and schema all pass.
@@ -829,6 +1099,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal) {
829
1099
  t3Audit.appendT3Audit(store.db,t3Audit.prepareT3Audit(name,{},principal.worker),principal.subject,`denied: ${denial}`);
830
1100
  throw error;
831
1101
  }
1102
+ sweepExpired();
832
1103
  const audit=t3Audit.prepareT3Audit(name,a,principal.worker);
833
1104
  t3Audit.appendT3Audit(store.db,audit,principal.subject,'started');
834
1105
  try {
@@ -878,6 +1149,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal) {
878
1149
  const isPolicyGet=policyRow&&name==='get'&&!store.hasAssignment(a.request_id);
879
1150
  if(isPolicyPage||isPolicyClaim||isPolicyGet) {
880
1151
  validate(name,a);if(oauth)needScope(principal,scopeFor(name));
1152
+ sweepExpired();
881
1153
  if(name==='get')return a.request_id.startsWith(PULL_PAGE_PREFIX)?{policy_work:policyPage(worker,a.request_id)}:store.pullQueue.get(a.request_id,worker,admitPolicyWorker);
882
1154
  const offered=policyRow.child_request_id?null:store.pullQueue.get(a.request_id,worker,admitPolicyWorker);
883
1155
  const preflight=offered?await preflightPR(offered.assignment):null;
@@ -894,7 +1166,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal) {
894
1166
  }
895
1167
  const repaired=repairArguments(name,a);
896
1168
  a=repaired.args;
897
- validate(name,a);
1169
+ validate(name,a,registryDefinition??undefined);
898
1170
  if(oauth) needScope(principal,scopeFor(name));
899
1171
  if(disabled.has(name)&&!(workspaceEnabled&&workerWorkspaceAllowed(worker,a?.request_id))) throw new Error('capability_not_enabled');
900
1172
  if(a.request_id===absentId&&disabled.has(name)) throw new Error('assignment not found');
@@ -902,9 +1174,11 @@ async function dispatchTool(name,a,principal,notifyMeta,signal) {
902
1174
  const strictJob=typeof a.request_id==='string'&&store.isProtocolJob(a.request_id);
903
1175
  if(strictJob&&catalogProfile!=='protocol-v0') throw new Error('protocol jobs require DALAN_CATALOG_PROFILE=protocol-v0');
904
1176
  if(strictJob)store.assertProtocolAvailable(a.request_id);
1177
+ sweepExpired();
905
1178
  // Strict commands validate authority, replay and revision in their transaction.
906
1179
  // The legacy implicit touch would mutate activity before a rejected CAS.
907
1180
  if(!strictJob&&typeof a.request_id==='string'&&typeof a.claim_id==='string'&&store.hasAssignment(a.request_id)) store.touchClaim(a.request_id,a.claim_id,subject,worker,connectionId);
1181
+ if(typeof a.request_id==='string') phaseTrace.action({requestId:a.request_id,tool:name,subject});
908
1182
  // Workspace tools (every one, reads included) refuse any caller but the live holding connection. Native jobs skip the implicit
909
1183
  // touch above, so this is their only check; legacy jobs get a second, post-await check. It runs synchronously right before
910
1184
  // the tool body, after the tool's last await, so no revoke can land between the check and the write.
@@ -919,22 +1193,31 @@ async function dispatchTool(name,a,principal,notifyMeta,signal) {
919
1193
  case 'list_tools': return toolRegistry.listTools(worker);
920
1194
  case 'call_tool_read': case 'call_tool_write': {
921
1195
  // The registry owns policy: grants, class match, argument validation, rate limits and audit.
922
- try { return (await toolRegistry.callTool({worker,tool:a.tool,class:name==='call_tool_read'?'read':'write',args:a.arguments,schema_hash:a.schema_hash,idempotency_key:a.idempotency_key})).result; }
1196
+ try { return (await toolRegistry.callTool({worker,tool:a.tool,class:name==='call_tool_read'?'read':'write',args:a.arguments,schema_hash:a.schema_hash,idempotency_key:a.idempotency_key,context:principal})).result; }
923
1197
  catch(e) { if(e instanceof RegistryError) throw new Error(e.message.startsWith(e.code)?e.message:`${e.code}: ${e.message}`); throw e; }
924
1198
  }
925
1199
  case 'list_pending': {
926
- const {free_lanes}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1200
+ const {free_lanes,worker_max_claims}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
927
1201
  const assignments=store.listPending(worker);
928
- store.recordListed(assignments,free_lanes,worker);
1202
+ store.recordListed(assignments,free_lanes,worker,!quiescing);
1203
+ phaseTrace.listed(assignments.map(x=>x.request_id));
929
1204
  log({kind:'list_pending_result',subject,free_lanes,total:assignments.length,request_ids:assignments.slice(0,20).map(x=>x.request_id)});
930
- const guidance=workers.workers.get(worker)?.guidance==='resume'?`${listGuidance} ${resumeNudge(store.resumeIdleMs()||undefined)}`:listGuidance;
1205
+ const hint=store.claimHint(worker),baseGuidance=hint===null?listGuidance:hintGuidance(hint);
1206
+ const guidance=workers.workers.get(worker)?.guidance==='resume'?`${baseGuidance} ${resumeNudge(store.resumeIdleMs()||undefined)}`:baseGuidance;
931
1207
  // Say outright whether a claim would be accepted now: a worker that once saw a pause refusal must not keep listing without claiming.
932
- const claims_accepted=!store.paused();
1208
+ const claims_accepted=!quiescing&&!store.paused();
933
1209
  const next=claims_accepted?store.nextQueued(free_lanes,null,worker):{};
934
- const claimsNote=claims_accepted?'':'Claims are paused (temporary): do not claim now; call list_pending again later and claim once claims_accepted is true.';
935
- return {assignments,policy_work:policyPage(worker),attention:store.attention(subject,worker),free_lanes,claims_accepted,...(claims_accepted?next:{next_action:claimsNote}),guidance};
1210
+ 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};
936
1212
  }
937
1213
  case 'claim': {
1214
+ if(Object.hasOwn(a,'next')) {
1215
+ const claimant=str(a.claimant,'claimant',128);
1216
+ 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},
1218
+ (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
+ return {claims,...(retry?{retry:true}:{}),free_lanes:lanes()};
1220
+ }
938
1221
  const requestId=id(a.request_id),claimant=str(a.claimant,'claimant',128),ctx=commandContext('claim',{claimant,acquisition_id:a.acquisition_id??null,lease_ms:a.lease_ms??null}),row=store.get(requestId),held=row.claim?.state==='active'?row.claim:null,retry=holdsLiveGrant(worker,requestId,claimant,subject,a.acquisition_id);
939
1222
  if(!retry)assertRepoAllowed(worker,row.assignment);
940
1223
  const needsWorkspace=workspaceEnabled&&(row.assignment.execution_scope==='implementation'||row.assignment.output_paths?.length);
@@ -959,19 +1242,36 @@ async function dispatchTool(name,a,principal,notifyMeta,signal) {
959
1242
  // claimant's own connection is still live. The token was verified before
960
1243
  // the awaited preflight/quiesce above, so a revoke in between must not
961
1244
  // admit the claim. External-OAuth principals pass null and are unchanged.
962
- const claimed=store.claim(requestId,claimant,subject,claimCapacity,preflight,worker,a.acquisition_id,a.lease_ms,ctx,principal.builtin?(principal.connection_id??''):null);
1245
+ const claimed=store.claim(requestId,claimant,subject,claimCapacity,preflight,worker,a.acquisition_id,a.lease_ms,ctx,principal.builtin?(principal.connection_id??''):null,batchMode);
963
1246
  const grant=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
1247
+ 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});
964
1248
  const {free_lanes,queued}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
965
- 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} ${claimMoreGuidance}`},true,worker,subject,workspaceAllowed);
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);
966
1250
  }
967
1251
  case 'renew_claim': {
968
1252
  if(!strictJob) throw new Error('renew_claim requires a protocol job');
969
1253
  return store.renewClaim(id(a.request_id),id(a.claim_id,'claim_id'),a.lease_ms,commandContext('renew',{leaseMs:a.lease_ms}),subject,worker,connectionId);
970
1254
  }
971
- case 'get': { const requestId=id(a.request_id); if(!store.hasAssignment(requestId)) return {kind:'message',message:store.getMessage(requestId,worker)}; store.markNotesSeenByHolder(requestId,subject,worker,connectionId); return {...publicWorkerGet(withAvailableChecks(store.get(requestId),true,worker,subject)),guidance:store.guidanceFor(worker)}; }
1255
+ case 'get': {
1256
+ const requestId=id(a.request_id);
1257
+ if(!store.hasAssignment(requestId)) return {kind:'message',message:store.getMessage(requestId,worker)};
1258
+ store.markNotesSeenByHolder(requestId,subject,worker,connectionId);
1259
+ const row=store.get(requestId);
1260
+ return {...publicWorkerGet(withAvailableChecks(row,true,worker,subject)),...store.workerGetHeartbeat(row,worker,subject,a.claim_id),guidance:store.guidanceFor(worker)};
1261
+ }
972
1262
  case 'ack_message': {const message=store.ackMessage(id(a.message_id,'message_id'),worker);log({kind:'message_acknowledged',message_id:message.message_id});return {kind:'message',message};}
973
1263
  case 'progress': {
974
- const requestId=id(a.request_id),note=str(a.note,'note',4096),receipt=store.progress(requestId,id(a.claim_id,'claim_id'),note,subject,a.blocker===true,worker,null,commandContext('progress',{note,blocker:a.blocker===true}),connectionId);
1264
+ const requestId=id(a.request_id),note=str(a.note,'note',4096),claimId=id(a.claim_id,'claim_id');
1265
+ let dispatchClaim;
1266
+ if(note.startsWith('dispatched_at=')) {
1267
+ try { dispatchClaim=store.db.prepare('SELECT claimed_at,last_progress_at FROM claims WHERE request_id=? AND claim_id=?').get(requestId,claimId); }
1268
+ catch { /* Telemetry never changes a tool result. */ }
1269
+ }
1270
+ const receipt=store.progress(requestId,claimId,note,subject,a.blocker===true,worker,null,commandContext('progress',{note,blocker:a.blocker===true}),connectionId);
1271
+ if(dispatchClaim?.last_progress_at===null) {
1272
+ try { phaseTrace.progress({requestId,claimId,claimedAt:dispatchClaim.claimed_at,first:true,note}); }
1273
+ catch { /* Telemetry never changes a tool result. */ }
1274
+ }
975
1275
  notifyAttachedWaiter(requestId);
976
1276
  return {...receipt,...repaired.marks};
977
1277
  }
@@ -988,6 +1288,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal) {
988
1288
  workspaceFence();
989
1289
  const existing=store.db.prepare('SELECT 1 FROM reports WHERE request_id=?').get(requestId);
990
1290
  let captureEvidence=null;
1291
+ const workerRuns=parseWorkerRuns(a.runs,a.run_limit,redactOutput), workerSession=parseWorkerSession(a.session,store.nowMs());
991
1292
  if(!existing) {
992
1293
  store.assertQuestionsResolved(requestId,claimId,a.outcome);
993
1294
  const request=store.get(requestId);
@@ -1009,6 +1310,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal) {
1009
1310
  // Recheck after the last await. The evidence capture below runs inside the finish transaction, after finishOnce's own
1010
1311
  // connection check, so a patch artifact is never committed for a holder that lost the connection.
1011
1312
  workspaceFence();
1313
+ if(workerWorkspaceEnabled&&request.status==='claimed'&&a.outcome==='completed') { await workspace.checkBeforeFinish(requestId,claimId,subject,worker);workspaceFence(); }
1012
1314
  if(workerWorkspaceEnabled&&request.status==='claimed'&&(request.assignment.execution_scope==='implementation'||request.assignment.output_paths?.length))
1013
1315
  captureEvidence=onRollback=>workspace.snapshotInTransaction(requestId,claimId,subject,worker,onRollback);
1014
1316
  if(request.status==='claimed'&&request.assignment.execution_scope==='read-only') {
@@ -1020,14 +1322,39 @@ async function dispatchTool(name,a,principal,notifyMeta,signal) {
1020
1322
  };
1021
1323
  }
1022
1324
  }
1325
+ if(!existing) { store.recordWorkerRuns(requestId,claimId,workerRuns);store.recordWorkerSession(worker,subject,workerSession); }
1023
1326
  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
+ if(receipt.deferred) return {...receipt,...repaired.marks};
1024
1328
  if(crashAt('after_report_persistence',a.request_id)) process.exit(73);
1025
1329
  notifyAttachedWaiter(requestId);
1026
1330
  if(repaired.marks.summary_derived||repaired.marks.summary_truncated) log({kind:'finish_summary_repaired',request_id:requestId,...repaired.marks});
1331
+ // The finish is committed: the tree serves nothing further, so clean it now instead of waiting for the
1332
+ // sweep (cleanup is never awaited, and an active check or a failed removal is left to the sweep).
1333
+ cleanupFinishedWorkspace(requestId);
1027
1334
  return finishReply({...receipt,...repaired.marks},{principal,requestId,claimId,signal}); }
1028
1335
  case 'list_files': await workspace.makeRoom(id(a.request_id));workspaceFence();return workspace.list(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.path,a.limit??200,worker,a.cursor);
1029
1336
  case 'read_file': await workspace.makeRoom(id(a.request_id));workspaceFence();return workspace.read(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.path,a.start_line??1,a.max_lines??200,worker);
1030
- case 'apply_patch': await workspace.makeRoom(id(a.request_id));workspaceFence();return workspace.apply(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.patch,worker);
1337
+ case 'apply_patch': {
1338
+ const requestId=id(a.request_id),claimId=id(a.claim_id,'claim_id');
1339
+ await workspace.makeRoom(requestId);
1340
+ workspaceFence();
1341
+ let patchResult;
1342
+ try {
1343
+ patchResult=await workspace.apply(requestId,claimId,subject,a.patch,worker);
1344
+ } catch(error) {
1345
+ // If authority changed during the attempt, do not attach evidence to the successor.
1346
+ try {store.recordPatchAttempt(requestId,claimId,'rejected',error?.message,subject,worker,connectionId);}
1347
+ catch(recordError) {log({kind:'patch_attempt_not_recorded',request_id:requestId,reason:safeDiagnostic(recordError?.message,120)});}
1348
+ throw error;
1349
+ }
1350
+ const rejected=patchResult?.error||patchResult?.ok===false;
1351
+ // The patch is already applied (or refused). If authority changed while it ran, the record is refused; never turn that into an error for a patch that did apply.
1352
+ try {
1353
+ store.recordPatchAttempt(requestId,claimId,rejected?'rejected':'applied',
1354
+ rejected?String(patchResult.error||'patch refused'):null,subject,worker,connectionId);
1355
+ } catch(recordError) {log({kind:'patch_attempt_not_recorded',request_id:requestId,reason:safeDiagnostic(recordError?.message,120)});}
1356
+ return patchResult;
1357
+ }
1031
1358
  case 'run_check': await workspace.makeRoom(id(a.request_id));workspaceFence();return workspace.check(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.check_id,worker);
1032
1359
  case 'artifact_chunk': return strictJob?protocolArtifactChunk(store,workspace,{requestId:id(a.request_id),claimId:id(a.claim_id,'claim_id'),subject,worker,artifactId:a.artifact_id,offset:a.offset,base64:a.data_base64,final:a.final,expected:a.sha256,expectedSize:a.size,connectionId},commandContext(a.final?'seal':'upload',{})):workspace.chunk(id(a.request_id),id(a.claim_id,'claim_id'),subject,a.artifact_id,a.offset,a.data_base64,a.final,a.sha256,worker);
1033
1360
  case 'workspace_result': workspaceFence();return workspace.result(id(a.request_id),id(a.claim_id,'claim_id'),subject,worker);
@@ -1073,7 +1400,7 @@ async function dispatch(message,principal,signal) {
1073
1400
  // Modern catalogs are process-wide. A worker's capability controls tools/call authority, not its cached schemas.
1074
1401
  // legacy-v46 keeps its pinned per-worker surface for compatibility.
1075
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};
1076
- case 'tools/call': { try { return {content:[{type:'text',text:JSON.stringify(redactOutput(await tool(p.name,p.arguments??{},principal,notifyTools.has(p.name)?p._meta:undefined,signal)))}],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; } }
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; } }
1077
1404
  case 'events/list': return {events:[event]};
1078
1405
  case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
1079
1406
  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 {}; }
@@ -1104,6 +1431,7 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
1104
1431
  log({kind:'connection_denied',reason:error.code??'unknown_connection',client_id:principal.client_id??null});
1105
1432
  res.writeHead(403,{'content-type':'application/json'});res.end(JSON.stringify({error:error.code??'unknown_connection'}));return;
1106
1433
  }
1434
+ outcome.state.worker=principal.worker;
1107
1435
  outcome.state.phase='body';
1108
1436
  const body=await readBody(req,outcome.state);
1109
1437
  if(req.method!=='POST') { res.writeHead(405,{allow:'POST'}); res.end(); return; }
@@ -1112,7 +1440,7 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
1112
1440
  if(!rpc||typeof rpc!=='object'||Array.isArray(rpc)||rpc.jsonrpc!=='2.0'||typeof rpc.method!=='string') return json(res,400,rpcError(rpc?.id??null,-32600,'Invalid Request'));
1113
1441
  outcome.identify(rpc);
1114
1442
  // Metadata only: bodies can carry webhook secrets and worker results.
1115
- log({kind:'mcp_inbound',call_id:outcome.state.call_id,rpc_method:outcome.state.rpc_method,tool:outcome.state.tool,ua:uaToken(req)});
1443
+ log({kind:'mcp_inbound',call_id:outcome.state.call_id,rpc_method:outcome.state.rpc_method,tool:outcome.state.tool,worker:principal.worker,ua:uaToken(req)});
1116
1444
  if(!Object.hasOwn(rpc,'id')) { res.writeHead(202); res.end(); return; }
1117
1445
  outcome.state.phase='dispatch';
1118
1446
  const eventStream=readEnv('DALAN_TRIAL_SSE')==='1'&&req.method==='POST'&&acceptsMcpEventStream(req.headers.accept)?beginMcpEventStream(res):null;
@@ -1127,7 +1455,7 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
1127
1455
  const adminServer=http.createServer(async(req,res)=>{
1128
1456
  // A refused submit is logged with its reason so the owner can distinguish rejected requests from stored assignments.
1129
1457
  const requestStartedAt=Date.now();
1130
- let rejected=null, dryRequested=false;
1458
+ let rejected=null, dryRequested=false, admission=null, previewMayReportAdmission=false;
1131
1459
  try {
1132
1460
  const raw=req.method==='POST'?await readBody(req):'',body=raw?JSON.parse(raw):{},url=new URL(req.url,'http://localhost');
1133
1461
  if(updateWindowOpen()&&!(req.method==='GET'&&url.pathname==='/service-check')) return refuseDuringUpdate(res);
@@ -1162,6 +1490,7 @@ const adminServer=http.createServer(async(req,res)=>{
1162
1490
  const supersedes=body.supersedes===undefined?null:body.supersedes;
1163
1491
  // {prior_id, prior_token}: this job corrects that one. Shape and authority are checked by the Store, in the submit transaction.
1164
1492
  const revises=body.revises===undefined?null:body.revises;
1493
+ const follows=body.follows===undefined?null:body.follows;
1165
1494
  const destinationRevision=body.destination_revision??null;
1166
1495
  if(body.destination_revision!==undefined&&(typeof destinationRevision!=='string'||!/^sha256:[a-f0-9]{64}$/.test(destinationRevision)))throw new Error('invalid destination_revision');
1167
1496
  if(body.command_key!==undefined&&(typeof commandKey!=='string'||commandKey.length<1||commandKey.length>128)) throw new Error('invalid command_key: use a nonempty string of at most 128 characters');
@@ -1190,6 +1519,7 @@ const adminServer=http.createServer(async(req,res)=>{
1190
1519
  }
1191
1520
  assertRepoAllowed(storedTarget??target??'dot',payload);
1192
1521
  if(body.max_queued!==undefined&&(!Number.isSafeInteger(body.max_queued)||body.max_queued<1)) throw new Error('invalid max_queued');
1522
+ if(body.caller_waiting!==undefined&&typeof body.caller_waiting!=='boolean') throw new Error('invalid caller_waiting');
1193
1523
  if(body.review!==undefined&&typeof body.review!=='boolean') throw new Error('invalid review');
1194
1524
  if(body.background!==undefined&&body.background!==true) throw new Error('invalid background');
1195
1525
  if(body.allow_main!==undefined&&typeof body.allow_main!=='boolean') throw new Error('invalid allow_main');
@@ -1207,10 +1537,20 @@ const adminServer=http.createServer(async(req,res)=>{
1207
1537
  const declaredSource=body.meta?.source??'agent';
1208
1538
  for(const [value,label] of [[body,'submit request'],[body.meta,'meta'],[body.assignment,'assignment']]) assertNoDeclaredConsumer(value,label,declaredSource);
1209
1539
  const meta=normalizeMeta(body.meta);
1540
+ // Advisory only, and not when a required operator authorization has not been checked.
1541
+ previewMayReportAdmission=body.allow_main!==true;
1542
+ admission=()=>{
1543
+ const priority=body.background===true?'background':'normal';
1544
+ const kind=meta.task_kind??(body.review===true?'review':payload.execution_scope??'unknown');
1545
+ return store.admissionAnswer(storedTarget??target??'dot',kind,priority,
1546
+ // The job a supersede replaces leaves the queue when this one is stored, so it is not ahead.
1547
+ {excludeIds:[payload.request_id,supersedes?.target_id??null],createdBefore:existingRequest?.created_at??null,callerWaiting:body.caller_waiting===true});
1548
+ };
1210
1549
  // A retry of an older row is not judged again; only a new submission has to prove the source it claims.
1211
1550
  if(!store.hasAssignment(payload.request_id)) {const refused=unprovenSource({request_id:payload.request_id,payload,meta},body.background===true?'background':'normal'); if(refused) throw new Error(refused);}
1212
1551
  {const input=payload.inputs[0];if(!store.hasAssignment(payload.request_id)&&payload.execution_scope==='implementation'&&body.review!==true&&input?.head_sha&&input.head_sha!==input.base_sha) throw new Error('head_sha_unsupported: implementation scope checks out base_sha; pin base_sha to the revision to work on, or use --review or read-only scope for head_sha');}
1213
1552
  if(body.allow_main===true) adminOperator(req);
1553
+ previewMayReportAdmission=true;
1214
1554
  destination.admit(delivery,{allowMain:body.allow_main===true});
1215
1555
  if(body.sensitive_scope_override!==undefined&&(typeof body.sensitive_scope_override!=='string'||!body.sensitive_scope_override)) throw new Error('invalid sensitive scope override');
1216
1556
  // A retry validates nothing and sends the original assignment, so the identity of a request is the assignment as submitted,
@@ -1220,7 +1560,7 @@ const adminServer=http.createServer(async(req,res)=>{
1220
1560
  if(isNew&&dryRun) store.relationshipForSubmission(target,body.relationship_id??null);
1221
1561
  // Reject immutable retry conflicts using the persisted binding before any external destination inspection.
1222
1562
  // A matching retry still validates the current destination below; this does not accept stale environment evidence.
1223
- 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);
1563
+ 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);
1224
1564
  let order=null;
1225
1565
  if(isNew) {
1226
1566
  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,
@@ -1241,7 +1581,7 @@ const adminServer=http.createServer(async(req,res)=>{
1241
1581
  },
1242
1582
  preflight:p=>preflightPR(p),
1243
1583
  // Advisory only, like Store.submit: a supersede target leaves the queued count unchanged. Store.submit rechecks it in its transaction.
1244
- 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}),
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}),
1245
1585
  kind:(r,p)=>r.meta?.task_kind??(r.review?'review':p.execution_scope??'unknown'),
1246
1586
  defaultValidity:(kind,r)=>store.defaultValidUntil(r.target,kind),
1247
1587
  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;},
@@ -1253,11 +1593,11 @@ const adminServer=http.createServer(async(req,res)=>{
1253
1593
  const {environmentId,generation}=(dryRun&&order&&order.verdict!=='admissible')?{}:await destination.validate(delivery);
1254
1594
  // An awaited repository/destination lookup may outlive a host policy edit.
1255
1595
  assertRepoAllowed(storedTarget??target??'dot',existingRequest?.assignment??payload);
1256
- if(dryRun) store.checkRetry(submitted,delivery,environmentId,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises);
1596
+ if(dryRun) store.checkRetry(submitted,delivery,environmentId,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises,follows,body.caller_waiting);
1257
1597
  const disclosure=isNew?store.destinationSnapshot(target??'dot',jobExecution,payload):existingRequest.destination_approval?.snapshot??null;
1258
1598
  if(dryRun) {
1259
1599
  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});
1260
- return json(res,200,{dry_run:true,request_id:submitted.request_id,stored:false,...(disclosure?{destination_disclosure:disclosure}:{}),...(order??{verdict:'admissible',reasons:[],duplicate:true}),...(order?.warnings?.length?{submission_warnings:order.warnings}:{})});
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}:{})});
1261
1601
  }
1262
1602
  // Defer refuses only for a requester that opts in; both the CLI and HTTP API queue by default.
1263
1603
  if(order?.verdict==='defer'&&body.refuse_defer===true&&body.queue_anyway!==true) {
@@ -1268,7 +1608,7 @@ const adminServer=http.createServer(async(req,res)=>{
1268
1608
  const readiness=order?.check_readiness??null;
1269
1609
  const preflight=order?.preflight??null;
1270
1610
  const defaultValidity=order?.defaultValidity??null;
1271
- 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);
1611
+ 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);
1272
1612
  // Only a committed first replacement wakes the TARGET's already-attached waiter.
1273
1613
  if(supersedes&&!result.duplicate) {
1274
1614
  const targetId=supersedes.target_id,waiter=waiters.get(targetId);
@@ -1278,7 +1618,7 @@ const adminServer=http.createServer(async(req,res)=>{
1278
1618
  // A retry validates nothing, so the narrowing it reports comes from the stored assignment.
1279
1619
  const stored=result.duplicate?JSON.parse(store.db.prepare('SELECT payload FROM assignments WHERE request_id=?').get(payload.request_id).payload):payload;
1280
1620
  if(stored.scope_excluded?.length&&!result.duplicate) log({kind:'scope_excluded',request_id:payload.request_id,excluded:stored.scope_excluded});
1281
- return json(res,200,{...result,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}:{})});
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}:{})});
1282
1622
  }
1283
1623
  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'}:{})}); }
1284
1624
  if(url.pathname==='/get') {
@@ -1289,6 +1629,10 @@ const adminServer=http.createServer(async(req,res)=>{
1289
1629
  store.recordFetched(requestId);
1290
1630
  // Read before recording consumption: the response then matches a peek read, which records no consumption.
1291
1631
  const got=maskedForOwner(withAvailableChecks(store.get(requestId)));
1632
+ if(req.method==='GET'&&url.searchParams.get('admission')==='1'&&got.status==='queued') {
1633
+ const snapshot=store.admissionForQueuedRequest(requestId);
1634
+ if(snapshot) got.admission=snapshot;
1635
+ }
1292
1636
  if(url.searchParams.get('peek')!=='1') store.recordConsumed(requestId,'get');
1293
1637
  if(protocolServices&&store.isProtocolJob(requestId))got.protocol_stop=protocolServices.observation(requestId);
1294
1638
  // The owner needs the current revision to build a keyed, revision-checked command such as `dalan answer`. It is null for a job with no protocol revisions.
@@ -1297,7 +1641,21 @@ const adminServer=http.createServer(async(req,res)=>{
1297
1641
  try { return json(res,200,{...got,check_metadata:workspace.checkMetadataFor(got.assignment,got.target_worker)}); }
1298
1642
  catch(error) { return json(res,200,{...got,check_metadata:null,check_metadata_error:publicErrorText(error,'check metadata')}); }
1299
1643
  }
1300
- if(url.pathname==='/artifact') { const artifactId=id(url.searchParams.get('id'),'artifact_id');const row=store.db.prepare('SELECT request_id FROM artifacts WHERE id=? AND sealed=1').get(artifactId);if(!row) throw new Error('artifact not found');adminOwner(req,row.request_id);const bytes=(workspace||new Workspace(store,false)).artifact(artifactId,row.request_id);res.writeHead(200,{'content-type':'application/octet-stream','content-length':bytes.bytes.length,'x-artifact-sha256':bytes.row.sha256});res.end(bytes.bytes);return; }
1644
+ if(url.pathname==='/artifact') {
1645
+ const artifactId=id(url.searchParams.get('id'),'artifact_id');
1646
+ const row=store.db.prepare('SELECT request_id FROM artifacts WHERE id=? AND sealed=1').get(artifactId);
1647
+ if(!row) throw new Error('artifact not found');
1648
+ adminOwner(req,row.request_id);
1649
+ const artifact=(workspace||new Workspace(store,false)).artifact(artifactId,row.request_id);
1650
+ try {
1651
+ guardArtifactDownload({id:artifactId,requestId:row.request_id,sha256:artifact.row.sha256,bytes:artifact.bytes});
1652
+ } catch(error) {
1653
+ if(error.code==='artifact_secret_content') return json(res,422,{code:error.code,error:error.message});
1654
+ throw error;
1655
+ }
1656
+ res.writeHead(200,{'content-type':'application/octet-stream','content-length':artifact.bytes.length,'x-artifact-sha256':artifact.row.sha256});
1657
+ res.end(artifact.bytes);return;
1658
+ }
1301
1659
  if(['/protocol/wait','/protocol/inbox','/protocol/ack'].includes(url.pathname)&&req.method==='POST') {
1302
1660
  if(catalogProfile!=='protocol-v0') throw new Error('protocol owner routes require DALAN_CATALOG_PROFILE=protocol-v0');
1303
1661
  const requestId=id(body.id),owner=req.headers['x-owner-capability'];
@@ -1338,7 +1696,7 @@ const adminServer=http.createServer(async(req,res)=>{
1338
1696
  // Only evidence holds refill: a pause or an owner-confirmed break. throttled stays false for older readers.
1339
1697
  const paused=store.paused(), dotBreak=!!store.holdingBreak();
1340
1698
  const held=paused?'paused':dotBreak?'worker_break':null;
1341
- return json(res,200,{states,refill:{held,paused,worker_break:dotBreak,throttled:false}});
1699
+ return json(res,200,{states,refill:{held,paused,worker_break:dotBreak,break_active:!!store.activeBreak(),throttled:false}});
1342
1700
  }
1343
1701
  if(url.pathname==='/tools'&&req.method==='GET') { adminOperator(req); return json(res,200,{tools:toolRegistry.list()}); }
1344
1702
  if(url.pathname.startsWith('/tools/')&&req.method==='POST') {
@@ -1351,7 +1709,7 @@ const adminServer=http.createServer(async(req,res)=>{
1351
1709
  if(action==='revoke') { toolRegistry.revoke(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:false}); }
1352
1710
  } catch(error) { if(error instanceof RegistryError) throw new Error(`${error.code}: ${error.message}`); throw error; }
1353
1711
  }
1354
- if(url.pathname==='/status') return json(res,200,{last_registry_change:toolRegistry.lastChange(),...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});
1712
+ if(url.pathname==='/status') return json(res,200,{last_registry_change:toolRegistry.lastChange(),...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});
1355
1713
  if(url.pathname==='/metrics'&&req.method==='GET') return json(res,200,lifecycleMetrics(store,{since:url.searchParams.get('since'),laneCapacity:redeliveryLimits.laneCapacity}));
1356
1714
  if(['/accept','/reject'].includes(url.pathname)&&req.method==='POST') {
1357
1715
  const requestId=id(body.id); adminOwner(req,requestId);
@@ -1385,6 +1743,10 @@ const adminServer=http.createServer(async(req,res)=>{
1385
1743
  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')));
1386
1744
  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)));
1387
1745
  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()}); }
1746
+ if(url.pathname==='/relationships/publish'&&req.method==='POST') {
1747
+ adminOperator(req);
1748
+ return json(res,200,{relationship:store.setPublishGrant(str(body.relationship_id,'relationship_id',128),parsePublishGrant(body.grant===undefined?null:body.grant))});
1749
+ }
1388
1750
  if(url.pathname==='/relationships/end'&&req.method==='POST') {
1389
1751
  adminOperator(req);
1390
1752
  const relationshipId=str(body.relationship_id,'relationship_id',128);
@@ -1445,6 +1807,16 @@ const adminServer=http.createServer(async(req,res)=>{
1445
1807
  if(body.dry_run!==undefined&&typeof body.dry_run!=='boolean') throw new Error('invalid dry_run');
1446
1808
  return json(res,200,store.backfillObjectives(body.tuples,{dryRun:body.dry_run===true}));
1447
1809
  }
1810
+ if(url.pathname==='/quiesce'&&(req.method==='GET'||req.method==='POST')) {
1811
+ adminOperator(req);
1812
+ if(req.method==='POST') {
1813
+ if(typeof body.on!=='boolean')return json(res,400,{error:'on must be a boolean'});
1814
+ // Clear the old eligibility at entry too: an interrupted quiesce may never receive an off call.
1815
+ if(body.on!==quiescing) store.restartSkipClock();
1816
+ quiescing=body.on;
1817
+ }
1818
+ return json(res,200,quiesceStatus());
1819
+ }
1448
1820
  if(url.pathname==='/claims'&&req.method==='GET') { adminOperator(req); return json(res,200,{lease_ms:store.limits.leaseMs,claims:store.claims()}); }
1449
1821
  if(url.pathname==='/abandon'&&req.method==='POST') {
1450
1822
  adminOperator(req);
@@ -1468,8 +1840,14 @@ const adminServer=http.createServer(async(req,res)=>{
1468
1840
  if(url.pathname==='/break'&&req.method==='POST') {
1469
1841
  adminOperator(req);
1470
1842
  if(body.clear===true) { const cleared=store.clearBreak(); sweepExpired(); return json(res,200,cleared); }
1471
- if(body.since!==undefined&&body.since!==null&&(typeof body.since!=='string'||!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(body.since)||!Number.isFinite(Date.parse(body.since)))) throw new Error('since must be an RFC 3339 time with offset');
1472
- const result=store.setBreak(str(body.reason,'reason',512),body.since?new Date(body.since).toISOString():null);
1843
+ const time=field=>{
1844
+ const value=body[field];
1845
+ if(value==null) return value;
1846
+ if(typeof value!=='string'||!/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?(?:Z|[+-]\d\d:\d\d)$/.test(value)||!Number.isFinite(Date.parse(value)))
1847
+ throw new Error(`${field} must be an RFC 3339 time with offset`);
1848
+ return new Date(value).toISOString();
1849
+ };
1850
+ const result=store.setBreak(str(body.reason,'reason',512),time('since'),time('until'));
1473
1851
  log({kind:'worker_break_set',source:'owner',since:result.since});
1474
1852
  return json(res,200,result);
1475
1853
  }
@@ -1500,7 +1878,14 @@ const adminServer=http.createServer(async(req,res)=>{
1500
1878
  const reasons=!infrastructure&&rejected?(e.reasons??reasonsFromError(e).map(({verdict,retry,blocking,...r})=>r)):null;
1501
1879
  const verdict=reasons?(e.verdict??strongest(reasonsFromError(e))):null;
1502
1880
  // A dry run answers every verdict with a 200 and stores nothing, including a refusal raised before the compiler ran.
1503
- if(dryRequested&&reasons) { log({kind:'submit_dry_run',...rejected,verdict,reason_codes:reasons.map(r=>r.code),attempt_latency_ms:Date.now()-requestStartedAt}); return json(res,200,{dry_run:true,stored:false,request_id:rejected?.request_id??null,verdict,reasons,bytes:e.bytes??null,warnings:[]}); }
1881
+ if(dryRequested&&reasons) {
1882
+ let advice;
1883
+ if(previewMayReportAdmission&&admission) {
1884
+ try { advice=admission(); } catch { /* Advice must not hide the original refusal. */ }
1885
+ }
1886
+ log({kind:'submit_dry_run',...rejected,verdict,reason_codes:reasons.map(r=>r.code),attempt_latency_ms:Date.now()-requestStartedAt});
1887
+ return json(res,200,{dry_run:true,stored:false,request_id:rejected?.request_id??null,verdict,reasons,bytes:e.bytes??null,warnings:[],...(advice?{admission:advice}:{})});
1888
+ }
1504
1889
  if(rejected) log({kind:'submit_rejected',...rejected,status:infrastructure?503:400,reason:e.message.slice(0,300),...(reasons?{verdict,reason_codes:reasons.map(r=>r.code)}:{}),bytes:e.bytes??null,attempt_latency_ms:Date.now()-requestStartedAt,...(e.suggested_scope_paths?{suggested_scope_count:e.suggested_scope_paths.length}:{})});
1505
1890
  if(infrastructure&&!rejected) log({kind:'admin_infrastructure_error',route:String(req.url).split('?')[0],code:e.code??null,reason:e.message.slice(0,300)});
1506
1891
  const shown=publicErrorText(e,'admin request');
@@ -1560,11 +1945,11 @@ async function reconcileTick() {
1560
1945
  }
1561
1946
  let delivering=false;
1562
1947
  async function drain() {
1563
- if(delivering||store.paused()) return; delivering=true;
1948
+ if(delivering||quiescing||store.paused()) return; delivering=true;
1564
1949
  try {
1565
1950
  store.reannounceQueued(redeliveryLimits);
1566
1951
  for(const item of store.due()) {
1567
- if(store.paused()) break;
1952
+ if(quiescing||store.paused()) break;
1568
1953
  const row=item.kind==='event'?null:store.get(item.request_id);
1569
1954
  let destination=null;
1570
1955
  if(row) {
@@ -1582,6 +1967,8 @@ async function drain() {
1582
1967
  if(reason) { store.quietDelivery(item.id,reason); notifyAttachedWaiter(item.request_id); continue; }
1583
1968
  }
1584
1969
  const argv=row?destination.argv(item,row):null;
1970
+ // Destination selection can await across the admin toggle.
1971
+ if(quiescing||store.paused()) break;
1585
1972
  const started=store.startAttempt(item.id,argv); if(!started) continue;
1586
1973
  if(crashAt('after_attempt_commit',item.request_id)) process.exit(71);
1587
1974
  let state='failed',reason='';
@@ -1603,7 +1990,11 @@ async function drain() {
1603
1990
  // An earlier ACK is not a new callback and must not clear callback failures.
1604
1991
  if(ackLedger.has(ack)) { ackDurablyRecorded=true; state='delivered'; reason='recovered from durable webhook acceptance acknowledgment'; }
1605
1992
  else {
1606
- const response=await sendWebhook(sub.url,store.subscriptionSecret(sub),item.id,sub.id,item.body);
1993
+ const sentAt=Date.now(),sentMono=performance.now();
1994
+ let response;
1995
+ try { response=await sendWebhook(sub.url,store.subscriptionSecret(sub),item.id,sub.id,item.body); }
1996
+ catch(error) { phaseTrace.wake({item,worker:sub.worker,attemptAt:sentAt,ackMs:null,status:null,state:'failed'}); throw error; }
1997
+ phaseTrace.wake({item,worker:sub.worker,attemptAt:sentAt,ackMs:performance.now()-sentMono,status:response.status,state:response.status>=200&&response.status<300?'delivered':'failed'});
1607
1998
  if(response.status>=200&&response.status<300) { positiveAckObserved=true; ackLedger.record(ack); ackDurablyRecorded=true; }
1608
1999
  store.eventResult(sub.id,response.status);
1609
2000
  state=response.status>=200&&response.status<300?'delivered':response.status===410||response.status===413?'suppressed':'failed';
@@ -1627,15 +2018,29 @@ function maintain() {
1627
2018
  } catch(error) { log({kind:'maintenance_error',reason:error.message}); }
1628
2019
  }
1629
2020
  const runDrain=createDrainRunner(drain,log);
2021
+ ensureAdminSocketDir(socket);
1630
2022
  try { fs.unlinkSync(socket); } catch(e) { if(e.code!=='ENOENT') throw e; }
1631
2023
  const adminListening=new Promise(resolve=>adminServer.listen(socket,()=>{fs.chmodSync(socket,0o600);console.log(`admin socket ${socket}`);resolve();}));
1632
2024
  // Built-in mode sits behind a tunnel on this computer: only loopback may reach the listener.
1633
2025
  const bindHost=readEnv('DALAN_BIND_HOST')||(as||loopbackOnly||loopback?'127.0.0.1':'0.0.0.0');
1634
2026
  const publicListening=new Promise(resolve=>publicServer.listen(port,bindHost,()=>{console.log(`MCP listening on ${bindHost}:${publicServer.address().port}`);resolve();}));
2027
+ const loopbackProbeMs=Number(readEnv('DALAN_LOOPBACK_PROBE_MS')??30000);
2028
+ if(!Number.isInteger(loopbackProbeMs)||loopbackProbeMs<0||(loopbackProbeMs>0&&loopbackProbeMs<1000)) throw new Error('DALAN_LOOPBACK_PROBE_MS must be 0 or at least 1000');
2029
+ let loopbackProbe=null;
1635
2030
  // Every background writer starts only when no update window is open, so a candidate restarted inside the window changes no state
1636
2031
  // the rollback snapshot would discard. Outside a window this runs at once, in the same order as before.
1637
2032
  function startBackground() {
2033
+ if (verifyService && as && readEnv('DALAN_TRIAL_SSE') !== '1') void publicListening.then(() => watchServicePublication({
2034
+ home, configDir, origin: new URL(as.publicUrl).origin, secret, canWrite: () => !updateWindowOpen(),
2035
+ }));
1638
2036
  store.recoverSends();
2037
+ // A boot is a reopen: a restart during quiesce ends it with no off call, and time the process was down was not claimable time.
2038
+ // Ordinary restarts retain earned eligibility; explicit pause and quiesce own the resets.
2039
+ // Off with DALAN_LOOPBACK_PROBE_MS=0. It asks the bridge's own listener a question every 30 s (default) and logs a slow or failed answer.
2040
+ if(loopbackProbeMs>0) {
2041
+ loopbackProbe=createLoopbackProbe({url:()=>{const {address,port}=publicServer.address();return `http://${['0.0.0.0','::'].includes(address)?'127.0.0.1':address.includes(':')?`[${address}]`:address}:${port}/`;},log,intervalMs:loopbackProbeMs});
2042
+ void publicListening.then(()=>loopbackProbe.start());
2043
+ }
1639
2044
  // Cleanup removes worktrees and dependency caches; it starts only after both servers listen, and
1640
2045
  // cleanupExpired is async and single-flight, so neither startup nor the hourly tick blocks requests.
1641
2046
  if(workspace) {