@tnunamak/dalan 0.9.4 → 0.9.6

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.6
8
+
9
+ - 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.
10
+ - 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.
11
+ - Small pinned review inputs arrive together from the bridge instead of requiring individual GitHub reads. Worker history breaks down unsuccessful runs by recorded reason.
12
+
13
+ ## 0.9.5
14
+
15
+ - 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.
16
+ - Queued reviews end with `pr_head_mismatch` when the pinned pull request head moves. This lets the requester prepare a new review without repeatedly waking a worker for the old request.
17
+ - MCP Tasks can sign and reopen requester task handles without loading the T3 integration.
18
+
7
19
  ## 0.9.4
8
20
 
9
21
  - Delegate in the background from Claude Code through MCP Tasks or from Codex through a custom agent. Supported host versions can bring the result back when the calling conversation is idle.
package/CONTRIBUTING.md CHANGED
@@ -15,6 +15,8 @@ DALAN_HOST_CHECKS=0 npm test
15
15
 
16
16
  `DALAN_HOST_CHECKS=0` turns host checks off by default; tests that exercise host checks may still turn them on.
17
17
 
18
+ Install `strace` on Linux for affected testing. Use `npm test -- --full` to run every segment serially. See [pull request feedback](docs/test-suite-isolation.md#pull-request-feedback) for how the runner chooses and checks affected segments.
19
+
18
20
  For concurrent runs, use a separate Git worktree and a separate short `TMPDIR` for each run (for example `/tmp/s-a-$$` and `/tmp/s-b-$$`). The temporary directory must exist before the run starts. Unix socket paths must fit within 107 bytes. Each test owns its temporary homes, databases, listeners, and host-check systemd units; installed dependencies and the toolchain may be shared read-only. Host-check resource ceilings apply per check, so concurrent runs add their resource use together.
19
21
 
20
22
  When running the installed Gozar journey on its own, point `TMPDIR` at a short, existing, writable directory on disk, especially if the isolated `HOME` is deeply nested. The journey creates and removes its own fixture directory under that temporary root.
@@ -389,7 +389,7 @@ The B7 walks of 2026-11-28 showed where a delegated build still differs from a l
389
389
 
390
390
  | # | Difference | Kind | Caller's part |
391
391
  |---|---|---|---|
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. |
392
+ | 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
393
  | 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
394
  | 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
395
  | 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
 
@@ -4,13 +4,20 @@ The ordered commands in `scripts/test-segments.json` are the audit boundary. The
4
4
 
5
5
  ## Pull request feedback
6
6
 
7
- `npm test` runs affected segments when every changed path is a modified
8
- standalone test in `scripts/test-affected.json`. The list records tests whose
9
- only suite entry points are direct manifest commands. Commands and receipts
10
- keep their original manifest ordinals. The runner uses committed, staged,
11
- unstaged and untracked paths. An unreviewed path, an ambiguous command or
12
- missing Git evidence selects the full manifest. Hosted PR checks compare the
13
- tested merge commit to its recorded base.
7
+ `npm test` reads committed, staged, unstaged and untracked changes. It follows
8
+ first-party imports and script paths from each manifest command to select
9
+ affected segments. An edit limited to the reviewed standalone tests in
10
+ `scripts/test-affected.json` can use their verified direct commands.
11
+ Commands and receipts keep their original manifest ordinals.
12
+ Segments with unresolved dynamic imports run on source edits. Global inputs,
13
+ unknown files or commands, and missing Git evidence select the full manifest.
14
+ Hosted PR checks compare the tested merge commit to its recorded base.
15
+
16
+ On Linux, `strace` checks the files opened by a selected segment and its
17
+ descendants. A first-party source read missing from the dependency graph fails
18
+ the segment. Use a literal module specifier or script path to make the dependency
19
+ visible. Without a working tracer, local feedback uses the full manifest.
20
+ Manually dispatched GitHub test runs also audit the full manifest.
14
21
 
15
22
  Use `npm test -- --full` for an explicit serial run. A detached checkout
16
23
  without a PR base also runs the full manifest. Profile recording runs the
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
 
@@ -1,25 +1 @@
1
- // Reattach capability: HMAC-SHA256(secret, id). The secret is created once (mode 0600, published atomically). The token is
2
- // derived, not stored, so it is the same after an adapter restart.
3
- import { createHmac, randomBytes } from 'node:crypto';
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
-
7
- // Read the secret, create it on first use. A file that is not exactly 0600 or is too short is an error, never replaced.
8
- export function readOrCreateSecret(file) {
9
- fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
10
- const read = () => {
11
- const mode = fs.statSync(file).mode & 0o777;
12
- if (mode !== 0o600) throw Object.assign(new Error(`${file} must be mode 0600 (found ${mode.toString(8)})`), { code: 'state_permissions' });
13
- const secret = fs.readFileSync(file, 'utf8').trim();
14
- if (secret.length < 32) throw new Error(`${file} is too short`);
15
- return secret;
16
- };
17
- try { return read(); } catch (error) { if (error.code !== 'ENOENT') throw error; }
18
- // link() fails with EEXIST when another creator won: the file appears complete or not at all, and the first one is kept.
19
- const tmp = `${file}.${process.pid}.tmp`;
20
- fs.writeFileSync(tmp, randomBytes(32).toString('hex') + '\n', { mode: 0o600 });
21
- try { fs.linkSync(tmp, file); } catch (error) { if (error.code !== 'EEXIST') throw error; } finally { fs.rmSync(tmp, { force: true }); }
22
- return read();
23
- }
24
-
25
- export const ownerToken = (secret, id) => createHmac('sha256', secret).update(id).digest('hex');
1
+ export { ownerToken, readOrCreateSecret } from '../../../../src/owner-capability.mjs';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tnunamak/dalan",
3
- "version": "0.9.4",
3
+ "version": "0.9.6",
4
4
  "description": "An MCP job bridge for bounded agent work, durable progress, results, and owner review.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -61,6 +61,7 @@
61
61
  "oidc-provider": "9.13.0"
62
62
  },
63
63
  "devDependencies": {
64
+ "acorn": "8.15.0",
64
65
  "ajv": "8.17.1",
65
66
  "ajv-formats": "3.0.1",
66
67
  "marked": "15.0.12"
@@ -14,7 +14,7 @@ import { hostCheckRefusal } from './host-execution-policy.mjs';
14
14
  import { redactLogEntry } from './redaction.mjs';
15
15
  import { isLiteralScopePath, submissionLimits } from './submission-policy.mjs';
16
16
  import { readablePath } from './path-syntax.mjs';
17
- import { readOrCreateSecret, ownerToken } from '../integrations/t3/acp-kit/src/capability.mjs';
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';
19
19
  import { adminSocketPathError, adminSocketPath } from './admin-socket.mjs';
20
20
 
@@ -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,17 @@ 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;
498
497
  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
- }
498
+ const policy = buildRepositoryPolicy(context.inputs[0].github_repo, env);
499
+ if (policy.reason) throw new Refusal(policy.reason);
500
+ denyPathTerms = policy.terms;
510
501
  }
511
502
  // 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 } : {}) };
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 } : {}) };
513
504
  let packedPaths = new Set();
514
505
  if (context.packBase) ({ assignment, packedPaths } = await packRepoDiff(cwd, assignment, context.packBase, NO_REPO_NOTE));
515
506
  else if (context.untracked && !build) assignment.brief = `${UNTRACKED_NOTE}\n\n${assignment.brief}`;
@@ -534,13 +525,10 @@ async function prepareUnexplained({ cwd, ...request }, options, env) {
534
525
  // A brief whose first line is exactly BUILD_MARKER asks the worker for a patch: implementation scope (apply_patch, run_check)
535
526
  // on the requester's pushed HEAD, task_kind "build" (the delegation gate measures acceptance of these), and a result that
536
527
  // 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.
528
+ // Older build markers may include path hints. All builds share the pinned repository with credential paths withheld.
540
529
  export const BUILD_MARKER = '[dot-build]';
541
530
  const buildLine = /^\[dot-build\]((?:[ \t]+\S+)*)[ \t]*$/;
542
531
  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
532
  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
533
  async function buildCheckoutRefusal(cwd, options) {
546
534
  if (!cwd || !(await git(cwd, ['rev-parse', '--is-inside-work-tree'])).ok) return BUILD_NEEDS_PUSHED;
@@ -559,11 +547,9 @@ async function buildCheckoutRefusal(cwd, options) {
559
547
  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
548
  return `a [dot-build] task needs the committed revision on origin; ${how}: git push origin ${commandArg}, then delegate again`;
561
549
  }
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
550
  // Who may receive a build comes from the operator's owner allowlist because a parent can send a [dot-build] task without
564
551
  // the delegation gate's offer. The repo exclusion config and credential path terms add further restrictions.
565
552
  // The current and legacy environment variable names are supported; a missing owner list refuses every build.
566
- export const BUILD_MAX_FILES = 5;
567
553
  const glob = pattern => new RegExp(`^${pattern.toLowerCase().replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`);
568
554
  function configuredOwners(value) {
569
555
  if (typeof value !== 'string' || !value.trim()) return null;
@@ -571,18 +557,22 @@ function configuredOwners(value) {
571
557
  if (owners.some(owner => !/^[a-z0-9_.-]+$/.test(owner))) return null;
572
558
  return owners;
573
559
  }
574
- export function buildIneligible(repo, files, env = process.env) {
560
+ function buildRepositoryPolicy(repo, env) {
575
561
  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';
562
+ if (!owners) return {reason:'[dot-build] refused: DALAN_ACP_BUILD_OWNERS or DOT_ACP_BUILD_OWNERS must list authorized repository owners'};
577
563
  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}`;
564
+ if (!owners.includes(name.split('/')[0])) return {reason:`[dot-build] refused: ${repo} is outside the configured owner allowlist`};
580
565
  let cfg;
581
566
  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'; }
567
+ catch { return {reason:'[dot-build] refused: the repo exclusion config is unreadable'}; }
583
568
  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`;
569
+ 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'};
570
+ if (exclude.some(g => glob(g).test(name))) return {reason:`[dot-build] refused: ${repo} is excluded by the repo exclusion config`};
571
+ return {terms};
572
+ }
573
+ export function buildIneligible(repo, files, env = process.env) {
574
+ const {reason, terms} = buildRepositoryPolicy(repo, env);
575
+ if (reason) return reason;
586
576
  const hit = files.find(f => terms.some(t => f.toLowerCase().includes(t.toLowerCase())));
587
577
  if (hit) return `[dot-build] refused: ${hit} matches a credential path term`;
588
578
  return null;
@@ -600,15 +590,11 @@ export function buildExecution(env = process.env) {
600
590
  return value;
601
591
  }
602
592
 
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 : [];
593
+ export function buildAssignment({ requestId, brief, inputs, validUntil, build = false, denyPathTerms = [] }) {
608
594
  return {
609
595
  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 } : {}),
596
+ ...(inputs.length ? { scope_paths: ['.'] } : {}),
597
+ ...(build ? { deny_path_terms: denyPathTerms } : {}),
612
598
  expected_output: build ? BUILD_OUTPUT : 'A complete answer as plain text. Put the result in the finish call.' +
613
599
  (inputs.length ? ' When asked to run checks, use your own permitted tools on the authorized files at the pinned commit. '+
614
600
  'Use a disposable checkout only if your repository grant permits it, or use the granted scoped file set. '+
package/src/mcp-tasks.mjs CHANGED
@@ -4,7 +4,7 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { timingSafeEqual } from 'node:crypto';
7
- import { ownerToken } from '../integrations/t3/acp-kit/src/capability.mjs';
7
+ import { ownerToken } from './owner-capability.mjs';
8
8
  import { defaultPath, ownerReceiptFile } from './paths.mjs';
9
9
  import { safeDiagnostic } from './diagnostic.mjs';
10
10
  import { MAX_ANSWER_BYTES } from './answer-journal.mjs';
@@ -0,0 +1,25 @@
1
+ // Reattach capability: HMAC-SHA256(secret, id). The secret is created once (mode 0600, published atomically). The token is
2
+ // derived, not stored, so it is the same after a requester restart.
3
+ import { createHmac, randomBytes } from 'node:crypto';
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+
7
+ // Read the secret, create it on first use. A file that is not exactly 0600 or is too short is an error, never replaced.
8
+ export function readOrCreateSecret(file) {
9
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
10
+ const read = () => {
11
+ const mode = fs.statSync(file).mode & 0o777;
12
+ if (mode !== 0o600) throw Object.assign(new Error(`${file} must be mode 0600 (found ${mode.toString(8)})`), { code: 'state_permissions' });
13
+ const secret = fs.readFileSync(file, 'utf8').trim();
14
+ if (secret.length < 32) throw new Error(`${file} is too short`);
15
+ return secret;
16
+ };
17
+ try { return read(); } catch (error) { if (error.code !== 'ENOENT') throw error; }
18
+ // link() fails with EEXIST when another creator won: the file appears complete or not at all, and the first one is kept.
19
+ const tmp = `${file}.${process.pid}.tmp`;
20
+ fs.writeFileSync(tmp, randomBytes(32).toString('hex') + '\n', { mode: 0o600 });
21
+ try { fs.linkSync(tmp, file); } catch (error) { if (error.code !== 'EEXIST') throw error; } finally { fs.rmSync(tmp, { force: true }); }
22
+ return read();
23
+ }
24
+
25
+ export const ownerToken = (secret, id) => createHmac('sha256', secret).update(id).digest('hex');
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,47 @@ 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 inlinePinnedSource(row,principal,connectionId,claimId) {
200
+ const {worker,subject}=principal;
201
+ const {assignment,request_id:requestId}=row;
202
+ if(!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
+ try {
207
+ if(oauth) needScope(principal,scopeFor('read_file'));
208
+ if(!workerWorkspaceAllowed(worker,requestId)) return {};
209
+ assertRepoAllowed(worker,assignment);
210
+ store.assertMutationConnection(requestId,grant,connectionId);
211
+ const input=assignmentInput(assignment);
212
+ if(input.input_patch) return {};
213
+ 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')};
216
+ if(JSON.stringify(redactOutput(bundle))!==JSON.stringify(bundle)) return {};
217
+ return {pinned_input_bundle:bundle};
218
+ } catch {
219
+ // A large or unavailable snapshot must not discard a valid claim or deny ordinary workspace reads.
220
+ return {};
221
+ }
222
+ }
182
223
  const phaseTrace = createPhaseTrace({ log });
183
224
  logShutdownSignals(log);
184
225
  // Registry definitions are discovered through list_tools. The native tools/list stays fixed.
@@ -239,35 +280,28 @@ const toolRegistry=createToolRegistry({store,now:()=>store.nowMs(),handlers:{
239
280
  return [requestId,claim.claim_id,claim.epoch,subject,connection];
240
281
  } catch(error) { throw assignmentRegistryRefusal(error); }
241
282
  },
242
- run({args,context:{worker,subject},grantScope,recordOnRead}) {
283
+ run({args,context:{worker,subject,builtin,connection_id},grantScope,recordOnRead}) {
243
284
  const requestId=id(args.request_id),claimId=id(args.claim_id,'claim_id');
244
285
  const offset=args.offset??0;
245
286
  if(offset%scopedSourceChunk!==0||(offset!==0&&!args.sha256)) throw new RegistryError('invalid_arguments','invalid scoped input offset');
246
287
  try {
247
288
  const {a,claim,input,mirror}=workspace.context(requestId,claimId,subject,false,worker);
248
289
  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);
290
+ const {manifest,refusedPaths,bytes,sha256:hash}=encodePinnedSource(mirror,a.assignment,requestId);
250
291
  if(grantScope && manifest.files.some(file=>!a.assignment.scope_paths.includes(file.path)))
251
292
  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
293
  if(args.sha256!==undefined&&args.sha256!==hash) throw new Error('scoped input changed');
263
294
  if(offset>=bytes.length) throw new Error('invalid scoped input offset');
264
295
  const end=Math.min(offset+scopedSourceChunk,bytes.length);
265
296
  const result={sha256:hash,size:bytes.length,offset,next_offset:end===bytes.length?null:end,data_base64:bytes.subarray(offset,end).toString('base64')};
266
297
  if(JSON.stringify(redactOutput(result))!==JSON.stringify(result)) throw new Error('scoped input encoding refused');
267
298
  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),
299
+ recordOnRead(()=>store.inTransaction(()=>{
300
+ store.touchClaim(requestId,claimId,subject,worker,builtin?(connection_id??''):null);
301
+ store.recordScopedInputChunk(requestId,{
302
+ epoch:claim.epoch,worker,sha256:hash,metadata,chunk:offset/scopedSourceChunk,
303
+ chunkCount:Math.ceil(bytes.length/scopedSourceChunk),
304
+ });
271
305
  }));
272
306
  return result;
273
307
  } catch(error) { throw assignmentRegistryRefusal(error); }
@@ -548,7 +582,7 @@ if(batchClaimProfile) {
548
582
  // No top-level oneOf: several MCP hosts reject combinators at the schema root. validate() enforces exactly one of request_id or next.
549
583
  // The stable catalog stays frozen: claim_id on get (heartbeat for that exact claim) is served only in this profile.
550
584
  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.';
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.';
552
586
  get.inputSchema.properties.claim_id=string;
553
587
  }
554
588
  // Opt-in compatibility catalog only; grant and lease enforcement are unchanged.
@@ -795,6 +829,15 @@ function sweepSkipped() {
795
829
  for(const requestId of ids) { const waiter=waiters.get(requestId); if(waiter) { waiters.delete(requestId); clearTimeout(waiter.timer); json(waiter.res,200,waitSummary(requestId)); } }
796
830
  return ids;
797
831
  }
832
+ function notifyStalePrCancellation(requestId) {
833
+ log({kind:'pr_head_mismatch_cancelled',request_id:requestId});
834
+ const waiter=waiters.get(requestId);
835
+ if(waiter) {
836
+ waiters.delete(requestId);
837
+ clearTimeout(waiter.timer);
838
+ json(waiter.res,200,waitSummary(requestId));
839
+ }
840
+ }
798
841
  // Abandon claims whose lease ran out (Store.sweepStaleLeases): the row is requeued and its lane is free.
799
842
  function sweepStaleLeases() {
800
843
  const ids=store.sweepStaleLeases();
@@ -918,11 +961,11 @@ function batchCapacityReply(name,reply,principal,callId,onOffer) {
918
961
  ready_queued>0&&hintFree===0?['hint_full','Lanes are free but the claim hint is full; claim again when the hint allows more.']:
919
962
  ['no_ready_work','No ready queued work; call list_pending again later.'];
920
963
  const {next_action:previousAction,free_lanes:previousFree,...rest}=reply;
921
- const response={next_action,free_lanes,ready_queued,...rest};
964
+ const response={next_action,free_lanes,claimable_lanes:available,ready_queued,recommended_claims:reason==='ready'?next:0,dispatch_reason:reason,...rest};
922
965
  if(recordListing) {
923
966
  const recommended=reason==='ready'?next:0;
924
967
  const readyIds=ready.slice(0,recommended).map(item=>item.request_id);
925
- logPendingReply(response,principal,callId,{ready_queued,dispatch_reason:reason,recommended_claims:recommended,ready_head_ids:readyIds});
968
+ logPendingReply(response,principal,callId,{ready_queued,claimable_lanes:available,dispatch_reason:reason,recommended_claims:recommended,ready_head_ids:readyIds});
926
969
  if(readyIds.length) onOffer?.({worker,subject,callId,readyIds});
927
970
  }
928
971
  return response;
@@ -1374,7 +1417,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1374
1417
  if(preflight) store.clearPrClaimMismatch(requestId,preflight);
1375
1418
  }
1376
1419
  catch(error) {
1377
- if(error.prHeadMismatch) store.recordPrClaimMismatch(requestId,error.prHeadMismatch);
1420
+ if(error.prHeadMismatch&&store.recordPrClaimMismatch(requestId,error.prHeadMismatch)) notifyStalePrCancellation(requestId);
1378
1421
  throw error;
1379
1422
  }
1380
1423
  }
@@ -1396,7 +1439,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1396
1439
  const grant=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
1397
1440
  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});
1398
1441
  const {free_lanes,queued,reserved_request_id}=store.laneState(subject,worker,redeliveryLimits.laneCapacity,claimCapacity);
1399
- 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);
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);
1400
1443
  }
1401
1444
  case 'renew_claim': {
1402
1445
  if(!strictJob) throw new Error('renew_claim requires a protocol job');
@@ -1407,7 +1450,9 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1407
1450
  if(!store.hasAssignment(requestId)) return {kind:'message',message:store.getMessage(requestId,worker)};
1408
1451
  store.markNotesSeenByHolder(requestId,subject,worker,connectionId);
1409
1452
  const row=store.get(requestId);
1410
- return {...publicWorkerGet(withAvailableChecks(row,true,worker,subject)),...store.workerGetHeartbeat(row,worker,subject,a.claim_id),guidance:store.guidanceFor(worker)};
1453
+ const claimId=a.claim_id??(row.claim?.epoch===1?row.claim.claim_id:undefined);
1454
+ 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)};
1411
1456
  }
1412
1457
  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};}
1413
1458
  case 'progress': {
@@ -2244,6 +2289,7 @@ function maintain() {
2244
2289
  } catch(error) { log({kind:'facade_withdrawal_error',request_id:requestId,reason:error.message}); }
2245
2290
  }
2246
2291
  sweepExpired();
2292
+ for(const requestId of store.sweepPrClaimMismatches()) notifyStalePrCancellation(requestId);
2247
2293
  sweepSkipped();
2248
2294
  sweepStaleLeases();
2249
2295
  store.retireUnknownSubscriptions();
package/src/store.mjs CHANGED
@@ -209,6 +209,7 @@ const live=nowMs=>`NOT ${expired(nowMs)} AND (request_id NOT IN (SELECT request_
209
209
  WHERE CAST(json_extract(p.settings,'$.retain_until_ms') AS INTEGER)>'${nowMs}'
210
210
  AND NOT EXISTS (SELECT 1 FROM job_retention_tombstones t WHERE t.job=p.request_id)
211
211
  ))`;
212
+ const noPrClaimBlock=table=>`NOT EXISTS (SELECT 1 FROM pr_claim_blocks b WHERE b.request_id=${table}.request_id)`;
212
213
  export const expiredError=(validUntil,{cancelled=false,requeue=false}={})=>`assignment_expired: its prepared inputs were valid until ${validUntil}; ${cancelled?'the bridge cancelled it and will not requeue it':requeue?'the bridge has not cancelled it; the expiry sweep will evaluate whether it can requeue it':'the bridge has not cancelled it yet and will not requeue it'}. Call list_pending, then claim another listed assignment.`;
213
214
  const denialPattern=/auto-?review|guardian|denied|not approved|paused out of precaution/i;
214
215
  export const workerGuidance='If auto-review or Guardian denies an action, stop that line of work, report BLOCKED: with the denied action, and never retry or rephrase to get around it. A denial or error about one assignment does not affect another: an error naming a different request_id (for example a finished assignment) is not a revocation of this one. An assignment with a new request_id that the owner submitted is a separate, fresh owner request, made after the owner saw the earlier outcome; it is not a retry of a denied action, so judge it on its own merits. If finish answers assignment_cancelled, the owner withdrew that request: this is not a denial and nothing to work around or retry; stop work on it and move on. Read the response to see whether bounded audit evidence was retained; output after the lease deadline is dropped. Check owner_notes on this assignment with get before finishing. Reading UI source that renders or validates a credential input field is ordinary UI work; the restriction is on revealing, copying, changing or transmitting actual secret values.';
@@ -1518,6 +1519,7 @@ export class Store {
1518
1519
  a.created_at
1519
1520
  )>=? AND a.target_worker=? AND ${queueKindSql}=? AND a.status IN ('finished','cancelled')`).all(since,worker,kind);
1520
1521
  const outcomes={landed:0,check_passed:0,checks_failed:0,refused_by_provider:0,unable_to_run:0,owner_cancelled:0,finished_unchecked:0};
1522
+ const unable_to_run_reasons={};
1521
1523
  let accepted=0,check_passed=0;
1522
1524
  const durations=[];
1523
1525
  // Check events from an earlier claim of a re-queued job describe a run that did not produce the result, so only the
@@ -1536,7 +1538,11 @@ export class Store {
1536
1538
  else {
1537
1539
  const {failure_type}=this.failureFields(row.request_id);
1538
1540
  if(failure_type==='owner_cancelled') outcomes.owner_cancelled++;
1539
- else outcomes.unable_to_run++;
1541
+ else {
1542
+ outcomes.unable_to_run++;
1543
+ const reason=failure_type??'unknown';
1544
+ unable_to_run_reasons[reason]=(unable_to_run_reasons[reason]??0)+1;
1545
+ }
1540
1546
  }
1541
1547
  }
1542
1548
  // The provider session is opaque. The final claim and its report delimit an observed span on this job.
@@ -1544,7 +1550,7 @@ export class Store {
1544
1550
  const min_samples=QUEUE_WINDOW.minSamples;
1545
1551
  const claim_to_report={source:'final_claim_to_report',n:durations.length,min_samples,
1546
1552
  p50_ms:durations.length<min_samples?null:durations[Math.ceil(durations.length/2)-1]};
1547
- return {worker,kind,window_days:days,n:rows.length,accepted,check_passed,outcomes,claim_to_report,session_length:this.sessionLength(worker,days)};
1553
+ 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)};
1548
1554
  }
1549
1555
  queueWaitsMs(worker,kind,days=7) { return this.queueWaitEvidence(worker,kind,days).waits_ms; }
1550
1556
  defaultValidUntil(worker,kind,days=7) {
@@ -2096,7 +2102,7 @@ export class Store {
2096
2102
  }
2097
2103
  // Queued assignments in list_pending order (waiting normal before other normal, then background and oldest) with queued_at (see queuedAt).
2098
2104
  queuedRows() {
2099
- 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())} ORDER BY ${LIST_ORDER}`).all();
2105
+ 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();
2100
2106
  }
2101
2107
  // Break intervals [since, until or open] in ms. Owner since never reaches back before the previous break's end, so they are disjoint.
2102
2108
  breakIntervals(worker='dot') {
@@ -2113,7 +2119,7 @@ export class Store {
2113
2119
  // sending owner delivery are left out: they wait for reconcile, not for the worker. Derived only: a requeue restarts the clock.
2114
2120
  unclaimedAfterReannounce(limits=this.limits,worker='dot') {
2115
2121
  const now=this.nowMs(), windowMs=limits.rewakeWindowMs??defaultRedeliveryLimits.rewakeWindowMs, breaks=this.breakIntervals(worker);
2116
- const rows=this.db.prepare(`SELECT a.request_id,${queuedAt} queued_at FROM assignments a WHERE a.target_worker=? AND a.status='queued' AND ${live(now)} ORDER BY queued_at`).all(worker).filter(r=>this.queuedAgeMs(r.queued_at,now,breaks)>=windowMs&&!this.uncertainDeliveries(r.request_id));
2122
+ const rows=this.db.prepare(`SELECT a.request_id,${queuedAt} queued_at FROM assignments a WHERE a.target_worker=? AND a.status='queued' AND ${live(now)} AND ${noPrClaimBlock('a')} ORDER BY queued_at`).all(worker).filter(r=>this.queuedAgeMs(r.queued_at,now,breaks)>=windowMs&&!this.uncertainDeliveries(r.request_id));
2117
2123
  return {count:rows.length,oldest_age_ms:rows.length?now-Date.parse(rows[0].queued_at):null,request_ids:rows.slice(0,10).map(r=>r.request_id)};
2118
2124
  }
2119
2125
  // Honest classification of queued work after its first event 2xx. Observations only: nothing here reclaims or cancels a claim.
@@ -2137,7 +2143,7 @@ export class Store {
2137
2143
  const hasLiveClaim=liveClaims.some(c=>now-Date.parse(c.last_claim_activity_at??c.claimed_at)<this.claimLeaseMs(c));
2138
2144
  const atCapacity=liveSubs.length>0&&liveSubs.every(sub=>this.subscriptionFreeLanes(sub,limits.laneCapacity??6,capacity)===0);
2139
2145
  const hasSubscription=liveSubs.length>0;
2140
- const items=this.db.prepare(`SELECT request_id,created_at,skipped_at,NOT (${live(now)}) expired FROM assignments WHERE target_worker=? AND status='queued' AND cancelled_at IS NULL ORDER BY created_at`).all(worker).map(row=>{
2146
+ const items=this.db.prepare(`SELECT request_id,created_at,skipped_at,NOT (${live(now)}) expired FROM assignments WHERE target_worker=? AND status='queued' AND cancelled_at IS NULL AND ${noPrClaimBlock('assignments')} ORDER BY created_at`).all(worker).map(row=>{
2141
2147
  // A queued row past its preparation's valid_until, or a protocol row past its retention, is 'expired', never alive_not_claiming: the worker cannot claim it.
2142
2148
  if(row.expired) return {request_id:row.request_id,class:'expired',event_2xx_age_ms:null};
2143
2149
  if(row.skipped_at!==null) return {request_id:row.request_id,class:null,event_2xx_age_ms:null};
@@ -2439,8 +2445,9 @@ export class Store {
2439
2445
  try { this.assertMutationConnection(id,claim,connectionId); }
2440
2446
  catch(error) { if(error.destination?.error==='connection_not_live')return false; throw error; }
2441
2447
  this.markNotesSeen(id,subject,worker);
2442
- // 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.
2443
- if(this.handoffWorkLeaseMs(claim)!==null&&!this.leaseExpired(claim)) this.refreshClaimActivity(id,claim.claim_id);
2448
+ // The initial holder's get proves activity on this claim. After reclaim, a request ID alone cannot
2449
+ // distinguish a delayed get from the previous epoch. Those reads need the current claim ID.
2450
+ if((claim.epoch===1||this.handoffWorkLeaseMs(claim)!==null)&&!this.leaseExpired(claim)) this.refreshClaimActivity(id,claim.claim_id);
2444
2451
  return true;
2445
2452
  }); }
2446
2453
  // Unfenced: for callers that already proved the holder inside their own claim transaction (exact retry, resume). `get` uses markNotesSeenByHolder.
@@ -2757,12 +2764,25 @@ export class Store {
2757
2764
  FROM scoped_input_receipts WHERE request_id=? ORDER BY epoch,sha256`).all(id)
2758
2765
  .map(({epoch,worker,sha256,metadata,complete})=>({...JSON.parse(metadata),epoch,worker,sha256,all_chunks_served:!!complete}));
2759
2766
  }
2760
- recordPrClaimMismatch(id,{pinned,observed}) {
2761
- this.db.prepare(`INSERT INTO pr_claim_blocks(request_id,pinned,observed,checked_at)
2762
- SELECT request_id,?,?,? FROM assignments WHERE request_id=? AND status='queued'
2767
+ recordPrClaimMismatch(id,{pinned,observed}) { return this.transaction(()=>{
2768
+ const recorded=this.db.prepare(`INSERT INTO pr_claim_blocks(request_id,pinned,observed,checked_at)
2769
+ SELECT request_id,?,?,? FROM assignments WHERE request_id=? AND status='queued' AND json_extract(payload,'$.inputs[0].head_sha')=?
2763
2770
  ON CONFLICT(request_id) DO UPDATE SET observed=excluded.observed,checked_at=excluded.checked_at
2764
- WHERE pr_claim_blocks.pinned=excluded.pinned`).run(pinned,observed,this.stamp(),id);
2771
+ WHERE pr_claim_blocks.pinned=excluded.pinned`).run(pinned,observed,this.stamp(),id,pinned);
2772
+ return recorded.changes>0&&this.cancelQueuedPrClaimMismatch(id);
2773
+ }); }
2774
+ cancelQueuedPrClaimMismatch(id) {
2775
+ if(this.uncertainDeliveries(id)) return false;
2776
+ const reason='pr_head_mismatch';
2777
+ this.cancelInTransaction(id,reason,'system');
2778
+ if(this.isProtocolJob(id)) this.protocolEventInTransaction(id,'cancelled',{reason});
2779
+ return true;
2765
2780
  }
2781
+ sweepPrClaimMismatches(limit=100) { return this.transaction(()=>{
2782
+ const rows=this.db.prepare(`SELECT a.request_id FROM pr_claim_blocks b JOIN assignments a USING(request_id)
2783
+ WHERE a.status='queued' AND ${live(this.nowMs())} ORDER BY b.checked_at LIMIT ?`).all(limit);
2784
+ return rows.map(row=>row.request_id).filter(id=>this.cancelQueuedPrClaimMismatch(id));
2785
+ }); }
2766
2786
  clearPrClaimMismatch(id,{head_sha,checked_at}) {
2767
2787
  this.db.prepare('DELETE FROM pr_claim_blocks WHERE request_id=? AND pinned=? AND checked_at<=?')
2768
2788
  .run(id,head_sha,checked_at);
@@ -3818,7 +3838,7 @@ export class Store {
3818
3838
  const workCancelled=this.pullQueue.cancel(id,reason);if(workCancelled)return workCancelled;
3819
3839
  return this.isProtocolJob(id)?cancelProtocolJob(this,id,reason,ownerToken,ctx):this.transaction(()=>this.cancelInTransaction(id,reason));
3820
3840
  }
3821
- cancelInTransaction(id,reason=null) {
3841
+ cancelInTransaction(id,reason=null,actor='owner') {
3822
3842
  if(!this.db.isTransaction)protocolError('transaction_required');
3823
3843
  const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found'); if(a.status==='finished') throw new Error('already finished');
3824
3844
  if(a.status!=='cancelled') {
@@ -3826,8 +3846,8 @@ export class Store {
3826
3846
  const released=this.db.prepare('DELETE FROM admission_reservations WHERE request_id=?').run(id).changes>0;
3827
3847
  if(a.status==='claimed'||released) this.laneFreed();
3828
3848
  this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=?,cancelled_reason=? WHERE request_id=?").run(this.stamp(),reason,id);
3829
- this.lifecycle(id,'withdraw_work','owner',reason,undefined,{scope:`job:${id}`,outcome:'done'});
3830
- this.lifecycle(id,'cancelled','owner',reason);
3849
+ this.lifecycle(id,'withdraw_work',actor,reason,undefined,{scope:`job:${id}`,outcome:'done'});
3850
+ this.lifecycle(id,'cancelled',actor,reason);
3831
3851
  this.db.prepare("UPDATE notifications SET state='suppressed' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
3832
3852
  this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
3833
3853
  }
@@ -4311,7 +4331,7 @@ export class Store {
4311
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);
4312
4332
  const sub=this.db.prepare("SELECT * FROM subscriptions WHERE worker='dot' ORDER BY verified_at DESC LIMIT 1").get();
4313
4333
  const active=this.activeSubscriptions().filter(sub=>sub.worker==='dot');
4314
- const oldest=this.db.prepare(`SELECT min(created_at) oldest FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())}`).get().oldest;
4334
+ 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;
4315
4335
  const lastClaim=this.db.prepare("SELECT max(claimed_at) last_claim FROM claims WHERE worker='dot'").get().last_claim;
4316
4336
  const uncertain=this.db.prepare("SELECT count(*) n FROM notifications WHERE state='uncertain' AND kind IN ('t3','watch','blocker','break','event')").get().n;
4317
4337
  const pause=this.db.prepare('SELECT paused_at,reason FROM operator_state WHERE id=1').get();
@@ -4319,9 +4339,9 @@ export class Store {
4319
4339
  SELECT target_worker worker,request_id,created_at,
4320
4340
  count(*) OVER (PARTITION BY target_worker) n,
4321
4341
  row_number() OVER (PARTITION BY target_worker ORDER BY created_at,request_id) rank
4322
- FROM assignments WHERE status='queued' AND cancelled_at IS NULL AND skipped_at IS NULL AND ${live(this.nowMs())})
4342
+ FROM assignments WHERE status='queued' AND cancelled_at IS NULL AND skipped_at IS NULL AND ${live(this.nowMs())} AND ${noPrClaimBlock('assignments')})
4323
4343
  SELECT worker,n,created_at oldest,request_id FROM live_queue WHERE rank=1`).all().map(r=>[r.worker,r]));
4324
- const dotQueuedWithoutSubscription=active.length===0&&!!this.db.prepare(`SELECT 1 FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())} LIMIT 1`).get();
4344
+ 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();
4325
4345
  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};
4326
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]))]));
4327
4347
  const throttle=this.rollingUsage(limits);
@@ -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();