@tnunamak/dalan 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/CHANGELOG.md +61 -2
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +8 -12
  4. package/bin/dalan.mjs +25 -4
  5. package/bin/dot-acp-agent.mjs +572 -76
  6. package/bin/dot-alert.mjs +9 -3
  7. package/bin/dot-deadman.mjs +3 -1
  8. package/bin/dot-heartbeat.mjs +14 -7
  9. package/bin/dot-pr-reviewer.mjs +3 -31
  10. package/bin/dot-worker.mjs +121 -34
  11. package/contracts/adapter-qualification.schema.json +94 -7
  12. package/docs/chatgpt-worker-onboarding.md +1 -1
  13. package/docs/codex-to-muse.md +2 -2
  14. package/docs/connect-chatgpt.md +1 -1
  15. package/docs/connection-longevity.md +2 -2
  16. package/docs/dalan-upgrade.md +8 -5
  17. package/docs/deadman.md +4 -0
  18. package/docs/design/authority-matrix.md +18 -0
  19. package/docs/design/failure-table.md +87 -0
  20. package/docs/design/identities.md +22 -0
  21. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  22. package/docs/design/reuse-ledger.md +75 -0
  23. package/docs/design/target-architecture-v2.md +434 -0
  24. package/docs/local-agent-mcp.md +14 -0
  25. package/docs/local-agent-requester.md +2 -1
  26. package/docs/manual-setup.md +1 -1
  27. package/docs/operations.md +77 -14
  28. package/docs/pull-workers.md +11 -1
  29. package/docs/service-setup.md +10 -10
  30. package/docs/t3-integration.md +4 -2
  31. package/docs/t3-reverse-control.md +5 -5
  32. package/docs/test-suite-isolation.md +7 -6
  33. package/docs/trials/chatgpt-agent.md +47 -0
  34. package/docs/trials/claude-code-requester.md +68 -0
  35. package/docs/trials/muse.md +46 -0
  36. package/docs/usage.md +21 -7
  37. package/docs/worker-clients.md +1 -1
  38. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  39. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  40. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  41. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  42. package/package.json +4 -3
  43. package/packages/job-core/protocol/canonical.mjs +45 -7
  44. package/packages/job-core/transitions.mjs +4 -2
  45. package/scripts/upgrade-drain.mjs +96 -8
  46. package/scripts/worker-bridge-setup.mjs +215 -120
  47. package/src/ack-ledger.mjs +7 -1
  48. package/src/acp-bridge.mjs +256 -28
  49. package/src/admin-socket.mjs +32 -3
  50. package/src/alerts.mjs +17 -8
  51. package/src/answer-journal-retention.mjs +82 -0
  52. package/src/answer-journal.mjs +6 -4
  53. package/src/as-store.mjs +51 -6
  54. package/src/as.mjs +27 -5
  55. package/src/catalog-switch-inventory.mjs +70 -0
  56. package/src/check-response.mjs +4 -1
  57. package/src/cli-help.mjs +14 -3
  58. package/src/cli-name.mjs +13 -1
  59. package/src/connect-cli.mjs +159 -4
  60. package/src/deadman.mjs +8 -5
  61. package/src/delivery.mjs +2 -19
  62. package/src/destinations/index.mjs +75 -14
  63. package/src/drain-runner.mjs +5 -1
  64. package/src/follow-current.mjs +3 -1
  65. package/src/get-summary.mjs +11 -2
  66. package/src/git-env.mjs +1 -1
  67. package/src/gozar-routes.mjs +313 -94
  68. package/src/host-budget-storage.py +56 -6
  69. package/src/host-budget.mjs +98 -15
  70. package/src/host-execution-policy.mjs +17 -6
  71. package/src/legacy-names.mjs +0 -2
  72. package/src/lifecycle.mjs +44 -9
  73. package/src/loopback-probe.mjs +46 -0
  74. package/src/mcp-outcome.mjs +3 -1
  75. package/src/mcp-sse.mjs +2 -1
  76. package/src/mcp-stdio.mjs +192 -30
  77. package/src/patch-apply.mjs +212 -7
  78. package/src/phase-trace.mjs +73 -0
  79. package/src/prepared-go-modules.mjs +127 -0
  80. package/src/prepared-node-modules.mjs +225 -38
  81. package/src/prepared-pnpm.mjs +276 -0
  82. package/src/prepared-store-prune.mjs +52 -0
  83. package/src/projects.mjs +59 -7
  84. package/src/protocol-artifact-commands.mjs +28 -0
  85. package/src/protocol-finish.mjs +3 -2
  86. package/src/publication-authority.mjs +22 -0
  87. package/src/publish-plan.mjs +2 -2
  88. package/src/pull-queue.mjs +55 -20
  89. package/src/read-api.mjs +127 -0
  90. package/src/redaction.mjs +173 -0
  91. package/src/rejections.mjs +19 -3
  92. package/src/route-custody.mjs +90 -0
  93. package/src/route-publication.mjs +50 -0
  94. package/src/route-setup.mjs +184 -0
  95. package/src/schema-subset.mjs +5 -3
  96. package/src/server.mjs +503 -98
  97. package/src/service-launchd.mjs +5 -1
  98. package/src/service-update-lock.mjs +7 -4
  99. package/src/service-update-runtime.mjs +136 -21
  100. package/src/service-update.mjs +207 -51
  101. package/src/service.mjs +276 -77
  102. package/src/setup.mjs +48 -25
  103. package/src/signal.mjs +1 -1
  104. package/src/status-evidence.mjs +18 -5
  105. package/src/store.mjs +876 -120
  106. package/src/submission-policy.mjs +257 -56
  107. package/src/t3-control.mjs +1 -1
  108. package/src/t3.mjs +14 -8
  109. package/src/terminal-safe.mjs +9 -7
  110. package/src/tool-registry.mjs +134 -41
  111. package/src/try-exposure.mjs +53 -86
  112. package/src/try-hosted.mjs +257 -70
  113. package/src/try.mjs +48 -22
  114. package/src/work-order.mjs +11 -6
  115. package/src/worker-instructions.mjs +26 -4
  116. package/src/worker-runs.mjs +35 -0
  117. package/src/workers.mjs +34 -7
  118. package/src/workspace.mjs +354 -54
  119. package/systemd/dot-deadman.service +3 -1
  120. package/docs/dot-pr-reviewer.config.example.json +0 -9
  121. package/docs/pr-head-reviewer.md +0 -70
  122. package/src/pr-head-reviewer.mjs +0 -596
  123. package/systemd/dot-pr-reviewer.service +0 -11
  124. package/systemd/dot-pr-reviewer.timer +0 -10
package/src/store.mjs CHANGED
@@ -25,6 +25,24 @@ import {answerProtocolQuestion,cancelProtocolJob} from './protocol-owner-mutatio
25
25
  import {defineProtocolRetentionInTransaction,assertProtocolAvailable as checkProtocolAvailable} from './protocol-retention.mjs';
26
26
  import {migrateProtocolDelivery} from './protocol-delivery-driver.mjs';
27
27
  import {migrateProtocolStopObserver} from './protocol-stop-observer.mjs';
28
+ import {destinationVersion,validT3ThreadId} from './destinations/index.mjs';
29
+
30
+ function deliveryColumns(value) {
31
+ // The old direct Store overload still accepts a bare T3 thread.
32
+ // New HTTP submissions arrive as parsed objects, which take the strict thread id check.
33
+ if(typeof value==='object'&&value?.mode==='t3'&&!validT3ThreadId(value.threadId)) {
34
+ throw Object.assign(new Error('invalid_delivery: t3 delivery needs a valid thread id'), {code:'invalid_delivery'});
35
+ }
36
+ const delivery=typeof value==='string'?{mode:'t3',threadId:value}:value;
37
+ const mode=delivery?.mode, version=destinationVersion(mode);
38
+ const address=mode==='none'?null:mode==='t3'?delivery?.threadId:delivery?.address;
39
+ if(!version || mode!=='none'&&(typeof address!=='string'||!address)) throw new Error('invalid delivery');
40
+ // A bare string is the legacy overload: it still stores and routes as t3:<value>, but, like the schema 73 backfill,
41
+ // its tuple stays unknown unless the value is a valid T3 thread id. So the tuple never names a bad thread.
42
+ const known=typeof value!=='string'||validT3ThreadId(value);
43
+ return {delivery,mode:known?mode:null,address:known?address:null,version:known?version:null,
44
+ threadId:mode==='t3'?address:'',deliveryValue:mode==='none'?'none':mode+':'+address};
45
+ }
28
46
 
29
47
  // A reserved HTTP response is a live effect channel. Persist its owner so a
30
48
  // second process cannot reset a reservation whose callback can still respond.
@@ -50,7 +68,7 @@ function waiterOwnerGone(attemptId) {
50
68
  return !!(owner.boot&&owner.start&&current.boot&&current.start&&(owner.boot!==current.boot||owner.start!==current.start));
51
69
  }
52
70
 
53
- const SUPPORTED_SCHEMA_VERSION = 72;
71
+ const SUPPORTED_SCHEMA_VERSION = 75;
54
72
  const monotonicMs=()=>Number(process.hrtime.bigint())/1e6;
55
73
  function systemBootId() {
56
74
  if(process.platform!=='linux') return null;
@@ -69,6 +87,11 @@ export function validateProtocol(value) {
69
87
 
70
88
  const questionError=(code,message)=>Object.assign(new Error(`${code}: ${message}`),{code});
71
89
  // A purpose other than clarification marks a question only a human may answer. SQLite cannot change a CHECK in place, so the schema 67 list below is the whole set.
90
+ // A claim made by a finish handoff starts on a short idle lease: a job handed to a session that never touches it returns to the queue
91
+ // after the worker's finish_handoff.idle_lease_ms (default 2 minutes). The holder's first call on it (any call, `get` included) moves it to the worker's configured lease (or HANDOFF_WORK_LEASE_MS), the lease
92
+ // it ran under before the idle phase existed. The claim's acquisition_id carries the prefix, so the Store needs no extra column.
93
+ export const HANDOFF_ACQUISITION_PREFIX='handoff-', HANDOFF_WORK_LEASE_MS=600000;
94
+ export const PROVIDER_REFUSAL='refused_by_provider';
72
95
  export const QUESTION_PURPOSES=['clarification','human_decision','authentication','tool_permission'];
73
96
  function validateQuestion(questionId,text) {
74
97
  if(typeof questionId!=='string'||!/^[A-Za-z0-9_.:-]{1,128}$/.test(questionId)) throw new Error('invalid question_id');
@@ -111,8 +134,41 @@ const storedMeta=(meta,legacy)=>({...meta,objective_key:storedObjectiveKey(meta.
111
134
  function submitIntentDigest(identity,delivery,environmentId,review,priority,meta,targetWorker,execution,requiredCapabilities,destinationRevision=null,legacyFixNames=true) {
112
135
  return hash(JSON.stringify(canonical({payload:identity,delivery,environmentId:environmentId??'',review:!!review,priority,meta:storedMeta(normalizeMeta(meta),legacyFixNames),targetWorker,execution,requiredCapabilities,...(destinationRevision===null?{}:{destination_revision:destinationRevision})})));
113
136
  }
114
- const defaultRedeliveryLimits={intervalMs:600000,maxCount:3,silenceMs:1200000,claimIdleWarningMs:900000,leaseMs:3600000,workerClaimLeaseMs:{},laneCapacity:6,rewakeMs:90000,rewakeWindowMs:7200000,rewakeStaleMs:1200000,breakSilenceMs:1200000,breakProbeMs:1800000,maxClaimsPerHour:90,maxToolCallsPerHour:1000,maxToolCallsPer24h:10000,maxResponseBytesPerHour:8000000,maxResponseBytesPer24h:100000000};
137
+ const defaultRedeliveryLimits={intervalMs:600000,maxCount:3,silenceMs:1200000,claimIdleWarningMs:900000,leaseMs:3600000,workerClaimLeaseMs:{},workerPostStartHoldMs:{},workerClaimHint:{},workerClaimMinGapMs:{},laneCapacity:6,rewakeMs:90000,rewakeWindowMs:7200000,rewakeStaleMs:1200000,breakSilenceMs:1200000,breakProbeMs:1800000,maxClaimsPerHour:90,maxToolCallsPerHour:1000,maxToolCallsPer24h:10000,maxResponseBytesPerHour:8000000,maxResponseBytesPer24h:100000000};
115
138
  const HOUR=3600000, iso=ms=>new Date(ms).toISOString();
139
+ const MINUTE=60000;
140
+ export function countReserveIdleMinutes(start,now,capacity,claimIntervals,waitIntervals) {
141
+ const buckets=Math.max(0,Math.floor((now-start)/MINUTE));
142
+ if(!buckets) return 0;
143
+ const events=[];
144
+ const add=(intervals,kind)=>{
145
+ for(const [from,to] of intervals) {
146
+ // Bucket k samples start+k*MINUTE, so [from,to) covers these bucket indices.
147
+ const first=Math.max(0,Math.min(buckets,Math.ceil((from-start)/MINUTE)));
148
+ const afterLast=Math.max(0,Math.min(buckets,Math.ceil((to-start)/MINUTE)));
149
+ if(first<afterLast) {
150
+ events.push([first,kind,1],[afterLast,kind,-1]);
151
+ }
152
+ }
153
+ };
154
+ add(claimIntervals,0);
155
+ add(waitIntervals,1);
156
+ events.sort((a,b)=>a[0]-b[0]);
157
+ // Apply every endpoint at an index before counting the buckets that follow it.
158
+ let idle=0,live=0,waiting=0,cursor=0;
159
+ for(let i=0;i<events.length;) {
160
+ const at=events[i][0];
161
+ if(cursor<at&&live<capacity&&waiting===0) idle+=at-cursor;
162
+ while(i<events.length&&events[i][0]===at) {
163
+ if(events[i][1]===0) live+=events[i][2];
164
+ else waiting+=events[i][2];
165
+ i++;
166
+ }
167
+ cursor=at;
168
+ }
169
+ if(cursor<buckets&&live<capacity&&waiting===0) idle+=buckets-cursor;
170
+ return idle;
171
+ }
116
172
  export const QUEUE_WINDOW=Object.freeze({minSamples:5,factor:3,minMs:15*60000,maxMs:12*HOUR});
117
173
  const queueKindSql=canonicalKindSql("COALESCE(a.task_kind,json_extract(a.payload,'$.task_kind'),CASE WHEN a.review=1 THEN 'review' ELSE json_extract(a.payload,'$.execution_scope') END,'unknown')");
118
174
  export const breakNoticeText=ids=>`the worker is on a usage break; do this yourself with a cheap model if it is urgent, or leave it queued (requests: ${ids.slice(0,20).join(', ')}${ids.length>20?` and ${ids.length-20} more`:''})`;
@@ -122,7 +178,16 @@ const queuedAt="COALESCE((SELECT max(l.at) FROM lifecycle_events l WHERE l.reque
122
178
  export const pausedClaimMessage='bridge paused (temporary): new claims are refused until the operator resumes. Keep working on jobs you already hold, then call list_pending and claim again later; claims are accepted as soon as the pause ends.';
123
179
  // Priority orders list_pending and re-wake; it never hides or refuses work. Within a priority, an item the worker passed over
124
180
  // (skipped_at) goes behind the others, then oldest first.
125
- const LIST_ORDER="CASE priority WHEN 'normal' THEN 0 ELSE 1 END,skipped_at IS NOT NULL,created_at";
181
+ // What a coordinator needs to decide which queued jobs can start together: the pinned repository, the execution scope, where the
182
+ // job may read and write, its priority and whether it is a review. Response data only; long path lists are capped.
183
+ const TRIAGE_PATHS_SHOWN=10,TRIAGE_KEYS=['execution_scope','repos','scope_paths','scope_paths_total','output_paths','output_paths_total','priority','review'];
184
+ const triageFields=(payload,row)=>{
185
+ const repos=(Array.isArray(payload.inputs)?payload.inputs:[]).filter(i=>i&&typeof i.github_repo==='string').map(i=>({github_repo:i.github_repo,...(typeof i.base_sha==='string'?{base_sha:i.base_sha}:{})}));
186
+ // Only string paths are projected; a total above the shown list means the shown part is not the whole scope.
187
+ const paths=(name,list)=>{const all=Array.isArray(list)?list.filter(x=>typeof x==='string'):[];return all.length?{[name]:all.slice(0,TRIAGE_PATHS_SHOWN),[`${name}_total`]:all.length}:{};};
188
+ return {execution_scope:typeof payload.execution_scope==='string'?payload.execution_scope:null,...(repos.length?{repos}:{}),...paths('scope_paths',payload.scope_paths),...paths('output_paths',payload.output_paths),priority:row.priority==='background'?'background':'normal',review:row.review===1||row.review===true};
189
+ };
190
+ const LIST_ORDER="CASE WHEN priority='background' THEN 2 WHEN caller_waiting=1 THEN 0 ELSE 1 END,skipped_at IS NOT NULL,created_at,rowid";
126
191
  // An item is marked skipped_by_worker when the worker passes it over, by either of two signals:
127
192
  // - passed over: the worker claimed an assignment listed after it, SKIP_AFTER_PASSED times, while it had listed this one within
128
193
  // PASSED_SEEN_MS. This detects items repeatedly pushed behind newer work before they enter the claimable window.
@@ -170,6 +235,32 @@ export function loadRedeliveryLimits(file=defaultPath(os.homedir(),'.config/dot-
170
235
  if(value.worker_claim_lease_ms===null||typeof workerClaimLeaseMs!=='object'||Array.isArray(workerClaimLeaseMs)||
171
236
  Object.entries(workerClaimLeaseMs).some(([worker,ms])=>!/^[a-z][a-z0-9_-]{0,31}$/.test(worker)||!Number.isInteger(ms)||ms<60000||ms>604800000))
172
237
  throw new Error('invalid worker_claim_lease_ms');
238
+ const workerHeartbeatMs=value.worker_heartbeat_ms??{};
239
+ if(value.worker_heartbeat_ms===null||typeof workerHeartbeatMs!=='object'||Array.isArray(workerHeartbeatMs)||
240
+ Object.entries(workerHeartbeatMs).some(([worker,ms])=>!/^[a-z][a-z0-9_-]{0,31}$/.test(worker)||!Number.isInteger(ms)||ms<60000||ms>604800000))
241
+ throw new Error('invalid worker_heartbeat_ms');
242
+ // After a bridge start the sweep holds a claim idle since before the start for its whole lease. This map shortens that hold for a worker.
243
+ const workerPostStartHoldMs=value.worker_post_start_hold_ms??{};
244
+ if(value.worker_post_start_hold_ms===null||typeof workerPostStartHoldMs!=='object'||Array.isArray(workerPostStartHoldMs)||
245
+ Object.entries(workerPostStartHoldMs).some(([worker,ms])=>!/^[a-z][a-z0-9_-]{0,31}$/.test(worker)||!Number.isInteger(ms)||ms<0||ms>604800000))
246
+ throw new Error('invalid worker_post_start_hold_ms');
247
+ // Guidance only: how many claims the bridge tells a worker to hold at once. It never refuses a claim (max_claimed_outer_assignments does that).
248
+ const workerClaimHint=value.worker_claim_hint??{};
249
+ if(value.worker_claim_hint===null||typeof workerClaimHint!=='object'||Array.isArray(workerClaimHint)||
250
+ Object.entries(workerClaimHint).some(([worker,n])=>!/^[a-z][a-z0-9_-]{0,31}$/.test(worker)||!Number.isInteger(n)||n<1||n>10))
251
+ throw new Error('invalid worker_claim_hint');
252
+ const workerMaxClaims=value.worker_max_claims??{};
253
+ if(value.worker_max_claims===null||typeof workerMaxClaims!=='object'||Array.isArray(workerMaxClaims)||
254
+ Object.entries(workerMaxClaims).some(([worker,n])=>!/^[a-z][a-z0-9_-]{0,31}$/.test(worker)||!Number.isInteger(n)||n<1||n>10))
255
+ throw new Error('invalid worker_max_claims');
256
+ const workerCallerReserve=value.worker_caller_reserve??{};
257
+ if(value.worker_caller_reserve===null||typeof workerCallerReserve!=='object'||Array.isArray(workerCallerReserve)||
258
+ Object.entries(workerCallerReserve).some(([worker,n])=>!/^[a-z][a-z0-9_-]{0,31}$/.test(worker)||!Number.isInteger(n)||n<0||n>9))
259
+ throw new Error('invalid worker_caller_reserve');
260
+ const workerClaimMinGapMs=value.worker_claim_min_gap_ms??{};
261
+ if(value.worker_claim_min_gap_ms===null||typeof workerClaimMinGapMs!=='object'||Array.isArray(workerClaimMinGapMs)||
262
+ Object.entries(workerClaimMinGapMs).some(([worker,ms])=>!/^[a-z][a-z0-9_-]{0,31}$/.test(worker)||!Number.isInteger(ms)||ms<1000||ms>600000))
263
+ throw new Error('invalid worker_claim_min_gap_ms');
173
264
  // Denominator of utilization metrics: how many lanes the worker can work in parallel. Independent of the claim cap (max_claimed_outer_assignments).
174
265
  // worker_* limits keys are the current names; the dot_* names are read as aliases so existing files keep working.
175
266
  const laneCapacity=value.worker_lane_capacity??value.dot_lane_capacity??defaultRedeliveryLimits.laneCapacity;
@@ -201,7 +292,7 @@ export function loadRedeliveryLimits(file=defaultPath(os.homedir(),'.config/dot-
201
292
  if(!Number.isInteger(maxResponseBytesPerHour)||maxResponseBytesPerHour<100000||maxResponseBytesPerHour>1000000000) throw new Error('invalid max_response_bytes_per_hour');
202
293
  const maxResponseBytesPer24h=value.max_response_bytes_per_24h??defaultRedeliveryLimits.maxResponseBytesPer24h;
203
294
  if(!Number.isInteger(maxResponseBytesPer24h)||maxResponseBytesPer24h<1000000||maxResponseBytesPer24h>10000000000) throw new Error('invalid max_response_bytes_per_24h');
204
- return {intervalMs,maxCount,silenceMs,claimIdleWarningMs,leaseMs,workerClaimLeaseMs,laneCapacity,rewakeMs,rewakeWindowMs,rewakeStaleMs,breakSilenceMs,breakProbeMs,maxClaimsPerHour,maxToolCallsPerHour,maxToolCallsPer24h,maxResponseBytesPer24h,maxResponseBytesPerHour};
295
+ return {intervalMs,maxCount,silenceMs,claimIdleWarningMs,leaseMs,workerClaimLeaseMs,...(Object.keys(workerHeartbeatMs).length?{workerHeartbeatMs}:{}),workerPostStartHoldMs,workerClaimHint,...(Object.keys(workerMaxClaims).length?{workerMaxClaims}:{}),...(Object.keys(workerCallerReserve).length?{workerCallerReserve}:{}),workerClaimMinGapMs,laneCapacity,rewakeMs,rewakeWindowMs,rewakeStaleMs,breakSilenceMs,breakProbeMs,maxClaimsPerHour,maxToolCallsPerHour,maxToolCallsPer24h,maxResponseBytesPer24h,maxResponseBytesPerHour};
205
296
  }
206
297
 
207
298
  // Gates that cap one rolling hour. They hold background work before agent-requested work (see rollingUsage).
@@ -305,13 +396,17 @@ export class Store {
305
396
  this.leaseBootId=options.bootId??(options.now?null:systemBootId());
306
397
  if(options.elapsedNow) {
307
398
  const epoch=wallNow(),elapsed=options.elapsedNow();
308
- this.nowMs=()=>Math.floor(epoch+options.elapsedNow()-elapsed);
399
+ this.nowMs=()=>Math.floor(epoch+(options.elapsedNow()-elapsed));
400
+ this.monotonicForWallDeadline=deadline=>elapsed+(deadline-epoch);
309
401
  } else if(options.now) this.nowMs=options.now;
310
402
  else {
311
403
  const epoch=Date.now(),elapsed=process.hrtime.bigint();
312
404
  this.nowMs=()=>Math.floor(epoch+Number(process.hrtime.bigint()-elapsed)/1e6);
405
+ // The wall clock advertises whole milliseconds; retain sub-millisecond elapsed precision.
406
+ this.monotonicForWallDeadline=deadline=>Number(elapsed+BigInt(deadline-epoch)*1000000n)/1e6;
313
407
  }
314
408
  this.capacity=options.capacity??6;
409
+ this.reserveIdleMinutesCache=new Map();
315
410
  this.backgroundMaxInFlight=options.backgroundMaxInFlight??4;
316
411
  this.limits=options.limits??{...defaultRedeliveryLimits};
317
412
  this.skipExpireMs=options.skipExpireMs??6*3600000;
@@ -333,6 +428,10 @@ export class Store {
333
428
  this.db.exec(`PRAGMA secure_delete=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA recursive_triggers=ON; PRAGMA busy_timeout=5000;
334
429
  CREATE TABLE IF NOT EXISTS assignments (request_id TEXT PRIMARY KEY, payload TEXT NOT NULL, payload_hash TEXT NOT NULL, thread_id TEXT NOT NULL, environment_id TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'queued', created_at TEXT NOT NULL, cancelled_at TEXT);
335
430
  CREATE TABLE IF NOT EXISTS claims (request_id TEXT PRIMARY KEY REFERENCES assignments(request_id), claimant TEXT NOT NULL, claim_id TEXT NOT NULL UNIQUE, claimed_at TEXT NOT NULL);
431
+ CREATE TABLE IF NOT EXISTS patch_attempts (
432
+ request_id TEXT NOT NULL REFERENCES assignments(request_id) ON DELETE CASCADE,
433
+ claim_id TEXT NOT NULL, applied INTEGER NOT NULL DEFAULT 0, rejected INTEGER NOT NULL DEFAULT 0,
434
+ last_rejection TEXT, updated_at TEXT NOT NULL, PRIMARY KEY(request_id,claim_id));
336
435
  CREATE TABLE IF NOT EXISTS progress (id INTEGER PRIMARY KEY, request_id TEXT NOT NULL REFERENCES assignments(request_id), note TEXT NOT NULL, created_at TEXT NOT NULL);
337
436
  CREATE TABLE IF NOT EXISTS reports (request_id TEXT PRIMARY KEY REFERENCES assignments(request_id), claim_id TEXT NOT NULL, outcome TEXT NOT NULL, summary TEXT NOT NULL, result TEXT NOT NULL, receipt_id TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL, late INTEGER NOT NULL DEFAULT 0);
338
437
  CREATE TABLE IF NOT EXISTS subscriptions (id TEXT PRIMARY KEY, principal TEXT NOT NULL, url TEXT NOT NULL, args TEXT NOT NULL, secret TEXT NOT NULL, expires_at TEXT NOT NULL, verified_at TEXT NOT NULL);
@@ -341,6 +440,7 @@ export class Store {
341
440
  CREATE TABLE IF NOT EXISTS bridge_state (key TEXT PRIMARY KEY,value TEXT NOT NULL) WITHOUT ROWID;
342
441
  CREATE INDEX IF NOT EXISTS notifications_due ON notifications(state,next_at);`);
343
442
  this.migrate();
443
+ this.ensureReadIndexes();
344
444
  this.pullQueue=new PullQueue(this);
345
445
  this.initializeLeaseClock();
346
446
  this.initializeSubscriptionStorage();
@@ -370,6 +470,16 @@ export class Store {
370
470
  if(confirmed&&denied) throw new Error('a control request cannot be both denied and confirmed');
371
471
  return this.inTransaction(()=>this.lifecycle(id,type,actor,[reason,denied].filter(Boolean).join('; ')||null,undefined,{scope:scope.trim(),outcome:confirmed?'confirmed':'unknown'}));
372
472
  }
473
+ // Indexes for the queries that run on a timer or on every owner read. Without them each call scans a table whose rows carry
474
+ // large payloads: on the live database (428 MB) that was 2.7 GB read per minute, and under memory pressure every read is a disk read
475
+ // that blocks the event loop. Idempotent and outside the schema version, so older code can still open the database.
476
+ ensureReadIndexes() {
477
+ this.db.exec(`
478
+ CREATE INDEX IF NOT EXISTS notifications_due_live ON notifications(state,next_at) WHERE kind IN ('event','t3','blocker','watch','break');
479
+ CREATE INDEX IF NOT EXISTS notifications_held ON notifications(state) WHERE held_kind IS NOT NULL;
480
+ CREATE INDEX IF NOT EXISTS progress_request ON progress(request_id,id);
481
+ CREATE INDEX IF NOT EXISTS assignments_worker_status ON assignments(target_worker,status,valid_until,valid_until_source,request_id);`);
482
+ }
373
483
  migrate() {
374
484
  this.transaction(() => {
375
485
  const version = this.db.prepare('PRAGMA user_version').get().user_version;
@@ -999,6 +1109,39 @@ export class Store {
999
1109
  addControlColumns(this.db);
1000
1110
  this.db.exec('PRAGMA user_version=72;');
1001
1111
  }
1112
+ if(version<73) {
1113
+ const columns=new Set(this.db.prepare('PRAGMA table_info(assignments)').all().map(row=>row.name));
1114
+ for(const name of ['delivery_adapter','delivery_address','delivery_adapter_version'])
1115
+ if(!columns.has(name))this.db.exec('ALTER TABLE assignments ADD COLUMN '+name+' TEXT');
1116
+ // Older custom/invalid rows have no historical version evidence. Keep their tuple unknown. A t3: row is filled only
1117
+ // when its address is a valid T3 thread id (destinations/index.mjs validT3ThreadId), so the tuple never names a bad thread.
1118
+ this.db.exec("UPDATE assignments SET delivery_adapter=CASE WHEN delivery='none' THEN 'none' ELSE 't3' END, delivery_address=CASE WHEN delivery='none' THEN NULL ELSE substr(delivery,4) END, delivery_adapter_version='1' WHERE delivery_adapter IS NULL AND (delivery='none' OR (substr(delivery,1,3)='t3:' AND length(substr(delivery,4)) BETWEEN 8 AND 1024 AND substr(delivery,4) NOT GLOB '*[^A-Za-z0-9._:%-]*')); PRAGMA user_version=73;");
1119
+ }
1120
+ if(version<74) {
1121
+ if(!this.db.prepare("SELECT 1 FROM pragma_table_info('assignments') WHERE name='caller_waiting'").get())
1122
+ this.db.exec('ALTER TABLE assignments ADD COLUMN caller_waiting INTEGER CHECK(caller_waiting IN (0,1))');
1123
+ this.db.exec('PRAGMA user_version=74;');
1124
+ }
1125
+ // Schema 74 already shipped with a different change, so the follow-link table takes the next number.
1126
+ if(version<75) this.db.exec(`CREATE TABLE IF NOT EXISTS job_follows(
1127
+ request_id TEXT PRIMARY KEY REFERENCES assignments(request_id),
1128
+ prior_id TEXT NOT NULL REFERENCES assignments(request_id),
1129
+ at TEXT NOT NULL
1130
+ ); PRAGMA user_version=75;`);
1131
+ // Worker run receipts (D9), hosted-session lifetimes (D14) and the publication grant on a relationship (D10).
1132
+ // Additive and idempotent, so it needs no schema number: older code ignores these tables and column.
1133
+ {
1134
+ this.db.exec(`CREATE TABLE IF NOT EXISTS worker_runs(
1135
+ request_id TEXT NOT NULL REFERENCES assignments(request_id), claim_id TEXT NOT NULL, seq INTEGER NOT NULL,
1136
+ command TEXT NOT NULL, exit_code INTEGER NOT NULL, output_tail TEXT NOT NULL, created_at TEXT NOT NULL,
1137
+ PRIMARY KEY(request_id,claim_id,seq));
1138
+ CREATE TABLE IF NOT EXISTS worker_run_limits(request_id TEXT NOT NULL REFERENCES assignments(request_id), claim_id TEXT NOT NULL, limit_text TEXT NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY(request_id,claim_id));
1139
+ CREATE TABLE IF NOT EXISTS worker_sessions(
1140
+ id INTEGER PRIMARY KEY AUTOINCREMENT, worker TEXT NOT NULL, subject TEXT NOT NULL,
1141
+ started_at TEXT NOT NULL, ended_at TEXT NOT NULL, duration_ms INTEGER NOT NULL CHECK(duration_ms>=0), recorded_at TEXT NOT NULL,
1142
+ UNIQUE(worker,subject,started_at));`);
1143
+ if(!this.db.prepare("SELECT 1 FROM pragma_table_info('relationships') WHERE name='publish_grant'").get()) this.db.exec('ALTER TABLE relationships ADD COLUMN publish_grant TEXT');
1144
+ }
1002
1145
  // Which spelling of the fix-loop source this database stores. Schemas created before the rename list the earlier
1003
1146
  // spelling in the CHECK constraint on assignments.source; newer schemas list only the neutral one.
1004
1147
  this.legacyFixNames=!!this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='assignments' AND instr(sql,?)>0").get(`'${legacyFixLoopName}'`);
@@ -1123,8 +1266,8 @@ export class Store {
1123
1266
  insertConfinedCheckAssignment(requestId,payload) {
1124
1267
  const body=JSON.stringify(payload);
1125
1268
  // "unknown" is a reserved name that no configured worker can have, so only the integrator ever touches this row.
1126
- this.db.prepare('INSERT INTO assignments(request_id,payload,payload_hash,thread_id,environment_id,status,created_at,target_worker) VALUES(?,?,?,?,?,?,?,?)')
1127
- .run(requestId,body,hash(body),'integrator','integrator','running',this.stamp(),'unknown');
1269
+ this.db.prepare('INSERT INTO assignments(request_id,payload,payload_hash,thread_id,environment_id,status,created_at,target_worker,delivery_adapter,delivery_adapter_version) VALUES(?,?,?,?,?,?,?,?,?,?)')
1270
+ .run(requestId,body,hash(body),'integrator','integrator','running',this.stamp(),'unknown','none',destinationVersion('none'));
1128
1271
  return this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(requestId);
1129
1272
  }
1130
1273
  // Queue waits are scoped to the selected worker and task kind, one sample per job. The first persisted claim is the
@@ -1157,6 +1300,141 @@ export class Store {
1157
1300
  observed.sort((a,b)=>a-b);
1158
1301
  return {waits_ms:observed,expired_lower_bounds:expiredLowerBounds,samples:observed.length,window_days:days,worker,kind};
1159
1302
  }
1303
+ // Use persisted worker progress for the start proxy. A reclaim resets the
1304
+ // first workspace call on the single current claim row, so mixing that time
1305
+ // in would make a job's measured first start change as it is reclaimed. Notes the bridge writes itself (the resume note)
1306
+ // start with `[bridge] ` and are not a start. A finished job with no worker note did start, at an unobserved time.
1307
+ admissionEvidence(worker,kind,days=7) {
1308
+ kind=canonicalKindLabel(kind);
1309
+ const since=iso(this.nowMs()-days*86400000);
1310
+ const rows=this.db.prepare(`WITH selected AS MATERIALIZED (
1311
+ SELECT a.request_id,a.target_worker,a.created_at,a.status,a.cancelled_reason
1312
+ FROM assignments a WHERE a.created_at>=? AND a.target_worker=? AND ${queueKindSql}=?
1313
+ ), lifecycle AS (
1314
+ SELECT a.request_id,
1315
+ min(CASE WHEN e.type='claimed' AND e.worker=a.target_worker THEN e.at END) claimed,
1316
+ max(CASE WHEN e.type='cancelled' AND e.actor='system' AND e.reason='expired' THEN 1 ELSE 0 END) system_expiry
1317
+ FROM selected a LEFT JOIN lifecycle_events e INDEXED BY lifecycle_events_request ON e.request_id=a.request_id
1318
+ GROUP BY a.request_id
1319
+ ) SELECT a.created_at,a.status,a.cancelled_reason,l.claimed,l.system_expiry,
1320
+ c.lease_deadline_at,c.lease_deadline_monotonic_ms,c.lease_boot_id,c.request_id has_claim,
1321
+ (SELECT p.created_at FROM progress p INDEXED BY progress_request WHERE p.request_id=a.request_id
1322
+ AND (p.worker IS NULL OR p.worker=a.target_worker)
1323
+ AND p.note NOT LIKE '[bridge] %'
1324
+ ORDER BY p.id LIMIT 1) started
1325
+ FROM selected a JOIN lifecycle l ON l.request_id=a.request_id
1326
+ LEFT JOIN claims c ON c.request_id=a.request_id`).all(since,worker,kind);
1327
+ const claimed=[], started=[], censored={expired_unclaimed:0,cancelled_unclaimed:0,claimed_not_started:0,finished_unobserved_start:0};
1328
+ for (const row of rows) {
1329
+ if (!row.claimed) {
1330
+ if (row.status==='cancelled') {
1331
+ if (row.cancelled_reason==='expired' && row.system_expiry) censored.expired_unclaimed++;
1332
+ else censored.cancelled_unclaimed++;
1333
+ }
1334
+ continue;
1335
+ }
1336
+ const created=Date.parse(row.created_at), claimMs=Date.parse(row.claimed)-created;
1337
+ if (!Number.isFinite(claimMs) || claimMs<0) continue;
1338
+ claimed.push(claimMs);
1339
+ const startMs=Date.parse(row.started)-created;
1340
+ if (Number.isFinite(startMs) && startMs>=claimMs) started.push(startMs);
1341
+ else if (row.status==='finished') censored.finished_unobserved_start++;
1342
+ else if (row.status==='cancelled' || (row.has_claim && this.leaseExpired(row))) censored.claimed_not_started++;
1343
+ }
1344
+ const summary=times=>{
1345
+ const n=times.length, insufficient_history=n<QUEUE_WINDOW.minSamples;
1346
+ if (insufficient_history) return {n,p50_ms:null,p90_ms:null,insufficient_history};
1347
+ times.sort((a,b)=>a-b);
1348
+ return {n,p50_ms:times[Math.ceil(n*0.5)-1],p90_ms:times[Math.ceil(n*0.9)-1],insufficient_history};
1349
+ };
1350
+ return {worker,kind,window_days:days,min_samples:QUEUE_WINDOW.minSamples,claimed:summary(claimed),started:summary(started),censored};
1351
+ }
1352
+ admissionForQueuedRequest(requestId) {
1353
+ const row=this.db.prepare(`SELECT a.target_worker,a.priority,${queueKindSql} AS kind
1354
+ FROM assignments a WHERE a.request_id=? AND a.status='queued'`).get(requestId);
1355
+ return row?this.admissionAnswer(row.target_worker,row.kind,row.priority,{excludeIds:[requestId]}):null;
1356
+ }
1357
+ // Reuse the worker's list tuple. A prospective row is unskipped and comes last among rows at its timestamp.
1358
+ admissionAnswer(worker,kind,priority,{excludeIds=[],createdBefore=null,callerWaiting=false}={}) {
1359
+ const now=this.nowMs(), at=iso(now), [first=null,second=null]=excludeIds;
1360
+ const anchor=first===null?null:this.db.prepare(
1361
+ 'SELECT priority,caller_waiting,skipped_at,created_at,CAST(rowid AS TEXT) queue_rowid FROM assignments WHERE request_id=? AND target_worker=?'
1362
+ ).get(first,worker);
1363
+ const rankPriority=(anchor?.priority??priority)==='background'?2:(anchor?anchor.caller_waiting===1:callerWaiting)?0:1;
1364
+ const rankSkipped=anchor?.skipped_at!=null?1:0;
1365
+ const rankCreated=anchor?.created_at??createdBefore??at;
1366
+ const rankRow=anchor?.queue_rowid??'9223372036854775807';
1367
+ const {count,oldest}=this.db.prepare(`SELECT count(*) count,min(created_at) oldest FROM assignments
1368
+ WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND request_id IS NOT ? AND ${live(now)}
1369
+ AND (${LIST_ORDER}) < (?, ?, ?, CAST(? AS INTEGER))`)
1370
+ .get(worker,first,second,rankPriority,rankSkipped,rankCreated,rankRow);
1371
+ const workerBreak=worker==='dot'?this.holdingBreak():null;
1372
+ const worker_state=this.paused()?'paused':workerBreak?'break':
1373
+ this.activeSubscriptions().some(sub=>sub.worker===worker)?'live':'no_live_subscription';
1374
+ const track_record=this.trackRecord(worker,kind);
1375
+ // 'now' requires a reserved worker lane. Admission is advisory and reserves nothing.
1376
+ return {start:'queued',ahead:{count,oldest_age_ms:oldest===null?null:Math.max(0,now-Date.parse(oldest))},
1377
+ latency:this.admissionEvidence(worker,kind),track_record,claim_to_report:track_record.claim_to_report,session_length:track_record.session_length,worker_state,...(worker_state==='break'?this.breakForecast(workerBreak.id,now):{}),at};
1378
+ }
1379
+ // D14: a hosted worker's own account of one session. A later job in the same session only extends it.
1380
+ recordWorkerSession(worker,subject,session) {
1381
+ if(!session) return;
1382
+ this.db.prepare(`INSERT INTO worker_sessions(worker,subject,started_at,ended_at,duration_ms,recorded_at) VALUES(?,?,?,?,?,?)
1383
+ ON CONFLICT(worker,subject,started_at) DO UPDATE SET ended_at=excluded.ended_at,duration_ms=excluded.duration_ms,recorded_at=excluded.recorded_at
1384
+ WHERE excluded.duration_ms>worker_sessions.duration_ms`).run(worker,subject,session.started_at,session.ended_at,session.duration_ms,this.stamp());
1385
+ }
1386
+ sessionLength(worker,days=7) {
1387
+ const since=iso(this.nowMs()-days*86400000), min_samples=QUEUE_WINDOW.minSamples;
1388
+ const lengths=this.db.prepare('SELECT duration_ms FROM worker_sessions WHERE worker=? AND ended_at>=? ORDER BY duration_ms').all(worker,since).map(row=>row.duration_ms);
1389
+ return {source:'worker_reported_sessions',n:lengths.length,min_samples,window_days:days,
1390
+ p50_ms:lengths.length<min_samples?null:lengths[Math.ceil(lengths.length/2)-1]};
1391
+ }
1392
+ trackRecord(worker,kind,days=7) {
1393
+ kind=canonicalKindLabel(kind);
1394
+ const since=iso(this.nowMs()-days*86400000);
1395
+ const rows=this.db.prepare(`SELECT a.request_id,a.status,r.outcome,r.created_at reported_at,
1396
+ CASE WHEN r.claim_id=c.claim_id AND c.state='active' AND r.late=0 THEN c.claimed_at END claimed_at,
1397
+ EXISTS(SELECT 1 FROM decisions d WHERE d.request_id=a.request_id AND d.decision='accepted' AND d.actor='owner') accepted,
1398
+ EXISTS(SELECT 1 FROM lifecycle_events e WHERE e.request_id=a.request_id AND e.type='integrated') integrated,
1399
+ EXISTS(SELECT 1 FROM decisions d WHERE d.request_id=a.request_id AND d.decision='applied' AND d.actor='owner') applied,
1400
+ EXISTS(SELECT 1 FROM lifecycle_events e WHERE e.request_id=a.request_id AND e.type='check_passed' AND (e.claim_id IS NULL OR e.claim_id=c.claim_id)) check_passed,
1401
+ EXISTS(SELECT 1 FROM lifecycle_events e WHERE e.request_id=a.request_id AND e.type='check_failed' AND (e.claim_id IS NULL OR e.claim_id=c.claim_id)) check_failed
1402
+ FROM assignments a LEFT JOIN reports r USING(request_id) LEFT JOIN claims c USING(request_id)
1403
+ WHERE COALESCE(
1404
+ CASE a.status WHEN 'cancelled' THEN a.cancelled_at ELSE r.created_at END,
1405
+ (SELECT MAX(e.at) FROM lifecycle_events e WHERE e.request_id=a.request_id
1406
+ AND e.type=CASE a.status WHEN 'cancelled' THEN 'cancelled' ELSE 'completed' END),
1407
+ a.created_at
1408
+ )>=? AND a.target_worker=? AND ${queueKindSql}=? AND a.status IN ('finished','cancelled')`).all(since,worker,kind);
1409
+ const outcomes={landed:0,check_passed:0,checks_failed:0,refused_by_provider:0,unable_to_run:0,owner_cancelled:0,finished_unchecked:0};
1410
+ let accepted=0,check_passed=0;
1411
+ const durations=[];
1412
+ // Check events from an earlier claim of a re-queued job describe a run that did not produce the result, so only the
1413
+ // final claim's events (or owner-side events with no claim) count.
1414
+ for(const row of rows) {
1415
+ accepted+=row.accepted;
1416
+ check_passed+=row.check_passed;
1417
+ const duration=Date.parse(row.reported_at)-Date.parse(row.claimed_at);
1418
+ if(row.status==='finished'&&Number.isFinite(duration)&&duration>=0) durations.push(duration);
1419
+ // A plain acceptance is a disposition on a report, not evidence that anything landed.
1420
+ if(row.status==='finished'&&row.outcome===PROVIDER_REFUSAL) outcomes.refused_by_provider++;
1421
+ else if(row.integrated||row.applied) outcomes.landed++;
1422
+ else if(row.check_passed) outcomes.check_passed++;
1423
+ else if(row.check_failed) outcomes.checks_failed++;
1424
+ else if(row.status==='finished'&&row.outcome==='completed') outcomes.finished_unchecked++;
1425
+ else {
1426
+ const {failure_type}=this.failureFields(row.request_id);
1427
+ if(failure_type==='owner_cancelled') outcomes.owner_cancelled++;
1428
+ else outcomes.unable_to_run++;
1429
+ }
1430
+ }
1431
+ // The provider session is opaque. The final claim and its report delimit an observed span on this job.
1432
+ durations.sort((a,b)=>a-b);
1433
+ const min_samples=QUEUE_WINDOW.minSamples;
1434
+ const claim_to_report={source:'final_claim_to_report',n:durations.length,min_samples,
1435
+ p50_ms:durations.length<min_samples?null:durations[Math.ceil(durations.length/2)-1]};
1436
+ return {worker,kind,window_days:days,n:rows.length,accepted,check_passed,outcomes,claim_to_report,session_length:this.sessionLength(worker,days)};
1437
+ }
1160
1438
  queueWaitsMs(worker,kind,days=7) { return this.queueWaitEvidence(worker,kind,days).waits_ms; }
1161
1439
  defaultValidUntil(worker,kind,days=7) {
1162
1440
  const evidence=this.queueWaitEvidence(worker,kind,days), waits=evidence.waits_ms;
@@ -1265,13 +1543,11 @@ export class Store {
1265
1543
  if(result?.destination_refusal)throw destinationError(result.destination_refusal);
1266
1544
  return result;
1267
1545
  }
1268
- checkRetry(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, priority='normal', meta=null, identity=payload, targetWorker=undefined, execution=null, requiredCapabilities=null, commandKey=null, supersedes=null, destinationRevision=null, revises=null) {
1546
+ checkRetry(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, priority='normal', meta=null, identity=payload, targetWorker=undefined, execution=null, requiredCapabilities=null, commandKey=null, supersedes=null, destinationRevision=null, revises=null, follows=null, callerWaiting=undefined) {
1269
1547
  validateSubmitKey(commandKey);
1270
1548
  const m=normalizeMeta(meta);
1271
- const delivery=typeof deliveryOrThreadId==='string'?{mode:'t3',threadId:deliveryOrThreadId}:deliveryOrThreadId;
1272
- if(!delivery||!['t3','none'].includes(delivery.mode)||delivery.mode==='t3'&&!delivery.threadId) throw new Error('invalid delivery');
1549
+ const {deliveryValue}=deliveryColumns(deliveryOrThreadId);
1273
1550
  if(!['normal','background'].includes(priority)) throw new Error('invalid priority');
1274
- const deliveryValue=delivery.mode==='t3'?`t3:${delivery.threadId}`:'none';
1275
1551
  const old=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(payload.request_id);
1276
1552
  if(supersedes!==null&&(!supersedes||typeof supersedes!=='object'||Array.isArray(supersedes)||
1277
1553
  Object.keys(supersedes).some(k=>!['target_id','target_token'].includes(k))||
@@ -1279,22 +1555,37 @@ export class Store {
1279
1555
  const targetId=supersedes?.target_id??null;
1280
1556
  const previous=this.db.prepare('SELECT target_id FROM submit_supersedes WHERE request_id=?').get(payload.request_id);
1281
1557
  if(targetId===payload.request_id) throw new Error('supersede_cycle');
1282
- // A correction names the job it revises and proves the owner capability of that job, as a supersede does. It cancels nothing.
1558
+ // A correction proves the prior owner's capability. Withdrawal is a separate, keyed opt-in.
1283
1559
  if(revises!==null) {
1284
- if(!revises||typeof revises!=='object'||Array.isArray(revises)||Object.keys(revises).some(k=>!['prior_id','prior_token'].includes(k))||
1285
- typeof revises.prior_id!=='string'||!/^[-\w]{8,128}$/.test(revises.prior_id)||typeof revises.prior_token!=='string') throw new Error('invalid revises: use {prior_id, prior_token}');
1560
+ if(!revises||typeof revises!=='object'||Array.isArray(revises)||Object.keys(revises).some(k=>!['prior_id','prior_token','withdraw_prior'].includes(k))||
1561
+ typeof revises.prior_id!=='string'||!/^[-\w]{8,128}$/.test(revises.prior_id)||typeof revises.prior_token!=='string') throw new Error('invalid revises: use {prior_id, prior_token, withdraw_prior?}');
1562
+ if(Object.hasOwn(revises,'withdraw_prior')&&revises.withdraw_prior!==true) throw new Error('withdraw_prior must be true when supplied');
1563
+ if(revises.withdraw_prior&&commandKey===null) throw new Error('withdraw_prior requires command_key');
1286
1564
  if(supersedes) throw new Error('revises_and_supersedes: a correction does not cancel its prior job; send one of them');
1287
1565
  if(revises.prior_id===payload.request_id) throw new Error('revises_cycle');
1288
- const prior=this.db.prepare('SELECT revision FROM assignments WHERE request_id=?').get(revises.prior_id);
1566
+ const prior=this.db.prepare('SELECT revision,status FROM assignments WHERE request_id=?').get(revises.prior_id);
1289
1567
  if(!prior) throw new Error('revises_prior_not_found');
1290
1568
  this.owner(revises.prior_id,revises.prior_token);
1569
+ if(!old&&revises.withdraw_prior&&['queued','claimed'].includes(prior.status)&&this.isProtocolJob(revises.prior_id))
1570
+ throw new Error('withdraw_prior requires the protocol cancellation path for this prior job');
1291
1571
  // The same revision under another request_id is a duplicate in the metrics, not a correction.
1292
1572
  if(m.revision!==null&&prior.revision!==null&&canonicalMetaValue('revision',prior.revision)===canonicalMetaValue('revision',m.revision)) throw new Error('revises_same_revision: a correction must carry a different --revision (meta.revision) from the job it revises');
1293
1573
  }
1294
1574
  const priorId=revises?.prior_id??null;
1575
+ if(follows!==null) {
1576
+ if(!follows||typeof follows!=='object'||Array.isArray(follows)||Object.keys(follows).some(k=>!['prior_id','prior_token'].includes(k))||
1577
+ typeof follows.prior_id!=='string'||!/^[-\w]{8,128}$/.test(follows.prior_id)||typeof follows.prior_token!=='string') throw new Error('invalid follows: use {prior_id, prior_token}');
1578
+ if(revises||supersedes) throw new Error('follows cannot be combined with revises or supersedes');
1579
+ if(follows.prior_id===payload.request_id) throw new Error('follows cycle');
1580
+ this.owner(follows.prior_id,follows.prior_token);
1581
+ if(this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(follows.prior_id)?.status!=='finished')
1582
+ throw new Error('follows predecessor must be finished');
1583
+ }
1584
+ const followsId=follows?.prior_id??null;
1585
+ const previousFollow=this.db.prepare('SELECT prior_id FROM job_follows WHERE request_id=?').get(payload.request_id);
1295
1586
  const previousRevision=this.db.prepare('SELECT prior_id FROM job_revisions WHERE request_id=?').get(payload.request_id);
1296
1587
  // Both capabilities are required even when returning an already-committed receipt.
1297
- if(old&&(supersedes||previous||revises||previousRevision)) this.owner(payload.request_id,ownerToken);
1588
+ if(old&&(supersedes||previous||revises||previousRevision||follows||previousFollow)) this.owner(payload.request_id,ownerToken);
1298
1589
  let target;
1299
1590
  if(supersedes) {
1300
1591
  target=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(targetId);
@@ -1320,17 +1611,19 @@ export class Store {
1320
1611
  // Authenticate before revealing or comparing the approval binding.
1321
1612
  if(approval)this.owner(payload.request_id,ownerToken);
1322
1613
  if((approval?.revision??null)!==destinationRevision)throw new Error('destination approval conflict: retry the original revision; cancel and resubmit to approve a change');
1614
+ if(callerWaiting!==undefined&&!!old.caller_waiting!==callerWaiting) throw new Error('request_id conflict: caller_waiting changed');
1323
1615
  const command=this.db.prepare('SELECT * FROM owner_submit_commands WHERE request_id=?').get(payload.request_id);
1324
1616
  // Authenticate before revealing key existence or replaying its receipt.
1325
1617
  if(commandKey!==null||command) this.owner(payload.request_id,ownerToken);
1326
1618
  if(commandKey!==null) {
1327
1619
  if(!command||command.key_digest!==hash(commandKey)) throw new Error('EXISTS: assignment already submitted under another command');
1328
1620
  const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??old.target_worker,execution??old.execution,requiredCapabilities,destinationRevision,this.legacyFixNames);
1329
- if((previous?.target_id??null)!==targetId||(previousRevision?.prior_id??null)!==priorId||command.owner_hash!==ownerHash||command.intent_digest!==intent) throw new Error('KEY_CONFLICT: command intent changed');
1330
- return {...JSON.parse(command.receipt),duplicate:true,...(approval?{destination_approval:approval}:{})};
1621
+ const receipt=JSON.parse(command.receipt);
1622
+ if((previous?.target_id??null)!==targetId||(previousRevision?.prior_id??null)!==priorId||(previousFollow?.prior_id??null)!==followsId||!!receipt.withdraw_prior!==!!revises?.withdraw_prior||command.owner_hash!==ownerHash||command.intent_digest!==intent) throw new Error('KEY_CONFLICT: command intent changed');
1623
+ return {...receipt,duplicate:true,...(approval?{destination_approval:approval}:{})};
1331
1624
  }
1332
1625
  if(command) throw new Error('EXISTS: command_key required to retry this assignment');
1333
- if ((previous?.target_id??null)!==targetId || (previousRevision?.prior_id??null)!==priorId || (targetWorker!==undefined&&old.target_worker!==targetWorker) || (execution!==null&&old.execution!==execution) || (requiredCapabilities!==null&&old.required_capabilities!==JSON.stringify(requiredCapabilities)) || old.payload_hash!==payloadHash || old.delivery!==deliveryValue || old.environment_id!==(environmentId??'') || old.owner_hash!==ownerHash || !!old.review!==!!review || old.priority!==priority || metaFields.some(k=>old[k]!=null&&m[k]!=null&&canonicalMetaValue(k,old[k])!==canonicalMetaValue(k,m[k]))) throw new Error('request_id conflict');
1626
+ if ((previous?.target_id??null)!==targetId || (previousRevision?.prior_id??null)!==priorId || (previousFollow?.prior_id??null)!==followsId || (targetWorker!==undefined&&old.target_worker!==targetWorker) || (execution!==null&&old.execution!==execution) || (requiredCapabilities!==null&&old.required_capabilities!==JSON.stringify(requiredCapabilities)) || old.payload_hash!==payloadHash || old.delivery!==deliveryValue || old.environment_id!==(environmentId??'') || old.owner_hash!==ownerHash || !!old.review!==!!review || old.priority!==priority || metaFields.some(k=>old[k]!=null&&m[k]!=null&&canonicalMetaValue(k,old[k])!==canonicalMetaValue(k,m[k]))) throw new Error('request_id conflict');
1334
1627
  return {request_id:payload.request_id,status:old.status,duplicate:true,...(approval?{destination_approval:approval}:{})};
1335
1628
  }
1336
1629
  // identity: the assignment as the submitter sent it, when the stored payload differs (scope narrowing); a retry then still matches.
@@ -1341,17 +1634,17 @@ export class Store {
1341
1634
  return relationship;
1342
1635
  }
1343
1636
  submit(...args) { return this.transaction(()=>this.submitInTransaction(...args)); }
1344
- submitInTransaction(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, preflight=null, priority='normal', meta=null, identity=payload, maxQueued=null, targetWorker=undefined, execution=null, defaultExecution='host', requiredCapabilities=null, defaultValidUntil=null, commandKey=null, supersedes=null, destinationRevision=null, inheritedOwnerHash=null, parentGeneration=null, relationshipId=null, revises=null) {
1637
+ submitInTransaction(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, preflight=null, priority='normal', meta=null, identity=payload, maxQueued=null, targetWorker=undefined, execution=null, defaultExecution='host', requiredCapabilities=null, defaultValidUntil=null, commandKey=null, supersedes=null, destinationRevision=null, inheritedOwnerHash=null, parentGeneration=null, relationshipId=null, revises=null, follows=null, callerWaiting=undefined) {
1345
1638
  if(!this.db.isTransaction) throw new Error('transaction_required');
1639
+ if(callerWaiting!==undefined&&typeof callerWaiting!=='boolean') throw new Error('invalid caller_waiting');
1346
1640
  if(payload.request_id.startsWith(PULL_PAGE_PREFIX)||!inheritedOwnerHash&&this.pullQueue.row(payload.request_id)) throw new Error('request_id reserved for policy work');
1347
1641
  const protocol=!this.hasAssignment(payload.request_id)&&Object.hasOwn(payload,'protocol')?validateProtocol(payload.protocol):null;
1348
1642
  if(protocol)identity={...identity,protocol};
1349
1643
  if(targetWorker==='pool') throw new Error('worker \"pool\" is not supported');
1350
- const delivery=typeof deliveryOrThreadId==='string'?{mode:'t3',threadId:deliveryOrThreadId}:deliveryOrThreadId;
1351
- if(!delivery||!['t3','none'].includes(delivery.mode)||delivery.mode==='t3'&&!delivery.threadId) throw new Error('invalid delivery');
1352
- const m=normalizeMeta(meta),threadId=delivery.threadId??'',deliveryValue=delivery.mode==='t3'?`t3:${threadId}`:'none';
1644
+ const {delivery,mode:deliveryAdapter,address:deliveryAddress,version:deliveryAdapterVersion,threadId,deliveryValue}=deliveryColumns(deliveryOrThreadId);
1645
+ const m=normalizeMeta(meta);
1353
1646
  if(!['normal','background'].includes(priority)) throw new Error('invalid priority');
1354
- const retry=this.checkRetry(payload,delivery,environmentId,ownerToken,review,priority,meta,identity,targetWorker,execution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises);
1647
+ const retry=this.checkRetry(payload,deliveryOrThreadId,environmentId,ownerToken,review,priority,meta,identity,targetWorker,execution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises,follows,callerWaiting);
1355
1648
  if(retry) return retry;
1356
1649
  let relationship;
1357
1650
  if(inheritedOwnerHash) {
@@ -1364,7 +1657,7 @@ export class Store {
1364
1657
  } else relationship=this.relationshipForSubmission(targetWorker,relationshipId);
1365
1658
  const id=payload.request_id, body=JSON.stringify(payload),payloadHash=hash(JSON.stringify(canonical(identity))),ownerHash=inheritedOwnerHash??hash(ownerToken);
1366
1659
  // checkRetry validated this target in the same transaction; only counts containing it gain room.
1367
- const supersededId=supersedes?.target_id??null;
1660
+ const supersededId=supersedes?.target_id??(revises?.withdraw_prior?revises.prior_id:null);
1368
1661
  if(destinationRevision!==null&&(typeof destinationRevision!=='string'||!/^sha256:[a-f0-9]{64}$/.test(destinationRevision)))throw new Error('invalid destination_revision');
1369
1662
  const disclosure=this.destinationSnapshot(targetWorker??'dot',execution??defaultExecution,payload,{required:destinationRevision!==null});
1370
1663
  if(disclosure&&destinationRevision===null)throw destinationError({error:'destination_approval_required',request_id:id,current:disclosure,message:'Review the destination disclosure and submit its exact destination_revision.'});
@@ -1397,12 +1690,14 @@ export class Store {
1397
1690
  }
1398
1691
  if(maxQueued!==null) {
1399
1692
  if(!Number.isSafeInteger(maxQueued)||maxQueued<1) throw new Error('invalid max_queued');
1400
- const queued=this.db.prepare(`SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND ${live(this.nowMs())}`).get(targetWorker??'dot',supersededId).n;
1693
+ // Waiting callers count only waiting peers of the same priority; backlog cannot refuse them.
1694
+ // Other callers keep the same-priority cap.
1695
+ const queued=this.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 ${live(this.nowMs())}`).get(targetWorker??'dot',priority,callerWaiting?1:0,supersededId).n;
1401
1696
  if(queued>=maxQueued) throw new Error(`worker queue is full (${queued} queued, in-flight cap ${maxQueued})`);
1402
1697
  }
1403
1698
  if(priority==='background'&&this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority='background' AND target_worker=? AND request_id IS NOT ? AND (status='claimed' OR status='queued' AND ${live(this.nowMs())})`).get(targetWorker??'dot',supersededId).n>=this.backgroundMaxInFlight) throw new Error('background_capacity_full');
1404
1699
  // The target is a column, not payload: an omitted worker means 'dot'.
1405
- this.db.prepare('INSERT INTO assignments(request_id,payload,payload_hash,thread_id,environment_id,status,created_at,owner_hash,review,delivery,priority,objective_key,revision,task_kind,source,target_worker,execution,required_capabilities) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,body,payloadHash,threadId,environmentId??'','queued',this.stamp(),ownerHash,review?1:0,deliveryValue,priority,...metaFields.map(k=>k==='source'?toStoredSource(m[k],this.legacyFixNames):m[k]),targetWorker??'dot',execution??defaultExecution,requiredCapabilities?JSON.stringify(requiredCapabilities):null);
1700
+ this.db.prepare('INSERT INTO assignments(request_id,payload,payload_hash,thread_id,environment_id,status,created_at,owner_hash,review,delivery,priority,objective_key,revision,task_kind,source,target_worker,execution,required_capabilities,delivery_adapter,delivery_address,delivery_adapter_version,caller_waiting) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,body,payloadHash,threadId,environmentId??'','queued',this.stamp(),ownerHash,review?1:0,deliveryValue,priority,...metaFields.map(k=>k==='source'?toStoredSource(m[k],this.legacyFixNames):m[k]),targetWorker??'dot',execution??defaultExecution,requiredCapabilities?JSON.stringify(requiredCapabilities):null,deliveryAdapter,deliveryAddress,deliveryAdapterVersion,callerWaiting?1:0);
1406
1701
  if(typeof parentGeneration==='string')this.db.prepare('UPDATE assignments SET parent_generation=? WHERE request_id=?').run(parentGeneration,id);
1407
1702
  if(relationship) this.db.prepare('UPDATE assignments SET relationship_id=? WHERE request_id=?').run(relationship.relationship_id,id);
1408
1703
  if(disclosure)this.db.prepare('INSERT INTO destination_approvals(request_id,revision,snapshot,actor,approved_at) VALUES(?,?,?,?,?)').run(id,disclosure.revision,JSON.stringify(disclosure),JSON.stringify({kind:'owner_capability',id:ownerHash}),this.stamp());
@@ -1424,12 +1719,18 @@ export class Store {
1424
1719
  this.cancelInTransaction(supersedes.target_id,'superseded');
1425
1720
  }
1426
1721
  if(revises) {
1427
- // The link and the note commit with the correction. A retry returned above, so neither is written twice.
1722
+ // The link and withdrawal or legacy note commit with the correction. Exact retries already returned.
1428
1723
  this.db.prepare('INSERT INTO job_revisions(request_id,prior_id,input_revision,at) VALUES(?,?,?,?)').run(id,revises.prior_id,m.revision,this.stamp());
1429
- this.announceRevisionInTransaction(revises.prior_id,id,m.revision);
1724
+ if(revises.withdraw_prior) {
1725
+ const prior=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(revises.prior_id);
1726
+ if(prior.status==='queued'||prior.status==='claimed') this.cancelInTransaction(revises.prior_id,'revised');
1727
+ } else {
1728
+ this.announceRevisionInTransaction(revises.prior_id,id,m.revision);
1729
+ }
1430
1730
  }
1731
+ if(follows) this.db.prepare('INSERT INTO job_follows(request_id,prior_id,at) VALUES(?,?,?)').run(id,follows.prior_id,this.stamp());
1431
1732
  for (const sub of this.activeSubscriptions()) this.submitWake(id,sub);
1432
- const receipt={request_id:id,status:'queued',duplicate:false,...(protocol?{revision:1}:{}),...this.destinationFields(id)};
1733
+ const receipt={request_id:id,status:'queued',duplicate:false,...(revises?.withdraw_prior?{withdraw_prior:true}:{}),...(protocol?{revision:1}:{}),...this.destinationFields(id)};
1433
1734
  if(commandKey!==null) {
1434
1735
  const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??'dot',execution??defaultExecution,requiredCapabilities,destinationRevision,this.legacyFixNames);
1435
1736
  this.db.prepare('INSERT INTO owner_submit_commands(request_id,key_digest,intent_digest,receipt,owner_hash) VALUES(?,?,?,?,?)').run(id,hash(commandKey),intent,JSON.stringify(receipt),ownerHash);
@@ -1517,7 +1818,7 @@ export class Store {
1517
1818
  const deadline=Date.parse(activity??this.stamp())+leaseMs;
1518
1819
  if(!protocolNat(deadline))protocolError('invalid_lease');
1519
1820
  this.db.prepare('UPDATE claims SET lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=?')
1520
- .run(iso(deadline),this.leaseBootId,this.leaseBootId?this.monotonicNow()+leaseMs:null,id);
1821
+ .run(iso(deadline),this.leaseBootId,this.monotonicDeadlineFor(deadline),id);
1521
1822
  }
1522
1823
  workerClaimLeaseCap(worker) {
1523
1824
  const caps=this.limits.workerClaimLeaseMs;
@@ -1535,7 +1836,7 @@ export class Store {
1535
1836
  const receipt=this.protocolMutationInTransaction(id,claimId,subject,worker,
1536
1837
  {...ctx,operation:'renew',args:{leaseMs:requestedLeaseMs}},({leaseUntil})=>{
1537
1838
  this.db.prepare('UPDATE claims SET lease_ms=?,lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=? AND claim_id=?')
1538
- .run(leaseMs,iso(leaseUntil),this.leaseBootId,this.leaseBootId?this.monotonicNow()+leaseMs:null,id,claimId);
1839
+ .run(leaseMs,iso(leaseUntil),this.leaseBootId,this.monotonicDeadlineFor(leaseUntil),id,claimId);
1539
1840
  const claim=this.assertClaim(id,claimId,subject,worker);
1540
1841
  this.protocolEventInTransaction(id,'renewed',{lease_ms:leaseMs,lease_deadline_at:iso(leaseUntil)},claim.epoch);
1541
1842
  return {request_id:id,claim_id:claimId,epoch:claim.epoch,lease_expires_at:iso(leaseUntil)};
@@ -1610,11 +1911,11 @@ export class Store {
1610
1911
  }
1611
1912
  retireUnusableSubscription(sub,reason='subscription inactive') {
1612
1913
  if(!sub) return [];
1613
- try {
1614
- const connection=this.subscriptionConnection(sub);
1615
- if(connection?.builtin&&this.connectionIsLive&&!this.connectionIsLive(connection.connection_id))
1616
- return this.retireConnectionSubscriptions(connection.connection_id,reason);
1617
- } catch { /* Retire the malformed or non-built-in subscription below. */ }
1914
+ let connection;
1915
+ try { connection=this.subscriptionConnection(sub); }
1916
+ catch { /* An undecodable subscription has only its own row identity. */ }
1917
+ if(connection?.builtin&&this.connectionIsLive&&!this.connectionIsLive(connection.connection_id))
1918
+ return this.retireConnectionSubscriptions(connection.connection_id,reason);
1618
1919
  return this.retireSubscription(sub.id,reason);
1619
1920
  }
1620
1921
  retireUnknownSubscriptions() {
@@ -1654,9 +1955,9 @@ export class Store {
1654
1955
  this.db.prepare('INSERT INTO notifications(id,kind,request_id,subscription_id,body,created_at,wake_kind) VALUES(?,?,?,?,?,?,?)').run(eventId,'event',id,sub.id,body,this.stamp(),wakeKind);
1655
1956
  return eventId;
1656
1957
  }
1657
- // Queued assignments in list_pending order (normal before background, then oldest) with queued_at (see queuedAt).
1958
+ // Queued assignments in list_pending order (waiting normal before other normal, then background and oldest) with queued_at (see queuedAt).
1658
1959
  queuedRows() {
1659
- return this.db.prepare(`SELECT a.request_id,a.payload,a.priority,a.target_worker,${queuedAt} queued_at FROM assignments a WHERE a.status='queued' AND a.cancelled_at IS NULL AND ${live(this.nowMs())} ORDER BY ${LIST_ORDER}`).all();
1960
+ return this.db.prepare(`SELECT a.request_id,a.payload,a.priority,a.caller_waiting,a.target_worker,${queuedAt} queued_at FROM assignments a WHERE a.status='queued' AND a.cancelled_at IS NULL AND ${live(this.nowMs())} ORDER BY ${LIST_ORDER}`).all();
1660
1961
  }
1661
1962
  // Break intervals [since, until or open] in ms. Owner since never reaches back before the previous break's end, so they are disjoint.
1662
1963
  breakIntervals() { return this.db.prepare('SELECT since,until FROM worker_breaks ORDER BY since').all().map(b=>[Date.parse(b.since),b.until?Date.parse(b.until):Infinity]); }
@@ -1693,9 +1994,10 @@ export class Store {
1693
1994
  const hasLiveClaim=liveClaims.some(c=>now-Date.parse(c.last_claim_activity_at??c.claimed_at)<this.claimLeaseMs(c));
1694
1995
  const atCapacity=liveSubs.length>0&&liveSubs.every(sub=>this.subscriptionFreeLanes(sub,limits.laneCapacity??6,capacity)===0);
1695
1996
  const hasSubscription=liveSubs.length>0;
1696
- const items=this.db.prepare(`SELECT request_id,created_at,NOT (${live(now)}) expired FROM assignments WHERE target_worker=? AND status='queued' AND cancelled_at IS NULL ORDER BY created_at`).all(worker).map(row=>{
1997
+ const items=this.db.prepare(`SELECT request_id,created_at,skipped_at,NOT (${live(now)}) expired FROM assignments WHERE target_worker=? AND status='queued' AND cancelled_at IS NULL ORDER BY created_at`).all(worker).map(row=>{
1697
1998
  // A queued row past its preparation's valid_until, or a protocol row past its retention, is 'expired', never alive_not_claiming: the worker cannot claim it.
1698
1999
  if(row.expired) return {request_id:row.request_id,class:'expired',event_2xx_age_ms:null};
2000
+ if(row.skipped_at!==null) return {request_id:row.request_id,class:null,event_2xx_age_ms:null};
1699
2001
  const first=this.db.prepare("SELECT min(COALESCE(attempt_started_at,created_at)) at FROM notifications WHERE kind='event' AND request_id=? AND state='delivered'").get(row.request_id).at;
1700
2002
  const eventAge=first?age(first):null;
1701
2003
  let cls=null;
@@ -1820,9 +2122,19 @@ export class Store {
1820
2122
  activeBreak() { return this.db.prepare('SELECT * FROM worker_breaks WHERE until IS NULL').get()??null; }
1821
2123
  // The break that holds work: only an owner-confirmed one. An inferred break (silence) is reported and alerted, not held on.
1822
2124
  holdingBreak() { const b=this.activeBreak(); return b?.source==='owner'?b:null; }
2125
+ // The forecast is an operator observation tied to one break. The break row's
2126
+ // until remains the time that a worker call or owner clear actually ended it.
2127
+ breakForecast(id,now=this.nowMs()) {
2128
+ const forecast=this.db.prepare('SELECT value FROM bridge_state WHERE key=?').get(`break_expected_end:${id}`)?.value;
2129
+ const until=Date.parse(forecast)>now?forecast:null;
2130
+ return {until,until_source:until===null?null:'owner_reported'};
2131
+ }
1823
2132
  breakState() {
1824
2133
  const b=this.activeBreak();
1825
- return b?{active:true,id:b.id,since:b.since,reason:b.reason,source:b.source,duration_ms:this.nowMs()-Date.parse(b.since),last_probe_at:b.last_probe_at}:{active:false,since:null,reason:null,source:null,duration_ms:null};
2134
+ if(!b) return {active:false,since:null,reason:null,source:null,duration_ms:null};
2135
+ const now=this.nowMs(),forecast=b.source==='owner'?this.breakForecast(b.id,now):null;
2136
+ return {active:true,id:b.id,since:b.since,reason:b.reason,source:b.source,duration_ms:now-Date.parse(b.since),
2137
+ last_probe_at:b.last_probe_at,...(forecast?.until?forecast:{})};
1826
2138
  }
1827
2139
  breaks() {
1828
2140
  return this.db.prepare('SELECT * FROM worker_breaks ORDER BY id').all().map(b=>({id:b.id,since:b.since,until:b.until,reason:b.reason,source:b.source,end_source:b.end_source,
@@ -1851,18 +2163,24 @@ export class Store {
1851
2163
  ...(learned[name]&&effective[name]<configured[name]?{learned:learned[name].value,break_id:learned[name].break_id}:{})}));
1852
2164
  }
1853
2165
  // Owner mark. Over an active break (e.g. an inferred one) it takes over: source owner, new reason, since if given, fresh snapshot.
1854
- setBreak(reason,since=null) { return this.transaction(() => {
2166
+ setBreak(reason,since=null,until=undefined) { return this.transaction(() => {
1855
2167
  if(typeof reason!=='string'||!reason.trim()||reason.length>512) throw new Error('invalid reason');
1856
- const active=this.activeBreak(), at=since??active?.since??this.stamp();
1857
- if(!Number.isFinite(Date.parse(at))||Date.parse(at)>this.nowMs()) throw new Error('since must not be in the future');
2168
+ const active=this.activeBreak(), now=this.nowMs(), at=since??active?.since??iso(now);
2169
+ if(until!==undefined&&until!==null&&(typeof until!=='string'||!(Date.parse(until)>now)))
2170
+ throw new Error('until must be in the future');
2171
+ if(!Number.isFinite(Date.parse(at))||Date.parse(at)>now) throw new Error('since must not be in the future');
1858
2172
  const ended=this.db.prepare('SELECT max(until) u FROM worker_breaks WHERE until IS NOT NULL').get().u;
1859
2173
  if(ended&&Date.parse(at)<Date.parse(ended)) throw new Error(`since must not be before the end of the previous break (${ended})`);
1860
- if(!active) return this.startBreak({since:at,reason,source:'owner'});
1861
- const usage=this.usageBefore(Date.parse(at));
1862
- this.db.prepare("UPDATE worker_breaks SET reason=?,source='owner',since=?,usage=? WHERE id=?").run(reason,at,JSON.stringify(usage),active.id);
1863
- // Confirming an inferred break without --since keeps its since (the worker's last call), so its last hour is still quiet:
1864
- // learn the 24 h budgets and the claims peak, not the hourly limits.
1865
- this.learnFromBreak(active.id,active.source==='inferred'&&!since?{...usage,'1h':undefined}:usage);
2174
+ const id=active?.id??this.startBreak({since:at,reason,source:'owner'}).id;
2175
+ if(active) {
2176
+ const usage=this.usageBefore(Date.parse(at));
2177
+ this.db.prepare("UPDATE worker_breaks SET reason=?,source='owner',since=?,usage=? WHERE id=?").run(reason,at,JSON.stringify(usage),active.id);
2178
+ // An inferred break keeps the quiet last hour unless the owner supplies since.
2179
+ this.learnFromBreak(active.id,active.source==='inferred'&&!since?{...usage,'1h':undefined}:usage);
2180
+ }
2181
+ const key=`break_expected_end:${id}`;
2182
+ if(until===null) this.db.prepare('DELETE FROM bridge_state WHERE key=?').run(key);
2183
+ else if(until!==undefined) this.db.prepare('INSERT INTO bridge_state(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key,iso(Date.parse(until)));
1866
2184
  return this.breakState();
1867
2185
  }); }
1868
2186
  clearBreak() { return this.transaction(() => {
@@ -1875,6 +2193,7 @@ export class Store {
1875
2193
  // Call inside a transaction.
1876
2194
  endBreak(active,endSource) {
1877
2195
  this.db.prepare('UPDATE worker_breaks SET until=?,end_source=? WHERE id=?').run(this.stamp(),endSource,active.id);
2196
+ this.db.prepare('DELETE FROM bridge_state WHERE key=?').run(`break_expected_end:${active.id}`);
1878
2197
  }
1879
2198
  // Inferred start: no worker tool call (any subject) for breakSilenceMs, an availability event got a 2xx after the last call,
1880
2199
  // and work is queued. since is the last call. A worker that never called is not inferred (no known silence start), and a break
@@ -1918,11 +2237,23 @@ export class Store {
1918
2237
  this.refreshClaimActivity(id,claimId);
1919
2238
  }
1920
2239
  refreshClaimActivity(id,claimId) {
1921
- const at=this.stamp(), claim=this.db.prepare('SELECT lease_ms,worker FROM claims WHERE request_id=? AND claim_id=?').get(id,claimId);
1922
- const leaseMs=Math.min(claim?.lease_ms??this.limits.leaseMs,this.workerClaimLeaseCap(claim?.worker));
2240
+ const at=this.stamp(), claim=this.db.prepare('SELECT lease_ms,worker,acquisition_id FROM claims WHERE request_id=? AND claim_id=?').get(id,claimId);
2241
+ const leaseMs=Math.min(this.handoffWorkLeaseMs(claim)??claim?.lease_ms??this.limits.leaseMs,this.workerClaimLeaseCap(claim?.worker));
2242
+ const deadline=Date.parse(at)+leaseMs;
1923
2243
  if(this.isProtocolJob(id)) this.db.prepare('UPDATE claims SET last_claim_activity_at=? WHERE request_id=? AND claim_id=?').run(at,id,claimId);
1924
2244
  else this.db.prepare('UPDATE claims SET last_claim_activity_at=?,lease_ms=?,lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=? AND claim_id=?')
1925
- .run(at,leaseMs,iso(Date.parse(at)+leaseMs),this.leaseBootId,this.leaseBootId?this.monotonicNow()+leaseMs:null,id,claimId);
2245
+ .run(at,leaseMs,iso(deadline),this.leaseBootId,this.monotonicDeadlineFor(deadline),id,claimId);
2246
+ }
2247
+ handoffWorkingLeaseMs(worker) {
2248
+ const cap=this.workerClaimLeaseCap(worker);
2249
+ return Math.min(this.limits.leaseMs,Number.isFinite(cap)?cap:HANDOFF_WORK_LEASE_MS);
2250
+ }
2251
+ // The working lease for a handoff claim that is still on its idle lease, else null (every other claim keeps its own lease_ms).
2252
+ handoffWorkLeaseMs(claim) {
2253
+ if(!claim?.acquisition_id?.startsWith(HANDOFF_ACQUISITION_PREFIX)) return null;
2254
+ const working=this.handoffWorkingLeaseMs(claim.worker);
2255
+ // Claims that began on the working lease do not need promotion.
2256
+ return claim.lease_ms<working?working:null;
1926
2257
  }
1927
2258
  // The active, unexpired claim this worker holds under claimId, or null. A missing or expired claim is left to the caller's own error.
1928
2259
  liveHeldClaim(id,claimId,subject,worker) {
@@ -1945,6 +2276,8 @@ export class Store {
1945
2276
  try { this.assertMutationConnection(id,claim,connectionId); }
1946
2277
  catch(error) { if(error.destination?.error==='connection_not_live')return false; throw error; }
1947
2278
  this.markNotesSeen(id,subject,worker);
2279
+ // The holder reading its handed job is the first sign of life: end the idle phase of a handoff claim. Other claims are not refreshed by a read.
2280
+ if(this.handoffWorkLeaseMs(claim)!==null&&!this.leaseExpired(claim)) this.refreshClaimActivity(id,claim.claim_id);
1948
2281
  return true;
1949
2282
  }); }
1950
2283
  // Unfenced: for callers that already proved the holder inside their own claim transaction (exact retry, resume). `get` uses markNotesSeenByHolder.
@@ -1963,21 +2296,35 @@ export class Store {
1963
2296
  const a=Store.toolActivity(c), t=x=>x.slice(11,19)+'Z';
1964
2297
  return `lease_expired: ${a.tool_calls} call${a.tool_calls===1?'':'s'}${a.last_tool?`, last ${a.last_tool} at ${t(a.last_tool_at)}`:''}${a.first_workspace_tool_at?`, first workspace tool at ${t(a.first_workspace_tool_at)}`:', no workspace tool'}${a.last_tool_error?`, last error: ${a.last_tool_error.slice(0,80)}`:''}`;
1965
2298
  }
2299
+ // A handed claim that lapsed with no call on it but the claim itself (reason "lease_expired: 1 call, last claim at ..."): the
2300
+ // worker did not take the job when it was pushed to it. A finish does not push that row again while that is its latest abandon; the worker claims it from its own list, and a later claim that ended another way clears it.
2301
+ handoffLapsed(id,worker) { const last=this.db.prepare("SELECT actor,reason FROM lifecycle_events WHERE request_id=? AND worker=? AND type='abandoned' ORDER BY id DESC LIMIT 1").get(id,worker); return last?.actor==='system'&&last.reason?.startsWith('lease_expired: 1 call, last claim at ')===true; }
1966
2302
  failureFields(id) {
1967
- const a=this.db.prepare('SELECT status,cancelled_reason FROM assignments WHERE request_id=?').get(id);
2303
+ const a=this.db.prepare(`SELECT a.status,a.cancelled_reason,r.outcome,r.summary,r.result,
2304
+ EXISTS(SELECT 1 FROM lifecycle_events e WHERE e.request_id=a.request_id AND e.type='check_failed') check_failed,
2305
+ CASE WHEN a.status='cancelled' THEN (SELECT e.actor FROM lifecycle_events e WHERE e.request_id=a.request_id AND e.type='cancelled' ORDER BY e.id DESC LIMIT 1) END cancel_actor,
2306
+ (a.status='cancelled' AND EXISTS(SELECT 1 FROM lifecycle_events e WHERE e.request_id=a.request_id AND e.type='abandoned' AND e.actor='system' AND e.reason LIKE 'lease_expired%')) lease_expired
2307
+ FROM assignments a LEFT JOIN reports r USING(request_id) WHERE a.request_id=?`).get(id);
1968
2308
  if(!a) {const policy=this.pullQueue.inbox(id);return policy?{failure_type:policy.failure_type,failure_type_source:policy.failure_type_source}:{failure_type:'unknown',failure_type_source:'unknown'};}
1969
- const report=this.db.prepare('SELECT outcome,summary,result FROM reports WHERE request_id=?').get(id);
1970
- const failedReport=!!report&&report.outcome!=='completed';
1971
- const checkFailedObserved=!!this.db.prepare("SELECT 1 FROM lifecycle_events WHERE request_id=? AND type='check_failed' LIMIT 1").get(id);
2309
+ if(a.status==='finished'&&a.outcome===PROVIDER_REFUSAL)
2310
+ return {failure_type:'worker_blocked',failure_type_source:'worker_reported_outcome',check_failed_observed:!!a.check_failed};
2311
+ const failedReport=a.outcome!==null&&a.outcome!=='completed';
2312
+ const checkFailedObserved=!!a.check_failed;
1972
2313
  if(a.status!=='cancelled'&&!failedReport) return {failure_type:null,failure_type_source:null,check_failed_observed:checkFailedObserved};
1973
- const cancelActor=a.status==='cancelled'?this.db.prepare("SELECT actor FROM lifecycle_events WHERE request_id=? AND type='cancelled' ORDER BY id DESC LIMIT 1").get(id)?.actor:null;
1974
- const observed=observeTransition({status:a.status,reason:a.cancelled_reason,cancelActor,
1975
- leaseExpired:a.status==='cancelled'&&!!this.db.prepare("SELECT 1 FROM lifecycle_events WHERE request_id=? AND type='abandoned' AND actor='system' AND reason LIKE 'lease_expired%' LIMIT 1").get(id)});
1976
- const inferred=report?inferWorkerReport(report):null;
2314
+ const observed=observeTransition({status:a.status,reason:a.cancelled_reason,cancelActor:a.cancel_actor,leaseExpired:!!a.lease_expired});
2315
+ const inferred=a.outcome===null?null:inferWorkerReport(a);
1977
2316
  const result=observed??inferred;
1978
2317
  return result?{failure_type:result.type,failure_type_source:result.source,check_failed_observed:checkFailedObserved}:{failure_type:'unknown',failure_type_source:'unknown',check_failed_observed:checkFailedObserved};
1979
2318
  }
1980
2319
  claimLeaseMs(claim) { return claim.lease_ms??this.limits.leaseMs; }
2320
+ // Invert the logical wall clock's origin without taking another clock sample.
2321
+ // A caller supplying only a wall clock has no shared origin; retain its existing fallback.
2322
+ monotonicDeadlineFor(wallDeadlineMs) {
2323
+ if(!this.leaseBootId) return null;
2324
+ return this.monotonicForWallDeadline
2325
+ ? this.monotonicForWallDeadline(wallDeadlineMs)
2326
+ : this.monotonicNow()+(wallDeadlineMs-this.nowMs());
2327
+ }
1981
2328
  leaseMonotonicDeadline(claim) {
1982
2329
  const deadline=Number(claim.lease_deadline_monotonic_ms);
1983
2330
  return this.leaseBootId&&claim.lease_boot_id===this.leaseBootId&&Number.isFinite(deadline)?deadline:null;
@@ -1987,10 +2334,13 @@ export class Store {
1987
2334
  return deadline===null?Date.parse(this.leaseExpiresAt(claim)):Math.floor(this.nowMs()+deadline-this.monotonicNow());
1988
2335
  }
1989
2336
  leaseExpiresAt(claim) { return claim.lease_deadline_at??new Date(Date.parse(claim.last_claim_activity_at??claim.claimed_at)+this.claimLeaseMs(claim)).toISOString(); }
1990
- // True while a claim idle since before this process started is inside its post-start window (start + its own lease).
2337
+ // True while a claim idle since before this process started is inside its post-start window: its own lease, or the shorter
2338
+ // limits.json worker_post_start_hold_ms for its worker.
1991
2339
  heldAfterStart(claim) {
1992
2340
  const activity=Date.parse(claim.activity??claim.last_claim_activity_at??claim.claimed_at);
1993
- return activity<this.startedMs&&this.nowMs()<this.startedMs+this.claimLeaseMs(claim);
2341
+ const holds=this.limits.workerPostStartHoldMs??{};
2342
+ const hold=Math.min(this.claimLeaseMs(claim),Object.hasOwn(holds,claim.worker)?holds[claim.worker]:Infinity);
2343
+ return activity<this.startedMs&&this.nowMs()<this.startedMs+hold;
1994
2344
  }
1995
2345
  leaseExpired(claim) {
1996
2346
  // Missing or malformed persisted deadlines carry no authority, even with a same-boot clock.
@@ -2181,8 +2531,38 @@ export class Store {
2181
2531
  const supersedes=this.db.prepare('SELECT target_id AS request_id,created_at FROM submit_supersedes WHERE request_id=?').get(id)??null;
2182
2532
  const superseded_by=this.db.prepare('SELECT request_id,created_at FROM submit_supersedes WHERE target_id=?').get(id)??null;
2183
2533
  const link=this.db.prepare('SELECT prior_id AS request_id,input_revision,at FROM job_revisions WHERE request_id=?').get(id),revises=link?{...link}:null;
2534
+ const follows=this.db.prepare('SELECT prior_id AS request_id,at FROM job_follows WHERE request_id=?').get(id);
2184
2535
  const authorityRevoked=!!a.cancelled_at||this.isProtocolJob(id)&&a.status==='finished';
2185
- return {...this.destinationFields(id),...(this.pullQueue.row(id)?{work_order_id:this.pullQueue.row(id).work_order_id,child_request_id:id}:{}),request_id:id,supersedes,superseded_by,revises,revised_by:this.newerRevision(id),apply:this.applyState(id),target_worker:a.target_worker,assignment:JSON.parse(a.payload),delivery_mode:a.delivery,t3_muted:this.deliveryMuted(id),thread_id:a.thread_id||null,environment_id:a.environment_id||null,parent_generation:a.parent_generation??null,status:a.status,execution:a.execution,required_capabilities:a.required_capabilities?JSON.parse(a.required_capabilities):[],review:!!a.review,created_at:a.created_at,valid_until:a.valid_until??null,valid_until_source:a.valid_until_source??null,expiry_requeues:a.expiry_requeues??0,...this.failureFields(id),cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancellation_requested:!!a.cancelled_at,authority_revoked:authorityRevoked,...this.sandboxStop(id,authorityRevoked),claim,progress,lifecycle_events:this.db.prepare("SELECT type,at,actor,reason FROM lifecycle_events WHERE request_id=? ORDER BY id").all(id),report:report??null,late_evidence,delivery,watch,owner_notes:this.ownerNotes(id),worker_break_notices:this.breakNotices(id),claim_denied:this.claimDenial(id),skipped_by_worker:a.skipped_at?{at:a.skipped_at,listed_count:a.listed_count,passed_over:a.passed_over}:null,pr_preflights:this.db.prepare("SELECT phase,evidence FROM pr_preflights WHERE request_id=? ORDER BY CASE phase WHEN 'submit' THEN 0 ELSE 1 END").all(id).map(row=>({phase:row.phase,...JSON.parse(row.evidence)}))};
2536
+ return {...this.destinationFields(id),...(this.pullQueue.row(id)?{work_order_id:this.pullQueue.row(id).work_order_id,child_request_id:id}:{}),request_id:id,supersedes,superseded_by,revises,...(follows?{follows:{...follows}}:{}),revised_by:this.newerRevision(id),apply:this.applyState(id),target_worker:a.target_worker,assignment:JSON.parse(a.payload),delivery_mode:a.delivery,t3_muted:this.deliveryMuted(id),thread_id:a.thread_id||null,environment_id:a.environment_id||null,parent_generation:a.parent_generation??null,status:a.status,execution:a.execution,required_capabilities:a.required_capabilities?JSON.parse(a.required_capabilities):[],review:!!a.review,created_at:a.created_at,valid_until:a.valid_until??null,valid_until_source:a.valid_until_source??null,expiry_requeues:a.expiry_requeues??0,...this.failureFields(id),cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancellation_requested:!!a.cancelled_at,authority_revoked:authorityRevoked,...this.sandboxStop(id,authorityRevoked),claim,progress,lifecycle_events:this.db.prepare("SELECT type,at,actor,reason FROM lifecycle_events WHERE request_id=? ORDER BY id").all(id),report:report??null,late_evidence,delivery,watch,owner_notes:this.ownerNotes(id),...this.workerRunsFor(id),publication_authority:this.publicationAuthority(id),worker_break_notices:this.breakNotices(id),claim_denied:this.claimDenial(id),skipped_by_worker:a.skipped_at?{at:a.skipped_at,listed_count:a.listed_count,passed_over:a.passed_over}:null,pr_preflights:this.db.prepare("SELECT phase,evidence FROM pr_preflights WHERE request_id=? ORDER BY CASE phase WHEN 'submit' THEN 0 ELSE 1 END").all(id).map(row=>({phase:row.phase,...JSON.parse(row.evidence)}))};
2537
+ }
2538
+ // D9: the worker's own run receipts. Stored before the report so a retried finish replaces them; never after a report exists.
2539
+ recordWorkerRuns(id,claimId,{runs,run_limit}) {
2540
+ if(!runs.length&&run_limit===null) return;
2541
+ this.transaction(()=>{
2542
+ if(this.db.prepare('SELECT 1 FROM reports WHERE request_id=?').get(id)) return;
2543
+ const at=this.stamp();
2544
+ this.db.prepare('DELETE FROM worker_runs WHERE request_id=? AND claim_id=?').run(id,claimId);
2545
+ this.db.prepare('DELETE FROM worker_run_limits WHERE request_id=? AND claim_id=?').run(id,claimId);
2546
+ runs.forEach((run,seq)=>this.db.prepare('INSERT INTO worker_runs(request_id,claim_id,seq,command,exit_code,output_tail,created_at) VALUES(?,?,?,?,?,?,?)').run(id,claimId,seq,run.command,run.exit_code,run.output_tail,at));
2547
+ if(run_limit!==null) this.db.prepare('INSERT INTO worker_run_limits(request_id,claim_id,limit_text,created_at) VALUES(?,?,?,?)').run(id,claimId,run_limit,at);
2548
+ });
2549
+ }
2550
+ // Every row is the worker's statement. The final report's claim picks which run receipts count.
2551
+ workerRunsFor(id) {
2552
+ const claim=this.db.prepare('SELECT claim_id FROM reports WHERE request_id=?').get(id)?.claim_id??this.db.prepare('SELECT claim_id FROM claims WHERE request_id=?').get(id)?.claim_id;
2553
+ if(!claim) return {worker_runs:[],worker_run_limit:null};
2554
+ return {worker_runs:this.db.prepare('SELECT command,exit_code,output_tail,created_at FROM worker_runs WHERE request_id=? AND claim_id=? ORDER BY seq').all(id,claim).map(row=>({...row,source:'worker_reported'})),
2555
+ worker_run_limit:this.db.prepare('SELECT limit_text FROM worker_run_limits WHERE request_id=? AND claim_id=?').get(id,claim)?.limit_text??null};
2556
+ }
2557
+ // D10: the work's current publication authority, read fresh at each effect. null when the work has no relationship.
2558
+ publicationAuthority(id) {
2559
+ const row=this.db.prepare('SELECT r.relationship_id,r.ended_at,r.publish_grant FROM assignments a JOIN relationships r USING(relationship_id) WHERE a.request_id=?').get(id);
2560
+ return row?{relationship_id:row.relationship_id,ended:row.ended_at!==null,publish_grant:row.publish_grant===null?null:JSON.parse(row.publish_grant)}:null;
2561
+ }
2562
+ setPublishGrant(relationshipId,grant) {
2563
+ const changed=this.db.prepare('UPDATE relationships SET publish_grant=? WHERE relationship_id=?').run(grant===null?null:JSON.stringify(grant),relationshipId);
2564
+ if(!changed.changes) throw new Error('relationship_not_found');
2565
+ return this.db.prepare('SELECT * FROM relationships WHERE relationship_id=?').get(relationshipId);
2186
2566
  }
2187
2567
  recordPrPreflight(id,phase,assignment,evidence,replace=false) {
2188
2568
  assertPreflight(assignment,evidence,this.nowMs());
@@ -2210,9 +2590,9 @@ export class Store {
2210
2590
  }
2211
2591
  }
2212
2592
  answerQuestion(id,questionId,text,ctx=null,ownerToken=null) {
2213
- return this.isProtocolJob(id)?answerProtocolQuestion(this,id,questionId,text,ownerToken,ctx):this.transaction(()=>this.answerQuestionInTransaction(id,questionId,text));
2593
+ return this.isProtocolJob(id)?answerProtocolQuestion(this,id,questionId,text,ownerToken,ctx):this.transaction(()=>this.answerQuestionInTransaction(id,questionId,text,true));
2214
2594
  }
2215
- answerQuestionInTransaction(id,questionId,text) {
2595
+ answerQuestionInTransaction(id,questionId,text,allowExactReplay=false) {
2216
2596
  if(!this.db.isTransaction)protocolError('transaction_required');
2217
2597
  validateQuestion(questionId,text);
2218
2598
  const assignment=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
@@ -2221,7 +2601,12 @@ export class Store {
2221
2601
  const question=this.db.prepare('SELECT * FROM job_questions WHERE request_id=? AND question_id=?').get(id,questionId);
2222
2602
  if(!question) throw questionError('NO_QUESTION','question does not exist');
2223
2603
  const claim=this.assertQuestionGrant(id,question);
2224
- if(question.answered_at!==null) throw questionError('ALREADY_ANSWERED','question already has an answer');
2604
+ if(question.answered_at!==null) {
2605
+ // Replay the same receipt without updating the answer, lifecycle or wake queue.
2606
+ // Keyed protocol commands keep their stricter command-ledger path.
2607
+ if(allowExactReplay&&question.answer===text) return {request_id:id,question_id:questionId,answered:true};
2608
+ throw questionError('ALREADY_ANSWERED','question already has an answer');
2609
+ }
2225
2610
  this.db.prepare('UPDATE job_questions SET answer=?,answered_at=? WHERE request_id=? AND question_id=?').run(text,this.stamp(),id,questionId);
2226
2611
  this.lifecycle(id,'waiting','owner',`question:answer:${questionId}`,claim);
2227
2612
  this.db.prepare(`UPDATE notifications SET state='suppressed',last_error='structured question answered'
@@ -2267,7 +2652,7 @@ export class Store {
2267
2652
  return {question_id:questionId,answer:question.answer,duplicate};
2268
2653
  }
2269
2654
  assertQuestionsResolved(id,claimId,outcome='completed') {
2270
- if(['blocked','failed'].includes(outcome)) return true;
2655
+ if(['blocked','failed',PROVIDER_REFUSAL].includes(outcome)) return true;
2271
2656
  const assignment=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
2272
2657
  if(assignment?.status==='cancelled') return true; // Preserve late evidence after cancellation.
2273
2658
  if(this.db.prepare('SELECT 1 FROM job_questions WHERE request_id=? AND claim_id=? AND consumed_at IS NULL').get(id,claimId)) throw questionError('QUESTION_OPEN','consume the current grant\'s outstanding answers before finishing');
@@ -2361,10 +2746,49 @@ export class Store {
2361
2746
  // This worker's expired claims, eligible only after verified host cessation.
2362
2747
  idleClaims(worker) {
2363
2748
  if(this.resumeIdleMs()<=0) return [];
2364
- return this.db.prepare("SELECT c.* FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND a.cancelled_at IS NULL AND c.state='active' AND c.worker=? ORDER BY c.last_claim_activity_at").all(worker).filter(c=>this.isIdleClaim(c));
2365
- }
2366
- guidanceFor(worker) { return this.workers.workers.get(worker)?.guidance==='resume'?`${workerGuidance} ${resumeNudge(this.resumeIdleMs()||defaultResumeIdleMs)}`:workerGuidance; }
2367
- // Owner messages first (oldest first), then assignments in LIST_ORDER: normal before background, items the worker skipped last.
2749
+ return this.db.prepare(`SELECT c.* FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND a.cancelled_at IS NULL AND c.state='active' AND c.worker=? AND NOT ${expired(this.nowMs())} ORDER BY c.last_claim_activity_at`).all(worker).filter(c=>this.isIdleClaim(c));
2750
+ }
2751
+ workerClaimGapMs(worker) {
2752
+ const gaps=this.limits.workerClaimMinGapMs??{};
2753
+ return Object.hasOwn(gaps,worker)?gaps[worker]:0;
2754
+ }
2755
+ workerHeartbeatMs(worker) {
2756
+ const intervals=this.limits.workerHeartbeatMs??{};
2757
+ return Object.hasOwn(intervals,worker)?intervals[worker]:null;
2758
+ }
2759
+ // The due time is reply guidance only; it never renews or fences a grant.
2760
+ workerHeartbeatFields(worker,claim) {
2761
+ const ms=this.workerHeartbeatMs(worker);
2762
+ if(ms===null||!claim) return {};
2763
+ const activity=Date.parse(claim.last_claim_activity_at??claim.claimed_at);
2764
+ return {progress_due_at:iso(Math.min(activity+ms,Date.parse(this.leaseExpiresAt(claim))))};
2765
+ }
2766
+ workerGetHeartbeat(row,worker,subject,claimId) {
2767
+ const c=row.claim;
2768
+ return row.status==='claimed'&&!row.cancellation_requested&&c?.state==='active'&&c.worker===worker&&c.subject===subject&&(claimId===undefined||c.claim_id===claimId)&&!this.leaseExpired(c)?this.workerHeartbeatFields(worker,c):{};
2769
+ }
2770
+ heartbeatForHeldClaim(id,claimId,worker) {
2771
+ if(this.workerHeartbeatMs(worker)===null||!claimId) return {};
2772
+ return this.workerHeartbeatFields(worker,this.db.prepare("SELECT * FROM claims WHERE request_id=? AND claim_id=? AND worker=? AND state='active'").get(id,claimId,worker));
2773
+ }
2774
+ guidanceFor(worker) {
2775
+ const base=this.workers.workers.get(worker)?.guidance==='resume'?`${workerGuidance} ${resumeNudge(this.resumeIdleMs()||defaultResumeIdleMs)}`:workerGuidance;
2776
+ const gap=this.workerClaimGapMs(worker)?`${base} Work this claim and report it before you claim another.`:base;
2777
+ const heartbeat=this.workerHeartbeatMs(worker);
2778
+ return heartbeat===null?gap:`${gap} Call progress with a short note at least every ${heartbeat/1000} seconds while you work, even when nothing changed.`;
2779
+ }
2780
+ assertClaimGap(id,subject,worker,active) {
2781
+ const gap=this.workerClaimGapMs(worker);
2782
+ if(!gap)return;
2783
+ const now=this.nowMs();
2784
+ const remaining=(active??this.activeClaims(subject,worker,id)).reduce((max,claim)=>{
2785
+ if(claim.subject!==subject||this.leaseExpired(claim))return max;
2786
+ const age=now-Date.parse(claim.claimed_at);
2787
+ return Number.isFinite(age)?Math.max(max,gap-Math.max(0,age)):max;
2788
+ },0);
2789
+ if(remaining>0)throw new Error(`claim_throttled: Work this claim and report it before you claim another. Retry after ${Math.ceil(remaining/1000)} seconds.`);
2790
+ }
2791
+ // Owner messages first (oldest first), then assignments in LIST_ORDER: waiting normal before other normal, then background; skipped items last in each class.
2368
2792
  // One bit for the public wake signal: a queued, live, uncancelled assignment targets one of these workers.
2369
2793
  hasQueuedFor(workerNames) {
2370
2794
  if(!workerNames.length) return false;
@@ -2372,7 +2796,63 @@ export class Store {
2372
2796
  }
2373
2797
  // Wake bit: queued work, or an expired own claim ready for regrant.
2374
2798
  hasWakeFor(worker) { return this.hasQueuedFor([worker])||this.idleClaims(worker).length>0; }
2375
- listPending(worker='dot') {
2799
+ // Persist selected IDs before asynchronous preflight. A retry can recover
2800
+ // live grants, or try the same nonempty plan if it never granted anything.
2801
+ // It cannot select different IDs or issue new grants after any grant landed.
2802
+ async claimBatch({next,available,worker,subject,connectionId,claimant,acquisitionId,leaseMs},grant) {
2803
+ if(!Number.isInteger(next)||next<1||next>8) throw new Error('invalid next');
2804
+ if(typeof acquisitionId!=='string'||!/^[A-Za-z0-9_-]{1,128}$/.test(acquisitionId)) throw new Error('batch claim requires acquisition_id');
2805
+ if(this.paused()) throw new Error(pausedClaimMessage);
2806
+ const hash=(...values)=>createHash('sha256').update(JSON.stringify(values)).digest('hex');
2807
+ const digest=hash(worker,subject,acquisitionId);
2808
+ const key='claim_batch_v1_'+digest;
2809
+ const parameters=hash(connectionId,claimant,next,leaseMs??null);
2810
+ const plan=this.transaction(()=>{
2811
+ const previous=this.db.prepare('SELECT value FROM bridge_state WHERE key=?').get(key);
2812
+ if(previous) {
2813
+ const saved=JSON.parse(previous.value);
2814
+ if(saved.parameters!==parameters) throw new Error('batch acquisition parameters changed');
2815
+ return {...saved,retry:true};
2816
+ }
2817
+ const ids=available>0?this.listPending(worker,{batch:true}).filter(item=>!item.blocked)
2818
+ .slice(0,Math.min(next,available)).map(item=>item.request_id):[];
2819
+ const fresh={parameters,ids,format:2,granted:false};
2820
+ this.db.prepare('INSERT INTO bridge_state(key,value) VALUES(?,?)').run(key,JSON.stringify(fresh));
2821
+ return {...fresh,retry:false};
2822
+ });
2823
+ // Old plans did not record completed grants; keep their conservative
2824
+ // replay-only behavior rather than possibly reissuing an ended claim.
2825
+ const replayOnly=plan.retry&&(plan.granted||plan.format!==2);
2826
+ const replies=[];
2827
+ for(const [slot,id] of plan.ids.entries()) {
2828
+ const perJob=plan.format===2?`batch_${digest}_${slot}`:'batch_'+hash(key,id);
2829
+ if(replayOnly) {
2830
+ const held=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
2831
+ if(held?.worker!==worker||!this.isExactClaimRetry(held,claimant,subject,perJob)) continue;
2832
+ }
2833
+ try {
2834
+ const reply=await grant(id,perJob,replayOnly?'retry':'queued');
2835
+ if(!reply?.claim_id||reply.error)break;
2836
+ replies.push(reply);
2837
+ } catch {
2838
+ // A later refusal cannot erase the successful prefix of the batch.
2839
+ break;
2840
+ }
2841
+ }
2842
+ if(plan.retry&&!replies.length&&(plan.ids.length===0||replayOnly)) throw new Error('acquisition_id was already used for a batch whose claims have all ended; call claim again with a fresh acquisition_id');
2843
+ return {claims:replies,retry:plan.retry};
2844
+ }
2845
+
2846
+ // Called inside the transaction that actually writes the claim, so a crash
2847
+ // or lost reply cannot make a completed grant look like a zero-grant plan.
2848
+ markBatchGrant(id,acquisitionId) {
2849
+ const match=typeof acquisitionId==='string'&&/^batch_([0-9a-f]{64})_([0-7])$/.exec(acquisitionId);
2850
+ if(!match)return;
2851
+ this.db.prepare("UPDATE bridge_state SET value=json_set(value,'$.granted',json('true')) WHERE key=? AND json_extract(value,'$.format')=2 AND json_extract(value,?)=?")
2852
+ .run('claim_batch_v1_'+match[1],`$.ids[${match[2]}]`,id);
2853
+ }
2854
+
2855
+ listPending(worker='dot',{batch=false,handoffExclusions=null}={}) {
2376
2856
  // Recheck historical refusals against one lazily loaded configuration per listing.
2377
2857
  // Listing is read-only: it neither deletes audit evidence nor grants approval.
2378
2858
  let loaded=false,failed=false,profile,loadError;
@@ -2398,7 +2878,9 @@ export class Store {
2398
2878
  return !(!approval&&!current||approval&&current?.revision===approval.revision&&current.policy.allowed);
2399
2879
  } catch { return true; }
2400
2880
  };
2401
- const assignments=this.db.prepare(`SELECT request_id,payload,created_at,EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked FROM assignments WHERE status='queued' AND ${live(this.nowMs())} ORDER BY ${LIST_ORDER}`).all().filter(a=>this.mayAct(worker,a.request_id)&&this.protocolListingLive(a.request_id)).map(a=>({...a,blocked:!!a.blocked&&blocked(a.request_id)})).sort((a,b)=>Number(a.blocked)-Number(b.blocked)).slice(0,50).map(a=>({kind:'assignment',request_id:a.request_id,title:JSON.parse(a.payload).brief.slice(0,160),created_at:a.created_at,...(a.blocked?{blocked:true}:{})}));
2881
+ let filler=this.activeCallerReserve(worker)>0?this.fillerRoom(worker):Infinity;
2882
+ const assignments=this.db.prepare(`SELECT request_id,payload,created_at,priority,review,caller_waiting,EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked FROM assignments WHERE status='queued' AND ${live(this.nowMs())}${batch?' AND skipped_at IS NULL':''} ORDER BY ${LIST_ORDER}`).all().filter(a=>this.mayAct(worker,a.request_id)&&this.protocolListingLive(a.request_id)&&(!batch||!this.isProtocolJob(a.request_id)&&!this.pullQueue.row(a.request_id))).map(a=>({...a,blocked:!!a.blocked&&blocked(a.request_id)})).sort((a,b)=>Number(a.blocked)-Number(b.blocked)).filter(a=>handoffExclusions===null||!a.blocked&&!handoffExclusions.has(a.request_id)&&!this.handoffLapsed(a.request_id,worker)).filter(a=>a.caller_waiting===1||filler-- > 0).slice(0,50).map(a=>({kind:'assignment',request_id:a.request_id,title:JSON.parse(a.payload).brief.slice(0,160),created_at:a.created_at,...(a.blocked?{blocked:true}:triageFields(JSON.parse(a.payload),a))}));
2883
+ if(batch||handoffExclusions!==null) return assignments;
2402
2884
  const messages=this.listMessages(worker).map(m=>({kind:'message',request_id:m.message_id,message_id:m.message_id,title:m.preview,created_at:m.created_at})).sort((a,b)=>a.created_at.localeCompare(b.created_at));
2403
2885
  const resumes=this.idleClaims(worker).filter(c=>this.protocolListingLive(c.request_id)).map(c=>({kind:'assignment',request_id:c.request_id,resume:true,idle_seconds:Math.floor(this.claimIdleMs(c)/1000),previous_epoch:c.epoch,
2404
2886
  ...(this.db.prepare('SELECT 1 FROM destination_blocks WHERE request_id=?').get(c.request_id)&&blocked(c.request_id)?{blocked:true}:{}),
@@ -2407,23 +2889,36 @@ export class Store {
2407
2889
  }
2408
2890
  // Called for each list_pending answer to the worker: the first freeLanes assignments are the ones it could claim now. One that
2409
2891
  // is still there SKIP_AFTER_ELIGIBLE_MS after it first was, with no claim, is marked skipped_by_worker (and goes behind its
2410
- // peers in LIST_ORDER). Every listed assignment is stamped as seen, which claim() uses to tell a pass-over from news.
2411
- recordListed(listed,freeLanes,worker='dot') { return this.transaction(() => {
2892
+ // peers in LIST_ORDER). Every eligible listing is stamped as seen, which claim() uses to tell a pass-over from news.
2893
+ recordListed(listed,freeLanes,worker='dot',claimsAccepted=true) { return this.transaction(() => {
2412
2894
  const now=this.nowMs(), at=iso(now), cutoff=iso(now-LISTED_POLL_GAP_MS), due=iso(now-SKIP_AFTER_ELIGIBLE_MS);
2413
2895
  const assignments=listed.filter(x=>x.kind==='assignment'&&!x.blocked);
2896
+ if(freeLanes<=0||this.paused()||!claimsAccepted) { for(const item of assignments) this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE request_id=?").run(item.request_id); return; }
2414
2897
  const seen=this.db.prepare("UPDATE assignments SET last_seen_listed_at=? WHERE request_id=? AND status='queued'");
2415
2898
  for(const item of assignments) seen.run(at,item.request_id);
2416
- if(freeLanes<=0) { for(const item of assignments) this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE request_id=?").run(item.request_id); return; }
2417
- const touch=this.db.prepare("UPDATE assignments SET eligible_since=COALESCE(eligible_since,?1),listed_count=listed_count+(last_listed_at IS NULL OR last_listed_at<=?3),last_listed_at=CASE WHEN last_listed_at IS NULL OR last_listed_at<=?3 THEN ?1 ELSE last_listed_at END,skipped_at=CASE WHEN skipped_at IS NULL AND eligible_since IS NOT NULL AND eligible_since<=?4 THEN ?1 ELSE skipped_at END WHERE request_id=?2 AND status='queued'");
2418
- for(const item of assignments.slice(0,freeLanes)) touch.run(at,item.request_id,cutoff,due);
2899
+ // A claim engaged in workspace work remains busy while live. A heartbeat by
2900
+ // itself earns only one lease after acquisition or a recorded resume.
2901
+ const busy=this.db.prepare(`SELECT c.*,(SELECT e.at FROM lifecycle_events e
2902
+ WHERE e.request_id=c.request_id AND e.claim_id=c.claim_id AND e.type='claimed' AND e.reason='resume'
2903
+ ORDER BY e.rowid DESC LIMIT 1) AS resumed_at
2904
+ FROM claims c JOIN assignments a USING(request_id)
2905
+ WHERE a.status='claimed' AND c.state='active' AND c.worker=?`).all(worker)
2906
+ .some(claim=>!this.leaseExpired(claim)&&(claim.first_workspace_tool_at!=null||
2907
+ now<Date.parse(claim.resumed_at??claim.claimed_at)+this.claimLeaseMs(claim)));
2908
+ if(busy) {
2909
+ const reset=this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE request_id=? AND status='queued'");
2910
+ for(const item of assignments) reset.run(item.request_id);
2911
+ }
2912
+ const touch=this.db.prepare("UPDATE assignments SET eligible_since=CASE WHEN ?5 THEN NULL ELSE COALESCE(eligible_since,?1) END,listed_count=listed_count+(last_listed_at IS NULL OR last_listed_at<=?3),last_listed_at=CASE WHEN last_listed_at IS NULL OR last_listed_at<=?3 THEN ?1 ELSE last_listed_at END,skipped_at=CASE WHEN NOT ?5 AND skipped_at IS NULL AND eligible_since IS NOT NULL AND eligible_since<=?4 THEN ?1 ELSE skipped_at END WHERE request_id=?2 AND status='queued'");
2913
+ for(const item of assignments.slice(0,freeLanes)) touch.run(at,item.request_id,cutoff,due,Number(busy));
2419
2914
  }); }
2420
- // A claim of one assignment passes over every queued one listed before it that the worker saw a moment ago.
2915
+ // A claim passes over recently seen queued peers ahead of it only in the same execution class.
2421
2916
  recordPassedOver(claimedId,worker='dot') {
2422
2917
  const now=this.nowMs(), at=iso(now), seenAfter=iso(now-PASSED_SEEN_MS);
2423
2918
  const order=this.listPending(worker).filter(x=>x.kind==='assignment'&&!x.blocked).map(x=>x.request_id);
2424
2919
  const ahead=order.slice(0,Math.max(0,order.indexOf(claimedId)));
2425
- const pass=this.db.prepare("UPDATE assignments SET passed_over=passed_over+1,skipped_at=CASE WHEN skipped_at IS NULL AND passed_over+1>=?3 THEN ?1 ELSE skipped_at END WHERE request_id=?2 AND status='queued' AND last_seen_listed_at>=?4");
2426
- for(const id of ahead) pass.run(at,id,SKIP_AFTER_PASSED,seenAfter);
2920
+ const pass=this.db.prepare("UPDATE assignments SET passed_over=passed_over+1,skipped_at=CASE WHEN skipped_at IS NULL AND passed_over+1>=?3 THEN ?1 ELSE skipped_at END WHERE request_id=?2 AND status='queued' AND last_seen_listed_at>=?4 AND execution=(SELECT execution FROM assignments WHERE request_id=?5)");
2921
+ for(const id of ahead) pass.run(at,id,SKIP_AFTER_PASSED,seenAfter,claimedId);
2427
2922
  }
2428
2923
  skippedByDot() { return this.db.prepare("SELECT request_id,skipped_at at,listed_count,passed_over FROM assignments WHERE status='queued' AND skipped_at IS NOT NULL ORDER BY skipped_at").all(); }
2429
2924
  // Built-in mode only: a fresh epoch is admitted only while the claimant's own
@@ -2491,11 +2986,19 @@ export class Store {
2491
2986
  } catch(error) { throw this.destinationConfigurationError(id,error); }
2492
2987
  if(digest!==approval.snapshot.connections_digest)throw refuse('Claim retry refused: the approved connection set changed.');
2493
2988
  }
2494
- claim(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,ctx=null,connectionId=null) {
2989
+ claim(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,ctx=null,connectionId=null,batchMode=null) {
2495
2990
  const requestedLeaseMs=arguments[7]??null;
2496
- return nonterminalOutcome(id,this.destinationOutcome(this.transaction(()=>this.isProtocolJob(id)
2497
- ?this.protocolClaimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,ctx?{...ctx,requestedLeaseMs}:ctx,connectionId)
2498
- :this.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,connectionId))));
2991
+ const claim=this.destinationOutcome(this.transaction(()=>{
2992
+ if(batchMode==='queued') {
2993
+ const selected=this.db.prepare('SELECT status,skipped_at FROM assignments WHERE request_id=?').get(id);
2994
+ if(selected?.status!=='queued'||selected.skipped_at!==null) throw new Error('batch assignment no longer eligible');
2995
+ }
2996
+ if(batchMode==='retry'&&!this.isExactClaimRetry(this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id),claimant,subject,acquisitionId)) throw new Error('batch grant no longer live');
2997
+ return this.isProtocolJob(id)
2998
+ ?this.protocolClaimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,ctx?{...ctx,requestedLeaseMs}:ctx,connectionId)
2999
+ :this.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,connectionId);
3000
+ }));
3001
+ return nonterminalOutcome(id,{...claim,...this.heartbeatForHeldClaim(id,claim.claim_id,worker)});
2499
3002
  }
2500
3003
  claimInTransaction(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,connectionId=null) {
2501
3004
  if(!this.db.isTransaction)protocolError('transaction_required');
@@ -2518,7 +3021,10 @@ export class Store {
2518
3021
  return {request_id:id,claim_id:old.claim_id,epoch:old.epoch,assignment:JSON.parse(a.payload),owner_notes:this.ownerNotes(id),duplicate:true,guidance:this.guidanceFor(worker),...this.destinationClaimFields(id)};
2519
3022
  }
2520
3023
  if(old && (old.state!=='active' || this.leaseExpired(old))) this.assertRegrantReady(old);
2521
- if(takeover&&old.subject===subject&&this.isIdleClaim(old)) return this.rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs,connectionId);
3024
+ if(takeover&&old.subject===subject&&this.isIdleClaim(old)) {
3025
+ this.assertClaimGap(id,subject,worker);
3026
+ return this.rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs,connectionId);
3027
+ }
2522
3028
  if(takeover) {
2523
3029
  if(!this.leaseExpired(old)&&old.subject===subject&&this.resumeIdleMs()>0) throw new Error(JSON.stringify({error:'claim_busy',message:`Request ${id}: another run of this worker holds it and is active; pick other work or retry after its lease expires. This affects only ${id}.`,request_id:id}));
2524
3030
  if(!this.leaseExpired(old)) throw new Error('already claimed by another claimant');
@@ -2527,7 +3033,10 @@ export class Store {
2527
3033
  if(destinationRefusal)return destinationRefusal;
2528
3034
  // Every new epoch of an existing claim (takeover, claim after abandon) waits for reconcile.
2529
3035
  if(old) this.assertNoUncertainDelivery(id);
2530
- if(this.activeClaims(subject,worker,id).length>=capacity) throw new Error('capacity_full');
3036
+ const active=this.activeClaims(subject,worker,id);
3037
+ this.assertWorkerClaimSlot(worker,id);
3038
+ if(active.length>=capacity) throw new Error('capacity_full');
3039
+ this.assertClaimGap(id,subject,worker,active);
2531
3040
  this.recordPrPreflight(id,'claim',JSON.parse(a.payload),preflight,!!old);
2532
3041
  if(takeover) { const why=Store.expirySummary(old); this.db.prepare("UPDATE claims SET state='abandoned',abandoned_at=?,abandon_reason=? WHERE request_id=?").run(this.stamp(),why,id); this.lifecycle(id,'abandoned','system',why,old); this.laneFreed(); }
2533
3042
  const claimId=`claim_${randomUUID()}`;
@@ -2537,8 +3046,12 @@ export class Store {
2537
3046
  this.rebindClaim(id,claimId);
2538
3047
  } else this.db.prepare('INSERT INTO claims(request_id,claimant,claim_id,claimed_at,subject,last_claim_activity_at,last_seen_note_seq,worker,lane_key,lane_scope,acquisition_id,lease_ms,connection_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,claimant,claimId,claimedAt,subject,claimedAt,seen,worker,laneKey,laneScope,acquisitionId,leaseMs,connectionId??null);
2539
3048
  this.setClaimDeadlineInTransaction(id,leaseMs);
2540
- if(a.status==='queued') this.recordPassedOver(id,worker);
3049
+ if(a.status==='queued') {
3050
+ this.recordPassedOver(id,worker);
3051
+ this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE target_worker=? AND status='queued' AND request_id<>? AND eligible_since IS NOT NULL").run(worker,id);
3052
+ }
2541
3053
  this.db.prepare("UPDATE assignments SET status='claimed',listed_count=0,last_listed_at=NULL,skipped_at=NULL,eligible_since=NULL,passed_over=0 WHERE request_id=?").run(id);
3054
+ this.markBatchGrant(id,acquisitionId);
2542
3055
  this.lifecycle(id,'claimed',`worker:${subject}`,takeover?'takeover':old?'reclaim':'new',{claim_id:claimId,epoch:old?old.epoch+1:1,worker});
2543
3056
  this.db.prepare('DELETE FROM claim_denials WHERE request_id=?').run(id);
2544
3057
  return {request_id:id,claim_id:claimId,epoch:old?old.epoch+1:1,assignment:JSON.parse(a.payload),owner_notes:this.ownerNotes(id),duplicate:false,guidance:this.guidanceFor(worker),...this.destinationGrantedInTransaction(id)};
@@ -2551,17 +3064,25 @@ export class Store {
2551
3064
  this.assertRegrantReady(old);
2552
3065
  this.assertLiveConnection(old.request_id,worker,connectionId);
2553
3066
  const id=old.request_id, idleS=Math.floor(this.claimIdleMs(old)/1000);
3067
+ this.assertWorkerClaimSlot(worker,id);
2554
3068
  const destinationRefusal=this.destinationAdmissionInTransaction(id);
2555
3069
  if(destinationRefusal)return destinationRefusal;
2556
3070
  this.assertNoUncertainDelivery(id);
2557
- const claimId=`claim_${randomUUID()}`, at=this.stamp(), epoch=old.epoch+1;
3071
+ const {claimId,at,epoch}=this.startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId);
3072
+ this.db.prepare('INSERT INTO progress(request_id,note,created_at,worker) VALUES(?,?,?,?)').run(id,`[bridge] run resumed: epoch ${old.epoch} lease expired after ${idleS}s without activity; epoch ${epoch} continues under a new claim`,at,worker);
3073
+ this.markBatchGrant(id,acquisitionId);
3074
+ this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch,worker});
3075
+ return {request_id:id,claim_id:claimId,epoch,previous_epoch:old.epoch,resumed:true,idle_seconds:idleS,assignment:JSON.parse(a.payload),owner_notes:this.ownerNotes(id),duplicate:false,guidance:this.guidanceFor(worker),...this.destinationGrantedInTransaction(id)};
3076
+ }
3077
+ // The one re-grant of an existing claim row: new claim_id and epoch, and every old-epoch field (progress, tool counters, acquisition, lease) reset.
3078
+ // rotateIdleClaim (claim wake) and resume both call it, so the two paths cannot drift.
3079
+ startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId) {
3080
+ const id=old.request_id, claimId=`claim_${randomUUID()}`, at=this.stamp(), epoch=old.epoch+1;
2558
3081
  const seen=this.db.prepare('SELECT COALESCE(max(sequence),0) n FROM owner_notes WHERE request_id=?').get(id).n;
2559
3082
  this.db.prepare("UPDATE claims SET claimant=?,claim_id=?,claimed_at=?,last_claim_activity_at=?,last_seen_note_seq=?,last_progress_at=NULL,epoch=?,tool_calls=0,last_tool=NULL,last_tool_at=NULL,last_tool_error=NULL,first_workspace_tool_at=NULL,acquisition_id=?,lease_ms=?,connection_id=? WHERE request_id=?").run(claimant,claimId,at,at,seen,epoch,acquisitionId,leaseMs,connectionId??null,id);
2560
3083
  this.setClaimDeadlineInTransaction(id,leaseMs);
2561
3084
  this.rebindClaim(id,claimId);
2562
- this.db.prepare('INSERT INTO progress(request_id,note,created_at,worker) VALUES(?,?,?,?)').run(id,`[bridge] run resumed: epoch ${old.epoch} lease expired after ${idleS}s without activity; epoch ${epoch} continues under a new claim`,at,worker);
2563
- this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch,worker});
2564
- return {request_id:id,claim_id:claimId,epoch,previous_epoch:old.epoch,resumed:true,idle_seconds:idleS,assignment:JSON.parse(a.payload),owner_notes:this.ownerNotes(id),duplicate:false,guidance:this.guidanceFor(worker),...this.destinationGrantedInTransaction(id)};
3085
+ return {claimId,at,epoch};
2565
3086
  }
2566
3087
  // The same subject continues under a fresh claim_id and the next epoch, so a lost process holding the old claim_id is fenced off.
2567
3088
  resume(id,subject='local-principal',connectionId=null) { return this.destinationOutcome(this.transaction(() => {
@@ -2571,14 +3092,11 @@ export class Store {
2571
3092
  if(!old||old.subject!==subject||a.status!=='claimed') throw new Error('no active claim for this subject');
2572
3093
  this.assertLiveConnection(id,old.worker,connectionId);
2573
3094
  this.assertRegrantReady(old);
3095
+ this.assertWorkerClaimSlot(old.worker,id);
2574
3096
  const destinationRefusal=this.destinationAdmissionInTransaction(id);
2575
3097
  if(destinationRefusal)return destinationRefusal;
2576
3098
  this.assertNoUncertainDelivery(id);
2577
- const claimId=`claim_${randomUUID()}`;
2578
- this.db.prepare('UPDATE claims SET claim_id=?,epoch=epoch+1,last_claim_activity_at=?,connection_id=COALESCE(?,connection_id) WHERE request_id=?').run(claimId,this.stamp(),connectionId??null,id);
2579
- this.rebindClaim(id,claimId);
2580
- this.setClaimDeadlineInTransaction(id,this.claimLeaseMs(old));
2581
- this.markNotesSeen(id,subject);
3099
+ const {claimId}=this.startNextEpoch(old,old.claimant,old.acquisition_id,this.claimLeaseMs(old),connectionId??old.connection_id); // resume cannot ask for a lease or an acquisition, so the epoch keeps the ones the worker was granted (its exact retry of a lost reply still matches)
2582
3100
  this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch:old.epoch+1});
2583
3101
  if(this.isProtocolJob(id)) {
2584
3102
  this.advanceProtocolRevisionInTransaction(id);
@@ -2587,11 +3105,15 @@ export class Store {
2587
3105
  return {request_id:id,claim_id:claimId,epoch:old.epoch+1,previous_epoch:old.epoch,assignment:JSON.parse(a.payload),owner_notes:this.ownerNotes(id),guidance:workerGuidance,...this.destinationGrantedInTransaction(id)};
2588
3106
  })); }
2589
3107
  // Withdraw the active claim and requeue the assignment, never while a delivery for it may be in flight or already delivered.
2590
- abandon(id,{actor='operator',reason='abandoned'}={}) { return this.transaction(() => {
3108
+ abandon(id,{actor='operator',reason='abandoned',fence=null}={}) { return this.transaction(() => {
2591
3109
  const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
2592
3110
  const old=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND state='active'").get(id);
2593
3111
  if(a.status==='finished'||a.status==='cancelled') throw new Error('assignment is terminal');
2594
3112
  if(!old||a.status!=='claimed') throw new Error('no active claim');
3113
+ if(fence && (a.status!=='claimed'||!old||old.claim_id!==fence.claim_id||old.epoch!==fence.epoch||
3114
+ old.lease_deadline_at!==fence.lease_deadline_at||old.lease_boot_id!==fence.lease_boot_id||
3115
+ old.lease_deadline_monotonic_ms!==fence.lease_deadline_monotonic_ms||
3116
+ !this.leaseExpired(old)||this.heldAfterStart(old))) return null;
2595
3117
  this.assertNoUncertainDelivery(id);
2596
3118
  const at=this.stamp();
2597
3119
  const expired=reason==='lease_expired'&&this.leaseExpired(old);
@@ -2612,19 +3134,83 @@ export class Store {
2612
3134
  // Result hints for list_pending and claim. Free lanes are bounded by both the lane capacity and the claim cap, so the
2613
3135
  // count never invites a claim that capacity_full would refuse.
2614
3136
  laneState(subject,worker='dot',laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity) {
2615
- return {free_lanes:this.freeLanes(subject,worker,laneCapacity,claimCapacity),queued:this.listPending(worker).filter(x=>x.kind==='assignment'&&!x.blocked).length};
3137
+ const max=this.workerMaxClaims(worker);
3138
+ return {...(max===null?{}:{worker_max_claims:max}),free_lanes:this.freeLanes(subject,worker,laneCapacity,claimCapacity),queued:this.listPending(worker).filter(x=>x.kind==='assignment'&&!x.resume&&!x.blocked).length};
2616
3139
  }
2617
3140
  // A claimed assignment left its lane: the next reannounceQueued tick may wake the worker at once instead of waiting out rewakeMs.
2618
3141
  laneFreed() { this.dispatchWake=true; }
2619
3142
  // Up to `free` live queued assignments in list_pending order (oldest, normal work first), never `exceptId`, with the one-line prompt to claim them.
2620
- nextQueued(free,exceptId=null,worker='dot') {
3143
+ // The claim count the bridge suggests to a worker (limits.json worker_claim_hint), or null. A suggestion only: free_lanes and every claim check stay as they are.
3144
+ claimHint(worker) { const hints=this.limits.workerClaimHint??{}; return Object.hasOwn(hints,worker)?hints[worker]:null; }
3145
+ // Claims the worker touched within the last 3 minutes. An older one is likely a dead run's and is listed to resume, so it does not count against the hint.
3146
+ recentClaimCount(worker) {
3147
+ const since=this.nowMs()-180000;
3148
+ return this.db.prepare("SELECT c.* FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' AND c.worker=?").all(worker)
3149
+ .filter(c=>Date.parse(c.last_claim_activity_at??c.claimed_at)>=since).length;
3150
+ }
3151
+ // `applyHint:false` is for the bridge's own picks (a finish handoff), which must see every eligible row: the hint only shapes what a worker is told.
3152
+ nextQueued(free,exceptId=null,worker='dot',{applyHint=true,handoffExclusions=null}={}) {
3153
+ const hint=applyHint?this.claimHint(worker):null,lanesFree=free;
3154
+ if(hint!==null) free=Math.min(free,Math.max(0,hint-this.recentClaimCount(worker)));
2621
3155
  if(free<=0) return {};
2622
- const all=this.listPending(worker).filter(x=>x.kind==='assignment'&&!x.blocked&&x.request_id!==exceptId);
3156
+ const all=this.listPending(worker,{handoffExclusions}).filter(x=>x.kind==='assignment'&&!x.blocked&&x.request_id!==exceptId);
2623
3157
  if(!all.length) return {};
2624
- const next=all.slice(0,free).map(({request_id,title})=>({request_id,title}));
2625
- return {next_queued:next,next_action:`${all.length} queued and ${free} ${free===1?'lane':'lanes'} free: claim ${next.map(x=>x.request_id).join(', ')} now (oldest first)`};
3158
+ const next=all.slice(0,free).map(x=>Object.fromEntries(['request_id','title',...TRIAGE_KEYS].filter(k=>x[k]!==undefined).map(k=>[k,x[k]])));
3159
+ const lanes=free<lanesFree?`${lanesFree} ${lanesFree===1?'lane':'lanes'} free, ${next.length} suggested`:`${free} ${free===1?'lane':'lanes'} free`;
3160
+ return {next_queued:next,next_action:`${all.length} queued and ${lanes}: claim ${next.map(x=>x.request_id).join(', ')} now (oldest first)`};
3161
+ }
3162
+ // Every inactive-to-live transition must enforce the same worker cap.
3163
+ // An exact retry of an already live grant never reaches this gate.
3164
+ assertWorkerClaimSlot(worker,id) {
3165
+ if(!this.db.isTransaction)protocolError('transaction_required');
3166
+ const max=this.workerMaxClaims(worker);
3167
+ if(max!==null&&this.liveWorkerClaims(worker,id)>=max)
3168
+ throw new Error(JSON.stringify({error:'capacity_full',message:`Worker ${worker} already holds its ${max} live claims`,worker}));
3169
+ if((this.limits?.workerCallerReserve?.[worker]??0)>0&&this.activeCallerReserve(worker)>0&&
3170
+ this.db.prepare('SELECT caller_waiting FROM assignments WHERE request_id=?').get(id)?.caller_waiting!==1&&this.fillerRoom(worker,id)<=0)
3171
+ throw new Error(JSON.stringify({error:'capacity_full',message:'No background lane is available because of the caller reserve.',worker}));
3172
+ }
3173
+ callerCapacity(worker,limits=this.limits,capacity=this.capacity) {
3174
+ return this.workerMaxClaims(worker,limits)??Math.min(limits.laneCapacity??6,capacity);
3175
+ }
3176
+ callerReserve(worker,limits=this.limits,capacity=this.capacity) {
3177
+ const reserve=limits.workerCallerReserve??{};
3178
+ const requested=Object.hasOwn(reserve,worker)?reserve[worker]:0;
3179
+ return Math.min(requested,Math.max(0,this.callerCapacity(worker,limits,capacity)-1));
3180
+ }
3181
+ // The reserve is work-conserving: a lane is held back only for a caller that is waiting now. With no waiting caller queued every
3182
+ // lane is open to normal jobs; with n waiting callers queued, up to n lanes (never more than the reserve) are held for them. A
3183
+ // running job is never stopped for this: the held lane is the next one that frees.
3184
+ activeCallerReserve(worker) {
3185
+ const reserve=this.callerReserve(worker);
3186
+ if(!(reserve>0)) return 0;
3187
+ const waiting=this.db.prepare(`SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND caller_waiting=1 AND ${live(this.nowMs())}`).get(worker).n;
3188
+ return Math.min(reserve,waiting);
3189
+ }
3190
+ fillerRoom(worker,exceptId=null) {
3191
+ // Every live claim holds a lane, a running caller's too: room for a normal job is what is left after those and the lanes held for waiting callers.
3192
+ const occupied=this.db.prepare("SELECT c.* FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' AND c.worker=? AND c.request_id IS NOT ?").all(worker,exceptId)
3193
+ .filter(claim=>!this.leaseExpired(claim)).length;
3194
+ return this.callerCapacity(worker)-this.activeCallerReserve(worker)-occupied;
3195
+ }
3196
+ workerMaxClaims(worker,limits=this.limits) {
3197
+ const caps=limits.workerMaxClaims??{};
3198
+ return Object.hasOwn(caps,worker)?caps[worker]:null;
3199
+ }
3200
+ liveWorkerClaims(worker,exceptId=null) {
3201
+ return this.db.prepare("SELECT c.* FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' AND c.worker=? AND c.request_id IS NOT ?").all(worker,exceptId)
3202
+ .filter(claim=>!this.leaseExpired(claim)).length;
3203
+ }
3204
+ freeLanes(subject,worker='dot',laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity) {
3205
+ const legacy=Math.min(laneCapacity,claimCapacity)-this.activeClaims(subject,worker).length;
3206
+ const max=this.workerMaxClaims(worker);
3207
+ return Math.max(0,max===null?legacy:Math.min(legacy,max-this.liveWorkerClaims(worker)));
3208
+ }
3209
+ quiesceCounts() {
3210
+ const live=this.db.prepare("SELECT c.* FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active'").all();
3211
+ const hostChecks=this.db.prepare("SELECT count(*) AS n FROM check_jobs WHERE status='running' OR stop_verified IS NOT 1").get().n;
3212
+ return {host_checks_unverified:hostChecks,live_leases:live.filter(claim=>!this.leaseExpired(claim)).length};
2626
3213
  }
2627
- freeLanes(subject,worker='dot',laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity) { return Math.max(0,Math.min(laneCapacity,claimCapacity)-this.activeClaims(subject,worker).length); }
2628
3214
  // Active claims for the operator, with the lease state that decides whether another claimant may take one over.
2629
3215
  claims() {
2630
3216
  return this.db.prepare("SELECT c.*,a.priority FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' ORDER BY c.claimed_at").all().map(c=>({
@@ -2637,9 +3223,15 @@ export class Store {
2637
3223
  // The sweep (sweepStaleLeases) or a takeover is what moves the claim to abandoned; until then the row stays active but cannot act.
2638
3224
  // A claim_id that an earlier epoch of this assignment held (rotation, takeover, reclaim) is superseded, not unknown. Only its own worker and subject learn that.
2639
3225
  refuseClaim(id,claimId,subject,worker) {
2640
- const cur=this.mayAct(worker,id)?this.db.prepare("SELECT claim_id,epoch,subject,worker FROM claims WHERE request_id=? AND state='active'").get(id):null;
3226
+ const cur=this.mayAct(worker,id)?this.db.prepare("SELECT * FROM claims WHERE request_id=? AND state='active'").get(id):null;
2641
3227
  if(cur&&cur.claim_id!==claimId&&cur.subject===subject&&cur.worker===worker&&this.db.prepare("SELECT 1 FROM lifecycle_events WHERE request_id=? AND claim_id=? AND type='claimed'").get(id,claimId))
2642
3228
  return new Error(JSON.stringify({error:'claim_superseded',message:`invalid claim: claim ${claimId} for ${id} was superseded by epoch ${cur.epoch}; stop using this claim. This affects only ${id}.`,request_id:id}));
3229
+ if(cur&&cur.claim_id!==claimId&&cur.subject===subject&&cur.worker===worker&&!this.leaseExpired(cur)&&
3230
+ this.db.prepare("SELECT 1 FROM lifecycle_events WHERE request_id<>? AND claim_id=? AND type='claimed' AND worker=? AND actor=?")
3231
+ .get(id,claimId,worker,`worker:${subject}`))
3232
+ return new Error(JSON.stringify({error:'claim_mismatch',
3233
+ message:`the supplied claim belongs to another job; call get for ${id} and check it against this run's grant.`,
3234
+ request_id:id}));
2643
3235
  return new Error('invalid claim');
2644
3236
  }
2645
3237
  // Commit-time authority only: never re-admit the grant against destination/repository policy.
@@ -2710,7 +3302,7 @@ export class Store {
2710
3302
  return {...receipt.value,revision:receipt.revision};
2711
3303
  });
2712
3304
  // Decorate after replay validation too, including receipts stored before this field existed.
2713
- return question?result:nonterminalOutcome(id,result);
3305
+ return question?result:nonterminalOutcome(id,{...result,...this.heartbeatForHeldClaim(id,claimId,worker)});
2714
3306
  }
2715
3307
  progressInTransaction(id,claimId,note,subject='local-principal',blocker=false,worker='dot',question=null) {
2716
3308
  if(!this.db.isTransaction) throw new Error('progress requires a caller-owned transaction');
@@ -2772,9 +3364,39 @@ export class Store {
2772
3364
  this.assertProtocolAvailable(id);
2773
3365
  return claim;
2774
3366
  }
3367
+ recordPatchAttempt(id,claimId,attempt,reason,subject,worker,connectionId=null) {
3368
+ if(attempt!=='applied'&&attempt!=='rejected')throw new TypeError('invalid patch attempt outcome');
3369
+ return this.transaction(()=>{
3370
+ const claim=this.assertClaim(id,claimId,subject,worker);
3371
+ this.assertMutationConnection(id,claim,connectionId);
3372
+ if(!this.db.prepare("SELECT 1 FROM assignments WHERE request_id=? AND status='claimed'").get(id))
3373
+ throw new Error('patch attempt requires a current claim');
3374
+ const rejected=attempt==='rejected';
3375
+ const safe=rejected?String(redactOutput(String(reason||'patch refused'))).replace(/[\u0000-\u001f\u007f]/g,' ').trim().slice(0,200):null;
3376
+ this.db.prepare(`INSERT INTO patch_attempts(request_id,claim_id,applied,rejected,last_rejection,updated_at)
3377
+ VALUES(?,?,?,?,?,?) ON CONFLICT(request_id,claim_id) DO UPDATE SET
3378
+ applied=patch_attempts.applied+excluded.applied,rejected=patch_attempts.rejected+excluded.rejected,
3379
+ last_rejection=COALESCE(excluded.last_rejection,patch_attempts.last_rejection),updated_at=excluded.updated_at`)
3380
+ .run(id,claimId,rejected?0:1,rejected?1:0,safe,this.stamp());
3381
+ });
3382
+ }
3383
+ patchAttemptSummary(id,claimId) {
3384
+ return this.db.prepare('SELECT applied,rejected,last_rejection FROM patch_attempts WHERE request_id=? AND claim_id=?')
3385
+ .get(id,claimId)??{applied:0,rejected:0,last_rejection:null};
3386
+ }
3387
+ finishPatchOutcome(id,claimId,outcome,summary) {
3388
+ if(outcome!=='completed'||!this.db.prepare("SELECT 1 FROM assignments WHERE request_id=? AND status<>'cancelled' AND json_extract(payload,'$.execution_scope')='implementation'").get(id))
3389
+ return {outcome,summary};
3390
+ const attempts=this.patchAttemptSummary(id,claimId);
3391
+ if(attempts.applied||!attempts.rejected)return {outcome,summary};
3392
+ // Preserve submitted text as an exact replay binding; the stored result remains untouched.
3393
+ return {outcome:'failed',summary:`every apply_patch was rejected; last: ${attempts.last_rejection||'patch refused'}\n${summary}`};
3394
+ }
2775
3395
  finishOnce(id,claimId,outcome,summary,result,subject,evidence,worker,captureEvidence=null,connectionId=null) {
2776
3396
  const claim=this.assertFinishClaim(id,claimId,subject,worker);
2777
3397
  this.assertMutationConnection(id,claim,connectionId);
3398
+ const submittedOutcome=outcome;
3399
+ ({outcome,summary}=this.finishPatchOutcome(id,claimId,outcome,summary));
2778
3400
  const old=this.db.prepare('SELECT * FROM reports WHERE request_id=?').get(id);
2779
3401
  if(old) { if(old.outcome!==outcome||old.summary!==summary||old.result!==result) throw new Error('contradictory report: this request already has a different stored report, which is kept; do not call finish again with other text. Call list_pending for your next job.'); return {receipt_id:old.receipt_id,request_id:id,duplicate:true,late:!!old.late,...Store.resultAuthority(!!old.late)}; }
2780
3402
  const a=this.db.prepare('SELECT status,cancelled_reason FROM assignments WHERE request_id=?').get(id);
@@ -2788,7 +3410,14 @@ export class Store {
2788
3410
  }
2789
3411
  return {cancelled:true,reason:a.cancelled_reason,contradiction:!!kept&&(kept.outcome!==outcome||kept.full_sha256!==full)};
2790
3412
  }
2791
- this.assertQuestionsResolved(id,claimId,outcome);
3413
+ this.assertQuestionsResolved(id,claimId,submittedOutcome);
3414
+ if(!this.isProtocolJob(id)) {
3415
+ const unseenNotes=this.db.prepare('SELECT id,at,text FROM owner_notes WHERE request_id=? AND sequence>? ORDER BY sequence')
3416
+ .all(id,claim.last_seen_note_seq??0);
3417
+ // Leave the note watermark alone until the authenticated holder reads the job.
3418
+ if(unseenNotes.length) return {request_id:id,status:'claimed',terminal:false,deferred:true,owner_notes:unseenNotes,
3419
+ guidance:'New owner notes arrived. Read the assignment, consider the notes, then finish again.'};
3420
+ }
2792
3421
  if(captureEvidence) evidence=captureEvidence();
2793
3422
  this.recordClaimDenials(id,`${summary}\n${result}`,worker);
2794
3423
  const receipt=`report_${randomUUID()}`;
@@ -2843,17 +3472,20 @@ export class Store {
2843
3472
  // same path as `dalan abandon`, so the row is requeued and its lane is free at once. Before this, an expired lease only
2844
3473
  // let another claimant take the item over, and a dead claim held its lane for as long as nobody did. A usage break neither holds
2845
3474
  // the sweep nor moves a deadline: only the claimant's own activity extends a lease. After a bridge start, a claim whose last activity came before the start is not swept
2846
- // before the start plus that claim's own lease (lease_ms), the full lease a restart would have given it, so a deadline that
3475
+ // before the start plus that claim's own lease (lease_ms), the full lease a restart would have given it (or the shorter worker_post_start_hold_ms of its worker), so a deadline that
2847
3476
  // passed while the bridge was down or draining does not requeue work the worker may still be running. A claim touched since
2848
3477
  // the start has no grace. A claim with an uncertain delivery waits for reconcile.
2849
3478
  // Returns the abandoned request ids.
2850
3479
  sweepStaleLeases(limit=20) {
2851
3480
  const done=[];
2852
- const stale=this.db.prepare("SELECT c.request_id,c.worker,c.lease_ms,c.lease_deadline_at,c.lease_boot_id,c.lease_deadline_monotonic_ms,c.claimed_at,c.last_claim_activity_at,COALESCE(c.last_claim_activity_at,c.claimed_at) activity FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active'").all()
3481
+ const stale=this.db.prepare("SELECT c.request_id,c.claim_id,c.epoch,c.worker,c.lease_ms,c.lease_deadline_at,c.lease_boot_id,c.lease_deadline_monotonic_ms,c.claimed_at,c.last_claim_activity_at,COALESCE(c.last_claim_activity_at,c.claimed_at) activity FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active'").all()
2853
3482
  .filter(c=>!this.heldAfterStart(c))
2854
3483
  .filter(c=>this.leaseExpired(c)).sort((a,b)=>a.activity<b.activity?-1:1).slice(0,limit);
2855
- for(const {request_id} of stale) {
2856
- try { this.abandon(request_id,{actor:'system',reason:'lease_expired'}); done.push(request_id); }
3484
+ for(const {request_id,claim_id,epoch,lease_deadline_at,lease_boot_id,lease_deadline_monotonic_ms} of stale) {
3485
+ try {
3486
+ const fence={claim_id,epoch,lease_deadline_at,lease_boot_id,lease_deadline_monotonic_ms};
3487
+ if(this.abandon(request_id,{actor:'system',reason:'lease_expired',fence})) done.push(request_id);
3488
+ }
2857
3489
  catch(e) { if(!/uncertain_delivery|no active claim|terminal/.test(e.message)) throw e; }
2858
3490
  }
2859
3491
  return done;
@@ -2929,7 +3561,11 @@ export class Store {
2929
3561
  }
2930
3562
  deliveryMuted(id) { return !!this.db.prepare('SELECT 1 FROM assignment_delivery_mutes WHERE request_id=?').get(id); }
2931
3563
  suppressFinishedQuestions(requestId=null) {
2932
- this.db.prepare("UPDATE notifications SET state='suppressed',last_error='result superseded question' WHERE (kind='blocker' OR kind='wait' AND body IS NOT NULL) AND state IN ('pending','failed') AND request_id IN (SELECT request_id FROM assignments WHERE status='finished' AND (? IS NULL OR request_id=?))").run(requestId,requestId);
3564
+ // One job, or every finished job. The two statements are not merged with `? IS NULL OR`: that form defeats the request_id index
3565
+ // and scanned every pending row on each finish.
3566
+ const supersede="UPDATE notifications SET state='suppressed',last_error='result superseded question' WHERE (kind='blocker' OR kind='wait' AND body IS NOT NULL) AND state IN ('pending','failed')";
3567
+ if(requestId===null) this.db.prepare(`${supersede} AND request_id IN (SELECT request_id FROM assignments WHERE status='finished')`).run();
3568
+ else this.db.prepare(`${supersede} AND request_id=? AND request_id IN (SELECT request_id FROM assignments WHERE status='finished' AND request_id=?)`).run(requestId,requestId);
2933
3569
  }
2934
3570
  quietDelivery(id,reason) {
2935
3571
  // Keep results/questions in the existing wait queue. Watches stay visible to
@@ -2970,7 +3606,9 @@ export class Store {
2970
3606
  return this.db.prepare("UPDATE notifications SET state='pending',next_at=?,last_error=?,uncertain_reason=NULL WHERE id=? AND state IN ('pending','failed')").run(this.nowMs()+delayMs,String(reason).slice(0,500),id).changes===1;
2971
3607
  }
2972
3608
  paused() { return this.db.prepare('SELECT paused_at,reason FROM operator_state WHERE id=1').get().paused_at !== null; }
2973
- setPause(reason) { return this.transaction(() => { this.db.prepare('UPDATE operator_state SET paused_at=?,reason=? WHERE id=1').run(reason?this.stamp():null,reason||null); return {paused:!!reason,reason:reason||null}; }); }
3609
+ // Claims reopening restarts the skip clock: time claims were refused is not time the worker passed a job over.
3610
+ restartSkipClock() { this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE status='queued'").run(); }
3611
+ setPause(reason) { return this.transaction(() => { this.db.prepare('UPDATE operator_state SET paused_at=?,reason=? WHERE id=1').run(reason?this.stamp():null,reason||null); if(!reason) this.restartSkipClock(); return {paused:!!reason,reason:reason||null}; }); }
2974
3612
  suppressStaleQuestion(row) {
2975
3613
  if(!row||!['blocker','wait'].includes(row.kind)||!row.body) return false;
2976
3614
  let body;try{body=JSON.parse(row.body);}catch{return false;}
@@ -3289,7 +3927,12 @@ export class Store {
3289
3927
  const lastClaim=this.db.prepare("SELECT max(claimed_at) last_claim FROM claims WHERE worker='dot'").get().last_claim;
3290
3928
  const uncertain=this.db.prepare("SELECT count(*) n FROM notifications WHERE state='uncertain' AND kind IN ('t3','watch','blocker','break','event')").get().n;
3291
3929
  const pause=this.db.prepare('SELECT paused_at,reason FROM operator_state WHERE id=1').get();
3292
- const queued=this.queuedRows().filter(row=>row.target_worker==='dot').length;
3930
+ const queuedByWorker=new Map(this.db.prepare(`WITH live_queue AS (
3931
+ SELECT target_worker worker,request_id,created_at,
3932
+ count(*) OVER (PARTITION BY target_worker) n,
3933
+ row_number() OVER (PARTITION BY target_worker ORDER BY created_at,request_id) rank
3934
+ FROM assignments WHERE status='queued' AND cancelled_at IS NULL AND skipped_at IS NULL AND ${live(this.nowMs())})
3935
+ SELECT worker,n,created_at oldest,request_id FROM live_queue WHERE rank=1`).all().map(r=>[r.worker,r]));
3293
3936
  const dotQueuedWithoutSubscription=active.length===0&&!!this.db.prepare(`SELECT 1 FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())} LIMIT 1`).get();
3294
3937
  const subscription={state:!sub?'absent':sub.state==='revoked'?'revoked':sub.rotation_blocked?'rotation_blocked':sub.auth_failures>=3?'callback_blocked':sub.expires_at<=this.stamp()?'expired':'active',expires_at:sub?.expires_at||null,last_verified_at:sub?.verified_at||null,last_event_2xx_at:sub?.last_event_2xx_at||null,last_claim_at:lastClaim,principal:sub?.principal||null,auth_failures:sub?.auth_failures||0};
3295
3938
  const priority_counts=Object.fromEntries(['normal','background'].map(priority=>[priority,Object.fromEntries(['queued','claimed'].map(status=>[status,this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority=? AND status=? AND (status<>'queued' OR ${live(this.nowMs())})`).get(priority,status).n]))]));
@@ -3301,23 +3944,136 @@ export class Store {
3301
3944
  const dotCapacity=this.workerCapacityEvidence('dot',active,limits,capacity);
3302
3945
  const freeLanes=dotCapacity.free_lanes;
3303
3946
  const legacyScope=this.workers.legacy===true||this.workers.workers.has('dot')?'dot':'none';
3304
- const dispatch={scope:legacyScope,state:pause.paused_at?'paused':freeLanes===null?'unknown':freeLanes<=0?'full':queued>0?'dispatch_gap':'supply_gap',free_lanes:freeLanes,queued_live:queued,oldest_unclaimed_age_ms:oldest?this.nowMs()-Date.parse(oldest):null};
3947
+ const dispatchState=(free,first)=>({
3948
+ state:pause.paused_at?'paused':free===null?'unknown':free<=0?'full':(first?.n??0)>0?'dispatch_gap':'supply_gap',
3949
+ free_lanes:free,queued_live:first?.n??0,oldest_unclaimed_age_ms:first?.oldest?this.nowMs()-Date.parse(first.oldest):null,
3950
+ oldest_unclaimed_request_id:first?.request_id??null
3951
+ });
3952
+ const dispatch={scope:legacyScope,...dispatchState(freeLanes,queuedByWorker.get('dot'))};
3305
3953
  const workerNames=new Set([...this.workers.workers.keys(),...this.db.prepare('SELECT DISTINCT target_worker worker FROM assignments').all().map(r=>r.worker),...this.db.prepare('SELECT DISTINCT worker FROM claims').all().map(r=>r.worker)]);
3306
3954
  const by_worker=Object.fromEntries([...workerNames].sort().map(worker=>{
3307
3955
  const workerSubscriptions=worker==='dot'?active:this.activeSubscriptions().filter(row=>row.worker===worker);
3308
3956
  const liveness=this.liveness(limits,capacity,worker),expired=this.queuedExpired(worker);
3309
3957
  const requeued=this.queuedExpiredRequeued(worker);
3310
3958
  const workerCounts=this.db.prepare(`SELECT status,count(*) count FROM assignments WHERE target_worker=? AND (status<>'queued' OR ${live(this.nowMs())}) GROUP BY status`).all(worker).filter(row=>row.count>0);
3311
- const liveQueued=this.queuedRows().filter(row=>row.target_worker===worker).length;
3312
- return [worker,{scope:'worker',counts:workerCounts,queued_expired:expired,queued_expired_requeued:requeued,active_claims:liveness.claimed_outer_count,queued_live:liveQueued,subscriptions_active:workerSubscriptions.length,capacity:this.workerCapacityEvidence(worker,workerSubscriptions,limits,capacity),last_call_at:liveness.last_worker_call_at,last_list_pending_at:liveness.last_list_pending_at,stale_claims:liveness.stale_claims,queue_classes:liveness.queue_classes,unclaimed_after_reannounce:liveness.unclaimed_after_reannounce,oldest_claim_age_ms:liveness.oldest_claim_age_ms,oldest_claim_progress_age_ms:liveness.oldest_claim_progress_age_ms,oldest_unclaimed_event_2xx_age_ms:liveness.oldest_unclaimed_event_2xx_age_ms,silence_ms:liveness.worker_silence_ms}];
3959
+ const liveQueued=this.queuedRows().filter(row=>row.target_worker===worker);
3960
+ const queuedNormal=liveQueued.filter(row=>row.priority==='normal').length;
3961
+ return [worker,{scope:'worker',...(Object.hasOwn(limits.workerHeartbeatMs??{},worker)?{heartbeat_ms:limits.workerHeartbeatMs[worker]}:{}),counts:workerCounts,queued_expired:expired,queued_expired_requeued:requeued,active_claims:liveness.claimed_outer_count,queued_live:liveQueued.length,queued_normal:queuedNormal,queued_waiting:liveQueued.filter(row=>row.priority==='normal'&&row.caller_waiting===1).length,queued_waiting_background:liveQueued.filter(row=>row.priority==='background'&&row.caller_waiting===1).length,subscriptions_active:workerSubscriptions.length,capacity:this.workerCapacityEvidence(worker,workerSubscriptions,limits,capacity),last_call_at:liveness.last_worker_call_at,last_list_pending_at:liveness.last_list_pending_at,stale_claims:liveness.stale_claims,queue_classes:liveness.queue_classes,unclaimed_after_reannounce:liveness.unclaimed_after_reannounce,oldest_claim_age_ms:liveness.oldest_claim_age_ms,oldest_claim_progress_age_ms:liveness.oldest_claim_progress_age_ms,oldest_unclaimed_event_2xx_age_ms:liveness.oldest_unclaimed_event_2xx_age_ms,silence_ms:liveness.worker_silence_ms}];
3962
+ }));
3963
+ dispatch.by_worker=Object.fromEntries([...this.workers.workers.keys()].sort().map(worker=>{
3964
+ const evidence=by_worker[worker].capacity;
3965
+ return [worker,{...dispatchState(evidence.free_lanes,queuedByWorker.get(worker)),free_lanes_for_callers:evidence.free_lanes_for_callers,...(evidence.worker_max_claims===undefined?{}:{worker_max_claims:evidence.worker_max_claims})}];
3313
3966
  }));
3314
3967
  const released=this.db.prepare("SELECT id,id notice_id,request_id,message_id,subscription_id,attempt_id,attempt_started_at,terminal_at,terminal_reason FROM notifications WHERE state='uncertain_terminal' ORDER BY terminal_at DESC LIMIT 20").all();
3315
3968
  return {held_wakes:this.db.prepare("SELECT count(*) n FROM notifications WHERE held_kind IS NOT NULL AND state IN ('pending','quiet')").get().n,dispatch,liveness_scope:legacyScope,counts,counts_scope:'global',by_worker,priority_counts,priority_counts_scope:'global',background_max_in_flight:backgroundMaxInFlight,skipped_by_worker:(skipped=>({count:skipped.length,request_ids:skipped.slice(0,20).map(x=>x.request_id)}))(this.skippedByDot()),claim_denied:{count:denied.length,request_ids:denied.map(d=>d.request_id).slice(0,20),capacity_hold_until:this.capacityHoldUntil()},subscriptions_active:active.length,last_verified:sub?.verified_at||null,oldest_pending:oldest,last_claim:lastClaim,last_claim_at:lastClaim,subscription,queued_without_active_subscription:dotQueuedWithoutSubscription,oldest_queue_age_ms:oldest?this.nowMs()-Date.parse(oldest):null,uncertain_deliveries:uncertain,uncertain_terminal_deliveries:released,queued_expired:queuedExpired,queued_expired_requeued:queuedExpiredRequeued,paused:!!pause.paused_at,pause_reason:pause.reason,...(({items,...rest})=>rest)(this.liveness(limits,capacity)),worker_break:this.breakState(),throttle,budget,...statusEvidence(this)};
3316
3969
  }
3970
+ // Minutes in the last 24 hours when a reserved lane sat free with no caller job waiting for this worker.
3971
+ // A reserved lane is free exactly when the worker holds fewer live claims than its caller capacity: filler
3972
+ // jobs may hold at most capacity minus reserve lanes, so a lane free while claims are below capacity is a
3973
+ // free reserved lane. The count is an approximation by 1-minute buckets: a minute counts when a reserved
3974
+ // lane is free and no caller job is waiting at the start of that minute. History comes from the append-only
3975
+ // lifecycle events, never from the claims table, whose row is rewritten when a claim resumes: a claim runs
3976
+ // from its 'claimed' event to the next terminal event for that claim ('completed', 'abandoned', 'detach',
3977
+ // 'cancelled') or to a later 'claimed' event for the same job under a new claim, and a caller job waits from
3978
+ // its 'queued' event to its 'claimed' or 'cancelled' event. Claim starts are read back 7 days, the longest
3979
+ // a lease can run, so a start older than that cannot still hold a lane. Time before the worker's first
3980
+ // recorded event is unknown and is not counted, so a fresh worker reports only the minutes since its first
3981
+ // activity.
3982
+ reserveIdleMinutes24h(worker,limits=this.limits,capacity=this.capacity) {
3983
+ const reserve=this.callerReserve(worker,limits,capacity);
3984
+ if(!(reserve>0)) return null;
3985
+ const cap=this.callerCapacity(worker,limits,capacity);
3986
+ const now=this.nowMs(), windowStart=now-24*HOUR;
3987
+ const cached=this.reserveIdleMinutesCache.get(worker);
3988
+ if(cached&&now>=cached.at&&now-cached.at<MINUTE) return cached.value;
3989
+ const remember=value=>{this.reserveIdleMinutesCache.set(worker,{at:now,value});return value;};
3990
+ // History can only start at the worker's first recorded event: a claim the worker held, or the first job
3991
+ // ever queued for the worker.
3992
+ const firsts=[this.db.prepare('SELECT min(at) first FROM lifecycle_events WHERE worker=?').get(worker)?.first,
3993
+ this.db.prepare('SELECT min(created_at) first FROM assignments WHERE target_worker=?').get(worker)?.first,
3994
+ this.db.prepare('SELECT min(claimed_at) first FROM claims WHERE worker=?').get(worker)?.first]
3995
+ .map(at=>typeof at==='string'?Date.parse(at):NaN).filter(Number.isFinite);
3996
+ if(!firsts.length) return remember(0);
3997
+ const start=Math.max(windowStart,Math.min(...firsts));
3998
+ const buckets=Math.max(0,Math.floor((now-start)/60000));
3999
+ if(!buckets) return remember(0);
4000
+ const lookback=iso(now-7*24*HOUR), startText=iso(start), nowText=iso(now);
4001
+ const starts=this.db.prepare(`SELECT s.id,s.request_id,s.claim_id,s.at FROM lifecycle_events s
4002
+ WHERE s.worker=? AND s.type='claimed' AND s.at>=? AND
4003
+ (s.at>=? OR NOT EXISTS (
4004
+ SELECT 1 FROM lifecycle_events e WHERE e.request_id=s.request_id
4005
+ AND (e.at>s.at OR (e.at=s.at AND e.id>s.id))
4006
+ AND (e.type IN ('completed','abandoned','detach','cancelled') OR
4007
+ (e.type='claimed' AND e.claim_id IS NOT NULL AND e.claim_id IS NOT s.claim_id))
4008
+ AND e.at<=?
4009
+ )) ORDER BY s.at,s.id`).all(worker,lookback,startText,nowText);
4010
+ const seen=new Set(), claimStarts=[];
4011
+ for(const s of starts) {
4012
+ const key=s.claim_id??`event:${s.id}`;
4013
+ if(seen.has(key)) continue;
4014
+ seen.add(key);
4015
+ claimStarts.push(s);
4016
+ }
4017
+ const requestIds=[...new Set(claimStarts.map(s=>s.request_id))];
4018
+ const events=[];
4019
+ for(let i=0;i<requestIds.length;i+=400) {
4020
+ const chunk=requestIds.slice(i,i+400);
4021
+ events.push(...this.db.prepare(`SELECT request_id,claim_id,type,at,id FROM lifecycle_events WHERE request_id IN (${chunk.map(()=>'?').join(',')}) AND type IN ('claimed','completed','abandoned','detach','cancelled') AND at>=? ORDER BY at,id`).all(...chunk,lookback));
4022
+ }
4023
+ const byRequest=new Map();
4024
+ for(const e of events) {
4025
+ if(!byRequest.has(e.request_id)) byRequest.set(e.request_id,[]);
4026
+ byRequest.get(e.request_id).push(e);
4027
+ }
4028
+ const claimIntervals=claimStarts.map(s=>{
4029
+ const later=(byRequest.get(s.request_id)??[]).find(e=>(e.at>s.at||(e.at===s.at&&e.id>s.id))&&
4030
+ (e.type!=='claimed'||(e.claim_id!=null&&e.claim_id!==s.claim_id)));
4031
+ return [Date.parse(s.at),later?Date.parse(later.at):now];
4032
+ });
4033
+ const waitingRows=this.db.prepare('SELECT request_id,created_at FROM assignments WHERE caller_waiting=1 AND target_worker=?').all(worker);
4034
+ const waitIntervals=[];
4035
+ if(waitingRows.length) {
4036
+ const waitingIds=waitingRows.map(r=>r.request_id), waitEvents=[];
4037
+ for(let i=0;i<waitingIds.length;i+=400) {
4038
+ const chunk=waitingIds.slice(i,i+400);
4039
+ waitEvents.push(...this.db.prepare(`SELECT request_id,type,at,id FROM lifecycle_events WHERE request_id IN (${chunk.map(()=>'?').join(',')}) AND type IN ('queued','claimed','cancelled') AND at>=? ORDER BY at,id`).all(...chunk,lookback));
4040
+ }
4041
+ const waitByRequest=new Map();
4042
+ for(const e of waitEvents) {
4043
+ if(!waitByRequest.has(e.request_id)) waitByRequest.set(e.request_id,[]);
4044
+ waitByRequest.get(e.request_id).push(e);
4045
+ }
4046
+ for(const row of waitingRows) {
4047
+ const evs=waitByRequest.get(row.request_id)??[], created=Date.parse(row.created_at);
4048
+ let open=null;
4049
+ for(const e of evs) {
4050
+ if(e.type==='queued') { if(open===null) open=Date.parse(e.at); }
4051
+ else {
4052
+ if(open===null) open=created;
4053
+ waitIntervals.push([open,Date.parse(e.at)]);
4054
+ open=null;
4055
+ }
4056
+ }
4057
+ if(open!==null) waitIntervals.push([open,now]);
4058
+ else if(!evs.length) {
4059
+ const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(row.request_id);
4060
+ if(a?.status==='queued') waitIntervals.push([created,now]);
4061
+ }
4062
+ }
4063
+ }
4064
+ return remember(countReserveIdleMinutes(start,now,cap,claimIntervals,waitIntervals));
4065
+ }
3317
4066
  workerCapacityEvidence(worker,subscriptions,limits,capacity) {
3318
4067
  const byPrincipal=[...new Map(subscriptions.map(sub=>[sub.principal,sub])).values()];
3319
4068
  const scope=this.workers.laneScope==='worker'?'worker':'principal';
3320
- const unknown=reason=>({state:'unknown',scope,source:null,free_lanes:null,unknown_reason:reason});
4069
+ const max=this.workerMaxClaims(worker,limits);
4070
+ const liveClaims=this.liveWorkerClaims(worker);
4071
+ const reserveIdle=this.reserveIdleMinutes24h(worker,limits,capacity);
4072
+ const workerCap={caller_reserve:this.callerReserve(worker,limits,capacity),
4073
+ ...(reserveIdle===null?{}:{reserve_idle_minutes_24h:reserveIdle}),
4074
+ free_lanes_for_callers:Math.max(0,this.callerCapacity(worker,limits,capacity)-liveClaims),
4075
+ ...(max===null?{}:{worker_max_claims:max,worker_free_claims:Math.max(0,max-liveClaims)})};
4076
+ const unknown=reason=>({...workerCap,state:'unknown',scope,source:null,free_lanes:null,unknown_reason:reason});
3321
4077
  if(!byPrincipal.length) return unknown('no_active_subscription');
3322
4078
  const subjectKeys=this.db.prepare("SELECT DISTINCT c.lane_key FROM claims c JOIN assignments a USING(request_id) WHERE c.worker=? AND c.state='active' AND c.lane_scope='subject' AND a.status='claimed'").all(worker).map(row=>row.lane_key);
3323
4079
  const principals=[...new Set([...byPrincipal.map(sub=>sub.principal),...subjectKeys])];
@@ -3330,6 +4086,6 @@ export class Store {
3330
4086
  const sub=byPrincipal[0];
3331
4087
  const lanes=this.subscriptionFreeLanes(sub,limits.laneCapacity??6,capacity);
3332
4088
  const laneEvidence=this.db.prepare("SELECT DISTINCT c.lane_scope,c.lane_key FROM claims c JOIN assignments a USING(request_id) WHERE c.worker=? AND c.state='active' AND a.status='claimed' ORDER BY c.lane_scope,c.lane_key").all(worker).map(row=>({lane_scope:row.lane_scope,lane_key:row.lane_key}));
3333
- return {state:'known',scope,source:'subscription_policy',free_lanes:lanes,lane_capacity:Math.min(limits.laneCapacity??6,capacity),principal:scope==='principal'?sub.principal:undefined,lane_evidence:laneEvidence};
4089
+ return {...workerCap,state:'known',scope,source:'subscription_policy',free_lanes:lanes,lane_capacity:Math.min(limits.laneCapacity??6,capacity,max??Infinity),principal:scope==='principal'?sub.principal:undefined,lane_evidence:laneEvidence};
3334
4090
  }
3335
4091
  }