@tnunamak/dalan 0.8.5 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/store.mjs CHANGED
@@ -69,6 +69,7 @@ function waiterOwnerGone(attemptId) {
69
69
  }
70
70
 
71
71
  const SUPPORTED_SCHEMA_VERSION = 75;
72
+ const ADMISSION_RESERVATION_MS = 15_000;
72
73
  const monotonicMs=()=>Number(process.hrtime.bigint())/1e6;
73
74
  function systemBootId() {
74
75
  if(process.platform!=='linux') return null;
@@ -125,6 +126,11 @@ export function nonterminalOutcome(id,receipt) {
125
126
  }
126
127
  const stamp = () => new Date().toISOString();
127
128
  const hash = value => createHash('sha256').update(value).digest('hex');
129
+ const FACADE_GRACE_MS = 2000;
130
+ const FACADE_PENDING_GRACE_TTL = 24 * 60 * 60 * 1000;
131
+ class FacadeFinishCutoff extends Error {
132
+ constructor(at) { super('facade withdrawal won'); this.at=at; }
133
+ }
128
134
  function validateSubmitKey(key) {
129
135
  if(key!==null&&(typeof key!=='string'||key.length<1||key.length>128)) throw new Error('invalid command_key: use a nonempty string of at most 128 characters');
130
136
  }
@@ -388,6 +394,7 @@ export class Store {
388
394
  this.resumeIdleOption=options.resumeIdleMs;
389
395
  this.workers=options.workers??LEGACY_PROFILE;
390
396
  this.destinationProfile=options.destinationProfile??null;
397
+ this.admissionOpen=options.admissionOpen??(()=>true);
391
398
  // Server-side diagnostic only: receives the raw configuration error that destinationConfigurationError hides from callers.
392
399
  this.onConfigError=options.onConfigError??null;
393
400
  this.allowedDotSubjects=options.allowedDotSubjects??null;
@@ -1128,6 +1135,37 @@ export class Store {
1128
1135
  prior_id TEXT NOT NULL REFERENCES assignments(request_id),
1129
1136
  at TEXT NOT NULL
1130
1137
  ); PRAGMA user_version=75;`);
1138
+ // Older bridges read every open row of worker_breaks as a primary-worker hold.
1139
+ // Keep secondary-worker holds out of that table so a rollback can still read current data.
1140
+ this.db.exec(`CREATE TABLE IF NOT EXISTS scoped_worker_breaks(
1141
+ id INTEGER PRIMARY KEY, worker TEXT NOT NULL CHECK(length(worker)>0),
1142
+ since TEXT NOT NULL, reason TEXT NOT NULL, until TEXT, expected_end TEXT,
1143
+ end_source TEXT, last_probe_at TEXT
1144
+ ); CREATE UNIQUE INDEX IF NOT EXISTS scoped_worker_breaks_one_open
1145
+ ON scoped_worker_breaks(worker) WHERE until IS NULL;`);
1146
+ this.db.exec(`CREATE TABLE IF NOT EXISTS work_messages(
1147
+ message_id TEXT PRIMARY KEY REFERENCES messages(message_id) ON DELETE CASCADE,
1148
+ request_id TEXT NOT NULL REFERENCES assignments(request_id) ON DELETE CASCADE,
1149
+ progress_id INTEGER UNIQUE REFERENCES progress(id) ON DELETE SET NULL
1150
+ );`);
1151
+ this.db.exec(`CREATE TABLE IF NOT EXISTS admission_reservations(
1152
+ worker TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE REFERENCES assignments(request_id) ON DELETE CASCADE,
1153
+ subscription_id TEXT NOT NULL, issued_at TEXT NOT NULL, expires_at TEXT NOT NULL,
1154
+ boot_id TEXT, monotonic_deadline_ms REAL
1155
+ );`);
1156
+ this.db.exec(`CREATE TABLE IF NOT EXISTS facade_withdrawals(
1157
+ request_id TEXT PRIMARY KEY REFERENCES assignments(request_id) ON DELETE CASCADE,
1158
+ intent TEXT NOT NULL, due_ms INTEGER NOT NULL
1159
+ ); CREATE INDEX IF NOT EXISTS facade_withdrawals_due ON facade_withdrawals(due_ms);
1160
+ CREATE TABLE IF NOT EXISTS facade_withdrawal_keeps(
1161
+ request_id TEXT REFERENCES assignments(request_id) ON DELETE CASCADE,
1162
+ intent TEXT NOT NULL, due_ms INTEGER NOT NULL, PRIMARY KEY(request_id,intent)
1163
+ ) WITHOUT ROWID;
1164
+ CREATE TABLE IF NOT EXISTS facade_withdrawal_admissions(
1165
+ request_id TEXT NOT NULL, owner_hash TEXT NOT NULL, intent TEXT NOT NULL,
1166
+ due_ms INTEGER NOT NULL, expires_ms INTEGER NOT NULL, kept INTEGER NOT NULL DEFAULT 0,
1167
+ PRIMARY KEY(request_id,owner_hash)
1168
+ ) WITHOUT ROWID;`);
1131
1169
  // Worker run receipts (D9), hosted-session lifetimes (D14) and the publication grant on a relationship (D10).
1132
1170
  // Additive and idempotent, so it needs no schema number: older code ignores these tables and column.
1133
1171
  {
@@ -1303,7 +1341,8 @@ export class Store {
1303
1341
  // Use persisted worker progress for the start proxy. A reclaim resets the
1304
1342
  // first workspace call on the single current claim row, so mixing that time
1305
1343
  // 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.
1344
+ // start with `[bridge] `. Inbox acknowledgments also don't attest to work starting.
1345
+ // A finished job without observed progress started at an unobserved time.
1307
1346
  admissionEvidence(worker,kind,days=7) {
1308
1347
  kind=canonicalKindLabel(kind);
1309
1348
  const since=iso(this.nowMs()-days*86400000);
@@ -1321,6 +1360,7 @@ export class Store {
1321
1360
  (SELECT p.created_at FROM progress p INDEXED BY progress_request WHERE p.request_id=a.request_id
1322
1361
  AND (p.worker IS NULL OR p.worker=a.target_worker)
1323
1362
  AND p.note NOT LIKE '[bridge] %'
1363
+ AND NOT EXISTS (SELECT 1 FROM work_messages m WHERE m.progress_id=p.id)
1324
1364
  ORDER BY p.id LIMIT 1) started
1325
1365
  FROM selected a JOIN lifecycle l ON l.request_id=a.request_id
1326
1366
  LEFT JOIN claims c ON c.request_id=a.request_id`).all(since,worker,kind);
@@ -1352,7 +1392,15 @@ export class Store {
1352
1392
  admissionForQueuedRequest(requestId) {
1353
1393
  const row=this.db.prepare(`SELECT a.target_worker,a.priority,${queueKindSql} AS kind
1354
1394
  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;
1395
+ if(!row) return null;
1396
+ const admission=this.admissionAnswer(row.target_worker,row.kind,row.priority,{excludeIds:[requestId]});
1397
+ const reservation=this.admissionReservation(row.target_worker);
1398
+ if(!this.admissionOpen()||reservation?.request_id!==requestId||admission.worker_state!=='live'||
1399
+ this.capacityHoldUntil(row.target_worker)||
1400
+ this.db.prepare('SELECT 1 FROM facade_withdrawals WHERE request_id=?').get(requestId)) return admission;
1401
+ const sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(reservation.subscription_id);
1402
+ if(!sub||this.subscriptionFreeLanes(sub,undefined,undefined,requestId)<=0) return admission;
1403
+ return {...admission,start:'now',ahead:{count:0,oldest_age_ms:null},reserved_until:reservation.expires_at};
1356
1404
  }
1357
1405
  // Reuse the worker's list tuple. A prospective row is unskipped and comes last among rows at its timestamp.
1358
1406
  admissionAnswer(worker,kind,priority,{excludeIds=[],createdBefore=null,callerWaiting=false}={}) {
@@ -1364,18 +1412,62 @@ export class Store {
1364
1412
  const rankSkipped=anchor?.skipped_at!=null?1:0;
1365
1413
  const rankCreated=anchor?.created_at??createdBefore??at;
1366
1414
  const rankRow=anchor?.queue_rowid??'9223372036854775807';
1367
- const {count,oldest}=this.db.prepare(`SELECT count(*) count,min(created_at) oldest FROM assignments
1415
+ const aheadRows=this.db.prepare(`SELECT request_id,created_at,
1416
+ EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked FROM assignments
1368
1417
  WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND request_id IS NOT ? AND ${live(now)}
1418
+ AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id)
1369
1419
  AND (${LIST_ORDER}) < (?, ?, ?, CAST(? AS INTEGER))`)
1370
- .get(worker,first,second,rankPriority,rankSkipped,rankCreated,rankRow);
1371
- const workerBreak=worker==='dot'?this.holdingBreak():null;
1420
+ .all(worker,first,second,rankPriority,rankSkipped,rankCreated,rankRow);
1421
+ const blocked=this.destinationBlockRecheck();
1422
+ let count=0, oldest=null;
1423
+ for(const row of aheadRows) {
1424
+ if(row.blocked&&blocked(row.request_id)) continue;
1425
+ count++;
1426
+ if(oldest===null||row.created_at<oldest) oldest=row.created_at;
1427
+ }
1428
+ const workerBreak=this.holdingBreak(worker);
1372
1429
  const worker_state=this.paused()?'paused':workerBreak?'break':
1373
1430
  this.activeSubscriptions().some(sub=>sub.worker===worker)?'live':'no_live_subscription';
1374
1431
  const track_record=this.trackRecord(worker,kind);
1375
- // 'now' requires a reserved worker lane. Admission is advisory and reserves nothing.
1432
+ // A forecast is always advisory. Only an owned, current reservation can upgrade it.
1376
1433
  return {start:'queued',ahead:{count,oldest_age_ms:oldest===null?null:Math.max(0,now-Date.parse(oldest))},
1377
1434
  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
1435
  }
1436
+ admissionSubscriptionReady(sub) {
1437
+ return this.subscriptionActive(sub)&&sub.auth_failures<3&&!sub.rotation_blocked;
1438
+ }
1439
+ admissionReservation(worker) {
1440
+ const now=this.stamp();
1441
+ const reservation=this.db.prepare(`SELECT r.* FROM admission_reservations r JOIN assignments a USING(request_id)
1442
+ WHERE r.worker=? AND a.target_worker=r.worker AND a.status='queued'
1443
+ AND r.issued_at<=? AND r.expires_at>? AND ${live(this.nowMs())}`).get(worker,now,now);
1444
+ if(!reservation||reservation.boot_id!==this.leaseBootId) return null;
1445
+ if(reservation.boot_id!==null&&!(reservation.monotonic_deadline_ms>this.monotonicNow())) return null;
1446
+ const sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(reservation.subscription_id);
1447
+ return this.admissionSubscriptionReady(sub)?reservation:null;
1448
+ }
1449
+ reserveAdmissionLane(id,worker) {
1450
+ if(!this.db.isTransaction)protocolError('transaction_required');
1451
+ if(!this.admissionOpen()||this.workers.laneScope!=='worker'||this.paused()||this.holdingBreak(worker)||this.capacityHoldUntil(worker)||
1452
+ this.admissionReservation(worker)) return;
1453
+ const hint=this.claimHint(worker);
1454
+ if(hint!==null&&this.recentClaimCount(worker)>=hint) return;
1455
+ const sub=this.activeSubscriptions().find(candidate=>candidate.worker===worker&&this.admissionSubscriptionReady(candidate)&&
1456
+ this.subscriptionFreeLanes(candidate)>0);
1457
+ if(!sub) return;
1458
+ const first=this.listPending(worker).find(item=>item.kind==='assignment'&&!item.blocked&&!item.resume);
1459
+ if(first?.request_id!==id||this.destinationAdmissionInTransaction(id)) return;
1460
+ try { this.assertClaimGap(id,sub.principal,worker); }
1461
+ catch(error) { if(error.message.startsWith('claim_throttled:')) return; throw error; }
1462
+ const now=this.nowMs(), expires=Math.min(now+ADMISSION_RESERVATION_MS,Date.parse(sub.expires_at));
1463
+ if(expires<=now) return;
1464
+ this.db.prepare(`INSERT INTO admission_reservations
1465
+ (worker,request_id,subscription_id,issued_at,expires_at,boot_id,monotonic_deadline_ms) VALUES(?,?,?,?,?,?,?)
1466
+ ON CONFLICT(worker) DO UPDATE SET
1467
+ request_id=excluded.request_id,subscription_id=excluded.subscription_id,issued_at=excluded.issued_at,
1468
+ expires_at=excluded.expires_at,boot_id=excluded.boot_id,monotonic_deadline_ms=excluded.monotonic_deadline_ms`)
1469
+ .run(worker,id,sub.id,iso(now),iso(expires),this.leaseBootId,this.monotonicDeadlineFor(expires));
1470
+ }
1379
1471
  // D14: a hosted worker's own account of one session. A later job in the same session only extends it.
1380
1472
  recordWorkerSession(worker,subject,session) {
1381
1473
  if(!session) return;
@@ -1566,15 +1658,22 @@ export class Store {
1566
1658
  if(targetId===payload.request_id) throw new Error('supersede_cycle');
1567
1659
  // A correction proves the prior owner's capability. Withdrawal is a separate, keyed opt-in.
1568
1660
  if(revises!==null) {
1569
- if(!revises||typeof revises!=='object'||Array.isArray(revises)||Object.keys(revises).some(k=>!['prior_id','prior_token','withdraw_prior'].includes(k))||
1570
- 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?}');
1661
+ if(!revises||typeof revises!=='object'||Array.isArray(revises)||Object.keys(revises).some(k=>!['prior_id','prior_token','withdraw_prior','require_active_prior'].includes(k))||
1662
+ 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?, require_active_prior?}');
1571
1663
  if(Object.hasOwn(revises,'withdraw_prior')&&revises.withdraw_prior!==true) throw new Error('withdraw_prior must be true when supplied');
1664
+ if(Object.hasOwn(revises,'require_active_prior')&&(revises.require_active_prior!==true||!revises.withdraw_prior)) throw new Error('require_active_prior requires withdraw_prior and must be true when supplied');
1572
1665
  if(revises.withdraw_prior&&commandKey===null) throw new Error('withdraw_prior requires command_key');
1573
1666
  if(supersedes) throw new Error('revises_and_supersedes: a correction does not cancel its prior job; send one of them');
1574
1667
  if(revises.prior_id===payload.request_id) throw new Error('revises_cycle');
1575
1668
  const prior=this.db.prepare('SELECT revision,status FROM assignments WHERE request_id=?').get(revises.prior_id);
1576
1669
  if(!prior) throw new Error('revises_prior_not_found');
1577
1670
  this.owner(revises.prior_id,revises.prior_token);
1671
+ if(!old&&revises.require_active_prior) {
1672
+ const active=this.db.prepare(`SELECT 1 FROM assignments WHERE request_id=? AND target_worker=? AND status IN ('queued','claimed')
1673
+ AND ${live(this.nowMs())} AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id)`)
1674
+ .get(revises.prior_id,targetWorker??'dot');
1675
+ if(!active) throw new Error('revises_prior_not_active: the prior job no longer waits for this worker');
1676
+ }
1578
1677
  if(!old&&revises.withdraw_prior&&['queued','claimed'].includes(prior.status)&&this.isProtocolJob(revises.prior_id))
1579
1678
  throw new Error('withdraw_prior requires the protocol cancellation path for this prior job');
1580
1679
  // The same revision under another request_id is a duplicate in the metrics, not a correction.
@@ -1628,7 +1727,7 @@ export class Store {
1628
1727
  if(!command||command.key_digest!==hash(commandKey)) throw new Error('EXISTS: assignment already submitted under another command');
1629
1728
  const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??old.target_worker,execution??old.execution,requiredCapabilities,destinationRevision,this.legacyFixNames);
1630
1729
  const receipt=JSON.parse(command.receipt);
1631
- 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');
1730
+ if((previous?.target_id??null)!==targetId||(previousRevision?.prior_id??null)!==priorId||(previousFollow?.prior_id??null)!==followsId||!!receipt.withdraw_prior!==!!revises?.withdraw_prior||!!receipt.require_active_prior!==!!revises?.require_active_prior||command.owner_hash!==ownerHash||command.intent_digest!==intent) throw new Error('KEY_CONFLICT: command intent changed');
1632
1731
  return {...receipt,duplicate:true,...(approval?{destination_approval:approval}:{})};
1633
1732
  }
1634
1733
  if(command) throw new Error('EXISTS: command_key required to retry this assignment');
@@ -1711,7 +1810,7 @@ export class Store {
1711
1810
  if(relationship) this.db.prepare('UPDATE assignments SET relationship_id=? WHERE request_id=?').run(relationship.relationship_id,id);
1712
1811
  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());
1713
1812
  const requestedValidUntil=validUntilOf(payload);
1714
- const mayUseDefault=priority==='normal'&&!this.paused()&&!((targetWorker??'dot')==='dot'&&this.holdingBreak());
1813
+ const mayUseDefault=priority==='normal'&&!this.paused()&&!this.holdingBreak(targetWorker??'dot');
1715
1814
  const effectiveValidUntil=requestedValidUntil??(mayUseDefault&&typeof defaultValidUntil==='string'?defaultValidUntil:null);
1716
1815
  this.db.prepare('UPDATE assignments SET valid_until=?,valid_until_source=? WHERE request_id=?').run(effectiveValidUntil,requestedValidUntil?'requester':effectiveValidUntil?'queue_p90':null,id);
1717
1816
  this.recordPrPreflight(id,'submit',payload,preflight);
@@ -1738,8 +1837,21 @@ export class Store {
1738
1837
  }
1739
1838
  }
1740
1839
  if(follows) this.db.prepare('INSERT INTO job_follows(request_id,prior_id,at) VALUES(?,?,?)').run(id,follows.prior_id,this.stamp());
1741
- for (const sub of this.activeSubscriptions()) this.submitWake(id,sub);
1742
- const receipt={request_id:id,status:'queued',duplicate:false,...(revises?.withdraw_prior?{withdraw_prior:true}:{}),...(protocol?{revision:1}:{}),...this.destinationFields(id)};
1840
+ const waitingWithdrawal=this.db.prepare(`DELETE FROM facade_withdrawal_admissions WHERE request_id=? AND owner_hash=?
1841
+ RETURNING intent,due_ms,expires_ms,kept`).get(id,ownerHash);
1842
+ let status='queued';
1843
+ if(waitingWithdrawal && waitingWithdrawal.expires_ms>this.nowMs()) {
1844
+ if(waitingWithdrawal.kept) this.db.prepare('INSERT INTO facade_withdrawal_keeps(request_id,intent,due_ms) VALUES(?,?,?)').run(id,waitingWithdrawal.intent,waitingWithdrawal.due_ms);
1845
+ else {
1846
+ this.db.prepare('INSERT INTO facade_withdrawals(request_id,intent,due_ms) VALUES(?,?,?)').run(id,waitingWithdrawal.intent,waitingWithdrawal.due_ms);
1847
+ if(this.applyFacadeWithdrawalInTransaction(id)) status='cancelled';
1848
+ }
1849
+ }
1850
+ if(status==='queued') {
1851
+ if(callerWaiting===true&&priority==='normal'&&!protocol&&!inheritedOwnerHash) this.reserveAdmissionLane(id,targetWorker??'dot');
1852
+ for (const sub of this.activeSubscriptions()) this.submitWake(id,sub);
1853
+ }
1854
+ const receipt={request_id:id,status,duplicate:false,...(revises?.withdraw_prior?{withdraw_prior:true}:{}),...(revises?.require_active_prior?{require_active_prior:true}:{}),...(protocol?{revision:this.protocolRevision(id)}:{}),...this.destinationFields(id)};
1743
1855
  if(commandKey!==null) {
1744
1856
  const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??'dot',execution??defaultExecution,requiredCapabilities,destinationRevision,this.legacyFixNames);
1745
1857
  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);
@@ -1857,6 +1969,8 @@ export class Store {
1857
1969
  if(!this.db.isTransaction)protocolError('transaction_required');
1858
1970
  // HTTP authenticates the subject; native admission checks visibility before any receipt lookup.
1859
1971
  if(!this.mayAct(worker,id)||typeof subject!=='string'||!subject)throw new Error('assignment not found');
1972
+ if(this.db.prepare("SELECT 1 FROM facade_withdrawals WHERE request_id=? AND EXISTS (SELECT 1 FROM assignments WHERE request_id=? AND status='queued')").get(id,id))
1973
+ throw new Error('assignment withdrawal pending');
1860
1974
  this.assertProtocolAvailable(id);
1861
1975
  if(!ctx||typeof ctx.key!=='string'||!ctx.key||ctx.key.length>512||!protocolNat(ctx.revision))protocolError('command_context_required');
1862
1976
  const command={job:id,subject,worker,operation:'claim',key:ctx.key,expectedRevision:ctx.revision,
@@ -1904,6 +2018,7 @@ export class Store {
1904
2018
  subscriptionActive(sub) { return !!sub&&sub.state==='active'&&sub.expires_at>this.stamp()&&this.subscriptionVisible(sub); }
1905
2019
  suppressSubscriptionRows(ids,reason) {
1906
2020
  for(const id of ids) {
2021
+ this.releaseSubscriptionReservation(id);
1907
2022
  this.db.prepare("UPDATE subscriptions SET state='revoked' WHERE id=?").run(id);
1908
2023
  this.db.prepare("UPDATE notifications SET state='suppressed',last_error=? WHERE subscription_id=? AND state IN ('pending','failed')").run(reason,id);
1909
2024
  }
@@ -1937,8 +2052,13 @@ export class Store {
1937
2052
  activeClaims(subject,worker,exceptId=null) {
1938
2053
  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.lane_scope='worker' OR c.lane_key=?) AND c.request_id IS NOT ?").all(worker,subject,exceptId);
1939
2054
  }
1940
- subscriptionFreeLanes(sub,laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity) {
1941
- return this.freeLanes(sub.principal,sub.worker,laneCapacity,claimCapacity);
2055
+ subscriptionFreeLanes(sub,laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity,requestId=null) {
2056
+ const reserved=this.admissionReservation(sub.worker);
2057
+ const own=reserved&&reserved.subscription_id===sub.id&&reserved.request_id===requestId?requestId:null;
2058
+ return this.freeLanes(sub.principal,sub.worker,laneCapacity,claimCapacity,own);
2059
+ }
2060
+ releaseSubscriptionReservation(id) {
2061
+ if(this.db.prepare('DELETE FROM admission_reservations WHERE subscription_id=?').run(id).changes>0) this.laneFreed();
1942
2062
  }
1943
2063
  activeSubscriptions() { return this.db.prepare("SELECT * FROM subscriptions WHERE state='active' AND expires_at>?").all(this.stamp()).filter(sub=>this.subscriptionActive(sub)); }
1944
2064
  // Text of a wake that names the queue head when several items wait: the worker claims oldest first via list_pending.
@@ -1969,7 +2089,11 @@ export class Store {
1969
2089
  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();
1970
2090
  }
1971
2091
  // Break intervals [since, until or open] in ms. Owner since never reaches back before the previous break's end, so they are disjoint.
1972
- 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]); }
2092
+ breakIntervals(worker='dot') {
2093
+ const rows=worker==='dot'?this.db.prepare('SELECT since,until FROM worker_breaks ORDER BY since').all():
2094
+ this.db.prepare('SELECT since,until FROM scoped_worker_breaks WHERE worker=? ORDER BY since').all(worker);
2095
+ return rows.map(b=>[Date.parse(b.since),b.until?Date.parse(b.until):Infinity]);
2096
+ }
1973
2097
  // How long a row has been queued, minus usage-break time: the re-wake window and the unclaimed clock stand still during a break.
1974
2098
  queuedAgeMs(queuedAtText,now=this.nowMs(),breaks=this.breakIntervals()) {
1975
2099
  const from=Date.parse(queuedAtText);
@@ -1978,7 +2102,7 @@ export class Store {
1978
2102
  // Queued assignments that waited longer than the re-wake window, so re-wake no longer names them. Items with an uncertain or
1979
2103
  // sending owner delivery are left out: they wait for reconcile, not for the worker. Derived only: a requeue restarts the clock.
1980
2104
  unclaimedAfterReannounce(limits=this.limits,worker='dot') {
1981
- const now=this.nowMs(), windowMs=limits.rewakeWindowMs??defaultRedeliveryLimits.rewakeWindowMs, breaks=worker==='dot'?this.breakIntervals():[];
2105
+ const now=this.nowMs(), windowMs=limits.rewakeWindowMs??defaultRedeliveryLimits.rewakeWindowMs, breaks=this.breakIntervals(worker);
1982
2106
  const rows=this.db.prepare(`SELECT a.request_id,${queuedAt} queued_at FROM assignments a WHERE a.target_worker=? AND a.status='queued' AND ${live(now)} ORDER BY queued_at`).all(worker).filter(r=>this.queuedAgeMs(r.queued_at,now,breaks)>=windowMs&&!this.uncertainDeliveries(r.request_id));
1983
2107
  return {count:rows.length,oldest_age_ms:rows.length?now-Date.parse(rows[0].queued_at):null,request_ids:rows.slice(0,10).map(r=>r.request_id)};
1984
2108
  }
@@ -2035,7 +2159,7 @@ export class Store {
2035
2159
  ON CONFLICT(worker,subject) DO UPDATE SET last_call_at=excluded.last_call_at,last_list_pending_at=COALESCE(excluded.last_list_pending_at,last_list_pending_at)`).run(worker,subject,at,tool==='list_pending'?at:null);
2036
2160
  this.db.prepare('INSERT INTO worker_calls(worker,subject,minute,tool,count,bytes) VALUES(?,?,?,?,1,0) ON CONFLICT(worker,subject,minute,tool) DO UPDATE SET count=count+1').run(worker,subject,Math.floor(this.nowMs()/60000),tool);
2037
2161
  // The worker's next authenticated tool call ends an active usage break.
2038
- if(worker==='dot') { const active=this.activeBreak(); if(active) this.endBreak(active,'tool_call'); }
2162
+ const active=this.activeBreak(worker); if(active) this.endBreak(active,'tool_call');
2039
2163
  }); }
2040
2164
  // Bytes of the serialized MCP response to one tool call, added once the response is written (the minute it was written).
2041
2165
  recordResponseBytes(subject,tool,bytes,worker='dot') {
@@ -2127,28 +2251,35 @@ export class Store {
2127
2251
  if(updated) this.db.prepare('UPDATE worker_breaks SET usage=? WHERE id=?').run(next,id);
2128
2252
  return {id,since:row.since,updated,usage_before:usage};
2129
2253
  }); }
2130
- // Limitation: usage breaks are tracked only for the default worker (`dot`). Break evidence and probe budgets are not per worker.
2131
- activeBreak() { return this.db.prepare('SELECT * FROM worker_breaks WHERE until IS NULL').get()??null; }
2254
+ activeBreak(worker='dot') {
2255
+ if(worker==='dot') return this.db.prepare('SELECT * FROM worker_breaks WHERE until IS NULL').get()??null;
2256
+ return this.db.prepare("SELECT -id id,worker,since,reason,last_probe_at,'owner' source FROM scoped_worker_breaks WHERE worker=? AND until IS NULL").get(worker)??null;
2257
+ }
2132
2258
  // The break that holds work: only an owner-confirmed one. An inferred break (silence) is reported and alerted, not held on.
2133
- holdingBreak() { const b=this.activeBreak(); return b?.source==='owner'?b:null; }
2259
+ holdingBreak(worker='dot') { const b=this.activeBreak(worker); return b?.source==='owner'?b:null; }
2134
2260
  // The forecast is an operator observation tied to one break. The break row's
2135
2261
  // until remains the time that a worker call or owner clear actually ended it.
2136
2262
  breakForecast(id,now=this.nowMs()) {
2137
- const forecast=this.db.prepare('SELECT value FROM bridge_state WHERE key=?').get(`break_expected_end:${id}`)?.value;
2263
+ const forecast=id<0?this.db.prepare('SELECT expected_end FROM scoped_worker_breaks WHERE id=?').get(-id)?.expected_end:
2264
+ this.db.prepare('SELECT value FROM bridge_state WHERE key=?').get(`break_expected_end:${id}`)?.value;
2138
2265
  const until=Date.parse(forecast)>now?forecast:null;
2139
2266
  return {until,until_source:until===null?null:'owner_reported'};
2140
2267
  }
2141
- breakState() {
2142
- const b=this.activeBreak();
2268
+ breakState(worker='dot') {
2269
+ const b=this.activeBreak(worker);
2143
2270
  if(!b) return {active:false,since:null,reason:null,source:null,duration_ms:null};
2144
2271
  const now=this.nowMs(),forecast=b.source==='owner'?this.breakForecast(b.id,now):null;
2145
- return {active:true,id:b.id,since:b.since,reason:b.reason,source:b.source,duration_ms:now-Date.parse(b.since),
2272
+ return {active:true,id:b.id,since:b.since,reason:b.reason,source:b.source,duration_ms:now-Date.parse(b.since),...(b.worker?{worker:b.worker}:{}),
2146
2273
  last_probe_at:b.last_probe_at,...(forecast?.until?forecast:{})};
2147
2274
  }
2148
2275
  breaks() {
2149
2276
  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,
2150
2277
  duration_ms:(b.until?Date.parse(b.until):this.nowMs())-Date.parse(b.since),usage_before:JSON.parse(b.usage),last_probe_at:b.last_probe_at}));
2151
2278
  }
2279
+ scopedBreaks(worker) {
2280
+ return this.db.prepare("SELECT -id id,worker,since,until,reason,'owner' source,end_source,last_probe_at FROM scoped_worker_breaks WHERE worker=? ORDER BY scoped_worker_breaks.id")
2281
+ .all(worker).map(b=>({...b,duration_ms:(b.until?Date.parse(b.until):this.nowMs())-Date.parse(b.since)}));
2282
+ }
2152
2283
  startBreak({since,reason,source}) {
2153
2284
  const usage=this.usageBefore(Date.parse(since));
2154
2285
  const {lastInsertRowid}=this.db.prepare('INSERT INTO worker_breaks(since,reason,source,usage,created_at) VALUES(?,?,?,?,?)').run(since,reason,source,JSON.stringify(usage),this.stamp());
@@ -2172,14 +2303,22 @@ export class Store {
2172
2303
  ...(learned[name]&&effective[name]<configured[name]?{learned:learned[name].value,break_id:learned[name].break_id}:{})}));
2173
2304
  }
2174
2305
  // Owner mark. Over an active break (e.g. an inferred one) it takes over: source owner, new reason, since if given, fresh snapshot.
2175
- setBreak(reason,since=null,until=undefined) { return this.transaction(() => {
2306
+ setBreak(reason,since=null,until=undefined,worker='dot') { return this.transaction(() => {
2176
2307
  if(typeof reason!=='string'||!reason.trim()||reason.length>512) throw new Error('invalid reason');
2177
- const active=this.activeBreak(), now=this.nowMs(), at=since??active?.since??iso(now);
2308
+ const active=this.activeBreak(worker), now=this.nowMs(), at=since??active?.since??iso(now);
2178
2309
  if(until!==undefined&&until!==null&&(typeof until!=='string'||!(Date.parse(until)>now)))
2179
2310
  throw new Error('until must be in the future');
2180
2311
  if(!Number.isFinite(Date.parse(at))||Date.parse(at)>now) throw new Error('since must not be in the future');
2181
- const ended=this.db.prepare('SELECT max(until) u FROM worker_breaks WHERE until IS NOT NULL').get().u;
2312
+ const ended=worker==='dot'?this.db.prepare('SELECT max(until) u FROM worker_breaks WHERE until IS NOT NULL').get().u:
2313
+ this.db.prepare('SELECT max(until) u FROM scoped_worker_breaks WHERE worker=? AND until IS NOT NULL').get(worker).u;
2182
2314
  if(ended&&Date.parse(at)<Date.parse(ended)) throw new Error(`since must not be before the end of the previous break (${ended})`);
2315
+ if(worker!=='dot') {
2316
+ if(active) this.db.prepare('UPDATE scoped_worker_breaks SET since=?,reason=?,expected_end=CASE WHEN ? THEN ? ELSE expected_end END WHERE id=?')
2317
+ .run(at,reason,until!==undefined?1:0,until?iso(Date.parse(until)):null,-active.id);
2318
+ else this.db.prepare('INSERT INTO scoped_worker_breaks(worker,since,reason,expected_end) VALUES(?,?,?,?)')
2319
+ .run(worker,at,reason,until?iso(Date.parse(until)):null);
2320
+ return this.breakState(worker);
2321
+ }
2183
2322
  const id=active?.id??this.startBreak({since:at,reason,source:'owner'}).id;
2184
2323
  if(active) {
2185
2324
  const usage=this.usageBefore(Date.parse(at));
@@ -2192,15 +2331,20 @@ export class Store {
2192
2331
  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)));
2193
2332
  return this.breakState();
2194
2333
  }); }
2195
- clearBreak() { return this.transaction(() => {
2196
- const active=this.activeBreak();
2334
+ clearBreak(worker='dot') { return this.transaction(() => {
2335
+ const active=this.activeBreak(worker);
2197
2336
  if(active) this.endBreak(active,'owner');
2198
- return {cleared:!!active,...(active?{id:active.id,since:active.since}:{}),worker_break:this.breakState()};
2337
+ return {cleared:!!active,...(active?{id:active.id,since:active.since}:{}),worker_break:this.breakState(worker)};
2199
2338
  }); }
2200
2339
  // End a usage break, by owner clear or by the worker's next tool call. A break never moves a claim's lease deadline: only the
2201
2340
  // claimant's own progress extends a lease, so a claim with no progress for one lease period is released even across a break.
2202
2341
  // Call inside a transaction.
2203
2342
  endBreak(active,endSource) {
2343
+ if(active.id<0) {
2344
+ this.db.prepare('UPDATE scoped_worker_breaks SET until=?,end_source=?,expected_end=NULL WHERE id=?')
2345
+ .run(this.stamp(),endSource,-active.id);
2346
+ return;
2347
+ }
2204
2348
  this.db.prepare('UPDATE worker_breaks SET until=?,end_source=? WHERE id=?').run(this.stamp(),endSource,active.id);
2205
2349
  this.db.prepare('DELETE FROM bridge_state WHERE key=?').run(`break_expected_end:${active.id}`);
2206
2350
  }
@@ -2431,13 +2575,19 @@ export class Store {
2431
2575
  // never hold it back through pending or failed rows. The event names the first eligible item in list_pending order (the
2432
2576
  // oldest, normal work first) and says how many lanes are free; it marks nothing else delivered and touches no other row. startAttempt checks it again before it is sent.
2433
2577
  reannounceQueued(limits=this.limits) { return this.transaction(() => {
2578
+ for(const {worker} of this.db.prepare('SELECT worker FROM admission_reservations').all()) {
2579
+ if(!this.admissionReservation(worker)) {
2580
+ this.db.prepare('DELETE FROM admission_reservations WHERE worker=?').run(worker);
2581
+ this.laneFreed();
2582
+ }
2583
+ }
2434
2584
  // A lane freed since the last tick (laneFreed) waives the rewakeMs cadence once; every other gate below still applies.
2435
2585
  const dispatchNow=this.dispatchWake; this.dispatchWake=false;
2436
2586
  if (this.paused()||!this.db.prepare("SELECT 1 FROM assignments WHERE status='queued'").get()) return {announced:0};
2437
2587
  const now=this.nowMs(), rewakeMs=dispatchNow?0:limits.rewakeMs??defaultRedeliveryLimits.rewakeMs;
2438
2588
  // During an owner-confirmed usage break the only re-wake is one probe every breakProbeMs (first one breakProbeMs after
2439
2589
  // since). An inferred break is silence, not evidence, so it does not pace re-wakes.
2440
- const brk=this.holdingBreak();
2590
+ const probed=new Set();
2441
2591
  let probe=false,heldBreak=false,heldCapacity=false;
2442
2592
  const outstanding=this.db.prepare("SELECT 1 FROM notifications WHERE subscription_id=? AND state IN ('pending','sending','failed') AND wake_kind IN ('submit','rewake') LIMIT 1");
2443
2593
  const lastWake=this.db.prepare(`SELECT max(at) at FROM (SELECT max(COALESCE(attempt_started_at,created_at)) at FROM notifications WHERE subscription_id=?1 AND state='delivered' AND wake_kind IN ('submit','rewake','owner_note')
@@ -2445,15 +2595,20 @@ export class Store {
2445
2595
  let announced=0;
2446
2596
  for (const sub of this.activeSubscriptions()) {
2447
2597
  if(this.capacityHoldUntil(sub.worker)) {heldCapacity=true;continue;}
2448
- if(sub.worker==='dot'&&brk&&(probe||now-Date.parse(brk.last_probe_at??brk.since)<(limits.breakProbeMs??defaultRedeliveryLimits.breakProbeMs))) {heldBreak=true;continue;}
2449
- if(this.subscriptionFreeLanes(sub,limits.laneCapacity??6)<=0||outstanding.get(sub.id)) continue;
2598
+ const brk=this.holdingBreak(sub.worker);
2599
+ if(brk&&(probed.has(sub.worker)||now-Date.parse(brk.last_probe_at??brk.since)<(limits.breakProbeMs??defaultRedeliveryLimits.breakProbeMs))) {heldBreak=true;continue;}
2600
+ if(outstanding.get(sub.id)) continue;
2450
2601
  const last=lastWake.get(sub.id).at;
2451
2602
  if(last&&rewakeMs&&now-Date.parse(last)<rewakeMs) continue;
2452
2603
  const eligible=this.rewakeCandidates(sub.id,limits);
2453
- if(!eligible.length) continue;
2604
+ if(!eligible.length||this.subscriptionFreeLanes(sub,limits.laneCapacity??6,undefined,eligible[0].request_id)<=0) continue;
2454
2605
  this.queueEvent(eligible[0].request_id,sub,true,this.queueHeadTitle(eligible,this.subscriptionFreeLanes(sub,limits.laneCapacity??6)),'rewake');
2455
2606
  announced++;
2456
- if(brk&&sub.worker==='dot') { this.db.prepare('UPDATE worker_breaks SET last_probe_at=? WHERE id=?').run(this.stamp(),brk.id); probe=true; }
2607
+ if(brk) {
2608
+ const table=brk.id<0?'scoped_worker_breaks':'worker_breaks';
2609
+ this.db.prepare(`UPDATE ${table} SET last_probe_at=? WHERE id=?`).run(this.stamp(),Math.abs(brk.id));
2610
+ probed.add(sub.worker); probe=true;
2611
+ }
2457
2612
  }
2458
2613
  return {announced,...(probe?{probe:true}:{}),...(!announced&&heldBreak?{worker_break:true}:{}),...(!announced&&heldCapacity?{capacity_denied:true}:{})};
2459
2614
  }); }
@@ -2462,27 +2617,29 @@ export class Store {
2462
2617
  // by the callback with HTTP 410 or 413 (terminal), and, once queued rewakeWindowMs or longer, no wake delivered or sending
2463
2618
  // for the item in the last rewakeStaleMs (a backoff: a stale item stays eligible but is re-woken rarely).
2464
2619
  rewakeCandidates(subscriptionId,limits=this.limits) {
2465
- const now=this.nowMs(), windowMs=limits.rewakeWindowMs??defaultRedeliveryLimits.rewakeWindowMs, staleMs=limits.rewakeStaleMs??defaultRedeliveryLimits.rewakeStaleMs, breaks=this.breakIntervals();
2620
+ const now=this.nowMs(), windowMs=limits.rewakeWindowMs??defaultRedeliveryLimits.rewakeWindowMs, staleMs=limits.rewakeStaleMs??defaultRedeliveryLimits.rewakeStaleMs;
2466
2621
  const latest=this.db.prepare("SELECT state,last_error FROM notifications WHERE request_id=? AND subscription_id=? AND wake_kind IN ('submit','rewake') ORDER BY created_at DESC, rowid DESC LIMIT 1");
2467
2622
  const lastSent=this.db.prepare("SELECT max(COALESCE(attempt_started_at,created_at)) at FROM notifications WHERE request_id=? AND subscription_id=? AND state IN ('delivered','sending') AND wake_kind IN ('submit','rewake')");
2468
2623
  const sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(subscriptionId);
2469
2624
  if(!sub||!this.subscriptionVisible(sub)) return [];
2625
+ const breaks=this.breakIntervals(sub.worker);
2470
2626
  const denied=new Set(this.deniedQueued(sub.worker).map(d=>d.request_id));
2627
+ const reservedId=this.admissionReservation(sub.worker)?.request_id;
2471
2628
  return this.queuedRows().filter(row=>{
2472
2629
  if(!this.mayAct(sub.worker,row.request_id)||denied.has(row.request_id)||this.uncertainDeliveries(row.request_id)) return false;
2473
2630
  const event=latest.get(row.request_id,subscriptionId);
2474
2631
  if(event?.state==='suppressed'&&/^HTTP 41[03]$/.test(event.last_error??'')) return false;
2475
- if(this.queuedAgeMs(row.queued_at,now,sub.worker==='dot'?breaks:[])<windowMs) return true;
2632
+ if(this.queuedAgeMs(row.queued_at,now,breaks)<windowMs) return true;
2476
2633
  const sent=lastSent.get(row.request_id,subscriptionId).at;
2477
2634
  return !sent||now-Date.parse(sent)>=staleMs;
2478
- });
2635
+ }).sort((a,b)=>Number(b.request_id===reservedId)-Number(a.request_id===reservedId));
2479
2636
  }
2480
2637
  // Why a queued re-wake must not be sent now, or null. Its eligibility was decided when it was queued; drain may send it
2481
2638
  // later, after the head was claimed, a delivery for it turned uncertain or the last free lane filled.
2482
2639
  rewakeStale(row) {
2483
2640
  const sub=this.db.prepare("SELECT * FROM subscriptions WHERE id=? AND state='active' AND expires_at>?").get(row.subscription_id,this.stamp());
2484
2641
  if(!sub||!this.subscriptionVisible(sub)) return 'subscription inactive';
2485
- if(this.subscriptionFreeLanes(sub)<=0) return 'no free lane';
2642
+ if(this.subscriptionFreeLanes(sub,undefined,undefined,row.request_id)<=0) return 'no free lane';
2486
2643
  if(this.capacityHoldUntil(sub.worker)) return 'the worker reported a capacity denial; waiting for a slot';
2487
2644
  if(!this.rewakeCandidates(row.subscription_id).some(x=>x.request_id===row.request_id)) return 'head no longer eligible';
2488
2645
  return null;
@@ -2503,6 +2660,7 @@ export class Store {
2503
2660
  }
2504
2661
  }
2505
2662
  return this.transaction(() => {
2663
+ if(old) this.releaseSubscriptionReservation(id);
2506
2664
  if(replacing) {
2507
2665
  // A verified re-subscribe creates a new row for the same worker, never updates an immutable connection.
2508
2666
  // Retire unsent events before replaying the queue for the new connection under the stable subscription ID.
@@ -2520,6 +2678,7 @@ export class Store {
2520
2678
  }
2521
2679
  }); }
2522
2680
  unsubscribe(id) { return this.transaction(() => {
2681
+ this.releaseSubscriptionReservation(id);
2523
2682
  this.db.prepare("UPDATE subscriptions SET state='revoked' WHERE id=?").run(id);
2524
2683
  this.db.prepare("UPDATE notifications SET state='suppressed',last_error='subscription revoked' WHERE subscription_id=? AND state IN ('pending','failed')").run(id);
2525
2684
  }); }
@@ -2534,7 +2693,10 @@ export class Store {
2534
2693
  if(report) { report.trust=TRUST.worker; Object.assign(report,Store.resultAuthority(!!report.late)); }
2535
2694
  const lateRow=this.db.prepare('SELECT summary,truncated,full_sha256,created_at FROM late_evidence WHERE request_id=? ORDER BY created_at LIMIT 1').get(id);
2536
2695
  const late_evidence=lateRow?{...lateRow,truncated:!!lateRow.truncated}:null;
2537
- const progress=this.db.prepare('SELECT note,created_at FROM progress WHERE request_id=? ORDER BY id').all(id);
2696
+ const progress=this.db.prepare(`SELECT p.note,p.created_at,p.worker,m.message_id
2697
+ FROM progress p LEFT JOIN work_messages m ON m.progress_id=p.id
2698
+ WHERE p.request_id=? ORDER BY p.id`).all(id).map(({worker,message_id,...event})=>
2699
+ message_id===null?event:{...event,kind:'ack_message',message_id,acknowledged_by_worker:worker});
2538
2700
  const delivery=this.db.prepare('SELECT id,kind,state,attempts,last_error,argv,attempt_started_at,attempt_id,last_reconciled_at,uncertain_reason,terminal_at,terminal_reason FROM notifications WHERE request_id=? ORDER BY created_at').all(id).map(n=>({...n,argv:n.argv?JSON.parse(n.argv):null}));
2539
2701
  const watch=this.db.prepare('SELECT deadline,state,updated_at,notification_id FROM watches WHERE request_id=?').get(id) || null;
2540
2702
  const supersedes=this.db.prepare('SELECT target_id AS request_id,created_at FROM submit_supersedes WHERE request_id=?').get(id)??null;
@@ -2544,10 +2706,10 @@ export class Store {
2544
2706
  const authorityRevoked=!!a.cancelled_at||this.isProtocolJob(id)&&a.status==='finished';
2545
2707
  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)}))};
2546
2708
  }
2547
- // D9: the worker's own run receipts. Stored before the report so a retried finish replaces them; never after a report exists.
2709
+ // D9: store the worker's own run receipts in the report transaction.
2548
2710
  recordWorkerRuns(id,claimId,{runs,run_limit}) {
2549
2711
  if(!runs.length&&run_limit===null) return;
2550
- this.transaction(()=>{
2712
+ this.inTransaction(()=>{
2551
2713
  if(this.db.prepare('SELECT 1 FROM reports WHERE request_id=?').get(id)) return;
2552
2714
  const at=this.stamp();
2553
2715
  this.db.prepare('DELETE FROM worker_runs WHERE request_id=? AND claim_id=?').run(id,claimId);
@@ -2700,12 +2862,21 @@ export class Store {
2700
2862
  try { validateOwnerNote(text,this.ownerNotes(priorId)); } catch { return; }
2701
2863
  this.noteInTransaction(priorId,text);
2702
2864
  }
2703
- tell(text,worker='dot') { return this.transaction(() => {
2865
+ tell(text,worker=null,work=null) { return this.transaction(() => {
2866
+ if(work) {
2867
+ this.owner(work.requestId,work.capability);
2868
+ const row=this.db.prepare('SELECT status,target_worker FROM assignments WHERE request_id=?').get(work.requestId);
2869
+ if(!row||!['queued','claimed'].includes(row.status)) throw new Error('work message requires an open assignment');
2870
+ if(worker!==null&&worker!==row.target_worker) throw new Error('work message worker must match the assignment');
2871
+ worker=row.target_worker;
2872
+ }
2873
+ worker??='dot';
2704
2874
  if(worker==='pool') throw new Error('worker \"pool\" is not supported');
2705
2875
  const messageId=`msg_${randomUUID()}`, preview=text.slice(0,200), createdAt=this.stamp();
2706
2876
  this.db.prepare('INSERT INTO messages(message_id,text,text_sha256,preview,created_at,target_worker) VALUES(?,?,?,?,?,?)').run(messageId,text,hash(text),preview,createdAt,worker);
2877
+ if(work) this.db.prepare('INSERT INTO work_messages(message_id,request_id) VALUES(?,?)').run(messageId,work.requestId);
2707
2878
  for(const sub of this.activeSubscriptions()) this.queueMessageEvent(messageId,preview,sub);
2708
- return {message_id:messageId,status:'pending',created_at:createdAt,text_sha256:hash(text),preview};
2879
+ return {message_id:messageId,status:'pending',created_at:createdAt,text_sha256:hash(text),preview,...(work?{request_id:work.requestId}:{})};
2709
2880
  }); }
2710
2881
  queueMessageEvent(messageId,title,sub) {
2711
2882
  sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(sub.id);
@@ -2724,19 +2895,40 @@ export class Store {
2724
2895
  }
2725
2896
  return this.getMessage(id);
2726
2897
  }); }
2727
- listMessages(worker='dot') { return this.db.prepare("SELECT message_id,preview,created_at FROM messages WHERE status='pending' ORDER BY created_at").all().filter(r=>this.mayAct(worker,r.message_id)).slice(0,50); }
2898
+ messageBindingForWorker(id,worker) {
2899
+ const binding=this.db.prepare(`SELECT m.request_id,a.status FROM work_messages m
2900
+ JOIN assignments a ON a.request_id=m.request_id WHERE m.message_id=?`).get(id);
2901
+ if(!binding||!this.mayAct(worker,binding.request_id)) return {};
2902
+ return {bound_request_id:binding.request_id,stale:!['queued','claimed'].includes(binding.status)};
2903
+ }
2904
+ listMessages(worker='dot') {
2905
+ return this.db.prepare("SELECT message_id,preview,created_at FROM messages WHERE status='pending' ORDER BY created_at").all()
2906
+ .filter(r=>this.mayAct(worker,r.message_id)).slice(0,50)
2907
+ .map(r=>({...r,...this.messageBindingForWorker(r.message_id,worker)}));
2908
+ }
2728
2909
  getMessage(id,worker=null) {
2729
2910
  if(worker!==null&&!this.mayAct(worker,id)) throw new Error('message not found');
2730
2911
  const row=this.db.prepare('SELECT message_id,text,text_sha256,preview,status,created_at,acknowledged_at FROM messages WHERE message_id=?').get(id);
2731
2912
  if(!row) throw new Error('message not found');
2732
- return row;
2913
+ return worker===null?row:{...row,...this.messageBindingForWorker(id,worker)};
2733
2914
  }
2734
2915
  ackMessage(id,worker='dot') { return this.transaction(() => {
2735
2916
  if(!this.mayAct(worker,id)) throw new Error('message not found');
2736
2917
  const row=this.db.prepare('SELECT status FROM messages WHERE message_id=?').get(id);
2737
2918
  if(!row) throw new Error('message not found');
2738
2919
  if(row.status==='withdrawn') throw new Error('message withdrawn');
2739
- if(row.status!=='acknowledged') this.db.prepare("UPDATE messages SET status='acknowledged',acknowledged_at=? WHERE message_id=?").run(this.stamp(),id);
2920
+ if(row.status!=='acknowledged') {
2921
+ const at=this.stamp();
2922
+ this.db.prepare("UPDATE messages SET status='acknowledged',acknowledged_at=? WHERE message_id=?").run(at,id);
2923
+ const binding=this.db.prepare(`SELECT m.request_id FROM work_messages m JOIN assignments a ON a.request_id=m.request_id
2924
+ WHERE m.message_id=? AND a.status IN ('queued','claimed')`).get(id);
2925
+ if(binding) {
2926
+ // This receipt records worker-inbox acknowledgment while work is open. It does not wake the parent.
2927
+ const event=this.db.prepare('INSERT INTO progress(request_id,note,created_at,worker) VALUES(?,?,?,?)')
2928
+ .run(binding.request_id,`Worker inbox ${worker} acknowledged message ${id}.`,at,worker);
2929
+ this.db.prepare('UPDATE work_messages SET progress_id=? WHERE message_id=?').run(event.lastInsertRowid,id);
2930
+ }
2931
+ }
2740
2932
  return this.getMessage(id);
2741
2933
  }); }
2742
2934
  // Resume wake. DALAN_RESUME_IDLE_MS (default 120000; 0 disables everything below). A claim is idle when its holder made no
@@ -2861,9 +3053,8 @@ export class Store {
2861
3053
  .run('claim_batch_v1_'+match[1],`$.ids[${match[2]}]`,id);
2862
3054
  }
2863
3055
 
2864
- listPending(worker='dot',{batch=false,handoffExclusions=null}={}) {
2865
- // Recheck historical refusals against one lazily loaded configuration per listing.
2866
- // Listing is read-only: it neither deletes audit evidence nor grants approval.
3056
+ destinationBlockRecheck() {
3057
+ // Recheck recorded blocks against one lazy profile snapshot without granting approval.
2867
3058
  let loaded=false,failed=false,profile,loadError;
2868
3059
  const fail=error=>{ failed=true; loadError=error??new Error('destination configuration could not be loaded'); };
2869
3060
  const resolve=()=>{
@@ -2878,7 +3069,7 @@ export class Store {
2878
3069
  if(failed)throw loadError;
2879
3070
  return profile;
2880
3071
  };
2881
- const blocked=id=>{
3072
+ return id=>{
2882
3073
  if(failed)return true; // a failed load is reported once per listing, whatever it threw or returned
2883
3074
  const row=this.db.prepare('SELECT payload,target_worker,execution FROM assignments WHERE request_id=?').get(id);
2884
3075
  const approval=this.destinationApproval(id);
@@ -2887,14 +3078,22 @@ export class Store {
2887
3078
  return !(!approval&&!current||approval&&current?.revision===approval.revision&&current.policy.allowed);
2888
3079
  } catch { return true; }
2889
3080
  };
3081
+ }
3082
+ listPending(worker='dot',{batch=false,handoffExclusions=null}={}) {
3083
+ const blocked=this.destinationBlockRecheck();
3084
+ const reservedId=this.admissionReservation(worker)?.request_id;
3085
+ const reserveOrder=(a,b)=>Number(b.request_id===reservedId)-Number(a.request_id===reservedId);
2890
3086
  let filler=this.activeCallerReserve(worker)>0?this.fillerRoom(worker):Infinity;
2891
- 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))}));
3087
+ 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 NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id) 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)}))
3088
+ .sort((a,b)=>Number(a.blocked)-Number(b.blocked)||reserveOrder(a,b))
3089
+ .filter(a=>handoffExclusions===null||!a.blocked&&a.request_id!==reservedId&&!handoffExclusions.has(a.request_id)&&!this.handoffLapsed(a.request_id,worker))
3090
+ .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))}));
2892
3091
  if(batch||handoffExclusions!==null) return assignments;
2893
- 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));
3092
+ const messages=this.listMessages(worker).map(({preview,...m})=>({kind:'message',request_id:m.message_id,title:preview,...m})).sort((a,b)=>a.created_at.localeCompare(b.created_at));
2894
3093
  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,
2895
3094
  ...(this.db.prepare('SELECT 1 FROM destination_blocks WHERE request_id=?').get(c.request_id)&&blocked(c.request_id)?{blocked:true}:{}),
2896
3095
  note:'The prior lease expired. Call claim(request_id, claimant, acquisition_id) to request a new epoch after old host work has verifiably stopped. Read progress and owner notes with get first.'}));
2897
- return [...resumes,...messages,...assignments].sort((a,b)=>Number(!!a.blocked)-Number(!!b.blocked)).slice(0,50);
3096
+ return [...resumes,...messages,...assignments].sort((a,b)=>Number(!!a.blocked)-Number(!!b.blocked)||reserveOrder(a,b)).slice(0,50);
2898
3097
  }
2899
3098
  // Called for each list_pending answer to the worker: the first freeLanes assignments are the ones it could claim now. One that
2900
3099
  // is still there SKIP_AFTER_ELIGIBLE_MS after it first was, with no claim, is marked skipped_by_worker (and goes behind its
@@ -3014,6 +3213,8 @@ export class Store {
3014
3213
  leaseMs=this.cappedClaimLeaseMs(leaseMs,worker);
3015
3214
  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');
3016
3215
  if(!this.mayAct(worker,id)) throw new Error('assignment not found');
3216
+ if(this.db.prepare("SELECT 1 FROM facade_withdrawals WHERE request_id=? AND EXISTS (SELECT 1 FROM assignments WHERE request_id=? AND status='queued')").get(id,id))
3217
+ throw new Error('assignment withdrawal pending');
3017
3218
  if (this.paused()) throw new Error(pausedClaimMessage);
3018
3219
  const a=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
3019
3220
  if(a.cancelled_at) throw new Error(a.cancelled_reason==='expired'?expiredError(a.valid_until,{cancelled:true}):'assignment cancelled'); if(a.status==='finished') throw new Error('assignment finished');
@@ -3044,7 +3245,9 @@ export class Store {
3044
3245
  if(old) this.assertNoUncertainDelivery(id);
3045
3246
  const active=this.activeClaims(subject,worker,id);
3046
3247
  this.assertWorkerClaimSlot(worker,id);
3047
- if(active.length>=capacity) throw new Error('capacity_full');
3248
+ const reserved=this.admissionReservation(worker);
3249
+ const claimLimit=reserved?Math.min(capacity,this.limits.laneCapacity??6):capacity;
3250
+ if(active.length+(reserved&&reserved.request_id!==id?1:0)>=claimLimit) throw new Error('capacity_full');
3048
3251
  this.assertClaimGap(id,subject,worker,active);
3049
3252
  this.recordPrPreflight(id,'claim',JSON.parse(a.payload),preflight,!!old);
3050
3253
  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(); }
@@ -3060,6 +3263,7 @@ export class Store {
3060
3263
  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);
3061
3264
  }
3062
3265
  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);
3266
+ this.db.prepare('DELETE FROM admission_reservations WHERE request_id=?').run(id);
3063
3267
  this.markBatchGrant(id,acquisitionId);
3064
3268
  this.lifecycle(id,'claimed',`worker:${subject}`,takeover?'takeover':old?'reclaim':'new',{claim_id:claimId,epoch:old?old.epoch+1:1,worker});
3065
3269
  this.db.prepare('DELETE FROM claim_denials WHERE request_id=?').run(id);
@@ -3074,6 +3278,7 @@ export class Store {
3074
3278
  this.assertLiveConnection(old.request_id,worker,connectionId);
3075
3279
  const id=old.request_id, idleS=Math.floor(this.claimIdleMs(old)/1000);
3076
3280
  this.assertWorkerClaimSlot(worker,id);
3281
+ this.assertReservationLane(subject,worker,id);
3077
3282
  const destinationRefusal=this.destinationAdmissionInTransaction(id);
3078
3283
  if(destinationRefusal)return destinationRefusal;
3079
3284
  this.assertNoUncertainDelivery(id);
@@ -3102,6 +3307,7 @@ export class Store {
3102
3307
  this.assertLiveConnection(id,old.worker,connectionId);
3103
3308
  this.assertRegrantReady(old);
3104
3309
  this.assertWorkerClaimSlot(old.worker,id);
3310
+ this.assertReservationLane(subject,old.worker,id);
3105
3311
  const destinationRefusal=this.destinationAdmissionInTransaction(id);
3106
3312
  if(destinationRefusal)return destinationRefusal;
3107
3313
  this.assertNoUncertainDelivery(id);
@@ -3144,7 +3350,22 @@ export class Store {
3144
3350
  // count never invites a claim that capacity_full would refuse.
3145
3351
  laneState(subject,worker='dot',laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity) {
3146
3352
  const max=this.workerMaxClaims(worker);
3147
- 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};
3353
+ const ready=this.listPending(worker).filter(x=>x.kind==='assignment'&&!x.resume&&!x.blocked);
3354
+ const free_lanes=this.freeLanes(subject,worker,laneCapacity,claimCapacity);
3355
+ const reserved_request_id=this.readyReservedLane(subject,worker,ready,laneCapacity,claimCapacity);
3356
+ return {...(max===null?{}:{worker_max_claims:max}),free_lanes,queued:ready.length,...(reserved_request_id?{reserved_request_id}:{})};
3357
+ }
3358
+ readyReservedLane(subject,worker,ready,laneCapacity,claimCapacity) {
3359
+ const reserved=this.admissionReservation(worker);
3360
+ if(reserved&&reserved.request_id===ready[0]?.request_id&&
3361
+ this.freeLanes(subject,worker,laneCapacity,claimCapacity,reserved.request_id)>0) return reserved.request_id;
3362
+ return null;
3363
+ }
3364
+ batchClaimRoom(subject,worker,laneCapacity,claimCapacity) {
3365
+ const ready=this.listPending(worker,{batch:true}).filter(item=>!item.blocked);
3366
+ const free_lanes=this.freeLanes(subject,worker,laneCapacity,claimCapacity);
3367
+ const reservedId=this.readyReservedLane(subject,worker,ready,laneCapacity,claimCapacity);
3368
+ return {ready,free_lanes,available:free_lanes+Number(!!reservedId),reservedId};
3148
3369
  }
3149
3370
  // A claimed assignment left its lane: the next reannounceQueued tick may wake the worker at once instead of waiting out rewakeMs.
3150
3371
  laneFreed() { this.dispatchWake=true; }
@@ -3158,14 +3379,17 @@ export class Store {
3158
3379
  .filter(c=>Date.parse(c.last_claim_activity_at??c.claimed_at)>=since).length;
3159
3380
  }
3160
3381
  // `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.
3161
- nextQueued(free,exceptId=null,worker='dot',{applyHint=true,handoffExclusions=null}={}) {
3382
+ nextQueued(free,exceptId=null,worker='dot',{applyHint=true,handoffExclusions=null,reservedId=null}={}) {
3162
3383
  const hint=applyHint?this.claimHint(worker):null,lanesFree=free;
3163
- if(hint!==null) free=Math.min(free,Math.max(0,hint-this.recentClaimCount(worker)));
3164
- if(free<=0) return {};
3384
+ if(!reservedId&&free<=0) return {};
3165
3385
  const all=this.listPending(worker,{handoffExclusions}).filter(x=>x.kind==='assignment'&&!x.blocked&&x.request_id!==exceptId);
3166
- if(!all.length) return {};
3386
+ const reserved=reservedId!==null&&all[0]?.request_id===reservedId;
3387
+ free+=Number(reserved);
3388
+ if(hint!==null) free=Math.min(free,Math.max(Number(reserved),hint-this.recentClaimCount(worker)));
3389
+ if(free<=0||!all.length) return {};
3167
3390
  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]])));
3168
- const lanes=free<lanesFree?`${lanesFree} ${lanesFree===1?'lane':'lanes'} free, ${next.length} suggested`:`${free} ${free===1?'lane':'lanes'} free`;
3391
+ const lanes=reserved?`1 reserved lane and ${lanesFree} free`:
3392
+ free<lanesFree?`${lanesFree} ${lanesFree===1?'lane':'lanes'} free, ${next.length} suggested`:`${free} ${free===1?'lane':'lanes'} free`;
3169
3393
  return {next_queued:next,next_action:`${all.length} queued and ${lanes}: claim ${next.map(x=>x.request_id).join(', ')} now (oldest first)`};
3170
3394
  }
3171
3395
  // Every inactive-to-live transition must enforce the same worker cap.
@@ -3173,8 +3397,13 @@ export class Store {
3173
3397
  assertWorkerClaimSlot(worker,id) {
3174
3398
  if(!this.db.isTransaction)protocolError('transaction_required');
3175
3399
  const max=this.workerMaxClaims(worker);
3176
- if(max!==null&&this.liveWorkerClaims(worker,id)>=max)
3177
- throw new Error(JSON.stringify({error:'capacity_full',message:`Worker ${worker} already holds its ${max} live claims`,worker}));
3400
+ const reserved=this.admissionReservation(worker);
3401
+ const held=reserved&&reserved.request_id!==id?1:0;
3402
+ if(max!==null) {
3403
+ const occupied=this.liveWorkerClaims(worker,id);
3404
+ if(occupied+held>=max) throw new Error(JSON.stringify({error:'capacity_full',worker,
3405
+ message:occupied>=max?`Worker ${worker} already holds its ${max} live claims`:`Worker ${worker} has a lane reserved for another request`}));
3406
+ }
3178
3407
  if((this.limits?.workerCallerReserve?.[worker]??0)>0&&this.activeCallerReserve(worker)>0&&
3179
3408
  this.db.prepare('SELECT caller_waiting FROM assignments WHERE request_id=?').get(id)?.caller_waiting!==1&&this.fillerRoom(worker,id)<=0)
3180
3409
  throw new Error(JSON.stringify({error:'capacity_full',message:'No background lane is available because of the caller reserve.',worker}));
@@ -3200,7 +3429,10 @@ export class Store {
3200
3429
  // 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.
3201
3430
  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)
3202
3431
  .filter(claim=>!this.leaseExpired(claim)).length;
3203
- return this.callerCapacity(worker)-this.activeCallerReserve(worker)-occupied;
3432
+ const reserved=this.admissionReservation(worker);
3433
+ // The reserved request is already a waiting caller. Do not set aside its lane twice.
3434
+ const held=Math.max(this.activeCallerReserve(worker),reserved&&reserved.request_id!==exceptId?1:0);
3435
+ return this.callerCapacity(worker)-held-occupied;
3204
3436
  }
3205
3437
  workerMaxClaims(worker,limits=this.limits) {
3206
3438
  const caps=limits.workerMaxClaims??{};
@@ -3210,10 +3442,18 @@ export class Store {
3210
3442
  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)
3211
3443
  .filter(claim=>!this.leaseExpired(claim)).length;
3212
3444
  }
3213
- freeLanes(subject,worker='dot',laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity) {
3445
+ assertReservationLane(subject,worker,id) {
3446
+ const reserved=this.admissionReservation(worker);
3447
+ if(!reserved||reserved.request_id===id) return;
3448
+ const limit=Math.min(this.limits.laneCapacity??6,this.capacity);
3449
+ if(this.activeClaims(subject,worker,id).length+1>=limit) throw new Error('capacity_full');
3450
+ }
3451
+ freeLanes(subject,worker='dot',laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity,requestId=null) {
3214
3452
  const legacy=Math.min(laneCapacity,claimCapacity)-this.activeClaims(subject,worker).length;
3215
3453
  const max=this.workerMaxClaims(worker);
3216
- return Math.max(0,max===null?legacy:Math.min(legacy,max-this.liveWorkerClaims(worker)));
3454
+ const reserved=this.admissionReservation(worker);
3455
+ const held=reserved&&reserved.request_id!==requestId?1:0;
3456
+ return Math.max(0,(max===null?legacy:Math.min(legacy,max-this.liveWorkerClaims(worker)))-held);
3217
3457
  }
3218
3458
  quiesceCounts() {
3219
3459
  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();
@@ -3354,16 +3594,30 @@ export class Store {
3354
3594
  static clipBytes(text,max) { const buf=Buffer.from(text); if(buf.length<=max) return text; let end=max; while(end>0&&(buf[end]&0xC0)===0x80) end--; return buf.subarray(0,end).toString(); }
3355
3595
  static lateEvidenceLimits={summary:4096,result:64*1024};
3356
3596
  finish(id,claimId,outcome,summary,result,subject='local-principal',evidence=null,worker='dot',ctx=null,captureEvidence=null,connectionId=null) {
3357
- if(this.isProtocolJob(id)&&this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id)?.status!=='cancelled')
3358
- return finishProtocol(this,id,claimId,outcome,summary,result,subject,evidence,worker,ctx,captureEvidence,connectionId);
3597
+ // The same deadline that closes keep also closes result authority, even before the sweep runs.
3598
+ this.applyFacadeWithdrawal(id);
3599
+ const protocol=this.isProtocolJob(id)&&this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id)?.status!=='cancelled';
3359
3600
  // Older worker runtimes report their safety rejection through ordinary finish.
3360
3601
  // Preserve the worker's text; only the explicit runtime cause changes classification.
3361
- if (outcome==='blocked' && [summary,result].some(text => typeof text==='string' &&
3602
+ if (!protocol && outcome==='blocked' && [summary,result].some(text => typeof text==='string' &&
3362
3603
  /(?:^|\n)(?:BLOCKED:\s*)?(?:The )?(?:claimed assignment content|claim tool result)\b[^\n]{0,240}\b(?:did not pass|failed)\b[^\n]{0,120}\b(?:safety|prompt-injection)[ -]check\b/i.test(text))) outcome=PROVIDER_REFUSAL;
3363
3604
  const rollback=[];
3605
+ const writeReport=capture=>this.finishOnce(id,claimId,outcome,summary,result,subject,evidence,worker,capture,connectionId);
3364
3606
  let done;
3365
- try { done=this.transaction(() => this.finishOnce(id,claimId,outcome,summary,result,subject,evidence,worker,captureEvidence?()=>captureEvidence(cleanup=>rollback.push(cleanup)):null,connectionId)); }
3366
- catch(error) {for(const cleanup of rollback)cleanup();throw error;}
3607
+ try {
3608
+ if(protocol) return finishProtocol(this,id,claimId,outcome,summary,result,subject,evidence,worker,ctx,captureEvidence,connectionId);
3609
+ done=this.transaction(()=>writeReport(captureEvidence?()=>captureEvidence(cleanup=>rollback.push(cleanup)):null));
3610
+ } catch(error) {
3611
+ for(const cleanup of rollback)cleanup();
3612
+ if(!(error instanceof FacadeFinishCutoff)) throw error;
3613
+ // Discard the attempted result and its artifacts before recording audit-only output.
3614
+ done=this.transaction(()=>{
3615
+ const claim=this.assertFinishClaim(id,claimId,subject,worker);
3616
+ this.assertMutationConnection(id,claim,connectionId);
3617
+ if(!this.applyFacadeWithdrawalInTransaction(id,error.at)) throw error;
3618
+ return writeReport(null);
3619
+ });
3620
+ }
3367
3621
  // Thrown after the transaction commits so the evidence row stays. TERMINAL: the worker has nothing more to do for this request.
3368
3622
  if(done.cancelled) throw new Error(JSON.stringify({error:'assignment_cancelled',message:`${id} was cancelled${done.reason?` (reason: ${done.reason})`:''} before this finish. Your output was kept as audit evidence only (not a result); nothing more is needed for ${id}; your other assignments are unaffected.${done.contradiction?' A different output was already kept for this request; this one was not stored.':''}`,request_id:id}));
3369
3623
  return done;
@@ -3433,8 +3687,11 @@ export class Store {
3433
3687
  }
3434
3688
  if(captureEvidence) evidence=captureEvidence();
3435
3689
  this.recordClaimDenials(id,`${summary}\n${result}`,worker);
3436
- const receipt=`report_${randomUUID()}`;
3437
- this.db.prepare('INSERT INTO reports(request_id,claim_id,outcome,summary,result,receipt_id,created_at,late,workspace_evidence,worker) VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,claimId,outcome,summary,result,receipt,this.stamp(),0,evidence?JSON.stringify(evidence):null,worker);
3690
+ const receipt=`report_${randomUUID()}`, encodedEvidence=evidence?JSON.stringify(evidence):null;
3691
+ // Authorize and timestamp the report at the insert, after evidence capture.
3692
+ const recordedAt=this.nowMs();
3693
+ if(this.facadeWithdrawalDue(id,recordedAt)) throw new FacadeFinishCutoff(recordedAt);
3694
+ this.db.prepare('INSERT INTO reports(request_id,claim_id,outcome,summary,result,receipt_id,created_at,late,workspace_evidence,worker) VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,claimId,outcome,summary,result,receipt,iso(recordedAt),0,encodedEvidence,worker);
3438
3695
  // completed means the worker filed its terminal report; acceptance is only ever the owner's accept event.
3439
3696
  this.lifecycle(id,'completed',`worker:${subject}`,`outcome=${outcome}`,claim);
3440
3697
  if(outcome==='blocked') this.lifecycle(id,'blocked',`worker:${subject}`,null,claim);
@@ -3446,6 +3703,84 @@ export class Store {
3446
3703
  this.laneFreed();
3447
3704
  return {receipt_id:receipt,request_id:id,duplicate:false,late:false,...Store.resultAuthority(false),...this.nextQueued(this.freeLanes(claim.subject,claim.worker),id,worker)};
3448
3705
  }
3706
+ armFacadeWithdrawal(id, intent) {
3707
+ return this.transaction(() => {
3708
+ this.assertProtocolAvailable(id);
3709
+ const assignment = this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
3710
+ if (!assignment) throw new Error('assignment not found');
3711
+ const priorKeep=this.facadeKeepReceipt(id,intent);
3712
+ if(priorKeep) return {not_before:priorKeep.due_ms,kept:true};
3713
+ const due = this.nowMs()+FACADE_GRACE_MS;
3714
+ this.db.prepare(`INSERT INTO facade_withdrawals(request_id,intent,due_ms)
3715
+ VALUES(?,?,?) ON CONFLICT(request_id) DO NOTHING`).run(id,intent,due);
3716
+ const record = this.db.prepare('SELECT intent,due_ms FROM facade_withdrawals WHERE request_id=?').get(id);
3717
+ if (record.intent!==intent) throw new Error('another withdrawal is already pending');
3718
+ if(this.db.prepare('DELETE FROM admission_reservations WHERE request_id=?').run(id).changes>0) this.laneFreed();
3719
+ return {not_before:record.due_ms};
3720
+ });
3721
+ }
3722
+ facadeKeepReceipt(id, intent) {
3723
+ return this.db.prepare('SELECT due_ms FROM facade_withdrawal_keeps WHERE request_id=? AND intent=?').get(id,intent);
3724
+ }
3725
+ facadeWithdrawalBeforeAdmission(id,intent,action,token) {
3726
+ // This can affect only an eventual admission carrying the same owner capability.
3727
+ const ownerHash=hash(token),now=this.nowMs();
3728
+ return this.transaction(()=>{
3729
+ if(action==='arm') {
3730
+ this.db.prepare('DELETE FROM facade_withdrawal_admissions WHERE expires_ms<=?').run(now);
3731
+ const exists=this.db.prepare('SELECT 1 FROM facade_withdrawal_admissions WHERE request_id=? AND owner_hash=?').get(id,ownerHash);
3732
+ if(!exists && this.db.prepare('SELECT count(*) AS n FROM facade_withdrawal_admissions').get().n>=1024)
3733
+ throw new Error('too many cancellations awaiting admission');
3734
+ this.db.prepare(`INSERT INTO facade_withdrawal_admissions(request_id,owner_hash,intent,due_ms,expires_ms)
3735
+ VALUES(?,?,?,?,?) ON CONFLICT(request_id,owner_hash) DO NOTHING`).run(id,ownerHash,intent,now+FACADE_GRACE_MS,now+FACADE_PENDING_GRACE_TTL);
3736
+ }
3737
+ const row=this.db.prepare(`SELECT intent,due_ms,kept FROM facade_withdrawal_admissions
3738
+ WHERE request_id=? AND owner_hash=? AND expires_ms>?`).get(id,ownerHash,now);
3739
+ if(action==='arm') {
3740
+ if(row.intent!==intent) throw new Error('another withdrawal is already pending');
3741
+ return {not_before:row.due_ms,...(row.kept?{kept:true}:{})};
3742
+ }
3743
+ if(!row || row.intent!==intent) return {kept:false};
3744
+ if(row.kept || action!=='keep' || row.due_ms<=now) return {kept:!!row.kept};
3745
+ this.db.prepare('UPDATE facade_withdrawal_admissions SET kept=1 WHERE request_id=? AND owner_hash=?').run(id,ownerHash);
3746
+ return {kept:true};
3747
+ });
3748
+ }
3749
+ keepFacadeWork(id, intent) {
3750
+ return this.transaction(() => {
3751
+ if(this.facadeKeepReceipt(id,intent)) return {kept:true};
3752
+ const removed = this.db.prepare('DELETE FROM facade_withdrawals WHERE request_id=? AND intent=? AND due_ms>? RETURNING due_ms')
3753
+ .get(id,intent,this.nowMs());
3754
+ if(!removed) return {kept:false};
3755
+ this.db.prepare('INSERT INTO facade_withdrawal_keeps(request_id,intent,due_ms) VALUES(?,?,?)')
3756
+ .run(id,intent,removed.due_ms);
3757
+ return {kept:true};
3758
+ });
3759
+ }
3760
+ dueFacadeWithdrawals() {
3761
+ return this.db.prepare('SELECT request_id FROM facade_withdrawals WHERE due_ms<=? ORDER BY due_ms,request_id LIMIT 100')
3762
+ .all(this.nowMs()).map(row=>row.request_id);
3763
+ }
3764
+ applyFacadeWithdrawal(id) {
3765
+ if(!this.facadeWithdrawalDue(id,this.nowMs())) return false;
3766
+ return this.transaction(()=>this.applyFacadeWithdrawalInTransaction(id));
3767
+ }
3768
+ facadeWithdrawalDue(id, at) {
3769
+ return !!this.db.prepare('SELECT 1 FROM facade_withdrawals WHERE request_id=? AND due_ms<=?').get(id,at);
3770
+ }
3771
+ applyFacadeWithdrawalInTransaction(id,at=this.nowMs()) {
3772
+ if(!this.facadeWithdrawalDue(id,at)) return false;
3773
+ const row = this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
3774
+ const withdrew = row && ['queued','claimed'].includes(row.status);
3775
+ if (withdrew) {
3776
+ this.assertProtocolAvailable(id);
3777
+ const reason = 'facade_cancelled';
3778
+ this.cancelInTransaction(id,reason);
3779
+ if (this.isProtocolJob(id)) this.protocolEventInTransaction(id,'cancelled',{reason});
3780
+ }
3781
+ this.db.prepare('DELETE FROM facade_withdrawals WHERE request_id=?').run(id);
3782
+ return !!withdrew;
3783
+ }
3449
3784
  cancel(id,reason=null,ctx=null,ownerToken=null) {
3450
3785
  const workCancelled=this.pullQueue.cancel(id,reason);if(workCancelled)return workCancelled;
3451
3786
  return this.isProtocolJob(id)?cancelProtocolJob(this,id,reason,ownerToken,ctx):this.transaction(()=>this.cancelInTransaction(id,reason));
@@ -3455,7 +3790,8 @@ export class Store {
3455
3790
  const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found'); if(a.status==='finished') throw new Error('already finished');
3456
3791
  if(a.status!=='cancelled') {
3457
3792
  this.assertNoUncertainDelivery(id);
3458
- if(a.status==='claimed') this.laneFreed();
3793
+ const released=this.db.prepare('DELETE FROM admission_reservations WHERE request_id=?').run(id).changes>0;
3794
+ if(a.status==='claimed'||released) this.laneFreed();
3459
3795
  this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=?,cancelled_reason=? WHERE request_id=?").run(this.stamp(),reason,id);
3460
3796
  this.lifecycle(id,'withdraw_work','owner',reason,undefined,{scope:`job:${id}`,outcome:'done'});
3461
3797
  this.lifecycle(id,'cancelled','owner',reason);
@@ -3474,6 +3810,7 @@ export class Store {
3474
3810
  if(this.isProtocolJob(id)) throw new Error('protocol jobs require keyed /cancel with command_key and expected_revision');
3475
3811
  const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
3476
3812
  if(a.status!=='queued') return {request_id:id,status:a.status,cancelled:false};
3813
+ if(this.db.prepare('DELETE FROM admission_reservations WHERE request_id=?').run(id).changes>0) this.laneFreed();
3477
3814
  this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=? WHERE request_id=? AND status='queued'").run(this.stamp(),id);
3478
3815
  this.lifecycle(id,'withdraw_work','owner',null,undefined,{scope:`job:${id}`,outcome:'done'});
3479
3816
  this.lifecycle(id,'cancelled','owner');
@@ -3620,7 +3957,12 @@ export class Store {
3620
3957
  }
3621
3958
  paused() { return this.db.prepare('SELECT paused_at,reason FROM operator_state WHERE id=1').get().paused_at !== null; }
3622
3959
  // Claims reopening restarts the skip clock: time claims were refused is not time the worker passed a job over.
3623
- restartSkipClock() { this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE status='queued'").run(); }
3960
+ restartSkipClock({releaseReservations=false}={}) {
3961
+ return this.inTransaction(()=>{
3962
+ this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE status='queued'").run();
3963
+ if(releaseReservations&&this.db.prepare('DELETE FROM admission_reservations').run().changes>0) this.laneFreed();
3964
+ });
3965
+ }
3624
3966
  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}; }); }
3625
3967
  suppressStaleQuestion(row) {
3626
3968
  if(!row||!['blocker','wait'].includes(row.kind)||!row.body) return false;
@@ -3971,7 +4313,8 @@ export class Store {
3971
4313
  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);
3972
4314
  const liveQueued=this.queuedRows().filter(row=>row.target_worker===worker);
3973
4315
  const queuedNormal=liveQueued.filter(row=>row.priority==='normal').length;
3974
- 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}];
4316
+ const hold=this.holdingBreak(worker);
4317
+ return [worker,{scope:'worker',...(hold?{worker_break:{active:true,source:hold.source,since:hold.since,...this.breakForecast(hold.id)}}:{}),...(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}];
3975
4318
  }));
3976
4319
  dispatch.by_worker=Object.fromEntries([...this.workers.workers.keys()].sort().map(worker=>{
3977
4320
  const evidence=by_worker[worker].capacity;