@tnunamak/dalan 0.9.6 → 0.9.8

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,18 @@ This file lists user-visible changes, newest first. Check the section for your t
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.9.8
8
+
9
+ - Let a worker declare the slots it can start on this poll. Hosted clients without slot declarations get advice that adjusts to observed completion and capacity pressure.
10
+ - Timed claims report an effective heartbeat interval and an independent run deadline.
11
+ - Report a reserved worker slot separately from the moment work starts.
12
+
13
+ ## 0.9.7
14
+
15
+ - Read a larger pinned input set as one verified bundle over several replies. Each reply requires the current claim.
16
+ - Keep blocked pull requests out of queue forecasts and prevent old availability notices from waking workers for them.
17
+ - Ignore credential-path hints on full-repository build markers and keep those files out of the worker workspace.
18
+
7
19
  ## 0.9.6
8
20
 
9
21
  - Delegate a full feature to a remote worker from a pushed commit. The worker can use the whole authorized repository, with known credential paths withheld.
@@ -335,7 +335,7 @@ function admissionText(admission, attached) {
335
335
  const duration = ms => ms < 1000 ? `${ms} ms` : ms < 60000 ? `${Math.round(ms / 1000)} s` : `${Math.round(ms / 60000)} min`;
336
336
  const counts = (record, keys) => keys.filter(key => count(record?.[key])).map(key => `${key.replaceAll('_', ' ')} ${record[key]}`);
337
337
  const window = days => count(days) ? `, ${days} days` : '';
338
- const line = [start === 'now' && Date.parse(reserved_until)>Date.now() ? 'starts now' : ['queued','now'].includes(start) ? 'queued' :
338
+ const line = [start === 'now' && Date.parse(reserved_until)>Date.now() ? 'slot reserved' : ['queued','now'].includes(start) ? 'queued' :
339
339
  ['queued', 'claimed', 'finished', 'cancelled'].includes(status) ? status : attached ? 'attached' : 'queued'];
340
340
  if (['host', 'worker', 'none'].includes(execution)) line.push(`execution ${execution}`);
341
341
  if (count(ahead?.count)) {
@@ -57,7 +57,7 @@ Reference: a Claude Code `Agent` subagent or a Codex `spawn_agent` child. Gap ki
57
57
  | `assignments.thread_id`, `environment_id` NOT NULL; delivery string only `none` or `t3:` | **Changes** | Delivery becomes `{adapter, address, adapter_version}`, with T3 columns moved into the T3 adapter's own table. The core names no host. |
58
58
  | Worker catalog `read_file`, `apply_patch`, `run_check` | **Changes**: kept for workers without a computer | A worker with its own computer gets the work as repo, base and task, and returns a branch or patch with evidence. |
59
59
  | Host `run_check` allowlist and `scope_paths_read_isolation_unavailable` | **Changes**: becomes acceptance evidence, not the worker's only test route | Owner-side checks still run on the returned branch when configured. They label their evidence `bridge_observed`; the worker's own runs are labeled `worker_reported`. |
60
- | Name-based refusals (`auth`, `sign*`, `token`, `*secret*` soft names) | **Changes**: soft names stop refusing | Safety is "no secrets, tokens or keys reach a worker". Soft-name matches inside a directory scope are dropped from what ships and noted; they no longer refuse the job. A hard secret path that the caller names explicitly (as a scope, output, diff or patch path) still refuses the job (`inspectPath`, `src/submission-policy.mjs`): the caller asked for a secret file. A soft-name file the caller names explicitly also still refuses, because the content scan misses secrets in formats it does not know; the refusal names the file and the rule it matched, and says to rename or redact the file. The exclusion, symlink and patch-authorization boundary stays (`src/submission-policy.mjs#validateSubmission`, `src/submission-policy.mjs#inspectPath`). Content scanning (`hasSecretContent`) stays as defense in depth, not as proof. |
60
+ | Name-based refusals (`auth`, `sign*`, `token`, `*secret*` soft names) | **Changes**: withhold files from the delivered inputs | A repository build retains implementation scope when it contains a known credential path. Dalan omits that file, records the exclusion, and enforces it on reads, writes and returned patches. A request for the excluded bytes or a patch to modify them is refused at that operation. Secrets in the brief or patch remain inadmissible. Content scanning is defense in depth. |
61
61
  | `status.dispatch` scoped to `dot` | **Changes**: per worker | It stays as a simple dispatch diagnostic, keyed by worker name. The admission answer (section 6) does not replace it. |
62
62
  | `dalan wait` loops as the wake for non-T3 callers (`docs/local-agent-requester.md`) | **Goes** as the documented wake | It stays as a tool for scripts. Section 4.3 gives native wakes. |
63
63
 
@@ -76,7 +76,7 @@ Operations, the same on every route: `delegate`, `forecast`, `status`, `result`,
76
76
 
77
77
  ## 4. Requester routes (versioned, disposable adapters)
78
78
 
79
- The rule: **the caller uses the subagent call its host already has.** Dalan supplies an adapter per host. Each adapter states which capabilities it actually delivers (design for the expected capabilities; advertise only the delivered ones).
79
+ The rule: **the caller uses the subagent call its host already has.** Dalan supplies an adapter per host. Each adapter states which capabilities it actually delivers (design for the expected capabilities; advertise only the delivered ones). When a compatible authorized worker is available, use this route first for any coding task a caller would give a local child, including full features. Pick the worker by the tools the job needs and current availability. Use a local child when the work depends on unpublished files or local tools. Callers supply real demand through these routes.
80
80
 
81
81
  ### 4.1 T3 Code child task (primary; covers Claude and Codex threads in T3)
82
82
 
@@ -123,13 +123,32 @@ When a peer speaks A2A, Dalan maps A2A task, message and artifact to work, quest
123
123
  ## 6. Admission, forecast and track record
124
124
 
125
125
  - Priority classes: `normal` (queue, with an estimate) and `background` (queue behind normal), as stored today (`CHECK(priority IN ('normal','background'))`). A start-or-refuse class would need a schema and admission change; v2 does not add one. The parent gets the admission answer within seconds and can cancel and route elsewhere.
126
- - A free lane or a first claim is not a start. Today `queueWaitEvidence` (`src/store.mjs#queueWaitEvidence`) measures to the first stored claim and uses lower bounds for work that expired unclaimed. v2 measures two latencies: **claimed** (first claim) and **started** (the worker's first substantive event on the work, such as a workspace read or a progress event). Censored samples (expired or cancelled before a claim or a start) are counted in their own group and never mixed into the percentiles.
126
+ - A free lane or a first claim is not a start. Today `queueWaitEvidence` (`src/store.mjs#queueWaitEvidence`) measures to the first stored claim and uses lower bounds for work that expired unclaimed. v2 measures two latencies: **claimed** (first claim) and **started** (the worker's first substantive event on the work, such as a workspace read or a substantive progress event on the live claim and epoch. A heartbeat renews the lease without proving work started). Censored samples (expired or cancelled before a claim or a start) are counted in their own group and never mixed into the percentiles.
127
127
  - Admission answer, computed before submit with a defined stale-answer policy: `start: "now"` only when Dalan has reserved a lane for this work and the worker's subscription is live at that moment. Otherwise `start: "queued"` with the facts: eligible ready work ahead (count and oldest age, same or higher class), measured claimed and started latencies (p50/p90, n, window, censored count), and the worker state (`live`, `break until T`, `no live subscription`). Below the existing minimum of 5 samples (`QUEUE_WINDOW.minSamples`, `src/store.mjs#QUEUE_WINDOW`) it says `insufficient_history` and gives no number. Lower bounds from work that expired unclaimed are reported as their own group; today they are mixed into the percentiles, which understates waits.
128
128
  - A preview reports a forecast. A normal waiting caller can reserve capacity for its request as part of a successful submit when it is the eligible queue head. The reservation expires at `reserved_until` after at most 15 seconds, and a delayed native reply displays it as queued. Replaying a submit does not extend a reservation. Claiming the request consumes the hold. Its claim and first substantive worker event remain separate measurements.
129
129
  - Track record, with outcomes kept apart: `unable_to_run`, `checks_failed`, `check_passed`, `landed` (merged or applied by the owner), plus `refused_by_provider`, n and window. "No passing check" is never reported as one blocked number.
130
130
  - `status.dispatch` stays as a simple diagnostic beside this answer (section 2).
131
131
  - No delegated-agent product shows a reliable ETA (see the prior-art list). Dalan reports only measured values with their basis, so a caller can judge them.
132
132
 
133
+ ### 6.1 Worker capacity and pacing
134
+
135
+ A caller gives the worker a task and a pushed repository anchor. A single allocator at the worker reserves its own execution slots before polling. The worker declares free slots on the poll, requests up to that many on claim, and uses the same slot reservation and acquisition ID on reconnect or transport retry. Dalan matches that demand to eligible work and delivers pinned inputs through the live claim. Availability events only prompt a poll. A requester reservation, a claim, and a first substantive action are separately recorded facts. The legacy wire value `start: now` names the reservation. It does not prove claimed or started. The worker uses its own tools and returns its result through the caller's native child route where qualified, or the durable inbox otherwise.
136
+
137
+ | Decision | Dalan parity rows from §1.1 | Acceptance |
138
+ |---|---|---|
139
+ | Full-feature delegation is the default. A build marker selects implementation of the whole authorized repository. Old file hints describe focus. Exclude known secret paths mechanically. | D1 call, D8 repository access, D9 execution, D16 pushed anchor | The native caller submits one build spanning multiple directories on a pushed commit. The worker can edit across the repository and return a patch. Known secret inputs and writes are withheld. No file-count rule. |
140
+ | Workers own execution capacity. Dalan offers at most the declared free slots and eligible ready jobs. Its independent admission and in-flight limits protect the shared service; they do not estimate executor capacity. | D2 admission, D12 breaks, D14 session length, D17 worker state | Four declared slots and four claimable jobs offer four; one ready job offers one; zero slots offer zero. Concurrent pulls and exact retries use the existing atomic claim and reservation checks. The negotiated route stores no worker execution width. Legacy admission quotas remain limits on service exposure. |
141
+ | A hosted client without slot declarations receives an advisory offer from the hosted adapter. Start with one. Grow by one on confirmed successful completion, within the batch and broker limits. Reduce on expired live leases and verified retryable provider or capacity pressure. Honor a known retry time; log reductions and recovery. Key short-lived advice by authenticated worker and connection. Reset stale estimates to one. A run ceiling or unexplained session end is excluded from pressure evidence. | D2 admission, D12 breaks, D14 session length, D15 outcomes, D17 worker state | The same replay does not train the estimate twice. A 429 or inability caused by a workload or access problem is recorded with its cause; only capacity-related pressure feeds the estimate. A worker that declares slots bypasses this advisory estimate. The matcher needs no worker names or configured worker widths. |
142
+ | An active attempt has two clocks. The worker negotiates a heartbeat interval, with detection at three heartbeat intervals, and an independent wall-clock run ceiling. Authorized claim activity proves liveness and moves its idle deadline, up to the run ceiling. Legacy clients without timed heartbeats retain their previous lease contract; explicit protocol renewal remains available where negotiated. | D2 admission, D7 progress, D11 recovery | A heartbeat extends the idle deadline without recording a start or extending the run ceiling. Queue polls, earlier epochs, expired claims and foreign connections cannot renew a grant. The reply reports the effective clocks. A rollback to a bridge without timed claims waits for those active attempts to settle. |
143
+ | Authorized scoped reads get one pinned file bundle and manifest, with a hash per path and a digest for the whole bundle. Deliver it inline if it fits; page the same verified bytes by digest when it does not. | D8 repository access, D11 recovery, D16 pushed anchor | A worker reads several pinned files without per-file forge requests. Retrying the bundle returns the same digest or an explicit discrepancy. The worker must present its current claim and retain read authority on every page. A stale holder or revoked reader receives no further bytes. The owner can distinguish a complete set from omitted inputs. |
144
+ | A verified result becomes a patch or a draft PR under current publication authority. | D9 execution, D10 result shape, D11 recovery | The owner verifies the anchor and the scoped delivery evidence where required. A standing install policy and the current relationship or work grant constrain publication at the time of push. Revoked or unrelated grants produce patch-only results. Retrying recovers the original draft. Owner acceptance stays separate. |
145
+ | Known blocked work stays visible with its reason and stays out of ready counts, admission forecasts, dispatch and wakes until verified eligible again or retired. | D2 admission, D12 breaks, D17 worker state | A blocked queue head cannot remove an eligible job from an offer or generate a wake. On reopen, the same rules apply to the persisted block. |
146
+ | Count unsuccessful runs by observed reason, alongside the cohort size. Keep rate-limit evidence distinct from worker-reported inability to run. | D13 policy refusals, D15 output quality, D17 track record | Compare live intervals by worker, kind and release. A reason breakdown sums to the displayed count. An inferred reason never becomes a confirmed provider refusal. |
147
+
148
+ Verify the combined journey with a synthetic repository: reserve a slot, claim it, verify the input digest, return an exact check, hand back the patch or authorized draft, and observe the native receipt or durable inbox. Repeat with a blocked head and an expired or revoked claim.
149
+
150
+ The D-numbers here are the caller's parity rows. Section 14 names its separate taxonomy and protocol packet identifiers. Fixtures prove the relevant decisions in isolation. Update the deployment parity evidence after the corresponding live requester and worker journeys.
151
+
133
152
  ## 7. Worker capability (full native ability)
134
153
 
135
154
  ### 7.1 Inputs
@@ -152,7 +171,7 @@ Authority to push is a **standing grant** on the relationship (the C2 #33 author
152
171
 
153
172
  ### 7.4 What a worker may receive
154
173
 
155
- Anything in the repos and data the relationship grants, including other people's data where the owner allows it, within the scoped paths of the work. The one hard line: no secrets, tokens or keys. Whole-job refusals by path name go away; the hard secret-file list removes those files from what Dalan ships. Content scanning stays as defense in depth; it is not proof that nothing secret left.
174
+ A repository build can work across the whole authorized repository at the pushed anchor. A declared read-only set remains limited to its authorized paths. Dalan withholds known secret, token and credential files from the delivered inputs and prevents changes to those files through the bridge. File-name and path hints in a build marker describe the job's focus without changing repository authority. Content scanning stays as defense in depth.
156
175
 
157
176
  ## 8. What Dalan reports
158
177
 
@@ -200,6 +219,15 @@ Captured in the research library (not in this repo): async completion contracts
200
219
 
201
220
  Primary sources behind the claims in sections 4 and 9, as read on 2026-11-27: [Claude Code MCP documentation](https://code.claude.com/docs/en/mcp) (Tasks support and polling); [ACP v2 migration guide](https://agentclientprotocol.com/protocol/v2/migration) (a preview; not an outside completion path); the MCP Tasks extension proposal SEP-2663 (`io.modelcontextprotocol/tasks`, MCP 2026-07-28); T3 Code source at commit 3dbefda28 (files and lines cited where used); Dalan `main` at d0dd670 (files and lines cited where used).
202
221
 
222
+ Queue and worker patterns used in §6.1
223
+
224
+ - Temporal slots, Celery prefetch, SQS visibility renewal and the separate Kafka heartbeat clock. [Consumer prefetch and lease timers](https://github.com/tnunamak/divan/blob/main/queue-systems/queue-consumers-bound-unacked-work-by-prefetch-or-slots-and-set-lease-timers-from-max-job-time-with-heartbeats-at-one-third-or-less-of-the-detection-timeout.md)
225
+ - A transport wake, host activation and job authority are distinct. [Agent delivery by push and pull](https://github.com/tnunamak/divan/blob/main/queue-systems/agent-job-delivery-push-vs-pull-and-what-mcp-lets-a-server-push.md)
226
+ - The amount a consumer asks for provides backpressure, and acceptance is observable. [Consumer demand and bounded queues](https://github.com/tnunamak/divan/blob/main/queue-systems/work-queue-and-review-pipeline-systems-prevent-write-only-output-by-letting-consumer-demand-not-producer-capacity-admit-work-and-by-delivering-findings-inside-the-consumers-workflow.md)
227
+ - Temporal polls after reserving capacity. A reservation does not establish an execution start. [Reservation, execution permission and execution evidence](https://github.com/tnunamak/divan/blob/main/queue-systems/a-reservation-permission-to-execute-and-evidence-of-execution-are-three-different-facts-so-a-lending-app-should-take-the-human-yes-before-the-execution-lease.md)
228
+ - Admission, delivery, authority and verification own different decisions. [Remote delegation taxonomy](https://github.com/tnunamak/divan/blob/main/remote-agent-delegation/taxonomy-v2-remote-coding-delegation-is-a-six-stage-lifecycle-with-twenty-dimensions-each-owning-one-design-decision.md)
229
+ - Measure the inability and unconsumed-work buckets before widening offers. [Remote delegation synthesis](https://github.com/tnunamak/divan/blob/main/remote-agent-delegation/synthesis-remote-coding-delegation-should-first-stop-unconsumed-supply-and-preventable-admission-failures-then-add-owner-side-integration-before-widening-what-workers-can-do.md)
230
+
203
231
  ## 12. Separation: Dalan and the tooling built on it
204
232
 
205
233
  Rule: this repository holds the bridge only: relationship, work, authority, delivery and wake, worker capability, and the surface that requester agents call. Tooling that an operator builds on top (job generators, admission gates, wake scripts, nudges to workers, filler rules, fleet reports) uses only Dalan's public interface. That interface is the CLI and MCP verbs, `status`/`metrics`/`get` JSON, the config files documented in `docs/`, and the requester adapters. Tooling holds no Dalan internals. Dalan holds no operator rules, host thread ids, account names or fleet vocabulary.
@@ -223,6 +251,8 @@ Where the line is crossed today, and where each piece moves:
223
251
  | Patch landing (turning a worker patch into a branch and draft PR) done by operator tooling | Tooling doing bridge work | Dalan's materialize step, under the owner's standing grant (section 7.3). Tooling keeps only its own merge policy. |
224
252
  | Admission decisions in an operator gate (deny, then override on repeat) | Tooling doing bridge work | Dalan's admission answer at the call (section 6). An operator gate may still apply its own routing policy on top. |
225
253
 
254
+ Operator filler and campaign queues use the public API. Dalan works with zero filler: ordinary callers hand coding jobs to their compatible remote child by default (section 4). Measure that requester demand outside the bridge. Dalan owns only which admitted work is eligible, when a worker can claim it, and what the caller sees (D1, D2 and D17).
255
+
226
256
  Test for the rule: a second operator with no fleet could install Dalan, use every requester route, and see no name or rule from this operator. And this operator's tooling keeps working across a Dalan schema change.
227
257
 
228
258
  ## 13. Consumers and the product-neutrality check
@@ -29,7 +29,9 @@ Put this loop in the worker's standing instructions, for example in its schedule
29
29
 
30
30
  ### Claim several ready assignments in one call
31
31
 
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.
32
+ The opt-in `batch-claim-v1` catalog accepts `list_pending({ free_slots })` and `claim({ next, claimant, acquisition_id, lease_ms? })`. Reserve free slots in your executor before polling. Pass zero if none are free. Claim only slots you reserved for this cycle and reuse the same acquisition ID on a transport retry. On denial, release that local reservation. The bridge reports whether its offer came from declared slots or hosted advice. Hosted advice starts with one and uses observed completions and capacity pressure. Each returned claim is a separate grant with its own ID and epoch.
33
+
34
+ A worker that can send timed heartbeats may pass `heartbeat_ms` and `run_timeout_ms` together on claim. Read the effective heartbeat interval and deadlines from the returned claim. Use authorized activity or `get` with the current claim ID within that interval. A renewal cannot extend the wall-clock run deadline. For confirmed capacity pressure at finish, send `capacity_feedback: capacity_rate_limited` with the retry delay if known, or `capacity_unavailable` for exhausted executor capacity.
33
35
 
34
36
  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.
35
37
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tnunamak/dalan",
3
- "version": "0.9.6",
3
+ "version": "0.9.8",
4
4
  "description": "An MCP job bridge for bounded agent work, durable progress, results, and owner review.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -12,7 +12,7 @@ import { promisify } from 'node:util';
12
12
  import { packRepoDiff, stripPacked } from './acp-context.mjs';
13
13
  import { hostCheckRefusal } from './host-execution-policy.mjs';
14
14
  import { redactLogEntry } from './redaction.mjs';
15
- import { isLiteralScopePath, submissionLimits } from './submission-policy.mjs';
15
+ import { isLiteralScopePath, submissionLimits, matchesCredentialPathTerm, withheldRepoPath } from './submission-policy.mjs';
16
16
  import { readablePath } from './path-syntax.mjs';
17
17
  import { readOrCreateSecret, ownerToken } from './owner-capability.mjs';
18
18
  import { CONTINUE_PROMPT, promptText, unwrapUserRequest, isT3RuntimeBlock, parseIdentity } from '../integrations/t3/acp-kit/src/t3-envelope.mjs';
@@ -494,13 +494,18 @@ async function prepareUnexplained({ cwd, ...request }, options, env) {
494
494
  if (build && (!context.inputs.length || context.packBase || context.note))
495
495
  throw new Refusal(env.DOT_ACP_TEXT_ONLY === '1' ? BUILD_NEEDS_PUSHED : await buildCheckoutRefusal(cwd, options));
496
496
  let denyPathTerms;
497
+ let brief=request.brief;
497
498
  if (build) {
498
499
  const policy = buildRepositoryPolicy(context.inputs[0].github_repo, env);
499
500
  if (policy.reason) throw new Refusal(policy.reason);
500
501
  denyPathTerms = policy.terms;
502
+ const [marker,...body]=brief.split('\n');
503
+ const hints=marker.trim().split(/[ ]+/).slice(1)
504
+ .filter(file=>!matchesCredentialPathTerm(file,denyPathTerms)&&!withheldRepoPath(file));
505
+ brief=[[BUILD_MARKER,...hints].join(' '),...body].join('\n');
501
506
  }
502
507
  // Identity is the requester's brief only; packed context and notes are presentation and never enter this hash.
503
- let assignment = { ...buildAssignment({ ...request, inputs: context.inputs, build, denyPathTerms }), acp_brief_hash: sha256(request.brief), ...(explicitRead ? { scope_paths: explicitRead.scope, read_paths: explicitRead.scope } : {}) };
508
+ let assignment = { ...buildAssignment({ ...request, brief, inputs: context.inputs, build, denyPathTerms }), acp_brief_hash: sha256(request.brief), ...(explicitRead ? { scope_paths: explicitRead.scope, read_paths: explicitRead.scope } : {}) };
504
509
  let packedPaths = new Set();
505
510
  if (context.packBase) ({ assignment, packedPaths } = await packRepoDiff(cwd, assignment, context.packBase, NO_REPO_NOTE));
506
511
  else if (context.untracked && !build) assignment.brief = `${UNTRACKED_NOTE}\n\n${assignment.brief}`;
@@ -0,0 +1,32 @@
1
+ export const maxBatchPull = 8;
2
+ const sampleLifetimeMs = 15 * 60_000;
3
+ const recoveryIntervalMs = 30_000;
4
+
5
+ // A worker's explicit demand needs no estimate. This local, expiring window only advises older clients.
6
+ export function createPullPacing({ now, log }) {
7
+ const windows = new Map();
8
+ const key = ({ worker, subject, connection_id }) => JSON.stringify([worker, subject, connection_id ?? null]);
9
+ const current = identity => {
10
+ const sample = windows.get(key(identity));
11
+ return sample && now() - sample.at < sampleLifetimeMs ? sample : null;
12
+ };
13
+ function observe(identity, signal, retryMs = 0) {
14
+ const at = now(), previous = current(identity), before = previous?.width ?? 1;
15
+ if (signal === 'completed' && at < Math.max(previous?.recoverAt ?? 0, previous?.holdUntil ?? 0)) return;
16
+ const width = signal === 'completed' ? Math.min(before + 1, maxBatchPull) : Math.max(1, Math.floor(before / 2));
17
+ const holdUntil = Math.max(previous?.holdUntil ?? 0, signal === 'capacity_rate_limited' ? at + retryMs : 0);
18
+ for (const [id, sample] of windows) if (at - sample.at >= sampleLifetimeMs) windows.delete(id);
19
+ windows.set(key(identity), { width, at, holdUntil, recoverAt: at + recoveryIntervalMs });
20
+ if (width !== before || holdUntil > (previous?.holdUntil ?? 0)) {
21
+ log({ kind: 'hosted_pull_pacing', worker: identity.worker, signal, previous_width: before,
22
+ advised_width: width, ...(holdUntil > at ? { retry_after_ms: holdUntil - at } : {}) });
23
+ }
24
+ }
25
+ return {
26
+ free(identity, held) {
27
+ const sample = current(identity);
28
+ return now() < (sample?.holdUntil ?? 0) ? 0 : Math.max(0, (sample?.width ?? 1) - held);
29
+ },
30
+ observe,
31
+ };
32
+ }
package/src/server.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { createPullPacing, maxBatchPull } from './pull-pacing.mjs';
1
2
  import { updateWindowOpen, refuseDuringUpdate } from './service-update-gate.mjs';
2
3
  import {routingPolicy,PULL_PAGE_PREFIX} from './pull-queue.mjs';
3
4
  import {inspect} from 'node:util';
@@ -177,6 +178,7 @@ if(t3ToolsEnabled) await loadT3Audit();
177
178
  const absentId=`req_${randomUUID()}`;
178
179
  if(store.hasAssignment(absentId)) throw new Error('absent gate id collision');
179
180
  const log = createRequestLog(path.join(stateDir, 'requests.jsonl'));
181
+ const pullPacing=createPullPacing({now:()=>store.nowMs(),log});
180
182
  const guardArtifactDownload = createArtifactDownloadGuard({log});
181
183
  const scopedSourceChunk=18*1024;
182
184
  function encodePinnedSource(mirror,assignment,requestId,maxBytes=SCOPED_SOURCE_MAX_BYTES,pin) {
@@ -196,13 +198,14 @@ function encodePinnedSource(mirror,assignment,requestId,maxBytes=SCOPED_SOURCE_M
196
198
 
197
199
  // A normal workspace reader can get the already-verified inputs in one reply. The explicit registry
198
200
  // artifact still has its own narrower grant and delivery receipts. This never fetches a missing mirror.
199
- function inlinePinnedSource(row,principal,connectionId,claimId) {
201
+ function pinnedSourceReply(row,principal,connectionId,{claim_id:claimId,input_offset:offset=0,input_sha256:expected}) {
200
202
  const {worker,subject}=principal;
201
203
  const {assignment,request_id:requestId}=row;
202
- if(!workspaceEnabled||row.status!=='claimed'||row.cancelled_at||assignment.execution_scope!=='read-only'||
204
+ if(!claimId||!workspaceEnabled||row.status!=='claimed'||row.cancelled_at||assignment.execution_scope!=='read-only'||
203
205
  assignment.paged_read_scope||!assignment.scope_paths?.length||assignment.scope_paths.includes('.')) return {};
204
206
  const grant=store.liveHeldClaim(requestId,claimId,subject,worker);
205
207
  if(!grant) return {};
208
+ if(offset%scopedSourceChunk!==0||(offset!==0&&!expected)) throw new Error('invalid pinned input offset');
206
209
  try {
207
210
  if(oauth) needScope(principal,scopeFor('read_file'));
208
211
  if(!workerWorkspaceAllowed(worker,requestId)) return {};
@@ -211,12 +214,20 @@ function inlinePinnedSource(row,principal,connectionId,claimId) {
211
214
  const input=assignmentInput(assignment);
212
215
  if(input.input_patch) return {};
213
216
  const mirror=mirrorPath(input.github_repo,{worker});
214
- const {manifest,bytes,sha256}=encodePinnedSource(mirror,assignment,requestId,scopedSourceChunk,input.head_sha??input.base_sha);
215
- const bundle={sha256,pin:manifest.pin,encoding:'base64-json',data_base64:bytes.toString('base64')};
217
+ const {manifest,refusedPaths,bytes,sha256}=encodePinnedSource(mirror,assignment,requestId,SCOPED_SOURCE_MAX_BYTES,input.head_sha??input.base_sha);
218
+ if(expected!==undefined&&expected!==sha256) return {pinned_input_error:'bundle_changed'};
219
+ if(offset>=bytes.length) return {pinned_input_error:'offset_out_of_range'};
220
+ const end=Math.min(offset+scopedSourceChunk,bytes.length);
221
+ const bundle={sha256,pin:manifest.pin,encoding:'base64-json',size:bytes.length,offset,
222
+ next_offset:end===bytes.length?null:end,data_base64:bytes.subarray(offset,end).toString('base64')};
216
223
  if(JSON.stringify(redactOutput(bundle))!==JSON.stringify(bundle)) return {};
224
+ store.recordScopedInputChunk(requestId,{
225
+ epoch:grant.epoch,worker,sha256,chunk:offset/scopedSourceChunk,chunkCount:Math.ceil(bytes.length/scopedSourceChunk),
226
+ metadata:{...manifest,size:bytes.length,...(refusedPaths.length?{refused_paths:refusedPaths}:{})},
227
+ });
217
228
  return {pinned_input_bundle:bundle};
218
229
  } catch {
219
- // A large or unavailable snapshot must not discard a valid claim or deny ordinary workspace reads.
230
+ // An unavailable snapshot must not discard a valid claim or deny ordinary workspace reads.
220
231
  return {};
221
232
  }
222
233
  }
@@ -464,7 +475,7 @@ function maskedForOwner(response) {
464
475
  if(out.claim?.activity) out.claim={...out.claim,activity:{...out.claim.activity,last_tool_error:maskText(out.claim.activity.last_tool_error)}};
465
476
  return out;
466
477
  }
467
- const publicClaimFields=['request_id','claimant','subject','claimed_at','last_progress_at','last_claim_activity_at','worker','epoch','state','abandoned_at','abandon_reason','lease_expires_at','activity','destination_revision'];
478
+ const publicClaimFields=['request_id','claimant','subject','claimed_at','last_progress_at','last_claim_activity_at','worker','epoch','state','abandoned_at','abandon_reason','lease_expires_at','run_deadline_at','heartbeat_interval_ms','activity','destination_revision'];
468
479
  // Worker-visible get must never carry claim capability values. The claim-field
469
480
  // allowlist above already drops claim_id; this recursive pass additionally drops
470
481
  // claim_id, origin_claim_id and acquisition_id from every other generated
@@ -576,14 +587,28 @@ const tools = [
576
587
  ].filter(tool=>((catalogProfile!=='stable'&&!batchClaimProfile)||!['ask_question','consume_answer'].includes(tool.name))&&(t3ToolsEnabled||!tool.name.startsWith('t3_')));
577
588
  if(batchClaimProfile) {
578
589
  const claim=tools.find(item=>item.name==='claim');
579
- claim.description+=' Use next (1 through 8) instead of request_id to claim several queued assignments with one acquisition_id. The reply contains claims and free_lanes.';
580
- claim.inputSchema.properties.next={type:'integer',minimum:1,maximum:8};
590
+ claim.description+=' Use next (1 through 8) instead of request_id to claim as many queued assignments as your own executor has reserved slots for, with one acquisition_id. The reply contains claims and free_lanes.';
591
+ const list=tools.find(item=>item.name==='list_pending');
592
+ list.description+=' Declare free_slots reserved by your local executor, including zero if it cannot start work.';
593
+ list.inputSchema.properties.free_slots={type:'integer',minimum:0,maximum:maxBatchPull};
594
+ Object.assign(claim.inputSchema.properties,{
595
+ next:{type:'integer',minimum:1,maximum:maxBatchPull},
596
+ heartbeat_ms:{type:'integer',minimum:10000,maximum:300000},
597
+ run_timeout_ms:{type:'integer',minimum:10000,maximum:store.limits.leaseMs},
598
+ });
599
+ const finish=tools.find(item=>item.name==='finish');
600
+ Object.assign(finish.inputSchema.properties,{
601
+ capacity_feedback:{type:'string',enum:['capacity_rate_limited','capacity_unavailable']},
602
+ retry_after_ms:{type:'integer',minimum:0,maximum:900000},
603
+ });
581
604
  claim.inputSchema.required=['claimant'];
582
605
  // No top-level oneOf: several MCP hosts reject combinators at the schema root. validate() enforces exactly one of request_id or next.
583
606
  // The stable catalog stays frozen: claim_id on get (heartbeat for that exact claim) is served only in this profile.
584
607
  const get=tools.find(item=>item.name==='get');
585
- get.description='Read assignment, available checks and delivery facts. For your active claim, pass claim_id to refresh activity and receive heartbeat guidance. Small pinned read-only inputs can come together in pinned_input_bundle.';
586
- get.inputSchema.properties.claim_id=string;
608
+ get.description='Read assignment, available checks and delivery facts. For your active claim, pass claim_id to refresh activity and receive heartbeat guidance. For pinned read-only input, decode pinned_input_bundle.data_base64. If next_offset is present, pass it as input_offset and the same bundle sha256 as input_sha256; concatenate decoded bytes as one JSON bundle.';
609
+ Object.assign(get.inputSchema.properties,{
610
+ claim_id:string,input_offset:{type:'integer',minimum:0,maximum:SCOPED_SOURCE_MAX_BYTES},input_sha256:hashField,
611
+ });
587
612
  }
588
613
  // Opt-in compatibility catalog only; grant and lease enforcement are unchanged.
589
614
  if(catalogProfile==='legacy-v46') {
@@ -740,6 +765,8 @@ function validate(name,args,definition=tools.find(x=>x.name===name)) { if(!defin
740
765
  if(name==='claim'&&batchClaimProfile) {
741
766
  if(Object.hasOwn(args,'next')===Object.hasOwn(args,'request_id')) throw new Error('supply exactly one of request_id or next');
742
767
  if(Object.hasOwn(args,'next')&&!Object.hasOwn(args,'acquisition_id')) throw refuse('missing','acquisition_id');
768
+ if(Object.hasOwn(args,'heartbeat_ms')!==Object.hasOwn(args,'run_timeout_ms'))
769
+ throw new Error('heartbeat_ms and run_timeout_ms must be declared together');
743
770
  }
744
771
  // The schema no longer requires summary, but one must exist by now: repairArguments could not derive it when the result is blank.
745
772
  if(name==='finish'&&(args.summary===undefined||typeof args.summary==='string'&&!args.summary.trim())) throw refuse('missing','summary');
@@ -841,8 +868,16 @@ function notifyStalePrCancellation(requestId) {
841
868
  // Abandon claims whose lease ran out (Store.sweepStaleLeases): the row is requeued and its lane is free.
842
869
  function sweepStaleLeases() {
843
870
  const ids=store.sweepStaleLeases();
844
- if(ids.length) log({kind:'claims_lease_expired',count:ids.length,request_ids:ids.slice(0,20)});
845
- for(const id of ids) phaseTrace.expired(id);
871
+ const idle=[],hard=[];
872
+ for(const id of ids) {
873
+ const claim=store.db.prepare('SELECT worker,subject,connection_id,last_progress_at,run_timeout_ms,claimed_at,lease_deadline_at FROM claims WHERE request_id=?').get(id);
874
+ const hardDeadline=claim?.run_timeout_ms!=null&&Date.parse(claim.lease_deadline_at)>=Date.parse(claim.claimed_at)+claim.run_timeout_ms;
875
+ (hardDeadline?hard:idle).push(id);
876
+ if(batchClaimProfile&&claim?.last_progress_at&&!hardDeadline) pullPacing.observe(claim,'live_idle_lease_lost');
877
+ phaseTrace.expired(id);
878
+ }
879
+ if(idle.length) log({kind:'claims_lease_expired',count:idle.length,request_ids:idle});
880
+ if(hard.length) log({kind:'claims_run_deadline_reached',count:hard.length,request_ids:hard});
846
881
  return ids;
847
882
  }
848
883
  const destinations=createDestinations({store,ackLedger,notify:notifyAttachedWaiter,log,crashAt,exit:code=>process.exit(code)});
@@ -938,13 +973,13 @@ function logPendingReply(reply,{worker,subject},callId,batch={}) {
938
973
 
939
974
  // Put the next acquisition before job detail, including after progress and finish.
940
975
  // Derive it after the call (and any finish handoff) so it describes remaining capacity.
941
- function batchRoom(subject,worker) {
942
- const {free_lanes,ready,available,reservedId}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
943
- const hint=store.claimHint(worker);
944
- const hintFree=hint===null?Infinity:Math.max(Number(!!reservedId),hint-store.recentClaimCount(worker));
945
- return {free_lanes,ready,available,hintFree,next:Math.min(available,ready.length,8,hintFree)};
976
+ function batchRoom(principal,freeSlots) {
977
+ const {worker,subject}=principal;
978
+ const {free_lanes,ready,available}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
979
+ const desired=freeSlots??pullPacing.free(principal,store.activeClaims(subject,worker).length);
980
+ return {free_lanes,ready,available,desired,next:Math.min(desired,available,ready.length,maxBatchPull)};
946
981
  }
947
- function batchCapacityReply(name,reply,principal,callId,onOffer) {
982
+ function batchCapacityReply(name,reply,principal,callId,onOffer,freeSlots) {
948
983
  if(!['list_pending','claim','progress','finish'].includes(name)) return reply;
949
984
  const recordListing=name==='list_pending'&&!!callId;
950
985
  if(!batchClaimProfile) {
@@ -952,20 +987,20 @@ function batchCapacityReply(name,reply,principal,callId,onOffer) {
952
987
  return reply;
953
988
  }
954
989
  const {worker,subject}=principal;
955
- const {free_lanes,ready,available,hintFree,next}=batchRoom(subject,worker);
956
- const ready_queued=ready.length;
990
+ const {free_lanes,ready,available,desired,next}=batchRoom(principal,freeSlots);
991
+ const ready_queued=ready.length, demand_source=freeSlots===undefined?'hosted_advice':'worker_declared';
957
992
  const [reason,next_action]=quiescing?['quiescing',restartQuiesceText]:
958
993
  store.paused()?['paused','Claims are paused; call list_pending again later.']:
959
994
  next>0?['ready',`claim with next=${next} now`]:
960
995
  available===0?['lanes_full','Continue held work and finish one before claiming more.']:
961
- ready_queued>0&&hintFree===0?['hint_full','Lanes are free but the claim hint is full; claim again when the hint allows more.']:
996
+ ready_queued>0&&desired===0?['no_worker_slots','Continue held work or poll with free_slots when your executor has capacity.']:
962
997
  ['no_ready_work','No ready queued work; call list_pending again later.'];
963
998
  const {next_action:previousAction,free_lanes:previousFree,...rest}=reply;
964
- const response={next_action,free_lanes,claimable_lanes:available,ready_queued,recommended_claims:reason==='ready'?next:0,dispatch_reason:reason,...rest};
999
+ const recommended_claims=reason==='ready'?next:0;
1000
+ const response={next_action,free_lanes,ready_queued,claimable_lanes:available,recommended_claims,dispatch_reason:reason,demand_source,...rest};
965
1001
  if(recordListing) {
966
- const recommended=reason==='ready'?next:0;
967
- const readyIds=ready.slice(0,recommended).map(item=>item.request_id);
968
- logPendingReply(response,principal,callId,{ready_queued,claimable_lanes:available,dispatch_reason:reason,recommended_claims:recommended,ready_head_ids:readyIds});
1002
+ const readyIds=ready.slice(0,recommended_claims).map(item=>item.request_id);
1003
+ logPendingReply(response,principal,callId,{ready_queued,claimable_lanes:available,dispatch_reason:reason,recommended_claims,demand_source,ready_head_ids:readyIds});
969
1004
  if(readyIds.length) onOffer?.({worker,subject,callId,readyIds});
970
1005
  }
971
1006
  return response;
@@ -1382,7 +1417,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1382
1417
  case 'list_pending': {
1383
1418
  const {free_lanes,worker_max_claims,reserved_request_id}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1384
1419
  const assignments=store.listPending(worker);
1385
- store.recordListed(assignments,free_lanes+Number(!!reserved_request_id),worker,!quiescing);
1420
+ store.recordListed(assignments,batchClaimProfile?batchRoom(principal,a.free_slots).next:free_lanes+Number(!!reserved_request_id),worker,!quiescing);
1386
1421
  phaseTrace.listed(assignments.map(x=>x.request_id));
1387
1422
  const hint=store.claimHint(worker),baseGuidance=hint===null?listGuidance:hintGuidance(hint);
1388
1423
  const guidance=workers.workers.get(worker)?.guidance==='resume'?`${baseGuidance} ${resumeNudge(store.resumeIdleMs()||undefined)}`:baseGuidance;
@@ -1397,8 +1432,8 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1397
1432
  const claimant=str(a.claimant,'claimant',128);
1398
1433
  const lanes=()=>store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity).free_lanes;
1399
1434
  const {available}=store.batchClaimRoom(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1400
- const {claims,retry}=await store.claimBatch({next:a.next,available,worker,subject,connectionId,claimant,acquisitionId:a.acquisition_id,leaseMs:a.lease_ms},
1401
- (request_id,acquisition_id,mode)=>signal?.aborted?null:tool('claim',{request_id,claimant,acquisition_id,...(a.lease_ms===undefined?{}:{lease_ms:a.lease_ms})},principal,undefined,signal,mode));
1435
+ const {claims,retry}=await store.claimBatch({next:a.next,available,worker,subject,connectionId,claimant,acquisitionId:a.acquisition_id,leaseMs:a.lease_ms,heartbeatMs:a.heartbeat_ms,runTimeoutMs:a.run_timeout_ms},
1436
+ (request_id,acquisition_id,mode)=>signal?.aborted?null:tool('claim',{request_id,claimant,acquisition_id,...(a.lease_ms===undefined?{}:{lease_ms:a.lease_ms}),...(a.heartbeat_ms===undefined?{}:{heartbeat_ms:a.heartbeat_ms,run_timeout_ms:a.run_timeout_ms})},principal,undefined,signal,mode));
1402
1437
  return {claims,...(retry?{retry:true}:{}),free_lanes:lanes()};
1403
1438
  }
1404
1439
  const requestId=id(a.request_id),claimant=str(a.claimant,'claimant',128),ctx=commandContext('claim',{claimant,acquisition_id:a.acquisition_id??null,lease_ms:a.lease_ms??null}),row=store.get(requestId),held=row.claim?.state==='active'?row.claim:null,retry=holdsLiveGrant(worker,requestId,claimant,subject,a.acquisition_id);
@@ -1435,11 +1470,15 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1435
1470
  // claimant's own connection is still live. The token was verified before
1436
1471
  // the awaited preflight/quiesce above, so a revoke in between must not
1437
1472
  // admit the claim. External-OAuth principals pass null and are unchanged.
1438
- const claimed=store.claim(requestId,claimant,subject,claimCapacity,preflight,worker,a.acquisition_id,a.lease_ms,ctx,principal.builtin?(principal.connection_id??''):null,batchMode);
1473
+ const idleLease=a.heartbeat_ms===undefined?a.lease_ms:Math.min(a.heartbeat_ms*3,a.lease_ms??store.limits.leaseMs);
1474
+ const claimed=store.claim(requestId,claimant,subject,claimCapacity,preflight,worker,a.acquisition_id,idleLease,ctx,principal.builtin?(principal.connection_id??''):null,batchMode,a.run_timeout_ms);
1439
1475
  const grant=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
1440
1476
  if(!retry) phaseTrace.claimed({requestId,worker,subject,claimId:claimed.claim_id,handoff:String(a.acquisition_id??'').startsWith(HANDOFF_ACQUISITION_PREFIX),createdAt:store.db.prepare('SELECT created_at FROM assignments WHERE request_id=?').get(requestId)?.created_at});
1441
1477
  const {free_lanes,queued,reserved_request_id}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1442
- return withAvailableChecks({...claimed,lease_ms:store.claimLeaseMs(grant),lease_expires_at:claimed.lease_expires_at??store.leaseExpiresAt(grant),queued_after_claim:queued,free_lanes,...store.nextQueued(free_lanes,requestId,worker,{reservedId:reserved_request_id??null}),guidance:`${claimed.guidance} ${store.claimHint(worker)===null?(batchClaimProfile?claimMoreGuidance:plainClaimGuidance(free_lanes,queued)):hintMoreGuidance(store.claimHint(worker))}`},true,worker,subject,workspaceAllowed);
1478
+ return withAvailableChecks({...claimed,lease_ms:store.claimLeaseMs(grant),...(grant.run_timeout_ms==null?{}:{
1479
+ heartbeat_interval_ms:Math.max(1,Math.floor(store.claimLeaseMs(grant)/3)),
1480
+ run_deadline_at:new Date(Date.parse(grant.claimed_at)+grant.run_timeout_ms).toISOString()
1481
+ }),lease_expires_at:claimed.lease_expires_at??store.leaseExpiresAt(grant),queued_after_claim:queued,free_lanes,...store.nextQueued(free_lanes,requestId,worker,{reservedId:reserved_request_id??null}),guidance:`${claimed.guidance} ${store.claimHint(worker)===null?(batchClaimProfile?claimMoreGuidance:plainClaimGuidance(free_lanes,queued)):hintMoreGuidance(store.claimHint(worker))}`},true,worker,subject,workspaceAllowed);
1443
1482
  }
1444
1483
  case 'renew_claim': {
1445
1484
  if(!strictJob) throw new Error('renew_claim requires a protocol job');
@@ -1450,9 +1489,8 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1450
1489
  if(!store.hasAssignment(requestId)) return {kind:'message',message:store.getMessage(requestId,worker)};
1451
1490
  store.markNotesSeenByHolder(requestId,subject,worker,connectionId);
1452
1491
  const row=store.get(requestId);
1453
- const claimId=a.claim_id??(row.claim?.epoch===1?row.claim.claim_id:undefined);
1454
1492
  return {...publicWorkerGet(withAvailableChecks(row,true,worker,subject)),...store.workerGetHeartbeat(row,worker,subject,a.claim_id),
1455
- ...inlinePinnedSource(row,principal,connectionId,claimId),guidance:store.guidanceFor(worker)};
1493
+ ...pinnedSourceReply(row,principal,connectionId,a),guidance:store.guidanceFor(worker)};
1456
1494
  }
1457
1495
  case 'ack_message': {const message=store.ackMessage(id(a.message_id,'message_id'),worker);log({kind:'message_acknowledged',message_id:message.message_id});return {kind:'message',message};}
1458
1496
  case 'progress': {
@@ -1529,6 +1567,10 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1529
1567
  }
1530
1568
  const receipt=store.finish(requestId,claimId,a.outcome,str(a.summary,'summary',4096),str(a.result,'result',256*1024),subject,null,worker,commandContext('finish',{artifact_ids:a.artifact_ids??[]}),captureEvidence,connectionId);
1531
1569
  if(receipt.deferred) return {...receipt,...repaired.marks};
1570
+ if(batchClaimProfile&&!receipt.duplicate&&!receipt.late) {
1571
+ if(a.outcome==='completed') pullPacing.observe(principal,'completed');
1572
+ else if(a.capacity_feedback) pullPacing.observe(principal,a.capacity_feedback,a.retry_after_ms??30000);
1573
+ }
1532
1574
  if(crashAt('after_report_persistence',a.request_id)) process.exit(73);
1533
1575
  notifyAttachedWaiter(requestId);
1534
1576
  if(repaired.marks.summary_derived||repaired.marks.summary_truncated) log({kind:'finish_summary_repaired',request_id:requestId,...repaired.marks});
@@ -1604,7 +1646,7 @@ async function dispatch(message,principal,signal,callId,onOffer) {
1604
1646
  // Modern catalogs are process-wide. A worker's capability controls tools/call authority, not its cached schemas.
1605
1647
  // legacy-v46 keeps its pinned per-worker surface for compatibility.
1606
1648
  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};
1607
- 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; } }
1649
+ 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,p.arguments?.free_slots)))}],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; } }
1608
1650
  case 'events/list': return {events:[event]};
1609
1651
  case 'events/subscribe': if(oauth)needScope(principal,'dalan.read');return subscribe(p,principal);
1610
1652
  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 {}; }
@@ -1801,7 +1843,9 @@ const adminServer=http.createServer(async(req,res)=>{
1801
1843
  },
1802
1844
  preflight:p=>preflightPR(p),
1803
1845
  // Advisory only, like Store.submit: a supersede target leaves the queued count unchanged. Store.submit rechecks it in its transaction.
1804
- state:r=>({paused:store.paused(),pause_reason:store.db.prepare('SELECT reason FROM operator_state WHERE id=1').get().reason,worker_break:store.holdingBreak(r.target),queued:store.db.prepare("SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND (valid_until IS NULL OR valid_until>?)").get(r.target,supersedes?.target_id??null,new Date(store.nowMs()).toISOString()).n,queued_same_priority:store.db.prepare("SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND priority=? AND (?=0 OR caller_waiting=1) AND request_id IS NOT ? AND (valid_until IS NULL OR valid_until>?)").get(r.target,body.background===true?'background':'normal',body.caller_waiting===true?1:0,supersedes?.target_id??null,new Date(store.nowMs()).toISOString()).n}),
1846
+ state:r=>({paused:store.paused(),pause_reason:store.db.prepare('SELECT reason FROM operator_state WHERE id=1').get().reason,
1847
+ worker_break:store.holdingBreak(r.target),
1848
+ ...store.admissionQueueCounts(r.target,body.background===true?'background':'normal',body.caller_waiting===true,supersedes?.target_id??null)}),
1805
1849
  kind:(r,p)=>r.meta?.task_kind??(r.review?'review':p.execution_scope??'unknown'),
1806
1850
  defaultValidity:(kind,r)=>store.defaultValidUntil(r.target,kind),
1807
1851
  retryAfterSeconds:r=>{const w=store.queueWaitsMs(r.target,r.meta?.task_kind??(r.review?'review':'unknown'));return w.length?Math.min(3600,Math.max(60,Math.round(w[Math.floor(w.length/2)]/1000))):300;},
@@ -2352,7 +2396,7 @@ setInterval(()=>{
2352
2396
  AND request_id IN (${ids.map(()=>'?').join(',')}) LIMIT 1`).get(...ids);
2353
2397
  if(!queued) return false;
2354
2398
  if(store.paused()||quiescing||store.holdingBreak(worker)||store.capacityHoldUntil(worker)) return null;
2355
- const {ready,next}=batchRoom(subject,worker);
2399
+ const {ready,next}=batchRoom({subject,worker},maxBatchPull);
2356
2400
  return ready.slice(0,next).some(item=>ids.includes(item.request_id))?true:null;
2357
2401
  });
2358
2402
  for(const stall of due) {
package/src/store.mjs CHANGED
@@ -1136,6 +1136,8 @@ export class Store {
1136
1136
  prior_id TEXT NOT NULL REFERENCES assignments(request_id),
1137
1137
  at TEXT NOT NULL
1138
1138
  ); PRAGMA user_version=75;`);
1139
+ if(!this.db.prepare("SELECT 1 FROM pragma_table_info('claims') WHERE name='run_timeout_ms'").get())
1140
+ this.db.exec('ALTER TABLE claims ADD COLUMN run_timeout_ms INTEGER');
1139
1141
  // Older bridges read every open row of worker_breaks as a primary-worker hold.
1140
1142
  // Keep secondary-worker holds out of that table so a rollback can still read current data.
1141
1143
  this.db.exec(`CREATE TABLE IF NOT EXISTS scoped_worker_breaks(
@@ -1426,6 +1428,7 @@ export class Store {
1426
1428
  const aheadRows=this.db.prepare(`SELECT request_id,created_at,
1427
1429
  EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked FROM assignments
1428
1430
  WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND request_id IS NOT ? AND ${live(now)}
1431
+ AND ${noPrClaimBlock('assignments')}
1429
1432
  AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id)
1430
1433
  AND (${LIST_ORDER}) < (?, ?, ?, CAST(? AS INTEGER))`)
1431
1434
  .all(worker,first,second,rankPriority,rankSkipped,rankCreated,rankRow);
@@ -1816,10 +1819,10 @@ export class Store {
1816
1819
  if(!Number.isSafeInteger(maxQueued)||maxQueued<1) throw new Error('invalid max_queued');
1817
1820
  // Waiting callers count only waiting peers of the same priority; backlog cannot refuse them.
1818
1821
  // Other callers keep the same-priority cap.
1819
- const queued=this.db.prepare(`SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND priority=? AND (?=0 OR caller_waiting=1) AND request_id IS NOT ? AND ${live(this.nowMs())}`).get(targetWorker??'dot',priority,callerWaiting?1:0,supersededId).n;
1822
+ const queued=this.admissionQueueCounts(targetWorker??'dot',priority,callerWaiting,supersededId).queued_same_priority;
1820
1823
  if(queued>=maxQueued) throw new Error(`worker queue is full (${queued} queued, in-flight cap ${maxQueued})`);
1821
1824
  }
1822
- if(priority==='background'&&this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority='background' AND target_worker=? AND request_id IS NOT ? AND (status='claimed' OR status='queued' AND ${live(this.nowMs())})`).get(targetWorker??'dot',supersededId).n>=this.backgroundMaxInFlight) throw new Error('background_capacity_full');
1825
+ if(priority==='background'&&this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority='background' AND target_worker=? AND request_id IS NOT ? AND (status='claimed' OR status='queued' AND ${live(this.nowMs())} AND ${noPrClaimBlock('assignments')})`).get(targetWorker??'dot',supersededId).n>=this.backgroundMaxInFlight) throw new Error('background_capacity_full');
1823
1826
  // The target is a column, not payload: an omitted worker means 'dot'.
1824
1827
  this.db.prepare('INSERT INTO assignments(request_id,payload,payload_hash,thread_id,environment_id,status,created_at,owner_hash,review,delivery,priority,objective_key,revision,task_kind,source,target_worker,execution,required_capabilities,delivery_adapter,delivery_address,delivery_adapter_version,caller_waiting) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,body,payloadHash,threadId,environmentId??'','queued',this.stamp(),ownerHash,review?1:0,deliveryValue,priority,...metaFields.map(k=>k==='source'?toStoredSource(m[k],this.legacyFixNames):m[k]),targetWorker??'dot',execution??defaultExecution,requiredCapabilities?JSON.stringify(requiredCapabilities):null,deliveryAdapter,deliveryAddress,deliveryAdapterVersion,callerWaiting?1:0);
1825
1828
  if(typeof parentGeneration==='string')this.db.prepare('UPDATE assignments SET parent_generation=? WHERE request_id=?').run(parentGeneration,id);
@@ -1950,12 +1953,13 @@ export class Store {
1950
1953
  key:ctx.key,expectedRevision:ctx.revision,operation:ctx.operation,args:ctx.args},mutate,
1951
1954
  {leaseCapMs:this.workerClaimLeaseCap(worker)});
1952
1955
  }
1953
- setClaimDeadlineInTransaction(id,leaseMs) {
1954
- const activity=this.db.prepare('SELECT last_claim_activity_at FROM claims WHERE request_id=?').get(id)?.last_claim_activity_at;
1955
- const deadline=Date.parse(activity??this.stamp())+leaseMs;
1956
+ setClaimDeadlineInTransaction(id,leaseMs,runTimeoutMs=null) {
1957
+ const claim=this.db.prepare('SELECT last_claim_activity_at,claimed_at FROM claims WHERE request_id=?').get(id);
1958
+ const activity=Date.parse(claim?.last_claim_activity_at??this.stamp());
1959
+ const deadline=Math.min(activity+leaseMs,runTimeoutMs===null?Infinity:Date.parse(claim.claimed_at)+runTimeoutMs);
1956
1960
  if(!protocolNat(deadline))protocolError('invalid_lease');
1957
- this.db.prepare('UPDATE claims SET lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=?')
1958
- .run(iso(deadline),this.leaseBootId,this.monotonicDeadlineFor(deadline),id);
1961
+ this.db.prepare('UPDATE claims SET lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=?,run_timeout_ms=? WHERE request_id=?')
1962
+ .run(iso(deadline),this.leaseBootId,this.monotonicDeadlineFor(deadline),runTimeoutMs,id);
1959
1963
  }
1960
1964
  workerClaimLeaseCap(worker) {
1961
1965
  const caps=this.limits.workerClaimLeaseMs;
@@ -2100,6 +2104,12 @@ export class Store {
2100
2104
  this.db.prepare('INSERT INTO notifications(id,kind,request_id,subscription_id,body,created_at,wake_kind) VALUES(?,?,?,?,?,?,?)').run(eventId,'event',id,sub.id,body,this.stamp(),wakeKind);
2101
2105
  return eventId;
2102
2106
  }
2107
+ admissionQueueCounts(worker,priority,callerWaiting,excludeId=null) {
2108
+ return this.db.prepare(`SELECT count(*) queued,
2109
+ count(*) FILTER (WHERE priority=? AND (?=0 OR caller_waiting=1)) queued_same_priority
2110
+ FROM assignments WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND ${live(this.nowMs())}
2111
+ AND ${noPrClaimBlock('assignments')}`).get(priority,callerWaiting?1:0,worker,excludeId);
2112
+ }
2103
2113
  // Queued assignments in list_pending order (waiting normal before other normal, then background and oldest) with queued_at (see queuedAt).
2104
2114
  queuedRows() {
2105
2115
  return this.db.prepare(`SELECT a.request_id,a.payload,a.priority,a.caller_waiting,a.target_worker,${queuedAt} queued_at FROM assignments a WHERE a.status='queued' AND a.cancelled_at IS NULL AND ${live(this.nowMs())} AND ${noPrClaimBlock('a')} ORDER BY ${LIST_ORDER}`).all();
@@ -2406,9 +2416,9 @@ export class Store {
2406
2416
  this.refreshClaimActivity(id,claimId);
2407
2417
  }
2408
2418
  refreshClaimActivity(id,claimId) {
2409
- const at=this.stamp(), claim=this.db.prepare('SELECT lease_ms,worker,acquisition_id FROM claims WHERE request_id=? AND claim_id=?').get(id,claimId);
2419
+ const at=this.stamp(), claim=this.db.prepare('SELECT lease_ms,worker,acquisition_id,claimed_at,run_timeout_ms FROM claims WHERE request_id=? AND claim_id=?').get(id,claimId);
2410
2420
  const leaseMs=Math.min(this.handoffWorkLeaseMs(claim)??claim?.lease_ms??this.limits.leaseMs,this.workerClaimLeaseCap(claim?.worker));
2411
- const deadline=Date.parse(at)+leaseMs;
2421
+ const deadline=Math.min(Date.parse(at)+leaseMs,claim.run_timeout_ms==null?Infinity:Date.parse(claim.claimed_at)+claim.run_timeout_ms);
2412
2422
  if(this.isProtocolJob(id)) this.db.prepare('UPDATE claims SET last_claim_activity_at=? WHERE request_id=? AND claim_id=?').run(at,id,claimId);
2413
2423
  else this.db.prepare('UPDATE claims SET last_claim_activity_at=?,lease_ms=?,lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=? AND claim_id=?')
2414
2424
  .run(at,leaseMs,iso(deadline),this.leaseBootId,this.monotonicDeadlineFor(deadline),id,claimId);
@@ -2703,7 +2713,9 @@ export class Store {
2703
2713
  const a=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(id); if(!a) { const work=this.pullQueue.row(id);if(work)return this.pullQueue.project(work);throw new Error('assignment not found'); }
2704
2714
  this.assertProtocolAvailable(id);
2705
2715
  const claimRow=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
2706
- const claim=claimRow&&(({acquisition_id,tool_calls,last_tool,last_tool_at,last_tool_error,first_workspace_tool_at,destination_revision,...rest})=>({...rest,...(destination_revision?{destination_revision}:{}),lease_expires_at:this.leaseExpiresAt(claimRow),activity:Store.toolActivity(claimRow)}))(claimRow);
2716
+ const claim=claimRow&&(({acquisition_id,tool_calls,last_tool,last_tool_at,last_tool_error,first_workspace_tool_at,destination_revision,run_timeout_ms,...rest})=>({...rest,...(run_timeout_ms==null?{}:{
2717
+ run_deadline_at:iso(Date.parse(rest.claimed_at)+run_timeout_ms),heartbeat_interval_ms:Math.max(1,Math.floor(this.claimLeaseMs(rest)/3))
2718
+ }),...(destination_revision?{destination_revision}:{}),lease_expires_at:this.leaseExpiresAt(claimRow),activity:Store.toolActivity(claimRow)}))(claimRow);
2707
2719
  const report=this.db.prepare('SELECT * FROM reports WHERE request_id=?').get(id);
2708
2720
  if(report?.workspace_evidence) report.workspace_evidence=JSON.parse(report.workspace_evidence);
2709
2721
  // Everything in a report is the worker's own statement. Only a check row carries bridge_verified, and only when the bridge ran it.
@@ -3052,14 +3064,14 @@ export class Store {
3052
3064
  // Persist selected IDs before asynchronous preflight. A retry can recover
3053
3065
  // live grants, or try the same nonempty plan if it never granted anything.
3054
3066
  // It cannot select different IDs or issue new grants after any grant landed.
3055
- async claimBatch({next,available,worker,subject,connectionId,claimant,acquisitionId,leaseMs},grant) {
3067
+ async claimBatch({next,available,worker,subject,connectionId,claimant,acquisitionId,leaseMs,heartbeatMs,runTimeoutMs},grant) {
3056
3068
  if(!Number.isInteger(next)||next<1||next>8) throw new Error('invalid next');
3057
3069
  if(typeof acquisitionId!=='string'||!/^[A-Za-z0-9_-]{1,128}$/.test(acquisitionId)) throw new Error('batch claim requires acquisition_id');
3058
3070
  if(this.paused()) throw new Error(pausedClaimMessage);
3059
3071
  const hash=(...values)=>createHash('sha256').update(JSON.stringify(values)).digest('hex');
3060
3072
  const digest=hash(worker,subject,acquisitionId);
3061
3073
  const key='claim_batch_v1_'+digest;
3062
- const parameters=hash(connectionId,claimant,next,leaseMs??null);
3074
+ const parameters=hash(connectionId,claimant,next,leaseMs??null,...(heartbeatMs===undefined?[]:[heartbeatMs,runTimeoutMs]));
3063
3075
  const plan=this.transaction(()=>{
3064
3076
  const previous=this.db.prepare('SELECT value FROM bridge_state WHERE key=?').get(key);
3065
3077
  if(previous) {
@@ -3246,7 +3258,7 @@ export class Store {
3246
3258
  } catch(error) { throw this.destinationConfigurationError(id,error); }
3247
3259
  if(digest!==approval.snapshot.connections_digest)throw refuse('Claim retry refused: the approved connection set changed.');
3248
3260
  }
3249
- claim(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,ctx=null,connectionId=null,batchMode=null) {
3261
+ claim(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,ctx=null,connectionId=null,batchMode=null,runTimeoutMs=null) {
3250
3262
  const requestedLeaseMs=arguments[7]??null;
3251
3263
  const claim=this.destinationOutcome(this.transaction(()=>{
3252
3264
  if(batchMode==='queued') {
@@ -3256,13 +3268,14 @@ export class Store {
3256
3268
  if(batchMode==='retry'&&!this.isExactClaimRetry(this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id),claimant,subject,acquisitionId)) throw new Error('batch grant no longer live');
3257
3269
  return this.isProtocolJob(id)
3258
3270
  ?this.protocolClaimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,ctx?{...ctx,requestedLeaseMs}:ctx,connectionId)
3259
- :this.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,connectionId);
3271
+ :this.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,connectionId,runTimeoutMs);
3260
3272
  }));
3261
3273
  return nonterminalOutcome(id,{...claim,...this.heartbeatForHeldClaim(id,claim.claim_id,worker)});
3262
3274
  }
3263
- claimInTransaction(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,connectionId=null) {
3275
+ claimInTransaction(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,connectionId=null,runTimeoutMs=null) {
3264
3276
  if(!this.db.isTransaction)protocolError('transaction_required');
3265
3277
  leaseMs=this.cappedClaimLeaseMs(leaseMs,worker);
3278
+ if(runTimeoutMs!==null&&(!Number.isSafeInteger(runTimeoutMs)||runTimeoutMs<1||runTimeoutMs>this.limits.leaseMs)) throw new Error('invalid run_timeout_ms');
3266
3279
  if(acquisitionId!==null&&(typeof acquisitionId!=='string'||!/^[A-Za-z0-9_-]{1,128}$/.test(acquisitionId))) throw new Error('invalid acquisition_id: use 1-128 letters, digits, underscores or hyphens');
3267
3280
  if(!this.mayAct(worker,id)) throw new Error('assignment not found');
3268
3281
  if(this.db.prepare("SELECT 1 FROM facade_withdrawals WHERE request_id=? AND EXISTS (SELECT 1 FROM assignments WHERE request_id=? AND status='queued')").get(id,id))
@@ -3285,7 +3298,7 @@ export class Store {
3285
3298
  if(old && (old.state!=='active' || this.leaseExpired(old))) this.assertRegrantReady(old);
3286
3299
  if(takeover&&old.subject===subject&&this.isIdleClaim(old)) {
3287
3300
  this.assertClaimGap(id,subject,worker);
3288
- return this.rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs,connectionId);
3301
+ return this.rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs,connectionId,runTimeoutMs);
3289
3302
  }
3290
3303
  if(takeover) {
3291
3304
  if(!this.leaseExpired(old)&&old.subject===subject&&this.resumeIdleMs()>0) throw new Error(JSON.stringify({error:'claim_busy',message:`Request ${id}: another run of this worker holds it and is active; pick other work or retry after its lease expires. This affects only ${id}.`,request_id:id}));
@@ -3310,7 +3323,7 @@ export class Store {
3310
3323
  this.db.prepare("UPDATE claims SET claimant=?,claim_id=?,claimed_at=?,subject=?,last_claim_activity_at=?,last_seen_note_seq=?,last_progress_at=NULL,epoch=epoch+1,state='active',abandoned_at=NULL,abandon_reason=NULL,tool_calls=0,last_tool=NULL,last_tool_at=NULL,last_tool_error=NULL,first_workspace_tool_at=NULL,lane_key=?,acquisition_id=?,lease_ms=?,connection_id=? WHERE request_id=?").run(claimant,claimId,claimedAt,subject,claimedAt,seen,laneKey,acquisitionId,leaseMs,connectionId??null,id);
3311
3324
  this.rebindClaim(id,claimId);
3312
3325
  } else this.db.prepare('INSERT INTO claims(request_id,claimant,claim_id,claimed_at,subject,last_claim_activity_at,last_seen_note_seq,worker,lane_key,lane_scope,acquisition_id,lease_ms,connection_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,claimant,claimId,claimedAt,subject,claimedAt,seen,worker,laneKey,laneScope,acquisitionId,leaseMs,connectionId??null);
3313
- this.setClaimDeadlineInTransaction(id,leaseMs);
3326
+ this.setClaimDeadlineInTransaction(id,leaseMs,runTimeoutMs);
3314
3327
  if(a.status==='queued') {
3315
3328
  this.recordPassedOver(id,worker);
3316
3329
  this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE target_worker=? AND status='queued' AND request_id<>? AND eligible_since IS NOT NULL").run(worker,id);
@@ -3326,7 +3339,7 @@ export class Store {
3326
3339
  // transaction, so a run still alive under the old claim_id is refused on its next call (claim_superseded). Worktree and sealed
3327
3340
  // uploads move with it (rebindClaim). Lifecycle: a 'claimed' event with reason 'resume' (not counted as a new admission; the
3328
3341
  // event type list is closed, so no 'resumed' type). The previous epoch and the idle time go to the progress history.
3329
- rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs=this.limits.leaseMs,connectionId=null) {
3342
+ rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs=this.limits.leaseMs,connectionId=null,runTimeoutMs=null) {
3330
3343
  this.assertRegrantReady(old);
3331
3344
  this.assertLiveConnection(old.request_id,worker,connectionId);
3332
3345
  const id=old.request_id, idleS=Math.floor(this.claimIdleMs(old)/1000);
@@ -3335,7 +3348,7 @@ export class Store {
3335
3348
  const destinationRefusal=this.destinationAdmissionInTransaction(id);
3336
3349
  if(destinationRefusal)return destinationRefusal;
3337
3350
  this.assertNoUncertainDelivery(id);
3338
- const {claimId,at,epoch}=this.startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId);
3351
+ const {claimId,at,epoch}=this.startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId,runTimeoutMs);
3339
3352
  this.db.prepare('INSERT INTO progress(request_id,note,created_at,worker) VALUES(?,?,?,?)').run(id,`[bridge] run resumed: epoch ${old.epoch} lease expired after ${idleS}s without activity; epoch ${epoch} continues under a new claim`,at,worker);
3340
3353
  this.markBatchGrant(id,acquisitionId);
3341
3354
  this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch,worker});
@@ -3343,11 +3356,11 @@ export class Store {
3343
3356
  }
3344
3357
  // The one re-grant of an existing claim row: new claim_id and epoch, and every old-epoch field (progress, tool counters, acquisition, lease) reset.
3345
3358
  // rotateIdleClaim (claim wake) and resume both call it, so the two paths cannot drift.
3346
- startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId) {
3359
+ startNextEpoch(old,claimant,acquisitionId,leaseMs,connectionId,runTimeoutMs=null) {
3347
3360
  const id=old.request_id, claimId=`claim_${randomUUID()}`, at=this.stamp(), epoch=old.epoch+1;
3348
3361
  const seen=this.db.prepare('SELECT COALESCE(max(sequence),0) n FROM owner_notes WHERE request_id=?').get(id).n;
3349
3362
  this.db.prepare("UPDATE claims SET claimant=?,claim_id=?,claimed_at=?,last_claim_activity_at=?,last_seen_note_seq=?,last_progress_at=NULL,epoch=?,tool_calls=0,last_tool=NULL,last_tool_at=NULL,last_tool_error=NULL,first_workspace_tool_at=NULL,acquisition_id=?,lease_ms=?,connection_id=? WHERE request_id=?").run(claimant,claimId,at,at,seen,epoch,acquisitionId,leaseMs,connectionId??null,id);
3350
- this.setClaimDeadlineInTransaction(id,leaseMs);
3363
+ this.setClaimDeadlineInTransaction(id,leaseMs,runTimeoutMs);
3351
3364
  this.rebindClaim(id,claimId);
3352
3365
  return {claimId,at,epoch};
3353
3366
  }
@@ -3364,7 +3377,7 @@ export class Store {
3364
3377
  const destinationRefusal=this.destinationAdmissionInTransaction(id);
3365
3378
  if(destinationRefusal)return destinationRefusal;
3366
3379
  this.assertNoUncertainDelivery(id);
3367
- const {claimId}=this.startNextEpoch(old,old.claimant,old.acquisition_id,this.claimLeaseMs(old),connectionId??old.connection_id); // resume cannot ask for a lease or an acquisition, so the epoch keeps the ones the worker was granted (its exact retry of a lost reply still matches)
3380
+ const {claimId}=this.startNextEpoch(old,old.claimant,old.acquisition_id,this.claimLeaseMs(old),connectionId??old.connection_id,old.run_timeout_ms??null); // resume cannot ask for a lease or an acquisition, so the epoch keeps the ones the worker was granted (its exact retry of a lost reply still matches)
3368
3381
  this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch:old.epoch+1});
3369
3382
  if(this.isProtocolJob(id)) {
3370
3383
  this.advanceProtocolRevisionInTransaction(id);
@@ -4045,6 +4058,14 @@ export class Store {
4045
4058
  if(row.kind==='event'&&row.request_id&&this.isProtocolJob(row.request_id)&&!this.protocolListingLive(row.request_id)) {
4046
4059
  this.db.prepare("UPDATE notifications SET state='suppressed',last_error='protocol retention expired' WHERE id=?").run(id);return null;
4047
4060
  }
4061
+ if(row.kind==='event'&&(row.wake_kind==='submit'||row.wake_kind==='rewake')) {
4062
+ const blocked=this.db.prepare(`SELECT 1 FROM pr_claim_blocks
4063
+ WHERE request_id IN (?1,CASE WHEN json_valid(?2) THEN json_extract(?2,'$.data.request_id') END)`).get(row.request_id,row.body);
4064
+ if(blocked) {
4065
+ this.db.prepare("UPDATE notifications SET state='suppressed',last_error='queued PR is blocked' WHERE id=?").run(id);
4066
+ return null;
4067
+ }
4068
+ }
4048
4069
  // A re-wake no longer valid is suppressed unsent: it is no last wake, so the next tick recomputes the head. A still
4049
4070
  // valid retry keeps its id and body.
4050
4071
  const stale=row.wake_kind==='rewake'&&this.rewakeStale(row);
@@ -4328,7 +4349,7 @@ export class Store {
4328
4349
  // Queued counts are live: rows past valid_until are reported as queued_expired, and protocol jobs past retention are
4329
4350
  // left out, never counted as queue, cap or throttle room.
4330
4351
  const queuedExpired=this.queuedExpired(), queuedExpiredRequeued=this.queuedExpiredRequeued();
4331
- const counts=this.db.prepare(`SELECT status,count(*) count FROM assignments WHERE status<>'queued' OR ${live(this.nowMs())} GROUP BY status`).all().filter(x=>x.count>0);
4352
+ const counts=this.db.prepare(`SELECT status,count(*) count FROM assignments WHERE status<>'queued' OR (${live(this.nowMs())} AND ${noPrClaimBlock('assignments')}) GROUP BY status`).all().filter(x=>x.count>0);
4332
4353
  const sub=this.db.prepare("SELECT * FROM subscriptions WHERE worker='dot' ORDER BY verified_at DESC LIMIT 1").get();
4333
4354
  const active=this.activeSubscriptions().filter(sub=>sub.worker==='dot');
4334
4355
  const oldest=this.db.prepare(`SELECT min(created_at) oldest FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())} AND ${noPrClaimBlock('assignments')}`).get().oldest;
@@ -4343,7 +4364,7 @@ export class Store {
4343
4364
  SELECT worker,n,created_at oldest,request_id FROM live_queue WHERE rank=1`).all().map(r=>[r.worker,r]));
4344
4365
  const dotQueuedWithoutSubscription=active.length===0&&!!this.db.prepare(`SELECT 1 FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())} AND ${noPrClaimBlock('assignments')} LIMIT 1`).get();
4345
4366
  const subscription={state:!sub?'absent':sub.state==='revoked'?'revoked':sub.rotation_blocked?'rotation_blocked':sub.auth_failures>=3?'callback_blocked':sub.expires_at<=this.stamp()?'expired':'active',expires_at:sub?.expires_at||null,last_verified_at:sub?.verified_at||null,last_event_2xx_at:sub?.last_event_2xx_at||null,last_claim_at:lastClaim,principal:sub?.principal||null,auth_failures:sub?.auth_failures||0};
4346
- const priority_counts=Object.fromEntries(['normal','background'].map(priority=>[priority,Object.fromEntries(['queued','claimed'].map(status=>[status,this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority=? AND status=? AND (status<>'queued' OR ${live(this.nowMs())})`).get(priority,status).n]))]));
4367
+ const priority_counts=Object.fromEntries(['normal','background'].map(priority=>[priority,Object.fromEntries(['queued','claimed'].map(status=>[status,this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority=? AND status=? AND (status<>'queued' OR (${live(this.nowMs())} AND ${noPrClaimBlock('assignments')}))`).get(priority,status).n]))]));
4347
4368
  const throttle=this.rollingUsage(limits);
4348
4369
  const budget={window:'rolling_24h',calls_used:throttle.tool_calls_last_24h,calls_cap:throttle.max_tool_calls_per_24h,
4349
4370
  bytes_used:throttle.response_bytes_last_24h,bytes_cap:throttle.max_response_bytes_per_24h};