@tnunamak/dalan 0.9.0 → 0.9.3
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 +18 -0
- package/bin/dot-acp-agent.mjs +15 -4
- package/bin/dot-worker.mjs +11 -1
- package/docs/operations.md +23 -0
- package/docs/pull-workers.md +10 -4
- package/docs/test-suite-isolation.md +36 -0
- package/package.json +1 -1
- package/qualification/README.md +2 -2
- package/qualification/registry-questions-v1.json +126 -0
- package/scripts/worker-bridge-setup.mjs +23 -21
- package/src/acp-bridge.mjs +41 -8
- package/src/cli-help.mjs +1 -1
- package/src/execution.mjs +6 -2
- package/src/get-summary.mjs +3 -2
- package/src/patch-apply.mjs +2 -1
- package/src/phase-trace.mjs +59 -2
- package/src/pr-preflight.mjs +3 -1
- package/src/server.mjs +117 -22
- package/src/service-update-runtime.mjs +18 -7
- package/src/store.mjs +65 -10
- package/src/t3-control.mjs +4 -0
- package/src/tool-registry.mjs +73 -14
- package/src/try-hosted.mjs +5 -2
- package/src/work-order.mjs +4 -0
package/src/phase-trace.mjs
CHANGED
|
@@ -6,12 +6,15 @@
|
|
|
6
6
|
// Fresh claims and finish handoffs are told apart by `handoff`: a handoff claim has no wake and no listing of its own.
|
|
7
7
|
// Remembered state is in memory and bounded; a restart forgets it, and the lines then carry nulls, never wrong numbers.
|
|
8
8
|
export const SILENCE_MS=120000;
|
|
9
|
+
export const OFFER_STALL_MS=5*60_000;
|
|
10
|
+
const OFFER_ALERT_INTERVAL_MS=30*60_000;
|
|
11
|
+
const HANDOFF_BACKOFF_MS=5*60_000;
|
|
9
12
|
const iso=ms=>new Date(ms).toISOString();
|
|
10
13
|
const gap=(from,to)=>from==null||to==null?null:Math.round(to-from);
|
|
11
14
|
export function createPhaseTrace({log:write,now=Date.now,max=5000}) {
|
|
12
15
|
// Telemetry only: a failing log write (full disk, missing directory) must never change a tool result or a wake delivery.
|
|
13
16
|
const log=entry=>{try{write(entry);}catch{}};
|
|
14
|
-
const listed=new Map(),woke=new Map(),fresh=new Map(),active=new Map();
|
|
17
|
+
const listed=new Map(),woke=new Map(),fresh=new Map(),active=new Map(),offers=new Map(),lastOfferAlert=new Map(),handoffBackoff=new Map();
|
|
15
18
|
const remember=(map,key,value)=>{map.set(key,value);while(map.size>max)map.delete(map.keys().next().value);};
|
|
16
19
|
// Measurement only: how long a claim goes quiet between the holder's calls. A claim that ends by cancel or lease expiry
|
|
17
20
|
// makes no call, so its last silence is read offline from the last mcp_outcome line against claim_phase.
|
|
@@ -24,7 +27,49 @@ export function createPhaseTrace({log:write,now=Date.now,max=5000}) {
|
|
|
24
27
|
if(final) active.delete(requestId);
|
|
25
28
|
else { claim.last=at;claim.calls++; }
|
|
26
29
|
};
|
|
30
|
+
function endOffer(worker,reason) {
|
|
31
|
+
const offer=offers.get(worker);
|
|
32
|
+
if(!offer)return;
|
|
33
|
+
offers.delete(worker);
|
|
34
|
+
if(offer.alerted) log({kind:'claim_offer_ended',worker,call_id:offer.callId,reason,stall_ms:gap(offer.since,now())});
|
|
35
|
+
}
|
|
27
36
|
return {
|
|
37
|
+
// Only a locally finished response carrying an acquisition recommendation starts this clock.
|
|
38
|
+
offered({worker,subject,callId,readyIds}) {
|
|
39
|
+
if(!readyIds.length) { endOffer(worker,'no_eligible_offer'); return; }
|
|
40
|
+
const previous=offers.get(worker);
|
|
41
|
+
if(previous?.subject===subject&&readyIds.some(id=>previous.readyIds.includes(id))) {
|
|
42
|
+
previous.readyIds=readyIds;
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
endOffer(worker,'offer_changed');
|
|
46
|
+
remember(offers,worker,{subject,callId,readyIds,since:now(),alerted:false});
|
|
47
|
+
},
|
|
48
|
+
claimAttempt(worker) { endOffer(worker,'claim_attempt'); },
|
|
49
|
+
dueOfferStalls(stillOffered) {
|
|
50
|
+
const at=now(), due=[];
|
|
51
|
+
for(const [worker,offer] of offers) {
|
|
52
|
+
if(at-offer.since<OFFER_STALL_MS) continue;
|
|
53
|
+
const ready=stillOffered(worker,offer.subject,offer.readyIds);
|
|
54
|
+
if(ready===false) endOffer(worker,'no_eligible_offer');
|
|
55
|
+
if(ready!==true||offer.alertPending||offer.alerted||
|
|
56
|
+
at-(lastOfferAlert.get(worker)??-Infinity)<OFFER_ALERT_INTERVAL_MS) continue;
|
|
57
|
+
offer.alertPending=true;
|
|
58
|
+
due.push({worker,call_id:offer.callId,stall_ms:gap(offer.since,at)});
|
|
59
|
+
}
|
|
60
|
+
return due;
|
|
61
|
+
},
|
|
62
|
+
offerAlertResult(stall,delivered) {
|
|
63
|
+
const offer=offers.get(stall.worker);
|
|
64
|
+
if(offer?.callId===stall.call_id) {
|
|
65
|
+
offer.alertPending=false;
|
|
66
|
+
if(delivered) offer.alerted=true;
|
|
67
|
+
}
|
|
68
|
+
if(delivered) {
|
|
69
|
+
remember(lastOfferAlert,stall.worker,now());
|
|
70
|
+
log({kind:'claim_offer_stalled',...stall});
|
|
71
|
+
}
|
|
72
|
+
},
|
|
28
73
|
// A list_pending call showed these rows: keep the first time each one was seen.
|
|
29
74
|
listed(requestIds) {
|
|
30
75
|
const at=now();
|
|
@@ -44,13 +89,24 @@ export function createPhaseTrace({log:write,now=Date.now,max=5000}) {
|
|
|
44
89
|
listed.delete(requestId);woke.delete(requestId);
|
|
45
90
|
// Send, answer and listing are separate stamps. A row listed before the answer came back (or before the send) has no known order: null, never a negative gap.
|
|
46
91
|
const wakeToListed=wake&&wake.ackAt!=null&&seen!=null&&seen>=wake.ackAt?gap(wake.ackAt,seen):null;
|
|
47
|
-
remember(fresh,requestId,{claimId,subject,at,handoff});
|
|
92
|
+
remember(fresh,requestId,{claimId,subject,worker,at,handoff});
|
|
48
93
|
remember(active,requestId,{claimId,subject,claimedAt:at,last:at,calls:0});
|
|
49
94
|
log({kind:'claim_phase',request_id:requestId,worker,claim_id:claimId,handoff,created_at:createdAt,
|
|
50
95
|
wake_attempt_at:wake?iso(wake.attemptAt):null,first_listed_at:seen==null?null:iso(seen),claimed_at:iso(at),
|
|
51
96
|
submit_to_wake_ms:gap(created,wake?.attemptAt),wake_ack_ms:wake&&wake.ackAt!=null?Math.round(wake.ackAt-wake.attemptAt):null,
|
|
52
97
|
wake_to_listed_ms:wakeToListed,listed_to_claim_ms:gap(seen,at),submit_to_claim_ms:gap(created,at)});
|
|
53
98
|
},
|
|
99
|
+
handoffBackingOff(worker) { return now()<(handoffBackoff.get(worker)??0); },
|
|
100
|
+
expired(requestId) {
|
|
101
|
+
const claim=fresh.get(requestId);
|
|
102
|
+
if(claim) {
|
|
103
|
+
fresh.delete(requestId);
|
|
104
|
+
if(claim.handoff) remember(handoffBackoff,claim.worker,now()+HANDOFF_BACKOFF_MS);
|
|
105
|
+
log({kind:'claim_expired_before_first_action',request_id:requestId,claim_id:claim.claimId,
|
|
106
|
+
worker:claim.worker,handoff:claim.handoff,claim_age_ms:gap(claim.at,now())});
|
|
107
|
+
}
|
|
108
|
+
active.delete(requestId);
|
|
109
|
+
},
|
|
54
110
|
// The server provides a snapshot taken before the successful progress write.
|
|
55
111
|
progress({requestId,claimId,claimedAt,first,note}) {
|
|
56
112
|
if(!first) return;
|
|
@@ -63,6 +119,7 @@ export function createPhaseTrace({log:write,now=Date.now,max=5000}) {
|
|
|
63
119
|
},
|
|
64
120
|
// Any worker call that names a request. The first one by the claimant after a fresh claim is the first action.
|
|
65
121
|
action({requestId,tool,subject}) {
|
|
122
|
+
if(tool==='claim') return; // Replaying the grant is not starting the job.
|
|
66
123
|
silence({requestId,tool,subject});
|
|
67
124
|
const claim=fresh.get(requestId);
|
|
68
125
|
if(!claim||claim.subject!==subject) return;
|
package/src/pr-preflight.mjs
CHANGED
|
@@ -37,7 +37,9 @@ export async function preflightPR(assignment, { now = Date.now, read = readPullR
|
|
|
37
37
|
prInput(assignment, now());
|
|
38
38
|
if (!remote || !['open', 'closed'].includes(remote.state) || typeof remote.draft !== 'boolean' || !fullSha.test(remote.head?.sha ?? '')) throw Object.assign(new Error('pr_head_unknown: incomplete GitHub observation'),{code:'DOT_BRIDGE_INFRASTRUCTURE'});
|
|
39
39
|
if (remote.state !== 'open' || remote.merged === true) throw new Error('PR is no longer open');
|
|
40
|
-
if (remote.head.sha !== input.head_sha) throw new Error('pr_head_mismatch: pinned revision moved')
|
|
40
|
+
if (remote.head.sha !== input.head_sha) throw Object.assign(new Error('pr_head_mismatch: pinned revision moved'), {
|
|
41
|
+
prHeadMismatch: { pinned: input.head_sha, observed: remote.head.sha },
|
|
42
|
+
});
|
|
41
43
|
return { github_repo: input.github_repo, pr_number: input.pr_number, head_sha: remote.head.sha, draft: remote.draft, checked_at: new Date(now()).toISOString() };
|
|
42
44
|
}
|
|
43
45
|
|
package/src/server.mjs
CHANGED
|
@@ -182,6 +182,9 @@ const scopedSourceChunk=18*1024;
|
|
|
182
182
|
const phaseTrace = createPhaseTrace({ log });
|
|
183
183
|
logShutdownSignals(log);
|
|
184
184
|
// Registry definitions are discovered through list_tools. The native tools/list stays fixed.
|
|
185
|
+
// The job owns repository, pin and path policy. A grant pins those stored values without copying them.
|
|
186
|
+
const scopedInputIdentity = row => createHash('sha256')
|
|
187
|
+
.update(JSON.stringify([row.assignment, row.claim.epoch])).digest('hex');
|
|
185
188
|
const t3PostHandler=createT3PostHandler({store,now:()=>store.nowMs()});
|
|
186
189
|
const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
|
|
187
190
|
t3_post:t3PostHandler,
|
|
@@ -191,6 +194,35 @@ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
|
|
|
191
194
|
validateConfig(_config,{name}) {
|
|
192
195
|
if(name!==scopedInputRegistration.name) throw new RegistryError('invalid_tool','unknown scoped input tool');
|
|
193
196
|
},
|
|
197
|
+
prepareGrant({worker,scope}) {
|
|
198
|
+
const keys = Object.keys(scope).sort().join();
|
|
199
|
+
if (keys !== 'claim_id,expires_at,request_id')
|
|
200
|
+
throw new RegistryError('invalid_tool','scoped input grant requires request_id, claim_id and expires_at');
|
|
201
|
+
const requestId=id(scope.request_id),claimId=id(scope.claim_id,'claim_id');
|
|
202
|
+
const row=store.get(requestId);
|
|
203
|
+
const expires=typeof scope.expires_at==='string' ? Date.parse(scope.expires_at) : NaN;
|
|
204
|
+
if (row.status!=='claimed'||row.cancelled_at||!row.claim)
|
|
205
|
+
throw new RegistryError('invalid_tool','scoped input grant requires a live assignment claim');
|
|
206
|
+
const claim=store.assertClaim(requestId,claimId,row.claim.subject,worker);
|
|
207
|
+
store.assertMutationConnection(requestId,claim,claim.connection_id??null);
|
|
208
|
+
if (!Number.isFinite(expires)||expires<=store.nowMs()||expires>store.leaseDeadlineClockMs(claim))
|
|
209
|
+
throw new RegistryError('invalid_tool','scoped input grant expiry must be within the current claim lease');
|
|
210
|
+
const {inputs,scope_paths,execution_scope,paged_read_scope}=row.assignment;
|
|
211
|
+
const input=inputs?.[0];
|
|
212
|
+
if (execution_scope!=='read-only'||paged_read_scope||inputs?.length!==1||!input?.github_repo||
|
|
213
|
+
!/^[a-f0-9]{40}$/.test(input.base_sha??'')||(input.head_sha&&input.head_sha!==input.base_sha)||
|
|
214
|
+
!scope_paths?.length||scope_paths.includes('.'))
|
|
215
|
+
throw new RegistryError('invalid_tool','scoped input grant requires a pinned read-only assignment with explicit paths');
|
|
216
|
+
assertRepoAllowed(worker,row.assignment);
|
|
217
|
+
return {request_id:requestId,claim_id:claimId,expires_at:new Date(expires).toISOString(),assignment_digest:scopedInputIdentity(row)};
|
|
218
|
+
},
|
|
219
|
+
authorizeGrant(scope,args) {
|
|
220
|
+
if (scope.request_id!==args?.request_id||scope.claim_id!==args?.claim_id) return false;
|
|
221
|
+
try {
|
|
222
|
+
const row=store.get(scope.request_id);
|
|
223
|
+
return scope.assignment_digest===scopedInputIdentity(row);
|
|
224
|
+
} catch { return false; }
|
|
225
|
+
},
|
|
194
226
|
authorizeReplay({args,context}) {
|
|
195
227
|
const {worker,subject,builtin,connection_id}=context,connection=builtin?(connection_id??''):null;
|
|
196
228
|
const requestId=id(args.request_id),claimId=id(args.claim_id,'claim_id');
|
|
@@ -207,7 +239,7 @@ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
|
|
|
207
239
|
return [requestId,claim.claim_id,claim.epoch,subject,connection];
|
|
208
240
|
} catch(error) { throw assignmentRegistryRefusal(error); }
|
|
209
241
|
},
|
|
210
|
-
run({args,context:{worker,subject}}) {
|
|
242
|
+
run({args,context:{worker,subject},grantScope}) {
|
|
211
243
|
const requestId=id(args.request_id),claimId=id(args.claim_id,'claim_id');
|
|
212
244
|
const offset=args.offset??0;
|
|
213
245
|
if(offset%scopedSourceChunk!==0||(offset!==0&&!args.sha256)) throw new RegistryError('invalid_arguments','invalid scoped input offset');
|
|
@@ -215,6 +247,8 @@ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
|
|
|
215
247
|
const {a,input,mirror}=workspace.context(requestId,claimId,subject,false,worker);
|
|
216
248
|
if(input.head_sha&&input.head_sha!==input.base_sha) throw new Error('scoped input requires the reviewed revision to match the base');
|
|
217
249
|
const {manifest,blobs}=pinnedScopedSource(mirror,a.assignment);
|
|
250
|
+
if(grantScope && manifest.files.some(file=>!a.assignment.scope_paths.includes(file.path)))
|
|
251
|
+
throw new Error('assignment grant requires exact scoped files');
|
|
218
252
|
if(!manifest.files.length) throw new Error('no approved scoped input files');
|
|
219
253
|
const files=manifest.files.map(file=>{
|
|
220
254
|
const bytes=blobs.get(file.path);
|
|
@@ -760,6 +794,7 @@ function sweepSkipped() {
|
|
|
760
794
|
function sweepStaleLeases() {
|
|
761
795
|
const ids=store.sweepStaleLeases();
|
|
762
796
|
if(ids.length) log({kind:'claims_lease_expired',count:ids.length,request_ids:ids.slice(0,20)});
|
|
797
|
+
for(const id of ids) phaseTrace.expired(id);
|
|
763
798
|
return ids;
|
|
764
799
|
}
|
|
765
800
|
const destinations=createDestinations({store,ackLedger,notify:notifyAttachedWaiter,log,crashAt,exit:code=>process.exit(code)});
|
|
@@ -855,7 +890,13 @@ function logPendingReply(reply,{worker,subject},callId,batch={}) {
|
|
|
855
890
|
|
|
856
891
|
// Put the next acquisition before job detail, including after progress and finish.
|
|
857
892
|
// Derive it after the call (and any finish handoff) so it describes remaining capacity.
|
|
858
|
-
function
|
|
893
|
+
function batchRoom(subject,worker) {
|
|
894
|
+
const {free_lanes,ready,available,reservedId}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
|
|
895
|
+
const hint=store.claimHint(worker);
|
|
896
|
+
const hintFree=hint===null?Infinity:Math.max(Number(!!reservedId),hint-store.recentClaimCount(worker));
|
|
897
|
+
return {free_lanes,ready,available,hintFree,next:Math.min(available,ready.length,8,hintFree)};
|
|
898
|
+
}
|
|
899
|
+
function batchCapacityReply(name,reply,principal,callId,onOffer) {
|
|
859
900
|
if(!['list_pending','claim','progress','finish'].includes(name)) return reply;
|
|
860
901
|
const recordListing=name==='list_pending'&&!!callId;
|
|
861
902
|
if(!batchClaimProfile) {
|
|
@@ -863,11 +904,8 @@ function batchCapacityReply(name,reply,principal,callId) {
|
|
|
863
904
|
return reply;
|
|
864
905
|
}
|
|
865
906
|
const {worker,subject}=principal;
|
|
866
|
-
const {free_lanes,ready,available,
|
|
907
|
+
const {free_lanes,ready,available,hintFree,next}=batchRoom(subject,worker);
|
|
867
908
|
const ready_queued=ready.length;
|
|
868
|
-
const hint=store.claimHint(worker);
|
|
869
|
-
const hintFree=hint===null?Infinity:Math.max(Number(!!reservedId),hint-store.recentClaimCount(worker));
|
|
870
|
-
const next=Math.min(available,ready_queued,8,hintFree);
|
|
871
909
|
const [reason,next_action]=quiescing?['quiescing',restartQuiesceText]:
|
|
872
910
|
store.paused()?['paused','Claims are paused; call list_pending again later.']:
|
|
873
911
|
next>0?['ready',`claim with next=${next} now`]:
|
|
@@ -878,8 +916,9 @@ function batchCapacityReply(name,reply,principal,callId) {
|
|
|
878
916
|
const response={next_action,free_lanes,ready_queued,...rest};
|
|
879
917
|
if(recordListing) {
|
|
880
918
|
const recommended=reason==='ready'?next:0;
|
|
881
|
-
|
|
882
|
-
|
|
919
|
+
const readyIds=ready.slice(0,recommended).map(item=>item.request_id);
|
|
920
|
+
logPendingReply(response,principal,callId,{ready_queued,dispatch_reason:reason,recommended_claims:recommended,ready_head_ids:readyIds});
|
|
921
|
+
if(readyIds.length) onOffer?.({worker,subject,callId,readyIds});
|
|
883
922
|
}
|
|
884
923
|
return response;
|
|
885
924
|
}
|
|
@@ -951,7 +990,7 @@ async function runHandoff({principal,requestId,claimId,waitMs,maxJobs=1,idleLeas
|
|
|
951
990
|
// Rows whose last handoff lapsed untouched are left for the worker's own list_pending: the same rows were handed ten times and never started.
|
|
952
991
|
const pick=free=>(store.nextQueued(free,null,worker,{applyHint:false,handoffExclusions:tried}).next_queued??[]);
|
|
953
992
|
for(;;) {
|
|
954
|
-
if(signal?.aborted||store.paused()) return jobs.length?{jobs}:{};
|
|
993
|
+
if(signal?.aborted||store.paused()||(batchClaimProfile&&phaseTrace.handoffBackingOff(worker))) return jobs.length?{jobs}:{};
|
|
955
994
|
const {free_lanes}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
|
|
956
995
|
if(free_lanes<=0) return jobs.length?{jobs}:{};
|
|
957
996
|
if(store.hasQueuedFor([worker])) {
|
|
@@ -970,6 +1009,7 @@ async function runHandoff({principal,requestId,claimId,waitMs,maxJobs=1,idleLeas
|
|
|
970
1009
|
fresh=pick(store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity).free_lanes);
|
|
971
1010
|
continue;
|
|
972
1011
|
}
|
|
1012
|
+
if(batchClaimProfile&&phaseTrace.handoffBackingOff(worker)) return jobs.length?{jobs}:{};
|
|
973
1013
|
tried.add(fresh[0].request_id);
|
|
974
1014
|
const job=await claim(fresh[0].request_id,slot);
|
|
975
1015
|
if(job) { jobs.push(job); if(jobs.length>=maxJobs) return {jobs}; }
|
|
@@ -1207,7 +1247,10 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
|
|
|
1207
1247
|
const t3=await import('./t3.mjs');
|
|
1208
1248
|
const authorize=()=>{
|
|
1209
1249
|
const threads=toolRegistry.t3Threads(name,principal);
|
|
1210
|
-
if(name!=='t3_thread_list' && !threads.has(a.threadId))
|
|
1250
|
+
if(name!=='t3_thread_list' && !threads.has(a.threadId)) {
|
|
1251
|
+
log(control.destinationDeniedEvent(name,principal.worker,audit.call_id));
|
|
1252
|
+
throw new RegistryError('tool_unavailable','tool unavailable');
|
|
1253
|
+
}
|
|
1211
1254
|
return threads;
|
|
1212
1255
|
};
|
|
1213
1256
|
// Linearization point: this synchronous live-grant read follows the last await before
|
|
@@ -1319,7 +1362,17 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
|
|
|
1319
1362
|
// A fresh claim, a claim after abandon and an expired-lease takeover are each a new admission. The Store
|
|
1320
1363
|
// still validates claimant, subject, lease, cancellation and capacity atomically.
|
|
1321
1364
|
const admission=!store.paused()&&(row.status==='queued'||row.status==='claimed'&&held&&!(held.claimant===claimant&&held.subject===subject)&&store.leaseExpired(held));
|
|
1322
|
-
|
|
1365
|
+
let preflight=null;
|
|
1366
|
+
if(admission) {
|
|
1367
|
+
try {
|
|
1368
|
+
preflight=await preflightPR(row.assignment);
|
|
1369
|
+
if(preflight) store.clearPrClaimMismatch(requestId,preflight);
|
|
1370
|
+
}
|
|
1371
|
+
catch(error) {
|
|
1372
|
+
if(error.prHeadMismatch) store.recordPrClaimMismatch(requestId,error.prHeadMismatch);
|
|
1373
|
+
throw error;
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1323
1376
|
if(!retry) {
|
|
1324
1377
|
assertRepoAllowed(worker,row.assignment);
|
|
1325
1378
|
// Resolve an optional workspace grant after remote preflight but before claim acquisition. A broken
|
|
@@ -1492,7 +1545,7 @@ function publicErrorText(error,what) {
|
|
|
1492
1545
|
log({kind:'request_error',what,error_id:errorId,detail:safeDiagnostic(error?.stack??error,4000)});
|
|
1493
1546
|
return `Error executing ${what} (error id ${errorId}; details are in the request log)`;
|
|
1494
1547
|
}
|
|
1495
|
-
async function dispatch(message,principal,signal,callId) {
|
|
1548
|
+
async function dispatch(message,principal,signal,callId,onOffer) {
|
|
1496
1549
|
const p=message.params??{};
|
|
1497
1550
|
switch(message.method) {
|
|
1498
1551
|
case 'server/discover': return {ttlMs:0,cacheScope:'private',supportedVersions:['2026-07-28'],capabilities:{tools:{},events:{}},_meta:{'io.modelcontextprotocol/serverInfo':serverInfo}};
|
|
@@ -1501,7 +1554,7 @@ async function dispatch(message,principal,signal,callId) {
|
|
|
1501
1554
|
// Modern catalogs are process-wide. A worker's capability controls tools/call authority, not its cached schemas.
|
|
1502
1555
|
// legacy-v46 keeps its pinned per-worker surface for compatibility.
|
|
1503
1556
|
case 'tools/list': return {ttlMs:0,cacheScope:'private',tools:catalogProfile==='legacy-v46'?advertisedTools.filter(t=>!(t3Tools.has(t.name)||notifyTools.has(t.name))||hasCapability(workers,principal.worker,'t3')):advertisedTools};
|
|
1504
|
-
case 'tools/call': { try { return {content:[{type:'text',text:JSON.stringify(redactOutput(batchCapacityReply(p.name,await tool(p.name,p.arguments??{},principal,notifyTools.has(p.name)?p._meta:undefined,signal),principal,callId)))}],isError:false}; } catch(e) { const error={content:[{type:'text',text:publicErrorText(e,`tool ${toolNames.has(p.name)?p.name:'unknown'}`)}],isError:true};if(oauth&&e.message==='insufficient_scope')error._meta={'mcp/www_authenticate':[[challenge(oauth,scopeFor(p.name)),'error="insufficient_scope"','error_description="Required scope is missing"'].join(', ')]};return error; } }
|
|
1557
|
+
case 'tools/call': { try { return {content:[{type:'text',text:JSON.stringify(redactOutput(batchCapacityReply(p.name,await tool(p.name,p.arguments??{},principal,notifyTools.has(p.name)?p._meta:undefined,signal),principal,callId,onOffer)))}],isError:false}; } catch(e) { const error={content:[{type:'text',text:publicErrorText(e,`tool ${toolNames.has(p.name)?p.name:'unknown'}`)}],isError:true};if(oauth&&e.message==='insufficient_scope')error._meta={'mcp/www_authenticate':[[challenge(oauth,scopeFor(p.name)),'error="insufficient_scope"','error_description="Required scope is missing"'].join(', ')]};return error; } }
|
|
1505
1558
|
case 'events/list': return {events:[event]};
|
|
1506
1559
|
case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
|
|
1507
1560
|
case 'events/unsubscribe': { if(oauth)needScope(principal,'dalan.read');if(!validEventParams(p)) throw new Error('invalid subscription'); store.unsubscribe(subId(p.delivery.url,principal.subject,principal.worker)); return {}; }
|
|
@@ -1543,11 +1596,12 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
|
|
|
1543
1596
|
// Metadata only: bodies can carry webhook secrets and worker results.
|
|
1544
1597
|
log({kind:'mcp_inbound',call_id:outcome.state.call_id,rpc_method:outcome.state.rpc_method,tool:outcome.state.tool,worker:principal.worker,ua:uaToken(req)});
|
|
1545
1598
|
if(!Object.hasOwn(rpc,'id')) { res.writeHead(202); res.end(); return; }
|
|
1599
|
+
if(outcome.state.tool==='claim') phaseTrace.claimAttempt(principal.worker);
|
|
1546
1600
|
outcome.state.phase='dispatch';
|
|
1547
1601
|
const eventStream=readEnv('DALAN_TRIAL_SSE')==='1'&&req.method==='POST'&&acceptsMcpEventStream(req.headers.accept)?beginMcpEventStream(res):null;
|
|
1548
1602
|
// A tool that waits (finish with finish_handoff) stops when the client leaves, so nothing is claimed for nobody.
|
|
1549
1603
|
const clientGone=new AbortController();res.once('close',()=>clientGone.abort());if(res.destroyed)clientGone.abort();
|
|
1550
|
-
try { json(res,200,{jsonrpc:'2.0',id:rpc.id,result:{resultType:'complete',...await dispatch(rpc,principal,clientGone.signal,outcome.state.call_id)}},eventStream); }
|
|
1604
|
+
try { json(res,200,{jsonrpc:'2.0',id:rpc.id,result:{resultType:'complete',...await dispatch(rpc,principal,clientGone.signal,outcome.state.call_id,offer=>res.once('finish',()=>phaseTrace.offered(offer)))}},eventStream); }
|
|
1551
1605
|
catch(e) { json(res,200,rpcError(rpc.id,e.code||-32602,publicErrorText(e,'request'),e.data),eventStream); }
|
|
1552
1606
|
// Response-byte accounting for the throttle and the break ledger; the response is already written, so a failure only logs.
|
|
1553
1607
|
if(outcome.state.tool) try { store.recordResponseBytes(principal.subject,outcome.state.tool,outcome.state.response_bytes,principal.worker); } catch(e) { log({kind:'response_bytes_error',call_id:outcome.state.call_id,reason:e.message}); }
|
|
@@ -1663,6 +1717,16 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1663
1717
|
// Reject immutable retry conflicts using the persisted binding before any external destination inspection.
|
|
1664
1718
|
// A matching retry still validates the current destination below; this does not accept stale environment evidence.
|
|
1665
1719
|
store.checkRetry(submitted,delivery,existingRequest?.environment_id,owner,body.review===true,body.background===true?'background':'normal',meta,submitted,target,explicitExecution,requiredCapabilities,commandKey,supersedes,destinationRevision,revises,follows,body.caller_waiting);
|
|
1720
|
+
const assignedWorker=storedTarget??target??'dot';
|
|
1721
|
+
const requiredAdapterCapabilities=jobExecution==='host'
|
|
1722
|
+
?requiredCapabilities?.filter(name=>ADAPTER_CAPABILITY_NAMES.includes(name))
|
|
1723
|
+
:requiredCapabilities;
|
|
1724
|
+
const admitWorkerAdapter=()=>{
|
|
1725
|
+
const adapter=workers.workers.get(assignedWorker)?.adapter;
|
|
1726
|
+
const registryQuestions=adapter==='registry-questions-v1'&&requiredAdapterCapabilities?.includes('identified_questions')
|
|
1727
|
+
&&toolRegistry.hasWorkerTools(assignedWorker,questionDefinitions,{kind:'worker_question'});
|
|
1728
|
+
admitAdapterCapabilities(adapter,requiredAdapterCapabilities,catalogProfile,{registryQuestions});
|
|
1729
|
+
};
|
|
1666
1730
|
let order=null;
|
|
1667
1731
|
if(isNew) {
|
|
1668
1732
|
// checkRetry has already verified the prior owner's capability and the active worker.
|
|
@@ -1672,8 +1736,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1672
1736
|
excludeSensitive:body.exclude_sensitive===true,sensitiveScopeOverride:body.sensitive_scope_override??null,target:target??'dot'},{
|
|
1673
1737
|
render:renderAssignment,
|
|
1674
1738
|
admitExecution:(p,r)=>{
|
|
1675
|
-
|
|
1676
|
-
admitAdapterCapabilities(workers.workers.get(storedTarget??target??'dot')?.adapter,adapterRequired,catalogProfile);
|
|
1739
|
+
admitWorkerAdapter();
|
|
1677
1740
|
// No usable executor, or a required capability the backend does not declare verified: never degraded to a run without it.
|
|
1678
1741
|
if(r.jobExecution==='host'&&(p.execution_scope==='implementation'||r.requiredCapabilities)) admitHostExecution(r.requiredCapabilities?.filter(name=>!ADAPTER_CAPABILITY_NAMES.includes(name)));
|
|
1679
1742
|
},
|
|
@@ -1716,10 +1779,14 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1716
1779
|
const readiness=order?.check_readiness??null;
|
|
1717
1780
|
const preflight=order?.preflight??null;
|
|
1718
1781
|
const defaultValidity=order?.defaultValidity??null;
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
if(
|
|
1722
|
-
|
|
1782
|
+
// I/O can outlive a grant or an overlapping submit. Store.submit checks the immutable identity of any replay.
|
|
1783
|
+
if(!store.hasAssignment(payload.request_id)) {
|
|
1784
|
+
if(body.facade_submit_until!==undefined) {
|
|
1785
|
+
const until=body.facade_submit_until;
|
|
1786
|
+
if(!Number.isSafeInteger(until)||until>requestStartedAt+600_000) throw new Error('invalid facade submission deadline');
|
|
1787
|
+
if(until<=store.nowMs()) throw new Error('facade submission deadline expired');
|
|
1788
|
+
}
|
|
1789
|
+
admitWorkerAdapter();
|
|
1723
1790
|
}
|
|
1724
1791
|
const result=store.submit(payload,delivery,environmentId,owner,body.review===true,preflight,body.background===true?'background':'normal',meta,(()=>{const r=renderAssignment(submitted);return payload.brief!==r.brief||JSON.stringify(payload.scope_paths)!==JSON.stringify(r.scope_paths);})()?submitted:payload,body.max_queued??null,target,explicitExecution,workers.defaultExecution,requiredCapabilities,defaultValidity?.valid_until??null,commandKey,supersedes,destinationRevision,null,generation??null,body.relationship_id??null,revises,follows,body.caller_waiting);
|
|
1725
1792
|
// Only a committed first replacement wakes the TARGET's already-attached waiter.
|
|
@@ -1857,7 +1924,14 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1857
1924
|
if(url.pathname==='/note'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId); return json(res,200,store.note(requestId,body.text)); }
|
|
1858
1925
|
if(url.pathname==='/answer'&&req.method==='POST') { const requestId=id(body.id); adminOwner(req,requestId);const questionId=str(body.question_id,'question_id',128); requireOperatorForHumanQuestion(req,requestId,questionId);return json(res,200,store.answerQuestion(requestId,questionId,str(body.text,'text',4096),{key:body.command_key,revision:body.expected_revision},req.headers['x-owner-capability'])); }
|
|
1859
1926
|
if(url.pathname==='/questions'&&req.method==='GET') { const requestId=id(url.searchParams.get('id'));adminOwner(req,requestId);return json(res,200,{request_id:requestId,questions:store.questions(requestId)}); }
|
|
1860
|
-
if(url.pathname==='/tell'&&req.method==='POST')
|
|
1927
|
+
if(url.pathname==='/tell'&&req.method==='POST') {
|
|
1928
|
+
const text=str(body.text,'text',4096);
|
|
1929
|
+
if(body.request_id!==undefined) {
|
|
1930
|
+
const worker=body.worker===undefined?null:assertTarget(workers,body.worker);
|
|
1931
|
+
return json(res,200,store.tell(text,worker,{requestId:id(body.request_id),capability:req.headers['x-owner-capability']}));
|
|
1932
|
+
}
|
|
1933
|
+
return json(res,200,store.tell(text,body.worker===undefined&&workers.workers.has('dot')?'dot':submitTarget(workers,body.worker)??assertTarget(workers,'dot')));
|
|
1934
|
+
}
|
|
1861
1935
|
if(url.pathname==='/untell'&&req.method==='POST') return json(res,200,store.untell(id(body.message_id,'message_id'),body.worker===undefined?null:assertTarget(workers,body.worker)));
|
|
1862
1936
|
if(url.pathname==='/relationships'&&req.method==='GET') { adminOperator(req); return json(res,200,{relationships:store.db.prepare('SELECT * FROM relationships ORDER BY created_at, rowid').all()}); }
|
|
1863
1937
|
if(url.pathname==='/relationships/publish'&&req.method==='POST') {
|
|
@@ -1876,7 +1950,7 @@ const adminServer=http.createServer(async(req,res)=>{
|
|
|
1876
1950
|
const currentWorkers=loadEffectiveOwnerWorkers(workersFile);
|
|
1877
1951
|
const grants=[
|
|
1878
1952
|
...store.db.prepare("SELECT c.*,a.relationship_id FROM claims c JOIN assignments a USING(request_id) WHERE c.state='active' AND a.status='claimed'").all().filter(row=>!store.leaseExpired(row)).map(row=>({request_id:row.request_id,worker:row.worker,relationship_id:row.relationship_id,expires_at:store.leaseExpiresAt(row),enforcer:'claim_lease'})),
|
|
1879
|
-
...
|
|
1953
|
+
...toolRegistry.listGrants().map(row=>({...row,enforcer:'tool_registry'})),
|
|
1880
1954
|
...store.db.prepare('SELECT d.request_id,d.revision,d.approved_at,a.relationship_id FROM destination_approvals d JOIN assignments a USING(request_id)').all().map(row=>({...row,enforcer:'destination_approval',expires_at:null})),
|
|
1881
1955
|
...store.activeSubscriptions().map(({id,principal,worker,expires_at})=>({id,principal,worker,expires_at,enforcer:'subscription'})),
|
|
1882
1956
|
...store.db.prepare('SELECT request_id,relationship_id FROM assignments WHERE owner_hash IS NOT NULL').all().filter(row=>store.protocolListingLive(row.request_id)).map(row=>({...row,enforcer:'owner_capability',expires_at:store.getProtocol(row.request_id)?new Date(store.getProtocol(row.request_id).retain_until_ms).toISOString():null})),
|
|
@@ -2218,6 +2292,27 @@ const staleDays=(d=>Number.isFinite(d)&&d>0?d:7)(Number(readEnv('DALAN_DECISION_
|
|
|
2218
2292
|
const sweepStale=()=>{try{const ids=store.sweepStaleDecisions(staleDays);if(ids.length)log({kind:'decisions_stale',count:ids.length,request_ids:ids.slice(0,20)});}catch(error){log({kind:'decisions_stale_error',reason:error.message});}};
|
|
2219
2293
|
sweepStale(); setInterval(sweepStale,3600000).unref();
|
|
2220
2294
|
setInterval(()=>checkAlerts(store,log).catch(e=>log({kind:'alert_error',reason:e.message})),60000).unref();
|
|
2295
|
+
setInterval(()=>{
|
|
2296
|
+
try {
|
|
2297
|
+
const due=phaseTrace.dueOfferStalls((worker,subject,ids)=>{
|
|
2298
|
+
const queued=store.db.prepare(`SELECT 1 FROM assignments WHERE status='queued'
|
|
2299
|
+
AND request_id IN (${ids.map(()=>'?').join(',')}) LIMIT 1`).get(...ids);
|
|
2300
|
+
if(!queued) return false;
|
|
2301
|
+
if(store.paused()||quiescing||store.holdingBreak(worker)||store.capacityHoldUntil(worker)) return null;
|
|
2302
|
+
const {ready,next}=batchRoom(subject,worker);
|
|
2303
|
+
return ready.slice(0,next).some(item=>ids.includes(item.request_id))?true:null;
|
|
2304
|
+
});
|
|
2305
|
+
for(const stall of due) {
|
|
2306
|
+
const {worker,call_id,stall_ms}=stall;
|
|
2307
|
+
void publishAlert('Dalan attention',`claim_offer_stalled: ${worker} received an offer and sent no claim for ${Math.floor(stall_ms/60000)} minutes. Check the worker conversation.`,log,
|
|
2308
|
+
{idempotencyKey:`claim-offer-stalled:${worker}:${call_id}`})
|
|
2309
|
+
.then(delivered=>phaseTrace.offerAlertResult(stall,delivered),error=>{
|
|
2310
|
+
phaseTrace.offerAlertResult(stall,false);
|
|
2311
|
+
log({kind:'claim_offer_alert_error',worker,reason:redactNote(error.message)});
|
|
2312
|
+
});
|
|
2313
|
+
}
|
|
2314
|
+
} catch(error) { log({kind:'claim_offer_alert_error',reason:redactNote(error.message)}); }
|
|
2315
|
+
},60000).unref();
|
|
2221
2316
|
}
|
|
2222
2317
|
const startWhenWindowCloses=()=>{ if(updateWindowOpen()) setTimeout(startWhenWindowCloses,250).unref(); else startBackground(); };
|
|
2223
2318
|
startWhenWindowCloses();
|
|
@@ -312,7 +312,7 @@ export async function stopChild(child, { termTimeoutMs = 3000, killTimeoutMs = 5
|
|
|
312
312
|
return await killWait || child.exitCode !== null || child.signalCode !== null || child.spawned === false;
|
|
313
313
|
}
|
|
314
314
|
|
|
315
|
-
async function requireCatalogGuard(repo, env, receipt, options) {
|
|
315
|
+
async function requireCatalogGuard(repo, env, receipt, options, stopProbe) {
|
|
316
316
|
const child = (options.spawn ?? spawn)(receipt.node ?? process.execPath, [path.join(repo, 'src/server.mjs')], { cwd: repo, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
317
317
|
let stdout = '', stderr = '';
|
|
318
318
|
let spawnError = null, closed = false;
|
|
@@ -331,7 +331,7 @@ async function requireCatalogGuard(repo, env, receipt, options) {
|
|
|
331
331
|
if (!closed) fail('candidate did not enforce the service catalog pin before timeout');
|
|
332
332
|
if (/MCP listening|admin socket/.test(stdout)) fail('candidate announced a listener before enforcing the service catalog pin');
|
|
333
333
|
if (child.exitCode === 0 || !stderr.includes('service catalog guard mismatch')) fail('candidate did not reject the mismatched service catalog pin');
|
|
334
|
-
} finally { await
|
|
334
|
+
} finally { await stopProbe(child); }
|
|
335
335
|
}
|
|
336
336
|
|
|
337
337
|
// Only fixed diagnostics authored by this module; never propagate socket or filesystem data.
|
|
@@ -347,11 +347,15 @@ const SAFE_CANDIDATE_PROBE_FAILURES = new Set([
|
|
|
347
347
|
]);
|
|
348
348
|
|
|
349
349
|
export async function probeCandidate(home, receipt, repo, options = {}) {
|
|
350
|
-
const scratchBase = path.join(os.homedir(), '.tmp');
|
|
350
|
+
const scratchBase = options.scratchBase ?? path.join(os.homedir(), '.tmp');
|
|
351
351
|
fs.mkdirSync(scratchBase, { recursive: true, mode: 0o700 });
|
|
352
352
|
const scratch = fs.mkdtempSync(path.join(scratchBase, 'dalan-candidate-'));
|
|
353
353
|
fs.chmodSync(scratch, 0o700);
|
|
354
354
|
let child;
|
|
355
|
+
let settled = true, succeeded = false;
|
|
356
|
+
const stopProbe = async candidate => {
|
|
357
|
+
if (!(await stopChild(candidate, options.stopBounds))) settled = false;
|
|
358
|
+
};
|
|
355
359
|
try {
|
|
356
360
|
prepareProbeConfig(home, scratch);
|
|
357
361
|
const serviceEnv = await (options.serviceEnvironment?.(receipt) ?? effectiveServiceEnvironment(receipt, options));
|
|
@@ -366,8 +370,8 @@ export async function probeCandidate(home, receipt, repo, options = {}) {
|
|
|
366
370
|
const pinFile = path.join(configDir, 'service-catalog.json');
|
|
367
371
|
const version = JSON.parse(fs.readFileSync(path.join(repo, 'package.json'), 'utf8')).version;
|
|
368
372
|
fs.writeFileSync(pinFile, JSON.stringify({ version, catalogs: {} }), { mode: 0o600, flag: 'wx' });
|
|
369
|
-
try { await requireCatalogGuard(repo, env, receipt, options); }
|
|
370
|
-
finally { fs.rmSync(pinFile, { force: true }); }
|
|
373
|
+
try { await requireCatalogGuard(repo, env, receipt, options, stopProbe); }
|
|
374
|
+
finally { if (settled) fs.rmSync(pinFile, { force: true }); }
|
|
371
375
|
child = (options.spawn ?? spawn)(receipt.node ?? process.execPath, [path.join(repo, 'src/server.mjs')], { cwd: repo, env, stdio: ['ignore', 'ignore', 'ignore'] });
|
|
372
376
|
let spawnError = null, closed = false;
|
|
373
377
|
child.on('error', error => { spawnError = error; });
|
|
@@ -388,10 +392,17 @@ export async function probeCandidate(home, receipt, repo, options = {}) {
|
|
|
388
392
|
if (!result) fail(lastSafeProbeFailure
|
|
389
393
|
? `candidate service did not pass its self-check: ${lastSafeProbeFailure}`
|
|
390
394
|
: 'candidate service did not pass its self-check before timeout');
|
|
395
|
+
succeeded = true;
|
|
391
396
|
return result;
|
|
392
397
|
} finally {
|
|
393
|
-
await
|
|
394
|
-
fs.rmSync(scratch, { recursive: true, force: true });
|
|
398
|
+
await stopProbe(child);
|
|
399
|
+
if (settled) fs.rmSync(scratch, { recursive: true, force: true });
|
|
400
|
+
else {
|
|
401
|
+
const warning = 'Candidate probe did not confirm child shutdown; temporary files were retained. Stop the remaining probe before removing its temporary files.';
|
|
402
|
+
if (succeeded) fail(warning);
|
|
403
|
+
// Preserve the original typed failure and do not print a private path.
|
|
404
|
+
console.warn(warning);
|
|
405
|
+
}
|
|
395
406
|
}
|
|
396
407
|
}
|
|
397
408
|
|
package/src/store.mjs
CHANGED
|
@@ -1143,6 +1143,15 @@ export class Store {
|
|
|
1143
1143
|
end_source TEXT, last_probe_at TEXT
|
|
1144
1144
|
); CREATE UNIQUE INDEX IF NOT EXISTS scoped_worker_breaks_one_open
|
|
1145
1145
|
ON scoped_worker_breaks(worker) WHERE until IS NULL;`);
|
|
1146
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS pr_claim_blocks(
|
|
1147
|
+
request_id TEXT PRIMARY KEY REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1148
|
+
pinned TEXT NOT NULL, observed TEXT NOT NULL, checked_at TEXT NOT NULL
|
|
1149
|
+
);`);
|
|
1150
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS work_messages(
|
|
1151
|
+
message_id TEXT PRIMARY KEY REFERENCES messages(message_id) ON DELETE CASCADE,
|
|
1152
|
+
request_id TEXT NOT NULL REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1153
|
+
progress_id INTEGER UNIQUE REFERENCES progress(id) ON DELETE SET NULL
|
|
1154
|
+
);`);
|
|
1146
1155
|
this.db.exec(`CREATE TABLE IF NOT EXISTS admission_reservations(
|
|
1147
1156
|
worker TEXT PRIMARY KEY, request_id TEXT NOT NULL UNIQUE REFERENCES assignments(request_id) ON DELETE CASCADE,
|
|
1148
1157
|
subscription_id TEXT NOT NULL, issued_at TEXT NOT NULL, expires_at TEXT NOT NULL,
|
|
@@ -1336,7 +1345,8 @@ export class Store {
|
|
|
1336
1345
|
// Use persisted worker progress for the start proxy. A reclaim resets the
|
|
1337
1346
|
// first workspace call on the single current claim row, so mixing that time
|
|
1338
1347
|
// in would make a job's measured first start change as it is reclaimed. Notes the bridge writes itself (the resume note)
|
|
1339
|
-
// start with `[bridge]
|
|
1348
|
+
// start with `[bridge] `. Inbox acknowledgments also don't attest to work starting.
|
|
1349
|
+
// A finished job without observed progress started at an unobserved time.
|
|
1340
1350
|
admissionEvidence(worker,kind,days=7) {
|
|
1341
1351
|
kind=canonicalKindLabel(kind);
|
|
1342
1352
|
const since=iso(this.nowMs()-days*86400000);
|
|
@@ -1354,6 +1364,7 @@ export class Store {
|
|
|
1354
1364
|
(SELECT p.created_at FROM progress p INDEXED BY progress_request WHERE p.request_id=a.request_id
|
|
1355
1365
|
AND (p.worker IS NULL OR p.worker=a.target_worker)
|
|
1356
1366
|
AND p.note NOT LIKE '[bridge] %'
|
|
1367
|
+
AND NOT EXISTS (SELECT 1 FROM work_messages m WHERE m.progress_id=p.id)
|
|
1357
1368
|
ORDER BY p.id LIMIT 1) started
|
|
1358
1369
|
FROM selected a JOIN lifecycle l ON l.request_id=a.request_id
|
|
1359
1370
|
LEFT JOIN claims c ON c.request_id=a.request_id`).all(since,worker,kind);
|
|
@@ -2686,7 +2697,10 @@ export class Store {
|
|
|
2686
2697
|
if(report) { report.trust=TRUST.worker; Object.assign(report,Store.resultAuthority(!!report.late)); }
|
|
2687
2698
|
const lateRow=this.db.prepare('SELECT summary,truncated,full_sha256,created_at FROM late_evidence WHERE request_id=? ORDER BY created_at LIMIT 1').get(id);
|
|
2688
2699
|
const late_evidence=lateRow?{...lateRow,truncated:!!lateRow.truncated}:null;
|
|
2689
|
-
const progress=this.db.prepare(
|
|
2700
|
+
const progress=this.db.prepare(`SELECT p.note,p.created_at,p.worker,m.message_id
|
|
2701
|
+
FROM progress p LEFT JOIN work_messages m ON m.progress_id=p.id
|
|
2702
|
+
WHERE p.request_id=? ORDER BY p.id`).all(id).map(({worker,message_id,...event})=>
|
|
2703
|
+
message_id===null?event:{...event,kind:'ack_message',message_id,acknowledged_by_worker:worker});
|
|
2690
2704
|
const delivery=this.db.prepare('SELECT id,kind,state,attempts,last_error,argv,attempt_started_at,attempt_id,last_reconciled_at,uncertain_reason,terminal_at,terminal_reason FROM notifications WHERE request_id=? ORDER BY created_at').all(id).map(n=>({...n,argv:n.argv?JSON.parse(n.argv):null}));
|
|
2691
2705
|
const watch=this.db.prepare('SELECT deadline,state,updated_at,notification_id FROM watches WHERE request_id=?').get(id) || null;
|
|
2692
2706
|
const supersedes=this.db.prepare('SELECT target_id AS request_id,created_at FROM submit_supersedes WHERE request_id=?').get(id)??null;
|
|
@@ -2725,6 +2739,16 @@ export class Store {
|
|
|
2725
2739
|
if(!changed.changes) throw new Error('relationship_not_found');
|
|
2726
2740
|
return this.db.prepare('SELECT * FROM relationships WHERE relationship_id=?').get(relationshipId);
|
|
2727
2741
|
}
|
|
2742
|
+
recordPrClaimMismatch(id,{pinned,observed}) {
|
|
2743
|
+
this.db.prepare(`INSERT INTO pr_claim_blocks(request_id,pinned,observed,checked_at)
|
|
2744
|
+
SELECT request_id,?,?,? FROM assignments WHERE request_id=? AND status='queued'
|
|
2745
|
+
ON CONFLICT(request_id) DO UPDATE SET observed=excluded.observed,checked_at=excluded.checked_at
|
|
2746
|
+
WHERE pr_claim_blocks.pinned=excluded.pinned`).run(pinned,observed,this.stamp(),id);
|
|
2747
|
+
}
|
|
2748
|
+
clearPrClaimMismatch(id,{head_sha,checked_at}) {
|
|
2749
|
+
this.db.prepare('DELETE FROM pr_claim_blocks WHERE request_id=? AND pinned=? AND checked_at<=?')
|
|
2750
|
+
.run(id,head_sha,checked_at);
|
|
2751
|
+
}
|
|
2728
2752
|
recordPrPreflight(id,phase,assignment,evidence,replace=false) {
|
|
2729
2753
|
assertPreflight(assignment,evidence,this.nowMs());
|
|
2730
2754
|
if(evidence) this.db.prepare(`INSERT ${replace?'OR REPLACE ':''}INTO pr_preflights(request_id,phase,evidence) VALUES(?,?,?)`).run(id,phase,JSON.stringify(evidence));
|
|
@@ -2852,12 +2876,21 @@ export class Store {
|
|
|
2852
2876
|
try { validateOwnerNote(text,this.ownerNotes(priorId)); } catch { return; }
|
|
2853
2877
|
this.noteInTransaction(priorId,text);
|
|
2854
2878
|
}
|
|
2855
|
-
tell(text,worker=
|
|
2879
|
+
tell(text,worker=null,work=null) { return this.transaction(() => {
|
|
2880
|
+
if(work) {
|
|
2881
|
+
this.owner(work.requestId,work.capability);
|
|
2882
|
+
const row=this.db.prepare('SELECT status,target_worker FROM assignments WHERE request_id=?').get(work.requestId);
|
|
2883
|
+
if(!row||!['queued','claimed'].includes(row.status)) throw new Error('work message requires an open assignment');
|
|
2884
|
+
if(worker!==null&&worker!==row.target_worker) throw new Error('work message worker must match the assignment');
|
|
2885
|
+
worker=row.target_worker;
|
|
2886
|
+
}
|
|
2887
|
+
worker??='dot';
|
|
2856
2888
|
if(worker==='pool') throw new Error('worker \"pool\" is not supported');
|
|
2857
2889
|
const messageId=`msg_${randomUUID()}`, preview=text.slice(0,200), createdAt=this.stamp();
|
|
2858
2890
|
this.db.prepare('INSERT INTO messages(message_id,text,text_sha256,preview,created_at,target_worker) VALUES(?,?,?,?,?,?)').run(messageId,text,hash(text),preview,createdAt,worker);
|
|
2891
|
+
if(work) this.db.prepare('INSERT INTO work_messages(message_id,request_id) VALUES(?,?)').run(messageId,work.requestId);
|
|
2859
2892
|
for(const sub of this.activeSubscriptions()) this.queueMessageEvent(messageId,preview,sub);
|
|
2860
|
-
return {message_id:messageId,status:'pending',created_at:createdAt,text_sha256:hash(text),preview};
|
|
2893
|
+
return {message_id:messageId,status:'pending',created_at:createdAt,text_sha256:hash(text),preview,...(work?{request_id:work.requestId}:{})};
|
|
2861
2894
|
}); }
|
|
2862
2895
|
queueMessageEvent(messageId,title,sub) {
|
|
2863
2896
|
sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(sub.id);
|
|
@@ -2876,19 +2909,40 @@ export class Store {
|
|
|
2876
2909
|
}
|
|
2877
2910
|
return this.getMessage(id);
|
|
2878
2911
|
}); }
|
|
2879
|
-
|
|
2912
|
+
messageBindingForWorker(id,worker) {
|
|
2913
|
+
const binding=this.db.prepare(`SELECT m.request_id,a.status FROM work_messages m
|
|
2914
|
+
JOIN assignments a ON a.request_id=m.request_id WHERE m.message_id=?`).get(id);
|
|
2915
|
+
if(!binding||!this.mayAct(worker,binding.request_id)) return {};
|
|
2916
|
+
return {bound_request_id:binding.request_id,stale:!['queued','claimed'].includes(binding.status)};
|
|
2917
|
+
}
|
|
2918
|
+
listMessages(worker='dot') {
|
|
2919
|
+
return this.db.prepare("SELECT message_id,preview,created_at FROM messages WHERE status='pending' ORDER BY created_at").all()
|
|
2920
|
+
.filter(r=>this.mayAct(worker,r.message_id)).slice(0,50)
|
|
2921
|
+
.map(r=>({...r,...this.messageBindingForWorker(r.message_id,worker)}));
|
|
2922
|
+
}
|
|
2880
2923
|
getMessage(id,worker=null) {
|
|
2881
2924
|
if(worker!==null&&!this.mayAct(worker,id)) throw new Error('message not found');
|
|
2882
2925
|
const row=this.db.prepare('SELECT message_id,text,text_sha256,preview,status,created_at,acknowledged_at FROM messages WHERE message_id=?').get(id);
|
|
2883
2926
|
if(!row) throw new Error('message not found');
|
|
2884
|
-
return row;
|
|
2927
|
+
return worker===null?row:{...row,...this.messageBindingForWorker(id,worker)};
|
|
2885
2928
|
}
|
|
2886
2929
|
ackMessage(id,worker='dot') { return this.transaction(() => {
|
|
2887
2930
|
if(!this.mayAct(worker,id)) throw new Error('message not found');
|
|
2888
2931
|
const row=this.db.prepare('SELECT status FROM messages WHERE message_id=?').get(id);
|
|
2889
2932
|
if(!row) throw new Error('message not found');
|
|
2890
2933
|
if(row.status==='withdrawn') throw new Error('message withdrawn');
|
|
2891
|
-
if(row.status!=='acknowledged')
|
|
2934
|
+
if(row.status!=='acknowledged') {
|
|
2935
|
+
const at=this.stamp();
|
|
2936
|
+
this.db.prepare("UPDATE messages SET status='acknowledged',acknowledged_at=? WHERE message_id=?").run(at,id);
|
|
2937
|
+
const binding=this.db.prepare(`SELECT m.request_id FROM work_messages m JOIN assignments a ON a.request_id=m.request_id
|
|
2938
|
+
WHERE m.message_id=? AND a.status IN ('queued','claimed')`).get(id);
|
|
2939
|
+
if(binding) {
|
|
2940
|
+
// This receipt records worker-inbox acknowledgment while work is open. It does not wake the parent.
|
|
2941
|
+
const event=this.db.prepare('INSERT INTO progress(request_id,note,created_at,worker) VALUES(?,?,?,?)')
|
|
2942
|
+
.run(binding.request_id,`Worker inbox ${worker} acknowledged message ${id}.`,at,worker);
|
|
2943
|
+
this.db.prepare('UPDATE work_messages SET progress_id=? WHERE message_id=?').run(event.lastInsertRowid,id);
|
|
2944
|
+
}
|
|
2945
|
+
}
|
|
2892
2946
|
return this.getMessage(id);
|
|
2893
2947
|
}); }
|
|
2894
2948
|
// Resume wake. DALAN_RESUME_IDLE_MS (default 120000; 0 disables everything below). A claim is idle when its holder made no
|
|
@@ -3044,12 +3098,12 @@ export class Store {
|
|
|
3044
3098
|
const reservedId=this.admissionReservation(worker)?.request_id;
|
|
3045
3099
|
const reserveOrder=(a,b)=>Number(b.request_id===reservedId)-Number(a.request_id===reservedId);
|
|
3046
3100
|
let filler=this.activeCallerReserve(worker)>0?this.fillerRoom(worker):Infinity;
|
|
3047
|
-
const assignments=this.db.prepare(`SELECT request_id,payload,created_at,priority,review,caller_waiting,EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked FROM assignments WHERE status='queued' AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id) AND ${live(this.nowMs())}${batch?' AND skipped_at IS NULL':''} ORDER BY ${LIST_ORDER}`).all().filter(a=>this.mayAct(worker,a.request_id)&&this.protocolListingLive(a.request_id)&&(!batch||!this.isProtocolJob(a.request_id)&&!this.pullQueue.row(a.request_id))).map(a=>({...a,blocked:!!a.blocked&&blocked(a.request_id)}))
|
|
3101
|
+
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)}))
|
|
3048
3102
|
.sort((a,b)=>Number(a.blocked)-Number(b.blocked)||reserveOrder(a,b))
|
|
3049
3103
|
.filter(a=>handoffExclusions===null||!a.blocked&&a.request_id!==reservedId&&!handoffExclusions.has(a.request_id)&&!this.handoffLapsed(a.request_id,worker))
|
|
3050
|
-
.filter(a=>a.caller_waiting===1||filler-- > 0).slice(0,50).map(a=>({kind:'assignment',request_id:a.request_id,title:JSON.parse(a.payload).brief.slice(0,160),created_at:a.created_at,...(a.blocked?{blocked:true}:triageFields(JSON.parse(a.payload),a))}));
|
|
3104
|
+
.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))}));
|
|
3051
3105
|
if(batch||handoffExclusions!==null) return assignments;
|
|
3052
|
-
const messages=this.listMessages(worker).map(m=>({kind:'message',request_id:m.message_id,
|
|
3106
|
+
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));
|
|
3053
3107
|
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,
|
|
3054
3108
|
...(this.db.prepare('SELECT 1 FROM destination_blocks WHERE request_id=?').get(c.request_id)&&blocked(c.request_id)?{blocked:true}:{}),
|
|
3055
3109
|
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.'}));
|
|
@@ -3210,6 +3264,7 @@ export class Store {
|
|
|
3210
3264
|
if(active.length+(reserved&&reserved.request_id!==id?1:0)>=claimLimit) throw new Error('capacity_full');
|
|
3211
3265
|
this.assertClaimGap(id,subject,worker,active);
|
|
3212
3266
|
this.recordPrPreflight(id,'claim',JSON.parse(a.payload),preflight,!!old);
|
|
3267
|
+
if(preflight) this.clearPrClaimMismatch(id,preflight);
|
|
3213
3268
|
if(takeover) { const why=Store.expirySummary(old); this.db.prepare("UPDATE claims SET state='abandoned',abandoned_at=?,abandon_reason=? WHERE request_id=?").run(this.stamp(),why,id); this.lifecycle(id,'abandoned','system',why,old); this.laneFreed(); }
|
|
3214
3269
|
const claimId=`claim_${randomUUID()}`;
|
|
3215
3270
|
const claimedAt=this.stamp(), seen=this.db.prepare('SELECT COALESCE(max(sequence),0) n FROM owner_notes WHERE request_id=?').get(id).n;
|