@tnunamak/dalan 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/CONTRIBUTING.md +2 -0
  3. package/PROTOCOL.md +6 -0
  4. package/README.md +8 -12
  5. package/bin/dalan.mjs +25 -4
  6. package/bin/dot-acp-agent.mjs +572 -76
  7. package/bin/dot-alert.mjs +9 -3
  8. package/bin/dot-deadman.mjs +3 -1
  9. package/bin/dot-heartbeat.mjs +14 -7
  10. package/bin/dot-pr-reviewer.mjs +3 -31
  11. package/bin/dot-worker.mjs +215 -40
  12. package/contracts/adapter-qualification.schema.json +94 -7
  13. package/docs/chatgpt-worker-onboarding.md +1 -1
  14. package/docs/codex-to-muse.md +2 -2
  15. package/docs/connect-chatgpt.md +1 -1
  16. package/docs/connection-longevity.md +2 -2
  17. package/docs/dalan-upgrade.md +8 -5
  18. package/docs/deadman.md +4 -0
  19. package/docs/design/authority-matrix.md +18 -0
  20. package/docs/design/failure-table.md +87 -0
  21. package/docs/design/identities.md +22 -0
  22. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  23. package/docs/design/reuse-ledger.md +75 -0
  24. package/docs/design/target-architecture-v2.md +434 -0
  25. package/docs/local-agent-mcp.md +14 -0
  26. package/docs/local-agent-requester.md +3 -2
  27. package/docs/manual-setup.md +1 -1
  28. package/docs/operations.md +78 -14
  29. package/docs/pull-workers.md +11 -0
  30. package/docs/relationships.md +13 -0
  31. package/docs/service-setup.md +10 -10
  32. package/docs/t3-integration.md +6 -2
  33. package/docs/t3-reverse-control.md +5 -5
  34. package/docs/t3-wake-fence-r4.md +1 -1
  35. package/docs/test-suite-isolation.md +8 -6
  36. package/docs/trials/chatgpt-agent.md +47 -0
  37. package/docs/trials/claude-code-requester.md +68 -0
  38. package/docs/trials/muse.md +46 -0
  39. package/docs/usage.md +35 -9
  40. package/docs/worker-clients.md +1 -1
  41. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  42. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  43. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  44. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  45. package/package.json +4 -3
  46. package/packages/job-core/protocol/canonical.mjs +45 -7
  47. package/packages/job-core/transitions.mjs +4 -2
  48. package/scripts/upgrade-drain.mjs +96 -8
  49. package/scripts/worker-bridge-setup.mjs +215 -120
  50. package/src/ack-ledger.mjs +7 -1
  51. package/src/acp-bridge.mjs +256 -28
  52. package/src/admin-socket.mjs +32 -3
  53. package/src/alerts.mjs +17 -8
  54. package/src/answer-journal-retention.mjs +82 -0
  55. package/src/answer-journal.mjs +6 -4
  56. package/src/as-store.mjs +51 -6
  57. package/src/as.mjs +27 -5
  58. package/src/catalog-switch-inventory.mjs +70 -0
  59. package/src/check-response.mjs +4 -1
  60. package/src/claim-command-ledger.mjs +3 -2
  61. package/src/cli-help.mjs +29 -10
  62. package/src/cli-name.mjs +13 -1
  63. package/src/connect-cli.mjs +159 -4
  64. package/src/deadman.mjs +8 -5
  65. package/src/delivery.mjs +2 -19
  66. package/src/destinations/index.mjs +75 -14
  67. package/src/drain-runner.mjs +5 -1
  68. package/src/follow-current.mjs +3 -1
  69. package/src/get-summary.mjs +11 -2
  70. package/src/git-env.mjs +1 -1
  71. package/src/gozar-routes.mjs +313 -94
  72. package/src/host-budget-storage.py +56 -6
  73. package/src/host-budget.mjs +98 -15
  74. package/src/host-execution-policy.mjs +17 -6
  75. package/src/inbox.mjs +13 -3
  76. package/src/legacy-names.mjs +0 -2
  77. package/src/lifecycle.mjs +104 -11
  78. package/src/loopback-probe.mjs +46 -0
  79. package/src/mcp-outcome.mjs +3 -1
  80. package/src/mcp-sse.mjs +2 -1
  81. package/src/mcp-stdio.mjs +192 -30
  82. package/src/patch-apply.mjs +285 -19
  83. package/src/phase-trace.mjs +73 -0
  84. package/src/prepared-go-modules.mjs +127 -0
  85. package/src/prepared-node-modules.mjs +225 -38
  86. package/src/prepared-pnpm.mjs +276 -0
  87. package/src/prepared-store-prune.mjs +52 -0
  88. package/src/projects.mjs +59 -7
  89. package/src/protocol-artifact-commands.mjs +28 -0
  90. package/src/protocol-finish.mjs +3 -2
  91. package/src/publication-authority.mjs +22 -0
  92. package/src/publish-plan.mjs +2 -2
  93. package/src/pull-queue.mjs +55 -20
  94. package/src/read-api.mjs +127 -0
  95. package/src/redaction.mjs +173 -0
  96. package/src/rejections.mjs +19 -3
  97. package/src/route-custody.mjs +90 -0
  98. package/src/route-publication.mjs +50 -0
  99. package/src/route-setup.mjs +184 -0
  100. package/src/schema-subset.mjs +5 -3
  101. package/src/server.mjs +619 -88
  102. package/src/service-launchd.mjs +5 -1
  103. package/src/service-update-lock.mjs +7 -4
  104. package/src/service-update-runtime.mjs +64 -19
  105. package/src/service-update.mjs +193 -48
  106. package/src/service.mjs +276 -77
  107. package/src/setup.mjs +48 -25
  108. package/src/signal.mjs +1 -1
  109. package/src/status-evidence.mjs +18 -5
  110. package/src/status-summary.mjs +3 -0
  111. package/src/store.mjs +1086 -127
  112. package/src/submission-policy.mjs +257 -56
  113. package/src/t3-control.mjs +1 -1
  114. package/src/t3.mjs +14 -8
  115. package/src/terminal-safe.mjs +9 -7
  116. package/src/tool-registry.mjs +134 -41
  117. package/src/try-exposure.mjs +53 -86
  118. package/src/try-hosted.mjs +257 -70
  119. package/src/try.mjs +48 -22
  120. package/src/work-order.mjs +11 -6
  121. package/src/worker-instructions.mjs +26 -4
  122. package/src/worker-runs.mjs +35 -0
  123. package/src/workers.mjs +49 -4
  124. package/src/workspace.mjs +354 -54
  125. package/systemd/dot-deadman.service +3 -1
  126. package/docs/dot-pr-reviewer.config.example.json +0 -9
  127. package/docs/pr-head-reviewer.md +0 -70
  128. package/src/pr-head-reviewer.mjs +0 -596
  129. package/systemd/dot-pr-reviewer.service +0 -11
  130. 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';
@@ -14,9 +16,11 @@ import fs from 'node:fs';
14
16
  import path from 'node:path';
15
17
  import os from 'node:os';
16
18
  import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
17
- import { loadWorkers, hasInstalledDatabase, legacyMarkerPath, seedWorkerRepos, resolveWorker, hasCapability, assertTarget, submitTarget } from './workers.mjs';
18
- import { Store, QUESTION_PURPOSES, nonterminalOutcome, validateProtocol, loadRedeliveryLimits, resumeNudge } from './store.mjs';
19
- import {protocolArtifactChunk} from './protocol-artifact-commands.mjs';
19
+ import { loadWorkers, loadEffectiveOwnerWorkers, hasInstalledDatabase, legacyMarkerPath, seedWorkerRepos, resolveWorker, hasCapability, assertTarget, submitTarget, ensureWorkerRelationship } from './workers.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';
@@ -38,15 +42,17 @@ import { parseExecution, parseRequiredCapabilities, admitHostExecution, admitAda
38
42
  import { loadCapacity } from './projects.mjs';
39
43
  import { authConfig, assertPublicRouteAuth, isLoopbackBindHost, protectedResource, challenge, verifyBearer, needScope } from './auth.mjs';
40
44
  import { beginMcpOutcome, recordMcpResponse, pathShape, uaToken } from './mcp-outcome.mjs';
41
- import { lifecycleMetrics, retainLifecycle } from './lifecycle.mjs';
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; }
@@ -148,6 +156,9 @@ const store = new Store(path.join(dataDir, 'bridge.db'),{
148
156
  // Intentional service startup opts past Store's accidental-migration footgun guard.
149
157
  deferSubscriptionRetirement:true,markProfileModeSeen:!legacyProfile,allowDefaultHomeMigration:true
150
158
  });
159
+ // An offline worker allow can precede the database. Reconcile named profiles at startup;
160
+ // legacy installations retain their pre-relationship behavior until explicitly enrolled.
161
+ if(!legacyProfile) for(const worker of workers.workers.keys()) ensureWorkerRelationship(store.db,worker);
151
162
  const ackLedger=new AckLedger(path.join(dataDir,'delivery-acks.db'));
152
163
  const notifyLedger=new NotifyLedger(path.join(dataDir,'notify-sent.db'));
153
164
  process.on('exit',()=>{try{ackLedger.close();}catch{}try{notifyLedger.close();}catch{}});
@@ -164,12 +175,59 @@ if(t3ToolsEnabled) await loadT3Audit();
164
175
  // A valid but unallocated ID preserves each tool's existing absent-request errors. Never accept it as an owner target.
165
176
  const absentId=`req_${randomUUID()}`;
166
177
  if(store.hasAssignment(absentId)) throw new Error('absent gate id collision');
167
- const socket = path.join(dataDir, 'admin.sock');
168
178
  const log = createRequestLog(path.join(stateDir, 'requests.jsonl'));
179
+ const guardArtifactDownload = createArtifactDownloadGuard({log});
180
+ const phaseTrace = createPhaseTrace({ log });
169
181
  logShutdownSignals(log);
170
- // 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.
171
183
  const t3PostHandler=createT3PostHandler({store,now:()=>store.nowMs()});
172
- 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
+ },
173
231
  audit:entry=>log({kind:'tool_registry',...entry})});
174
232
  for(const warning of pathWarnings) {
175
233
  const entry={kind:'root_passed_over',...warning};
@@ -242,7 +300,9 @@ function withAvailableChecks(response,workerSurface=false,worker='dot',subject=n
242
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));
243
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);
244
302
  const blocker=workerSurface?null:queuedRepositoryBlocker(response);
245
- 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}:{})};
246
306
  if(!workspaceEnabled||response.assignment?.execution_scope!=='implementation') return enriched;
247
307
  if(workerSurface&&workspaceAllowed===null) {
248
308
  try { workspaceAllowed=workerWorkspaceAllowed(worker,response.request_id); }
@@ -295,7 +355,7 @@ function publicWorkerGet(response) {
295
355
  }
296
356
  const questions=store.questions(response.request_id).map(({claim_id,subject,...question})=>question);
297
357
  if(questions.length) response={...response,questions};
298
- const {assignment,...rest}=response;
358
+ const {assignment,publication_authority,...rest}=response;
299
359
  const projected=rest.claim?{...rest,claim:Object.fromEntries(publicClaimFields.filter(key=>Object.hasOwn(rest.claim,key)).map(key=>[key,rest.claim[key]]))}:rest;
300
360
  const redacted=omitWorkerCapabilityKeys(projected);
301
361
  return Object.hasOwn(response,'assignment')?{...redacted,assignment}:redacted;
@@ -350,15 +410,18 @@ const message={type:'string',maxLength:262144};
350
410
  const bool={type:'boolean'};
351
411
  const maxT3WaitMs=catalogProfile==='legacy-v46'?120000:90000;
352
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
+ ];
353
417
  const tools = [
354
418
  { name:'list_pending',description:'List up to 50 queued assignment IDs and titles.',inputSchema:schema({}) },
355
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']) },
356
420
  { name:'get',description:'Read assignment, available_checks, cancellation, progress, report and delivery facts.',inputSchema:schema({request_id:string},['request_id']) },
357
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']) },
358
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']) },
359
- { 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']) },
360
- { 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']) },
361
- { 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']) },
362
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']) },
363
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']) },
364
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']) },
@@ -375,7 +438,18 @@ const tools = [
375
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({}) },
376
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']) },
377
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']) }
378
- ].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
+ }
379
453
  // Opt-in compatibility catalog only; grant and lease enforcement are unchanged.
380
454
  if(catalogProfile==='legacy-v46') {
381
455
  const names=new Set(['list_pending','claim','get','ack_message','progress','finish',
@@ -450,6 +524,25 @@ if(fs.existsSync(catalogGuardFile)) {
450
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]));
451
525
  if(guard.version!==packageVersion||JSON.stringify(normalize(ordered(guard.catalogs??{})))!==JSON.stringify(normalize(ordered(actual))))throw new Error('service catalog guard mismatch');
452
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
+ }
453
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".
454
547
  const argumentFixes={
455
548
  finish:{
@@ -458,7 +551,8 @@ const argumentFixes={
458
551
  artifact_ids:'artifact_ids must be at most 8 strings; call finish again with fewer ids',
459
552
  summary:'summary must be text; call finish again with a string or leave summary out'
460
553
  },
461
- 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'}
462
556
  };
463
557
  const SUMMARY_MAX=4096,NOTE_MAX=4096;
464
558
  const clipWithMarker=(text,max,marker)=>`${Store.clipBytes(text,max-Buffer.byteLength(marker))}${marker}`;
@@ -484,8 +578,7 @@ function repairArguments(name,args) {
484
578
  marks.summary_derived=true;
485
579
  return {args:{...args,summary:Store.clipBytes(first,SUMMARY_MAX)},marks};
486
580
  }
487
- function validate(name,args) {
488
- 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');
489
582
  const refuse=(kind,field)=>{
490
583
  const fix=argumentFixes[name]?.[field];
491
584
  // repairArguments already derives a missing summary, so a summary that is still missing means the result cannot supply one.
@@ -494,8 +587,12 @@ function validate(name,args) {
494
587
  };
495
588
  if(!args||typeof args!=='object'||Array.isArray(args)) throw new Error('invalid arguments');
496
589
  const s=definition.inputSchema;
497
- 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}`);
498
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
+ }
499
596
  // The schema no longer requires summary, but one must exist by now: repairArguments could not derive it when the result is blank.
500
597
  if(name==='finish'&&(args.summary===undefined||typeof args.summary==='string'&&!args.summary.trim())) throw refuse('missing','summary');
501
598
  for(const [field,value] of Object.entries(args)) {
@@ -505,7 +602,7 @@ function validate(name,args) {
505
602
  if(rule.type==='integer'&&(!Number.isInteger(value)||(rule.minimum!==undefined&&value<rule.minimum)||(rule.maximum!==undefined&&value>rule.maximum))) throw refuse('invalid',field);
506
603
  if(rule.type==='boolean'&&typeof value!=='boolean') throw refuse('invalid',field);
507
604
  if(rule.type==='object'&&(!value||typeof value!=='object'||Array.isArray(value))) throw refuse('invalid',field);
508
- 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);
509
606
  if(rule.enum&&!rule.enum.includes(value)||rule.pattern&&!new RegExp(rule.pattern).test(value)) throw refuse('invalid',field);
510
607
  }
511
608
  }
@@ -521,14 +618,25 @@ function artifactIdsFor(requestId, report) {
521
618
  for(const check of evidence?.checks??[]) if(check?.output_artifact_id) ids.add(check.output_artifact_id);
522
619
  return [...ids];
523
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
+ }
524
630
  function waitSummary(requestId, attention=null) {
525
631
  const row=store.get(requestId);
526
632
  const body=attention?.body?JSON.parse(attention.body):null, note=body?.note??null;
527
633
  // A usage-break notice: the request stays queued; the owner may do it elsewhere or wait again.
528
- 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);
529
635
  const status=row.status==='finished'?'finished':row.status==='cancelled'?'cancelled':/^\s*QUESTION:/im.test(note??'')?'question':'blocker';
530
636
  const failure=store.failureFields(requestId);
531
- 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}:{})};
532
640
  }
533
641
  function notifyAttachedWaiter(requestId) {
534
642
  const waiter=waiters.get(requestId);
@@ -580,15 +688,63 @@ function sweepStaleLeases() {
580
688
  return ids;
581
689
  }
582
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
+
583
732
  async function attachWaiter(req,res,requestId,timeoutMs,consume=true) {
584
733
  const immediate=store.get(requestId);
585
734
  if(['finished','cancelled'].includes(immediate.status)) { store.recordFetched(requestId);if(consume) store.recordConsumed(requestId,'wait'); return json(res,200,waitSummary(requestId)); }
586
- if(waiters.has(requestId)) return json(res,409,{error:'waiter already attached'});
735
+ if(waiters.has(requestId))return attachTerminalWaiter(req,res,requestId,timeoutMs,consume);
587
736
  const queueBlocker=queuedRepositoryBlocker(immediate);
588
737
  if(queueBlocker) return json(res,200,{status:'blocker',report_summary:null,blocker_text:queueBlocker.message,artifact_ids:[],queue_blocker:queueBlocker});
589
738
  // `none` has no fallback delivery channel, so a newly attached waiter must
590
739
  // also observe attention recorded before it attached.
591
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);
592
748
  const waiter={res,timer:null,consume,cursor:immediate.delivery_mode==='none'||destination.quietReason(immediate)?0:store.deliveryCursor(requestId)};
593
749
  const detach=()=>{
594
750
  if(waiters.get(requestId)!==waiter) return;
@@ -608,6 +764,8 @@ async function attachWaiter(req,res,requestId,timeoutMs,consume=true) {
608
764
  return json(res,200,waitSummary(requestId));
609
765
  }
610
766
  blocker=queuedRepositoryBlocker(row);
767
+ const workerBreak=!blocker&&activeBreakWait(row);
768
+ if(workerBreak) return json(res,200,workerBreak);
611
769
  } catch { /* the request may have expired while waiting */ }
612
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:[]});
613
771
  },timeoutMs);
@@ -615,11 +773,178 @@ async function attachWaiter(req,res,requestId,timeoutMs,consume=true) {
615
773
  waiters.set(requestId,waiter);
616
774
  notifyAttachedWaiter(requestId);
617
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
+ }
618
794
  // Result guidance only; tool descriptions stay fixed.
619
- 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.';
620
- 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.`;
621
806
  // A finishing lane takes the next queued item itself; an error on any claim means the list changed, so list again.
622
- 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.`;
808
+ // A worker with finish_handoff gets its next job inside the finish reply, or waits a bounded time for work.
809
+ // The claim is the worker's own `claim` call, run by the bridge: same policy, preflight, scope, pause, capacity and
810
+ // connection checks, one claim per job. The claim carries acquisition_id handoff-<finished claim_id>, so a repeated
811
+ // finish gets the same job back, and a second finish by the same claimant name, which would otherwise count as an
812
+ // exact retry of the first claim, is refused that job and takes the next one.
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;
815
+ const nap=(ms,signal)=>new Promise(resolve=>{
816
+ const done=()=>{clearTimeout(timer);signal?.removeEventListener('abort',done);resolve();};
817
+ const timer=setTimeout(done,ms);
818
+ signal?.addEventListener('abort',done,{once:true});
819
+ });
820
+ // One handoff per finished claim at a time: a retried finish that arrives while the first is still waiting or
821
+ // claiming queues behind it, then finds the first one's grant instead of taking a second job.
822
+ const handoffsInFlight=new Map();
823
+ async function handOffNextJob(args) {
824
+ const key=`${args.principal.worker}\0${args.principal.subject}\0${args.claimId}`;
825
+ while(handoffsInFlight.has(key)) await handoffsInFlight.get(key);
826
+ const run=runHandoff(args).finally(()=>handoffsInFlight.delete(key));
827
+ handoffsInFlight.set(key,run);
828
+ return run;
829
+ }
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
835
+ try {
836
+ const {worker,subject}=principal;
837
+ const held=store.db.prepare('SELECT claimant FROM claims WHERE request_id=? AND claim_id=?').get(requestId,claimId);
838
+ if(!held) return {};
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)=>{
842
+ try {
843
+ const job=await tool('claim',{request_id:next,claimant:held.claimant,acquisition_id,lease_ms},principal,undefined,signal);
844
+ return job&&typeof job.error!=='string'&&job.claim_id?{...job,already_claimed:true}:null;
845
+ } catch { return null; }
846
+ };
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
+ }
855
+ const started=Date.now(),tried=new Set();
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??[]);
861
+ for(;;) {
862
+ if(signal?.aborted||store.paused()) return jobs.length?{jobs}:{};
863
+ const {free_lanes}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
864
+ if(free_lanes<=0) return jobs.length?{jobs}:{};
865
+ if(store.hasQueuedFor([worker])) {
866
+ sawQueued=true;
867
+ // A lost race or an unclaimable head moves on to the next job; an unclaimable queue ends in the old hint.
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
+ }
881
+ tried.add(fresh[0].request_id);
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);
887
+ }
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}:{};
890
+ }
891
+ const left=started+waitMs-Date.now();
892
+ if(left<=0) return sawQueued?{}:{empty:true,waited_ms:Date.now()-started};
893
+ await nap(Math.min(HANDOFF_POLL_MS,left),signal);
894
+ }
895
+ } catch(error) { log({kind:'finish_handoff_error',request_id:requestId,reason:redactNote(String(error?.message??error))}); return jobs.length?{jobs}:{}; }
896
+ }
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;
905
+ const setting=workers.workers.get(principal.worker)?.finishHandoff;
906
+ if(setting&&reply.receipt_id&&!store.isProtocolJob(requestId)) {
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});
909
+ const {next_queued,next_action,...rest}=reply;
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};
928
+ }
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}));
947
+ }
623
948
  // A loader failure carries host paths or quotes the file. Every caller of this policy gets the Store's fixed error instead.
624
949
  function repoPolicyFor(assignment) {
625
950
  try { return currentRepoPolicy(); }
@@ -664,7 +989,7 @@ const policyPage=(worker,cursor=null)=>store.pullQueue.list(worker,admitPolicyWo
664
989
  async function submitPolicy(body,req,dryRun) {
665
990
  if(req.method!=='POST')throw new Error('policy submit requires POST');
666
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');
667
- if(body.worker!==undefined||body.command_key!==undefined||body.supersedes!==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, command, supersede 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');
668
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');
669
994
  if(!Array.isArray(body.assignment.inputs)) throw new Error('invalid assignment inputs');
670
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');
@@ -682,6 +1007,7 @@ async function submitPolicy(body,req,dryRun) {
682
1007
  const approvals=body.destination_revisions??{};
683
1008
  if(!approvals||typeof approvals!=='object'||Array.isArray(approvals)||Object.keys(approvals).some(worker=>!routing.allowed_workers.includes(worker)))throw new Error('invalid destination_revisions');
684
1009
  const options={delivery,environmentId:oldOptions?.environmentId??'',execution,review:body.review===true,priority,meta};
1010
+ if(oldOptions&&Object.hasOwn(oldOptions,'relationships')) options.relationships=oldOptions.relationships;
685
1011
  if(old)return store.pullQueue.submit(JSON.parse(old.payload),identity,options,routing,approvals,owner,{dryRun});
686
1012
  let payload=identity,preflight=null;
687
1013
  // Validate scope under each candidate's current repository policy. No candidate
@@ -697,40 +1023,67 @@ async function submitPolicy(body,req,dryRun) {
697
1023
  preflight=await preflightPR(payload);
698
1024
  options.environmentId=(await destination.validate(delivery)).environmentId??'';
699
1025
  for(const worker of routing.allowed_workers)if(!dryRun)admitPolicyWorker(worker,payload,execution,approvals[worker]);
700
- if(dryRun)return {...store.pullQueue.submit(payload,identity,options,routing,approvals,owner,{dryRun:true}),destination_disclosures:disclosures};
701
- // Synchronous checks immediately precede the transaction; acquisition repeats
702
- // them in its write transaction after its own async preflight.
703
- const result=store.pullQueue.submit(payload,identity,options,routing,approvals,owner);
1026
+ // Capture each candidate's relationship at the same transaction boundary as admission.
1027
+ // Acquisition uses this binding, so ending it later does not revoke accepted work.
1028
+ const excludedWorkers=[];
1029
+ const result=store.inTransaction(()=>{
1030
+ const existing=store.pullQueue.row(identity.request_id);
1031
+ if(existing) {
1032
+ const saved=JSON.parse(existing.options);
1033
+ if(Object.hasOwn(saved,'relationships')) options.relationships=saved.relationships;
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
+ }
1046
+ return store.pullQueue.submit(payload,identity,options,routing,approvals,owner,{dryRun});
1047
+ });
1048
+ if(dryRun)return {...result,destination_disclosures:disclosures,excluded_workers:excludedWorkers};
704
1049
  log({kind:'policy_work_submitted',request_id:identity.request_id,work_order_id:result.work_order_id});
705
- 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()};
706
1057
  }
707
1058
 
708
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.
709
- async function tool(name,a,principal,notifyMeta) {
710
- if(!toolNames.has(name)) throw new Error('unknown tool');
711
- // Refuse hidden names before audits, lease touches, sweeps or repository preparation.
712
- if(name==='claim'&&typeof a?.request_id==='string'&&store.hasAssignment(a.request_id)&&store.mayAct(principal.worker,a.request_id)&&
713
- !holdsLiveGrant(principal.worker,a.request_id,a.claimant,principal.subject,a.acquisition_id)) {
714
- assertRepoAllowed(principal.worker,store.get(a.request_id).assignment);
715
- }
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++;
716
1064
  let error=null;
717
1065
  try {
718
- const result=await dispatchTool(name,a,principal,notifyMeta);
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);
719
1071
  if(typeof result?.error==='string') error=redactNote(result.error);
720
1072
  return result;
721
1073
  } catch(e) { error=redactNote(String(e?.message??e)); if(e.destination&&typeof a?.request_id==='string')notifyAttachedWaiter(a.request_id); throw e; }
722
1074
  finally {
723
- const rid=a?.request_id;
724
- if(typeof rid==='string'&&rid!==absentId&&toolNames.has(name)&&!t3Tools.has(name)&&!notifyTools.has(name)) {
725
- 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 */ }
726
- }
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--; }
727
1081
  }
728
1082
  }
729
- async function dispatchTool(name,a,principal,notifyMeta) {
1083
+ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,registryDefinition=null) {
730
1084
  const t3Audit=(t3Tools.has(name)||notifyTools.has(name))?await loadT3Audit():null;
731
1085
  if(t3Audit) t3Audit.admitT3Audit(store.db,principal.worker,principal.subject);
732
- store.recordWorkerCall(principal.subject,toolNames.has(name)?name:'unknown',principal.worker);
733
- sweepExpired();
1086
+ if(!registryDefinition) store.recordWorkerCall(principal.subject,toolNames.has(name)?name:'unknown',principal.worker);
734
1087
  if(t3Tools.has(name)||notifyTools.has(name)) {
735
1088
  // Denials carry only verified identity, tool and a fixed reason. Never prepare
736
1089
  // an argument-bearing audit until capability, scope and schema all pass.
@@ -746,6 +1099,7 @@ async function dispatchTool(name,a,principal,notifyMeta) {
746
1099
  t3Audit.appendT3Audit(store.db,t3Audit.prepareT3Audit(name,{},principal.worker),principal.subject,`denied: ${denial}`);
747
1100
  throw error;
748
1101
  }
1102
+ sweepExpired();
749
1103
  const audit=t3Audit.prepareT3Audit(name,a,principal.worker);
750
1104
  t3Audit.appendT3Audit(store.db,audit,principal.subject,'started');
751
1105
  try {
@@ -795,6 +1149,7 @@ async function dispatchTool(name,a,principal,notifyMeta) {
795
1149
  const isPolicyGet=policyRow&&name==='get'&&!store.hasAssignment(a.request_id);
796
1150
  if(isPolicyPage||isPolicyClaim||isPolicyGet) {
797
1151
  validate(name,a);if(oauth)needScope(principal,scopeFor(name));
1152
+ sweepExpired();
798
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);
799
1154
  const offered=policyRow.child_request_id?null:store.pullQueue.get(a.request_id,worker,admitPolicyWorker);
800
1155
  const preflight=offered?await preflightPR(offered.assignment):null;
@@ -811,7 +1166,7 @@ async function dispatchTool(name,a,principal,notifyMeta) {
811
1166
  }
812
1167
  const repaired=repairArguments(name,a);
813
1168
  a=repaired.args;
814
- validate(name,a);
1169
+ validate(name,a,registryDefinition??undefined);
815
1170
  if(oauth) needScope(principal,scopeFor(name));
816
1171
  if(disabled.has(name)&&!(workspaceEnabled&&workerWorkspaceAllowed(worker,a?.request_id))) throw new Error('capability_not_enabled');
817
1172
  if(a.request_id===absentId&&disabled.has(name)) throw new Error('assignment not found');
@@ -819,9 +1174,11 @@ async function dispatchTool(name,a,principal,notifyMeta) {
819
1174
  const strictJob=typeof a.request_id==='string'&&store.isProtocolJob(a.request_id);
820
1175
  if(strictJob&&catalogProfile!=='protocol-v0') throw new Error('protocol jobs require DALAN_CATALOG_PROFILE=protocol-v0');
821
1176
  if(strictJob)store.assertProtocolAvailable(a.request_id);
1177
+ sweepExpired();
822
1178
  // Strict commands validate authority, replay and revision in their transaction.
823
1179
  // The legacy implicit touch would mutate activity before a rejected CAS.
824
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});
825
1182
  // Workspace tools (every one, reads included) refuse any caller but the live holding connection. Native jobs skip the implicit
826
1183
  // touch above, so this is their only check; legacy jobs get a second, post-await check. It runs synchronously right before
827
1184
  // the tool body, after the tool's last await, so no revoke can land between the check and the write.
@@ -836,22 +1193,31 @@ async function dispatchTool(name,a,principal,notifyMeta) {
836
1193
  case 'list_tools': return toolRegistry.listTools(worker);
837
1194
  case 'call_tool_read': case 'call_tool_write': {
838
1195
  // The registry owns policy: grants, class match, argument validation, rate limits and audit.
839
- 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; }
840
1197
  catch(e) { if(e instanceof RegistryError) throw new Error(e.message.startsWith(e.code)?e.message:`${e.code}: ${e.message}`); throw e; }
841
1198
  }
842
1199
  case 'list_pending': {
843
- const {free_lanes}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1200
+ const {free_lanes,worker_max_claims}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
844
1201
  const assignments=store.listPending(worker);
845
- store.recordListed(assignments,free_lanes,worker);
1202
+ store.recordListed(assignments,free_lanes,worker,!quiescing);
1203
+ phaseTrace.listed(assignments.map(x=>x.request_id));
846
1204
  log({kind:'list_pending_result',subject,free_lanes,total:assignments.length,request_ids:assignments.slice(0,20).map(x=>x.request_id)});
847
- 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;
848
1207
  // Say outright whether a claim would be accepted now: a worker that once saw a pause refusal must not keep listing without claiming.
849
- const claims_accepted=!store.paused();
1208
+ const claims_accepted=!quiescing&&!store.paused();
850
1209
  const next=claims_accepted?store.nextQueued(free_lanes,null,worker):{};
851
- const claimsNote=claims_accepted?'':'Claims are paused (temporary): do not claim now; call list_pending again later and claim once claims_accepted is true.';
852
- 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};
853
1212
  }
854
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
+ }
855
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);
856
1222
  if(!retry)assertRepoAllowed(worker,row.assignment);
857
1223
  const needsWorkspace=workspaceEnabled&&(row.assignment.execution_scope==='implementation'||row.assignment.output_paths?.length);
@@ -876,19 +1242,36 @@ async function dispatchTool(name,a,principal,notifyMeta) {
876
1242
  // claimant's own connection is still live. The token was verified before
877
1243
  // the awaited preflight/quiesce above, so a revoke in between must not
878
1244
  // admit the claim. External-OAuth principals pass null and are unchanged.
879
- 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);
880
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});
881
1248
  const {free_lanes,queued}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
882
- 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);
883
1250
  }
884
1251
  case 'renew_claim': {
885
1252
  if(!strictJob) throw new Error('renew_claim requires a protocol job');
886
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);
887
1254
  }
888
- 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
+ }
889
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};}
890
1263
  case 'progress': {
891
- 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
+ }
892
1275
  notifyAttachedWaiter(requestId);
893
1276
  return {...receipt,...repaired.marks};
894
1277
  }
@@ -905,6 +1288,7 @@ async function dispatchTool(name,a,principal,notifyMeta) {
905
1288
  workspaceFence();
906
1289
  const existing=store.db.prepare('SELECT 1 FROM reports WHERE request_id=?').get(requestId);
907
1290
  let captureEvidence=null;
1291
+ const workerRuns=parseWorkerRuns(a.runs,a.run_limit,redactOutput), workerSession=parseWorkerSession(a.session,store.nowMs());
908
1292
  if(!existing) {
909
1293
  store.assertQuestionsResolved(requestId,claimId,a.outcome);
910
1294
  const request=store.get(requestId);
@@ -926,6 +1310,7 @@ async function dispatchTool(name,a,principal,notifyMeta) {
926
1310
  // Recheck after the last await. The evidence capture below runs inside the finish transaction, after finishOnce's own
927
1311
  // connection check, so a patch artifact is never committed for a holder that lost the connection.
928
1312
  workspaceFence();
1313
+ if(workerWorkspaceEnabled&&request.status==='claimed'&&a.outcome==='completed') { await workspace.checkBeforeFinish(requestId,claimId,subject,worker);workspaceFence(); }
929
1314
  if(workerWorkspaceEnabled&&request.status==='claimed'&&(request.assignment.execution_scope==='implementation'||request.assignment.output_paths?.length))
930
1315
  captureEvidence=onRollback=>workspace.snapshotInTransaction(requestId,claimId,subject,worker,onRollback);
931
1316
  if(request.status==='claimed'&&request.assignment.execution_scope==='read-only') {
@@ -937,15 +1322,39 @@ async function dispatchTool(name,a,principal,notifyMeta) {
937
1322
  };
938
1323
  }
939
1324
  }
1325
+ if(!existing) { store.recordWorkerRuns(requestId,claimId,workerRuns);store.recordWorkerSession(worker,subject,workerSession); }
940
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};
941
1328
  if(crashAt('after_report_persistence',a.request_id)) process.exit(73);
942
1329
  notifyAttachedWaiter(requestId);
943
1330
  if(repaired.marks.summary_derived||repaired.marks.summary_truncated) log({kind:'finish_summary_repaired',request_id:requestId,...repaired.marks});
944
- const marked={...receipt,...repaired.marks};
945
- return receipt.next_queued?.length&&!store.paused()?{...marked,guidance:finishNextGuidance(receipt.next_queued)}:marked; }
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);
1334
+ return finishReply({...receipt,...repaired.marks},{principal,requestId,claimId,signal}); }
946
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);
947
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);
948
- 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
+ }
949
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);
950
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);
951
1360
  case 'workspace_result': workspaceFence();return workspace.result(id(a.request_id),id(a.claim_id,'claim_id'),subject,worker);
@@ -982,7 +1391,7 @@ function publicErrorText(error,what) {
982
1391
  log({kind:'request_error',what,error_id:errorId,detail:safeDiagnostic(error?.stack??error,4000)});
983
1392
  return `Error executing ${what} (error id ${errorId}; details are in the request log)`;
984
1393
  }
985
- async function dispatch(message,principal) {
1394
+ async function dispatch(message,principal,signal) {
986
1395
  const p=message.params??{};
987
1396
  switch(message.method) {
988
1397
  case 'server/discover': return {ttlMs:0,cacheScope:'private',supportedVersions:['2026-07-28'],capabilities:{tools:{},events:{}},_meta:{'io.modelcontextprotocol/serverInfo':serverInfo}};
@@ -991,7 +1400,7 @@ async function dispatch(message,principal) {
991
1400
  // Modern catalogs are process-wide. A worker's capability controls tools/call authority, not its cached schemas.
992
1401
  // legacy-v46 keeps its pinned per-worker surface for compatibility.
993
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};
994
- 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)))}],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; } }
995
1404
  case 'events/list': return {events:[event]};
996
1405
  case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
997
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 {}; }
@@ -1022,6 +1431,7 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
1022
1431
  log({kind:'connection_denied',reason:error.code??'unknown_connection',client_id:principal.client_id??null});
1023
1432
  res.writeHead(403,{'content-type':'application/json'});res.end(JSON.stringify({error:error.code??'unknown_connection'}));return;
1024
1433
  }
1434
+ outcome.state.worker=principal.worker;
1025
1435
  outcome.state.phase='body';
1026
1436
  const body=await readBody(req,outcome.state);
1027
1437
  if(req.method!=='POST') { res.writeHead(405,{allow:'POST'}); res.end(); return; }
@@ -1030,11 +1440,13 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
1030
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'));
1031
1441
  outcome.identify(rpc);
1032
1442
  // Metadata only: bodies can carry webhook secrets and worker results.
1033
- 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)});
1034
1444
  if(!Object.hasOwn(rpc,'id')) { res.writeHead(202); res.end(); return; }
1035
1445
  outcome.state.phase='dispatch';
1036
1446
  const eventStream=readEnv('DALAN_TRIAL_SSE')==='1'&&req.method==='POST'&&acceptsMcpEventStream(req.headers.accept)?beginMcpEventStream(res):null;
1037
- try { json(res,200,{jsonrpc:'2.0',id:rpc.id,result:{resultType:'complete',...await dispatch(rpc,principal)}},eventStream); }
1447
+ // A tool that waits (finish with finish_handoff) stops when the client leaves, so nothing is claimed for nobody.
1448
+ const clientGone=new AbortController();res.once('close',()=>clientGone.abort());if(res.destroyed)clientGone.abort();
1449
+ try { json(res,200,{jsonrpc:'2.0',id:rpc.id,result:{resultType:'complete',...await dispatch(rpc,principal,clientGone.signal)}},eventStream); }
1038
1450
  catch(e) { json(res,200,rpcError(rpc.id,e.code||-32602,publicErrorText(e,'request'),e.data),eventStream); }
1039
1451
  // Response-byte accounting for the throttle and the break ledger; the response is already written, so a failure only logs.
1040
1452
  if(outcome.state.tool) try { store.recordResponseBytes(principal.subject,outcome.state.tool,outcome.state.response_bytes,principal.worker); } catch(e) { log({kind:'response_bytes_error',call_id:outcome.state.call_id,reason:e.message}); }
@@ -1043,7 +1455,7 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
1043
1455
  const adminServer=http.createServer(async(req,res)=>{
1044
1456
  // A refused submit is logged with its reason so the owner can distinguish rejected requests from stored assignments.
1045
1457
  const requestStartedAt=Date.now();
1046
- let rejected=null, dryRequested=false;
1458
+ let rejected=null, dryRequested=false, admission=null, previewMayReportAdmission=false;
1047
1459
  try {
1048
1460
  const raw=req.method==='POST'?await readBody(req):'',body=raw?JSON.parse(raw):{},url=new URL(req.url,'http://localhost');
1049
1461
  if(updateWindowOpen()&&!(req.method==='GET'&&url.pathname==='/service-check')) return refuseDuringUpdate(res);
@@ -1076,6 +1488,9 @@ const adminServer=http.createServer(async(req,res)=>{
1076
1488
  if(body.assignment?.request_id===absentId) throw new Error('invalid assignment');
1077
1489
  const commandKey=body.command_key===undefined?null:body.command_key;
1078
1490
  const supersedes=body.supersedes===undefined?null:body.supersedes;
1491
+ // {prior_id, prior_token}: this job corrects that one. Shape and authority are checked by the Store, in the submit transaction.
1492
+ const revises=body.revises===undefined?null:body.revises;
1493
+ const follows=body.follows===undefined?null:body.follows;
1079
1494
  const destinationRevision=body.destination_revision??null;
1080
1495
  if(body.destination_revision!==undefined&&(typeof destinationRevision!=='string'||!/^sha256:[a-f0-9]{64}$/.test(destinationRevision)))throw new Error('invalid destination_revision');
1081
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');
@@ -1104,6 +1519,7 @@ const adminServer=http.createServer(async(req,res)=>{
1104
1519
  }
1105
1520
  assertRepoAllowed(storedTarget??target??'dot',payload);
1106
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');
1107
1523
  if(body.review!==undefined&&typeof body.review!=='boolean') throw new Error('invalid review');
1108
1524
  if(body.background!==undefined&&body.background!==true) throw new Error('invalid background');
1109
1525
  if(body.allow_main!==undefined&&typeof body.allow_main!=='boolean') throw new Error('invalid allow_main');
@@ -1121,19 +1537,30 @@ const adminServer=http.createServer(async(req,res)=>{
1121
1537
  const declaredSource=body.meta?.source??'agent';
1122
1538
  for(const [value,label] of [[body,'submit request'],[body.meta,'meta'],[body.assignment,'assignment']]) assertNoDeclaredConsumer(value,label,declaredSource);
1123
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
+ };
1124
1549
  // A retry of an older row is not judged again; only a new submission has to prove the source it claims.
1125
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);}
1126
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');}
1127
1552
  if(body.allow_main===true) adminOperator(req);
1553
+ previewMayReportAdmission=true;
1128
1554
  destination.admit(delivery,{allowMain:body.allow_main===true});
1129
1555
  if(body.sensitive_scope_override!==undefined&&(typeof body.sensitive_scope_override!=='string'||!body.sensitive_scope_override)) throw new Error('invalid sensitive scope override');
1130
1556
  // A retry validates nothing and sends the original assignment, so the identity of a request is the assignment as submitted,
1131
1557
  // even when validation changed the stored brief (scope narrowing, the appended allow-list).
1132
1558
  const submitted=payload;
1133
1559
  const isNew=!store.hasAssignment(payload.request_id);
1560
+ if(isNew&&dryRun) store.relationshipForSubmission(target,body.relationship_id??null);
1134
1561
  // Reject immutable retry conflicts using the persisted binding before any external destination inspection.
1135
1562
  // A matching retry still validates the current destination below; this does not accept stale environment evidence.
1136
- store.checkRetry(submitted,delivery,existingRequest?.environment_id,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision);
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);
1137
1564
  let order=null;
1138
1565
  if(isNew) {
1139
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,
@@ -1154,7 +1581,7 @@ const adminServer=http.createServer(async(req,res)=>{
1154
1581
  },
1155
1582
  preflight:p=>preflightPR(p),
1156
1583
  // Advisory only, like Store.submit: a supersede target leaves the queued count unchanged. Store.submit rechecks it in its transaction.
1157
- 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}),
1158
1585
  kind:(r,p)=>r.meta?.task_kind??(r.review?'review':p.execution_scope??'unknown'),
1159
1586
  defaultValidity:(kind,r)=>store.defaultValidUntil(r.target,kind),
1160
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;},
@@ -1166,11 +1593,11 @@ const adminServer=http.createServer(async(req,res)=>{
1166
1593
  const {environmentId,generation}=(dryRun&&order&&order.verdict!=='admissible')?{}:await destination.validate(delivery);
1167
1594
  // An awaited repository/destination lookup may outlive a host policy edit.
1168
1595
  assertRepoAllowed(storedTarget??target??'dot',existingRequest?.assignment??payload);
1169
- if(dryRun) store.checkRetry(submitted,delivery,environmentId,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision);
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);
1170
1597
  const disclosure=isNew?store.destinationSnapshot(target??'dot',jobExecution,payload):existingRequest.destination_approval?.snapshot??null;
1171
1598
  if(dryRun) {
1172
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});
1173
- 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}:{})});
1174
1601
  }
1175
1602
  // Defer refuses only for a requester that opts in; both the CLI and HTTP API queue by default.
1176
1603
  if(order?.verdict==='defer'&&body.refuse_defer===true&&body.queue_anyway!==true) {
@@ -1181,7 +1608,7 @@ const adminServer=http.createServer(async(req,res)=>{
1181
1608
  const readiness=order?.check_readiness??null;
1182
1609
  const preflight=order?.preflight??null;
1183
1610
  const defaultValidity=order?.defaultValidity??null;
1184
- 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);
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);
1185
1612
  // Only a committed first replacement wakes the TARGET's already-attached waiter.
1186
1613
  if(supersedes&&!result.duplicate) {
1187
1614
  const targetId=supersedes.target_id,waiter=waiters.get(targetId);
@@ -1191,7 +1618,7 @@ const adminServer=http.createServer(async(req,res)=>{
1191
1618
  // A retry validates nothing, so the narrowing it reports comes from the stored assignment.
1192
1619
  const stored=result.duplicate?JSON.parse(store.db.prepare('SELECT payload FROM assignments WHERE request_id=?').get(payload.request_id).payload):payload;
1193
1620
  if(stored.scope_excluded?.length&&!result.duplicate) log({kind:'scope_excluded',request_id:payload.request_id,excluded:stored.scope_excluded});
1194
- 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}:{})});
1195
1622
  }
1196
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'}:{})}); }
1197
1624
  if(url.pathname==='/get') {
@@ -1202,6 +1629,10 @@ const adminServer=http.createServer(async(req,res)=>{
1202
1629
  store.recordFetched(requestId);
1203
1630
  // Read before recording consumption: the response then matches a peek read, which records no consumption.
1204
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
+ }
1205
1636
  if(url.searchParams.get('peek')!=='1') store.recordConsumed(requestId,'get');
1206
1637
  if(protocolServices&&store.isProtocolJob(requestId))got.protocol_stop=protocolServices.observation(requestId);
1207
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.
@@ -1210,7 +1641,21 @@ const adminServer=http.createServer(async(req,res)=>{
1210
1641
  try { return json(res,200,{...got,check_metadata:workspace.checkMetadataFor(got.assignment,got.target_worker)}); }
1211
1642
  catch(error) { return json(res,200,{...got,check_metadata:null,check_metadata_error:publicErrorText(error,'check metadata')}); }
1212
1643
  }
1213
- 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
+ }
1214
1659
  if(['/protocol/wait','/protocol/inbox','/protocol/ack'].includes(url.pathname)&&req.method==='POST') {
1215
1660
  if(catalogProfile!=='protocol-v0') throw new Error('protocol owner routes require DALAN_CATALOG_PROFILE=protocol-v0');
1216
1661
  const requestId=id(body.id),owner=req.headers['x-owner-capability'];
@@ -1251,7 +1696,7 @@ const adminServer=http.createServer(async(req,res)=>{
1251
1696
  // Only evidence holds refill: a pause or an owner-confirmed break. throttled stays false for older readers.
1252
1697
  const paused=store.paused(), dotBreak=!!store.holdingBreak();
1253
1698
  const held=paused?'paused':dotBreak?'worker_break':null;
1254
- 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}});
1255
1700
  }
1256
1701
  if(url.pathname==='/tools'&&req.method==='GET') { adminOperator(req); return json(res,200,{tools:toolRegistry.list()}); }
1257
1702
  if(url.pathname.startsWith('/tools/')&&req.method==='POST') {
@@ -1264,7 +1709,7 @@ const adminServer=http.createServer(async(req,res)=>{
1264
1709
  if(action==='revoke') { toolRegistry.revoke(body.name,body.worker); return json(res,200,{name:body.name,worker:body.worker,granted:false}); }
1265
1710
  } catch(error) { if(error instanceof RegistryError) throw new Error(`${error.code}: ${error.message}`); throw error; }
1266
1711
  }
1267
- 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});
1268
1713
  if(url.pathname==='/metrics'&&req.method==='GET') return json(res,200,lifecycleMetrics(store,{since:url.searchParams.get('since'),laneCapacity:redeliveryLimits.laneCapacity}));
1269
1714
  if(['/accept','/reject'].includes(url.pathname)&&req.method==='POST') {
1270
1715
  const requestId=id(body.id); adminOwner(req,requestId);
@@ -1275,6 +1720,16 @@ const adminServer=http.createServer(async(req,res)=>{
1275
1720
  const requestId=id(body.id); adminOwner(req,requestId);
1276
1721
  if(body.decision==='stale') throw new Error('stale is recorded by the sweep only');
1277
1722
  const via=['cli','apply','adapter'].includes(body.via)?body.via:'cli';
1723
+ // The two-phase apply: reserve (the stale check), then confirm or release once the patch is written or has failed.
1724
+ if(body.phase!==undefined) {
1725
+ if(body.decision!=='applied'||!['reserve','confirm','release'].includes(body.phase)) throw new Error('phase is reserve, confirm or release, and goes with decision applied');
1726
+ // Every attempt reserves and gets a token; confirm and release must present the current one. force releases an
1727
+ // uncertain reservation on purpose (the owner's own capability, no token).
1728
+ if(body.phase==='reserve') return json(res,200,store.reserveApply(requestId));
1729
+ const attempt=body.attempt===undefined||body.attempt===null?undefined:str(body.attempt,'attempt',128);
1730
+ if(body.phase==='release') return json(res,200,store.releaseApply(requestId,{attempt,force:body.force===true,reason:body.reason===undefined||body.reason===null?null:str(body.reason,'reason',512)}));
1731
+ return json(res,200,store.confirmApply(requestId,{attempt,note:body.note===undefined||body.note===null?null:str(body.note,'note',4096),via}));
1732
+ }
1278
1733
  return json(res,200,store.decide(requestId,String(body.decision),{note:body.note===undefined||body.note===null?null:str(body.note,'note',4096),via}));
1279
1734
  }
1280
1735
  if(url.pathname==='/lifecycle'&&req.method==='POST') {
@@ -1287,6 +1742,33 @@ const adminServer=http.createServer(async(req,res)=>{
1287
1742
  if(url.pathname==='/questions'&&req.method==='GET') { const requestId=id(url.searchParams.get('id'));adminOwner(req,requestId);return json(res,200,{request_id:requestId,questions:store.questions(requestId)}); }
1288
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')));
1289
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)));
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
+ }
1750
+ if(url.pathname==='/relationships/end'&&req.method==='POST') {
1751
+ adminOperator(req);
1752
+ const relationshipId=str(body.relationship_id,'relationship_id',128);
1753
+ const changed=store.db.prepare('UPDATE relationships SET ended_at=COALESCE(ended_at,?) WHERE relationship_id=?').run(new Date(store.nowMs()).toISOString(),relationshipId);
1754
+ if(!changed.changes) throw new Error('relationship_not_found');
1755
+ return json(res,200,{relationship:store.db.prepare('SELECT * FROM relationships WHERE relationship_id=?').get(relationshipId)});
1756
+ }
1757
+ if(url.pathname==='/grants'&&req.method==='GET') {
1758
+ adminOperator(req);
1759
+ const currentWorkers=loadEffectiveOwnerWorkers(workersFile);
1760
+ const grants=[
1761
+ ...store.db.prepare("SELECT c.*,a.relationship_id FROM claims c JOIN assignments a USING(request_id) WHERE c.state='active' AND a.status='claimed'").all().filter(row=>!store.leaseExpired(row)).map(row=>({request_id:row.request_id,worker:row.worker,relationship_id:row.relationship_id,expires_at:store.leaseExpiresAt(row),enforcer:'claim_lease'})),
1762
+ ...store.db.prepare('SELECT g.tool,g.worker,g.granted_at,g.scope FROM tool_grants g JOIN registered_tools t ON t.name=g.tool WHERE t.enabled=1').all().map(row=>({...row,scope:row.scope===null?null:JSON.parse(row.scope),enforcer:'tool_registry',expires_at:null})),
1763
+ ...store.db.prepare('SELECT d.request_id,d.revision,d.approved_at,a.relationship_id FROM destination_approvals d JOIN assignments a USING(request_id)').all().map(row=>({...row,enforcer:'destination_approval',expires_at:null})),
1764
+ ...store.activeSubscriptions().map(({id,principal,worker,expires_at})=>({id,principal,worker,expires_at,enforcer:'subscription'})),
1765
+ ...store.db.prepare('SELECT request_id,relationship_id FROM assignments WHERE owner_hash IS NOT NULL').all().filter(row=>store.protocolListingLive(row.request_id)).map(row=>({...row,enforcer:'owner_capability',expires_at:store.getProtocol(row.request_id)?new Date(store.getProtocol(row.request_id).retain_until_ms).toISOString():null})),
1766
+ ...[...currentWorkers.workers.keys()].flatMap(worker=>(currentWorkers.repoPolicy(worker)?.repos??[]).map(repo=>({worker,repo,enforcer:'repository_policy',expires_at:null}))),
1767
+ ...(as?as.store.db.prepare("SELECT c.connection_id,c.worker,c.scopes,c.created_at,o.expires_at FROM connections c JOIN oidc o ON o.model='Grant' AND o.id=c.grant_id WHERE c.revoked_at IS NULL AND (o.expires_at IS NULL OR o.expires_at>?)").all(store.nowMs()).map(row=>({connection_id:row.connection_id,worker:row.worker,scopes:row.scopes.split(' '),created_at:new Date(row.created_at).toISOString(),enforcer:'connection',expires_at:row.expires_at===null?null:new Date(row.expires_at).toISOString()})):
1768
+ [...workers.workers].flatMap(([worker,profile])=>(profile.connections??[]).map(({issuer,subject,client_id,connection_id})=>({worker,issuer,subject,client_id,connection_id,enforcer:'external_connection',expires_at:null,expiry_status:'unknown'})))),
1769
+ ];
1770
+ return json(res,200,{relationships:store.db.prepare('SELECT * FROM relationships ORDER BY created_at, rowid').all(),grants});
1771
+ }
1290
1772
  if(url.pathname.startsWith('/connect/')) {
1291
1773
  adminOperator(req);
1292
1774
  if(!as) throw new Error('built-in authorization server is not enabled (DALAN_AUTH_MODE=builtin)');
@@ -1298,7 +1780,11 @@ const adminServer=http.createServer(async(req,res)=>{
1298
1780
  if(url.pathname==='/connect/reset'&&req.method==='POST') return json(res,200,ops.reset());
1299
1781
  if(url.pathname==='/connect/stop'&&req.method==='POST') return json(res,200,ops.stop());
1300
1782
  if(url.pathname==='/connect/pending'&&req.method==='GET') return json(res,200,ops.pending());
1301
- if(url.pathname==='/connect/approve'&&req.method==='POST') return json(res,200,await ops.approve({code:body.code,worker:body.worker,replace:body.replace===true?true:body.replace===undefined?false:body.replace,confirm_redirect:body.confirm_redirect}));
1783
+ if(url.pathname==='/connect/approve'&&req.method==='POST') {
1784
+ const approval=await ops.approve({code:body.code,worker:body.worker,replace:body.replace===true?true:body.replace===undefined?false:body.replace,confirm_redirect:body.confirm_redirect});
1785
+ ensureWorkerRelationship(store.db,approval.worker);
1786
+ return json(res,200,approval);
1787
+ }
1302
1788
  if(url.pathname==='/connect/list'&&req.method==='GET') return json(res,200,ops.list());
1303
1789
  if(url.pathname==='/connect/revoke'&&req.method==='POST') return json(res,200,ops.revoke({worker:body.worker}));
1304
1790
  if(url.pathname==='/connect/signal-token'&&req.method==='POST') return json(res,200,signal.tokenUrl({worker:body.worker,rotate:body.rotate===true}));
@@ -1321,29 +1807,47 @@ const adminServer=http.createServer(async(req,res)=>{
1321
1807
  if(body.dry_run!==undefined&&typeof body.dry_run!=='boolean') throw new Error('invalid dry_run');
1322
1808
  return json(res,200,store.backfillObjectives(body.tuples,{dryRun:body.dry_run===true}));
1323
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
+ }
1324
1820
  if(url.pathname==='/claims'&&req.method==='GET') { adminOperator(req); return json(res,200,{lease_ms:store.limits.leaseMs,claims:store.claims()}); }
1325
1821
  if(url.pathname==='/abandon'&&req.method==='POST') {
1326
1822
  adminOperator(req);
1327
1823
  const requestId=id(body.id),result=store.abandon(requestId,{actor:'operator',reason:body.reason===undefined||body.reason===null?'operator_abandon':str(body.reason,'reason',512)});
1328
1824
  log({kind:'claim_abandoned',request_id:requestId,epoch:result.abandoned.epoch,actor:'operator'});
1329
1825
  runDrain();
1330
- return json(res,200,result);
1826
+ return json(res,200,{...result,scope:controlScopeText('detach',{ref:`claim:${result.abandoned.claim_id}@${result.abandoned.epoch}`})});
1331
1827
  }
1332
1828
  if(url.pathname==='/cancel') {
1333
1829
  const requestId=id(body.id); adminOwner(req,requestId);
1334
- const result=store.cancel(requestId,body.reason===undefined||body.reason===null?null:str(body.reason,'reason',64),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability']); const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } return json(res,200,result);
1830
+ // Read before the cancel: the scope text depends on whether a worker held the job.
1831
+ const wasClaimed=store.db.prepare("SELECT 1 FROM assignments WHERE request_id=? AND status='claimed'").get(requestId)!==undefined;
1832
+ const result=store.cancel(requestId,body.reason===undefined||body.reason===null?null:str(body.reason,'reason',64),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability']); const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } return json(res,200,{...result,scope:controlScopeText('withdraw_work',{ref:`job:${requestId}`,claimed:wasClaimed})});
1335
1833
  }
1336
1834
  if(url.pathname==='/cancel-if-queued'&&req.method==='POST') {
1337
1835
  const requestId=id(body.id); adminOwner(req,requestId);
1338
1836
  const result=store.cancelIfQueued(requestId);
1339
1837
  if(result.cancelled) { const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } }
1340
- return json(res,200,result);
1838
+ return json(res,200,result.cancelled?{...result,scope:controlScopeText('withdraw_work',{ref:`job:${requestId}`,claimed:false})}:result);
1341
1839
  }
1342
1840
  if(url.pathname==='/break'&&req.method==='POST') {
1343
1841
  adminOperator(req);
1344
1842
  if(body.clear===true) { const cleared=store.clearBreak(); sweepExpired(); return json(res,200,cleared); }
1345
- 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');
1346
- 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'));
1347
1851
  log({kind:'worker_break_set',source:'owner',since:result.since});
1348
1852
  return json(res,200,result);
1349
1853
  }
@@ -1374,11 +1878,18 @@ const adminServer=http.createServer(async(req,res)=>{
1374
1878
  const reasons=!infrastructure&&rejected?(e.reasons??reasonsFromError(e).map(({verdict,retry,blocking,...r})=>r)):null;
1375
1879
  const verdict=reasons?(e.verdict??strongest(reasonsFromError(e))):null;
1376
1880
  // A dry run answers every verdict with a 200 and stores nothing, including a refusal raised before the compiler ran.
1377
- 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
+ }
1378
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}:{})});
1379
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)});
1380
1891
  const shown=publicErrorText(e,'admin request');
1381
- json(res,infrastructure?503:400,{error:infrastructure?'admin service unavailable':shown,...(e.destination?{destination:e.destination}:{}),...(infrastructure?{code:e.code??null,reason:shown.slice(0,300)}:{}),...(!infrastructure&&e.suggested_scope_paths?{suggested_scope_paths:e.suggested_scope_paths}:{}),...(reasons?{verdict,reasons,...(e.bytes?{bytes:e.bytes}:{})}:{})});
1892
+ json(res,infrastructure?503:400,{error:infrastructure?'admin service unavailable':shown,...(e.destination?{destination:e.destination}:{}),...(e.stale?{stale:e.stale}:{}),...(infrastructure?{code:e.code??null,reason:shown.slice(0,300)}:{}),...(!infrastructure&&e.suggested_scope_paths?{suggested_scope_paths:e.suggested_scope_paths}:{}),...(reasons?{verdict,reasons,...(e.bytes?{bytes:e.bytes}:{})}:{})});
1382
1893
  }
1383
1894
  });
1384
1895
 
@@ -1434,11 +1945,11 @@ async function reconcileTick() {
1434
1945
  }
1435
1946
  let delivering=false;
1436
1947
  async function drain() {
1437
- if(delivering||store.paused()) return; delivering=true;
1948
+ if(delivering||quiescing||store.paused()) return; delivering=true;
1438
1949
  try {
1439
1950
  store.reannounceQueued(redeliveryLimits);
1440
1951
  for(const item of store.due()) {
1441
- if(store.paused()) break;
1952
+ if(quiescing||store.paused()) break;
1442
1953
  const row=item.kind==='event'?null:store.get(item.request_id);
1443
1954
  let destination=null;
1444
1955
  if(row) {
@@ -1456,6 +1967,8 @@ async function drain() {
1456
1967
  if(reason) { store.quietDelivery(item.id,reason); notifyAttachedWaiter(item.request_id); continue; }
1457
1968
  }
1458
1969
  const argv=row?destination.argv(item,row):null;
1970
+ // Destination selection can await across the admin toggle.
1971
+ if(quiescing||store.paused()) break;
1459
1972
  const started=store.startAttempt(item.id,argv); if(!started) continue;
1460
1973
  if(crashAt('after_attempt_commit',item.request_id)) process.exit(71);
1461
1974
  let state='failed',reason='';
@@ -1477,7 +1990,11 @@ async function drain() {
1477
1990
  // An earlier ACK is not a new callback and must not clear callback failures.
1478
1991
  if(ackLedger.has(ack)) { ackDurablyRecorded=true; state='delivered'; reason='recovered from durable webhook acceptance acknowledgment'; }
1479
1992
  else {
1480
- 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'});
1481
1998
  if(response.status>=200&&response.status<300) { positiveAckObserved=true; ackLedger.record(ack); ackDurablyRecorded=true; }
1482
1999
  store.eventResult(sub.id,response.status);
1483
2000
  state=response.status>=200&&response.status<300?'delivered':response.status===410||response.status===413?'suppressed':'failed';
@@ -1501,15 +2018,29 @@ function maintain() {
1501
2018
  } catch(error) { log({kind:'maintenance_error',reason:error.message}); }
1502
2019
  }
1503
2020
  const runDrain=createDrainRunner(drain,log);
2021
+ ensureAdminSocketDir(socket);
1504
2022
  try { fs.unlinkSync(socket); } catch(e) { if(e.code!=='ENOENT') throw e; }
1505
2023
  const adminListening=new Promise(resolve=>adminServer.listen(socket,()=>{fs.chmodSync(socket,0o600);console.log(`admin socket ${socket}`);resolve();}));
1506
2024
  // Built-in mode sits behind a tunnel on this computer: only loopback may reach the listener.
1507
2025
  const bindHost=readEnv('DALAN_BIND_HOST')||(as||loopbackOnly||loopback?'127.0.0.1':'0.0.0.0');
1508
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;
1509
2030
  // Every background writer starts only when no update window is open, so a candidate restarted inside the window changes no state
1510
2031
  // the rollback snapshot would discard. Outside a window this runs at once, in the same order as before.
1511
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
+ }));
1512
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
+ }
1513
2044
  // Cleanup removes worktrees and dependency caches; it starts only after both servers listen, and
1514
2045
  // cleanupExpired is async and single-flight, so neither startup nor the hourly tick blocks requests.
1515
2046
  if(workspace) {