@tnunamak/dalan 0.8.5 → 0.9.2

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.
@@ -1,4 +1,4 @@
1
- import { materialize } from './patch-apply.mjs';
1
+ import { materialize, publicationFailureText } from './patch-apply.mjs';
2
2
  import { defaultPath } from './paths.mjs';
3
3
  // Bridge-facing pieces of the ACP adapter (bin/dot-acp-agent.mjs): the admin-socket client, the owner token, brief and
4
4
  // request-id rules, submit eligibility and the payload builder. Nothing here speaks ACP.
@@ -12,7 +12,8 @@ import { promisify } from 'node:util';
12
12
  import { packRepoDiff, stripPacked } from './acp-context.mjs';
13
13
  import { hostCheckRefusal } from './host-execution-policy.mjs';
14
14
  import { redactLogEntry } from './redaction.mjs';
15
- import { submissionLimits } from './submission-policy.mjs';
15
+ import { isLiteralScopePath, submissionLimits } from './submission-policy.mjs';
16
+ import { readablePath } from './path-syntax.mjs';
16
17
  import { readOrCreateSecret, ownerToken } from '../integrations/t3/acp-kit/src/capability.mjs';
17
18
  import { CONTINUE_PROMPT, promptText, unwrapUserRequest, isT3RuntimeBlock, parseIdentity } from '../integrations/t3/acp-kit/src/t3-envelope.mjs';
18
19
  import { adminSocketPathError, adminSocketPath } from './admin-socket.mjs';
@@ -36,7 +37,7 @@ export function paths(env = process.env) {
36
37
  export class BridgeError extends Error {
37
38
  constructor(message, kind, httpStatus) { super(message); this.kind = kind; this.http_status = httpStatus ?? null; }
38
39
  }
39
- export const transient = e => e.kind === 'transport' || e.http_status >= 500;
40
+ export const transient = e => e.retryable !== false && (e.kind === 'transport' || e.http_status >= 500);
40
41
 
41
42
  const isReplyRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value);
42
43
  function validAdminVerdict(value) {
@@ -47,7 +48,7 @@ function validAdminVerdict(value) {
47
48
  reason.candidates.every(candidate => typeof candidate === 'string'))));
48
49
  }
49
50
 
50
- export function adminRequest(socket, route, { method = 'GET', payload, token, signal, timeoutMs } = {}) {
51
+ export function adminRequest(socket, route, { method = 'GET', payload, token, signal, timeoutMs, maxResponseBytes } = {}) {
51
52
  const positive = (value, fallback) => Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : fallback;
52
53
  const baseMs = positive(process.env.DOT_ACP_HTTP_TIMEOUT_MS, 20000);
53
54
  const graceMs = positive(process.env.DOT_ACP_HTTP_GRACE_MS, 1000);
@@ -61,13 +62,43 @@ export function adminRequest(socket, route, { method = 'GET', payload, token, si
61
62
  let timer;
62
63
  const fail = error => { clearTimeout(timer); reject(error instanceof BridgeError ? error : Object.assign(new BridgeError(error.message, 'transport'), { name: error.name })); };
63
64
  const headers = { 'content-type': 'application/json', 'content-length': Buffer.byteLength(bytes), ...(token ? { 'x-owner-capability': token } : {}) };
65
+ // A response intrinsically over the cap will be over it on every retry, so it is a
66
+ // deterministic, nonretryable diagnostic (kind 'local'), never a transport error the
67
+ // restart wrapper repeats. Output stays bounded: chunks past the cap are not retained.
68
+ // An interrupted response (error/aborted/deadline) remains transport and retryable.
69
+ const capBytes = positive(maxResponseBytes ?? process.env.DOT_ACP_ADMIN_RESPONSE_CAP_BYTES, 16 * 1024 * 1024);
70
+ const tooLarge = status => Object.assign(
71
+ new BridgeError(`admin response too large: ${method} ${url.pathname} exceeds the ${capBytes}-byte response cap (HTTP ${status}); not retrying`, 'local', status),
72
+ { code: 'admin_response_too_large', retryable: false, cap_bytes: capBytes });
64
73
  const req = http.request({ socketPath: socket, path: route, method, headers, signal }, res => {
65
- let out = '';
66
- res.on('data', b => { out += b; });
67
- res.on('error', fail);
68
- res.on('aborted', () => fail(new Error('admin response aborted')));
74
+ const chunks = [];
75
+ let received = 0, capped = false;
76
+ const declared = Number(res.headers['content-length']);
77
+ if (Number.isFinite(declared) && declared > capBytes) {
78
+ capped = true;
79
+ res.destroy();
80
+ req.destroy();
81
+ return fail(tooLarge(res.statusCode));
82
+ }
83
+ res.on('data', b => {
84
+ if (capped) return;
85
+ received += b.length;
86
+ if (received > capBytes) {
87
+ capped = true;
88
+ chunks.length = 0;
89
+ res.destroy();
90
+ req.destroy();
91
+ fail(tooLarge(res.statusCode));
92
+ return;
93
+ }
94
+ chunks.push(b);
95
+ });
96
+ res.on('error', error => { if (!capped) fail(error); });
97
+ res.on('aborted', () => { if (!capped) fail(new Error('admin response aborted')); });
69
98
  res.on('end', () => {
99
+ if (capped) return;
70
100
  clearTimeout(timer);
101
+ const out = Buffer.concat(chunks).toString('utf8');
71
102
  let value;
72
103
  try { value = JSON.parse(out); } catch { return fail(new Error('invalid admin response')); }
73
104
  const admission = url.pathname === '/submit' || url.pathname === '/submit-preview';
@@ -100,7 +131,7 @@ export async function adminRequestThroughRestart(socket, route, options = {}) {
100
131
  catch (e) {
101
132
  const unsent = ['ECONNREFUSED', 'ENOENT'].includes(e.code) || /ECONNREFUSED|ENOENT/.test(e.message ?? '');
102
133
  const quiescing = /bridge_quiescing/.test(e.message ?? '');
103
- const retry = unsent || quiescing || (read && e.kind === 'transport');
134
+ const retry = e.retryable !== false && e.code !== 'admin_response_too_large' && (unsent || quiescing || (read && e.kind === 'transport'));
104
135
  if (!retry || options.signal?.aborted || Date.now() + stepMs > until) throw e;
105
136
  await new Promise(resolve => setTimeout(resolve, stepMs));
106
137
  }
@@ -142,7 +173,10 @@ export function adminArtifact(socket, artifactId, token, timeoutMs = 5000, wallC
142
173
  // T3's delegate_task puts `Act as the <role> sub-agent for this task.\n\n` before the task for every role except general
143
174
  // (and none); parseIdentity strips it, because otherwise the token line and a [dot-build] line are no longer first.
144
175
  export function parsePrompt(prompt, { worker = null } = {}) {
145
- const { id: root, text, brief } = parseIdentity(prompt, { prefix: 'dot-decision', idPattern });
176
+ const legacy = parseIdentity(prompt, { prefix: 'dot-decision', idPattern });
177
+ const { id: root, text, brief } = worker === 'muse' && legacy.text.startsWith('[muse-decision:')
178
+ ? parseIdentity(prompt, { prefix: 'muse-decision', idPattern })
179
+ : legacy;
146
180
  // Without a token the identity is the text after the T3 preamble, so a resend with or without a role maps to one request.
147
181
  const lines = brief.split('\n');
148
182
  let priority = 'normal', requirements = [];
@@ -338,6 +372,35 @@ export async function prepareAssignmentWithContext(request, options, env = proce
338
372
  throw error;
339
373
  }
340
374
  }
375
+ // Older hosts carry explicit repository intent in a marked first line. The
376
+ // existing submission compiler still authorizes the pinned tree and paths.
377
+ export function explicitReadIntent(brief) {
378
+ const lines=brief.split(/\r?\n/);
379
+ const markers=[];
380
+ let fence=null,buildMarker=false;
381
+ for(const [index,line] of lines.entries()) {
382
+ const delimiter=/^[ \t]*(\x60{3,}|~{3,})/.exec(line)?.[1];
383
+ if(delimiter) {
384
+ if(!fence) fence=delimiter;
385
+ else if(delimiter[0]===fence[0]&&delimiter.length>=fence.length) fence=null;
386
+ } else if(!fence) {
387
+ if(/^[ \t]*\[dalan-read\b/i.test(line)) markers.push(index);
388
+ if(/^[ \t]*\[dot-build\b/i.test(line)) buildMarker=true;
389
+ }
390
+ }
391
+ if(!markers.length) return null;
392
+ const header=/^\[dalan-read\][ \t]+([A-Za-z0-9][\w.-]*\/[A-Za-z0-9][\w.-]*)@([a-f0-9]{40})[ \t]+(\S+(?:[ \t]+\S+)*)[ \t]*$/i.exec(lines[0]);
393
+ if(!header||markers.length!==1||markers[0]!==0||buildMarker) {
394
+ throw new Refusal('Use one first-line [dalan-read] owner/repo@FULL_SHA followed by the allowed paths.');
395
+ }
396
+ const [,repo,sha,list]=header;
397
+ const scope=list.split(/[ \t]+/).map(file=>file.replace(/^\.\//,''));
398
+ if(scope.length>200||new Set(scope).size!==scope.length||!scope.every(file=>readablePath(file)&&isLiteralScopePath(file))) {
399
+ throw new Refusal('The [dalan-read] line must name distinct repository-relative paths.');
400
+ }
401
+ return {repo,sha:sha.toLowerCase(),scope};
402
+ }
403
+
341
404
  async function prepareUnexplained({ cwd, ...request }, options, env) {
342
405
  // A text-only worker cannot open host files, so a brief that names one would end BLOCKED after a wake-up cycle. Refuse
343
406
  // at submit, while the sender can still paste the content. URLs and repository-relative names are allowed.
@@ -347,9 +410,10 @@ async function prepareUnexplained({ cwd, ...request }, options, env) {
347
410
  }
348
411
  const textOnly = env.DOT_ACP_TEXT_ONLY === '1';
349
412
  const build = isBuild(request.brief);
413
+ const explicitRead = explicitReadIntent(request.brief);
350
414
  // Without an explicit list, a named repository is allowed when a build of it would be: its owner is in the configured owner
351
415
  // list and no exclusion rule covers it (the same rules as buildIneligible, so a review reads what a build may read).
352
- const named = namedRepoInputs(request.brief, options?.allowedRepos ?? (repo => buildIneligible(repo, [], env) === null ? repo : null));
416
+ const named = namedRepoInputs(explicitRead ? `${explicitRead.repo}@${explicitRead.sha}` : request.brief, options?.allowedRepos ?? (repo => buildIneligible(repo, [], env) === null ? repo : null));
353
417
  const hint = 'File it as a backlog row instead, or name owner/repo@FULL_SHA';
354
418
  const refuseNamed = (code, reason) => new Refusal(`${reason}. ${hint}`, 'admission_refused', {code, refused: code});
355
419
  if (named?.refused) {
@@ -392,7 +456,7 @@ async function prepareUnexplained({ cwd, ...request }, options, env) {
392
456
  }
393
457
  }
394
458
  // Identity is the requester's brief only; packed context and notes are presentation and never enter this hash.
395
- let assignment = { ...buildAssignment({ ...request, inputs: context.inputs, build, newFiles, repoScope: build && buildExecution(env) === 'host' }), acp_brief_hash: sha256(request.brief) };
459
+ 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 } : {}) };
396
460
  if (context.packBase) assignment = await packRepoDiff(cwd, assignment, context.packBase, NO_REPO_NOTE);
397
461
  else if (context.untracked && !build) assignment.brief = `${UNTRACKED_NOTE}\n\n${assignment.brief}`;
398
462
  else if (context.note) assignment.brief = `${context.note}\n\n${assignment.brief}`;
@@ -487,7 +551,11 @@ export function buildAssignment({ requestId, brief, inputs, validUntil, build =
487
551
  schema_version: 1, request_id: requestId, brief, inputs,
488
552
  ...(inputs.length ? { scope_paths: build && !repoScope ? buildScope(brief).filter(p => !created.includes(p)) : ['.'] } : {}),
489
553
  ...(inputs.length && created.length ? { output_paths: created } : {}),
490
- expected_output: build ? BUILD_OUTPUT : 'A complete answer as plain text. Put the result in the finish call.',
554
+ expected_output: build ? BUILD_OUTPUT : 'A complete answer as plain text. Put the result in the finish call.' +
555
+ (inputs.length ? ' When asked to run checks, use your own permitted tools on the authorized files at the pinned commit. '+
556
+ 'Use a disposable checkout only if your repository grant permits it, or use the granted scoped file set. '+
557
+ 'Leave the source unchanged and do not push. Record each command and exit code in finish.runs. '+
558
+ 'If the workspace, shell, or other required access is unavailable, report that limit and which checks did not run.' : ''),
491
559
  execution_scope: build ? 'implementation' : 'read-only', valid_until: validUntil,
492
560
  };
493
561
  }
@@ -611,32 +679,58 @@ export const decideHint = rid => `decide: dalan decide ${rid} accepted|applied|u
611
679
  // A build answer includes the worker's result, patch evidence and owner-decision instructions.
612
680
  // patch is the artifact's bytes (Buffer or string) or null when it could not be read.
613
681
  // Publication is best effort: keep all build evidence and the patch on every failure.
614
- export async function materializeBuildResult(row, text, patch, proseCheck, {cwd, getCurrent}) {
682
+ export async function materializeBuildResult(row, text, patch, proseCheck, {cwd, getCurrent, timeoutMs}) {
615
683
  let publication;
616
684
  try {
617
685
  const result=await materialize({id:row.request_id, got:row, dir:cwd, recheck:getCurrent,
618
686
  grantFile:path.join(os.homedir(),'.config/dot-bridge/materialize.json'),
619
- download:async()=>patch, standingOnly:true, fetchBase:true});
687
+ download:async()=>patch, standingOnly:true, fetchBase:true, timeoutMs});
620
688
  publication=result;
621
- } catch(error) { publication='Not published: '+String(error?.message ?? error).replace(/[\r\n]+/g,' '); }
689
+ } catch(error) {
690
+ publication={published:false,reason:publicationFailureText(error),
691
+ remote_effect:error?.remote_effect,cleanup_pending:error?.cleanup_pending===true};
692
+ }
622
693
  return buildResultText(row,text,patch,proseCheck,publication);
623
694
  }
624
695
 
696
+ export function workerRunEvidenceLines(row) {
697
+ const lines = [];
698
+ const runs = (row.worker_runs ?? []).map(run => `${run.command} exit ${run.exit_code}`);
699
+ if (runs.length) lines.push(`worker runs (worker_reported, not checked by the bridge): ${runs.join('; ')}`);
700
+ if (row.worker_run_limit) lines.push(`worker run limit (worker_reported): ${row.worker_run_limit}`);
701
+ return lines;
702
+ }
703
+
625
704
  export function buildResultText(row, text, patch, proseCheck = null, publication = null) {
626
705
  const rid = row.request_id, ev = row.report?.workspace_evidence ?? {}, input = row.assignment?.inputs?.[0] ?? {};
627
- const art = ev.patch_artifact, lines = [text, '', `--- worker build evidence (request ${rid}) ---`, `base: ${input.github_repo ?? '?'}@${ev.base_sha ?? input.base_sha ?? '?'}`];
706
+ const art = ev.patch_artifact;
707
+ const published=publication?.published === true && /^[a-f0-9]{40}$/.test(publication.verified_head_sha ?? '');
708
+ const lines = [];
709
+ if (published) {
710
+ lines.push('Published and verified by Dalan.',
711
+ `Branch: ${publication.branch}`, `Draft PR: ${publication.pr_url}`,
712
+ `Verified head SHA: ${publication.verified_head_sha} (remote head matches the sealed patch and pinned base)`,
713
+ '', 'Worker report (before publication verification):');
714
+ }
715
+ lines.push(text, '', `--- worker build evidence (request ${rid}) ---`, `base: ${input.github_repo ?? '?'}@${ev.base_sha ?? input.base_sha ?? '?'}`);
628
716
  const checks = (ev.checks ?? []).map(c => `${c.check_id} ${c.status}${c.exit_code === null || c.exit_code === undefined ? '' : ` exit ${c.exit_code}`} on diff ${String(c.diff_sha256 ?? '').slice(0, 12)}${c.check_summary?`; ${c.check_summary}`:''}`);
629
717
  const skippedReason=ev.checks_skipped?.at(-1)?.reason;
630
718
  // A check from an older diff does not cover this one: then the skip reason still explains the current diff.
631
719
  const currentChecked = (ev.checks ?? []).some(c => c.applies_to_current_diff === true);
632
720
  lines.push(`worker checks: ${checks.length ? checks.join('; ') : 'none run'}${skippedReason && !currentChecked ? ` (check not run${checks.length ? ' on the current diff' : ''}: ${skippedReason})` : ''}`);
633
- const runs = (row.worker_runs ?? []).map(run => `${run.command} exit ${run.exit_code}`);
634
- if (runs.length) lines.push(`worker runs (worker_reported, not checked by the bridge): ${runs.join('; ')}`);
635
- if (row.worker_run_limit) lines.push(`worker run limit (worker_reported): ${row.worker_run_limit}`);
721
+ lines.push(...workerRunEvidenceLines(row));
636
722
  if (proseCheck) lines.push(proseCheckText(proseCheck));
637
- const published=publication?.published === true && /^[a-f0-9]{40}$/.test(publication.verified_head_sha ?? '');
638
- if (published) lines.push(`Branch: ${publication.branch}\nDraft PR: ${publication.pr_url}\nVerified head SHA: ${publication.verified_head_sha} (remote head matches the sealed patch and pinned base)`);
639
- else if (publication) lines.push(typeof publication === 'string' ? publication : `Not published: ${publication.reason ?? 'head not verified'}`);
723
+ const remote = published ? null : publication?.remote_effect;
724
+ if (remote) {
725
+ lines.push(`Publication unverified: ${publication.reason}`);
726
+ const branchStatus = remote.branch_state === 'push_succeeded' ? 'Branch push succeeded'
727
+ : remote.branch_state === 'observed' ? 'Observed remote branch' : 'Branch push unconfirmed';
728
+ lines.push(`${branchStatus}: ${remote.branch}.`);
729
+ if (remote.draft_attempted) lines.push('A draft pull request may already exist.');
730
+ } else if (!published && publication) {
731
+ lines.push(typeof publication === 'string' ? publication : `Not published: ${publication.reason ?? 'head not verified'}`);
732
+ }
733
+ if (publication?.cleanup_pending) lines.push('Temporary checkout cleanup is pending on the publication host.');
640
734
  if (!art?.artifact_id || !art.size) lines.push('patch: none (empty diff). Nothing to apply.');
641
735
  else {
642
736
  const body = patch === null || patch === undefined ? null : Buffer.from(patch).toString('utf8');
@@ -648,6 +742,10 @@ export function buildResultText(row, text, patch, proseCheck = null, publication
648
742
  lines.push(`Next: review the published draft and its checks. ${decideHint(rid)}`);
649
743
  return lines.join('\n');
650
744
  }
745
+ if (remote) {
746
+ lines.push(`Next: Check the existing branch and any draft before retrying. ${decideHint(rid)}`);
747
+ return lines.join('\n');
748
+ }
651
749
  lines.push(`Next: on a clean checkout of that base, git apply the patch, re-run the tests yourself, push only if they pass. Then record the verdict: dalan accept ${rid}, or dalan reject ${rid} --note '<why>'. The delegation gate offers the worker builds only while these verdicts stay good.`);
652
750
  lines.push(`Or apply it for you: dalan apply ${rid} [--dir <checkout>] (checks the digest and base, then records applied). ${decideHint(rid)}`);
653
751
  return lines.join('\n');
package/src/cli-help.mjs CHANGED
@@ -110,7 +110,7 @@ export const COMMANDS = [
110
110
  { name: 'note', summary: 'Add a note to a job', usage: 'dalan note ID TEXT [--json]' },
111
111
  { name: 'questions', summary: 'List a job\'s open worker questions', usage: 'dalan questions ID [--json]' },
112
112
  { name: 'answer', summary: 'Answer a worker question', usage: 'dalan answer ID QUESTION_ID TEXT [--json]' },
113
- { name: 'tell', summary: 'Send a message to workers', usage: 'dalan tell [--worker NAME] TEXT [--json]' },
113
+ { name: 'tell', summary: 'Send a worker-inbox message, optionally linked to open work', usage: 'dalan tell [--worker NAME] [--work ID] TEXT [--json]' },
114
114
  { name: 'untell', summary: 'Withdraw a message', usage: 'dalan untell MESSAGE_ID [--worker NAME] [--json]' },
115
115
  { name: 'audit', summary: 'Show the audit trail', usage: 'dalan audit [--since RFC3339]' },
116
116
  { name: 'claims', summary: 'List active worker claims', usage: 'dalan claims [--json]' },
package/src/execution.mjs CHANGED
@@ -117,13 +117,17 @@ export function withEvidence(row) {
117
117
  // Committed adapter qualification is independent of per-worker authority grants.
118
118
  export const ADAPTER_QUALIFICATIONS = Object.freeze({
119
119
  mcp: Object.freeze({capabilities: Object.freeze({})}),
120
+ 'registry-questions-v1': Object.freeze({capabilities: Object.freeze({identified_questions: 'verified'})}),
120
121
  'protocol-v0': Object.freeze({capabilities: Object.freeze({identified_questions: 'verified'})}),
121
122
  });
122
123
 
123
- export function admitAdapterCapabilities(adapter, required, catalogProfile) {
124
+ export function admitAdapterCapabilities(adapter, required, catalogProfile, {registryQuestions=false}={}) {
124
125
  const qualification = Object.hasOwn(ADAPTER_QUALIFICATIONS, adapter) ? ADAPTER_QUALIFICATIONS[adapter] : null;
126
+ const profileMatches = adapter === 'protocol-v0' ? catalogProfile === 'protocol-v0'
127
+ : adapter === 'registry-questions-v1' ? catalogProfile === 'batch-claim-v1' && registryQuestions
128
+ : true;
125
129
  for (const name of required ?? []) {
126
- const state = adapter === 'protocol-v0' && catalogProfile !== 'protocol-v0' ? 'unknown' : qualification?.capabilities[name] ?? 'unknown';
130
+ const state = profileMatches ? qualification?.capabilities[name] ?? 'unknown' : 'unknown';
127
131
  if (state !== 'verified') throw new Error(
128
132
  'capability_not_available: ' + name + ' (adapter ' + (adapter ?? 'undeclared') + ' declares ' + state + ')');
129
133
  }
@@ -16,7 +16,7 @@ export function formatGetSummary(job, { id, cli }) {
16
16
  const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
17
17
  const artifacts = (job.artifacts?.length ?? 0) || (job.artifact_ids?.length ?? 0), checks = job.checks?.length ?? 0;
18
18
  if (artifacts || checks) lines.push('', `Evidence: ${[artifacts && count(artifacts, 'artifact'), checks && count(checks, 'check')].filter(Boolean).join(', ')}`);
19
- const next = correctionAction(job, cli) ?? (state === 'finished' ? `${cli} decide ${id} accepted`
19
+ const next = correctionAction(job, cli) ?? (state === 'finished' ? (hasSuccessfulReport(job) ? `${cli} decide ${id} accepted` : null)
20
20
  : state === 'cancelled' ? null
21
21
  : `${cli} wait ${id} --timeout 3600, then ${cli} get ${id}`);
22
22
  if (next) lines.push('', `Next: ${next}`);
@@ -25,11 +25,12 @@ export function formatGetSummary(job, { id, cli }) {
25
25
  }
26
26
 
27
27
  const correctionAction = (job, cli) => job?.revised_by?.request_id ? `${cli} get ${job.revised_by.request_id}` : null;
28
+ const hasSuccessfulReport = job => ['completed', 'done'].includes(job?.report?.outcome);
28
29
 
29
30
  // Piped human output retains the full JSON record and adds only this stderr guidance.
30
31
  export function formatGetEndNote(job, { id, cli, decideWords }) {
31
32
  const correction = correctionAction(job, cli);
32
- return correction ? `Next: ${correction}` : job?.status === 'finished' ? `decide: ${cli} decide ${id} ${decideWords}` : null;
33
+ return correction ? `Next: ${correction}` : job?.status === 'finished' && hasSuccessfulReport(job) ? `decide: ${cli} decide ${id} ${decideWords}` : null;
33
34
  }
34
35
 
35
36
  // `dalan wait` on a terminal: one line, in place of the JSON status document.
@@ -34,7 +34,7 @@ export function hostCheckAuthorization(repo, checkId, expectedSpec = null, assig
34
34
  export function hostCheckRefusal(assignment={}, repo=null, checkId=null, expectedSpec=null,excludedPathsAbsent=false) {
35
35
  const scope=assignment.scope_paths;
36
36
  const narrow=Array.isArray(scope)&&scope.length&&!scope.some(p=>p.replace(/^\.\//,'').replace(/\/$/,'')==='.');
37
- if(narrow||(assignment.scope_excluded?.length&&!excludedPathsAbsent)) {
37
+ if(assignment.paged_read_scope===true||narrow||(assignment.scope_excluded?.length&&!excludedPathsAbsent)) {
38
38
  return 'scope_paths_read_isolation_unavailable: this executor exposes the whole checkout; a check needs an owner-approved repository-wide read grant';
39
39
  }
40
40
  if(sensitivePolicyPaths().error) return 'sensitive_policy_unavailable: restore a valid mode-0600 submission policy before running host checks';
package/src/inbox.mjs CHANGED
@@ -51,10 +51,52 @@ export function buildInbox(states,scope,{cutoff=null}={}) {
51
51
  return {scope,total:items.length,counts,hidden_older,delivered_t3,items,...(unknown.length?{unknown}:{})};
52
52
  }
53
53
 
54
+
55
+ // Keep passive reads bounded without changing wait/mark-read behavior. The
56
+ // caller supplies the non-consuming route, not a fallback to a result fetch.
57
+ export async function readInboxPages(receipts,readPage,{budgetMs=3000,concurrency=3}={}) {
58
+ const pages=[];
59
+ for(let i=0;i===0||i<receipts.length;i+=500) pages.push(receipts.slice(i,i+500));
60
+ const deadline=performance.now()+budgetMs, results=new Array(pages.length);
61
+ let cursor=0;
62
+ await Promise.all(Array.from({length:Math.min(concurrency,pages.length)},async()=>{
63
+ while(cursor<pages.length) {
64
+ const time=Math.floor(deadline-performance.now());
65
+ if(time<=0) return;
66
+ const index=cursor++, page=pages[index];
67
+ try {
68
+ const result=await readPage(page.map(x=>({id:x.id,capability:x.token})),time);
69
+ if(!Array.isArray(result?.states)) throw new Error('invalid inbox page');
70
+ const owned=new Set(page.map(x=>x.id)), states=[];
71
+ for(const state of result.states) if(owned.delete(state?.request_id)) states.push(state);
72
+ results[index]={states,missing:owned.size};
73
+ } catch(error) { results[index]={error}; }
74
+ }
75
+ }));
76
+ const states=[], failed=[];
77
+ let unresolved=0, resolvedPages=0;
78
+ for(const [index,page] of pages.entries()) {
79
+ const part=results[index];
80
+ if(part?.states) {
81
+ resolvedPages++;
82
+ for(const state of part.states) states.push(state);
83
+ if(!part.missing) continue;
84
+ }
85
+ failed.push(index+1);
86
+ unresolved+=part?.missing??page.length;
87
+ }
88
+ const partial = failed.length ? {partial_read:{failed_pages:failed,unresolved_receipts:unresolved}} : {};
89
+ if (resolvedPages > 0) return {states,...partial};
90
+ if (pages.every((_, index) => results[index]?.error?.http_status === 404)) return {legacy:true,states:[]};
91
+ const error = results.find(part => part?.error && part.error.http_status !== 404)?.error;
92
+ return {states,...partial,...(error ? {error} : {})};
93
+ }
94
+
54
95
  export function formatInbox(inbox) {
55
96
  const hidden=inbox.hidden_older?`${inbox.hidden_older} older item${inbox.hidden_older===1?'':'s'} hidden (--since all to show)`:'';
56
- if(!inbox.total) return hidden?`inbox empty\n${hidden}`:'inbox empty';
57
- const lines=[];
97
+ const partial=inbox.partial_read?`Inbox partially read: could not check ${inbox.partial_read.unresolved_receipts} receipt(s) on ${inbox.partial_read.failed_pages.length} page(s). Try again for the full inbox.`:'';
98
+ if(!inbox.total) return [partial||'inbox empty',hidden].filter(Boolean).join('\n');
99
+ const lines=partial?[partial]:[];
58
100
  for(const g of inboxGroups) for(const i of inbox.items.filter(x=>x.group===g)) {
59
101
  const held=i.wake_held?` [wake held: ${i.wake_held.reason}${i.wake_held.detail?`, ${i.wake_held.detail}`:''}; it sends when the parent runs again]`:'';
60
102
  const why=(i.group==='cancelled_unread'?` (${i.reason??'cancelled'})`:i.group==='question'?` ${i.text}`:'')+held;