@tnunamak/dalan 0.7.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/CHANGELOG.md +42 -0
- package/CONTRIBUTING.md +4 -0
- package/PROTOCOL.md +8 -0
- package/README.md +68 -28
- package/bin/dalan.mjs +1 -1
- package/bin/dot-worker.mjs +115 -16
- package/contracts/adapter-qualification.schema.json +170 -0
- package/docs/chatgpt-worker-onboarding.md +1 -1
- package/docs/local-agent-requester.md +46 -0
- package/docs/manual-setup.md +1 -1
- package/docs/operations.md +4 -3
- package/docs/pull-workers.md +1 -0
- package/docs/relationships.md +13 -0
- package/docs/service-setup.md +40 -17
- package/docs/setup-reference.md +1 -1
- package/docs/t3-integration.md +2 -0
- package/docs/t3-question-relationship.md +43 -0
- package/docs/t3-reverse-control.md +12 -8
- package/docs/t3-wake-fence-r4.md +42 -0
- package/docs/test-suite-isolation.md +205 -0
- package/docs/usage.md +14 -2
- package/docs/worker-clients.md +3 -1
- package/package.json +6 -3
- package/qualification/README.md +13 -0
- package/qualification/mcp.json +121 -0
- package/qualification/protocol-v0.json +127 -0
- package/src/admin-socket.mjs +2 -1
- package/src/answer-journal.mjs +200 -0
- package/src/auth-check.mjs +8 -2
- package/src/claim-command-ledger.mjs +3 -2
- package/src/cli-help.mjs +19 -10
- package/src/destinations/index.mjs +6 -0
- package/src/destinations/none.mjs +3 -0
- package/src/destinations/t3.mjs +63 -6
- package/src/execution.mjs +20 -2
- package/src/follow-current.mjs +4 -2
- package/src/gozar-routes.mjs +4 -3
- package/src/host-budget.mjs +17 -11
- package/src/host-execution-policy.mjs +2 -2
- package/src/host-stop-reverify.mjs +6 -4
- package/src/inbox.mjs +13 -3
- package/src/integrator.mjs +3 -1
- package/src/lifecycle.mjs +60 -2
- package/src/patch-apply.mjs +74 -13
- package/src/server.mjs +210 -34
- package/src/service-launchd.mjs +28 -8
- package/src/service-migrate-workers.mjs +12 -2
- package/src/service.mjs +52 -16
- package/src/status-summary.mjs +3 -0
- package/src/store.mjs +300 -34
- package/src/submission-policy.mjs +8 -4
- package/src/t3.mjs +21 -2
- package/src/tool-registry.mjs +54 -8
- package/src/workers.mjs +22 -3
- package/src/workspace.mjs +94 -15
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&¤t.boot&¤t.start&&(owner.boot!==current.boot||owner.start!==current.start));
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
-
const SUPPORTED_SCHEMA_VERSION =
|
|
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;
|
|
@@ -68,6 +68,8 @@ export function validateProtocol(value) {
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
const questionError=(code,message)=>Object.assign(new Error(`${code}: ${message}`),{code});
|
|
71
|
+
// A purpose other than clarification marks a question only a human may answer. SQLite cannot change a CHECK in place, so the schema 67 list below is the whole set.
|
|
72
|
+
export const QUESTION_PURPOSES=['clarification','human_decision','authentication','tool_permission'];
|
|
71
73
|
function validateQuestion(questionId,text) {
|
|
72
74
|
if(typeof questionId!=='string'||!/^[A-Za-z0-9_.:-]{1,128}$/.test(questionId)) throw new Error('invalid question_id');
|
|
73
75
|
if(arguments.length>1&&(typeof text!=='string'||!text.trim()||Buffer.byteLength(text)>4096)) throw new Error('question text must be 1-4096 UTF-8 bytes');
|
|
@@ -78,6 +80,7 @@ function unsupportedSchemaVersion(found) {
|
|
|
78
80
|
}
|
|
79
81
|
|
|
80
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}});
|
|
81
84
|
export const decisionTypes=['accepted','applied','useful_no_change','useful_negative','not_useful','stale'];
|
|
82
85
|
export const MAX_INTEGRATION_PATCH_BYTES=262144;
|
|
83
86
|
import os from 'node:os';
|
|
@@ -108,7 +111,7 @@ const storedMeta=(meta,legacy)=>({...meta,objective_key:storedObjectiveKey(meta.
|
|
|
108
111
|
function submitIntentDigest(identity,delivery,environmentId,review,priority,meta,targetWorker,execution,requiredCapabilities,destinationRevision=null,legacyFixNames=true) {
|
|
109
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})})));
|
|
110
113
|
}
|
|
111
|
-
const defaultRedeliveryLimits={intervalMs:600000,maxCount:3,silenceMs:1200000,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};
|
|
112
115
|
const HOUR=3600000, iso=ms=>new Date(ms).toISOString();
|
|
113
116
|
export const QUEUE_WINDOW=Object.freeze({minSamples:5,factor:3,minMs:15*60000,maxMs:12*HOUR});
|
|
114
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')");
|
|
@@ -155,11 +158,18 @@ export function loadRedeliveryLimits(file=defaultPath(os.homedir(),'.config/dot-
|
|
|
155
158
|
if(!Number.isInteger(intervalMs)||intervalMs<60000||intervalMs>86400000) throw new Error('invalid assignment_reannounce_interval_ms');
|
|
156
159
|
if(!Number.isInteger(maxCount)||maxCount<0||maxCount>10) throw new Error('invalid assignment_reannounce_max_count');
|
|
157
160
|
const silenceMs=value.pause_suspected_silence_ms??defaultRedeliveryLimits.silenceMs;
|
|
161
|
+
// Observational warning only: independent of lease expiry, takeover and cancellation.
|
|
162
|
+
const claimIdleWarningMs=value.claim_idle_warning_ms??defaultRedeliveryLimits.claimIdleWarningMs;
|
|
163
|
+
if(!Number.isInteger(claimIdleWarningMs)||claimIdleWarningMs<60000||claimIdleWarningMs>604800000) throw new Error('invalid claim_idle_warning_ms');
|
|
158
164
|
// A claim lease expires at last claim activity + leaseMs. stale_claim_ms is the legacy name, read only when claim_lease_ms is absent.
|
|
159
165
|
const leaseKey=value.claim_lease_ms!=null?'claim_lease_ms':value.stale_claim_ms!=null?'stale_claim_ms':null;
|
|
160
166
|
const leaseMs=leaseKey?value[leaseKey]:defaultRedeliveryLimits.leaseMs;
|
|
161
167
|
if(!Number.isInteger(silenceMs)||silenceMs<60000||silenceMs>86400000) throw new Error('invalid pause_suspected_silence_ms');
|
|
162
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');
|
|
163
173
|
// Denominator of utilization metrics: how many lanes the worker can work in parallel. Independent of the claim cap (max_claimed_outer_assignments).
|
|
164
174
|
// worker_* limits keys are the current names; the dot_* names are read as aliases so existing files keep working.
|
|
165
175
|
const laneCapacity=value.worker_lane_capacity??value.dot_lane_capacity??defaultRedeliveryLimits.laneCapacity;
|
|
@@ -191,7 +201,7 @@ export function loadRedeliveryLimits(file=defaultPath(os.homedir(),'.config/dot-
|
|
|
191
201
|
if(!Number.isInteger(maxResponseBytesPerHour)||maxResponseBytesPerHour<100000||maxResponseBytesPerHour>1000000000) throw new Error('invalid max_response_bytes_per_hour');
|
|
192
202
|
const maxResponseBytesPer24h=value.max_response_bytes_per_24h??defaultRedeliveryLimits.maxResponseBytesPer24h;
|
|
193
203
|
if(!Number.isInteger(maxResponseBytesPer24h)||maxResponseBytesPer24h<1000000||maxResponseBytesPer24h>10000000000) throw new Error('invalid max_response_bytes_per_24h');
|
|
194
|
-
return {intervalMs,maxCount,silenceMs,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};
|
|
195
205
|
}
|
|
196
206
|
|
|
197
207
|
// Gates that cap one rolling hour. They hold background work before agent-requested work (see rollingUsage).
|
|
@@ -345,10 +355,20 @@ export class Store {
|
|
|
345
355
|
markProfileModeSeen() { this.db.prepare("INSERT INTO bridge_state(key,value) VALUES('workers_profile_seen','1') ON CONFLICT(key) DO NOTHING").run(); }
|
|
346
356
|
// Record one lifecycle event; callers run it inside the transaction of the state change it describes.
|
|
347
357
|
// claim defaults to the claim in force (the active row); an explicit claim_id without epoch resolves its epoch from history.
|
|
348
|
-
|
|
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={}) {
|
|
349
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;
|
|
350
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';
|
|
351
|
-
this.db.prepare("INSERT INTO lifecycle_events(request_id,claim_id,epoch,type,at,actor,source,reason,worker) VALUES(?,?,?,?,?,?,'live'
|
|
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'}));
|
|
352
372
|
}
|
|
353
373
|
migrate() {
|
|
354
374
|
this.transaction(() => {
|
|
@@ -924,6 +944,61 @@ export class Store {
|
|
|
924
944
|
this.db.exec('PRAGMA user_version=65;');
|
|
925
945
|
}
|
|
926
946
|
if(version<66) { migratePullQueue(this.db); this.db.exec('PRAGMA user_version=66;'); }
|
|
947
|
+
if(version<67) {
|
|
948
|
+
// What a question asks for. Every row that exists now is a clarification, the only kind before this step.
|
|
949
|
+
// A historical fixture that dropped the post-54 tables has no job_questions to alter; every real database has one.
|
|
950
|
+
if(this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='job_questions'").get()&&!this.db.prepare("SELECT 1 FROM pragma_table_info('job_questions') WHERE name='purpose'").get()) this.db.exec("ALTER TABLE job_questions ADD COLUMN purpose TEXT NOT NULL DEFAULT 'clarification' CHECK(purpose IN ('clarification','human_decision','authentication','tool_permission'))");
|
|
951
|
+
this.db.exec('PRAGMA user_version=67;');
|
|
952
|
+
}
|
|
953
|
+
if(version<68) {
|
|
954
|
+
// The parent generation a destination recorded when the job was submitted. One opaque string: the destination
|
|
955
|
+
// module writes it (capture) and reads it (readGeneration); the Store never parses it. NULL means none was recorded
|
|
956
|
+
// (older rows, delivery none, policy-queue jobs).
|
|
957
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('assignments') WHERE name='parent_generation'").get()) this.db.exec('ALTER TABLE assignments ADD COLUMN parent_generation TEXT');
|
|
958
|
+
// The kind a notification had before a held parent moved it into the wait queue. Set only by holdDelivery.
|
|
959
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('notifications') WHERE name='held_kind'").get()) this.db.exec('ALTER TABLE notifications ADD COLUMN held_kind TEXT');
|
|
960
|
+
this.db.exec('PRAGMA user_version=68;');
|
|
961
|
+
}
|
|
962
|
+
if(version<69) {
|
|
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');
|
|
964
|
+
this.db.exec('PRAGMA user_version=69;');
|
|
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
|
+
}
|
|
927
1002
|
// Which spelling of the fix-loop source this database stores. Schemas created before the rename list the earlier
|
|
928
1003
|
// spelling in the CHECK constraint on assignments.source; newer schemas list only the neutral one.
|
|
929
1004
|
this.legacyFixNames=!!this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='assignments' AND instr(sql,?)>0").get(`'${legacyFixLoopName}'`);
|
|
@@ -1190,7 +1265,7 @@ export class Store {
|
|
|
1190
1265
|
if(result?.destination_refusal)throw destinationError(result.destination_refusal);
|
|
1191
1266
|
return result;
|
|
1192
1267
|
}
|
|
1193
|
-
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) {
|
|
1194
1269
|
validateSubmitKey(commandKey);
|
|
1195
1270
|
const m=normalizeMeta(meta);
|
|
1196
1271
|
const delivery=typeof deliveryOrThreadId==='string'?{mode:'t3',threadId:deliveryOrThreadId}:deliveryOrThreadId;
|
|
@@ -1204,8 +1279,22 @@ export class Store {
|
|
|
1204
1279
|
const targetId=supersedes?.target_id??null;
|
|
1205
1280
|
const previous=this.db.prepare('SELECT target_id FROM submit_supersedes WHERE request_id=?').get(payload.request_id);
|
|
1206
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);
|
|
1207
1296
|
// Both capabilities are required even when returning an already-committed receipt.
|
|
1208
|
-
if(old&&(supersedes||previous)) this.owner(payload.request_id,ownerToken);
|
|
1297
|
+
if(old&&(supersedes||previous||revises||previousRevision)) this.owner(payload.request_id,ownerToken);
|
|
1209
1298
|
let target;
|
|
1210
1299
|
if(supersedes) {
|
|
1211
1300
|
target=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(targetId);
|
|
@@ -1237,16 +1326,22 @@ export class Store {
|
|
|
1237
1326
|
if(commandKey!==null) {
|
|
1238
1327
|
if(!command||command.key_digest!==hash(commandKey)) throw new Error('EXISTS: assignment already submitted under another command');
|
|
1239
1328
|
const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??old.target_worker,execution??old.execution,requiredCapabilities,destinationRevision,this.legacyFixNames);
|
|
1240
|
-
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');
|
|
1241
1330
|
return {...JSON.parse(command.receipt),duplicate:true,...(approval?{destination_approval:approval}:{})};
|
|
1242
1331
|
}
|
|
1243
1332
|
if(command) throw new Error('EXISTS: command_key required to retry this assignment');
|
|
1244
|
-
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');
|
|
1245
1334
|
return {request_id:payload.request_id,status:old.status,duplicate:true,...(approval?{destination_approval:approval}:{})};
|
|
1246
1335
|
}
|
|
1247
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
|
+
}
|
|
1248
1343
|
submit(...args) { return this.transaction(()=>this.submitInTransaction(...args)); }
|
|
1249
|
-
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) {
|
|
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) {
|
|
1250
1345
|
if(!this.db.isTransaction) throw new Error('transaction_required');
|
|
1251
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');
|
|
1252
1347
|
const protocol=!this.hasAssignment(payload.request_id)&&Object.hasOwn(payload,'protocol')?validateProtocol(payload.protocol):null;
|
|
@@ -1256,8 +1351,17 @@ export class Store {
|
|
|
1256
1351
|
if(!delivery||!['t3','none'].includes(delivery.mode)||delivery.mode==='t3'&&!delivery.threadId) throw new Error('invalid delivery');
|
|
1257
1352
|
const m=normalizeMeta(meta),threadId=delivery.threadId??'',deliveryValue=delivery.mode==='t3'?`t3:${threadId}`:'none';
|
|
1258
1353
|
if(!['normal','background'].includes(priority)) throw new Error('invalid priority');
|
|
1259
|
-
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);
|
|
1260
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);
|
|
1261
1365
|
const id=payload.request_id, body=JSON.stringify(payload),payloadHash=hash(JSON.stringify(canonical(identity))),ownerHash=inheritedOwnerHash??hash(ownerToken);
|
|
1262
1366
|
// checkRetry validated this target in the same transaction; only counts containing it gain room.
|
|
1263
1367
|
const supersededId=supersedes?.target_id??null;
|
|
@@ -1299,6 +1403,8 @@ export class Store {
|
|
|
1299
1403
|
if(priority==='background'&&this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority='background' AND target_worker=? AND request_id IS NOT ? AND (status='claimed' OR status='queued' AND ${live(this.nowMs())})`).get(targetWorker??'dot',supersededId).n>=this.backgroundMaxInFlight) throw new Error('background_capacity_full');
|
|
1300
1404
|
// The target is a column, not payload: an omitted worker means 'dot'.
|
|
1301
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);
|
|
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);
|
|
1302
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());
|
|
1303
1409
|
const requestedValidUntil=validUntilOf(payload);
|
|
1304
1410
|
const mayUseDefault=priority==='normal'&&!this.paused()&&!((targetWorker??'dot')==='dot'&&this.holdingBreak());
|
|
@@ -1317,6 +1423,11 @@ export class Store {
|
|
|
1317
1423
|
this.db.prepare('INSERT INTO submit_supersedes(request_id,target_id,created_at) VALUES(?,?,?)').run(id,supersedes.target_id,this.stamp());
|
|
1318
1424
|
this.cancelInTransaction(supersedes.target_id,'superseded');
|
|
1319
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
|
+
}
|
|
1320
1431
|
for (const sub of this.activeSubscriptions()) this.submitWake(id,sub);
|
|
1321
1432
|
const receipt={request_id:id,status:'queued',duplicate:false,...(protocol?{revision:1}:{}),...this.destinationFields(id)};
|
|
1322
1433
|
if(commandKey!==null) {
|
|
@@ -1398,7 +1509,8 @@ export class Store {
|
|
|
1398
1509
|
if(!ctx||typeof ctx.key!=='string'||!ctx.key||!protocolNat(ctx.revision)||typeof mutate!=='function')protocolError('command_context_required');
|
|
1399
1510
|
if(ctx.epoch!==undefined&&ctx.epoch!==claim.epoch)protocolError('stale_authority');
|
|
1400
1511
|
return this.protocolCommands().execute({job:id,subject,worker,claim:claimId,epoch:claim.epoch,
|
|
1401
|
-
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)});
|
|
1402
1514
|
}
|
|
1403
1515
|
setClaimDeadlineInTransaction(id,leaseMs) {
|
|
1404
1516
|
const activity=this.db.prepare('SELECT last_claim_activity_at FROM claims WHERE request_id=?').get(id)?.last_claim_activity_at;
|
|
@@ -1407,10 +1519,21 @@ export class Store {
|
|
|
1407
1519
|
this.db.prepare('UPDATE claims SET lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=?')
|
|
1408
1520
|
.run(iso(deadline),this.leaseBootId,this.leaseBootId?this.monotonicNow()+leaseMs:null,id);
|
|
1409
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
|
+
}
|
|
1410
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));
|
|
1411
1534
|
return this.transaction(()=>{
|
|
1412
1535
|
const receipt=this.protocolMutationInTransaction(id,claimId,subject,worker,
|
|
1413
|
-
{...ctx,operation:'renew',args:{leaseMs}},({leaseUntil})=>{
|
|
1536
|
+
{...ctx,operation:'renew',args:{leaseMs:requestedLeaseMs}},({leaseUntil})=>{
|
|
1414
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=?')
|
|
1415
1538
|
.run(leaseMs,iso(leaseUntil),this.leaseBootId,this.leaseBootId?this.monotonicNow()+leaseMs:null,id,claimId);
|
|
1416
1539
|
const claim=this.assertClaim(id,claimId,subject,worker);
|
|
@@ -1555,8 +1678,16 @@ export class Store {
|
|
|
1555
1678
|
const calls=this.db.prepare('SELECT max(last_call_at) call, max(last_list_pending_at) list FROM worker_activity WHERE worker=?').get(worker);
|
|
1556
1679
|
const lastCall=calls.call??null, lastList=calls.list??null;
|
|
1557
1680
|
const silence=lastCall?age(lastCall):Infinity;
|
|
1558
|
-
const claims=this.db.prepare("SELECT c.subject,c.worker,c.lane_key,c.lane_scope,c.lease_ms,c.lease_deadline_at,c.lease_boot_id,c.lease_deadline_monotonic_ms,c.claimed_at,c.last_claim_activity_at,c.last_progress_at,COALESCE(c.last_claim_activity_at,c.claimed_at) activity FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' AND c.worker=?").all(worker);
|
|
1559
|
-
|
|
1681
|
+
const claims=this.db.prepare("SELECT c.request_id,c.subject,c.worker,c.lane_key,c.lane_scope,c.lease_ms,c.lease_deadline_at,c.lease_boot_id,c.lease_deadline_monotonic_ms,c.claimed_at,c.last_claim_activity_at,c.last_progress_at,c.last_tool_at,COALESCE(c.last_claim_activity_at,c.claimed_at) activity FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' AND c.worker=?").all(worker);
|
|
1682
|
+
// Activity warnings are not lease expiry. Renewals and post-start holds must
|
|
1683
|
+
// not hide a silent claim; only progress or assignment-specific tool activity
|
|
1684
|
+
// refreshes this observation. claimed_at is the fallback for a new grant.
|
|
1685
|
+
const idleThresholdMs=limits.claimIdleWarningMs??defaultRedeliveryLimits.claimIdleWarningMs;
|
|
1686
|
+
const staleClaims=claims.map(c=>{
|
|
1687
|
+
const times=[c.claimed_at,c.last_progress_at,c.last_tool_at].map(t=>Date.parse(t)).filter(Number.isFinite);
|
|
1688
|
+
const last=times.length?Math.max(...times):now;
|
|
1689
|
+
return {request_id:c.request_id,idle_ms:Math.max(0,now-last),last_progress_at:c.last_progress_at??null,last_tool_at:c.last_tool_at??null};
|
|
1690
|
+
}).filter(c=>c.idle_ms>=idleThresholdMs).sort((a,b)=>b.idle_ms-a.idle_ms||a.request_id.localeCompare(b.request_id));
|
|
1560
1691
|
const liveSubs=this.activeSubscriptions().filter(sub=>sub.worker===worker);
|
|
1561
1692
|
const liveClaims=liveSubs.flatMap(sub=>this.activeClaims(sub.principal,sub.worker));
|
|
1562
1693
|
const hasLiveClaim=liveClaims.some(c=>now-Date.parse(c.last_claim_activity_at??c.claimed_at)<this.claimLeaseMs(c));
|
|
@@ -1583,7 +1714,7 @@ export class Store {
|
|
|
1583
1714
|
oldest_claim_progress_age_ms:claims.length?Math.max(...claims.map(c=>age(c.last_progress_at??c.claimed_at))):null,
|
|
1584
1715
|
last_worker_call_at:lastCall,last_list_pending_at:lastList,
|
|
1585
1716
|
oldest_unclaimed_event_2xx_age_ms:ages.length?Math.max(...ages):null,
|
|
1586
|
-
queue_classes:queueClasses,stale_claims:{count:staleClaims.length,max_idle_ms:staleClaims
|
|
1717
|
+
queue_classes:queueClasses,stale_claims:{count:staleClaims.length,max_idle_ms:staleClaims[0]?.idle_ms??null,threshold_ms:idleThresholdMs,items:staleClaims.slice(0,20)},
|
|
1587
1718
|
worker_silence_ms:Number.isFinite(silence)?silence:null,unclaimed_after_reannounce:this.unclaimedAfterReannounce(limits,worker),items
|
|
1588
1719
|
};
|
|
1589
1720
|
}
|
|
@@ -1787,10 +1918,11 @@ export class Store {
|
|
|
1787
1918
|
this.refreshClaimActivity(id,claimId);
|
|
1788
1919
|
}
|
|
1789
1920
|
refreshClaimActivity(id,claimId) {
|
|
1790
|
-
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));
|
|
1791
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);
|
|
1792
|
-
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=?')
|
|
1793
|
-
.run(at,iso(Date.parse(at)+
|
|
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);
|
|
1794
1926
|
}
|
|
1795
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.
|
|
1796
1928
|
liveHeldClaim(id,claimId,subject,worker) {
|
|
@@ -1861,8 +1993,11 @@ export class Store {
|
|
|
1861
1993
|
return activity<this.startedMs&&this.nowMs()<this.startedMs+this.claimLeaseMs(claim);
|
|
1862
1994
|
}
|
|
1863
1995
|
leaseExpired(claim) {
|
|
1996
|
+
// Missing or malformed persisted deadlines carry no authority, even with a same-boot clock.
|
|
1997
|
+
const persistedDeadline=Date.parse(claim.lease_deadline_at);
|
|
1998
|
+
if(!Number.isFinite(persistedDeadline)) return true;
|
|
1864
1999
|
const deadline=this.leaseMonotonicDeadline(claim);
|
|
1865
|
-
return deadline===null?this.nowMs()>=
|
|
2000
|
+
return deadline===null?this.nowMs()>=persistedDeadline:this.monotonicNow()>=deadline;
|
|
1866
2001
|
}
|
|
1867
2002
|
// A revoked grant cannot authorize a successor until its deadline and all
|
|
1868
2003
|
// host effect channels have stopped. Unknown stop evidence fails closed.
|
|
@@ -2045,8 +2180,9 @@ export class Store {
|
|
|
2045
2180
|
const watch=this.db.prepare('SELECT deadline,state,updated_at,notification_id FROM watches WHERE request_id=?').get(id) || null;
|
|
2046
2181
|
const supersedes=this.db.prepare('SELECT target_id AS request_id,created_at FROM submit_supersedes WHERE request_id=?').get(id)??null;
|
|
2047
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;
|
|
2048
2184
|
const authorityRevoked=!!a.cancelled_at||this.isProtocolJob(id)&&a.status==='finished';
|
|
2049
|
-
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,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)}))};
|
|
2050
2186
|
}
|
|
2051
2187
|
recordPrPreflight(id,phase,assignment,evidence,replace=false) {
|
|
2052
2188
|
assertPreflight(assignment,evidence,this.nowMs());
|
|
@@ -2054,10 +2190,14 @@ export class Store {
|
|
|
2054
2190
|
}
|
|
2055
2191
|
hasAssignment(id) { return !!this.db.prepare('SELECT 1 FROM assignments WHERE request_id=?').get(id); }
|
|
2056
2192
|
ownerNotes(id) { return this.db.prepare('SELECT id,at,text FROM owner_notes WHERE request_id=? ORDER BY sequence').all(id); }
|
|
2057
|
-
|
|
2058
|
-
|
|
2193
|
+
// A clarification row keeps the shape it had before purposes existed; a row with another purpose shows it.
|
|
2194
|
+
questions(id) { this.assertProtocolAvailable(id);return this.db.prepare('SELECT * FROM job_questions WHERE request_id=? ORDER BY rowid').all(id).map(({purpose,...row})=>purpose==='clarification'?row:{...row,purpose}); }
|
|
2195
|
+
questionPurpose(id,questionId) { return this.db.prepare('SELECT purpose FROM job_questions WHERE request_id=? AND question_id=?').get(id,questionId)?.purpose??null; }
|
|
2196
|
+
askQuestion(id,claimId,questionId,text,subject='local-principal',worker='dot',ctx=null,connectionId=null,purpose='clarification') {
|
|
2059
2197
|
validateQuestion(questionId,text);
|
|
2060
|
-
|
|
2198
|
+
if(!QUESTION_PURPOSES.includes(purpose)) throw new Error(`invalid question purpose: use ${QUESTION_PURPOSES.join(' or ')}`);
|
|
2199
|
+
// The purpose joins the stored command only when it is not the default, so a clarification keeps its pre-existing receipt identity.
|
|
2200
|
+
return this.progress(id,claimId,`QUESTION: ${text}`,subject,false,worker,{questionId,text,...(purpose==='clarification'?{}:{purpose})},ctx,connectionId);
|
|
2061
2201
|
}
|
|
2062
2202
|
assertQuestionGrant(id,question) {
|
|
2063
2203
|
const claim=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
@@ -2143,7 +2283,8 @@ export class Store {
|
|
|
2143
2283
|
if(!question||question.answered_at===null||question.consumed_at!==null||question.epoch!==wake.epoch) return false;
|
|
2144
2284
|
try { this.assertQuestionGrant(row.request_id,question);return true; } catch { return false; }
|
|
2145
2285
|
}
|
|
2146
|
-
note(id,text) { return this.transaction(() =>
|
|
2286
|
+
note(id,text) { return this.transaction(() => this.noteInTransaction(id,text)); }
|
|
2287
|
+
noteInTransaction(id,text) {
|
|
2147
2288
|
this.assertProtocolAvailable(id);
|
|
2148
2289
|
validateOwnerNote(text,this.ownerNotes(id));
|
|
2149
2290
|
const assignment=this.db.prepare('SELECT payload FROM assignments WHERE request_id=?').get(id);
|
|
@@ -2156,7 +2297,15 @@ export class Store {
|
|
|
2156
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());
|
|
2157
2298
|
}
|
|
2158
2299
|
return {request_id:id,...note};
|
|
2159
|
-
}
|
|
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
|
+
}
|
|
2160
2309
|
tell(text,worker='dot') { return this.transaction(() => {
|
|
2161
2310
|
if(worker==='pool') throw new Error('worker \"pool\" is not supported');
|
|
2162
2311
|
const messageId=`msg_${randomUUID()}`, preview=text.slice(0,200), createdAt=this.stamp();
|
|
@@ -2350,7 +2499,7 @@ export class Store {
|
|
|
2350
2499
|
}
|
|
2351
2500
|
claimInTransaction(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,connectionId=null) {
|
|
2352
2501
|
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
2353
|
-
|
|
2502
|
+
leaseMs=this.cappedClaimLeaseMs(leaseMs,worker);
|
|
2354
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');
|
|
2355
2504
|
if(!this.mayAct(worker,id)) throw new Error('assignment not found');
|
|
2356
2505
|
if (this.paused()) throw new Error(pausedClaimMessage);
|
|
@@ -2449,6 +2598,7 @@ export class Store {
|
|
|
2449
2598
|
if(reason==='lease_expired') reason=Store.expirySummary(old);
|
|
2450
2599
|
this.db.prepare("UPDATE claims SET state='abandoned',abandoned_at=?,abandon_reason=? WHERE request_id=?").run(at,reason,id);
|
|
2451
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'});
|
|
2452
2602
|
this.lifecycle(id,'abandoned',actor,reason,old);
|
|
2453
2603
|
this.lifecycle(id,'queued',actor,'requeued',null);
|
|
2454
2604
|
if(this.isProtocolJob(id)) {
|
|
@@ -2573,9 +2723,10 @@ export class Store {
|
|
|
2573
2723
|
if(old) {
|
|
2574
2724
|
if(old.claim_id!==claimId||old.epoch!==claim.epoch) throw questionError('STALE_EPOCH','question identity belongs to an earlier grant');
|
|
2575
2725
|
if(old.text!==question.text) throw questionError('KEY_CONFLICT','question identity has different text');
|
|
2726
|
+
if(old.purpose!==(question.purpose??'clarification')) throw questionError('KEY_CONFLICT','question identity has a different purpose');
|
|
2576
2727
|
return {recorded:true,question_id:question.questionId,duplicate:true};
|
|
2577
2728
|
}
|
|
2578
|
-
this.db.prepare('INSERT INTO job_questions(request_id,question_id,claim_id,epoch,worker,subject,text,asked_at) VALUES(
|
|
2729
|
+
this.db.prepare('INSERT INTO job_questions(request_id,question_id,claim_id,epoch,worker,subject,text,asked_at,purpose) VALUES(?,?,?,?,?,?,?,?,?)').run(id,question.questionId,claimId,claim.epoch,worker,subject,question.text,this.stamp(),question.purpose??'clarification');
|
|
2579
2730
|
}
|
|
2580
2731
|
this.db.prepare('INSERT INTO progress(request_id,note,created_at,worker) VALUES(?,?,?,?)').run(id,note,this.stamp(),worker);
|
|
2581
2732
|
this.recordClaimDenials(id,note,worker);
|
|
@@ -2585,7 +2736,7 @@ export class Store {
|
|
|
2585
2736
|
this.lifecycle(id,question?'waiting':progressType(note,blocker),`worker:${subject}`,question?`question:ask:${question.questionId}`:null,claim);
|
|
2586
2737
|
if(isBlocker) {
|
|
2587
2738
|
const ownerNoteSeq=this.db.prepare('SELECT COALESCE(max(sequence),0) sequence FROM owner_notes WHERE request_id=?').get(id).sequence;
|
|
2588
|
-
const body=JSON.stringify({note,epoch:claim.epoch,owner_note_seq:ownerNoteSeq,...(question?{question_id:question.questionId}:{})});
|
|
2739
|
+
const body=JSON.stringify({note,epoch:claim.epoch,owner_note_seq:ownerNoteSeq,...(question?{question_id:question.questionId,...(question.purpose&&question.purpose!=='clarification'?{purpose:question.purpose}:{})}:{})});
|
|
2589
2740
|
// Legacy bodies have no generation fields. Preserve them only before any later answer/claim boundary;
|
|
2590
2741
|
// equal timestamps at a boundary cannot prove the original generation, so do not suppress a fresh question.
|
|
2591
2742
|
// Owner notes have no shared sequence with notifications; table-local rowids or a delivered-ID set cannot
|
|
@@ -2664,6 +2815,7 @@ export class Store {
|
|
|
2664
2815
|
this.assertNoUncertainDelivery(id);
|
|
2665
2816
|
if(a.status==='claimed') this.laneFreed();
|
|
2666
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'});
|
|
2667
2819
|
this.lifecycle(id,'cancelled','owner',reason);
|
|
2668
2820
|
this.db.prepare("UPDATE notifications SET state='suppressed' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
|
|
2669
2821
|
this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
|
|
@@ -2681,6 +2833,7 @@ export class Store {
|
|
|
2681
2833
|
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
2682
2834
|
if(a.status!=='queued') return {request_id:id,status:a.status,cancelled:false};
|
|
2683
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'});
|
|
2684
2837
|
this.lifecycle(id,'cancelled','owner');
|
|
2685
2838
|
this.db.prepare("UPDATE notifications SET state='suppressed' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
|
|
2686
2839
|
this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
|
|
@@ -2784,6 +2937,32 @@ export class Store {
|
|
|
2784
2937
|
this.db.prepare("UPDATE notifications SET kind=CASE WHEN kind='watch' THEN kind ELSE 'wait' END,state=CASE WHEN kind='watch' THEN 'quiet' ELSE 'pending' END,next_at=0,last_error=? WHERE id=? AND kind IN ('t3','blocker','watch','break') AND state IN ('pending','failed','sending')").run(reason,id);
|
|
2785
2938
|
this.suppressFinishedQuestions(this.db.prepare('SELECT request_id FROM notifications WHERE id=?').get(id)?.request_id??null);
|
|
2786
2939
|
}
|
|
2940
|
+
// A parent that is not running (T3 reports its latest run as interrupted) holds the wake. The wake stays in the durable
|
|
2941
|
+
// queue like any quieted one, and held_kind remembers what it was so releaseHeld can put it back once the parent runs again.
|
|
2942
|
+
// One transaction: held_kind and the quiet state land together or not at all. A crash between two separate writes would
|
|
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.
|
|
2946
|
+
holdDelivery(id,reason) {
|
|
2947
|
+
this.inTransaction(() => {
|
|
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;
|
|
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'});
|
|
2952
|
+
});
|
|
2953
|
+
}
|
|
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
|
|
2955
|
+
// inspected instead of reading the same oldest rows on every call.
|
|
2956
|
+
heldDeliveries(limit=20,after=null) {
|
|
2957
|
+
const base="SELECT * FROM notifications WHERE held_kind IS NOT NULL AND state IN ('pending','quiet')";
|
|
2958
|
+
return after
|
|
2959
|
+
? this.db.prepare(`${base} AND (created_at,id)>(?,?) ORDER BY created_at,id LIMIT ?`).all(after.created_at,after.id,limit)
|
|
2960
|
+
: this.db.prepare(`${base} ORDER BY created_at,id LIMIT ?`).all(limit);
|
|
2961
|
+
}
|
|
2962
|
+
// Back to the original kind, pending and due now. A waiter that already took the row (state 'waiting') is not touched.
|
|
2963
|
+
releaseHeld(id) {
|
|
2964
|
+
return this.db.prepare("UPDATE notifications SET kind=held_kind,held_kind=NULL,state='pending',next_at=0,last_error='' WHERE id=? AND held_kind IS NOT NULL AND state IN ('pending','quiet')").run(id).changes===1;
|
|
2965
|
+
}
|
|
2787
2966
|
quarantineDelivery(id,reason) {
|
|
2788
2967
|
return this.db.prepare("UPDATE notifications SET state='suppressed',last_error=?,uncertain_reason=NULL WHERE id=? AND state IN ('pending','failed')").run(String(reason).slice(0,500),id).changes===1;
|
|
2789
2968
|
}
|
|
@@ -2880,8 +3059,16 @@ export class Store {
|
|
|
2880
3059
|
cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancelled_by_owner:cancelActor==='owner',read:a.owner_read_at!==null,
|
|
2881
3060
|
...this.failureFields(id),
|
|
2882
3061
|
unanswered_blocker:lastBlocker&&(lastAnswer===null||lastBlocker.created_at>lastAnswer)?{text:lastBlocker.note,at:lastBlocker.created_at}:null,
|
|
3062
|
+
held_wake:this.heldWake(id),
|
|
2883
3063
|
};
|
|
2884
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
|
+
}
|
|
2885
3072
|
// Owner action for `dalan inbox --mark-read`: the same read marker as get, without fetching the result. True when it was unread.
|
|
2886
3073
|
markInboxRead(id,via) { return this.transaction(() => {
|
|
2887
3074
|
const status=this.get(id).status, v=this.ownerInbox(id);
|
|
@@ -2899,16 +3086,95 @@ export class Store {
|
|
|
2899
3086
|
// Record a decision on a finished report. Append-only: a different decision is added and the latest wins; the same decision
|
|
2900
3087
|
// again is a no-op. accepted and applied also write the 'accepted' event, not_useful the legacy reject event, so readers of
|
|
2901
3088
|
// those events keep working; an owner decision also counts as the owner read.
|
|
2902
|
-
|
|
2903
|
-
|
|
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'&¤t) 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}={}) {
|
|
2904
3162
|
if(!decisionTypes.includes(decision)) throw new Error(`decision must be one of ${decisionTypes.join(', ')}`);
|
|
2905
3163
|
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
2906
3164
|
if(a.status!=='finished') throw new Error('only a finished assignment can be decided');
|
|
2907
3165
|
const latest=this.db.prepare('SELECT decision,actor FROM decisions WHERE request_id=? ORDER BY id DESC LIMIT 1').get(id);
|
|
2908
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
|
+
}
|
|
2909
3174
|
if(latest&&latest.decision===decision&&latest.actor===actor) return {request_id:id,decision,duplicate:true,at:this.stamp()};
|
|
2910
3175
|
const at=this.stamp();
|
|
2911
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);
|
|
2912
3178
|
if(actor==='owner') {
|
|
2913
3179
|
this.consumeOnce(id,'decide');
|
|
2914
3180
|
if(decision==='accepted'||decision==='applied') this.lifecycle(id,'accepted','owner',decision==='applied'?(note?`applied: ${note}`:'applied'):note);
|
|
@@ -3046,7 +3312,7 @@ export class Store {
|
|
|
3046
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}];
|
|
3047
3313
|
}));
|
|
3048
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();
|
|
3049
|
-
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)};
|
|
3050
3316
|
}
|
|
3051
3317
|
workerCapacityEvidence(worker,subscriptions,limits,capacity) {
|
|
3052
3318
|
const byPrincipal=[...new Map(subscriptions.map(sub=>[sub.principal,sub])).values()];
|