@tnunamak/dalan 0.8.0 → 0.8.1

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
@@ -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';
@@ -50,7 +50,7 @@ function waiterOwnerGone(attemptId) {
50
50
  return !!(owner.boot&&owner.start&&current.boot&&current.start&&(owner.boot!==current.boot||owner.start!==current.start));
51
51
  }
52
52
 
53
- const SUPPORTED_SCHEMA_VERSION = 69;
53
+ const SUPPORTED_SCHEMA_VERSION = 72;
54
54
  const monotonicMs=()=>Number(process.hrtime.bigint())/1e6;
55
55
  function systemBootId() {
56
56
  if(process.platform!=='linux') return null;
@@ -80,6 +80,7 @@ function unsupportedSchemaVersion(found) {
80
80
  }
81
81
 
82
82
  // Owner decisions on a finished result, in the words the CLI takes. 'stale' is only ever written by the sweep.
83
+ 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
84
  export const decisionTypes=['accepted','applied','useful_no_change','useful_negative','not_useful','stale'];
84
85
  export const MAX_INTEGRATION_PATCH_BYTES=262144;
85
86
  import os from 'node:os';
@@ -110,7 +111,7 @@ const storedMeta=(meta,legacy)=>({...meta,objective_key:storedObjectiveKey(meta.
110
111
  function submitIntentDigest(identity,delivery,environmentId,review,priority,meta,targetWorker,execution,requiredCapabilities,destinationRevision=null,legacyFixNames=true) {
111
112
  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
113
  }
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};
114
+ const defaultRedeliveryLimits={intervalMs:600000,maxCount:3,silenceMs:1200000,claimIdleWarningMs:900000,leaseMs:3600000,workerClaimLeaseMs:{},laneCapacity:6,rewakeMs:90000,rewakeWindowMs:7200000,rewakeStaleMs:1200000,breakSilenceMs:1200000,breakProbeMs:1800000,maxClaimsPerHour:90,maxToolCallsPerHour:1000,maxToolCallsPer24h:10000,maxResponseBytesPerHour:8000000,maxResponseBytesPer24h:100000000};
114
115
  const HOUR=3600000, iso=ms=>new Date(ms).toISOString();
115
116
  export const QUEUE_WINDOW=Object.freeze({minSamples:5,factor:3,minMs:15*60000,maxMs:12*HOUR});
116
117
  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')");
@@ -165,6 +166,10 @@ export function loadRedeliveryLimits(file=defaultPath(os.homedir(),'.config/dot-
165
166
  const leaseMs=leaseKey?value[leaseKey]:defaultRedeliveryLimits.leaseMs;
166
167
  if(!Number.isInteger(silenceMs)||silenceMs<60000||silenceMs>86400000) throw new Error('invalid pause_suspected_silence_ms');
167
168
  if(!Number.isInteger(leaseMs)||leaseMs<60000||leaseMs>604800000) throw new Error(`invalid ${leaseKey}`);
169
+ const workerClaimLeaseMs=value.worker_claim_lease_ms??{};
170
+ if(value.worker_claim_lease_ms===null||typeof workerClaimLeaseMs!=='object'||Array.isArray(workerClaimLeaseMs)||
171
+ Object.entries(workerClaimLeaseMs).some(([worker,ms])=>!/^[a-z][a-z0-9_-]{0,31}$/.test(worker)||!Number.isInteger(ms)||ms<60000||ms>604800000))
172
+ throw new Error('invalid worker_claim_lease_ms');
168
173
  // Denominator of utilization metrics: how many lanes the worker can work in parallel. Independent of the claim cap (max_claimed_outer_assignments).
169
174
  // worker_* limits keys are the current names; the dot_* names are read as aliases so existing files keep working.
170
175
  const laneCapacity=value.worker_lane_capacity??value.dot_lane_capacity??defaultRedeliveryLimits.laneCapacity;
@@ -196,7 +201,7 @@ export function loadRedeliveryLimits(file=defaultPath(os.homedir(),'.config/dot-
196
201
  if(!Number.isInteger(maxResponseBytesPerHour)||maxResponseBytesPerHour<100000||maxResponseBytesPerHour>1000000000) throw new Error('invalid max_response_bytes_per_hour');
197
202
  const maxResponseBytesPer24h=value.max_response_bytes_per_24h??defaultRedeliveryLimits.maxResponseBytesPer24h;
198
203
  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};
204
+ return {intervalMs,maxCount,silenceMs,claimIdleWarningMs,leaseMs,workerClaimLeaseMs,laneCapacity,rewakeMs,rewakeWindowMs,rewakeStaleMs,breakSilenceMs,breakProbeMs,maxClaimsPerHour,maxToolCallsPerHour,maxToolCallsPer24h,maxResponseBytesPer24h,maxResponseBytesPerHour};
200
205
  }
201
206
 
202
207
  // Gates that cap one rolling hour. They hold background work before agent-requested work (see rollingUsage).
@@ -350,10 +355,20 @@ export class Store {
350
355
  markProfileModeSeen() { this.db.prepare("INSERT INTO bridge_state(key,value) VALUES('workers_profile_seen','1') ON CONFLICT(key) DO NOTHING").run(); }
351
356
  // Record one lifecycle event; callers run it inside the transaction of the state change it describes.
352
357
  // 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)) {
358
+ // Control events (controlTypes) also carry the scope they acted on and an outcome: extra={scope,outcome}.
359
+ 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
360
  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
361
  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);
362
+ 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);
363
+ }
364
+ // Record a control request (detach, interrupt_foreground, withdraw_work, revoke_grant) with the scope it named.
365
+ // The outcome is 'unknown' unless the caller holds an observation (confirmed). A denial is a request that did not take
366
+ // effect as asked, and says nothing about what already stopped, so it is unknown too: never success.
367
+ recordControl(id,type,{scope,confirmed=false,denied=null,actor='owner',reason=null}={}) {
368
+ if(!controlTypes.includes(type)) throw new Error(`not a control type: ${type}`);
369
+ if(typeof scope!=='string'||!scope.trim()) throw new Error('a control event needs a scope');
370
+ if(confirmed&&denied) throw new Error('a control request cannot be both denied and confirmed');
371
+ return this.inTransaction(()=>this.lifecycle(id,type,actor,[reason,denied].filter(Boolean).join('; ')||null,undefined,{scope:scope.trim(),outcome:confirmed?'confirmed':'unknown'}));
357
372
  }
358
373
  migrate() {
359
374
  this.transaction(() => {
@@ -948,6 +963,42 @@ export class Store {
948
963
  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
964
  this.db.exec('PRAGMA user_version=69;');
950
965
  }
966
+ if(version<70) {
967
+ 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);`);
968
+ 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)');
969
+ this.db.exec('PRAGMA user_version=70;');
970
+ }
971
+ if(version<71) {
972
+ // A correction links to the job it revises (C1). The link cancels nothing: the prior job runs to its own terminal state,
973
+ // and its result is judged against this table when the owner decides. input_revision copies meta.revision of the
974
+ // correction when it sent one. 71 follows C3 (69) and C2 (70) on main; renumbering at merge changes this
975
+ // line, the user_version below and SUPPORTED_SCHEMA_VERSION.
976
+ this.db.exec(`CREATE TABLE IF NOT EXISTS job_revisions(
977
+ request_id TEXT PRIMARY KEY REFERENCES assignments(request_id),
978
+ prior_id TEXT NOT NULL REFERENCES assignments(request_id),
979
+ input_revision TEXT,
980
+ at TEXT NOT NULL,
981
+ CHECK(request_id<>prior_id));
982
+ CREATE INDEX IF NOT EXISTS job_revisions_prior ON job_revisions(prior_id);
983
+ -- A patch is applied in two phases so that no decision is recorded before the effect: 'applying' reserves it (the
984
+ -- stale check is made here), the CLI writes the patch, then 'confirmed' records the decision or 'released' gives it up.
985
+ -- A row left in 'applying' is an apply that may or may not have happened. attempt is the fencing token of the run that
986
+ -- holds the reservation: every reserve mints a new one, and a confirm or release must present the current one.
987
+ CREATE TABLE IF NOT EXISTS apply_reservations(
988
+ request_id TEXT PRIMARY KEY REFERENCES assignments(request_id),
989
+ state TEXT NOT NULL CHECK(state IN ('applying','confirmed','released')),
990
+ reserved_at TEXT NOT NULL,
991
+ resolved_at TEXT,
992
+ reason TEXT,
993
+ attempt TEXT);
994
+ PRAGMA user_version=71;`);
995
+ }
996
+ if(version<72) {
997
+ // Typed control events: wake_held and the control vocabulary join the lifecycle types, and each event may carry the
998
+ // scope it acted on and an outcome. See addControlColumns for the table rebuild.
999
+ addControlColumns(this.db);
1000
+ this.db.exec('PRAGMA user_version=72;');
1001
+ }
951
1002
  // Which spelling of the fix-loop source this database stores. Schemas created before the rename list the earlier
952
1003
  // spelling in the CHECK constraint on assignments.source; newer schemas list only the neutral one.
953
1004
  this.legacyFixNames=!!this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='assignments' AND instr(sql,?)>0").get(`'${legacyFixLoopName}'`);
@@ -1214,7 +1265,7 @@ export class Store {
1214
1265
  if(result?.destination_refusal)throw destinationError(result.destination_refusal);
1215
1266
  return result;
1216
1267
  }
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) {
1268
+ checkRetry(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, priority='normal', meta=null, identity=payload, targetWorker=undefined, execution=null, requiredCapabilities=null, commandKey=null, supersedes=null, destinationRevision=null, revises=null) {
1218
1269
  validateSubmitKey(commandKey);
1219
1270
  const m=normalizeMeta(meta);
1220
1271
  const delivery=typeof deliveryOrThreadId==='string'?{mode:'t3',threadId:deliveryOrThreadId}:deliveryOrThreadId;
@@ -1228,8 +1279,22 @@ export class Store {
1228
1279
  const targetId=supersedes?.target_id??null;
1229
1280
  const previous=this.db.prepare('SELECT target_id FROM submit_supersedes WHERE request_id=?').get(payload.request_id);
1230
1281
  if(targetId===payload.request_id) throw new Error('supersede_cycle');
1282
+ // A correction names the job it revises and proves the owner capability of that job, as a supersede does. It cancels nothing.
1283
+ if(revises!==null) {
1284
+ if(!revises||typeof revises!=='object'||Array.isArray(revises)||Object.keys(revises).some(k=>!['prior_id','prior_token'].includes(k))||
1285
+ typeof revises.prior_id!=='string'||!/^[-\w]{8,128}$/.test(revises.prior_id)||typeof revises.prior_token!=='string') throw new Error('invalid revises: use {prior_id, prior_token}');
1286
+ if(supersedes) throw new Error('revises_and_supersedes: a correction does not cancel its prior job; send one of them');
1287
+ if(revises.prior_id===payload.request_id) throw new Error('revises_cycle');
1288
+ const prior=this.db.prepare('SELECT revision FROM assignments WHERE request_id=?').get(revises.prior_id);
1289
+ if(!prior) throw new Error('revises_prior_not_found');
1290
+ this.owner(revises.prior_id,revises.prior_token);
1291
+ // The same revision under another request_id is a duplicate in the metrics, not a correction.
1292
+ if(m.revision!==null&&prior.revision!==null&&canonicalMetaValue('revision',prior.revision)===canonicalMetaValue('revision',m.revision)) throw new Error('revises_same_revision: a correction must carry a different --revision (meta.revision) from the job it revises');
1293
+ }
1294
+ const priorId=revises?.prior_id??null;
1295
+ const previousRevision=this.db.prepare('SELECT prior_id FROM job_revisions WHERE request_id=?').get(payload.request_id);
1231
1296
  // Both capabilities are required even when returning an already-committed receipt.
1232
- if(old&&(supersedes||previous)) this.owner(payload.request_id,ownerToken);
1297
+ if(old&&(supersedes||previous||revises||previousRevision)) this.owner(payload.request_id,ownerToken);
1233
1298
  let target;
1234
1299
  if(supersedes) {
1235
1300
  target=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(targetId);
@@ -1261,16 +1326,22 @@ export class Store {
1261
1326
  if(commandKey!==null) {
1262
1327
  if(!command||command.key_digest!==hash(commandKey)) throw new Error('EXISTS: assignment already submitted under another command');
1263
1328
  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');
1329
+ if((previous?.target_id??null)!==targetId||(previousRevision?.prior_id??null)!==priorId||command.owner_hash!==ownerHash||command.intent_digest!==intent) throw new Error('KEY_CONFLICT: command intent changed');
1265
1330
  return {...JSON.parse(command.receipt),duplicate:true,...(approval?{destination_approval:approval}:{})};
1266
1331
  }
1267
1332
  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');
1333
+ if ((previous?.target_id??null)!==targetId || (previousRevision?.prior_id??null)!==priorId || (targetWorker!==undefined&&old.target_worker!==targetWorker) || (execution!==null&&old.execution!==execution) || (requiredCapabilities!==null&&old.required_capabilities!==JSON.stringify(requiredCapabilities)) || old.payload_hash!==payloadHash || old.delivery!==deliveryValue || old.environment_id!==(environmentId??'') || old.owner_hash!==ownerHash || !!old.review!==!!review || old.priority!==priority || metaFields.some(k=>old[k]!=null&&m[k]!=null&&canonicalMetaValue(k,old[k])!==canonicalMetaValue(k,m[k]))) throw new Error('request_id conflict');
1269
1334
  return {request_id:payload.request_id,status:old.status,duplicate:true,...(approval?{destination_approval:approval}:{})};
1270
1335
  }
1271
1336
  // identity: the assignment as the submitter sent it, when the stored payload differs (scope narrowing); a retry then still matches.
1337
+ relationshipForSubmission(worker,relationshipId=null) {
1338
+ const relationship=this.db.prepare('SELECT * FROM relationships WHERE counterpart_ref=? ORDER BY created_at DESC, rowid DESC LIMIT 1').get(worker??'dot');
1339
+ if(relationshipId!==null&&relationshipId!==relationship?.relationship_id) throw new Error('relationship_mismatch');
1340
+ if(relationship?.ended_at) throw new Error('relationship_ended');
1341
+ return relationship;
1342
+ }
1272
1343
  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) {
1344
+ submitInTransaction(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, preflight=null, priority='normal', meta=null, identity=payload, maxQueued=null, targetWorker=undefined, execution=null, defaultExecution='host', requiredCapabilities=null, defaultValidUntil=null, commandKey=null, supersedes=null, destinationRevision=null, inheritedOwnerHash=null, parentGeneration=null, relationshipId=null, revises=null) {
1274
1345
  if(!this.db.isTransaction) throw new Error('transaction_required');
1275
1346
  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
1347
  const protocol=!this.hasAssignment(payload.request_id)&&Object.hasOwn(payload,'protocol')?validateProtocol(payload.protocol):null;
@@ -1280,8 +1351,17 @@ export class Store {
1280
1351
  if(!delivery||!['t3','none'].includes(delivery.mode)||delivery.mode==='t3'&&!delivery.threadId) throw new Error('invalid delivery');
1281
1352
  const m=normalizeMeta(meta),threadId=delivery.threadId??'',deliveryValue=delivery.mode==='t3'?`t3:${threadId}`:'none';
1282
1353
  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);
1354
+ const retry=this.checkRetry(payload,delivery,environmentId,ownerToken,review,priority,meta,identity,targetWorker,execution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises);
1284
1355
  if(retry) return retry;
1356
+ let relationship;
1357
+ if(inheritedOwnerHash) {
1358
+ const order=this.pullQueue.row(payload.request_id);
1359
+ if(!order||order.owner_hash!==inheritedOwnerHash) throw new Error('invalid policy work owner');
1360
+ const relationships=JSON.parse(order.options).relationships;
1361
+ if(relationships&&!Object.hasOwn(relationships,targetWorker)) throw new Error('invalid policy relationship binding');
1362
+ const bound=relationships?.[targetWorker]??null;
1363
+ relationship=bound?{relationship_id:bound}:null;
1364
+ } else relationship=this.relationshipForSubmission(targetWorker,relationshipId);
1285
1365
  const id=payload.request_id, body=JSON.stringify(payload),payloadHash=hash(JSON.stringify(canonical(identity))),ownerHash=inheritedOwnerHash??hash(ownerToken);
1286
1366
  // checkRetry validated this target in the same transaction; only counts containing it gain room.
1287
1367
  const supersededId=supersedes?.target_id??null;
@@ -1324,6 +1404,7 @@ export class Store {
1324
1404
  // The target is a column, not payload: an omitted worker means 'dot'.
1325
1405
  this.db.prepare('INSERT INTO assignments(request_id,payload,payload_hash,thread_id,environment_id,status,created_at,owner_hash,review,delivery,priority,objective_key,revision,task_kind,source,target_worker,execution,required_capabilities) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,body,payloadHash,threadId,environmentId??'','queued',this.stamp(),ownerHash,review?1:0,deliveryValue,priority,...metaFields.map(k=>k==='source'?toStoredSource(m[k],this.legacyFixNames):m[k]),targetWorker??'dot',execution??defaultExecution,requiredCapabilities?JSON.stringify(requiredCapabilities):null);
1326
1406
  if(typeof parentGeneration==='string')this.db.prepare('UPDATE assignments SET parent_generation=? WHERE request_id=?').run(parentGeneration,id);
1407
+ if(relationship) this.db.prepare('UPDATE assignments SET relationship_id=? WHERE request_id=?').run(relationship.relationship_id,id);
1327
1408
  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
1409
  const requestedValidUntil=validUntilOf(payload);
1329
1410
  const mayUseDefault=priority==='normal'&&!this.paused()&&!((targetWorker??'dot')==='dot'&&this.holdingBreak());
@@ -1342,6 +1423,11 @@ export class Store {
1342
1423
  this.db.prepare('INSERT INTO submit_supersedes(request_id,target_id,created_at) VALUES(?,?,?)').run(id,supersedes.target_id,this.stamp());
1343
1424
  this.cancelInTransaction(supersedes.target_id,'superseded');
1344
1425
  }
1426
+ if(revises) {
1427
+ // The link and the note commit with the correction. A retry returned above, so neither is written twice.
1428
+ this.db.prepare('INSERT INTO job_revisions(request_id,prior_id,input_revision,at) VALUES(?,?,?,?)').run(id,revises.prior_id,m.revision,this.stamp());
1429
+ this.announceRevisionInTransaction(revises.prior_id,id,m.revision);
1430
+ }
1345
1431
  for (const sub of this.activeSubscriptions()) this.submitWake(id,sub);
1346
1432
  const receipt={request_id:id,status:'queued',duplicate:false,...(protocol?{revision:1}:{}),...this.destinationFields(id)};
1347
1433
  if(commandKey!==null) {
@@ -1423,7 +1509,8 @@ export class Store {
1423
1509
  if(!ctx||typeof ctx.key!=='string'||!ctx.key||!protocolNat(ctx.revision)||typeof mutate!=='function')protocolError('command_context_required');
1424
1510
  if(ctx.epoch!==undefined&&ctx.epoch!==claim.epoch)protocolError('stale_authority');
1425
1511
  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);
1512
+ key:ctx.key,expectedRevision:ctx.revision,operation:ctx.operation,args:ctx.args},mutate,
1513
+ {leaseCapMs:this.workerClaimLeaseCap(worker)});
1427
1514
  }
1428
1515
  setClaimDeadlineInTransaction(id,leaseMs) {
1429
1516
  const activity=this.db.prepare('SELECT last_claim_activity_at FROM claims WHERE request_id=?').get(id)?.last_claim_activity_at;
@@ -1432,10 +1519,21 @@ export class Store {
1432
1519
  this.db.prepare('UPDATE claims SET lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=?')
1433
1520
  .run(iso(deadline),this.leaseBootId,this.leaseBootId?this.monotonicNow()+leaseMs:null,id);
1434
1521
  }
1522
+ workerClaimLeaseCap(worker) {
1523
+ const caps=this.limits.workerClaimLeaseMs;
1524
+ return caps&&Object.hasOwn(caps,worker)?caps[worker]:Infinity;
1525
+ }
1526
+ cappedClaimLeaseMs(leaseMs,worker) {
1527
+ 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}`);
1528
+ return Math.min(leaseMs,this.workerClaimLeaseCap(worker));
1529
+ }
1435
1530
  renewClaim(id,claimId,leaseMs,ctx,subject='local-principal',worker='dot',connectionId=null) {
1531
+ if(!Number.isInteger(leaseMs)||leaseMs<1||leaseMs>this.limits.leaseMs)protocolError('invalid_lease');
1532
+ const requestedLeaseMs=leaseMs;
1533
+ leaseMs=Math.min(leaseMs,this.workerClaimLeaseCap(worker));
1436
1534
  return this.transaction(()=>{
1437
1535
  const receipt=this.protocolMutationInTransaction(id,claimId,subject,worker,
1438
- {...ctx,operation:'renew',args:{leaseMs}},({leaseUntil})=>{
1536
+ {...ctx,operation:'renew',args:{leaseMs:requestedLeaseMs}},({leaseUntil})=>{
1439
1537
  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
1538
  .run(leaseMs,iso(leaseUntil),this.leaseBootId,this.leaseBootId?this.monotonicNow()+leaseMs:null,id,claimId);
1441
1539
  const claim=this.assertClaim(id,claimId,subject,worker);
@@ -1820,10 +1918,11 @@ export class Store {
1820
1918
  this.refreshClaimActivity(id,claimId);
1821
1919
  }
1822
1920
  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);
1921
+ const at=this.stamp(), claim=this.db.prepare('SELECT lease_ms,worker FROM claims WHERE request_id=? AND claim_id=?').get(id,claimId);
1922
+ const leaseMs=Math.min(claim?.lease_ms??this.limits.leaseMs,this.workerClaimLeaseCap(claim?.worker));
1824
1923
  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);
1924
+ else this.db.prepare('UPDATE claims SET last_claim_activity_at=?,lease_ms=?,lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=? AND claim_id=?')
1925
+ .run(at,leaseMs,iso(Date.parse(at)+leaseMs),this.leaseBootId,this.leaseBootId?this.monotonicNow()+leaseMs:null,id,claimId);
1827
1926
  }
1828
1927
  // 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
1928
  liveHeldClaim(id,claimId,subject,worker) {
@@ -2081,8 +2180,9 @@ export class Store {
2081
2180
  const watch=this.db.prepare('SELECT deadline,state,updated_at,notification_id FROM watches WHERE request_id=?').get(id) || null;
2082
2181
  const supersedes=this.db.prepare('SELECT target_id AS request_id,created_at FROM submit_supersedes WHERE request_id=?').get(id)??null;
2083
2182
  const superseded_by=this.db.prepare('SELECT request_id,created_at FROM submit_supersedes WHERE target_id=?').get(id)??null;
2183
+ 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;
2084
2184
  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)}))};
2185
+ return {...this.destinationFields(id),...(this.pullQueue.row(id)?{work_order_id:this.pullQueue.row(id).work_order_id,child_request_id:id}:{}),request_id:id,supersedes,superseded_by,revises,revised_by:this.newerRevision(id),apply:this.applyState(id),target_worker:a.target_worker,assignment:JSON.parse(a.payload),delivery_mode:a.delivery,t3_muted:this.deliveryMuted(id),thread_id:a.thread_id||null,environment_id:a.environment_id||null,parent_generation:a.parent_generation??null,status:a.status,execution:a.execution,required_capabilities:a.required_capabilities?JSON.parse(a.required_capabilities):[],review:!!a.review,created_at:a.created_at,valid_until:a.valid_until??null,valid_until_source:a.valid_until_source??null,expiry_requeues:a.expiry_requeues??0,...this.failureFields(id),cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancellation_requested:!!a.cancelled_at,authority_revoked:authorityRevoked,...this.sandboxStop(id,authorityRevoked),claim,progress,lifecycle_events:this.db.prepare("SELECT type,at,actor,reason FROM lifecycle_events WHERE request_id=? ORDER BY id").all(id),report:report??null,late_evidence,delivery,watch,owner_notes:this.ownerNotes(id),worker_break_notices:this.breakNotices(id),claim_denied:this.claimDenial(id),skipped_by_worker:a.skipped_at?{at:a.skipped_at,listed_count:a.listed_count,passed_over:a.passed_over}:null,pr_preflights:this.db.prepare("SELECT phase,evidence FROM pr_preflights WHERE request_id=? ORDER BY CASE phase WHEN 'submit' THEN 0 ELSE 1 END").all(id).map(row=>({phase:row.phase,...JSON.parse(row.evidence)}))};
2086
2186
  }
2087
2187
  recordPrPreflight(id,phase,assignment,evidence,replace=false) {
2088
2188
  assertPreflight(assignment,evidence,this.nowMs());
@@ -2183,7 +2283,8 @@ export class Store {
2183
2283
  if(!question||question.answered_at===null||question.consumed_at!==null||question.epoch!==wake.epoch) return false;
2184
2284
  try { this.assertQuestionGrant(row.request_id,question);return true; } catch { return false; }
2185
2285
  }
2186
- note(id,text) { return this.transaction(() => {
2286
+ note(id,text) { return this.transaction(() => this.noteInTransaction(id,text)); }
2287
+ noteInTransaction(id,text) {
2187
2288
  this.assertProtocolAvailable(id);
2188
2289
  validateOwnerNote(text,this.ownerNotes(id));
2189
2290
  const assignment=this.db.prepare('SELECT payload FROM assignments WHERE request_id=?').get(id);
@@ -2196,7 +2297,15 @@ export class Store {
2196
2297
  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
2298
  }
2198
2299
  return {request_id:id,...note};
2199
- }); }
2300
+ }
2301
+ // 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
2302
+ // as they were. An exhausted note budget skips only the note: the link alone makes the result stale.
2303
+ announceRevisionInTransaction(priorId,successorId,inputRevision) {
2304
+ if(!['queued','claimed'].includes(this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(priorId).status)) return;
2305
+ 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.`;
2306
+ try { validateOwnerNote(text,this.ownerNotes(priorId)); } catch { return; }
2307
+ this.noteInTransaction(priorId,text);
2308
+ }
2200
2309
  tell(text,worker='dot') { return this.transaction(() => {
2201
2310
  if(worker==='pool') throw new Error('worker \"pool\" is not supported');
2202
2311
  const messageId=`msg_${randomUUID()}`, preview=text.slice(0,200), createdAt=this.stamp();
@@ -2390,7 +2499,7 @@ export class Store {
2390
2499
  }
2391
2500
  claimInTransaction(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,connectionId=null) {
2392
2501
  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}`);
2502
+ leaseMs=this.cappedClaimLeaseMs(leaseMs,worker);
2394
2503
  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
2504
  if(!this.mayAct(worker,id)) throw new Error('assignment not found');
2396
2505
  if (this.paused()) throw new Error(pausedClaimMessage);
@@ -2489,6 +2598,7 @@ export class Store {
2489
2598
  if(reason==='lease_expired') reason=Store.expirySummary(old);
2490
2599
  this.db.prepare("UPDATE claims SET state='abandoned',abandoned_at=?,abandon_reason=? WHERE request_id=?").run(at,reason,id);
2491
2600
  this.db.prepare("UPDATE assignments SET status='queued' WHERE request_id=?").run(id);
2601
+ this.lifecycle(id,'detach',actor,reason,old,{scope:`claim:${old.claim_id}@${old.epoch}`,outcome:'done'});
2492
2602
  this.lifecycle(id,'abandoned',actor,reason,old);
2493
2603
  this.lifecycle(id,'queued',actor,'requeued',null);
2494
2604
  if(this.isProtocolJob(id)) {
@@ -2705,6 +2815,7 @@ export class Store {
2705
2815
  this.assertNoUncertainDelivery(id);
2706
2816
  if(a.status==='claimed') this.laneFreed();
2707
2817
  this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=?,cancelled_reason=? WHERE request_id=?").run(this.stamp(),reason,id);
2818
+ this.lifecycle(id,'withdraw_work','owner',reason,undefined,{scope:`job:${id}`,outcome:'done'});
2708
2819
  this.lifecycle(id,'cancelled','owner',reason);
2709
2820
  this.db.prepare("UPDATE notifications SET state='suppressed' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
2710
2821
  this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
@@ -2722,6 +2833,7 @@ export class Store {
2722
2833
  const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
2723
2834
  if(a.status!=='queued') return {request_id:id,status:a.status,cancelled:false};
2724
2835
  this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=? WHERE request_id=? AND status='queued'").run(this.stamp(),id);
2836
+ this.lifecycle(id,'withdraw_work','owner',null,undefined,{scope:`job:${id}`,outcome:'done'});
2725
2837
  this.lifecycle(id,'cancelled','owner');
2726
2838
  this.db.prepare("UPDATE notifications SET state='suppressed' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
2727
2839
  this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
@@ -2829,10 +2941,14 @@ export class Store {
2829
2941
  // queue like any quieted one, and held_kind remembers what it was so releaseHeld can put it back once the parent runs again.
2830
2942
  // One transaction: held_kind and the quiet state land together or not at all. A crash between two separate writes would
2831
2943
  // leave a sending row that recoverSends turns into uncertain, which heldDeliveries skips.
2944
+ // The same transaction writes the typed wake_held event, once per hold: a row that is already held no longer matches the
2945
+ // UPDATE (quietDelivery moved its kind to 'wait'), so a repeat hold changes nothing and writes nothing.
2832
2946
  holdDelivery(id,reason) {
2833
2947
  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);
2948
+ 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
2949
  this.quietDelivery(id,reason);
2950
+ const request=held&&this.db.prepare('SELECT request_id FROM notifications WHERE id=?').get(id)?.request_id;
2951
+ if(request) this.lifecycle(request,'wake_held','system','parent_stopped',undefined,{scope:`wake:${id}`,outcome:'unknown'});
2836
2952
  });
2837
2953
  }
2838
2954
  // 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
@@ -2943,8 +3059,16 @@ export class Store {
2943
3059
  cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancelled_by_owner:cancelActor==='owner',read:a.owner_read_at!==null,
2944
3060
  ...this.failureFields(id),
2945
3061
  unanswered_blocker:lastBlocker&&(lastAnswer===null||lastBlocker.created_at>lastAnswer)?{text:lastBlocker.note,at:lastBlocker.created_at}:null,
3062
+ held_wake:this.heldWake(id),
2946
3063
  };
2947
3064
  }
3065
+ // The oldest wake still held for this request, with the typed reason its wake_held event recorded. Reads only.
3066
+ heldWake(id) {
3067
+ 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);
3068
+ if(!row) return null;
3069
+ 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}`);
3070
+ return {kind:row.held_kind,reason:event?.reason??'parent_stopped',detail:row.last_error||null,since:event?.at??null,notification_id:row.id};
3071
+ }
2948
3072
  // Owner action for `dalan inbox --mark-read`: the same read marker as get, without fetching the result. True when it was unread.
2949
3073
  markInboxRead(id,via) { return this.transaction(() => {
2950
3074
  const status=this.get(id).status, v=this.ownerInbox(id);
@@ -2962,16 +3086,95 @@ export class Store {
2962
3086
  // Record a decision on a finished report. Append-only: a different decision is added and the latest wins; the same decision
2963
3087
  // again is a no-op. accepted and applied also write the 'accepted' event, not_useful the legacy reject event, so readers of
2964
3088
  // 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'}={}) {
3089
+ // The refusal is thrown after the transaction committed, so the stale row it wrote stays.
3090
+ decide(id,decision,opts={}) {
3091
+ const result=this.transaction(() => this.recordDecision(id,decision,opts));
3092
+ if(result.stale_refusal) throw staleRevisionError(result.stale_refusal);
3093
+ return result;
3094
+ }
3095
+ // The first correction of a job that was not withdrawn. A cancelled correction never carried the work, so it supersedes nothing.
3096
+ newerRevision(id) {
3097
+ 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);
3098
+ return row?{...row}:null;
3099
+ }
3100
+ // The refusal for a result whose job has a newer revision, or null. Records stale on an undecided result. Run it inside a transaction.
3101
+ staleRefusal(id,{record=true}={}) {
3102
+ const newer=this.newerRevision(id); if(!newer) return null;
3103
+ const recorded=record&&!this.latestDecision(id);
3104
+ 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());
3105
+ return {request_id:id,revised_by:newer.request_id,at:newer.at,recorded};
3106
+ }
3107
+ // Applying a patch is two phases, so that no decision is recorded before the patch is written. reserveApply is the fence: it
3108
+ // refuses when a newer revision exists. The caller then writes the patch, and calls confirmApply (records applied) or
3109
+ // releaseApply (the write failed; nothing is recorded). A reservation with neither is an apply that may or may not have
3110
+ // happened; it shows as uncertain in get, and a re-run resumes it. A correction after the reservation is new work.
3111
+ applyState(id) {
3112
+ const r=this.db.prepare('SELECT state,reserved_at,resolved_at,reason FROM apply_reservations WHERE request_id=?').get(id);
3113
+ if(!r) return null;
3114
+ if(r.state==='applying') return {state:'applying',uncertain:true,since:r.reserved_at};
3115
+ return r.state==='confirmed'?{state:'applied',at:r.resolved_at}:{state:'released',reason:r.reason,at:r.resolved_at};
3116
+ }
3117
+ // Every attempt, a first one or a resumed one, calls this and gets a new attempt token in the same transaction as the stale
3118
+ // check. An open reservation is taken over: the previous token is superseded and its confirm or release is refused. The stale
3119
+ // check always runs, before the already-applied shortcut and even when the caller found the patch already in its tree: a
3120
+ // revised job's result is never recorded accepted or applied. A refused takeover of an open reservation records nothing.
3121
+ reserveApply(id) {
3122
+ const result=this.transaction(() => {
3123
+ const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
3124
+ if(a.status!=='finished') throw new Error('only a finished assignment can be decided');
3125
+ const open=this.db.prepare("SELECT reserved_at FROM apply_reservations WHERE request_id=? AND state='applying'").get(id);
3126
+ const refusal=this.staleRefusal(id,{record:!open}); if(refusal) return {request_id:id,stale_refusal:refusal};
3127
+ if(!open&&this.latestDecision(id)?.decision==='applied') return {request_id:id,state:'applied',resumed:false};
3128
+ const at=this.stamp(), attempt=randomBytes(16).toString('hex');
3129
+ 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);
3130
+ return {request_id:id,state:'applying',resumed:!!open,since:at,attempt};
3131
+ });
3132
+ if(result.stale_refusal) throw staleRevisionError(result.stale_refusal);
3133
+ return result;
3134
+ }
3135
+ // The row the caller's token is checked against. A token that is not the current one is superseded: a later attempt took over,
3136
+ // the owner released the reservation, or the apply already finished.
3137
+ currentAttempt(id,attempt) {
3138
+ if(typeof attempt!=='string'||!attempt) throw new Error(`apply attempt token required for ${id}: reserve first`);
3139
+ const row=this.db.prepare('SELECT state,attempt FROM apply_reservations WHERE request_id=?').get(id);
3140
+ if(!row) throw new Error(`no open apply reservation for ${id}`);
3141
+ return {row,current:row.attempt===attempt};
3142
+ }
3143
+ confirmApply(id,{attempt,note=null,via='apply'}={}) { return this.transaction(() => {
3144
+ const {row,current}=this.currentAttempt(id,attempt);
3145
+ if(row.state==='confirmed'&&current) return {request_id:id,decision:'applied',duplicate:true,at:this.stamp()};
3146
+ if(row.state!=='applying') throw new Error(`no open apply reservation for ${id}`);
3147
+ if(!current) throw new Error(`superseded apply attempt for ${id}: not the current attempt; reserve again`);
3148
+ return this.recordDecision(id,'applied',{note,via,fenced:true});
3149
+ }); }
3150
+ // force is the owner giving up an uncertain reservation on purpose (the token may be lost); otherwise the current token is required.
3151
+ releaseApply(id,{attempt,reason=null,force=false}={}) { return this.transaction(() => {
3152
+ const row=this.db.prepare('SELECT state,attempt FROM apply_reservations WHERE request_id=?').get(id);
3153
+ if(!row) throw new Error(`no apply reservation for ${id}`);
3154
+ if(row.state==='confirmed') throw new Error(`${id} is already applied; a confirmed apply is not released`);
3155
+ if(row.state==='applying') {
3156
+ if(!force) { const {current}=this.currentAttempt(id,attempt); if(!current) throw new Error(`superseded apply attempt for ${id}: not the current attempt`); }
3157
+ 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);
3158
+ } else if(!force&&row.attempt!==attempt) throw new Error(`superseded apply attempt for ${id}: not the current attempt`);
3159
+ return {request_id:id,state:'released'};
3160
+ }); }
3161
+ recordDecision(id,decision,{note=null,actor='owner',via='cli',fenced=false}={}) {
2967
3162
  if(!decisionTypes.includes(decision)) throw new Error(`decision must be one of ${decisionTypes.join(', ')}`);
2968
3163
  const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
2969
3164
  if(a.status!=='finished') throw new Error('only a finished assignment can be decided');
2970
3165
  const latest=this.db.prepare('SELECT decision,actor FROM decisions WHERE request_id=? ORDER BY id DESC LIMIT 1').get(id);
2971
3166
  if(decision==='stale'&&(actor!=='system'||this.latestDecision(id))) return {request_id:id,decision:latest?.decision??null,duplicate:true};
3167
+ // An owner cannot accept or apply a result whose job has a newer revision. The check and the write share this transaction,
3168
+ // so a correction that commits first is always seen. It runs before the duplicate shortcut: accepting or applying again after a
3169
+ // correction is refused too. An undecided result is recorded stale; a decided one is left alone. A confirmed apply (fenced) was
3170
+ // checked when it was reserved, so a correction after the reservation is new work and does not block it.
3171
+ if(actor==='owner'&&!fenced&&(decision==='accepted'||decision==='applied')) {
3172
+ const refusal=this.staleRefusal(id); if(refusal) return {request_id:id,stale_refusal:refusal};
3173
+ }
2972
3174
  if(latest&&latest.decision===decision&&latest.actor===actor) return {request_id:id,decision,duplicate:true,at:this.stamp()};
2973
3175
  const at=this.stamp();
2974
3176
  this.db.prepare('INSERT INTO decisions(request_id,decision,note,actor,via,at) VALUES(?,?,?,?,?,?)').run(id,decision,note,actor,via,at);
3177
+ 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
3178
  if(actor==='owner') {
2976
3179
  this.consumeOnce(id,'decide');
2977
3180
  if(decision==='accepted'||decision==='applied') this.lifecycle(id,'accepted','owner',decision==='applied'?(note?`applied: ${note}`:'applied'):note);
@@ -3109,7 +3312,7 @@ export class Store {
3109
3312
  return [worker,{scope:'worker',counts:workerCounts,queued_expired:expired,queued_expired_requeued:requeued,active_claims:liveness.claimed_outer_count,queued_live:liveQueued,subscriptions_active:workerSubscriptions.length,capacity:this.workerCapacityEvidence(worker,workerSubscriptions,limits,capacity),last_call_at:liveness.last_worker_call_at,last_list_pending_at:liveness.last_list_pending_at,stale_claims:liveness.stale_claims,queue_classes:liveness.queue_classes,unclaimed_after_reannounce:liveness.unclaimed_after_reannounce,oldest_claim_age_ms:liveness.oldest_claim_age_ms,oldest_claim_progress_age_ms:liveness.oldest_claim_progress_age_ms,oldest_unclaimed_event_2xx_age_ms:liveness.oldest_unclaimed_event_2xx_age_ms,silence_ms:liveness.worker_silence_ms}];
3110
3313
  }));
3111
3314
  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)};
3315
+ 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)};
3113
3316
  }
3114
3317
  workerCapacityEvidence(worker,subscriptions,limits,capacity) {
3115
3318
  const byPrincipal=[...new Map(subscriptions.map(sub=>[sub.principal,sub])).values()];
package/src/workers.mjs CHANGED
@@ -12,6 +12,23 @@ const fail=message=>{throw new Error(`workers: ${message}`);};
12
12
  const object=(v,keys)=>{if(!v||typeof v!=='object'||Array.isArray(v)||Object.keys(v).some(k=>!keys.includes(k))) fail(`expected object with keys ${keys.join(', ')}`);};
13
13
  const text=v=>{if(typeof v!=='string'||!v||v.length>2048) fail('connection fields must be non-empty strings');return v;};
14
14
  const legacyWorker={connections:[],capabilities:new Set(['t3']),guidance:'resume'};
15
+ // Enrollment never revives an ended relationship. A new relationship requires an explicit future transition.
16
+ export function ensureWorkerRelationship(db,worker,pattern='outbound_only') {
17
+ db.prepare(`INSERT INTO relationships(relationship_id,my_roles,counterpart_ref,pattern,continuity,onward,created_at)
18
+ SELECT ?,?,?,?,?,?,? WHERE NOT EXISTS (SELECT 1 FROM relationships WHERE counterpart_ref=?)`)
19
+ .run(`rel_${randomUUID()}`,JSON.stringify(['requester']),worker,pattern,'unknown','none',new Date().toISOString(),worker);
20
+ }
21
+ // finish_handoff: true | {wait_ms}. A finishing worker is handed its next job in the reply, or waits up to wait_ms for one.
22
+ // ChatGPT documents no tool-call timeout and users report about 60 s, so the wait stays well below that.
23
+ export const FINISH_HANDOFF_WAIT_MS=20000, FINISH_HANDOFF_MAX_WAIT_MS=45000;
24
+ function parseFinishHandoff(value,name) {
25
+ if(value===undefined||value===false) return null;
26
+ if(value===true) return {waitMs:FINISH_HANDOFF_WAIT_MS};
27
+ object(value,['wait_ms']);
28
+ const waitMs=value.wait_ms===undefined?FINISH_HANDOFF_WAIT_MS:value.wait_ms;
29
+ if(!Number.isInteger(waitMs)||waitMs<0||waitMs>FINISH_HANDOFF_MAX_WAIT_MS) fail(`${name}.finish_handoff.wait_ms must be an integer from 0 to ${FINISH_HANDOFF_MAX_WAIT_MS}`);
30
+ return {waitMs};
31
+ }
15
32
  const repoPart=/^[A-Za-z0-9_.-]+$/;
16
33
  function validRepoName(repo) {
17
34
  if(typeof repo!=='string'||repo.split('/').length!==2) return false;
@@ -62,7 +79,8 @@ export function parseWorkers(value,{builtin=false,builtinConnectionIds}={}) {
62
79
  if(name==='pool'||name==='unknown') fail(`worker name "${name}" is reserved and unsupported`);
63
80
  if(!/^[a-z][a-z0-9_-]{0,31}$/.test(name)) fail('invalid worker name');
64
81
  if(Object.hasOwn(config??{},'pool')) fail(`${name}.pool is not supported`);
65
- object(config,['connections','capabilities','guidance','repos','repo_access','denied_repos','destination','workspaceAllowed','adapter']);
82
+ object(config,['connections','capabilities','guidance','repos','repo_access','denied_repos','destination','workspaceAllowed','adapter','finish_handoff']);
83
+ const finishHandoff=parseFinishHandoff(config.finish_handoff,name);
66
84
  if(Object.hasOwn(config,'adapter')&&(typeof config.adapter!=='string'||!Object.hasOwn(ADAPTER_QUALIFICATIONS,config.adapter))) fail(`${name}.adapter must name a qualified adapter: ${Object.keys(ADAPTER_QUALIFICATIONS).join(', ')}`);
67
85
  const repoSettings=normalizeRepoSettings(config,name);
68
86
  if(config.guidance!==undefined&&config.guidance!=='resume') fail(`${name}.guidance may only be "resume"`);
@@ -82,7 +100,7 @@ export function parseWorkers(value,{builtin=false,builtinConnectionIds}={}) {
82
100
  if(config.workspaceAllowed!==undefined&&typeof config.workspaceAllowed!=='boolean') fail(`${name}.workspaceAllowed must be boolean`);
83
101
  const caps=config.capabilities??[];
84
102
  if(!Array.isArray(caps)||caps.some(c=>c!=='t3')) fail('capabilities may only contain t3');
85
- workers.set(name,{connections,capabilities:new Set(caps),...(config.adapter!==undefined?{adapter:config.adapter}:{}),...(config.workspaceAllowed!==undefined?{workspaceAllowed:config.workspaceAllowed}:{}),...(config.guidance?{guidance:config.guidance}:{}),...repoSettings,
103
+ workers.set(name,{connections,capabilities:new Set(caps),...(config.adapter!==undefined?{adapter:config.adapter}:{}),...(config.workspaceAllowed!==undefined?{workspaceAllowed:config.workspaceAllowed}:{}),...(config.guidance?{guidance:config.guidance}:{}),...(finishHandoff?{finishHandoff}:{}),...repoSettings,
86
104
  ...(Object.hasOwn(config,'destination')?{destination:parseDestinationDeclaration(config.destination)}:{})});
87
105
  }
88
106
  if(!workers.size) fail('workers must not be empty');