@tnunamak/dalan 0.8.0 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/CONTRIBUTING.md +2 -0
  3. package/PROTOCOL.md +6 -0
  4. package/README.md +8 -12
  5. package/bin/dalan.mjs +25 -4
  6. package/bin/dot-acp-agent.mjs +572 -76
  7. package/bin/dot-alert.mjs +9 -3
  8. package/bin/dot-deadman.mjs +3 -1
  9. package/bin/dot-heartbeat.mjs +14 -7
  10. package/bin/dot-pr-reviewer.mjs +3 -31
  11. package/bin/dot-worker.mjs +215 -40
  12. package/contracts/adapter-qualification.schema.json +94 -7
  13. package/docs/chatgpt-worker-onboarding.md +1 -1
  14. package/docs/codex-to-muse.md +2 -2
  15. package/docs/connect-chatgpt.md +1 -1
  16. package/docs/connection-longevity.md +2 -2
  17. package/docs/dalan-upgrade.md +8 -5
  18. package/docs/deadman.md +4 -0
  19. package/docs/design/authority-matrix.md +18 -0
  20. package/docs/design/failure-table.md +87 -0
  21. package/docs/design/identities.md +22 -0
  22. package/docs/design/pnpm-prepared-dependencies.md +64 -0
  23. package/docs/design/reuse-ledger.md +75 -0
  24. package/docs/design/target-architecture-v2.md +434 -0
  25. package/docs/local-agent-mcp.md +14 -0
  26. package/docs/local-agent-requester.md +3 -2
  27. package/docs/manual-setup.md +1 -1
  28. package/docs/operations.md +78 -14
  29. package/docs/pull-workers.md +11 -0
  30. package/docs/relationships.md +13 -0
  31. package/docs/service-setup.md +10 -10
  32. package/docs/t3-integration.md +6 -2
  33. package/docs/t3-reverse-control.md +5 -5
  34. package/docs/t3-wake-fence-r4.md +1 -1
  35. package/docs/test-suite-isolation.md +8 -6
  36. package/docs/trials/chatgpt-agent.md +47 -0
  37. package/docs/trials/claude-code-requester.md +68 -0
  38. package/docs/trials/muse.md +46 -0
  39. package/docs/usage.md +35 -9
  40. package/docs/worker-clients.md +1 -1
  41. package/integrations/t3/acp-kit/src/errors.mjs +6 -2
  42. package/integrations/t3/acp-kit/src/lock.mjs +46 -17
  43. package/integrations/t3/acp-kit/src/session-store.mjs +15 -3
  44. package/integrations/t3/acp-kit/src/t3-envelope.mjs +10 -2
  45. package/package.json +4 -3
  46. package/packages/job-core/protocol/canonical.mjs +45 -7
  47. package/packages/job-core/transitions.mjs +4 -2
  48. package/scripts/upgrade-drain.mjs +96 -8
  49. package/scripts/worker-bridge-setup.mjs +215 -120
  50. package/src/ack-ledger.mjs +7 -1
  51. package/src/acp-bridge.mjs +256 -28
  52. package/src/admin-socket.mjs +32 -3
  53. package/src/alerts.mjs +17 -8
  54. package/src/answer-journal-retention.mjs +82 -0
  55. package/src/answer-journal.mjs +6 -4
  56. package/src/as-store.mjs +51 -6
  57. package/src/as.mjs +27 -5
  58. package/src/catalog-switch-inventory.mjs +70 -0
  59. package/src/check-response.mjs +4 -1
  60. package/src/claim-command-ledger.mjs +3 -2
  61. package/src/cli-help.mjs +29 -10
  62. package/src/cli-name.mjs +13 -1
  63. package/src/connect-cli.mjs +159 -4
  64. package/src/deadman.mjs +8 -5
  65. package/src/delivery.mjs +2 -19
  66. package/src/destinations/index.mjs +75 -14
  67. package/src/drain-runner.mjs +5 -1
  68. package/src/follow-current.mjs +3 -1
  69. package/src/get-summary.mjs +11 -2
  70. package/src/git-env.mjs +1 -1
  71. package/src/gozar-routes.mjs +313 -94
  72. package/src/host-budget-storage.py +56 -6
  73. package/src/host-budget.mjs +98 -15
  74. package/src/host-execution-policy.mjs +17 -6
  75. package/src/inbox.mjs +13 -3
  76. package/src/legacy-names.mjs +0 -2
  77. package/src/lifecycle.mjs +104 -11
  78. package/src/loopback-probe.mjs +46 -0
  79. package/src/mcp-outcome.mjs +3 -1
  80. package/src/mcp-sse.mjs +2 -1
  81. package/src/mcp-stdio.mjs +192 -30
  82. package/src/patch-apply.mjs +285 -19
  83. package/src/phase-trace.mjs +73 -0
  84. package/src/prepared-go-modules.mjs +127 -0
  85. package/src/prepared-node-modules.mjs +225 -38
  86. package/src/prepared-pnpm.mjs +276 -0
  87. package/src/prepared-store-prune.mjs +52 -0
  88. package/src/projects.mjs +59 -7
  89. package/src/protocol-artifact-commands.mjs +28 -0
  90. package/src/protocol-finish.mjs +3 -2
  91. package/src/publication-authority.mjs +22 -0
  92. package/src/publish-plan.mjs +2 -2
  93. package/src/pull-queue.mjs +55 -20
  94. package/src/read-api.mjs +127 -0
  95. package/src/redaction.mjs +173 -0
  96. package/src/rejections.mjs +19 -3
  97. package/src/route-custody.mjs +90 -0
  98. package/src/route-publication.mjs +50 -0
  99. package/src/route-setup.mjs +184 -0
  100. package/src/schema-subset.mjs +5 -3
  101. package/src/server.mjs +619 -88
  102. package/src/service-launchd.mjs +5 -1
  103. package/src/service-update-lock.mjs +7 -4
  104. package/src/service-update-runtime.mjs +64 -19
  105. package/src/service-update.mjs +193 -48
  106. package/src/service.mjs +276 -77
  107. package/src/setup.mjs +48 -25
  108. package/src/signal.mjs +1 -1
  109. package/src/status-evidence.mjs +18 -5
  110. package/src/status-summary.mjs +3 -0
  111. package/src/store.mjs +1086 -127
  112. package/src/submission-policy.mjs +257 -56
  113. package/src/t3-control.mjs +1 -1
  114. package/src/t3.mjs +14 -8
  115. package/src/terminal-safe.mjs +9 -7
  116. package/src/tool-registry.mjs +134 -41
  117. package/src/try-exposure.mjs +53 -86
  118. package/src/try-hosted.mjs +257 -70
  119. package/src/try.mjs +48 -22
  120. package/src/work-order.mjs +11 -6
  121. package/src/worker-instructions.mjs +26 -4
  122. package/src/worker-runs.mjs +35 -0
  123. package/src/workers.mjs +49 -4
  124. package/src/workspace.mjs +354 -54
  125. package/systemd/dot-deadman.service +3 -1
  126. package/docs/dot-pr-reviewer.config.example.json +0 -9
  127. package/docs/pr-head-reviewer.md +0 -70
  128. package/src/pr-head-reviewer.mjs +0 -596
  129. package/systemd/dot-pr-reviewer.service +0 -11
  130. package/systemd/dot-pr-reviewer.timer +0 -10
package/src/store.mjs CHANGED
@@ -5,7 +5,7 @@ import { validateOwnerNote } from './submission-policy.mjs';
5
5
  import { redactOutput } from './redaction.mjs';
6
6
  import { statusEvidence } from './status-evidence.mjs';
7
7
  import { assertPreflight } from './pr-preflight.mjs';
8
- import { lifecycleSchema, backfillLifecycle, progressType } from './lifecycle.mjs';
8
+ import { lifecycleSchema, backfillLifecycle, progressType, addControlColumns, controlTypes } from './lifecycle.mjs';
9
9
  import { objectiveSources, metaFields, normalizeMeta, toStoredSource, fromStoredSource, canonicalMetaValue, canonicalKindSql, canonicalKindLabel, storedObjectiveKey, storedTaskKind, verifyObjective } from './objectives.mjs';
10
10
  import { legacyFixLoopName } from './legacy-names.mjs';
11
11
  import { LEGACY_PROFILE, canSee, resolveWorker, destinationDisclosure, destinationDifferences, destinationError, connectionsDigest } from './workers.mjs';
@@ -13,7 +13,7 @@ import { TRUST } from './execution.mjs';
13
13
  import { inferWorkerReport, observeTransition } from './failure-type.mjs';
14
14
  import { DatabaseSync } from 'node:sqlite';
15
15
  import { acquireSubscriptionStorage, SubscriptionCodec } from './subscription-storage.mjs';
16
- import { randomUUID, createHash, timingSafeEqual } from 'node:crypto';
16
+ import { randomUUID, randomBytes, createHash, timingSafeEqual } from 'node:crypto';
17
17
  import fs from 'node:fs';
18
18
  import {migrateClaimCommands,createClaimCommands} from './claim-command-ledger.mjs';
19
19
  import {migrateArtifactJournal} from './artifact-journal.mjs';
@@ -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 = 69;
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');
@@ -80,6 +103,7 @@ function unsupportedSchemaVersion(found) {
80
103
  }
81
104
 
82
105
  // Owner decisions on a finished result, in the words the CLI takes. 'stale' is only ever written by the sweep.
106
+ export const staleRevisionError=({request_id,revised_by,at,recorded})=>Object.assign(new Error(`stale_revision: ${request_id} was revised by ${revised_by}; its result is kept as evidence and cannot be accepted or applied. Decide ${revised_by} instead.`),{code:'STALE_REVISION',stale:{request_id,revised_by,at,recorded}});
83
107
  export const decisionTypes=['accepted','applied','useful_no_change','useful_negative','not_useful','stale'];
84
108
  export const MAX_INTEGRATION_PATCH_BYTES=262144;
85
109
  import os from 'node:os';
@@ -110,8 +134,41 @@ const storedMeta=(meta,legacy)=>({...meta,objective_key:storedObjectiveKey(meta.
110
134
  function submitIntentDigest(identity,delivery,environmentId,review,priority,meta,targetWorker,execution,requiredCapabilities,destinationRevision=null,legacyFixNames=true) {
111
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})})));
112
136
  }
113
- const defaultRedeliveryLimits={intervalMs:600000,maxCount:3,silenceMs:1200000,claimIdleWarningMs:900000,leaseMs:3600000,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};
114
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
+ }
115
172
  export const QUEUE_WINDOW=Object.freeze({minSamples:5,factor:3,minMs:15*60000,maxMs:12*HOUR});
116
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')");
117
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`:''})`;
@@ -121,7 +178,16 @@ const queuedAt="COALESCE((SELECT max(l.at) FROM lifecycle_events l WHERE l.reque
121
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.';
122
179
  // Priority orders list_pending and re-wake; it never hides or refuses work. Within a priority, an item the worker passed over
123
180
  // (skipped_at) goes behind the others, then oldest first.
124
- 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";
125
191
  // An item is marked skipped_by_worker when the worker passes it over, by either of two signals:
126
192
  // - passed over: the worker claimed an assignment listed after it, SKIP_AFTER_PASSED times, while it had listed this one within
127
193
  // PASSED_SEEN_MS. This detects items repeatedly pushed behind newer work before they enter the claimable window.
@@ -165,6 +231,36 @@ export function loadRedeliveryLimits(file=defaultPath(os.homedir(),'.config/dot-
165
231
  const leaseMs=leaseKey?value[leaseKey]:defaultRedeliveryLimits.leaseMs;
166
232
  if(!Number.isInteger(silenceMs)||silenceMs<60000||silenceMs>86400000) throw new Error('invalid pause_suspected_silence_ms');
167
233
  if(!Number.isInteger(leaseMs)||leaseMs<60000||leaseMs>604800000) throw new Error(`invalid ${leaseKey}`);
234
+ const workerClaimLeaseMs=value.worker_claim_lease_ms??{};
235
+ if(value.worker_claim_lease_ms===null||typeof workerClaimLeaseMs!=='object'||Array.isArray(workerClaimLeaseMs)||
236
+ Object.entries(workerClaimLeaseMs).some(([worker,ms])=>!/^[a-z][a-z0-9_-]{0,31}$/.test(worker)||!Number.isInteger(ms)||ms<60000||ms>604800000))
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');
168
264
  // Denominator of utilization metrics: how many lanes the worker can work in parallel. Independent of the claim cap (max_claimed_outer_assignments).
169
265
  // worker_* limits keys are the current names; the dot_* names are read as aliases so existing files keep working.
170
266
  const laneCapacity=value.worker_lane_capacity??value.dot_lane_capacity??defaultRedeliveryLimits.laneCapacity;
@@ -196,7 +292,7 @@ export function loadRedeliveryLimits(file=defaultPath(os.homedir(),'.config/dot-
196
292
  if(!Number.isInteger(maxResponseBytesPerHour)||maxResponseBytesPerHour<100000||maxResponseBytesPerHour>1000000000) throw new Error('invalid max_response_bytes_per_hour');
197
293
  const maxResponseBytesPer24h=value.max_response_bytes_per_24h??defaultRedeliveryLimits.maxResponseBytesPer24h;
198
294
  if(!Number.isInteger(maxResponseBytesPer24h)||maxResponseBytesPer24h<1000000||maxResponseBytesPer24h>10000000000) throw new Error('invalid max_response_bytes_per_24h');
199
- return {intervalMs,maxCount,silenceMs,claimIdleWarningMs,leaseMs,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};
200
296
  }
201
297
 
202
298
  // Gates that cap one rolling hour. They hold background work before agent-requested work (see rollingUsage).
@@ -300,13 +396,17 @@ export class Store {
300
396
  this.leaseBootId=options.bootId??(options.now?null:systemBootId());
301
397
  if(options.elapsedNow) {
302
398
  const epoch=wallNow(),elapsed=options.elapsedNow();
303
- this.nowMs=()=>Math.floor(epoch+options.elapsedNow()-elapsed);
399
+ this.nowMs=()=>Math.floor(epoch+(options.elapsedNow()-elapsed));
400
+ this.monotonicForWallDeadline=deadline=>elapsed+(deadline-epoch);
304
401
  } else if(options.now) this.nowMs=options.now;
305
402
  else {
306
403
  const epoch=Date.now(),elapsed=process.hrtime.bigint();
307
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;
308
407
  }
309
408
  this.capacity=options.capacity??6;
409
+ this.reserveIdleMinutesCache=new Map();
310
410
  this.backgroundMaxInFlight=options.backgroundMaxInFlight??4;
311
411
  this.limits=options.limits??{...defaultRedeliveryLimits};
312
412
  this.skipExpireMs=options.skipExpireMs??6*3600000;
@@ -328,6 +428,10 @@ export class Store {
328
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;
329
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);
330
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));
331
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);
332
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);
333
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);
@@ -336,6 +440,7 @@ export class Store {
336
440
  CREATE TABLE IF NOT EXISTS bridge_state (key TEXT PRIMARY KEY,value TEXT NOT NULL) WITHOUT ROWID;
337
441
  CREATE INDEX IF NOT EXISTS notifications_due ON notifications(state,next_at);`);
338
442
  this.migrate();
443
+ this.ensureReadIndexes();
339
444
  this.pullQueue=new PullQueue(this);
340
445
  this.initializeLeaseClock();
341
446
  this.initializeSubscriptionStorage();
@@ -350,10 +455,30 @@ export class Store {
350
455
  markProfileModeSeen() { this.db.prepare("INSERT INTO bridge_state(key,value) VALUES('workers_profile_seen','1') ON CONFLICT(key) DO NOTHING").run(); }
351
456
  // Record one lifecycle event; callers run it inside the transaction of the state change it describes.
352
457
  // claim defaults to the claim in force (the active row); an explicit claim_id without epoch resolves its epoch from history.
353
- lifecycle(id,type,actor='system',reason=null,claim=this.db.prepare("SELECT claim_id,epoch FROM claims WHERE request_id=? AND state='active'").get(id)) {
458
+ // Control events (controlTypes) also carry the scope they acted on and an outcome: extra={scope,outcome}.
459
+ lifecycle(id,type,actor='system',reason=null,claim=this.db.prepare("SELECT claim_id,epoch FROM claims WHERE request_id=? AND state='active'").get(id),extra={}) {
354
460
  const epoch=claim?.claim_id&&claim.epoch==null?this.db.prepare('SELECT epoch FROM claims WHERE claim_id=?').get(claim.claim_id)?.epoch??this.db.prepare('SELECT epoch FROM lifecycle_events WHERE claim_id=? AND epoch IS NOT NULL LIMIT 1').get(claim.claim_id)?.epoch??null:claim?.epoch??null;
355
461
  const worker=claim?.worker??(claim?.claim_id?this.db.prepare('SELECT worker FROM claims WHERE claim_id=?').get(claim.claim_id)?.worker??this.db.prepare('SELECT worker FROM lifecycle_events WHERE claim_id=? LIMIT 1').get(claim.claim_id)?.worker:null)??'unknown';
356
- this.db.prepare("INSERT INTO lifecycle_events(request_id,claim_id,epoch,type,at,actor,source,reason,worker) VALUES(?,?,?,?,?,?,'live',?,?)").run(id,claim?.claim_id??null,epoch,type,this.stamp(),actor,reason,worker);
462
+ this.db.prepare("INSERT INTO lifecycle_events(request_id,claim_id,epoch,type,at,actor,source,reason,worker,scope,outcome) VALUES(?,?,?,?,?,?,'live',?,?,?,?)").run(id,claim?.claim_id??null,epoch,type,this.stamp(),actor,reason,worker,extra.scope??null,extra.outcome??null);
463
+ }
464
+ // Record a control request (detach, interrupt_foreground, withdraw_work, revoke_grant) with the scope it named.
465
+ // The outcome is 'unknown' unless the caller holds an observation (confirmed). A denial is a request that did not take
466
+ // effect as asked, and says nothing about what already stopped, so it is unknown too: never success.
467
+ recordControl(id,type,{scope,confirmed=false,denied=null,actor='owner',reason=null}={}) {
468
+ if(!controlTypes.includes(type)) throw new Error(`not a control type: ${type}`);
469
+ if(typeof scope!=='string'||!scope.trim()) throw new Error('a control event needs a scope');
470
+ if(confirmed&&denied) throw new Error('a control request cannot be both denied and confirmed');
471
+ return this.inTransaction(()=>this.lifecycle(id,type,actor,[reason,denied].filter(Boolean).join('; ')||null,undefined,{scope:scope.trim(),outcome:confirmed?'confirmed':'unknown'}));
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);`);
357
482
  }
358
483
  migrate() {
359
484
  this.transaction(() => {
@@ -948,6 +1073,75 @@ export class Store {
948
1073
  if(!this.db.prepare("SELECT 1 FROM pragma_table_info('tool_grants') WHERE name='scope'").get()) this.db.exec('ALTER TABLE tool_grants ADD COLUMN scope TEXT');
949
1074
  this.db.exec('PRAGMA user_version=69;');
950
1075
  }
1076
+ if(version<70) {
1077
+ this.db.exec(`CREATE TABLE IF NOT EXISTS relationships (relationship_id TEXT PRIMARY KEY, my_roles TEXT NOT NULL, counterpart_ref TEXT NOT NULL, pattern TEXT NOT NULL CHECK(pattern IN ('outbound_only','service_native','controllable')), continuity TEXT NOT NULL CHECK(continuity IN ('retained_native','checkpoint_replay','reconstructed_explicit_context','new_work','inbox_only','unknown')), onward TEXT NOT NULL CHECK(onward IN ('none','attenuated')), inbound_grant_ref TEXT, created_at TEXT NOT NULL, ended_at TEXT);`);
1078
+ if(!this.db.prepare("SELECT 1 FROM pragma_table_info('assignments') WHERE name='relationship_id'").get()) this.db.exec('ALTER TABLE assignments ADD COLUMN relationship_id TEXT REFERENCES relationships(relationship_id)');
1079
+ this.db.exec('PRAGMA user_version=70;');
1080
+ }
1081
+ if(version<71) {
1082
+ // A correction links to the job it revises (C1). The link cancels nothing: the prior job runs to its own terminal state,
1083
+ // and its result is judged against this table when the owner decides. input_revision copies meta.revision of the
1084
+ // correction when it sent one. 71 follows C3 (69) and C2 (70) on main; renumbering at merge changes this
1085
+ // line, the user_version below and SUPPORTED_SCHEMA_VERSION.
1086
+ this.db.exec(`CREATE TABLE IF NOT EXISTS job_revisions(
1087
+ request_id TEXT PRIMARY KEY REFERENCES assignments(request_id),
1088
+ prior_id TEXT NOT NULL REFERENCES assignments(request_id),
1089
+ input_revision TEXT,
1090
+ at TEXT NOT NULL,
1091
+ CHECK(request_id<>prior_id));
1092
+ CREATE INDEX IF NOT EXISTS job_revisions_prior ON job_revisions(prior_id);
1093
+ -- A patch is applied in two phases so that no decision is recorded before the effect: 'applying' reserves it (the
1094
+ -- stale check is made here), the CLI writes the patch, then 'confirmed' records the decision or 'released' gives it up.
1095
+ -- A row left in 'applying' is an apply that may or may not have happened. attempt is the fencing token of the run that
1096
+ -- holds the reservation: every reserve mints a new one, and a confirm or release must present the current one.
1097
+ CREATE TABLE IF NOT EXISTS apply_reservations(
1098
+ request_id TEXT PRIMARY KEY REFERENCES assignments(request_id),
1099
+ state TEXT NOT NULL CHECK(state IN ('applying','confirmed','released')),
1100
+ reserved_at TEXT NOT NULL,
1101
+ resolved_at TEXT,
1102
+ reason TEXT,
1103
+ attempt TEXT);
1104
+ PRAGMA user_version=71;`);
1105
+ }
1106
+ if(version<72) {
1107
+ // Typed control events: wake_held and the control vocabulary join the lifecycle types, and each event may carry the
1108
+ // scope it acted on and an outcome. See addControlColumns for the table rebuild.
1109
+ addControlColumns(this.db);
1110
+ this.db.exec('PRAGMA user_version=72;');
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
+ }
951
1145
  // Which spelling of the fix-loop source this database stores. Schemas created before the rename list the earlier
952
1146
  // spelling in the CHECK constraint on assignments.source; newer schemas list only the neutral one.
953
1147
  this.legacyFixNames=!!this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='assignments' AND instr(sql,?)>0").get(`'${legacyFixLoopName}'`);
@@ -1072,8 +1266,8 @@ export class Store {
1072
1266
  insertConfinedCheckAssignment(requestId,payload) {
1073
1267
  const body=JSON.stringify(payload);
1074
1268
  // "unknown" is a reserved name that no configured worker can have, so only the integrator ever touches this row.
1075
- this.db.prepare('INSERT INTO assignments(request_id,payload,payload_hash,thread_id,environment_id,status,created_at,target_worker) VALUES(?,?,?,?,?,?,?,?)')
1076
- .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'));
1077
1271
  return this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(requestId);
1078
1272
  }
1079
1273
  // Queue waits are scoped to the selected worker and task kind, one sample per job. The first persisted claim is the
@@ -1106,6 +1300,141 @@ export class Store {
1106
1300
  observed.sort((a,b)=>a-b);
1107
1301
  return {waits_ms:observed,expired_lower_bounds:expiredLowerBounds,samples:observed.length,window_days:days,worker,kind};
1108
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
+ }
1109
1438
  queueWaitsMs(worker,kind,days=7) { return this.queueWaitEvidence(worker,kind,days).waits_ms; }
1110
1439
  defaultValidUntil(worker,kind,days=7) {
1111
1440
  const evidence=this.queueWaitEvidence(worker,kind,days), waits=evidence.waits_ms;
@@ -1214,13 +1543,11 @@ export class Store {
1214
1543
  if(result?.destination_refusal)throw destinationError(result.destination_refusal);
1215
1544
  return result;
1216
1545
  }
1217
- 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) {
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) {
1218
1547
  validateSubmitKey(commandKey);
1219
1548
  const m=normalizeMeta(meta);
1220
- const delivery=typeof deliveryOrThreadId==='string'?{mode:'t3',threadId:deliveryOrThreadId}:deliveryOrThreadId;
1221
- if(!delivery||!['t3','none'].includes(delivery.mode)||delivery.mode==='t3'&&!delivery.threadId) throw new Error('invalid delivery');
1549
+ const {deliveryValue}=deliveryColumns(deliveryOrThreadId);
1222
1550
  if(!['normal','background'].includes(priority)) throw new Error('invalid priority');
1223
- const deliveryValue=delivery.mode==='t3'?`t3:${delivery.threadId}`:'none';
1224
1551
  const old=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(payload.request_id);
1225
1552
  if(supersedes!==null&&(!supersedes||typeof supersedes!=='object'||Array.isArray(supersedes)||
1226
1553
  Object.keys(supersedes).some(k=>!['target_id','target_token'].includes(k))||
@@ -1228,8 +1555,37 @@ export class Store {
1228
1555
  const targetId=supersedes?.target_id??null;
1229
1556
  const previous=this.db.prepare('SELECT target_id FROM submit_supersedes WHERE request_id=?').get(payload.request_id);
1230
1557
  if(targetId===payload.request_id) throw new Error('supersede_cycle');
1558
+ // A correction proves the prior owner's capability. Withdrawal is a separate, keyed opt-in.
1559
+ if(revises!==null) {
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');
1564
+ if(supersedes) throw new Error('revises_and_supersedes: a correction does not cancel its prior job; send one of them');
1565
+ if(revises.prior_id===payload.request_id) throw new Error('revises_cycle');
1566
+ const prior=this.db.prepare('SELECT revision,status FROM assignments WHERE request_id=?').get(revises.prior_id);
1567
+ if(!prior) throw new Error('revises_prior_not_found');
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');
1571
+ // The same revision under another request_id is a duplicate in the metrics, not a correction.
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');
1573
+ }
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);
1586
+ const previousRevision=this.db.prepare('SELECT prior_id FROM job_revisions WHERE request_id=?').get(payload.request_id);
1231
1587
  // Both capabilities are required even when returning an already-committed receipt.
1232
- if(old&&(supersedes||previous)) this.owner(payload.request_id,ownerToken);
1588
+ if(old&&(supersedes||previous||revises||previousRevision||follows||previousFollow)) this.owner(payload.request_id,ownerToken);
1233
1589
  let target;
1234
1590
  if(supersedes) {
1235
1591
  target=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(targetId);
@@ -1255,36 +1611,53 @@ export class Store {
1255
1611
  // Authenticate before revealing or comparing the approval binding.
1256
1612
  if(approval)this.owner(payload.request_id,ownerToken);
1257
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');
1258
1615
  const command=this.db.prepare('SELECT * FROM owner_submit_commands WHERE request_id=?').get(payload.request_id);
1259
1616
  // Authenticate before revealing key existence or replaying its receipt.
1260
1617
  if(commandKey!==null||command) this.owner(payload.request_id,ownerToken);
1261
1618
  if(commandKey!==null) {
1262
1619
  if(!command||command.key_digest!==hash(commandKey)) throw new Error('EXISTS: assignment already submitted under another command');
1263
1620
  const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??old.target_worker,execution??old.execution,requiredCapabilities,destinationRevision,this.legacyFixNames);
1264
- if((previous?.target_id??null)!==targetId||command.owner_hash!==ownerHash||command.intent_digest!==intent) throw new Error('KEY_CONFLICT: command intent changed');
1265
- 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}:{})};
1266
1624
  }
1267
1625
  if(command) throw new Error('EXISTS: command_key required to retry this assignment');
1268
- if ((previous?.target_id??null)!==targetId || (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');
1269
1627
  return {request_id:payload.request_id,status:old.status,duplicate:true,...(approval?{destination_approval:approval}:{})};
1270
1628
  }
1271
1629
  // identity: the assignment as the submitter sent it, when the stored payload differs (scope narrowing); a retry then still matches.
1630
+ relationshipForSubmission(worker,relationshipId=null) {
1631
+ const relationship=this.db.prepare('SELECT * FROM relationships WHERE counterpart_ref=? ORDER BY created_at DESC, rowid DESC LIMIT 1').get(worker??'dot');
1632
+ if(relationshipId!==null&&relationshipId!==relationship?.relationship_id) throw new Error('relationship_mismatch');
1633
+ if(relationship?.ended_at) throw new Error('relationship_ended');
1634
+ return relationship;
1635
+ }
1272
1636
  submit(...args) { return this.transaction(()=>this.submitInTransaction(...args)); }
1273
- 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) {
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) {
1274
1638
  if(!this.db.isTransaction) throw new Error('transaction_required');
1639
+ if(callerWaiting!==undefined&&typeof callerWaiting!=='boolean') throw new Error('invalid caller_waiting');
1275
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');
1276
1641
  const protocol=!this.hasAssignment(payload.request_id)&&Object.hasOwn(payload,'protocol')?validateProtocol(payload.protocol):null;
1277
1642
  if(protocol)identity={...identity,protocol};
1278
1643
  if(targetWorker==='pool') throw new Error('worker \"pool\" is not supported');
1279
- const delivery=typeof deliveryOrThreadId==='string'?{mode:'t3',threadId:deliveryOrThreadId}:deliveryOrThreadId;
1280
- if(!delivery||!['t3','none'].includes(delivery.mode)||delivery.mode==='t3'&&!delivery.threadId) throw new Error('invalid delivery');
1281
- 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);
1282
1646
  if(!['normal','background'].includes(priority)) throw new Error('invalid priority');
1283
- const retry=this.checkRetry(payload,delivery,environmentId,ownerToken,review,priority,meta,identity,targetWorker,execution,requiredCapabilities,commandKey,supersedes,destinationRevision);
1647
+ const retry=this.checkRetry(payload,deliveryOrThreadId,environmentId,ownerToken,review,priority,meta,identity,targetWorker,execution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises,follows,callerWaiting);
1284
1648
  if(retry) return retry;
1649
+ let relationship;
1650
+ if(inheritedOwnerHash) {
1651
+ const order=this.pullQueue.row(payload.request_id);
1652
+ if(!order||order.owner_hash!==inheritedOwnerHash) throw new Error('invalid policy work owner');
1653
+ const relationships=JSON.parse(order.options).relationships;
1654
+ if(relationships&&!Object.hasOwn(relationships,targetWorker)) throw new Error('invalid policy relationship binding');
1655
+ const bound=relationships?.[targetWorker]??null;
1656
+ relationship=bound?{relationship_id:bound}:null;
1657
+ } else relationship=this.relationshipForSubmission(targetWorker,relationshipId);
1285
1658
  const id=payload.request_id, body=JSON.stringify(payload),payloadHash=hash(JSON.stringify(canonical(identity))),ownerHash=inheritedOwnerHash??hash(ownerToken);
1286
1659
  // checkRetry validated this target in the same transaction; only counts containing it gain room.
1287
- const supersededId=supersedes?.target_id??null;
1660
+ const supersededId=supersedes?.target_id??(revises?.withdraw_prior?revises.prior_id:null);
1288
1661
  if(destinationRevision!==null&&(typeof destinationRevision!=='string'||!/^sha256:[a-f0-9]{64}$/.test(destinationRevision)))throw new Error('invalid destination_revision');
1289
1662
  const disclosure=this.destinationSnapshot(targetWorker??'dot',execution??defaultExecution,payload,{required:destinationRevision!==null});
1290
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.'});
@@ -1317,13 +1690,16 @@ export class Store {
1317
1690
  }
1318
1691
  if(maxQueued!==null) {
1319
1692
  if(!Number.isSafeInteger(maxQueued)||maxQueued<1) throw new Error('invalid max_queued');
1320
- 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;
1321
1696
  if(queued>=maxQueued) throw new Error(`worker queue is full (${queued} queued, in-flight cap ${maxQueued})`);
1322
1697
  }
1323
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');
1324
1699
  // The target is a column, not payload: an omitted worker means 'dot'.
1325
- 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);
1326
1701
  if(typeof parentGeneration==='string')this.db.prepare('UPDATE assignments SET parent_generation=? WHERE request_id=?').run(parentGeneration,id);
1702
+ if(relationship) this.db.prepare('UPDATE assignments SET relationship_id=? WHERE request_id=?').run(relationship.relationship_id,id);
1327
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());
1328
1704
  const requestedValidUntil=validUntilOf(payload);
1329
1705
  const mayUseDefault=priority==='normal'&&!this.paused()&&!((targetWorker??'dot')==='dot'&&this.holdingBreak());
@@ -1342,8 +1718,19 @@ export class Store {
1342
1718
  this.db.prepare('INSERT INTO submit_supersedes(request_id,target_id,created_at) VALUES(?,?,?)').run(id,supersedes.target_id,this.stamp());
1343
1719
  this.cancelInTransaction(supersedes.target_id,'superseded');
1344
1720
  }
1721
+ if(revises) {
1722
+ // The link and withdrawal or legacy note commit with the correction. Exact retries already returned.
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());
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
+ }
1730
+ }
1731
+ if(follows) this.db.prepare('INSERT INTO job_follows(request_id,prior_id,at) VALUES(?,?,?)').run(id,follows.prior_id,this.stamp());
1345
1732
  for (const sub of this.activeSubscriptions()) this.submitWake(id,sub);
1346
- 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)};
1347
1734
  if(commandKey!==null) {
1348
1735
  const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??'dot',execution??defaultExecution,requiredCapabilities,destinationRevision,this.legacyFixNames);
1349
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);
@@ -1423,21 +1810,33 @@ export class Store {
1423
1810
  if(!ctx||typeof ctx.key!=='string'||!ctx.key||!protocolNat(ctx.revision)||typeof mutate!=='function')protocolError('command_context_required');
1424
1811
  if(ctx.epoch!==undefined&&ctx.epoch!==claim.epoch)protocolError('stale_authority');
1425
1812
  return this.protocolCommands().execute({job:id,subject,worker,claim:claimId,epoch:claim.epoch,
1426
- key:ctx.key,expectedRevision:ctx.revision,operation:ctx.operation,args:ctx.args},mutate);
1813
+ key:ctx.key,expectedRevision:ctx.revision,operation:ctx.operation,args:ctx.args},mutate,
1814
+ {leaseCapMs:this.workerClaimLeaseCap(worker)});
1427
1815
  }
1428
1816
  setClaimDeadlineInTransaction(id,leaseMs) {
1429
1817
  const activity=this.db.prepare('SELECT last_claim_activity_at FROM claims WHERE request_id=?').get(id)?.last_claim_activity_at;
1430
1818
  const deadline=Date.parse(activity??this.stamp())+leaseMs;
1431
1819
  if(!protocolNat(deadline))protocolError('invalid_lease');
1432
1820
  this.db.prepare('UPDATE claims SET lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=?')
1433
- .run(iso(deadline),this.leaseBootId,this.leaseBootId?this.monotonicNow()+leaseMs:null,id);
1821
+ .run(iso(deadline),this.leaseBootId,this.monotonicDeadlineFor(deadline),id);
1822
+ }
1823
+ workerClaimLeaseCap(worker) {
1824
+ const caps=this.limits.workerClaimLeaseMs;
1825
+ return caps&&Object.hasOwn(caps,worker)?caps[worker]:Infinity;
1826
+ }
1827
+ cappedClaimLeaseMs(leaseMs,worker) {
1828
+ if(!Number.isInteger(leaseMs)||leaseMs<1||leaseMs>this.limits.leaseMs) throw new Error(`invalid lease_ms: must be an integer from 1 to ${this.limits.leaseMs}`);
1829
+ return Math.min(leaseMs,this.workerClaimLeaseCap(worker));
1434
1830
  }
1435
1831
  renewClaim(id,claimId,leaseMs,ctx,subject='local-principal',worker='dot',connectionId=null) {
1832
+ if(!Number.isInteger(leaseMs)||leaseMs<1||leaseMs>this.limits.leaseMs)protocolError('invalid_lease');
1833
+ const requestedLeaseMs=leaseMs;
1834
+ leaseMs=Math.min(leaseMs,this.workerClaimLeaseCap(worker));
1436
1835
  return this.transaction(()=>{
1437
1836
  const receipt=this.protocolMutationInTransaction(id,claimId,subject,worker,
1438
- {...ctx,operation:'renew',args:{leaseMs}},({leaseUntil})=>{
1837
+ {...ctx,operation:'renew',args:{leaseMs:requestedLeaseMs}},({leaseUntil})=>{
1439
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=?')
1440
- .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);
1441
1840
  const claim=this.assertClaim(id,claimId,subject,worker);
1442
1841
  this.protocolEventInTransaction(id,'renewed',{lease_ms:leaseMs,lease_deadline_at:iso(leaseUntil)},claim.epoch);
1443
1842
  return {request_id:id,claim_id:claimId,epoch:claim.epoch,lease_expires_at:iso(leaseUntil)};
@@ -1512,11 +1911,11 @@ export class Store {
1512
1911
  }
1513
1912
  retireUnusableSubscription(sub,reason='subscription inactive') {
1514
1913
  if(!sub) return [];
1515
- try {
1516
- const connection=this.subscriptionConnection(sub);
1517
- if(connection?.builtin&&this.connectionIsLive&&!this.connectionIsLive(connection.connection_id))
1518
- return this.retireConnectionSubscriptions(connection.connection_id,reason);
1519
- } 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);
1520
1919
  return this.retireSubscription(sub.id,reason);
1521
1920
  }
1522
1921
  retireUnknownSubscriptions() {
@@ -1556,9 +1955,9 @@ export class Store {
1556
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);
1557
1956
  return eventId;
1558
1957
  }
1559
- // 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).
1560
1959
  queuedRows() {
1561
- 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();
1562
1961
  }
1563
1962
  // Break intervals [since, until or open] in ms. Owner since never reaches back before the previous break's end, so they are disjoint.
1564
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]); }
@@ -1595,9 +1994,10 @@ export class Store {
1595
1994
  const hasLiveClaim=liveClaims.some(c=>now-Date.parse(c.last_claim_activity_at??c.claimed_at)<this.claimLeaseMs(c));
1596
1995
  const atCapacity=liveSubs.length>0&&liveSubs.every(sub=>this.subscriptionFreeLanes(sub,limits.laneCapacity??6,capacity)===0);
1597
1996
  const hasSubscription=liveSubs.length>0;
1598
- 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=>{
1599
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.
1600
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};
1601
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;
1602
2002
  const eventAge=first?age(first):null;
1603
2003
  let cls=null;
@@ -1722,9 +2122,19 @@ export class Store {
1722
2122
  activeBreak() { return this.db.prepare('SELECT * FROM worker_breaks WHERE until IS NULL').get()??null; }
1723
2123
  // The break that holds work: only an owner-confirmed one. An inferred break (silence) is reported and alerted, not held on.
1724
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
+ }
1725
2132
  breakState() {
1726
2133
  const b=this.activeBreak();
1727
- 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:{})};
1728
2138
  }
1729
2139
  breaks() {
1730
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,
@@ -1753,18 +2163,24 @@ export class Store {
1753
2163
  ...(learned[name]&&effective[name]<configured[name]?{learned:learned[name].value,break_id:learned[name].break_id}:{})}));
1754
2164
  }
1755
2165
  // Owner mark. Over an active break (e.g. an inferred one) it takes over: source owner, new reason, since if given, fresh snapshot.
1756
- setBreak(reason,since=null) { return this.transaction(() => {
2166
+ setBreak(reason,since=null,until=undefined) { return this.transaction(() => {
1757
2167
  if(typeof reason!=='string'||!reason.trim()||reason.length>512) throw new Error('invalid reason');
1758
- const active=this.activeBreak(), at=since??active?.since??this.stamp();
1759
- 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');
1760
2172
  const ended=this.db.prepare('SELECT max(until) u FROM worker_breaks WHERE until IS NOT NULL').get().u;
1761
2173
  if(ended&&Date.parse(at)<Date.parse(ended)) throw new Error(`since must not be before the end of the previous break (${ended})`);
1762
- if(!active) return this.startBreak({since:at,reason,source:'owner'});
1763
- const usage=this.usageBefore(Date.parse(at));
1764
- this.db.prepare("UPDATE worker_breaks SET reason=?,source='owner',since=?,usage=? WHERE id=?").run(reason,at,JSON.stringify(usage),active.id);
1765
- // Confirming an inferred break without --since keeps its since (the worker's last call), so its last hour is still quiet:
1766
- // learn the 24 h budgets and the claims peak, not the hourly limits.
1767
- 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)));
1768
2184
  return this.breakState();
1769
2185
  }); }
1770
2186
  clearBreak() { return this.transaction(() => {
@@ -1777,6 +2193,7 @@ export class Store {
1777
2193
  // Call inside a transaction.
1778
2194
  endBreak(active,endSource) {
1779
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}`);
1780
2197
  }
1781
2198
  // Inferred start: no worker tool call (any subject) for breakSilenceMs, an availability event got a 2xx after the last call,
1782
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
@@ -1820,10 +2237,23 @@ export class Store {
1820
2237
  this.refreshClaimActivity(id,claimId);
1821
2238
  }
1822
2239
  refreshClaimActivity(id,claimId) {
1823
- const at=this.stamp(), claim=this.db.prepare('SELECT lease_ms FROM claims WHERE request_id=? AND claim_id=?').get(id,claimId);
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;
1824
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);
1825
- else this.db.prepare('UPDATE claims SET last_claim_activity_at=?,lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=? AND claim_id=?')
1826
- .run(at,iso(Date.parse(at)+(claim?.lease_ms??this.limits.leaseMs)),this.leaseBootId,this.leaseBootId?this.monotonicNow()+(claim?.lease_ms??this.limits.leaseMs):null,id,claimId);
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=?')
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;
1827
2257
  }
1828
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.
1829
2259
  liveHeldClaim(id,claimId,subject,worker) {
@@ -1846,6 +2276,8 @@ export class Store {
1846
2276
  try { this.assertMutationConnection(id,claim,connectionId); }
1847
2277
  catch(error) { if(error.destination?.error==='connection_not_live')return false; throw error; }
1848
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);
1849
2281
  return true;
1850
2282
  }); }
1851
2283
  // Unfenced: for callers that already proved the holder inside their own claim transaction (exact retry, resume). `get` uses markNotesSeenByHolder.
@@ -1864,21 +2296,35 @@ export class Store {
1864
2296
  const a=Store.toolActivity(c), t=x=>x.slice(11,19)+'Z';
1865
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)}`:''}`;
1866
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; }
1867
2302
  failureFields(id) {
1868
- 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);
1869
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'};}
1870
- const report=this.db.prepare('SELECT outcome,summary,result FROM reports WHERE request_id=?').get(id);
1871
- const failedReport=!!report&&report.outcome!=='completed';
1872
- 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;
1873
2313
  if(a.status!=='cancelled'&&!failedReport) return {failure_type:null,failure_type_source:null,check_failed_observed:checkFailedObserved};
1874
- 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;
1875
- const observed=observeTransition({status:a.status,reason:a.cancelled_reason,cancelActor,
1876
- 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)});
1877
- 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);
1878
2316
  const result=observed??inferred;
1879
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};
1880
2318
  }
1881
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
+ }
1882
2328
  leaseMonotonicDeadline(claim) {
1883
2329
  const deadline=Number(claim.lease_deadline_monotonic_ms);
1884
2330
  return this.leaseBootId&&claim.lease_boot_id===this.leaseBootId&&Number.isFinite(deadline)?deadline:null;
@@ -1888,10 +2334,13 @@ export class Store {
1888
2334
  return deadline===null?Date.parse(this.leaseExpiresAt(claim)):Math.floor(this.nowMs()+deadline-this.monotonicNow());
1889
2335
  }
1890
2336
  leaseExpiresAt(claim) { return claim.lease_deadline_at??new Date(Date.parse(claim.last_claim_activity_at??claim.claimed_at)+this.claimLeaseMs(claim)).toISOString(); }
1891
- // 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.
1892
2339
  heldAfterStart(claim) {
1893
2340
  const activity=Date.parse(claim.activity??claim.last_claim_activity_at??claim.claimed_at);
1894
- 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;
1895
2344
  }
1896
2345
  leaseExpired(claim) {
1897
2346
  // Missing or malformed persisted deadlines carry no authority, even with a same-boot clock.
@@ -2081,8 +2530,39 @@ export class Store {
2081
2530
  const watch=this.db.prepare('SELECT deadline,state,updated_at,notification_id FROM watches WHERE request_id=?').get(id) || null;
2082
2531
  const supersedes=this.db.prepare('SELECT target_id AS request_id,created_at FROM submit_supersedes WHERE request_id=?').get(id)??null;
2083
2532
  const superseded_by=this.db.prepare('SELECT request_id,created_at FROM submit_supersedes WHERE target_id=?').get(id)??null;
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);
2084
2535
  const authorityRevoked=!!a.cancelled_at||this.isProtocolJob(id)&&a.status==='finished';
2085
- 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,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);
2086
2566
  }
2087
2567
  recordPrPreflight(id,phase,assignment,evidence,replace=false) {
2088
2568
  assertPreflight(assignment,evidence,this.nowMs());
@@ -2110,9 +2590,9 @@ export class Store {
2110
2590
  }
2111
2591
  }
2112
2592
  answerQuestion(id,questionId,text,ctx=null,ownerToken=null) {
2113
- 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));
2114
2594
  }
2115
- answerQuestionInTransaction(id,questionId,text) {
2595
+ answerQuestionInTransaction(id,questionId,text,allowExactReplay=false) {
2116
2596
  if(!this.db.isTransaction)protocolError('transaction_required');
2117
2597
  validateQuestion(questionId,text);
2118
2598
  const assignment=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
@@ -2121,7 +2601,12 @@ export class Store {
2121
2601
  const question=this.db.prepare('SELECT * FROM job_questions WHERE request_id=? AND question_id=?').get(id,questionId);
2122
2602
  if(!question) throw questionError('NO_QUESTION','question does not exist');
2123
2603
  const claim=this.assertQuestionGrant(id,question);
2124
- 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
+ }
2125
2610
  this.db.prepare('UPDATE job_questions SET answer=?,answered_at=? WHERE request_id=? AND question_id=?').run(text,this.stamp(),id,questionId);
2126
2611
  this.lifecycle(id,'waiting','owner',`question:answer:${questionId}`,claim);
2127
2612
  this.db.prepare(`UPDATE notifications SET state='suppressed',last_error='structured question answered'
@@ -2167,7 +2652,7 @@ export class Store {
2167
2652
  return {question_id:questionId,answer:question.answer,duplicate};
2168
2653
  }
2169
2654
  assertQuestionsResolved(id,claimId,outcome='completed') {
2170
- if(['blocked','failed'].includes(outcome)) return true;
2655
+ if(['blocked','failed',PROVIDER_REFUSAL].includes(outcome)) return true;
2171
2656
  const assignment=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
2172
2657
  if(assignment?.status==='cancelled') return true; // Preserve late evidence after cancellation.
2173
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');
@@ -2183,7 +2668,8 @@ export class Store {
2183
2668
  if(!question||question.answered_at===null||question.consumed_at!==null||question.epoch!==wake.epoch) return false;
2184
2669
  try { this.assertQuestionGrant(row.request_id,question);return true; } catch { return false; }
2185
2670
  }
2186
- note(id,text) { return this.transaction(() => {
2671
+ note(id,text) { return this.transaction(() => this.noteInTransaction(id,text)); }
2672
+ noteInTransaction(id,text) {
2187
2673
  this.assertProtocolAvailable(id);
2188
2674
  validateOwnerNote(text,this.ownerNotes(id));
2189
2675
  const assignment=this.db.prepare('SELECT payload FROM assignments WHERE request_id=?').get(id);
@@ -2196,7 +2682,15 @@ export class Store {
2196
2682
  this.db.prepare("INSERT INTO notifications(id,kind,request_id,subscription_id,body,created_at,wake_kind) VALUES(?,?,?,?,?,?,'owner_note')").run(eventId,'event',id,sub.id,body,this.stamp());
2197
2683
  }
2198
2684
  return {request_id:id,...note};
2199
- }); }
2685
+ }
2686
+ // Tell a worker that may still be running the prior job. A job that already ended has no worker to tell, and its rows stay
2687
+ // as they were. An exhausted note budget skips only the note: the link alone makes the result stale.
2688
+ announceRevisionInTransaction(priorId,successorId,inputRevision) {
2689
+ if(!['queued','claimed'].includes(this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(priorId).status)) return;
2690
+ const text=`This job was revised by ${successorId}, a corrected revision of the same work${inputRevision?` (input revision ${inputRevision})`:''}. Stop work on it and finish with a short report of where you stopped. The report is kept as evidence and cannot be accepted or applied.`;
2691
+ try { validateOwnerNote(text,this.ownerNotes(priorId)); } catch { return; }
2692
+ this.noteInTransaction(priorId,text);
2693
+ }
2200
2694
  tell(text,worker='dot') { return this.transaction(() => {
2201
2695
  if(worker==='pool') throw new Error('worker \"pool\" is not supported');
2202
2696
  const messageId=`msg_${randomUUID()}`, preview=text.slice(0,200), createdAt=this.stamp();
@@ -2252,10 +2746,49 @@ export class Store {
2252
2746
  // This worker's expired claims, eligible only after verified host cessation.
2253
2747
  idleClaims(worker) {
2254
2748
  if(this.resumeIdleMs()<=0) return [];
2255
- 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));
2256
- }
2257
- guidanceFor(worker) { return this.workers.workers.get(worker)?.guidance==='resume'?`${workerGuidance} ${resumeNudge(this.resumeIdleMs()||defaultResumeIdleMs)}`:workerGuidance; }
2258
- // 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.
2259
2792
  // One bit for the public wake signal: a queued, live, uncancelled assignment targets one of these workers.
2260
2793
  hasQueuedFor(workerNames) {
2261
2794
  if(!workerNames.length) return false;
@@ -2263,7 +2796,63 @@ export class Store {
2263
2796
  }
2264
2797
  // Wake bit: queued work, or an expired own claim ready for regrant.
2265
2798
  hasWakeFor(worker) { return this.hasQueuedFor([worker])||this.idleClaims(worker).length>0; }
2266
- 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}={}) {
2267
2856
  // Recheck historical refusals against one lazily loaded configuration per listing.
2268
2857
  // Listing is read-only: it neither deletes audit evidence nor grants approval.
2269
2858
  let loaded=false,failed=false,profile,loadError;
@@ -2289,7 +2878,9 @@ export class Store {
2289
2878
  return !(!approval&&!current||approval&&current?.revision===approval.revision&&current.policy.allowed);
2290
2879
  } catch { return true; }
2291
2880
  };
2292
- 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;
2293
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));
2294
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,
2295
2886
  ...(this.db.prepare('SELECT 1 FROM destination_blocks WHERE request_id=?').get(c.request_id)&&blocked(c.request_id)?{blocked:true}:{}),
@@ -2298,23 +2889,36 @@ export class Store {
2298
2889
  }
2299
2890
  // Called for each list_pending answer to the worker: the first freeLanes assignments are the ones it could claim now. One that
2300
2891
  // is still there SKIP_AFTER_ELIGIBLE_MS after it first was, with no claim, is marked skipped_by_worker (and goes behind its
2301
- // peers in LIST_ORDER). Every listed assignment is stamped as seen, which claim() uses to tell a pass-over from news.
2302
- 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(() => {
2303
2894
  const now=this.nowMs(), at=iso(now), cutoff=iso(now-LISTED_POLL_GAP_MS), due=iso(now-SKIP_AFTER_ELIGIBLE_MS);
2304
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; }
2305
2897
  const seen=this.db.prepare("UPDATE assignments SET last_seen_listed_at=? WHERE request_id=? AND status='queued'");
2306
2898
  for(const item of assignments) seen.run(at,item.request_id);
2307
- 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; }
2308
- 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'");
2309
- 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));
2310
2914
  }); }
2311
- // 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.
2312
2916
  recordPassedOver(claimedId,worker='dot') {
2313
2917
  const now=this.nowMs(), at=iso(now), seenAfter=iso(now-PASSED_SEEN_MS);
2314
2918
  const order=this.listPending(worker).filter(x=>x.kind==='assignment'&&!x.blocked).map(x=>x.request_id);
2315
2919
  const ahead=order.slice(0,Math.max(0,order.indexOf(claimedId)));
2316
- 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");
2317
- 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);
2318
2922
  }
2319
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(); }
2320
2924
  // Built-in mode only: a fresh epoch is admitted only while the claimant's own
@@ -2382,15 +2986,23 @@ export class Store {
2382
2986
  } catch(error) { throw this.destinationConfigurationError(id,error); }
2383
2987
  if(digest!==approval.snapshot.connections_digest)throw refuse('Claim retry refused: the approved connection set changed.');
2384
2988
  }
2385
- 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) {
2386
2990
  const requestedLeaseMs=arguments[7]??null;
2387
- return nonterminalOutcome(id,this.destinationOutcome(this.transaction(()=>this.isProtocolJob(id)
2388
- ?this.protocolClaimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,ctx?{...ctx,requestedLeaseMs}:ctx,connectionId)
2389
- :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)});
2390
3002
  }
2391
3003
  claimInTransaction(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,connectionId=null) {
2392
3004
  if(!this.db.isTransaction)protocolError('transaction_required');
2393
- if(!Number.isInteger(leaseMs)||leaseMs<1||leaseMs>this.limits.leaseMs) throw new Error(`invalid lease_ms: must be an integer from 1 to ${this.limits.leaseMs}`);
3005
+ leaseMs=this.cappedClaimLeaseMs(leaseMs,worker);
2394
3006
  if(acquisitionId!==null&&(typeof acquisitionId!=='string'||!/^[A-Za-z0-9_-]{1,128}$/.test(acquisitionId))) throw new Error('invalid acquisition_id: use 1-128 letters, digits, underscores or hyphens');
2395
3007
  if(!this.mayAct(worker,id)) throw new Error('assignment not found');
2396
3008
  if (this.paused()) throw new Error(pausedClaimMessage);
@@ -2409,7 +3021,10 @@ export class Store {
2409
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)};
2410
3022
  }
2411
3023
  if(old && (old.state!=='active' || this.leaseExpired(old))) this.assertRegrantReady(old);
2412
- 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
+ }
2413
3028
  if(takeover) {
2414
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}));
2415
3030
  if(!this.leaseExpired(old)) throw new Error('already claimed by another claimant');
@@ -2418,7 +3033,10 @@ export class Store {
2418
3033
  if(destinationRefusal)return destinationRefusal;
2419
3034
  // Every new epoch of an existing claim (takeover, claim after abandon) waits for reconcile.
2420
3035
  if(old) this.assertNoUncertainDelivery(id);
2421
- 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);
2422
3040
  this.recordPrPreflight(id,'claim',JSON.parse(a.payload),preflight,!!old);
2423
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(); }
2424
3042
  const claimId=`claim_${randomUUID()}`;
@@ -2428,8 +3046,12 @@ export class Store {
2428
3046
  this.rebindClaim(id,claimId);
2429
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);
2430
3048
  this.setClaimDeadlineInTransaction(id,leaseMs);
2431
- 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
+ }
2432
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);
2433
3055
  this.lifecycle(id,'claimed',`worker:${subject}`,takeover?'takeover':old?'reclaim':'new',{claim_id:claimId,epoch:old?old.epoch+1:1,worker});
2434
3056
  this.db.prepare('DELETE FROM claim_denials WHERE request_id=?').run(id);
2435
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)};
@@ -2442,17 +3064,25 @@ export class Store {
2442
3064
  this.assertRegrantReady(old);
2443
3065
  this.assertLiveConnection(old.request_id,worker,connectionId);
2444
3066
  const id=old.request_id, idleS=Math.floor(this.claimIdleMs(old)/1000);
3067
+ this.assertWorkerClaimSlot(worker,id);
2445
3068
  const destinationRefusal=this.destinationAdmissionInTransaction(id);
2446
3069
  if(destinationRefusal)return destinationRefusal;
2447
3070
  this.assertNoUncertainDelivery(id);
2448
- 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;
2449
3081
  const seen=this.db.prepare('SELECT COALESCE(max(sequence),0) n FROM owner_notes WHERE request_id=?').get(id).n;
2450
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);
2451
3083
  this.setClaimDeadlineInTransaction(id,leaseMs);
2452
3084
  this.rebindClaim(id,claimId);
2453
- 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);
2454
- this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch,worker});
2455
- 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};
2456
3086
  }
2457
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.
2458
3088
  resume(id,subject='local-principal',connectionId=null) { return this.destinationOutcome(this.transaction(() => {
@@ -2462,14 +3092,11 @@ export class Store {
2462
3092
  if(!old||old.subject!==subject||a.status!=='claimed') throw new Error('no active claim for this subject');
2463
3093
  this.assertLiveConnection(id,old.worker,connectionId);
2464
3094
  this.assertRegrantReady(old);
3095
+ this.assertWorkerClaimSlot(old.worker,id);
2465
3096
  const destinationRefusal=this.destinationAdmissionInTransaction(id);
2466
3097
  if(destinationRefusal)return destinationRefusal;
2467
3098
  this.assertNoUncertainDelivery(id);
2468
- const claimId=`claim_${randomUUID()}`;
2469
- 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);
2470
- this.rebindClaim(id,claimId);
2471
- this.setClaimDeadlineInTransaction(id,this.claimLeaseMs(old));
2472
- 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)
2473
3100
  this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch:old.epoch+1});
2474
3101
  if(this.isProtocolJob(id)) {
2475
3102
  this.advanceProtocolRevisionInTransaction(id);
@@ -2478,17 +3105,22 @@ export class Store {
2478
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)};
2479
3106
  })); }
2480
3107
  // Withdraw the active claim and requeue the assignment, never while a delivery for it may be in flight or already delivered.
2481
- abandon(id,{actor='operator',reason='abandoned'}={}) { return this.transaction(() => {
3108
+ abandon(id,{actor='operator',reason='abandoned',fence=null}={}) { return this.transaction(() => {
2482
3109
  const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
2483
3110
  const old=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND state='active'").get(id);
2484
3111
  if(a.status==='finished'||a.status==='cancelled') throw new Error('assignment is terminal');
2485
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;
2486
3117
  this.assertNoUncertainDelivery(id);
2487
3118
  const at=this.stamp();
2488
3119
  const expired=reason==='lease_expired'&&this.leaseExpired(old);
2489
3120
  if(reason==='lease_expired') reason=Store.expirySummary(old);
2490
3121
  this.db.prepare("UPDATE claims SET state='abandoned',abandoned_at=?,abandon_reason=? WHERE request_id=?").run(at,reason,id);
2491
3122
  this.db.prepare("UPDATE assignments SET status='queued' WHERE request_id=?").run(id);
3123
+ this.lifecycle(id,'detach',actor,reason,old,{scope:`claim:${old.claim_id}@${old.epoch}`,outcome:'done'});
2492
3124
  this.lifecycle(id,'abandoned',actor,reason,old);
2493
3125
  this.lifecycle(id,'queued',actor,'requeued',null);
2494
3126
  if(this.isProtocolJob(id)) {
@@ -2502,19 +3134,83 @@ export class Store {
2502
3134
  // Result hints for list_pending and claim. Free lanes are bounded by both the lane capacity and the claim cap, so the
2503
3135
  // count never invites a claim that capacity_full would refuse.
2504
3136
  laneState(subject,worker='dot',laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity) {
2505
- 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};
2506
3139
  }
2507
3140
  // A claimed assignment left its lane: the next reannounceQueued tick may wake the worker at once instead of waiting out rewakeMs.
2508
3141
  laneFreed() { this.dispatchWake=true; }
2509
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.
2510
- 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)));
2511
3155
  if(free<=0) return {};
2512
- 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);
2513
3157
  if(!all.length) return {};
2514
- const next=all.slice(0,free).map(({request_id,title})=>({request_id,title}));
2515
- 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};
2516
3213
  }
2517
- 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); }
2518
3214
  // Active claims for the operator, with the lease state that decides whether another claimant may take one over.
2519
3215
  claims() {
2520
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=>({
@@ -2527,9 +3223,15 @@ export class Store {
2527
3223
  // The sweep (sweepStaleLeases) or a takeover is what moves the claim to abandoned; until then the row stays active but cannot act.
2528
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.
2529
3225
  refuseClaim(id,claimId,subject,worker) {
2530
- 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;
2531
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))
2532
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}));
2533
3235
  return new Error('invalid claim');
2534
3236
  }
2535
3237
  // Commit-time authority only: never re-admit the grant against destination/repository policy.
@@ -2600,7 +3302,7 @@ export class Store {
2600
3302
  return {...receipt.value,revision:receipt.revision};
2601
3303
  });
2602
3304
  // Decorate after replay validation too, including receipts stored before this field existed.
2603
- return question?result:nonterminalOutcome(id,result);
3305
+ return question?result:nonterminalOutcome(id,{...result,...this.heartbeatForHeldClaim(id,claimId,worker)});
2604
3306
  }
2605
3307
  progressInTransaction(id,claimId,note,subject='local-principal',blocker=false,worker='dot',question=null) {
2606
3308
  if(!this.db.isTransaction) throw new Error('progress requires a caller-owned transaction');
@@ -2662,9 +3364,39 @@ export class Store {
2662
3364
  this.assertProtocolAvailable(id);
2663
3365
  return claim;
2664
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
+ }
2665
3395
  finishOnce(id,claimId,outcome,summary,result,subject,evidence,worker,captureEvidence=null,connectionId=null) {
2666
3396
  const claim=this.assertFinishClaim(id,claimId,subject,worker);
2667
3397
  this.assertMutationConnection(id,claim,connectionId);
3398
+ const submittedOutcome=outcome;
3399
+ ({outcome,summary}=this.finishPatchOutcome(id,claimId,outcome,summary));
2668
3400
  const old=this.db.prepare('SELECT * FROM reports WHERE request_id=?').get(id);
2669
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)}; }
2670
3402
  const a=this.db.prepare('SELECT status,cancelled_reason FROM assignments WHERE request_id=?').get(id);
@@ -2678,7 +3410,14 @@ export class Store {
2678
3410
  }
2679
3411
  return {cancelled:true,reason:a.cancelled_reason,contradiction:!!kept&&(kept.outcome!==outcome||kept.full_sha256!==full)};
2680
3412
  }
2681
- 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
+ }
2682
3421
  if(captureEvidence) evidence=captureEvidence();
2683
3422
  this.recordClaimDenials(id,`${summary}\n${result}`,worker);
2684
3423
  const receipt=`report_${randomUUID()}`;
@@ -2705,6 +3444,7 @@ export class Store {
2705
3444
  this.assertNoUncertainDelivery(id);
2706
3445
  if(a.status==='claimed') this.laneFreed();
2707
3446
  this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=?,cancelled_reason=? WHERE request_id=?").run(this.stamp(),reason,id);
3447
+ this.lifecycle(id,'withdraw_work','owner',reason,undefined,{scope:`job:${id}`,outcome:'done'});
2708
3448
  this.lifecycle(id,'cancelled','owner',reason);
2709
3449
  this.db.prepare("UPDATE notifications SET state='suppressed' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
2710
3450
  this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
@@ -2722,6 +3462,7 @@ export class Store {
2722
3462
  const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
2723
3463
  if(a.status!=='queued') return {request_id:id,status:a.status,cancelled:false};
2724
3464
  this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=? WHERE request_id=? AND status='queued'").run(this.stamp(),id);
3465
+ this.lifecycle(id,'withdraw_work','owner',null,undefined,{scope:`job:${id}`,outcome:'done'});
2725
3466
  this.lifecycle(id,'cancelled','owner');
2726
3467
  this.db.prepare("UPDATE notifications SET state='suppressed' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
2727
3468
  this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
@@ -2731,17 +3472,20 @@ export class Store {
2731
3472
  // same path as `dalan abandon`, so the row is requeued and its lane is free at once. Before this, an expired lease only
2732
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
2733
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
2734
- // 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
2735
3476
  // passed while the bridge was down or draining does not requeue work the worker may still be running. A claim touched since
2736
3477
  // the start has no grace. A claim with an uncertain delivery waits for reconcile.
2737
3478
  // Returns the abandoned request ids.
2738
3479
  sweepStaleLeases(limit=20) {
2739
3480
  const done=[];
2740
- 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()
2741
3482
  .filter(c=>!this.heldAfterStart(c))
2742
3483
  .filter(c=>this.leaseExpired(c)).sort((a,b)=>a.activity<b.activity?-1:1).slice(0,limit);
2743
- for(const {request_id} of stale) {
2744
- 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
+ }
2745
3489
  catch(e) { if(!/uncertain_delivery|no active claim|terminal/.test(e.message)) throw e; }
2746
3490
  }
2747
3491
  return done;
@@ -2817,7 +3561,11 @@ export class Store {
2817
3561
  }
2818
3562
  deliveryMuted(id) { return !!this.db.prepare('SELECT 1 FROM assignment_delivery_mutes WHERE request_id=?').get(id); }
2819
3563
  suppressFinishedQuestions(requestId=null) {
2820
- 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);
2821
3569
  }
2822
3570
  quietDelivery(id,reason) {
2823
3571
  // Keep results/questions in the existing wait queue. Watches stay visible to
@@ -2829,10 +3577,14 @@ export class Store {
2829
3577
  // queue like any quieted one, and held_kind remembers what it was so releaseHeld can put it back once the parent runs again.
2830
3578
  // One transaction: held_kind and the quiet state land together or not at all. A crash between two separate writes would
2831
3579
  // leave a sending row that recoverSends turns into uncertain, which heldDeliveries skips.
3580
+ // The same transaction writes the typed wake_held event, once per hold: a row that is already held no longer matches the
3581
+ // UPDATE (quietDelivery moved its kind to 'wait'), so a repeat hold changes nothing and writes nothing.
2832
3582
  holdDelivery(id,reason) {
2833
3583
  this.inTransaction(() => {
2834
- this.db.prepare("UPDATE notifications SET held_kind=kind WHERE id=? AND kind IN ('t3','blocker','watch','break') AND state IN ('pending','failed','sending')").run(id);
3584
+ const held=this.db.prepare("UPDATE notifications SET held_kind=kind WHERE id=? AND kind IN ('t3','blocker','watch','break') AND state IN ('pending','failed','sending')").run(id).changes===1;
2835
3585
  this.quietDelivery(id,reason);
3586
+ const request=held&&this.db.prepare('SELECT request_id FROM notifications WHERE id=?').get(id)?.request_id;
3587
+ if(request) this.lifecycle(request,'wake_held','system','parent_stopped',undefined,{scope:`wake:${id}`,outcome:'unknown'});
2836
3588
  });
2837
3589
  }
2838
3590
  // Oldest first. `after` is the {created_at,id} of the last row a caller saw, so a caller can page past rows it has already
@@ -2854,7 +3606,9 @@ export class Store {
2854
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;
2855
3607
  }
2856
3608
  paused() { return this.db.prepare('SELECT paused_at,reason FROM operator_state WHERE id=1').get().paused_at !== null; }
2857
- 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}; }); }
2858
3612
  suppressStaleQuestion(row) {
2859
3613
  if(!row||!['blocker','wait'].includes(row.kind)||!row.body) return false;
2860
3614
  let body;try{body=JSON.parse(row.body);}catch{return false;}
@@ -2943,8 +3697,16 @@ export class Store {
2943
3697
  cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancelled_by_owner:cancelActor==='owner',read:a.owner_read_at!==null,
2944
3698
  ...this.failureFields(id),
2945
3699
  unanswered_blocker:lastBlocker&&(lastAnswer===null||lastBlocker.created_at>lastAnswer)?{text:lastBlocker.note,at:lastBlocker.created_at}:null,
3700
+ held_wake:this.heldWake(id),
2946
3701
  };
2947
3702
  }
3703
+ // The oldest wake still held for this request, with the typed reason its wake_held event recorded. Reads only.
3704
+ heldWake(id) {
3705
+ const row=this.db.prepare("SELECT id,held_kind,last_error FROM notifications WHERE request_id=? AND held_kind IS NOT NULL AND state IN ('pending','quiet') ORDER BY created_at,id LIMIT 1").get(id);
3706
+ if(!row) return null;
3707
+ const event=this.db.prepare("SELECT at,reason FROM lifecycle_events WHERE request_id=? AND type='wake_held' AND scope=? ORDER BY id DESC LIMIT 1").get(id,`wake:${row.id}`);
3708
+ return {kind:row.held_kind,reason:event?.reason??'parent_stopped',detail:row.last_error||null,since:event?.at??null,notification_id:row.id};
3709
+ }
2948
3710
  // Owner action for `dalan inbox --mark-read`: the same read marker as get, without fetching the result. True when it was unread.
2949
3711
  markInboxRead(id,via) { return this.transaction(() => {
2950
3712
  const status=this.get(id).status, v=this.ownerInbox(id);
@@ -2962,16 +3724,95 @@ export class Store {
2962
3724
  // Record a decision on a finished report. Append-only: a different decision is added and the latest wins; the same decision
2963
3725
  // again is a no-op. accepted and applied also write the 'accepted' event, not_useful the legacy reject event, so readers of
2964
3726
  // those events keep working; an owner decision also counts as the owner read.
2965
- decide(id,decision,opts={}) { return this.transaction(() => this.recordDecision(id,decision,opts)); }
2966
- recordDecision(id,decision,{note=null,actor='owner',via='cli'}={}) {
3727
+ // The refusal is thrown after the transaction committed, so the stale row it wrote stays.
3728
+ decide(id,decision,opts={}) {
3729
+ const result=this.transaction(() => this.recordDecision(id,decision,opts));
3730
+ if(result.stale_refusal) throw staleRevisionError(result.stale_refusal);
3731
+ return result;
3732
+ }
3733
+ // The first correction of a job that was not withdrawn. A cancelled correction never carried the work, so it supersedes nothing.
3734
+ newerRevision(id) {
3735
+ const row=this.db.prepare("SELECT r.request_id,r.input_revision,r.at FROM job_revisions r JOIN assignments a ON a.request_id=r.request_id WHERE r.prior_id=? AND a.status<>'cancelled' ORDER BY r.rowid LIMIT 1").get(id);
3736
+ return row?{...row}:null;
3737
+ }
3738
+ // The refusal for a result whose job has a newer revision, or null. Records stale on an undecided result. Run it inside a transaction.
3739
+ staleRefusal(id,{record=true}={}) {
3740
+ const newer=this.newerRevision(id); if(!newer) return null;
3741
+ const recorded=record&&!this.latestDecision(id);
3742
+ if(recorded) this.db.prepare("INSERT INTO decisions(request_id,decision,note,actor,via,at) VALUES(?,'stale',?,'system','revises',?)").run(id,`revised by ${newer.request_id}`,this.stamp());
3743
+ return {request_id:id,revised_by:newer.request_id,at:newer.at,recorded};
3744
+ }
3745
+ // Applying a patch is two phases, so that no decision is recorded before the patch is written. reserveApply is the fence: it
3746
+ // refuses when a newer revision exists. The caller then writes the patch, and calls confirmApply (records applied) or
3747
+ // releaseApply (the write failed; nothing is recorded). A reservation with neither is an apply that may or may not have
3748
+ // happened; it shows as uncertain in get, and a re-run resumes it. A correction after the reservation is new work.
3749
+ applyState(id) {
3750
+ const r=this.db.prepare('SELECT state,reserved_at,resolved_at,reason FROM apply_reservations WHERE request_id=?').get(id);
3751
+ if(!r) return null;
3752
+ if(r.state==='applying') return {state:'applying',uncertain:true,since:r.reserved_at};
3753
+ return r.state==='confirmed'?{state:'applied',at:r.resolved_at}:{state:'released',reason:r.reason,at:r.resolved_at};
3754
+ }
3755
+ // Every attempt, a first one or a resumed one, calls this and gets a new attempt token in the same transaction as the stale
3756
+ // check. An open reservation is taken over: the previous token is superseded and its confirm or release is refused. The stale
3757
+ // check always runs, before the already-applied shortcut and even when the caller found the patch already in its tree: a
3758
+ // revised job's result is never recorded accepted or applied. A refused takeover of an open reservation records nothing.
3759
+ reserveApply(id) {
3760
+ const result=this.transaction(() => {
3761
+ const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
3762
+ if(a.status!=='finished') throw new Error('only a finished assignment can be decided');
3763
+ const open=this.db.prepare("SELECT reserved_at FROM apply_reservations WHERE request_id=? AND state='applying'").get(id);
3764
+ const refusal=this.staleRefusal(id,{record:!open}); if(refusal) return {request_id:id,stale_refusal:refusal};
3765
+ if(!open&&this.latestDecision(id)?.decision==='applied') return {request_id:id,state:'applied',resumed:false};
3766
+ const at=this.stamp(), attempt=randomBytes(16).toString('hex');
3767
+ this.db.prepare("INSERT INTO apply_reservations(request_id,state,reserved_at,attempt) VALUES(?,'applying',?,?) ON CONFLICT(request_id) DO UPDATE SET state='applying',reserved_at=excluded.reserved_at,resolved_at=NULL,reason=NULL,attempt=excluded.attempt").run(id,at,attempt);
3768
+ return {request_id:id,state:'applying',resumed:!!open,since:at,attempt};
3769
+ });
3770
+ if(result.stale_refusal) throw staleRevisionError(result.stale_refusal);
3771
+ return result;
3772
+ }
3773
+ // The row the caller's token is checked against. A token that is not the current one is superseded: a later attempt took over,
3774
+ // the owner released the reservation, or the apply already finished.
3775
+ currentAttempt(id,attempt) {
3776
+ if(typeof attempt!=='string'||!attempt) throw new Error(`apply attempt token required for ${id}: reserve first`);
3777
+ const row=this.db.prepare('SELECT state,attempt FROM apply_reservations WHERE request_id=?').get(id);
3778
+ if(!row) throw new Error(`no open apply reservation for ${id}`);
3779
+ return {row,current:row.attempt===attempt};
3780
+ }
3781
+ confirmApply(id,{attempt,note=null,via='apply'}={}) { return this.transaction(() => {
3782
+ const {row,current}=this.currentAttempt(id,attempt);
3783
+ if(row.state==='confirmed'&&current) return {request_id:id,decision:'applied',duplicate:true,at:this.stamp()};
3784
+ if(row.state!=='applying') throw new Error(`no open apply reservation for ${id}`);
3785
+ if(!current) throw new Error(`superseded apply attempt for ${id}: not the current attempt; reserve again`);
3786
+ return this.recordDecision(id,'applied',{note,via,fenced:true});
3787
+ }); }
3788
+ // force is the owner giving up an uncertain reservation on purpose (the token may be lost); otherwise the current token is required.
3789
+ releaseApply(id,{attempt,reason=null,force=false}={}) { return this.transaction(() => {
3790
+ const row=this.db.prepare('SELECT state,attempt FROM apply_reservations WHERE request_id=?').get(id);
3791
+ if(!row) throw new Error(`no apply reservation for ${id}`);
3792
+ if(row.state==='confirmed') throw new Error(`${id} is already applied; a confirmed apply is not released`);
3793
+ if(row.state==='applying') {
3794
+ if(!force) { const {current}=this.currentAttempt(id,attempt); if(!current) throw new Error(`superseded apply attempt for ${id}: not the current attempt`); }
3795
+ this.db.prepare("UPDATE apply_reservations SET state='released',resolved_at=?,reason=? WHERE request_id=?").run(this.stamp(),reason===null?null:String(reason).slice(0,512),id);
3796
+ } else if(!force&&row.attempt!==attempt) throw new Error(`superseded apply attempt for ${id}: not the current attempt`);
3797
+ return {request_id:id,state:'released'};
3798
+ }); }
3799
+ recordDecision(id,decision,{note=null,actor='owner',via='cli',fenced=false}={}) {
2967
3800
  if(!decisionTypes.includes(decision)) throw new Error(`decision must be one of ${decisionTypes.join(', ')}`);
2968
3801
  const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
2969
3802
  if(a.status!=='finished') throw new Error('only a finished assignment can be decided');
2970
3803
  const latest=this.db.prepare('SELECT decision,actor FROM decisions WHERE request_id=? ORDER BY id DESC LIMIT 1').get(id);
2971
3804
  if(decision==='stale'&&(actor!=='system'||this.latestDecision(id))) return {request_id:id,decision:latest?.decision??null,duplicate:true};
3805
+ // An owner cannot accept or apply a result whose job has a newer revision. The check and the write share this transaction,
3806
+ // so a correction that commits first is always seen. It runs before the duplicate shortcut: accepting or applying again after a
3807
+ // correction is refused too. An undecided result is recorded stale; a decided one is left alone. A confirmed apply (fenced) was
3808
+ // checked when it was reserved, so a correction after the reservation is new work and does not block it.
3809
+ if(actor==='owner'&&!fenced&&(decision==='accepted'||decision==='applied')) {
3810
+ const refusal=this.staleRefusal(id); if(refusal) return {request_id:id,stale_refusal:refusal};
3811
+ }
2972
3812
  if(latest&&latest.decision===decision&&latest.actor===actor) return {request_id:id,decision,duplicate:true,at:this.stamp()};
2973
3813
  const at=this.stamp();
2974
3814
  this.db.prepare('INSERT INTO decisions(request_id,decision,note,actor,via,at) VALUES(?,?,?,?,?,?)').run(id,decision,note,actor,via,at);
3815
+ if(actor==='owner'&&decision==='applied') this.db.prepare("UPDATE apply_reservations SET state='confirmed',resolved_at=? WHERE request_id=? AND state='applying'").run(at,id);
2975
3816
  if(actor==='owner') {
2976
3817
  this.consumeOnce(id,'decide');
2977
3818
  if(decision==='accepted'||decision==='applied') this.lifecycle(id,'accepted','owner',decision==='applied'?(note?`applied: ${note}`:'applied'):note);
@@ -3086,7 +3927,12 @@ export class Store {
3086
3927
  const lastClaim=this.db.prepare("SELECT max(claimed_at) last_claim FROM claims WHERE worker='dot'").get().last_claim;
3087
3928
  const uncertain=this.db.prepare("SELECT count(*) n FROM notifications WHERE state='uncertain' AND kind IN ('t3','watch','blocker','break','event')").get().n;
3088
3929
  const pause=this.db.prepare('SELECT paused_at,reason FROM operator_state WHERE id=1').get();
3089
- 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]));
3090
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();
3091
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};
3092
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]))]));
@@ -3098,23 +3944,136 @@ export class Store {
3098
3944
  const dotCapacity=this.workerCapacityEvidence('dot',active,limits,capacity);
3099
3945
  const freeLanes=dotCapacity.free_lanes;
3100
3946
  const legacyScope=this.workers.legacy===true||this.workers.workers.has('dot')?'dot':'none';
3101
- 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'))};
3102
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)]);
3103
3954
  const by_worker=Object.fromEntries([...workerNames].sort().map(worker=>{
3104
3955
  const workerSubscriptions=worker==='dot'?active:this.activeSubscriptions().filter(row=>row.worker===worker);
3105
3956
  const liveness=this.liveness(limits,capacity,worker),expired=this.queuedExpired(worker);
3106
3957
  const requeued=this.queuedExpiredRequeued(worker);
3107
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);
3108
- const liveQueued=this.queuedRows().filter(row=>row.target_worker===worker).length;
3109
- 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})}];
3110
3966
  }));
3111
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();
3112
- return {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)};
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)};
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));
3113
4065
  }
3114
4066
  workerCapacityEvidence(worker,subscriptions,limits,capacity) {
3115
4067
  const byPrincipal=[...new Map(subscriptions.map(sub=>[sub.principal,sub])).values()];
3116
4068
  const scope=this.workers.laneScope==='worker'?'worker':'principal';
3117
- 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});
3118
4077
  if(!byPrincipal.length) return unknown('no_active_subscription');
3119
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);
3120
4079
  const principals=[...new Set([...byPrincipal.map(sub=>sub.principal),...subjectKeys])];
@@ -3127,6 +4086,6 @@ export class Store {
3127
4086
  const sub=byPrincipal[0];
3128
4087
  const lanes=this.subscriptionFreeLanes(sub,limits.laneCapacity??6,capacity);
3129
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}));
3130
- 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};
3131
4090
  }
3132
4091
  }