@tnunamak/dalan 0.9.5 → 0.9.7

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.7
8
+
9
+ - Read a larger pinned input set as one verified bundle over several replies. Each reply requires the current claim.
10
+ - Keep blocked pull requests out of queue forecasts and prevent old availability notices from waking workers for them.
11
+ - Ignore credential-path hints on full-repository build markers and keep those files out of the worker workspace.
12
+
13
+ ## 0.9.6
14
+
15
+ - 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.
16
+ - See how many jobs the bridge is offering, why it cannot offer more, and when a claim expires. Reading active work can renew its lease.
17
+ - Small pinned review inputs arrive together from the bridge instead of requiring individual GitHub reads. Worker history breaks down unsuccessful runs by recorded reason.
18
+
7
19
  ## 0.9.5
8
20
 
9
21
  - Small source edits run the checks that depend on the edited files. Unclear dependencies keep more checks in the run. Release qualification still runs the full suite.
@@ -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,31 @@ 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. Dalan tells the caller when that job can start, offers the worker exactly the work it can claim, and delivers pinned inputs through the same live claim. 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
+ | Each worker gets its own capacity reading. Base a configured ceiling on observed simultaneous claims and genuine provider limits. Use eligible ready work and usable lanes after reservations and holds to compute the one `next_action` on list, claim, progress and finish. | D2 admission, D12 breaks, D14 session length, D17 worker state | Four usable lanes and four ready jobs offer four. Four lanes and one ready job offer one. A hold or reservation reduces the offer with its reason. Recorded claim and session evidence make it possible to verify and revise the ceiling. Silence alone does not establish a provider limit. |
141
+ | Activity on the live claim refreshes its idle lease within the worker's configured limit. Publish the effective duration and deadline. Where a negotiated protocol uses explicit renewal, use its renewal command. | D2 admission, D7 progress, D11 recovery | The current holder's activity moves the deadline. Earlier epochs, expired claims and foreign connections cannot renew it. A queue listing or other work cannot extend the lease. |
142
+ | 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. |
143
+ | 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. |
144
+ | 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. |
145
+ | 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. |
146
+
147
+ 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.
148
+
149
+ 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.
150
+
133
151
  ## 7. Worker capability (full native ability)
134
152
 
135
153
  ### 7.1 Inputs
@@ -152,7 +170,7 @@ Authority to push is a **standing grant** on the relationship (the C2 #33 author
152
170
 
153
171
  ### 7.4 What a worker may receive
154
172
 
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.
173
+ 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
174
 
157
175
  ## 8. What Dalan reports
158
176
 
@@ -223,6 +241,8 @@ Where the line is crossed today, and where each piece moves:
223
241
  | 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
242
  | 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
243
 
244
+ 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).
245
+
226
246
  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
247
 
228
248
  ## 13. Consumers and the product-neutrality check
@@ -389,7 +409,7 @@ The B7 walks of 2026-11-28 showed where a delegated build still differs from a l
389
409
 
390
410
  | # | Difference | Kind | Caller's part |
391
411
  |---|---|---|---|
392
- | P1 | A build names every file it reads or changes on its `[dot-build]` line, at most `BUILD_MAX_FILES` (`src/acp-bridge.mjs#BUILD_MAX_FILES`). A brief that mentions a file outside that list is refused with `undeclared instruction path` and the corrected list (`src/work-order.mjs#undeclared_path`). A local subagent needs no declared paths. | Stays by design: the declared list bounds what a remote worker reads and changes, which section 7 relies on. | A good caller acts on the refusal: it resubmits once with the corrected list it was given. Repeated refusals are a caller failure, not a route failure. |
412
+ | P1 | A native `[dot-build]` shares the authorized repository at the pushed revision. | Known credential files and excluded paths are withheld mechanically. | The worker can edit or create repository files without an enumerated path list. |
393
413
  | P2 | A listed file that does not exist at the caller's HEAD is a new file the worker creates (`src/acp-bridge.mjs#buildAssignment`, `output_paths`). Before this, such a build was refused. | Gap, closed by the new-file change. | None. |
394
414
  | P3 | Builds run only for repository owners on the operator's list (`src/acp-bridge.mjs#buildIneligible`). An unset list refuses every build. | Stays by design (operator authority); a setup without the list must say so when the adapter starts. | None; an operator setting. |
395
415
  | P4 | A caller's job was refused when backlog that nobody waited on filled the queue cap (`src/acp-bridge.mjs#bridgeRefusal`). | Gap: a waiting caller must be admitted and claimed ahead of backlog. | None. |
@@ -54,7 +54,9 @@ Start a scoped review with `[dalan-read] OWNER/REPO@FULL_SHA path/to/file anothe
54
54
 
55
55
  Builds never publish a branch for you. A refusal tells you whether to commit tracked edits or, if you are authorized to publish the revision, gives the exact ref to push before delegating again. The worker cannot open a file just because the brief names a path on your computer; paste only the text you are authorized to share.
56
56
 
57
- A `delegate_task` to the worker provider whose task starts with `[dot-build] <path> ...` (after an optional `[dot-decision:ID]` line; T3's role preamble is removed first) is a build. The adapter submits it with `execution_scope: "implementation"`, `scope_paths` set to the listed paths that exist at the requester's HEAD, `output_paths` set to the listed paths that do not (new files the worker creates), and meta `task_kind: "build"`, using the requester's HEAD. Set `DALAN_ACP_BUILD_EXECUTION=host` (legacy `DOT_ACP_BUILD_EXECUTION`) where the bridge runs host checks (`DALAN_HOST_CHECKS=1`): the bridge then runs the repository's named checks on the build, and runs the default check itself before finish when the worker did not. A host build's scope is the whole repository with sensitive paths excluded at submit (host checks need a repository-wide read), the same scope the fleet's own host builds use; the `[dot-build]` list still names the files the change is about. Unset, a build gets the worker profile's default execution, which may leave it unchecked. A build is refused unless `DALAN_ACP_BUILD_OWNERS` (or the legacy `DOT_ACP_BUILD_OWNERS`) is set to a comma-separated list of authorized repository owners. An empty, missing or malformed list fails closed. `DALAN_ACP_REPO_CONFIG` (or the legacy `DOT_ACP_REPO_CONFIG`) can select the local repository policy file; otherwise the adapter reads the Dalan producer configuration, with legacy path fallback. That file must provide valid `repo_selection.exclude` and `deny_path_terms` arrays; missing or malformed policy also fails closed. A brief must name no path outside its list, and at most five files may be named. Optional: `DALAN_ACP_PROSE_CHECK_OWNERS` lists the owners whose added prose is checked by an external prose linter. `DALAN_ACP_PROSE_CHECK` names its executable, which the adapter runs as `COMMAND check --stdin --kind doc --json` with the added lines on stdin; when the owner list is unset or empty, no prose check runs; an enabled check without an executable reports an error; a malformed non-empty list returns an error. The result includes the base, check results, patch preview, fetch command and verdict commands. `dalan get`, `artifact`, `accept` and `reject` work on adapter rows: with no CLI receipt, the CLI derives the owner token from `~/.config/dalan/acp-secret`.
57
+ Start a build brief with `[dot-build]`, after the optional route decision token. The adapter pins the requester's clean, pushed GitHub commit and shares the whole authorized repository. Older briefs can keep file or directory hints on the marker. The worker can edit existing files and add new ones anywhere in the shared repository. The bridge withholds known secret files, symlinks and files matching the operator's `deny_path_terms`. Keep secrets out of the brief.
58
+
59
+ The repository owner allowlist and exclusions still apply. The operator configures `DALAN_ACP_BUILD_OWNERS` and the producer file selected by `DALAN_ACP_REPO_CONFIG`, with legacy variable support. `DALAN_ACP_BUILD_EXECUTION=host` requests the bridge's existing approved host checks. Otherwise the worker uses its configured execution mode. Publishing a draft requires the existing publication permission. Optional: `DALAN_ACP_PROSE_CHECK_OWNERS` lists the owners whose added prose is checked by an external prose linter. `DALAN_ACP_PROSE_CHECK` names its executable, which the adapter runs as `COMMAND check --stdin --kind doc --json` with the added lines on stdin; when the owner list is unset or empty, no prose check runs; an enabled check without an executable reports an error; a malformed non-empty list returns an error. The result includes the base, check results, patch preview, fetch command and verdict commands. `dalan get`, `artifact`, `accept` and `reject` work on adapter rows: with no CLI receipt, the CLI derives the owner token from `~/.config/dalan/acp-secret`.
58
60
 
59
61
  ## Consumers are assigned by code
60
62
 
package/docs/usage.md CHANGED
@@ -309,7 +309,7 @@ The bridge logs every refused submit as `submit_rejected` (request ID, reason, s
309
309
  - Implementation scope: `apply_patch` may create the listed files in addition to the `scope_paths` files. Once created, a file is readable and editable in the same job.
310
310
  - Read-only scope: `apply_patch` is allowed only for patches whose files are all in `output_paths`; once created, those outputs are readable and editable in the same job. A patch that touches any other file is refused as a whole with `read_only_assignment`, and nothing is applied. `run_check` stays closed to read-only jobs. `workspace_result` and the sealed patch artifact then carry only the `output_paths` files.
311
311
  - The field is part of the assignment, so it is covered by the request hash: a retry must send the same list. The bridge appends `Output paths (output_paths; may create):` and the list to the brief (a structured brief has the same section), so the default worker's reviewer knows the writes are allowed.
312
- - The `[dot-build]` line of a [T3 build](t3-integration.md#builds-through-the-t3-worker-provider) is unchanged: it lists existing files only, and a path missing at HEAD is refused by the bridge as `unknown scope path`.
312
+ - A [T3 build](t3-integration.md#builds-through-the-t3-worker-provider) starts with `[dot-build]`. It may create new files anywhere in the shared repository.
313
313
 
314
314
  Build that adds a file and a test:
315
315
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tnunamak/dalan",
3
- "version": "0.9.5",
3
+ "version": "0.9.7",
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';
@@ -482,7 +482,7 @@ async function prepareUnexplained({ cwd, ...request }, options, env) {
482
482
  context = textOnly ? { inputs: [], note: TEXT_ONLY_NOTE } : await repoInputs(cwd, options);
483
483
  if (named?.inputs && build) {
484
484
  const actual = context.inputs[0], requested = named.inputs[0];
485
- // A build's path checks below inspect the local HEAD. Do not classify paths against a different tree.
485
+ // The build patch must apply to the caller's own pushed checkout.
486
486
  if (!actual || context.packBase || context.note || actual.github_repo.toLowerCase() !== requested.github_repo.toLowerCase() ||
487
487
  actual.head_sha !== requested.head_sha)
488
488
  throw refuseNamed('unresolved_repo', 'The named build revision is not the eligible local checkout');
@@ -490,26 +490,22 @@ async function prepareUnexplained({ cwd, ...request }, options, env) {
490
490
  }
491
491
  }
492
492
  if (!build && !cwd && !context.inputs.length && !context.note) context = { ...context, note: TEXT_ONLY_NOTE };
493
- const newFiles = [];
494
493
  // A build patch must apply to the requester's own commit: no packed local diff and no text-only fallback.
495
- if (build && !buildScope(request.brief).length) throw new Refusal(BUILD_NEEDS_SCOPE);
496
494
  if (build && (!context.inputs.length || context.packBase || context.note))
497
495
  throw new Refusal(env.DOT_ACP_TEXT_ONLY === '1' ? BUILD_NEEDS_PUSHED : await buildCheckoutRefusal(cwd, options));
496
+ let denyPathTerms;
497
+ let brief=request.brief;
498
498
  if (build) {
499
- const why = buildIneligible(context.inputs[0].github_repo, buildScope(request.brief));
500
- if (why) throw new Refusal(why);
501
- // Each listed path is a file at HEAD or a new file; a directory would widen the scope past the file bound and path terms.
502
- // A path absent at HEAD is a new file the worker creates, as a local subagent would: it goes to output_paths.
503
- for (const p of buildScope(request.brief)) {
504
- const kind = await git(cwd, ['cat-file', '-t', `HEAD:${p}`]);
505
- if (kind.out === 'tree') throw new Refusal(`[dot-build] lists a directory (${p}); list files`);
506
- // Only a path git reports as absent from HEAD is a new file; any other git failure (timeout, bad object store) refuses.
507
- if (!kind.ok && !/does not exist in|exists on disk, but not in|Not a valid object name|invalid object name/i.test(kind.err)) throw new Refusal(`[dot-build] could not read ${p} at HEAD: ${kind.err.slice(0, 160)}`);
508
- if (!kind.ok) newFiles.push(p);
509
- }
499
+ const policy = buildRepositoryPolicy(context.inputs[0].github_repo, env);
500
+ if (policy.reason) throw new Refusal(policy.reason);
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');
510
506
  }
511
507
  // Identity is the requester's brief only; packed context and notes are presentation and never enter this hash.
512
- let assignment = { ...buildAssignment({ ...request, inputs: context.inputs, build, newFiles, repoScope: build && buildExecution(env) === 'host' }), 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 } : {}) };
513
509
  let packedPaths = new Set();
514
510
  if (context.packBase) ({ assignment, packedPaths } = await packRepoDiff(cwd, assignment, context.packBase, NO_REPO_NOTE));
515
511
  else if (context.untracked && !build) assignment.brief = `${UNTRACKED_NOTE}\n\n${assignment.brief}`;
@@ -534,13 +530,10 @@ async function prepareUnexplained({ cwd, ...request }, options, env) {
534
530
  // A brief whose first line is exactly BUILD_MARKER asks the worker for a patch: implementation scope (apply_patch, run_check)
535
531
  // on the requester's pushed HEAD, task_kind "build" (the delegation gate measures acceptance of these), and a result that
536
532
  // carries the patch evidence and the verdict commands. Any other brief keeps read-only scope.
537
- // The marker line names the repository paths the worker may read and change: `[dot-build] src/a.py tests/test_a.py`. Implementation
538
- // scope admits no sensitive file in scope (--exclude-sensitive is for read-only work), so a whole-repo scope fails on any
539
- // repository with a .env.example; an explicit list also keeps the worker's reads, and so its usage, small.
533
+ // Older build markers may include path hints. All builds share the pinned repository with credential paths withheld.
540
534
  export const BUILD_MARKER = '[dot-build]';
541
535
  const buildLine = /^\[dot-build\]((?:[ \t]+\S+)*)[ \t]*$/;
542
536
  export const isBuild = brief => typeof brief === 'string' && buildLine.test(brief.split('\n', 1)[0].trim());
543
- export const buildScope = brief => (buildLine.exec(brief.split('\n', 1)[0].trim())?.[1] ?? '').trim().split(/[ \t]+/).filter(Boolean);
544
537
  export const BUILD_NEEDS_PUSHED = 'a [dot-build] task needs a clean checkout whose HEAD is pushed to a GitHub origin; push first, or use dalan submit with an explicit base_sha';
545
538
  async function buildCheckoutRefusal(cwd, options) {
546
539
  if (!cwd || !(await git(cwd, ['rev-parse', '--is-inside-work-tree'])).ok) return BUILD_NEEDS_PUSHED;
@@ -559,11 +552,9 @@ async function buildCheckoutRefusal(cwd, options) {
559
552
  const how = detached ? 'HEAD is detached, so if approved to publish, push it as a new branch first' : 'if approved to publish, push this branch first';
560
553
  return `a [dot-build] task needs the committed revision on origin; ${how}: git push origin ${commandArg}, then delegate again`;
561
554
  }
562
- export const BUILD_NEEDS_SCOPE = 'a [dot-build] line must name the files the worker may read and change, e.g. "[dot-build] src/a.py tests/test_a.py"';
563
555
  // Who may receive a build comes from the operator's owner allowlist because a parent can send a [dot-build] task without
564
556
  // the delegation gate's offer. The repo exclusion config and credential path terms add further restrictions.
565
557
  // The current and legacy environment variable names are supported; a missing owner list refuses every build.
566
- export const BUILD_MAX_FILES = 5;
567
558
  const glob = pattern => new RegExp(`^${pattern.toLowerCase().replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`);
568
559
  function configuredOwners(value) {
569
560
  if (typeof value !== 'string' || !value.trim()) return null;
@@ -571,18 +562,22 @@ function configuredOwners(value) {
571
562
  if (owners.some(owner => !/^[a-z0-9_.-]+$/.test(owner))) return null;
572
563
  return owners;
573
564
  }
574
- export function buildIneligible(repo, files, env = process.env) {
565
+ function buildRepositoryPolicy(repo, env) {
575
566
  const owners = configuredOwners(env.DALAN_ACP_BUILD_OWNERS || env.DOT_ACP_BUILD_OWNERS);
576
- if (!owners) return '[dot-build] refused: DALAN_ACP_BUILD_OWNERS or DOT_ACP_BUILD_OWNERS must list authorized repository owners';
567
+ if (!owners) return {reason:'[dot-build] refused: DALAN_ACP_BUILD_OWNERS or DOT_ACP_BUILD_OWNERS must list authorized repository owners'};
577
568
  const name = String(repo || '').toLowerCase();
578
- if (!owners.includes(name.split('/')[0])) return `[dot-build] refused: ${repo} is outside the configured owner allowlist`;
579
- if (files.length > BUILD_MAX_FILES) return `[dot-build] names ${files.length} paths; at most ${BUILD_MAX_FILES}`;
569
+ if (!owners.includes(name.split('/')[0])) return {reason:`[dot-build] refused: ${repo} is outside the configured owner allowlist`};
580
570
  let cfg;
581
571
  try { cfg = JSON.parse(fs.readFileSync(env.DALAN_ACP_REPO_CONFIG || env.DOT_ACP_REPO_CONFIG || defaultPath(os.homedir(),'.config/dot-bridge/producer.json'), 'utf8')); }
582
- catch { return '[dot-build] refused: the repo exclusion config is unreadable'; }
572
+ catch { return {reason:'[dot-build] refused: the repo exclusion config is unreadable'}; }
583
573
  const exclude = cfg?.repo_selection?.exclude, terms = cfg?.deny_path_terms;
584
- if (!Array.isArray(exclude) || !Array.isArray(terms) || ![...exclude, ...terms].every(x => typeof x === 'string' && x)) return '[dot-build] refused: the repo exclusion config is malformed';
585
- if (exclude.some(g => glob(g).test(name))) return `[dot-build] refused: ${repo} is excluded by the repo exclusion config`;
574
+ if (!Array.isArray(exclude) || !Array.isArray(terms) || ![...exclude, ...terms].every(x => typeof x === 'string' && x)) return {reason:'[dot-build] refused: the repo exclusion config is malformed'};
575
+ if (exclude.some(g => glob(g).test(name))) return {reason:`[dot-build] refused: ${repo} is excluded by the repo exclusion config`};
576
+ return {terms};
577
+ }
578
+ export function buildIneligible(repo, files, env = process.env) {
579
+ const {reason, terms} = buildRepositoryPolicy(repo, env);
580
+ if (reason) return reason;
586
581
  const hit = files.find(f => terms.some(t => f.toLowerCase().includes(t.toLowerCase())));
587
582
  if (hit) return `[dot-build] refused: ${hit} matches a credential path term`;
588
583
  return null;
@@ -600,15 +595,11 @@ export function buildExecution(env = process.env) {
600
595
  return value;
601
596
  }
602
597
 
603
- // repoScope: on host execution the bridge's checks run only on a whole-repository scope (src/host-execution-policy.mjs#hostCheckRefusal
604
- // refuses a narrow one), so a host build reads and changes the repository with sensitive paths excluded at submit, as the
605
- // fleet's own host builds do. The [dot-build] list still names the files the change is about and stays in the brief.
606
- export function buildAssignment({ requestId, brief, inputs, validUntil, build = false, newFiles = [], repoScope = false }) {
607
- const created = build ? newFiles : [];
598
+ export function buildAssignment({ requestId, brief, inputs, validUntil, build = false, denyPathTerms = [] }) {
608
599
  return {
609
600
  schema_version: 1, request_id: requestId, brief, inputs,
610
- ...(inputs.length ? { scope_paths: build && !repoScope ? buildScope(brief).filter(p => !created.includes(p)) : ['.'] } : {}),
611
- ...(inputs.length && created.length ? { output_paths: created } : {}),
601
+ ...(inputs.length ? { scope_paths: ['.'] } : {}),
602
+ ...(build ? { deny_path_terms: denyPathTerms } : {}),
612
603
  expected_output: build ? BUILD_OUTPUT : 'A complete answer as plain text. Put the result in the finish call.' +
613
604
  (inputs.length ? ' When asked to run checks, use your own permitted tools on the authorized files at the pinned commit. '+
614
605
  'Use a disposable checkout only if your repository grant permits it, or use the granted scoped file set. '+
package/src/server.mjs CHANGED
@@ -39,7 +39,7 @@ import { assertNoDeclaredConsumer, unprovenSource } from './consumers.mjs';
39
39
  import { preflightPR } from './pr-preflight.mjs';
40
40
  import { admitImplementation } from './check-readiness.mjs';
41
41
  import { parseExecution, parseRequiredCapabilities, admitHostExecution, admitAdapterCapabilities, ADAPTER_CAPABILITY_NAMES, withEvidence } from './execution.mjs';
42
- import { assignmentInput, loadCapacity } from './projects.mjs';
42
+ import { assignmentInput, loadCapacity, mirrorPath } from './projects.mjs';
43
43
  import { authConfig, assertPublicRouteAuth, isLoopbackBindHost, protectedResource, challenge, verifyBearer, needScope } from './auth.mjs';
44
44
  import { beginMcpOutcome, recordMcpResponse, pathShape, uaToken } from './mcp-outcome.mjs';
45
45
  import { lifecycleMetrics, retainLifecycle, controlScopeText } from './lifecycle.mjs';
@@ -179,6 +179,56 @@ if(store.hasAssignment(absentId)) throw new Error('absent gate id collision');
179
179
  const log = createRequestLog(path.join(stateDir, 'requests.jsonl'));
180
180
  const guardArtifactDownload = createArtifactDownloadGuard({log});
181
181
  const scopedSourceChunk=18*1024;
182
+ function encodePinnedSource(mirror,assignment,requestId,maxBytes=SCOPED_SOURCE_MAX_BYTES,pin) {
183
+ const {manifest,blobs,refusedPaths}=pinnedScopedSource(mirror,assignment,maxBytes,pin);
184
+ if(!manifest.files.length) throw new Error('no approved scoped input files');
185
+ const files=manifest.files.map(file=>{
186
+ const bytes=blobs.get(file.path);
187
+ guardArtifactDownload({bytes,sha256:file.sha256,id:'scoped-input-file',requestId});
188
+ return {...file,data_base64:bytes.toString('base64')};
189
+ });
190
+ const bytes=Buffer.from(JSON.stringify({...manifest,files}));
191
+ if(bytes.length>maxBytes) throw new Error('scoped input exceeds the download limit; use a smaller scope');
192
+ const sha256=createHash('sha256').update(bytes).digest('hex');
193
+ guardArtifactDownload({bytes,sha256,id:'scoped-input',requestId});
194
+ return {manifest,refusedPaths,bytes,sha256};
195
+ }
196
+
197
+ // A normal workspace reader can get the already-verified inputs in one reply. The explicit registry
198
+ // artifact still has its own narrower grant and delivery receipts. This never fetches a missing mirror.
199
+ function pinnedSourceReply(row,principal,connectionId,{claim_id:claimId,input_offset:offset=0,input_sha256:expected}) {
200
+ const {worker,subject}=principal;
201
+ const {assignment,request_id:requestId}=row;
202
+ if(!claimId||!workspaceEnabled||row.status!=='claimed'||row.cancelled_at||assignment.execution_scope!=='read-only'||
203
+ assignment.paged_read_scope||!assignment.scope_paths?.length||assignment.scope_paths.includes('.')) return {};
204
+ const grant=store.liveHeldClaim(requestId,claimId,subject,worker);
205
+ if(!grant) return {};
206
+ if(offset%scopedSourceChunk!==0||(offset!==0&&!expected)) throw new Error('invalid pinned input offset');
207
+ try {
208
+ if(oauth) needScope(principal,scopeFor('read_file'));
209
+ if(!workerWorkspaceAllowed(worker,requestId)) return {};
210
+ assertRepoAllowed(worker,assignment);
211
+ store.assertMutationConnection(requestId,grant,connectionId);
212
+ const input=assignmentInput(assignment);
213
+ if(input.input_patch) return {};
214
+ const mirror=mirrorPath(input.github_repo,{worker});
215
+ const {manifest,refusedPaths,bytes,sha256}=encodePinnedSource(mirror,assignment,requestId,SCOPED_SOURCE_MAX_BYTES,input.head_sha??input.base_sha);
216
+ if(expected!==undefined&&expected!==sha256) return {pinned_input_error:'bundle_changed'};
217
+ if(offset>=bytes.length) return {pinned_input_error:'offset_out_of_range'};
218
+ const end=Math.min(offset+scopedSourceChunk,bytes.length);
219
+ const bundle={sha256,pin:manifest.pin,encoding:'base64-json',size:bytes.length,offset,
220
+ next_offset:end===bytes.length?null:end,data_base64:bytes.subarray(offset,end).toString('base64')};
221
+ if(JSON.stringify(redactOutput(bundle))!==JSON.stringify(bundle)) return {};
222
+ store.recordScopedInputChunk(requestId,{
223
+ epoch:grant.epoch,worker,sha256,chunk:offset/scopedSourceChunk,chunkCount:Math.ceil(bytes.length/scopedSourceChunk),
224
+ metadata:{...manifest,size:bytes.length,...(refusedPaths.length?{refused_paths:refusedPaths}:{})},
225
+ });
226
+ return {pinned_input_bundle:bundle};
227
+ } catch {
228
+ // An unavailable snapshot must not discard a valid claim or deny ordinary workspace reads.
229
+ return {};
230
+ }
231
+ }
182
232
  const phaseTrace = createPhaseTrace({ log });
183
233
  logShutdownSignals(log);
184
234
  // Registry definitions are discovered through list_tools. The native tools/list stays fixed.
@@ -239,35 +289,28 @@ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
239
289
  return [requestId,claim.claim_id,claim.epoch,subject,connection];
240
290
  } catch(error) { throw assignmentRegistryRefusal(error); }
241
291
  },
242
- run({args,context:{worker,subject},grantScope,recordOnRead}) {
292
+ run({args,context:{worker,subject,builtin,connection_id},grantScope,recordOnRead}) {
243
293
  const requestId=id(args.request_id),claimId=id(args.claim_id,'claim_id');
244
294
  const offset=args.offset??0;
245
295
  if(offset%scopedSourceChunk!==0||(offset!==0&&!args.sha256)) throw new RegistryError('invalid_arguments','invalid scoped input offset');
246
296
  try {
247
297
  const {a,claim,input,mirror}=workspace.context(requestId,claimId,subject,false,worker);
248
298
  if(input.head_sha&&input.head_sha!==input.base_sha) throw new Error('scoped input requires the reviewed revision to match the base');
249
- const {manifest,blobs,refusedPaths}=pinnedScopedSource(mirror,a.assignment);
299
+ const {manifest,refusedPaths,bytes,sha256:hash}=encodePinnedSource(mirror,a.assignment,requestId);
250
300
  if(grantScope && manifest.files.some(file=>!a.assignment.scope_paths.includes(file.path)))
251
301
  throw new Error('assignment grant requires exact scoped files');
252
- if(!manifest.files.length) throw new Error('no approved scoped input files');
253
- const files=manifest.files.map(file=>{
254
- const bytes=blobs.get(file.path);
255
- guardArtifactDownload({bytes,sha256:file.sha256,id:'scoped-input-file',requestId});
256
- return {...file,data_base64:bytes.toString('base64')};
257
- });
258
- const bytes=Buffer.from(JSON.stringify({...manifest,files}));
259
- if(bytes.length>SCOPED_SOURCE_MAX_BYTES) throw new Error('scoped input exceeds the download limit; use a smaller scope');
260
- const hash=createHash('sha256').update(bytes).digest('hex');
261
- guardArtifactDownload({bytes,sha256:hash,id:'scoped-input',requestId});
262
302
  if(args.sha256!==undefined&&args.sha256!==hash) throw new Error('scoped input changed');
263
303
  if(offset>=bytes.length) throw new Error('invalid scoped input offset');
264
304
  const end=Math.min(offset+scopedSourceChunk,bytes.length);
265
305
  const result={sha256:hash,size:bytes.length,offset,next_offset:end===bytes.length?null:end,data_base64:bytes.subarray(offset,end).toString('base64')};
266
306
  if(JSON.stringify(redactOutput(result))!==JSON.stringify(result)) throw new Error('scoped input encoding refused');
267
307
  const metadata={...manifest,size:bytes.length,...(refusedPaths.length?{refused_paths:refusedPaths}:{})};
268
- recordOnRead(()=>store.recordScopedInputChunk(requestId,{
269
- epoch:claim.epoch,worker,sha256:hash,metadata,chunk:offset/scopedSourceChunk,
270
- chunkCount:Math.ceil(bytes.length/scopedSourceChunk),
308
+ recordOnRead(()=>store.inTransaction(()=>{
309
+ store.touchClaim(requestId,claimId,subject,worker,builtin?(connection_id??''):null);
310
+ store.recordScopedInputChunk(requestId,{
311
+ epoch:claim.epoch,worker,sha256:hash,metadata,chunk:offset/scopedSourceChunk,
312
+ chunkCount:Math.ceil(bytes.length/scopedSourceChunk),
313
+ });
271
314
  }));
272
315
  return result;
273
316
  } catch(error) { throw assignmentRegistryRefusal(error); }
@@ -548,8 +591,10 @@ if(batchClaimProfile) {
548
591
  // No top-level oneOf: several MCP hosts reject combinators at the schema root. validate() enforces exactly one of request_id or next.
549
592
  // The stable catalog stays frozen: claim_id on get (heartbeat for that exact claim) is served only in this profile.
550
593
  const get=tools.find(item=>item.name==='get');
551
- get.description='Read assignment, available_checks, cancellation, progress, report and delivery facts; optional claim_id scopes heartbeat guidance.';
552
- get.inputSchema.properties.claim_id=string;
594
+ 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.';
595
+ Object.assign(get.inputSchema.properties,{
596
+ claim_id:string,input_offset:{type:'integer',minimum:0,maximum:SCOPED_SOURCE_MAX_BYTES},input_sha256:hashField,
597
+ });
553
598
  }
554
599
  // Opt-in compatibility catalog only; grant and lease enforcement are unchanged.
555
600
  if(catalogProfile==='legacy-v46') {
@@ -927,11 +972,11 @@ function batchCapacityReply(name,reply,principal,callId,onOffer) {
927
972
  ready_queued>0&&hintFree===0?['hint_full','Lanes are free but the claim hint is full; claim again when the hint allows more.']:
928
973
  ['no_ready_work','No ready queued work; call list_pending again later.'];
929
974
  const {next_action:previousAction,free_lanes:previousFree,...rest}=reply;
930
- const response={next_action,free_lanes,ready_queued,...rest};
975
+ const response={next_action,free_lanes,claimable_lanes:available,ready_queued,recommended_claims:reason==='ready'?next:0,dispatch_reason:reason,...rest};
931
976
  if(recordListing) {
932
977
  const recommended=reason==='ready'?next:0;
933
978
  const readyIds=ready.slice(0,recommended).map(item=>item.request_id);
934
- logPendingReply(response,principal,callId,{ready_queued,dispatch_reason:reason,recommended_claims:recommended,ready_head_ids:readyIds});
979
+ logPendingReply(response,principal,callId,{ready_queued,claimable_lanes:available,dispatch_reason:reason,recommended_claims:recommended,ready_head_ids:readyIds});
935
980
  if(readyIds.length) onOffer?.({worker,subject,callId,readyIds});
936
981
  }
937
982
  return response;
@@ -1405,7 +1450,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1405
1450
  const grant=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
1406
1451
  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});
1407
1452
  const {free_lanes,queued,reserved_request_id}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1408
- return withAvailableChecks({...claimed,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);
1453
+ 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);
1409
1454
  }
1410
1455
  case 'renew_claim': {
1411
1456
  if(!strictJob) throw new Error('renew_claim requires a protocol job');
@@ -1416,7 +1461,8 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1416
1461
  if(!store.hasAssignment(requestId)) return {kind:'message',message:store.getMessage(requestId,worker)};
1417
1462
  store.markNotesSeenByHolder(requestId,subject,worker,connectionId);
1418
1463
  const row=store.get(requestId);
1419
- return {...publicWorkerGet(withAvailableChecks(row,true,worker,subject)),...store.workerGetHeartbeat(row,worker,subject,a.claim_id),guidance:store.guidanceFor(worker)};
1464
+ return {...publicWorkerGet(withAvailableChecks(row,true,worker,subject)),...store.workerGetHeartbeat(row,worker,subject,a.claim_id),
1465
+ ...pinnedSourceReply(row,principal,connectionId,a),guidance:store.guidanceFor(worker)};
1420
1466
  }
1421
1467
  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};}
1422
1468
  case 'progress': {
@@ -1765,7 +1811,9 @@ const adminServer=http.createServer(async(req,res)=>{
1765
1811
  },
1766
1812
  preflight:p=>preflightPR(p),
1767
1813
  // Advisory only, like Store.submit: a supersede target leaves the queued count unchanged. Store.submit rechecks it in its transaction.
1768
- 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}),
1814
+ state:r=>({paused:store.paused(),pause_reason:store.db.prepare('SELECT reason FROM operator_state WHERE id=1').get().reason,
1815
+ worker_break:store.holdingBreak(r.target),
1816
+ ...store.admissionQueueCounts(r.target,body.background===true?'background':'normal',body.caller_waiting===true,supersedes?.target_id??null)}),
1769
1817
  kind:(r,p)=>r.meta?.task_kind??(r.review?'review':p.execution_scope??'unknown'),
1770
1818
  defaultValidity:(kind,r)=>store.defaultValidUntil(r.target,kind),
1771
1819
  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;},
package/src/store.mjs CHANGED
@@ -1426,6 +1426,7 @@ export class Store {
1426
1426
  const aheadRows=this.db.prepare(`SELECT request_id,created_at,
1427
1427
  EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked FROM assignments
1428
1428
  WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND request_id IS NOT ? AND ${live(now)}
1429
+ AND ${noPrClaimBlock('assignments')}
1429
1430
  AND NOT EXISTS(SELECT 1 FROM facade_withdrawals f WHERE f.request_id=assignments.request_id)
1430
1431
  AND (${LIST_ORDER}) < (?, ?, ?, CAST(? AS INTEGER))`)
1431
1432
  .all(worker,first,second,rankPriority,rankSkipped,rankCreated,rankRow);
@@ -1519,6 +1520,7 @@ export class Store {
1519
1520
  a.created_at
1520
1521
  )>=? AND a.target_worker=? AND ${queueKindSql}=? AND a.status IN ('finished','cancelled')`).all(since,worker,kind);
1521
1522
  const outcomes={landed:0,check_passed:0,checks_failed:0,refused_by_provider:0,unable_to_run:0,owner_cancelled:0,finished_unchecked:0};
1523
+ const unable_to_run_reasons={};
1522
1524
  let accepted=0,check_passed=0;
1523
1525
  const durations=[];
1524
1526
  // Check events from an earlier claim of a re-queued job describe a run that did not produce the result, so only the
@@ -1537,7 +1539,11 @@ export class Store {
1537
1539
  else {
1538
1540
  const {failure_type}=this.failureFields(row.request_id);
1539
1541
  if(failure_type==='owner_cancelled') outcomes.owner_cancelled++;
1540
- else outcomes.unable_to_run++;
1542
+ else {
1543
+ outcomes.unable_to_run++;
1544
+ const reason=failure_type??'unknown';
1545
+ unable_to_run_reasons[reason]=(unable_to_run_reasons[reason]??0)+1;
1546
+ }
1541
1547
  }
1542
1548
  }
1543
1549
  // The provider session is opaque. The final claim and its report delimit an observed span on this job.
@@ -1545,7 +1551,7 @@ export class Store {
1545
1551
  const min_samples=QUEUE_WINDOW.minSamples;
1546
1552
  const claim_to_report={source:'final_claim_to_report',n:durations.length,min_samples,
1547
1553
  p50_ms:durations.length<min_samples?null:durations[Math.ceil(durations.length/2)-1]};
1548
- return {worker,kind,window_days:days,n:rows.length,accepted,check_passed,outcomes,claim_to_report,session_length:this.sessionLength(worker,days)};
1554
+ return {worker,kind,window_days:days,n:rows.length,accepted,check_passed,outcomes,unable_to_run_reasons,claim_to_report,session_length:this.sessionLength(worker,days)};
1549
1555
  }
1550
1556
  queueWaitsMs(worker,kind,days=7) { return this.queueWaitEvidence(worker,kind,days).waits_ms; }
1551
1557
  defaultValidUntil(worker,kind,days=7) {
@@ -1811,10 +1817,10 @@ export class Store {
1811
1817
  if(!Number.isSafeInteger(maxQueued)||maxQueued<1) throw new Error('invalid max_queued');
1812
1818
  // Waiting callers count only waiting peers of the same priority; backlog cannot refuse them.
1813
1819
  // Other callers keep the same-priority cap.
1814
- 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;
1820
+ const queued=this.admissionQueueCounts(targetWorker??'dot',priority,callerWaiting,supersededId).queued_same_priority;
1815
1821
  if(queued>=maxQueued) throw new Error(`worker queue is full (${queued} queued, in-flight cap ${maxQueued})`);
1816
1822
  }
1817
- 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');
1823
+ 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');
1818
1824
  // The target is a column, not payload: an omitted worker means 'dot'.
1819
1825
  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);
1820
1826
  if(typeof parentGeneration==='string')this.db.prepare('UPDATE assignments SET parent_generation=? WHERE request_id=?').run(parentGeneration,id);
@@ -2095,6 +2101,12 @@ export class Store {
2095
2101
  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);
2096
2102
  return eventId;
2097
2103
  }
2104
+ admissionQueueCounts(worker,priority,callerWaiting,excludeId=null) {
2105
+ return this.db.prepare(`SELECT count(*) queued,
2106
+ count(*) FILTER (WHERE priority=? AND (?=0 OR caller_waiting=1)) queued_same_priority
2107
+ FROM assignments WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND ${live(this.nowMs())}
2108
+ AND ${noPrClaimBlock('assignments')}`).get(priority,callerWaiting?1:0,worker,excludeId);
2109
+ }
2098
2110
  // Queued assignments in list_pending order (waiting normal before other normal, then background and oldest) with queued_at (see queuedAt).
2099
2111
  queuedRows() {
2100
2112
  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();
@@ -2440,8 +2452,9 @@ export class Store {
2440
2452
  try { this.assertMutationConnection(id,claim,connectionId); }
2441
2453
  catch(error) { if(error.destination?.error==='connection_not_live')return false; throw error; }
2442
2454
  this.markNotesSeen(id,subject,worker);
2443
- // The holder reading its handed job is the first sign of life: end the idle phase of a handoff claim. Other claims are not refreshed by a read.
2444
- if(this.handoffWorkLeaseMs(claim)!==null&&!this.leaseExpired(claim)) this.refreshClaimActivity(id,claim.claim_id);
2455
+ // The initial holder's get proves activity on this claim. After reclaim, a request ID alone cannot
2456
+ // distinguish a delayed get from the previous epoch. Those reads need the current claim ID.
2457
+ if((claim.epoch===1||this.handoffWorkLeaseMs(claim)!==null)&&!this.leaseExpired(claim)) this.refreshClaimActivity(id,claim.claim_id);
2445
2458
  return true;
2446
2459
  }); }
2447
2460
  // Unfenced: for callers that already proved the holder inside their own claim transaction (exact retry, resume). `get` uses markNotesSeenByHolder.
@@ -4039,6 +4052,14 @@ export class Store {
4039
4052
  if(row.kind==='event'&&row.request_id&&this.isProtocolJob(row.request_id)&&!this.protocolListingLive(row.request_id)) {
4040
4053
  this.db.prepare("UPDATE notifications SET state='suppressed',last_error='protocol retention expired' WHERE id=?").run(id);return null;
4041
4054
  }
4055
+ if(row.kind==='event'&&(row.wake_kind==='submit'||row.wake_kind==='rewake')) {
4056
+ const blocked=this.db.prepare(`SELECT 1 FROM pr_claim_blocks
4057
+ WHERE request_id IN (?1,CASE WHEN json_valid(?2) THEN json_extract(?2,'$.data.request_id') END)`).get(row.request_id,row.body);
4058
+ if(blocked) {
4059
+ this.db.prepare("UPDATE notifications SET state='suppressed',last_error='queued PR is blocked' WHERE id=?").run(id);
4060
+ return null;
4061
+ }
4062
+ }
4042
4063
  // A re-wake no longer valid is suppressed unsent: it is no last wake, so the next tick recomputes the head. A still
4043
4064
  // valid retry keeps its id and body.
4044
4065
  const stale=row.wake_kind==='rewake'&&this.rewakeStale(row);
@@ -4322,7 +4343,7 @@ export class Store {
4322
4343
  // Queued counts are live: rows past valid_until are reported as queued_expired, and protocol jobs past retention are
4323
4344
  // left out, never counted as queue, cap or throttle room.
4324
4345
  const queuedExpired=this.queuedExpired(), queuedExpiredRequeued=this.queuedExpiredRequeued();
4325
- 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);
4346
+ 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);
4326
4347
  const sub=this.db.prepare("SELECT * FROM subscriptions WHERE worker='dot' ORDER BY verified_at DESC LIMIT 1").get();
4327
4348
  const active=this.activeSubscriptions().filter(sub=>sub.worker==='dot');
4328
4349
  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;
@@ -4337,7 +4358,7 @@ export class Store {
4337
4358
  SELECT worker,n,created_at oldest,request_id FROM live_queue WHERE rank=1`).all().map(r=>[r.worker,r]));
4338
4359
  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();
4339
4360
  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};
4340
- 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]))]));
4361
+ 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]))]));
4341
4362
  const throttle=this.rollingUsage(limits);
4342
4363
  const budget={window:'rolling_24h',calls_used:throttle.tool_calls_last_24h,calls_cap:throttle.max_tool_calls_per_24h,
4343
4364
  bytes_used:throttle.response_bytes_last_24h,bytes_cap:throttle.max_response_bytes_per_24h};
@@ -404,6 +404,10 @@ const ownerSensitiveRepoPath=(file,policyPaths)=>policyPaths.some(x=>file===x||f
404
404
  export function isSensitiveRepoPath(file,policyPaths=[]) {
405
405
  return hardSensitiveRepoPath(file)||softName(file)||ownerSensitiveRepoPath(file,policyPaths);
406
406
  }
407
+ export function matchesCredentialPathTerm(file,terms=[]) {
408
+ const name=file.normalize('NFC').toLowerCase();
409
+ return terms.some(term=>name.includes(term.normalize('NFC').toLowerCase()));
410
+ }
407
411
  // Soft ancestors describe a code topic, not a credential store. Keep the
408
412
  // established source exception, but never for a hard or owner-denied ancestor.
409
413
  export function withheldRepoPath(file,policyPaths=[],{directory=false}={}) {
@@ -444,6 +448,11 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
444
448
  let p;
445
449
  try { p=loadPolicy(); } catch(error) { throw infrastructureError(error.message); }
446
450
  let rendered=renderAssignment(assignment);
451
+ const denyTerms=rendered.deny_path_terms===undefined?[]:rendered.deny_path_terms;
452
+ if(Object.hasOwn(rendered,'deny_path_terms')&&(rendered.execution_scope!=='implementation'||
453
+ !Array.isArray(denyTerms)||denyTerms.length>128||denyTerms.some(term=>typeof term!=='string'||!term.trim()||term.length>128||/[\x00-\x1f\x7f]/.test(term)))) {
454
+ throw new Error('invalid deny_path_terms: expected credential path terms for an implementation assignment');
455
+ }
447
456
  const briefBytes=cap(rendered.brief,submissionLimits.brief,'brief');
448
457
  const outputBytes=cap(rendered.expected_output,submissionLimits.instructions,'expected output');
449
458
  if(rendered.scope_text!==undefined&&typeof rendered.scope_text!=='string') throw new Error('invalid scope_text');
@@ -493,6 +502,7 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
493
502
  function inspectPath(file) {
494
503
  // A router group cannot hide a sensitive name: `(x).env` is also checked as `.env`.
495
504
  if(hardSensitive(file)) throw sensitivePathError(`hard sensitive path exclusion: ${file}`,file);
505
+ if(matchesCredentialPathTerm(file,denyTerms)) throw sensitivePathError(`sensitive scope path: ${file}; configured credential path term`,file);
496
506
  const parts=outputPathKeys[3](file).split('/');
497
507
  if(priorExcluded.size&&parts.some((_,i)=>priorExcluded.has(parts.slice(0,i+1).join('/'))))
498
508
  throw sensitivePathError(`sensitive scope path: ${file}; the prior assignment excluded this path`,file);
@@ -719,6 +729,9 @@ export function validateSubmission(assignment,{sensitiveScopeOverride=null,scanI
719
729
  // Named paths and patch paths still refuse above and below.
720
730
  for(const file of scan.files.filter(f=>within(f,scope)&&!scope.includes(f))) {
721
731
  if(priorOmittedPaths.has(file)) continue;
732
+ if(withholdImplementation&&matchesCredentialPathTerm(file,denyTerms)) {
733
+ dropped.push({path:file,reason:'refused: configured credential path term'});continue;
734
+ }
722
735
  if(withholdImplementation&&withheldRepoPath(file,p.sensitive_paths)) {
723
736
  dropped.push({path:file,reason:isSensitiveRepoPath(file,p.sensitive_paths)?sensitiveReason(file):'refused: sensitive ancestor directory'});continue;
724
737
  }
package/src/workspace.mjs CHANGED
@@ -8,7 +8,7 @@ import { spawnSync, spawn } from 'node:child_process';
8
8
  import { createHash, randomUUID } from 'node:crypto';
9
9
  import { checkOutcome } from './lifecycle.mjs';
10
10
  import { checkResponse } from './check-response.mjs';
11
- import { secretContent, isSensitiveRepoPath, withheldRepoPath, isSourceExemptionPath, sensitivePolicyPaths } from './submission-policy.mjs';
11
+ import { secretContent, isSensitiveRepoPath, matchesCredentialPathTerm, withheldRepoPath, isSourceExemptionPath, sensitivePolicyPaths } from './submission-policy.mjs';
12
12
  import { argvTestFiles, assignmentInput, assignmentNamedCheck, isNamedCheck, prepareGithubRepo, detectCheck, detectCheckWithOrigin, availableChecks, workspaceCheck, mirrorPath, withCheckMetadata, checkSpecsAt, checkSummary } from './projects.mjs';
13
13
  import { hostBackend, hostReadiness, capabilityNotAvailable, TRUST, withEvidence } from './execution.mjs';
14
14
  import { redactSecrets, redactOutput, privateKeyHeader } from './redaction.mjs';
@@ -138,9 +138,10 @@ function scopeOf(assignment) {
138
138
  }
139
139
  const paths=!scope.length||scope.includes('.')?null:scope;
140
140
  const outputs=outputsOf(assignment);
141
- const sensitive=assignment.execution_scope==='implementation'&&excluded.size?sensitivePolicyPaths():null;
141
+ const denyTerms=assignment.deny_path_terms;
142
+ const sensitive=assignment.execution_scope==='implementation'&&(excluded.size||denyTerms)?sensitivePolicyPaths():null;
142
143
  if(sensitive?.error) throw new Error('sensitive_policy_unavailable');
143
- return paths||excluded.size||outputs.size?{paths,excluded,outputs,sensitive}:null;
144
+ return paths||excluded.size||outputs.size||denyTerms?{paths,excluded,outputs,sensitive,denyTerms}:null;
144
145
  }
145
146
  // output_paths: new files the job may create. They are readable and writable once they exist, and are the only writable
146
147
  // files of a read-only assignment. Submit proved they are absent at the pinned revision and not sensitive.
@@ -153,7 +154,7 @@ function existsAtHead(dir,file) {
153
154
  if(r.error||r.status!==0) throw new Error(`git ls-tree failed: ${(r.stderr||r.error?.message||'').slice(0,200)}`);
154
155
  return r.stdout.length>0;
155
156
  }
156
- const inScope=(p,scope)=>!scope||(scope.files?scope.files.has(p):!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded)&&(!scope.sensitive||scope.paths?.includes(p)||!isSensitiveRepoPath(p,scope.sensitive.paths));
157
+ const inScope=(p,scope)=>!scope||(scope.files?scope.files.has(p):!scope.paths||scope.outputs.has(p)||scope.paths.some(s=>p===s||p.startsWith(`${s}/`)))&&!isExcludedPath(p,scope.excluded)&&!matchesCredentialPathTerm(p,scope.denyTerms)&&(!scope.sensitive||scope.paths?.includes(p)||!isSensitiveRepoPath(p,scope.sensitive.paths));
157
158
  // A directory that holds a scope entry may be listed so the walk can reach it.
158
159
  const leadsToScope=(p,scope)=>!scope||!isExcludedPath(p,scope.excluded)&&
159
160
  (scope.files?scope.dirs.has(p)||inScope(p,scope):!scope.paths||inScope(p,scope)||scope.paths.some(s=>s.startsWith(`${p}/`))||[...scope.outputs].some(o=>o.startsWith(`${p}/`)));
@@ -505,21 +506,21 @@ export function excludedPathsAccountedAtBase(mirror,assignment) {
505
506
  // Internal producer only: the caller must supply a persisted, validated assignment
506
507
  // and its trusted mirror. Do not accept a request-supplied path/ref or reuse checkout files.
507
508
  export const SCOPED_SOURCE_MAX_BYTES=512*1024;
508
- export function pinnedScopedSource(mirror,assignment) {
509
+ export function pinnedScopedSource(mirror,assignment,maxBytes=SCOPED_SOURCE_MAX_BYTES,pin=assignmentInput(assignment).base_sha) {
509
510
  if(assignment.paged_read_scope===true) throw new Error('paged read scope does not support artifacts');
510
- const pin=assignmentInput(assignment).base_sha;
511
511
  if(typeof pin!=='string'||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(pin)||
512
512
  !Array.isArray(assignment.scope_paths)||!assignment.scope_paths.length)
513
513
  throw new Error('validated pinned source scope required');
514
514
  const scope=scopeOf({...assignment,output_paths:[]});
515
515
  const policy=sensitivePolicyPaths();
516
516
  if(policy.error) throw new Error('sensitive_policy_unavailable');
517
- const env={...gitEnv(),GIT_NO_REPLACE_OBJECTS:'1',GIT_NO_LAZY_FETCH:'1',GIT_OPTIONAL_LOCKS:'0'};
517
+ const env={...gitEnv(),GIT_NO_REPLACE_OBJECTS:'1',GIT_NO_LAZY_FETCH:'1',GIT_OPTIONAL_LOCKS:'0',GIT_LITERAL_PATHSPECS:'1'};
518
518
  const readGit=(args,maxBuffer,input)=>spawnSync('git',['-C',mirror,...args],{env,timeout:3000,maxBuffer,input});
519
519
  const anchor=readGit(['cat-file','-t',pin],1024);
520
520
  if(anchor.status!==0||anchor.stdout.toString().trim()!=='commit')
521
521
  throw new Error('pinned source commit unavailable');
522
- const tree=readGit(['ls-tree','-rlz','--full-tree',pin],16*1024*1024);
522
+ const paths=scope?.paths?.includes('.')?[]:scope?.paths??[];
523
+ const tree=readGit(['ls-tree','-rlz','--full-tree',pin,'--',...paths],16*1024*1024);
523
524
  if(tree.error||tree.status!==0) throw new Error('pinned source tree unavailable');
524
525
  const decoder=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true});
525
526
  const entries=[],spellings=new Map(),refusedPaths=[];
@@ -549,7 +550,7 @@ export function pinnedScopedSource(mirror,assignment) {
549
550
  }
550
551
  const length=Number(meta[2]);
551
552
  total+=length;
552
- if(entries.length>=256||total>SCOPED_SOURCE_MAX_BYTES) throw new Error('pinned source snapshot exceeds limits');
553
+ if(entries.length>=256||total>maxBytes) throw new Error('pinned source snapshot exceeds limits');
553
554
  entries.push({file,oid:meta[1],length});
554
555
  }
555
556
  const files=[],blobs=new Map();