@tnunamak/dalan 0.9.2 → 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 CHANGED
@@ -4,6 +4,13 @@ This file lists user-visible changes, newest first. Check the section for your t
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.9.3
8
+
9
+ - Pull request review jobs whose pinned revision has changed stop appearing ready. If an explicit claim confirms the original revision is back, the stale status clears even when all worker lanes are busy.
10
+ - Dalan alerts the operator when a worker keeps receiving eligible work without claiming it. Temporary pauses and failed alert delivery preserve the outstanding alert.
11
+ - Blank clarification responses leave the question open and prompt once more. A trial update retains its settings and scratch files if shutdown cannot be confirmed.
12
+ - Recovery after an interrupted apply shows the original result and preserves its patch when publication cannot be verified.
13
+
7
14
  ## 0.9.2
8
15
 
9
16
  - An operator can limit private scoped-file reads to one held read-only assignment and set them to expire within its claim lease. The worker needs a separate grant for other assignments.
@@ -324,7 +324,7 @@ function publishPending(s, ctl) {
324
324
  function storedRepositoryContext(assignment, preparedContext) {
325
325
  const input = assignment?.inputs?.[0];
326
326
  if (!input) return preparedContext ?? 'No repository input was submitted. The worker sees only the local material included in the brief.';
327
- const context = preparedContext ?? `Repository input: ${input.github_repo} at pinned commit ${input.head_sha ?? input.base_sha}. The worker can see local changes included in the brief. Other local work is unseen.`;
327
+ const context = preparedContext ?? `Repository input: ${input.github_repo} at pinned commit ${input.head_sha ?? input.base_sha}. The worker can see only local changes explicitly included in the brief. Other local work is unseen.`;
328
328
  const fileCount = assignment.paged_read_scope === true ? assignment.scope_paths.length : undefined;
329
329
  return withReadScope(context, assignment.read_paths, fileCount);
330
330
  }
@@ -678,18 +678,29 @@ async function handleQuestions(s, ctl, say, client, notice) {
678
678
  continue;
679
679
  }
680
680
  if (ctl.cancelled) return;
681
- (ctl.askedQuestions ??= new Set()).add(q.question_id);
682
- if (response.action !== 'accept') {
681
+ if (response?.action !== 'accept') {
682
+ (ctl.askedQuestions ??= new Set()).add(q.question_id);
683
683
  await say('agent_message_chunk', `Work ${rid}: you declined to answer question ${q.question_id}. The question is still open and the job waits for an answer (child turn held).\n\n`);
684
684
  continue;
685
685
  }
686
+ const accepted = response.content?.answer;
687
+ if (typeof accepted !== 'string' || !accepted.trim()) {
688
+ if (ctl.blankAnswerNotices?.has(q.question_id)) {
689
+ (ctl.askedQuestions ??= new Set()).add(q.question_id);
690
+ } else {
691
+ (ctl.blankAnswerNotices ??= new Set()).add(q.question_id);
692
+ await say('agent_message_chunk', `Work ${rid}: question ${q.question_id} received no answer. The question is still open. I will ask once more. To answer manually: dot-worker answer ${rid} ${q.question_id} TEXT\n\n`);
693
+ }
694
+ continue;
695
+ }
696
+ (ctl.askedQuestions ??= new Set()).add(q.question_id);
686
697
  const stillOpen = await live(q.question_id);
687
698
  if (ctl.cancelled) return;
688
699
  if (!stillOpen) {
689
700
  await say('agent_message_chunk', `Work ${rid}: question ${q.question_id} was answered or closed while you decided, so your answer was not sent.\n\n`);
690
701
  continue;
691
702
  }
692
- text = response.content?.answer;
703
+ text = accepted;
693
704
  }
694
705
  await answerThroughJournal({receiptsDir, job:rid, questionId:q.question_id, text,
695
706
  readRevision:async () => (await readRowOrThrow(rid)).protocol_revision ?? null,
@@ -505,6 +505,12 @@ Four line kinds split the time from submit to claim. `wake_delivery` is written
505
505
 
506
506
  MCP arrivals and response outcomes are logged without request contents or secrets. `mcp_inbound`, `mcp_outcome` and an answered `signal` line carry `worker`, the configured worker name, so a gap in one worker's calls (for example after a deploy) can be measured from the log. A failed tool call's `mcp_outcome` line also carries `tool_error_message`: the bridge's error text, redacted like alert notes and cut to 300 characters (null for a successful call).
507
507
 
508
+ ### A ready offer without a claim
509
+
510
+ When an authenticated batch listing returns ready work and the worker sends no claim for five minutes, the bridge checks that eligible work and capacity are still available. It logs `claim_offer_stalled` with elapsed milliseconds and publishes through the configured operator alert channel. Open the worker conversation to nudge it if needed. A claim attempt ends this episode, even if the claim is refused. Ordinary webhook wakes continue.
511
+
512
+ If an automatic finish handoff expires before the worker starts it, the bridge records `claim_expired_before_first_action`. On the batch-claim profile it defers new automatic handoffs to that worker for five minutes. The worker can still claim work explicitly and recover an existing live handoff.
513
+
508
514
  ### Usage breaks and usage estimates
509
515
 
510
516
  The bridge records usage breaks and slows the worker only on evidence: an owner-confirmed break or a pause. Rate limits are estimates that it reports and never enforces. See [usage](usage.md#usage-breaks-and-usage-estimates) for the commands.
@@ -10,22 +10,28 @@ Start a new [ChatGPT worker](chatgpt-worker-onboarding.md) or [Claude worker](cl
10
10
 
11
11
  Each run checks the worker's MCP connector. The bridge stores the job, progress and owner notes. An independent run needs no earlier grant, but a run that continues after a QUESTION/answer pause or reconnect must retain its acquisition ID, claimant and claim ID. A new run cannot use an active grant merely because `get` shows it.
12
12
 
13
- 1. Call `list_pending`. For a saved continuation, read any `attention` notes with `get` and continue under the saved grant; skip the new acquisition step below. Otherwise choose a claimable assignment from `assignments`. If neither needs work, stop. An empty run costs one tool call.
14
- 2. Generate a random `acquisition_id` for this independent run and call `claim` on one job with that ID and a stable `claimant`. Save them with the returned `claim_id` and epoch. Reuse the acquisition ID for retries and continuation of this run. The default lease is 60 minutes. You can request `lease_ms` from 1 ms up to the owner-configured maximum; the bridge stores that duration on the grant and returns `lease_expires_at`. Matching live retries keep the stored duration. A competing live acquisition returns `claim_busy`; pick another job, or stop. Expired idle own claims can rotate as described below.
13
+ 1. Call `list_pending`. For a saved continuation, read any `attention` notes with `get` and continue under the saved grant. For new work, act only when the listing accepts claims and shows claimable work. If neither needs work, stop. An empty run costs one tool call.
14
+ 2. For ordinary queued work, prefer `claim({ next: 1, claimant, acquisition_id })` when you can start one job and the bridge and client advertise `next`. Let the bridge choose from its current queue. Use a stable `claimant` and a fresh random `acquisition_id` for each new acquisition. On a transport failure with an unknown outcome, retry the exact same call with that ID and the same arguments. Retain each returned grant and epoch for continuation.
15
+ - After a successful claim, start the granted work. If the reply's `next_action` offers more claims and you can start more compatible jobs now, make a fresh acquisition before the first job finishes. Claim at most the number offered and only as many jobs as you can start.
16
+ - If the reply grants nothing, call `list_pending` again promptly. Stop when claims are unavailable or no eligible work is ready. If you try a new acquisition from the fresh listing, use a fresh ID.
17
+ - Keep the existing acquisition routes for named jobs, resume, and policy work. Use `request_id` for ordinary work on a client that does not advertise `next`. A live competing named claim returns `claim_busy`. If the client shows a generic error, keep the actual reason unknown. Refresh `list_pending` before continuing and use only grants returned by a successful claim.
18
+ - The default lease is 60 minutes. You can request `lease_ms` from 1 ms up to the owner-configured maximum. The grant records that duration and returns `lease_expires_at`. Matching live retries keep the stored duration. Expired idle own claims can rotate as described below.
15
19
  3. Read the job with `get`. Do the work. For repository jobs, use `list_files`, `read_file`, `apply_patch` and `workspace_result`.
16
20
  4. Call `progress` while you work. Accepted claim-bearing activity slides a legacy non-protocol lease; `get` does not. Native protocol leases have a fixed deadline: activity and repeated `claim` do not slide it. Use explicit `renew_claim` with the current grant, command key and revision before expiry.
17
21
  5. To ask the requester a question, send `progress` with a note that starts `QUESTION:`. The requester answers with `dalan note REQUEST_ID TEXT`. `list_pending` lists claimed jobs with unread owner notes under `attention`, and `get` shows the answer. QUESTION records waiting history but does not pause the lease, stop compute or renew authority when the answer arrives. Continue with the saved grant while it remains valid. If an independent later run takes over, it must use its own acquisition and wait for lease expiry and verified effect-channel cessation; it must not copy the earlier grant from `get`.
18
- 6. Call `finish` with the report. If the response carries `next_queued`, claim `next_queued[0]` yourself before the run ends. On any wake, call `list_pending` and claim up to `free_lanes` assignments, oldest first, instead of claiming only the event's `request_id`. After any claim error such as `assignment_expired`, call `list_pending` again before you claim another. For builds, inspect `workspace_result` first; the bridge computes the patch from the workspace changes.
22
+ 6. Call `finish` with the report. If `finish` returns work that is already claimed for you, start it using the supplied grant. On a wake or a hint about more queued work, start a new cycle at `list_pending`. For builds, inspect `workspace_result` first. The bridge computes the patch from the workspace changes.
19
23
 
20
24
  Messages that the owner sends with `dalan tell` show up in `list_pending`; read them, then call `ack_message`.
21
25
 
26
+ Finish the assignment through the original requester’s route. A separate message to a T3 thread needs its own thread authorization and delivery confirmation. Report a cancelled or unavailable send as undelivered. If a direct T3 send is unavailable, put the update in `progress` on its original job. Use an operator-registered relay only if discovery shows that grant. A cancelled relay with no delivery attempts did not dispatch a message.
27
+
22
28
  Put this loop in the worker's standing instructions, for example in its scheduled task prompt. The bridge also returns short guidance in each `get` response.
23
29
 
24
30
  ### Claim several ready assignments in one call
25
31
 
26
32
  The opt-in `batch-claim-v1` catalog advertises `claim({ next, claimant, acquisition_id, lease_ms? })`. Set `next` to 1 through 8 instead of `request_id`. The bridge returns `{ claims, free_lanes }`; each entry is a normal claim reply with the assignment, claim ID and epoch. Treat each entry as a separate grant and start the work before moving on. Save the original acquisition ID and the returned grants across retries. Choose a new acquisition ID for a new batch.
27
33
 
28
- The bridge takes ordinary, unskipped queued assignments in list order, limited by current free lanes. It stops at the first refusal and returns the admitted prefix. Cancelled, skipped, and resumable grants are not batch candidates. Native protocol jobs and policy work still use the explicit request ID or their existing acquisition path. A retry with the same batch arguments can recover the still-live grants in that batch; it never claims additional work, even if the first call was interrupted or a lane opened later. If the returned batch is partial, call `list_pending` to see what's ready and use a fresh acquisition ID for a new batch.
34
+ The bridge takes ordinary, unskipped queued assignments in list order, limited by current free lanes. It stops at the first refusal and returns the admitted prefix. Cancelled, skipped, and resumable grants are not batch candidates. Native protocol jobs and policy work still use the explicit request ID or their existing acquisition path. A retry with the same batch arguments uses the original selection. If the bridge saved a nonempty selection and no grant committed, it can still try those same jobs. Once a grant commits, a retry can only recover grants from that batch that are still live. If the returned batch is partial, call `list_pending` to see what's ready and use a fresh acquisition ID for a new batch.
29
35
 
30
36
  Older profiles and single-request calls are unchanged. Only enable the opt-in catalog after coordinating the deployment pin and refreshing the connector's tool schema. Until both advertise `next`, continue using `request_id`.
31
37
 
@@ -2,6 +2,42 @@
2
2
 
3
3
  The ordered commands in `scripts/test-segments.json` are the audit boundary. The suite owns mutable state below private, randomly allocated roots. Tests may allocate more private children. Code, installed dependencies, system binaries, and kernel metadata remain shared read-only inputs. Real systemd checks share the user manager but use a distinct unit name per suite.
4
4
 
5
+ ## Parallel qualification
6
+
7
+ The Linux checkout can run the full manifest under one CPU, memory, and process
8
+ governor. Stage each lane in a separate clean checkout at the same commit.
9
+ Point each lane at the same lockfile-matched dependencies. Stage the checkouts
10
+ and keep their short private HOME and scratch roots on disk. Run these commands
11
+ inside the existing qualification governor from the source checkout.
12
+
13
+ ```sh
14
+ node scripts/test-qualification-plan.mjs \
15
+ "$serial_profile" scripts/test-qualification-policy.json "$output" "$@" > "$plan"
16
+ node scripts/test-segments.mjs --qualification-plan "$plan"
17
+ ```
18
+
19
+ Pass one staged checkout root per lane as positional arguments. The measured
20
+ plan uses twelve roots. The serial profile must cover the exact command
21
+ manifest in one passing run. The plan records each expected exit and recorded
22
+ skip count by original ordinal. A changed capability or skip needs a new
23
+ serial reference under that host configuration.
24
+
25
+ Commands absent from the reviewed policy run in the serial phase. Changing the
26
+ manifest requires a new policy digest and a matching serial baseline.
27
+ The loopback lanes have separate network and PID namespaces. Tests that inspect
28
+ the original filesystem owners, use normal DNS behavior, or exercise the native
29
+ trial tools share the host network with independent checkout and fixture roots.
30
+ The host executor, nested sandbox and outbound capability tests share one
31
+ lane. Run the existing host-only release proof as usual.
32
+
33
+ On success, `qualification.json` records the commit, governor, serial baseline
34
+ digest and original lane receipts. `segments.jsonl` contains one record per
35
+ manifest ordinal with the qualification and lane run identities. Compare
36
+ `qualification.json` and the runner exit before using the combined profile.
37
+ Individual lane logs remain available on failure. The `npm test` entry point
38
+ continues to run the manifest serially.
39
+
40
+
5
41
  ## Confirmed failures
6
42
 
7
43
  | Failure | Shared resource or race | Correction and evidence |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tnunamak/dalan",
3
- "version": "0.9.2",
3
+ "version": "0.9.3",
4
4
  "description": "An MCP job bridge for bounded agent work, durable progress, results, and owner review.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -917,24 +917,6 @@ export function workerRouteReference(home, retained, view, custody) {
917
917
  }
918
918
 
919
919
  export async function publishWorkerRoute({ o, env, gozar, url, secret, urlFile, configDir, log, consent = routeConsent(log), readReference = readWorkerRouteReference, write = writeAtomic, observeRoute = observeRetainedRoute, platform = process.platform }) {
920
- const reference = path.join(configDir, 'route-reference.json');
921
- let ref = readReference(o.home, reference);
922
- const home = ref?.home ?? gozarHomeFor(env);
923
- const custody = ref?.custody ?? routeCustodyPath({ HOME: os.homedir(), ...env }, home);
924
- const target = o.lan ? `${o.lan.address}:${o.lan.port}` : `127.0.0.1:${o.port}`;
925
- const external = !ref?.handle || ref.handle.kind === 'external';
926
- const remember = value => {
927
- const next = { ...value, custody };
928
- write(reference, JSON.stringify(next));
929
- ref = next;
930
- };
931
- gozar ??= await resolveGozar({ env, home, custody });
932
- const observed = ref && await observeRoute(gozar, ref);
933
- const view = observed?.state === 'recorded' ? observed.view : await ensureDurableRoute({
934
- gozar, query: buildQuery({ home, origin: url, target, address: 'stable', usage: { kind: 'durable', routeId: `dalan-${o.worker}` } }),
935
- consent, remember, recovery: ref, external: true,
936
- });
937
- if (!ref?.handle || (!ref.operationId && view.operationId)) remember(workerRouteReference(home, ref, view, custody));
938
920
  const retainedInstall = () => {
939
921
  const dir = unitDirFor(platform, env);
940
922
  const unit = dir && path.join(dir, platform === 'darwin' ? `${launchLabel(o.worker)}.plist` : `dot-bridge-${o.worker}.service`);
@@ -945,8 +927,28 @@ export async function publishWorkerRoute({ o, env, gozar, url, secret, urlFile,
945
927
  };
946
928
  return { homeRetained: entry(o.home)?.isDirectory() === true, serviceRetained: entry(unit)?.isFile() === true };
947
929
  };
948
- let retained;
930
+ let phase = 'route_preparation';
931
+ let view, retained;
949
932
  try {
933
+ const reference = path.join(configDir, 'route-reference.json');
934
+ let ref = readReference(o.home, reference);
935
+ const home = ref?.home ?? gozarHomeFor(env);
936
+ const custody = ref?.custody ?? routeCustodyPath({ HOME: os.homedir(), ...env }, home);
937
+ const target = o.lan ? `${o.lan.address}:${o.lan.port}` : `127.0.0.1:${o.port}`;
938
+ const external = !ref?.handle || ref.handle.kind === 'external';
939
+ const remember = value => {
940
+ const next = { ...value, custody };
941
+ write(reference, JSON.stringify(next));
942
+ ref = next;
943
+ };
944
+ gozar ??= await resolveGozar({ env, home, custody });
945
+ const observed = ref && await observeRoute(gozar, ref);
946
+ view = observed?.state === 'recorded' ? observed.view : await ensureDurableRoute({
947
+ gozar, query: buildQuery({ home, origin: url, target, address: 'stable', usage: { kind: 'durable', routeId: `dalan-${o.worker}` } }),
948
+ consent, remember, recovery: ref, external: true,
949
+ });
950
+ if (!ref?.handle || (!ref.operationId && view.operationId)) remember(workerRouteReference(home, ref, view, custody));
951
+ phase = 'public_verification';
950
952
  if (external) requireExternalRoute(view, url, target);
951
953
  if (!isPublished(view) || view.published !== url) {
952
954
  retained = retainedInstall();
@@ -957,7 +959,7 @@ export async function publishWorkerRoute({ o, env, gozar, url, secret, urlFile,
957
959
  }
958
960
  } catch (error) {
959
961
  error.partialSetup = {
960
- phase: 'public_verification', ...(retained ?? retainedInstall()), resourceUrlRewritten: false,
962
+ phase, ...(retained ?? retainedInstall()), resourceUrlRewritten: false,
961
963
  };
962
964
  throw error;
963
965
  }
@@ -1021,7 +1023,7 @@ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import
1021
1023
  try { await run(process.argv.slice(2)); }
1022
1024
  catch (e) {
1023
1025
  console.error(`worker-bridge-setup: ${e.message}`);
1024
- if (e.partialSetup?.phase === 'public_verification') {
1026
+ if (['route_preparation', 'public_verification'].includes(e.partialSetup?.phase)) {
1025
1027
  const { homeRetained, serviceRetained } = e.partialSetup;
1026
1028
  console.error(`worker-bridge-setup: partial setup: home ${homeRetained ? 'retained' : 'not retained'}; service unit ${serviceRetained ? 'retained' : 'not retained'}; resource URL not rewritten.`);
1027
1029
  }
@@ -111,6 +111,7 @@ function publicationBudget(timeoutMs) {
111
111
  // Shared owner-side publication path. Approval and formatting belong to the caller.
112
112
  export async function materialize({id, got, dir, grantFile, download, recheck,
113
113
  dryRun=false, approve=false, standingOnly=false, fetchBase=false, timeoutMs=30000}) {
114
+ if(got?.request_id!==id) throw new Error('materialize result does not match the requested work');
114
115
  const grant=readMaterializeGrant(grantFile);
115
116
  if(got.status!=='finished'||got.revised_by) throw new Error('materialize needs a current, finished result');
116
117
  const ev=got.report?.workspace_evidence, art=ev?.patch_artifact, inputs=got.assignment?.inputs;
@@ -145,7 +146,7 @@ export async function materialize({id, got, dir, grantFile, download, recheck,
145
146
  rememberCleanup:()=>{ cleanupPending=true; },recheck:async(phase='push')=>{
146
147
  const current=await budget.read(signal=>recheck({signal}));
147
148
  const after=phase==='pr' ? 'the branch was pushed, so it exists, but no draft pull request was opened' : 'nothing pushed';
148
- if(current.status!=='finished'||current.revised_by||current.report?.workspace_evidence?.patch_artifact?.sha256!==art.sha256) {
149
+ if(current?.request_id!==id||current.status!=='finished'||current.revised_by||current.report?.workspace_evidence?.patch_artifact?.sha256!==art.sha256) {
149
150
  throw new Error('materialize result changed before publication; '+after);
150
151
  }
151
152
  const currentDecision=materializeDecision(readMaterializeGrant(grantFile),repo,id,current.publication_authority);
@@ -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;
@@ -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
@@ -794,6 +794,7 @@ function sweepSkipped() {
794
794
  function sweepStaleLeases() {
795
795
  const ids=store.sweepStaleLeases();
796
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);
797
798
  return ids;
798
799
  }
799
800
  const destinations=createDestinations({store,ackLedger,notify:notifyAttachedWaiter,log,crashAt,exit:code=>process.exit(code)});
@@ -889,7 +890,13 @@ function logPendingReply(reply,{worker,subject},callId,batch={}) {
889
890
 
890
891
  // Put the next acquisition before job detail, including after progress and finish.
891
892
  // Derive it after the call (and any finish handoff) so it describes remaining capacity.
892
- function batchCapacityReply(name,reply,principal,callId) {
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) {
893
900
  if(!['list_pending','claim','progress','finish'].includes(name)) return reply;
894
901
  const recordListing=name==='list_pending'&&!!callId;
895
902
  if(!batchClaimProfile) {
@@ -897,11 +904,8 @@ function batchCapacityReply(name,reply,principal,callId) {
897
904
  return reply;
898
905
  }
899
906
  const {worker,subject}=principal;
900
- const {free_lanes,ready,available,reservedId}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
907
+ const {free_lanes,ready,available,hintFree,next}=batchRoom(subject,worker);
901
908
  const ready_queued=ready.length;
902
- const hint=store.claimHint(worker);
903
- const hintFree=hint===null?Infinity:Math.max(Number(!!reservedId),hint-store.recentClaimCount(worker));
904
- const next=Math.min(available,ready_queued,8,hintFree);
905
909
  const [reason,next_action]=quiescing?['quiescing',restartQuiesceText]:
906
910
  store.paused()?['paused','Claims are paused; call list_pending again later.']:
907
911
  next>0?['ready',`claim with next=${next} now`]:
@@ -912,8 +916,9 @@ function batchCapacityReply(name,reply,principal,callId) {
912
916
  const response={next_action,free_lanes,ready_queued,...rest};
913
917
  if(recordListing) {
914
918
  const recommended=reason==='ready'?next:0;
915
- logPendingReply(response,principal,callId,{ready_queued,dispatch_reason:reason,recommended_claims:recommended,
916
- ready_head_ids:ready.slice(0,recommended).map(item=>item.request_id)});
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});
917
922
  }
918
923
  return response;
919
924
  }
@@ -985,7 +990,7 @@ async function runHandoff({principal,requestId,claimId,waitMs,maxJobs=1,idleLeas
985
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.
986
991
  const pick=free=>(store.nextQueued(free,null,worker,{applyHint:false,handoffExclusions:tried}).next_queued??[]);
987
992
  for(;;) {
988
- if(signal?.aborted||store.paused()) return jobs.length?{jobs}:{};
993
+ if(signal?.aborted||store.paused()||(batchClaimProfile&&phaseTrace.handoffBackingOff(worker))) return jobs.length?{jobs}:{};
989
994
  const {free_lanes}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
990
995
  if(free_lanes<=0) return jobs.length?{jobs}:{};
991
996
  if(store.hasQueuedFor([worker])) {
@@ -1004,6 +1009,7 @@ async function runHandoff({principal,requestId,claimId,waitMs,maxJobs=1,idleLeas
1004
1009
  fresh=pick(store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity).free_lanes);
1005
1010
  continue;
1006
1011
  }
1012
+ if(batchClaimProfile&&phaseTrace.handoffBackingOff(worker)) return jobs.length?{jobs}:{};
1007
1013
  tried.add(fresh[0].request_id);
1008
1014
  const job=await claim(fresh[0].request_id,slot);
1009
1015
  if(job) { jobs.push(job); if(jobs.length>=maxJobs) return {jobs}; }
@@ -1241,7 +1247,10 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1241
1247
  const t3=await import('./t3.mjs');
1242
1248
  const authorize=()=>{
1243
1249
  const threads=toolRegistry.t3Threads(name,principal);
1244
- if(name!=='t3_thread_list' && !threads.has(a.threadId)) throw new RegistryError('tool_unavailable','tool unavailable');
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
+ }
1245
1254
  return threads;
1246
1255
  };
1247
1256
  // Linearization point: this synchronous live-grant read follows the last await before
@@ -1353,7 +1362,17 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1353
1362
  // A fresh claim, a claim after abandon and an expired-lease takeover are each a new admission. The Store
1354
1363
  // still validates claimant, subject, lease, cancellation and capacity atomically.
1355
1364
  const admission=!store.paused()&&(row.status==='queued'||row.status==='claimed'&&held&&!(held.claimant===claimant&&held.subject===subject)&&store.leaseExpired(held));
1356
- const preflight=admission?await preflightPR(row.assignment):null;
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
+ }
1357
1376
  if(!retry) {
1358
1377
  assertRepoAllowed(worker,row.assignment);
1359
1378
  // Resolve an optional workspace grant after remote preflight but before claim acquisition. A broken
@@ -1526,7 +1545,7 @@ function publicErrorText(error,what) {
1526
1545
  log({kind:'request_error',what,error_id:errorId,detail:safeDiagnostic(error?.stack??error,4000)});
1527
1546
  return `Error executing ${what} (error id ${errorId}; details are in the request log)`;
1528
1547
  }
1529
- async function dispatch(message,principal,signal,callId) {
1548
+ async function dispatch(message,principal,signal,callId,onOffer) {
1530
1549
  const p=message.params??{};
1531
1550
  switch(message.method) {
1532
1551
  case 'server/discover': return {ttlMs:0,cacheScope:'private',supportedVersions:['2026-07-28'],capabilities:{tools:{},events:{}},_meta:{'io.modelcontextprotocol/serverInfo':serverInfo}};
@@ -1535,7 +1554,7 @@ async function dispatch(message,principal,signal,callId) {
1535
1554
  // Modern catalogs are process-wide. A worker's capability controls tools/call authority, not its cached schemas.
1536
1555
  // legacy-v46 keeps its pinned per-worker surface for compatibility.
1537
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};
1538
- 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; } }
1539
1558
  case 'events/list': return {events:[event]};
1540
1559
  case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
1541
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 {}; }
@@ -1577,11 +1596,12 @@ const publicServer=(as?createBuiltinHttpServer:http.createServer)(async(req,res)
1577
1596
  // Metadata only: bodies can carry webhook secrets and worker results.
1578
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)});
1579
1598
  if(!Object.hasOwn(rpc,'id')) { res.writeHead(202); res.end(); return; }
1599
+ if(outcome.state.tool==='claim') phaseTrace.claimAttempt(principal.worker);
1580
1600
  outcome.state.phase='dispatch';
1581
1601
  const eventStream=readEnv('DALAN_TRIAL_SSE')==='1'&&req.method==='POST'&&acceptsMcpEventStream(req.headers.accept)?beginMcpEventStream(res):null;
1582
1602
  // A tool that waits (finish with finish_handoff) stops when the client leaves, so nothing is claimed for nobody.
1583
1603
  const clientGone=new AbortController();res.once('close',()=>clientGone.abort());if(res.destroyed)clientGone.abort();
1584
- 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); }
1585
1605
  catch(e) { json(res,200,rpcError(rpc.id,e.code||-32602,publicErrorText(e,'request'),e.data),eventStream); }
1586
1606
  // Response-byte accounting for the throttle and the break ledger; the response is already written, so a failure only logs.
1587
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}); }
@@ -2272,6 +2292,27 @@ const staleDays=(d=>Number.isFinite(d)&&d>0?d:7)(Number(readEnv('DALAN_DECISION_
2272
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});}};
2273
2293
  sweepStale(); setInterval(sweepStale,3600000).unref();
2274
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();
2275
2316
  }
2276
2317
  const startWhenWindowCloses=()=>{ if(updateWindowOpen()) setTimeout(startWhenWindowCloses,250).unref(); else startBackground(); };
2277
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 stopChild(child); }
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 stopChild(child);
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,10 @@ 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
+ );`);
1146
1150
  this.db.exec(`CREATE TABLE IF NOT EXISTS work_messages(
1147
1151
  message_id TEXT PRIMARY KEY REFERENCES messages(message_id) ON DELETE CASCADE,
1148
1152
  request_id TEXT NOT NULL REFERENCES assignments(request_id) ON DELETE CASCADE,
@@ -2735,6 +2739,16 @@ export class Store {
2735
2739
  if(!changed.changes) throw new Error('relationship_not_found');
2736
2740
  return this.db.prepare('SELECT * FROM relationships WHERE relationship_id=?').get(relationshipId);
2737
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
+ }
2738
2752
  recordPrPreflight(id,phase,assignment,evidence,replace=false) {
2739
2753
  assertPreflight(assignment,evidence,this.nowMs());
2740
2754
  if(evidence) this.db.prepare(`INSERT ${replace?'OR REPLACE ':''}INTO pr_preflights(request_id,phase,evidence) VALUES(?,?,?)`).run(id,phase,JSON.stringify(evidence));
@@ -3084,10 +3098,10 @@ export class Store {
3084
3098
  const reservedId=this.admissionReservation(worker)?.request_id;
3085
3099
  const reserveOrder=(a,b)=>Number(b.request_id===reservedId)-Number(a.request_id===reservedId);
3086
3100
  let filler=this.activeCallerReserve(worker)>0?this.fillerRoom(worker):Infinity;
3087
- const assignments=this.db.prepare(`SELECT request_id,payload,created_at,priority,review,caller_waiting,EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked FROM assignments WHERE status='queued' AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id) AND ${live(this.nowMs())}${batch?' AND skipped_at IS NULL':''} ORDER BY ${LIST_ORDER}`).all().filter(a=>this.mayAct(worker,a.request_id)&&this.protocolListingLive(a.request_id)&&(!batch||!this.isProtocolJob(a.request_id)&&!this.pullQueue.row(a.request_id))).map(a=>({...a,blocked:!!a.blocked&&blocked(a.request_id)}))
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)}))
3088
3102
  .sort((a,b)=>Number(a.blocked)-Number(b.blocked)||reserveOrder(a,b))
3089
3103
  .filter(a=>handoffExclusions===null||!a.blocked&&a.request_id!==reservedId&&!handoffExclusions.has(a.request_id)&&!this.handoffLapsed(a.request_id,worker))
3090
- .filter(a=>a.caller_waiting===1||filler-- > 0).slice(0,50).map(a=>({kind:'assignment',request_id:a.request_id,title:JSON.parse(a.payload).brief.slice(0,160),created_at:a.created_at,...(a.blocked?{blocked:true}:triageFields(JSON.parse(a.payload),a))}));
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))}));
3091
3105
  if(batch||handoffExclusions!==null) return assignments;
3092
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));
3093
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,
@@ -3250,6 +3264,7 @@ export class Store {
3250
3264
  if(active.length+(reserved&&reserved.request_id!==id?1:0)>=claimLimit) throw new Error('capacity_full');
3251
3265
  this.assertClaimGap(id,subject,worker,active);
3252
3266
  this.recordPrPreflight(id,'claim',JSON.parse(a.payload),preflight,!!old);
3267
+ if(preflight) this.clearPrClaimMismatch(id,preflight);
3253
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(); }
3254
3269
  const claimId=`claim_${randomUUID()}`;
3255
3270
  const claimedAt=this.stamp(), seen=this.db.prepare('SELECT COALESCE(max(sequence),0) n FROM owner_notes WHERE request_id=?').get(id).n;
@@ -74,6 +74,10 @@ async function cwdForProject(a) {
74
74
  return project.workspaceRoot;
75
75
  }
76
76
 
77
+ export function destinationDeniedEvent(tool, worker, callId) {
78
+ return {kind:'t3_destination_denied',tool,worker,call_id:callId,reason:'no_live_destination_grant'};
79
+ }
80
+
77
81
  export async function runT3Tool(name, a) {
78
82
  switch(name) {
79
83
  case 't3_thread_list':
@@ -398,7 +398,10 @@ export async function runHosted({ options, env, out, input, signal, errorContext
398
398
 
399
399
  const trialOver = () => expired || (trialEndsAt !== null && clock.now() >= trialEndsAt);
400
400
  if (trialMs !== null) {
401
- const expiry = new Promise(resolve => { expireTimer = setTimeout(() => { expired = true; resolve(); }, Math.max(0, trialEndsAt - clock.now())); expireTimer.unref?.(); });
401
+ const expiry = new Promise(resolve => {
402
+ expireTimer = (clock.setTimeout ?? setTimeout)(() => { expired = true; resolve(); }, Math.max(0, trialEndsAt - clock.now()));
403
+ expireTimer?.unref?.();
404
+ });
402
405
  routeGone = Promise.race([routeGone, expiry]);
403
406
  }
404
407
  const trialLeft = () => trialEndsAt === null ? '' : ` Local shutdown limit: ${timeLeft(trialEndsAt - clock.now())}. The temporary link can stop earlier.`;
@@ -530,7 +533,7 @@ export async function runHosted({ options, env, out, input, signal, errorContext
530
533
  }
531
534
  };
532
535
  lines.close();
533
- clearTimeout(expireTimer);
536
+ if (expireTimer !== null) (clock.clearTimeout ?? clearTimeout)(expireTimer);
534
537
  await cleanup('identity watcher cleanup', () => identityWatcher?.stop());
535
538
  // Withdraw handoff, revoke the trial's app credentials, then close the retained route.
536
539
  let ignoredHandoffCleanup = false;