@tnunamak/dalan 0.9.10 → 0.9.11
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 +14 -0
- package/bin/dot-acp-agent.mjs +146 -29
- package/bin/dot-worker.mjs +17 -4
- package/docs/design/target-architecture-v2.md +71 -5
- package/docs/design/target-architecture-v3.md +151 -0
- package/docs/local-agent-requester.md +52 -0
- package/docs/pull-workers.md +8 -2
- package/package.json +1 -1
- package/src/acp-bridge.mjs +23 -11
- package/src/as-files.mjs +6 -3
- package/src/cli-help.mjs +4 -2
- package/src/get-summary.mjs +5 -0
- package/src/local-attachment-authority.mjs +174 -0
- package/src/local-attachment-capture.mjs +136 -0
- package/src/local-attachment-cli.mjs +46 -0
- package/src/local-attachment-gateway.mjs +93 -0
- package/src/local-attachment-owner-verify.mjs +152 -0
- package/src/local-attachment-result.mjs +64 -0
- package/src/local-attachment-snapshot.mjs +142 -0
- package/src/mcp-stdio.mjs +189 -7
- package/src/patch-apply.mjs +28 -6
- package/src/publication-authority.mjs +1 -0
- package/src/pull-pacing.mjs +42 -0
- package/src/requester-local-context.mjs +113 -0
- package/src/server.mjs +96 -33
- package/src/store.mjs +225 -35
- package/src/work-recovery.mjs +143 -0
- package/src/worker-runs.mjs +25 -0
- package/src/workspace.mjs +17 -10
package/src/store.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {migrateWorkRecovery,isRecoveryCheckpoint,saveWorkCheckpoint,projectWorkRecovery} from './work-recovery.mjs';
|
|
1
2
|
import {PullQueue,migratePullQueue,PULL_PAGE_PREFIX} from './pull-queue.mjs';
|
|
2
3
|
import { defaultPath } from './paths.mjs';
|
|
3
4
|
import { readEnv } from './env.mjs';
|
|
@@ -18,6 +19,8 @@ import fs from 'node:fs';
|
|
|
18
19
|
import {migrateClaimCommands,createClaimCommands} from './claim-command-ledger.mjs';
|
|
19
20
|
import {migrateArtifactJournal} from './artifact-journal.mjs';
|
|
20
21
|
import {migrateResultBindings} from './result-binding.mjs';
|
|
22
|
+
import {migrateLocalAttachments} from './local-attachment-authority.mjs';
|
|
23
|
+
import {localAttachmentPublicationRestriction,assertOrdinaryLocalAttachmentBoundary,hasLocalAttachment} from './local-attachment-result.mjs';
|
|
21
24
|
import {migrateJobRetention} from './job-retention.mjs';
|
|
22
25
|
import {migrateProtocolOwnerWaiters,materializeProtocolWaiters} from './protocol-owner-waiters.mjs';
|
|
23
26
|
import {finishProtocol} from './protocol-finish.mjs';
|
|
@@ -68,7 +71,7 @@ function waiterOwnerGone(attemptId) {
|
|
|
68
71
|
return !!(owner.boot&&owner.start&¤t.boot&¤t.start&&(owner.boot!==current.boot||owner.start!==current.start));
|
|
69
72
|
}
|
|
70
73
|
|
|
71
|
-
const SUPPORTED_SCHEMA_VERSION =
|
|
74
|
+
const SUPPORTED_SCHEMA_VERSION = 76;
|
|
72
75
|
const ADMISSION_RESERVATION_MS = 15_000;
|
|
73
76
|
const monotonicMs=()=>Number(process.hrtime.bigint())/1e6;
|
|
74
77
|
function systemBootId() {
|
|
@@ -1136,6 +1139,20 @@ export class Store {
|
|
|
1136
1139
|
prior_id TEXT NOT NULL REFERENCES assignments(request_id),
|
|
1137
1140
|
at TEXT NOT NULL
|
|
1138
1141
|
); PRAGMA user_version=75;`);
|
|
1142
|
+
if(version<76) { migrateLocalAttachments(this.db); this.db.exec('PRAGMA user_version=76;'); }
|
|
1143
|
+
// These owner-only projections need no backfill and leave existing job receipts intact.
|
|
1144
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS continuing_subagents(
|
|
1145
|
+
subagent_id TEXT PRIMARY KEY, owner_hash TEXT NOT NULL,
|
|
1146
|
+
target_worker TEXT NOT NULL, relationship_id TEXT
|
|
1147
|
+
);
|
|
1148
|
+
CREATE TABLE IF NOT EXISTS continuing_subagent_jobs(
|
|
1149
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1150
|
+
subagent_id TEXT NOT NULL REFERENCES continuing_subagents(subagent_id),
|
|
1151
|
+
request_id TEXT NOT NULL UNIQUE REFERENCES assignments(request_id) ON DELETE CASCADE
|
|
1152
|
+
);
|
|
1153
|
+
CREATE INDEX IF NOT EXISTS continuing_subagent_history ON continuing_subagent_jobs(subagent_id,seq);`);
|
|
1154
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('claims') WHERE name='run_timeout_ms'").get())
|
|
1155
|
+
this.db.exec('ALTER TABLE claims ADD COLUMN run_timeout_ms INTEGER');
|
|
1139
1156
|
// Older bridges read every open row of worker_breaks as a primary-worker hold.
|
|
1140
1157
|
// Keep secondary-worker holds out of that table so a rollback can still read current data.
|
|
1141
1158
|
this.db.exec(`CREATE TABLE IF NOT EXISTS scoped_worker_breaks(
|
|
@@ -1153,6 +1170,15 @@ export class Store {
|
|
|
1153
1170
|
request_id TEXT NOT NULL REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1154
1171
|
progress_id INTEGER UNIQUE REFERENCES progress(id) ON DELETE SET NULL
|
|
1155
1172
|
);`);
|
|
1173
|
+
// Additive evidence; legacy projections and ordinary unkeyed withdraw replies remain unchanged.
|
|
1174
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS offer_withdraw_receipts(
|
|
1175
|
+
request_id TEXT PRIMARY KEY REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1176
|
+
key_digest TEXT NOT NULL, owner_digest TEXT NOT NULL, receipt TEXT NOT NULL
|
|
1177
|
+
);
|
|
1178
|
+
CREATE TABLE IF NOT EXISTS offer_start_evidence(
|
|
1179
|
+
request_id TEXT PRIMARY KEY REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1180
|
+
epoch INTEGER NOT NULL, at TEXT NOT NULL
|
|
1181
|
+
);`);
|
|
1156
1182
|
this.db.exec(`CREATE TABLE IF NOT EXISTS admission_reservations(
|
|
1157
1183
|
worker TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1158
1184
|
subscription_id TEXT NOT NULL, issued_at TEXT NOT NULL, expires_at TEXT NOT NULL,
|
|
@@ -1171,6 +1197,7 @@ export class Store {
|
|
|
1171
1197
|
due_ms INTEGER NOT NULL, expires_ms INTEGER NOT NULL, kept INTEGER NOT NULL DEFAULT 0,
|
|
1172
1198
|
PRIMARY KEY(request_id,owner_hash)
|
|
1173
1199
|
) WITHOUT ROWID;`);
|
|
1200
|
+
migrateWorkRecovery(this.db);
|
|
1174
1201
|
// Worker run receipts (D9), hosted-session lifetimes (D14) and the publication grant on a relationship (D10).
|
|
1175
1202
|
// Additive and idempotent, so it needs no schema number: older code ignores these tables and column.
|
|
1176
1203
|
{
|
|
@@ -1758,11 +1785,60 @@ export class Store {
|
|
|
1758
1785
|
if(relationship?.ended_at) throw new Error('relationship_ended');
|
|
1759
1786
|
return relationship;
|
|
1760
1787
|
}
|
|
1788
|
+
// The first job's owner receipt controls this handle, independently of the shared worker relationship.
|
|
1789
|
+
// Per-job operations still require each job's original owner receipt.
|
|
1790
|
+
subagentOwner(subagentId, credential) {
|
|
1791
|
+
if(typeof subagentId!=='string'||!/^sg_[A-Za-z0-9_-]{22,80}$/.test(subagentId)||
|
|
1792
|
+
typeof credential!=='string'||!credential||credential.length>128) throw new Error('subagent_unavailable');
|
|
1793
|
+
const row=this.db.prepare('SELECT * FROM continuing_subagents WHERE subagent_id=?').get(subagentId);
|
|
1794
|
+
const expected=Buffer.from(row?.owner_hash??'00'.repeat(32),'hex');
|
|
1795
|
+
const permitted=timingSafeEqual(expected,Buffer.from(hash(credential),'hex'));
|
|
1796
|
+
if(!row||!permitted) throw new Error('subagent_unavailable');
|
|
1797
|
+
return row;
|
|
1798
|
+
}
|
|
1799
|
+
checkSubagentSubmission(requestId, ownerToken, options, links=[]) {
|
|
1800
|
+
const known=this.db.prepare('SELECT subagent_id FROM continuing_subagent_jobs WHERE request_id=?').get(requestId);
|
|
1801
|
+
const subagentId=options?.id;
|
|
1802
|
+
if(subagentId===undefined) {
|
|
1803
|
+
if(known||options?.credential!==undefined) throw new Error('subagent_unavailable');
|
|
1804
|
+
return null;
|
|
1805
|
+
}
|
|
1806
|
+
if(typeof subagentId!=='string'||!/^sg_[A-Za-z0-9_-]{22,80}$/.test(subagentId)||
|
|
1807
|
+
(options.credential!==undefined&&(typeof options.credential!=='string'||!options.credential||options.credential.length>128)))
|
|
1808
|
+
throw new Error('subagent_unavailable');
|
|
1809
|
+
if(known?.subagent_id!==subagentId&&(known||this.hasAssignment(requestId))) throw new Error('subagent_unavailable');
|
|
1810
|
+
const exists=this.db.prepare('SELECT 1 FROM continuing_subagents WHERE subagent_id=?').get(subagentId);
|
|
1811
|
+
// An explicit prior receipt must never create a replacement for a missing handle.
|
|
1812
|
+
const binding=exists||options.credential!==undefined?this.subagentOwner(subagentId,options.credential??ownerToken):null;
|
|
1813
|
+
for(const linked of links.filter(Boolean)) {
|
|
1814
|
+
if(this.db.prepare('SELECT subagent_id FROM continuing_subagent_jobs WHERE request_id=?').get(linked)?.subagent_id!==subagentId)
|
|
1815
|
+
throw new Error('subagent_unavailable');
|
|
1816
|
+
}
|
|
1817
|
+
return {id:subagentId,binding};
|
|
1818
|
+
}
|
|
1819
|
+
subagentHistory(subagentId, credential, after=0, limit=30) {
|
|
1820
|
+
this.subagentOwner(subagentId,credential);
|
|
1821
|
+
if(!Number.isSafeInteger(after)||after<0||!Number.isSafeInteger(limit)||limit<1||limit>30)
|
|
1822
|
+
throw new Error('invalid_subagent_page');
|
|
1823
|
+
const rows=this.db.prepare('SELECT seq,request_id FROM continuing_subagent_jobs WHERE subagent_id=? AND seq>? ORDER BY seq LIMIT ?')
|
|
1824
|
+
.all(subagentId,after,limit+1);
|
|
1825
|
+
const work=rows.slice(0,limit).map(({request_id})=>{
|
|
1826
|
+
const item=this.get(request_id), report=item.report;
|
|
1827
|
+
return {request_id,status:item.status,created_at:item.created_at,follows:item.follows??null,
|
|
1828
|
+
revises:item.revises??null,report:report?{receipt_id:report.receipt_id,outcome:report.outcome,
|
|
1829
|
+
summary:report.summary,result:report.result,created_at:report.created_at}:null};
|
|
1830
|
+
});
|
|
1831
|
+
return {subagent_id:subagentId,work,next_after:rows.length>limit?rows[limit-1].seq:null};
|
|
1832
|
+
}
|
|
1761
1833
|
submit(...args) { return this.transaction(()=>this.submitInTransaction(...args)); }
|
|
1762
|
-
submitInTransaction(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, preflight=null, priority='normal', meta=null, identity=payload, maxQueued=null, targetWorker=undefined, execution=null, defaultExecution='host', requiredCapabilities=null, defaultValidUntil=null, commandKey=null, supersedes=null, destinationRevision=null, inheritedOwnerHash=null, parentGeneration=null, relationshipId=null, revises=null, follows=null, callerWaiting=undefined) {
|
|
1834
|
+
submitInTransaction(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, preflight=null, priority='normal', meta=null, identity=payload, maxQueued=null, targetWorker=undefined, execution=null, defaultExecution='host', requiredCapabilities=null, defaultValidUntil=null, commandKey=null, supersedes=null, destinationRevision=null, inheritedOwnerHash=null, parentGeneration=null, relationshipId=null, revises=null, follows=null, callerWaiting=undefined, subagentOptions=undefined) {
|
|
1763
1835
|
if(!this.db.isTransaction) throw new Error('transaction_required');
|
|
1764
1836
|
if(callerWaiting!==undefined&&typeof callerWaiting!=='boolean') throw new Error('invalid caller_waiting');
|
|
1765
1837
|
if(payload.request_id.startsWith(PULL_PAGE_PREFIX)||!inheritedOwnerHash&&this.pullQueue.row(payload.request_id)) throw new Error('request_id reserved for policy work');
|
|
1838
|
+
if(subagentOptions?.id!==undefined&&(inheritedOwnerHash||Object.hasOwn(payload,'protocol')))
|
|
1839
|
+
throw new Error('subagent_unavailable');
|
|
1840
|
+
const subagent=this.checkSubagentSubmission(payload.request_id,ownerToken,subagentOptions,
|
|
1841
|
+
[follows?.prior_id,revises?.prior_id,supersedes?.target_id]);
|
|
1766
1842
|
const protocol=!this.hasAssignment(payload.request_id)&&Object.hasOwn(payload,'protocol')?validateProtocol(payload.protocol):null;
|
|
1767
1843
|
if(protocol)identity={...identity,protocol};
|
|
1768
1844
|
if(targetWorker==='pool') throw new Error('worker \"pool\" is not supported');
|
|
@@ -1770,7 +1846,7 @@ export class Store {
|
|
|
1770
1846
|
const m=normalizeMeta(meta);
|
|
1771
1847
|
if(!['normal','background'].includes(priority)) throw new Error('invalid priority');
|
|
1772
1848
|
const retry=this.checkRetry(payload,deliveryOrThreadId,environmentId,ownerToken,review,priority,meta,identity,targetWorker,execution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises,follows,callerWaiting);
|
|
1773
|
-
if(retry) return retry;
|
|
1849
|
+
if(retry) return subagent?{...retry,subagent_id:subagent.id}:retry;
|
|
1774
1850
|
let relationship;
|
|
1775
1851
|
if(inheritedOwnerHash) {
|
|
1776
1852
|
const order=this.pullQueue.row(payload.request_id);
|
|
@@ -1825,6 +1901,16 @@ export class Store {
|
|
|
1825
1901
|
this.db.prepare('INSERT INTO assignments(request_id,payload,payload_hash,thread_id,environment_id,status,created_at,owner_hash,review,delivery,priority,objective_key,revision,task_kind,source,target_worker,execution,required_capabilities,delivery_adapter,delivery_address,delivery_adapter_version,caller_waiting) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,body,payloadHash,threadId,environmentId??'','queued',this.stamp(),ownerHash,review?1:0,deliveryValue,priority,...metaFields.map(k=>k==='source'?toStoredSource(m[k],this.legacyFixNames):m[k]),targetWorker??'dot',execution??defaultExecution,requiredCapabilities?JSON.stringify(requiredCapabilities):null,deliveryAdapter,deliveryAddress,deliveryAdapterVersion,callerWaiting?1:0);
|
|
1826
1902
|
if(typeof parentGeneration==='string')this.db.prepare('UPDATE assignments SET parent_generation=? WHERE request_id=?').run(parentGeneration,id);
|
|
1827
1903
|
if(relationship) this.db.prepare('UPDATE assignments SET relationship_id=? WHERE request_id=?').run(relationship.relationship_id,id);
|
|
1904
|
+
if(subagent) {
|
|
1905
|
+
const worker=targetWorker??'dot', relation=relationship?.relationship_id??null;
|
|
1906
|
+
if(subagent.binding) {
|
|
1907
|
+
if(subagent.binding.target_worker!==worker||subagent.binding.relationship_id!==relation)
|
|
1908
|
+
throw new Error('subagent_unavailable');
|
|
1909
|
+
} else this.db.prepare('INSERT INTO continuing_subagents VALUES(?,?,?,?)')
|
|
1910
|
+
.run(subagent.id,ownerHash,worker,relation);
|
|
1911
|
+
this.db.prepare('INSERT INTO continuing_subagent_jobs(subagent_id,request_id) VALUES(?,?)').run(subagent.id,id);
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1828
1914
|
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());
|
|
1829
1915
|
const requestedValidUntil=validUntilOf(payload);
|
|
1830
1916
|
const mayUseDefault=priority==='normal'&&!this.paused()&&!this.holdingBreak(targetWorker??'dot');
|
|
@@ -1868,7 +1954,7 @@ export class Store {
|
|
|
1868
1954
|
if(callerWaiting===true&&priority==='normal'&&!protocol&&!inheritedOwnerHash) this.reserveAdmissionLane(id,targetWorker??'dot');
|
|
1869
1955
|
for (const sub of this.activeSubscriptions()) this.submitWake(id,sub);
|
|
1870
1956
|
}
|
|
1871
|
-
const receipt={request_id:id,status,duplicate:false,...(revises?.withdraw_prior?{withdraw_prior:true}:{}),...(revises?.require_active_prior?{require_active_prior:true}:{}),...(protocol?{revision:this.protocolRevision(id)}:{}),...this.destinationFields(id)};
|
|
1957
|
+
const receipt={request_id:id,status,duplicate:false,...(subagent?{subagent_id:subagent.id}:{}),...(revises?.withdraw_prior?{withdraw_prior:true}:{}),...(revises?.require_active_prior?{require_active_prior:true}:{}),...(protocol?{revision:this.protocolRevision(id)}:{}),...this.destinationFields(id)};
|
|
1872
1958
|
if(commandKey!==null) {
|
|
1873
1959
|
const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??'dot',execution??defaultExecution,requiredCapabilities,destinationRevision,this.legacyFixNames);
|
|
1874
1960
|
this.db.prepare('INSERT INTO owner_submit_commands(request_id,key_digest,intent_digest,receipt,owner_hash) VALUES(?,?,?,?,?)').run(id,hash(commandKey),intent,JSON.stringify(receipt),ownerHash);
|
|
@@ -1951,12 +2037,13 @@ export class Store {
|
|
|
1951
2037
|
key:ctx.key,expectedRevision:ctx.revision,operation:ctx.operation,args:ctx.args},mutate,
|
|
1952
2038
|
{leaseCapMs:this.workerClaimLeaseCap(worker)});
|
|
1953
2039
|
}
|
|
1954
|
-
setClaimDeadlineInTransaction(id,leaseMs) {
|
|
1955
|
-
const
|
|
1956
|
-
const
|
|
2040
|
+
setClaimDeadlineInTransaction(id,leaseMs,runTimeoutMs=null) {
|
|
2041
|
+
const claim=this.db.prepare('SELECT last_claim_activity_at,claimed_at FROM claims WHERE request_id=?').get(id);
|
|
2042
|
+
const activity=Date.parse(claim?.last_claim_activity_at??this.stamp());
|
|
2043
|
+
const deadline=Math.min(activity+leaseMs,runTimeoutMs===null?Infinity:Date.parse(claim.claimed_at)+runTimeoutMs);
|
|
1957
2044
|
if(!protocolNat(deadline))protocolError('invalid_lease');
|
|
1958
|
-
this.db.prepare('UPDATE claims SET lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=?')
|
|
1959
|
-
.run(iso(deadline),this.leaseBootId,this.monotonicDeadlineFor(deadline),id);
|
|
2045
|
+
this.db.prepare('UPDATE claims SET lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=?,run_timeout_ms=? WHERE request_id=?')
|
|
2046
|
+
.run(iso(deadline),this.leaseBootId,this.monotonicDeadlineFor(deadline),runTimeoutMs,id);
|
|
1960
2047
|
}
|
|
1961
2048
|
workerClaimLeaseCap(worker) {
|
|
1962
2049
|
const caps=this.limits.workerClaimLeaseMs;
|
|
@@ -2408,17 +2495,23 @@ export class Store {
|
|
|
2408
2495
|
// `authorize` runs on the live claim row before the write. An exact claim retry passes none: assertRetryConnection already proved the holder.
|
|
2409
2496
|
touchHeldClaim(id,claimId,subject,worker,authorize=null) {
|
|
2410
2497
|
const c=this.liveHeldClaim(id,claimId,subject,worker);
|
|
2411
|
-
if(!c)return;
|
|
2498
|
+
if(!c)return false;
|
|
2412
2499
|
authorize?.(c);
|
|
2413
|
-
this.refreshClaimActivity(id,claimId);
|
|
2500
|
+
const deadline=this.refreshClaimActivity(id,claimId);
|
|
2501
|
+
return deadline!==null&&deadline>this.leaseExpiresAt(c);
|
|
2414
2502
|
}
|
|
2415
2503
|
refreshClaimActivity(id,claimId) {
|
|
2416
|
-
const at=this.stamp(), claim=this.db.prepare('SELECT lease_ms,worker,acquisition_id FROM claims WHERE request_id=? AND claim_id=?').get(id,claimId);
|
|
2504
|
+
const at=this.stamp(), claim=this.db.prepare('SELECT lease_ms,worker,acquisition_id,claimed_at,run_timeout_ms FROM claims WHERE request_id=? AND claim_id=?').get(id,claimId);
|
|
2417
2505
|
const leaseMs=Math.min(this.handoffWorkLeaseMs(claim)??claim?.lease_ms??this.limits.leaseMs,this.workerClaimLeaseCap(claim?.worker));
|
|
2418
|
-
const deadline=Date.parse(at)+leaseMs;
|
|
2419
|
-
if(this.isProtocolJob(id))
|
|
2420
|
-
|
|
2421
|
-
|
|
2506
|
+
const deadline=Math.min(Date.parse(at)+leaseMs,claim.run_timeout_ms==null?Infinity:Date.parse(claim.claimed_at)+claim.run_timeout_ms);
|
|
2507
|
+
if(this.isProtocolJob(id)) {
|
|
2508
|
+
this.db.prepare('UPDATE claims SET last_claim_activity_at=? WHERE request_id=? AND claim_id=?').run(at,id,claimId);
|
|
2509
|
+
return null;
|
|
2510
|
+
}
|
|
2511
|
+
const expiresAt=iso(deadline);
|
|
2512
|
+
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=?')
|
|
2513
|
+
.run(at,leaseMs,expiresAt,this.leaseBootId,this.monotonicDeadlineFor(deadline),id,claimId);
|
|
2514
|
+
return expiresAt;
|
|
2422
2515
|
}
|
|
2423
2516
|
handoffWorkingLeaseMs(worker) {
|
|
2424
2517
|
const cap=this.workerClaimLeaseCap(worker);
|
|
@@ -2460,12 +2553,19 @@ export class Store {
|
|
|
2460
2553
|
// Unfenced: for callers that already proved the holder inside their own claim transaction (exact retry, resume). `get` uses markNotesSeenByHolder.
|
|
2461
2554
|
markNotesSeen(id,subject,worker='dot') { if(!this.mayAct(worker,id)) return; this.db.prepare("UPDATE claims SET last_seen_note_seq=COALESCE((SELECT max(sequence) FROM owner_notes n WHERE n.request_id=claims.request_id),0) WHERE request_id=? AND subject=? AND worker=? AND state='active'").run(id,subject,worker); }
|
|
2462
2555
|
// One UPDATE per tool call that names an assignment; it matches only that worker's active claim, so a denied or foreign call counts nowhere.
|
|
2463
|
-
recordToolActivity(id,subject,worker,tool,{workspace=false,error=null,connectionId=null}={}) { return this.inTransaction(()=>{
|
|
2556
|
+
recordToolActivity(id,subject,worker,tool,{workspace=false,error=null,connectionId=null,claimId=null}={}) { return this.inTransaction(()=>{
|
|
2464
2557
|
const claim=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND subject=? AND worker=? AND state='active'").get(id,subject,worker);
|
|
2465
2558
|
if(!claim)return;
|
|
2466
2559
|
this.assertMutationConnection(id,claim,connectionId);
|
|
2467
2560
|
const at=this.stamp();
|
|
2468
2561
|
this.db.prepare("UPDATE claims SET tool_calls=tool_calls+1,last_tool=?,last_tool_at=?,last_tool_error=?,first_workspace_tool_at=CASE WHEN ? THEN COALESCE(first_workspace_tool_at,?) ELSE first_workspace_tool_at END WHERE request_id=? AND subject=? AND worker=? AND state='active'").run(tool,at,error===null?null:String(error).slice(0,200),workspace?1:0,at,id,subject,worker);
|
|
2562
|
+
if(workspace&&error===null&&claimId===claim.claim_id&&!this.leaseExpired(claim)&&
|
|
2563
|
+
['read_file','apply_patch','run_check'].includes(tool)) {
|
|
2564
|
+
this.db.prepare(`INSERT INTO offer_start_evidence VALUES(?,?,?)
|
|
2565
|
+
ON CONFLICT(request_id) DO UPDATE SET epoch=excluded.epoch,at=excluded.at
|
|
2566
|
+
WHERE excluded.epoch>offer_start_evidence.epoch`).run(id,claim.epoch,at);
|
|
2567
|
+
}
|
|
2568
|
+
|
|
2469
2569
|
}); }
|
|
2470
2570
|
static toolActivity(c) { return {acquisition_id:c.acquisition_id??null,tool_calls:c.tool_calls??0,last_tool:c.last_tool??null,last_tool_at:c.last_tool_at??null,last_tool_error:c.last_tool_error??null,first_workspace_tool_at:c.first_workspace_tool_at??null}; }
|
|
2471
2571
|
// For example: "lease_expired: <calls>, last <tool> at <time>, no workspace tool".
|
|
@@ -2710,7 +2810,9 @@ export class Store {
|
|
|
2710
2810
|
const a=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(id); if(!a) { const work=this.pullQueue.row(id);if(work)return this.pullQueue.project(work);throw new Error('assignment not found'); }
|
|
2711
2811
|
this.assertProtocolAvailable(id);
|
|
2712
2812
|
const claimRow=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
2713
|
-
const claim=claimRow&&(({acquisition_id,tool_calls,last_tool,last_tool_at,last_tool_error,first_workspace_tool_at,destination_revision,...rest})=>({...rest,...(
|
|
2813
|
+
const claim=claimRow&&(({acquisition_id,tool_calls,last_tool,last_tool_at,last_tool_error,first_workspace_tool_at,destination_revision,run_timeout_ms,...rest})=>({...rest,...(run_timeout_ms==null?{}:{
|
|
2814
|
+
run_deadline_at:iso(Date.parse(rest.claimed_at)+run_timeout_ms),heartbeat_interval_ms:Math.max(1,Math.floor(this.claimLeaseMs(rest)/3))
|
|
2815
|
+
}),...(destination_revision?{destination_revision}:{}),lease_expires_at:this.leaseExpiresAt(claimRow),activity:Store.toolActivity(claimRow)}))(claimRow);
|
|
2714
2816
|
const report=this.db.prepare('SELECT * FROM reports WHERE request_id=?').get(id);
|
|
2715
2817
|
if(report?.workspace_evidence) report.workspace_evidence=JSON.parse(report.workspace_evidence);
|
|
2716
2818
|
// Everything in a report is the worker's own statement. Only a check row carries bridge_verified, and only when the bridge ran it.
|
|
@@ -2751,6 +2853,8 @@ export class Store {
|
|
|
2751
2853
|
}
|
|
2752
2854
|
// D10: the work's current publication authority, read fresh at each effect. null when the work has no relationship.
|
|
2753
2855
|
publicationAuthority(id) {
|
|
2856
|
+
const restriction=localAttachmentPublicationRestriction(this.db,id);
|
|
2857
|
+
if(restriction) return {publish_restriction:restriction};
|
|
2754
2858
|
const row=this.db.prepare('SELECT r.relationship_id,r.ended_at,r.publish_grant FROM assignments a JOIN relationships r USING(relationship_id) WHERE a.request_id=?').get(id);
|
|
2755
2859
|
return row?{relationship_id:row.relationship_id,ended:row.ended_at!==null,publish_grant:row.publish_grant===null?null:JSON.parse(row.publish_grant)}:null;
|
|
2756
2860
|
}
|
|
@@ -3027,6 +3131,18 @@ export class Store {
|
|
|
3027
3131
|
const c=row.claim;
|
|
3028
3132
|
return row.status==='claimed'&&!row.cancellation_requested&&c?.state==='active'&&c.worker===worker&&c.subject===subject&&(claimId===undefined||c.claim_id===claimId)&&!this.leaseExpired(c)?this.workerHeartbeatFields(worker,c):{};
|
|
3029
3133
|
}
|
|
3134
|
+
workerGetLease(id,worker,subject,claimId,connectionId=null,renewed=false) {
|
|
3135
|
+
if(claimId===undefined) return {claim_lease:{mode:'request_only',
|
|
3136
|
+
guidance:'Use progress with your current claim ID. After reacquisition, a get without claim_id cannot renew the new claim.'}};
|
|
3137
|
+
const c=this.liveHeldClaim(id,claimId,subject,worker);
|
|
3138
|
+
if(!c) return {claim_lease:{mode:'not_current',renewed:false,
|
|
3139
|
+
guidance:'This claim is not a current live grant. Stop using it; do not borrow another claim ID from get.'}};
|
|
3140
|
+
this.assertMutationConnection(id,c,connectionId);
|
|
3141
|
+
const explicit=this.isProtocolJob(id);
|
|
3142
|
+
return {claim_lease:{mode:explicit?'explicit_renewal':'current',renewed:!explicit&&renewed===true,
|
|
3143
|
+
epoch:c.epoch,lease_expires_at:this.leaseExpiresAt(c),
|
|
3144
|
+
guidance:explicit?'Protocol jobs require renew_claim before this deadline; get does not renew them.':'Send progress with this claim while working and stop if it expires.'}};
|
|
3145
|
+
}
|
|
3030
3146
|
heartbeatForHeldClaim(id,claimId,worker) {
|
|
3031
3147
|
if(this.workerHeartbeatMs(worker)===null||!claimId) return {};
|
|
3032
3148
|
return this.workerHeartbeatFields(worker,this.db.prepare("SELECT * FROM claims WHERE request_id=? AND claim_id=? AND worker=? AND state='active'").get(id,claimId,worker));
|
|
@@ -3059,14 +3175,14 @@ export class Store {
|
|
|
3059
3175
|
// Persist selected IDs before asynchronous preflight. A retry can recover
|
|
3060
3176
|
// live grants, or try the same nonempty plan if it never granted anything.
|
|
3061
3177
|
// It cannot select different IDs or issue new grants after any grant landed.
|
|
3062
|
-
async claimBatch({next,available,worker,subject,connectionId,claimant,acquisitionId,leaseMs},grant) {
|
|
3178
|
+
async claimBatch({next,available,worker,subject,connectionId,claimant,acquisitionId,leaseMs,heartbeatMs,runTimeoutMs},grant) {
|
|
3063
3179
|
if(!Number.isInteger(next)||next<1||next>8) throw new Error('invalid next');
|
|
3064
3180
|
if(typeof acquisitionId!=='string'||!/^[A-Za-z0-9_-]{1,128}$/.test(acquisitionId)) throw new Error('batch claim requires acquisition_id');
|
|
3065
3181
|
if(this.paused()) throw new Error(pausedClaimMessage);
|
|
3066
3182
|
const hash=(...values)=>createHash('sha256').update(JSON.stringify(values)).digest('hex');
|
|
3067
3183
|
const digest=hash(worker,subject,acquisitionId);
|
|
3068
3184
|
const key='claim_batch_v1_'+digest;
|
|
3069
|
-
const parameters=hash(connectionId,claimant,next,leaseMs??null);
|
|
3185
|
+
const parameters=hash(connectionId,claimant,next,leaseMs??null,...(heartbeatMs===undefined?[]:[heartbeatMs,runTimeoutMs]));
|
|
3070
3186
|
const plan=this.transaction(()=>{
|
|
3071
3187
|
const previous=this.db.prepare('SELECT value FROM bridge_state WHERE key=?').get(key);
|
|
3072
3188
|
if(previous) {
|
|
@@ -3143,14 +3259,15 @@ export class Store {
|
|
|
3143
3259
|
const reservedId=this.admissionReservation(worker)?.request_id;
|
|
3144
3260
|
const reserveOrder=(a,b)=>Number(b.request_id===reservedId)-Number(a.request_id===reservedId);
|
|
3145
3261
|
let filler=this.activeCallerReserve(worker)>0?this.fillerRoom(worker):Infinity;
|
|
3146
|
-
const assignments=this.db.prepare(`SELECT request_id,payload,created_at,priority,review,caller_waiting,EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked, EXISTS(SELECT 1 FROM pr_claim_blocks b WHERE b.request_id=assignments.request_id) stale_pr FROM assignments WHERE status='queued' AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id) AND ${live(this.nowMs())}${batch?' AND skipped_at IS NULL':''} ORDER BY ${LIST_ORDER}`).all().filter(a=>this.mayAct(worker,a.request_id)&&this.protocolListingLive(a.request_id)&&(!batch||!this.isProtocolJob(a.request_id)&&!this.pullQueue.row(a.request_id))).map(a=>({...a,blocked:!!a.stale_pr||!!a.blocked&&blocked(a.request_id)}))
|
|
3262
|
+
const assignments=this.db.prepare(`SELECT request_id,payload,created_at,priority,review,caller_waiting,EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked, EXISTS(SELECT 1 FROM pr_claim_blocks b WHERE b.request_id=assignments.request_id) stale_pr,EXISTS(SELECT 1 FROM local_attachment_bindings b WHERE b.work=assignments.request_id) attachment_unqualified FROM assignments WHERE status='queued' AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id) AND ${live(this.nowMs())}${batch?' AND skipped_at IS NULL':''} ORDER BY ${LIST_ORDER}`).all().filter(a=>this.mayAct(worker,a.request_id)&&this.protocolListingLive(a.request_id)&&(!batch||!this.isProtocolJob(a.request_id)&&!this.pullQueue.row(a.request_id))).map(a=>({...a,blocked:!!a.attachment_unqualified||!!a.stale_pr||!!a.blocked&&blocked(a.request_id)}))
|
|
3147
3263
|
.sort((a,b)=>Number(a.blocked)-Number(b.blocked)||reserveOrder(a,b))
|
|
3148
3264
|
.filter(a=>handoffExclusions===null||!a.blocked&&a.request_id!==reservedId&&!handoffExclusions.has(a.request_id)&&!this.handoffLapsed(a.request_id,worker))
|
|
3149
|
-
.filter(a=>a.caller_waiting===1||filler-- > 0).slice(0,50).map(a=>({kind:'assignment',request_id:a.request_id,title:JSON.parse(a.payload).brief.slice(0,160),created_at:a.created_at,...(a.blocked?{blocked:true,...(a.stale_pr?{block_reason:'pr_head_mismatch'}:{})}:triageFields(JSON.parse(a.payload),a))}));
|
|
3265
|
+
.filter(a=>a.caller_waiting===1||filler-- > 0).slice(0,50).map(a=>({kind:'assignment',request_id:a.request_id,title:JSON.parse(a.payload).brief.slice(0,160),created_at:a.created_at,...(a.blocked?{blocked:true,...(a.attachment_unqualified?{block_reason:'attachment_recipient_unavailable'}:a.stale_pr?{block_reason:'pr_head_mismatch'}:{})}:triageFields(JSON.parse(a.payload),a))}));
|
|
3150
3266
|
if(batch||handoffExclusions!==null) return assignments;
|
|
3151
3267
|
const messages=this.listMessages(worker).map(({preview,...m})=>({kind:'message',request_id:m.message_id,title:preview,...m})).sort((a,b)=>a.created_at.localeCompare(b.created_at));
|
|
3152
3268
|
const resumes=this.idleClaims(worker).filter(c=>this.protocolListingLive(c.request_id)).map(c=>({kind:'assignment',request_id:c.request_id,resume:true,idle_seconds:Math.floor(this.claimIdleMs(c)/1000),previous_epoch:c.epoch,
|
|
3153
|
-
...(this.db
|
|
3269
|
+
...(hasLocalAttachment(this.db,c.request_id)?{blocked:true,block_reason:'attachment_recipient_unavailable'}:
|
|
3270
|
+
this.db.prepare('SELECT 1 FROM destination_blocks WHERE request_id=?').get(c.request_id)&&blocked(c.request_id)?{blocked:true}:{}),
|
|
3154
3271
|
note:'The prior lease expired. Call claim(request_id, claimant, acquisition_id) to request a new epoch after old host work has verifiably stopped. Read progress and owner notes with get first.'}));
|
|
3155
3272
|
return [...resumes,...messages,...assignments].sort((a,b)=>Number(!!a.blocked)-Number(!!b.blocked)||reserveOrder(a,b)).slice(0,50);
|
|
3156
3273
|
}
|
|
@@ -3253,7 +3370,7 @@ export class Store {
|
|
|
3253
3370
|
} catch(error) { throw this.destinationConfigurationError(id,error); }
|
|
3254
3371
|
if(digest!==approval.snapshot.connections_digest)throw refuse('Claim retry refused: the approved connection set changed.');
|
|
3255
3372
|
}
|
|
3256
|
-
claim(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,ctx=null,connectionId=null,batchMode=null) {
|
|
3373
|
+
claim(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,ctx=null,connectionId=null,batchMode=null,runTimeoutMs=null) {
|
|
3257
3374
|
const requestedLeaseMs=arguments[7]??null;
|
|
3258
3375
|
const claim=this.destinationOutcome(this.transaction(()=>{
|
|
3259
3376
|
if(batchMode==='queued') {
|
|
@@ -3263,13 +3380,14 @@ export class Store {
|
|
|
3263
3380
|
if(batchMode==='retry'&&!this.isExactClaimRetry(this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id),claimant,subject,acquisitionId)) throw new Error('batch grant no longer live');
|
|
3264
3381
|
return this.isProtocolJob(id)
|
|
3265
3382
|
?this.protocolClaimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,ctx?{...ctx,requestedLeaseMs}:ctx,connectionId)
|
|
3266
|
-
:this.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,connectionId);
|
|
3383
|
+
:this.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,connectionId,runTimeoutMs);
|
|
3267
3384
|
}));
|
|
3268
3385
|
return nonterminalOutcome(id,{...claim,...this.heartbeatForHeldClaim(id,claim.claim_id,worker)});
|
|
3269
3386
|
}
|
|
3270
|
-
claimInTransaction(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,connectionId=null) {
|
|
3387
|
+
claimInTransaction(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,connectionId=null,runTimeoutMs=null) {
|
|
3271
3388
|
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
3272
3389
|
leaseMs=this.cappedClaimLeaseMs(leaseMs,worker);
|
|
3390
|
+
if(runTimeoutMs!==null&&(!Number.isSafeInteger(runTimeoutMs)||runTimeoutMs<1||runTimeoutMs>this.limits.leaseMs)) throw new Error('invalid run_timeout_ms');
|
|
3273
3391
|
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');
|
|
3274
3392
|
if(!this.mayAct(worker,id)) throw new Error('assignment not found');
|
|
3275
3393
|
if(this.db.prepare("SELECT 1 FROM facade_withdrawals WHERE request_id=? AND EXISTS (SELECT 1 FROM assignments WHERE request_id=? AND status='queued')").get(id,id))
|
|
@@ -3281,6 +3399,7 @@ export class Store {
|
|
|
3281
3399
|
const old=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
3282
3400
|
if(old&&old.worker!==worker) throw new Error('invalid claim');
|
|
3283
3401
|
this.assertLiveConnection(id,worker,connectionId);
|
|
3402
|
+
this.assertAttachmentRecipientQualified(id);
|
|
3284
3403
|
const laneScope=old?.lane_scope??this.workers.laneScope;
|
|
3285
3404
|
const laneKey=laneScope==='subject'?subject:worker;
|
|
3286
3405
|
const takeover=old?.state==='active';
|
|
@@ -3292,7 +3411,7 @@ export class Store {
|
|
|
3292
3411
|
if(old && (old.state!=='active' || this.leaseExpired(old))) this.assertRegrantReady(old);
|
|
3293
3412
|
if(takeover&&old.subject===subject&&this.isIdleClaim(old)) {
|
|
3294
3413
|
this.assertClaimGap(id,subject,worker);
|
|
3295
|
-
return this.rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs,connectionId);
|
|
3414
|
+
return this.rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs,connectionId,runTimeoutMs);
|
|
3296
3415
|
}
|
|
3297
3416
|
if(takeover) {
|
|
3298
3417
|
if(!this.leaseExpired(old)&&old.subject===subject&&this.resumeIdleMs()>0) throw new Error(JSON.stringify({error:'claim_busy',message:`Request ${id}: another run of this worker holds it and is active; pick other work or retry after its lease expires. This affects only ${id}.`,request_id:id}));
|
|
@@ -3317,7 +3436,7 @@ export class Store {
|
|
|
3317
3436
|
this.db.prepare("UPDATE claims SET claimant=?,claim_id=?,claimed_at=?,subject=?,last_claim_activity_at=?,last_seen_note_seq=?,last_progress_at=NULL,epoch=epoch+1,state='active',abandoned_at=NULL,abandon_reason=NULL,tool_calls=0,last_tool=NULL,last_tool_at=NULL,last_tool_error=NULL,first_workspace_tool_at=NULL,lane_key=?,acquisition_id=?,lease_ms=?,connection_id=? WHERE request_id=?").run(claimant,claimId,claimedAt,subject,claimedAt,seen,laneKey,acquisitionId,leaseMs,connectionId??null,id);
|
|
3318
3437
|
this.rebindClaim(id,claimId);
|
|
3319
3438
|
} else this.db.prepare('INSERT INTO claims(request_id,claimant,claim_id,claimed_at,subject,last_claim_activity_at,last_seen_note_seq,worker,lane_key,lane_scope,acquisition_id,lease_ms,connection_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,claimant,claimId,claimedAt,subject,claimedAt,seen,worker,laneKey,laneScope,acquisitionId,leaseMs,connectionId??null);
|
|
3320
|
-
this.setClaimDeadlineInTransaction(id,leaseMs);
|
|
3439
|
+
this.setClaimDeadlineInTransaction(id,leaseMs,runTimeoutMs);
|
|
3321
3440
|
if(a.status==='queued') {
|
|
3322
3441
|
this.recordPassedOver(id,worker);
|
|
3323
3442
|
this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE target_worker=? AND status='queued' AND request_id<>? AND eligible_since IS NOT NULL").run(worker,id);
|
|
@@ -3333,7 +3452,7 @@ export class Store {
|
|
|
3333
3452
|
// transaction, so a run still alive under the old claim_id is refused on its next call (claim_superseded). Worktree and sealed
|
|
3334
3453
|
// uploads move with it (rebindClaim). Lifecycle: a 'claimed' event with reason 'resume' (not counted as a new admission; the
|
|
3335
3454
|
// event type list is closed, so no 'resumed' type). The previous epoch and the idle time go to the progress history.
|
|
3336
|
-
rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs=this.limits.leaseMs,connectionId=null) {
|
|
3455
|
+
rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs=this.limits.leaseMs,connectionId=null,runTimeoutMs=null) {
|
|
3337
3456
|
this.assertRegrantReady(old);
|
|
3338
3457
|
this.assertLiveConnection(old.request_id,worker,connectionId);
|
|
3339
3458
|
const id=old.request_id, idleS=Math.floor(this.claimIdleMs(old)/1000);
|
|
@@ -3342,7 +3461,7 @@ export class Store {
|
|
|
3342
3461
|
const destinationRefusal=this.destinationAdmissionInTransaction(id);
|
|
3343
3462
|
if(destinationRefusal)return destinationRefusal;
|
|
3344
3463
|
this.assertNoUncertainDelivery(id);
|
|
3345
|
-
const {claimId,at,epoch}=this.startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId);
|
|
3464
|
+
const {claimId,at,epoch}=this.startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId,runTimeoutMs);
|
|
3346
3465
|
this.db.prepare('INSERT INTO progress(request_id,note,created_at,worker) VALUES(?,?,?,?)').run(id,`[bridge] run resumed: epoch ${old.epoch} lease expired after ${idleS}s without activity; epoch ${epoch} continues under a new claim`,at,worker);
|
|
3347
3466
|
this.markBatchGrant(id,acquisitionId);
|
|
3348
3467
|
this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch,worker});
|
|
@@ -3350,11 +3469,19 @@ export class Store {
|
|
|
3350
3469
|
}
|
|
3351
3470
|
// The one re-grant of an existing claim row: new claim_id and epoch, and every old-epoch field (progress, tool counters, acquisition, lease) reset.
|
|
3352
3471
|
// rotateIdleClaim (claim wake) and resume both call it, so the two paths cannot drift.
|
|
3353
|
-
|
|
3472
|
+
// Hosted claims attest holder and registered connection, but not an independent
|
|
3473
|
+
// worker destination address, relationship side or attachment materialization.
|
|
3474
|
+
// No runtime adapter qualifies yet, so a reserved/queued ordinary offer must
|
|
3475
|
+
// never be upgraded to a grant for a job bound to a local attachment.
|
|
3476
|
+
assertAttachmentRecipientQualified(id) {
|
|
3477
|
+
if(hasLocalAttachment(this.db,id))throw Object.assign(new Error('attachment_recipient_unavailable'),{code:'attachment_recipient_unavailable'});
|
|
3478
|
+
}
|
|
3479
|
+
startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId,runTimeoutMs=null) {
|
|
3480
|
+
this.assertAttachmentRecipientQualified(old.request_id);
|
|
3354
3481
|
const id=old.request_id, claimId=`claim_${randomUUID()}`, at=this.stamp(), epoch=old.epoch+1;
|
|
3355
3482
|
const seen=this.db.prepare('SELECT COALESCE(max(sequence),0) n FROM owner_notes WHERE request_id=?').get(id).n;
|
|
3356
3483
|
this.db.prepare("UPDATE claims SET claimant=?,claim_id=?,claimed_at=?,last_claim_activity_at=?,last_seen_note_seq=?,last_progress_at=NULL,epoch=?,tool_calls=0,last_tool=NULL,last_tool_at=NULL,last_tool_error=NULL,first_workspace_tool_at=NULL,acquisition_id=?,lease_ms=?,connection_id=? WHERE request_id=?").run(claimant,claimId,at,at,seen,epoch,acquisitionId,leaseMs,connectionId??null,id);
|
|
3357
|
-
this.setClaimDeadlineInTransaction(id,leaseMs);
|
|
3484
|
+
this.setClaimDeadlineInTransaction(id,leaseMs,runTimeoutMs);
|
|
3358
3485
|
this.rebindClaim(id,claimId);
|
|
3359
3486
|
return {claimId,at,epoch};
|
|
3360
3487
|
}
|
|
@@ -3365,13 +3492,14 @@ export class Store {
|
|
|
3365
3492
|
const old=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND state='active'").get(id);
|
|
3366
3493
|
if(!old||old.subject!==subject||a.status!=='claimed') throw new Error('no active claim for this subject');
|
|
3367
3494
|
this.assertLiveConnection(id,old.worker,connectionId);
|
|
3495
|
+
this.assertAttachmentRecipientQualified(id);
|
|
3368
3496
|
this.assertRegrantReady(old);
|
|
3369
3497
|
this.assertWorkerClaimSlot(old.worker,id);
|
|
3370
3498
|
this.assertReservationLane(subject,old.worker,id);
|
|
3371
3499
|
const destinationRefusal=this.destinationAdmissionInTransaction(id);
|
|
3372
3500
|
if(destinationRefusal)return destinationRefusal;
|
|
3373
3501
|
this.assertNoUncertainDelivery(id);
|
|
3374
|
-
const {claimId}=this.startNextEpoch(old,old.claimant,old.acquisition_id,this.claimLeaseMs(old),connectionId??old.connection_id); // resume cannot ask for a lease or an acquisition, so the epoch keeps the ones the worker was granted (its exact retry of a lost reply still matches)
|
|
3502
|
+
const {claimId}=this.startNextEpoch(old,old.claimant,old.acquisition_id,this.claimLeaseMs(old),connectionId??old.connection_id,old.run_timeout_ms??null); // resume cannot ask for a lease or an acquisition, so the epoch keeps the ones the worker was granted (its exact retry of a lost reply still matches)
|
|
3375
3503
|
this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch:old.epoch+1});
|
|
3376
3504
|
if(this.isProtocolJob(id)) {
|
|
3377
3505
|
this.advanceProtocolRevisionInTransaction(id);
|
|
@@ -3594,9 +3722,23 @@ export class Store {
|
|
|
3594
3722
|
if(this.db.prepare("SELECT 1 FROM lifecycle_events e WHERE e.type IN ('completed','abandoned','cancelled') AND e.at>? AND e.worker=? AND EXISTS(SELECT 1 FROM claims c WHERE c.request_id=e.request_id) LIMIT 1").get(at,worker)) return null;
|
|
3595
3723
|
return iso(Date.parse(at)+capacityHoldMaxMs);
|
|
3596
3724
|
}
|
|
3725
|
+
workerRecovery(id,claimId,subject,worker,connectionId=null) {
|
|
3726
|
+
if(!this.mayAct(worker,id)||this.isProtocolJob(id))return null;
|
|
3727
|
+
const status=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id)?.status;
|
|
3728
|
+
if(status==='finished')return projectWorkRecovery(this,id);
|
|
3729
|
+
const grant=claimId?this.liveHeldClaim(id,claimId,subject,worker):null;
|
|
3730
|
+
if(!grant||status!=='claimed')return null;
|
|
3731
|
+
try {this.assertMutationConnection(id,grant,connectionId);}
|
|
3732
|
+
catch {return null;}
|
|
3733
|
+
return projectWorkRecovery(this,id,grant);
|
|
3734
|
+
}
|
|
3597
3735
|
progress(id,claimId,note,subject='local-principal',blocker=false,worker='dot',question=null,ctx=null,connectionId=null) {
|
|
3598
3736
|
const result=this.transaction(()=>{
|
|
3599
3737
|
if(!this.isProtocolJob(id)) {
|
|
3738
|
+
if(!question&&isRecoveryCheckpoint(note)) {
|
|
3739
|
+
if(blocker)throw new Error('checkpoint must not be a blocker message');
|
|
3740
|
+
return saveWorkCheckpoint(this,{work:id,claimId,subject,worker,connectionId},note);
|
|
3741
|
+
}
|
|
3600
3742
|
this.assertMutationConnection(id,this.assertClaim(id,claimId,subject,worker),connectionId);
|
|
3601
3743
|
return this.progressInTransaction(id,claimId,note,subject,blocker,worker,question);
|
|
3602
3744
|
}
|
|
@@ -3722,6 +3864,7 @@ export class Store {
|
|
|
3722
3864
|
finishOnce(id,claimId,outcome,summary,result,subject,evidence,worker,captureEvidence=null,connectionId=null) {
|
|
3723
3865
|
const claim=this.assertFinishClaim(id,claimId,subject,worker);
|
|
3724
3866
|
this.assertMutationConnection(id,claim,connectionId);
|
|
3867
|
+
assertOrdinaryLocalAttachmentBoundary(this.db,id);
|
|
3725
3868
|
const submittedOutcome=outcome;
|
|
3726
3869
|
({outcome,summary}=this.finishPatchOutcome(id,claimId,outcome,summary));
|
|
3727
3870
|
const old=this.db.prepare('SELECT * FROM reports WHERE request_id=?').get(id);
|
|
@@ -3863,7 +4006,52 @@ export class Store {
|
|
|
3863
4006
|
// Cancel only while the row is still queued, in one transaction, so a claim cannot slip in between a check and the cancel.
|
|
3864
4007
|
// Returns the resulting state either way: cancelled:true when this call cancelled it, false when it was already claimed,
|
|
3865
4008
|
// finished or cancelled (the status then says which). A claimed row keeps running; nothing is revoked.
|
|
3866
|
-
|
|
4009
|
+
offerView(id) {
|
|
4010
|
+
const row=this.db.prepare('SELECT status,target_worker FROM assignments WHERE request_id=?').get(id);
|
|
4011
|
+
if(!row||this.isProtocolJob(id)||this.pullQueue.row(id))return null;
|
|
4012
|
+
if(row.status==='queued') {
|
|
4013
|
+
const prior=this.db.prepare('SELECT claimed_at FROM claims WHERE request_id=?').get(id);
|
|
4014
|
+
if(prior)return {state:'queued',started_at:null,previous_acceptance_at:prior.claimed_at};
|
|
4015
|
+
const reservation=this.admissionReservation(row.target_worker);
|
|
4016
|
+
if(reservation?.request_id===id&&this.admissionOpen()&&!this.paused()&&!this.holdingBreak(row.target_worker)&&
|
|
4017
|
+
!this.capacityHoldUntil(row.target_worker)&&!this.db.prepare('SELECT 1 FROM facade_withdrawals WHERE request_id=?').get(id))
|
|
4018
|
+
return {state:'reserved',reserved_until:reservation.expires_at,started_at:null};
|
|
4019
|
+
return {state:'queued',started_at:null};
|
|
4020
|
+
}
|
|
4021
|
+
if(row.status!=='claimed')return {state:'terminal',status:row.status};
|
|
4022
|
+
const claim=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND state='active'").get(id);
|
|
4023
|
+
if(!claim||this.leaseExpired(claim)) return {state:'unresolved',status:'claimed',started_at:null};
|
|
4024
|
+
const start=this.db.prepare('SELECT at FROM offer_start_evidence WHERE request_id=? AND epoch=?').get(id,claim.epoch);
|
|
4025
|
+
return {state:start?'started':'accepted',claim_epoch:claim.epoch,accepted_at:claim.claimed_at,
|
|
4026
|
+
started_at:start?.at??null,...(start?{start_source:'successful_fenced_workspace_operation'}:{})};
|
|
4027
|
+
}
|
|
4028
|
+
cancelIfQueued(id,{key,owner}={}) { return this.transaction(() => {
|
|
4029
|
+
if(key===undefined)return this.cancelIfQueuedInTransaction(id);
|
|
4030
|
+
this.owner(id,owner);
|
|
4031
|
+
if(typeof key!=='string'||!key||key.length>128)throw new Error('invalid withdrawal command key');
|
|
4032
|
+
if(this.isProtocolJob(id)||this.pullQueue.row(id))throw new Error('keyed offer withdrawal requires an ordinary assignment');
|
|
4033
|
+
const prior=this.db.prepare('SELECT * FROM offer_withdraw_receipts WHERE request_id=?').get(id);
|
|
4034
|
+
const keyDigest=hash(key), ownerDigest=hash(owner);
|
|
4035
|
+
if(prior) {
|
|
4036
|
+
if(prior.key_digest!==keyDigest||prior.owner_digest!==ownerDigest)throw new Error('KEY_CONFLICT: withdrawal key changed');
|
|
4037
|
+
return JSON.parse(prior.receipt);
|
|
4038
|
+
}
|
|
4039
|
+
const view=this.offerView(id);
|
|
4040
|
+
// A claim can end and release its lane without proving the worker stopped.
|
|
4041
|
+
const requeuedAfterAcceptance=view?.previous_acceptance_at!=null;
|
|
4042
|
+
const result=requeuedAfterAcceptance
|
|
4043
|
+
?{request_id:id,status:'queued',cancelled:false}
|
|
4044
|
+
:this.cancelIfQueuedInTransaction(id);
|
|
4045
|
+
const disposition=result.cancelled?'withdrawn_while_queued':
|
|
4046
|
+
view?.state==='accepted'||view?.state==='started'||requeuedAfterAcceptance?'already_accepted':
|
|
4047
|
+
view?.state==='unresolved'?'acceptance_unresolved':'already_terminal';
|
|
4048
|
+
const receipt={...result,disposition,offer_at_decision:view};
|
|
4049
|
+
this.db.prepare('INSERT INTO offer_withdraw_receipts VALUES(?,?,?,?)')
|
|
4050
|
+
.run(id,keyDigest,ownerDigest,JSON.stringify(receipt));
|
|
4051
|
+
return receipt;
|
|
4052
|
+
}); }
|
|
4053
|
+
cancelIfQueuedInTransaction(id) {
|
|
4054
|
+
if(!this.db.isTransaction)throw new Error('transaction_required');
|
|
3867
4055
|
const pendingWork=this.pullQueue.row(id);
|
|
3868
4056
|
if(pendingWork&&!pendingWork.child_request_id) {const status=this.pullQueue.project(pendingWork).status;if(status!=='queued')return {request_id:id,status,cancelled:false};return {...this.pullQueue.cancel(id),cancelled:true};}
|
|
3869
4057
|
this.assertProtocolAvailable(id);
|
|
@@ -3877,7 +4065,7 @@ export class Store {
|
|
|
3877
4065
|
this.db.prepare("UPDATE notifications SET state='suppressed' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
|
|
3878
4066
|
this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
|
|
3879
4067
|
return {request_id:id,status:'cancelled',cancelled:true};
|
|
3880
|
-
}
|
|
4068
|
+
}
|
|
3881
4069
|
// Lease sweep: a claim whose lease ran out with no claim activity is abandoned (actor system, reason lease_expired) through the
|
|
3882
4070
|
// same path as `dalan abandon`, so the row is requeued and its lane is free at once. Before this, an expired lease only
|
|
3883
4071
|
// let another claimant take the item over, and a dead claim held its lane for as long as nobody did. A usage break neither holds
|
|
@@ -4181,6 +4369,7 @@ export class Store {
|
|
|
4181
4369
|
// revised job's result is never recorded accepted or applied. A refused takeover of an open reservation records nothing.
|
|
4182
4370
|
reserveApply(id) {
|
|
4183
4371
|
const result=this.transaction(() => {
|
|
4372
|
+
assertOrdinaryLocalAttachmentBoundary(this.db,id);
|
|
4184
4373
|
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
4185
4374
|
if(a.status!=='finished') throw new Error('only a finished assignment can be decided');
|
|
4186
4375
|
const open=this.db.prepare("SELECT reserved_at FROM apply_reservations WHERE request_id=? AND state='applying'").get(id);
|
|
@@ -4220,6 +4409,7 @@ export class Store {
|
|
|
4220
4409
|
return {request_id:id,state:'released'};
|
|
4221
4410
|
}); }
|
|
4222
4411
|
recordDecision(id,decision,{note=null,actor='owner',via='cli',fenced=false}={}) {
|
|
4412
|
+
if(actor==='owner'&&(decision==='accepted'||decision==='applied'))assertOrdinaryLocalAttachmentBoundary(this.db,id);
|
|
4223
4413
|
if(!decisionTypes.includes(decision)) throw new Error(`decision must be one of ${decisionTypes.join(', ')}`);
|
|
4224
4414
|
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
4225
4415
|
if(a.status!=='finished') throw new Error('only a finished assignment can be decided');
|