@tnunamak/dalan 0.9.5 → 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,12 @@ 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
+
7
13
  ## 0.9.5
8
14
 
9
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.
@@ -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
 
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.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",
@@ -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/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.
@@ -927,11 +961,11 @@ function batchCapacityReply(name,reply,principal,callId,onOffer) {
927
961
  ready_queued>0&&hintFree===0?['hint_full','Lanes are free but the claim hint is full; claim again when the hint allows more.']:
928
962
  ['no_ready_work','No ready queued work; call list_pending again later.'];
929
963
  const {next_action:previousAction,free_lanes:previousFree,...rest}=reply;
930
- 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};
931
965
  if(recordListing) {
932
966
  const recommended=reason==='ready'?next:0;
933
967
  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});
968
+ logPendingReply(response,principal,callId,{ready_queued,claimable_lanes:available,dispatch_reason:reason,recommended_claims:recommended,ready_head_ids:readyIds});
935
969
  if(readyIds.length) onOffer?.({worker,subject,callId,readyIds});
936
970
  }
937
971
  return response;
@@ -1405,7 +1439,7 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1405
1439
  const grant=store.db.prepare('SELECT * FROM claims WHERE request_id=?').get(requestId);
1406
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});
1407
1441
  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);
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);
1409
1443
  }
1410
1444
  case 'renew_claim': {
1411
1445
  if(!strictJob) throw new Error('renew_claim requires a protocol job');
@@ -1416,7 +1450,9 @@ async function dispatchTool(name,a,principal,notifyMeta,signal,batchMode=null,re
1416
1450
  if(!store.hasAssignment(requestId)) return {kind:'message',message:store.getMessage(requestId,worker)};
1417
1451
  store.markNotesSeenByHolder(requestId,subject,worker,connectionId);
1418
1452
  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)};
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)};
1420
1456
  }
1421
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};}
1422
1458
  case 'progress': {
package/src/store.mjs CHANGED
@@ -1519,6 +1519,7 @@ export class Store {
1519
1519
  a.created_at
1520
1520
  )>=? AND a.target_worker=? AND ${queueKindSql}=? AND a.status IN ('finished','cancelled')`).all(since,worker,kind);
1521
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={};
1522
1523
  let accepted=0,check_passed=0;
1523
1524
  const durations=[];
1524
1525
  // 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 +1538,11 @@ export class Store {
1537
1538
  else {
1538
1539
  const {failure_type}=this.failureFields(row.request_id);
1539
1540
  if(failure_type==='owner_cancelled') outcomes.owner_cancelled++;
1540
- 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
+ }
1541
1546
  }
1542
1547
  }
1543
1548
  // The provider session is opaque. The final claim and its report delimit an observed span on this job.
@@ -1545,7 +1550,7 @@ export class Store {
1545
1550
  const min_samples=QUEUE_WINDOW.minSamples;
1546
1551
  const claim_to_report={source:'final_claim_to_report',n:durations.length,min_samples,
1547
1552
  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)};
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)};
1549
1554
  }
1550
1555
  queueWaitsMs(worker,kind,days=7) { return this.queueWaitEvidence(worker,kind,days).waits_ms; }
1551
1556
  defaultValidUntil(worker,kind,days=7) {
@@ -2440,8 +2445,9 @@ export class Store {
2440
2445
  try { this.assertMutationConnection(id,claim,connectionId); }
2441
2446
  catch(error) { if(error.destination?.error==='connection_not_live')return false; throw error; }
2442
2447
  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);
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);
2445
2451
  return true;
2446
2452
  }); }
2447
2453
  // Unfenced: for callers that already proved the holder inside their own claim transaction (exact retry, resume). `get` uses markNotesSeenByHolder.
@@ -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();