@promptdriven/runtime-client 1.1.0 → 1.1.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
- // Generated from prompts/cli/runtime-client.prompt.md (sha256: bc46a590b2b1b2fbd0d35e45ea8e329d99805c2d0eff806e55d768ac45916a3e).
1
+ // Generated from prompts/cli/runtime-client.prompt.md (sha256: 8ef3589623ef5027a66fbd6a9bba5957281443d6d2924eb687a9e707082123fd).
2
2
  import { composeProductTry, selectJourneys, productTapCallBound } from './product-composition.mjs';
3
3
  import { bindExistingTry, projectTryCall, projectTryObservation, selectTryToStop } from './try-session.mjs';
4
4
  import {expandSource, parseJsonValue, stringifyJsonValue, jsonNumberIdentity} from './contract-refs.mjs';
@@ -10,6 +10,7 @@ import { compileLocalManifest, validateLocalManifest } from './live-local.mjs';
10
10
  import { rememberSecrets as fallbackRememberSecrets } from './secret-redaction.mjs';
11
11
  import { bindingPlanLines, bindingRefusals } from './runtime-binding-plan.mjs';
12
12
  import { buildCheckPlan, checkPlanResults, checkPlanLines, checkPlanResultLines, selectCheckTests, baselineReport, evaluateCheckBudget } from './runtime-check-plan.mjs';
13
+ import { projectCheckReconciliation } from './runtime-check-reconcile.mjs';
13
14
  import {loadRuntimeWorkspace,allowsRuntimePath,requireRuntimePath,RuntimeWorkspaceError} from './runtime-workspace.mjs';
14
15
  import { failedCheckCount, hasProgress, outcomeDone, outcomeFor, outcomeOverall, outcomeText, progressText, resultOutcome, resultOverall } from './runtime-outcome.mjs';
15
16
  import { acquireRuntimeSlot, recordRuntimeRequest, releaseRuntimeSlot, listRuntimeJobs } from './runtime-slots.mjs';
@@ -27,6 +28,8 @@ import { catalogRecords, compareCopies } from './contract-refs.mjs';
27
28
  import { jsonSafe, parseScenarioJson } from './scenario-json.mjs';
28
29
  import { scenarioDerivationRefusal } from './runtime-preflight.mjs';
29
30
  import { OPEN_STATES, causeText, cleanText, progressTicker, projectAnswer, refusalView, renderJson, renderText, summaryLine, stepTimeLimit, tokenUsageOf, tryUsage, validLink, coverageText } from './runtime-output.mjs';
31
+ import { adaptivePollMs, isSseContentType, parseSseStream, preferWaitHeaders, SSE_IDLE_MS, WAIT_PREFER_CALL_SECONDS, WAIT_PREFER_RUN_SECONDS } from './runtime-stream.mjs';
32
+ import { DEFAULT_CHECK_CONCURRENCY, createAdaptiveConcurrency, recordContention, recordCleanSuccess } from './adaptive-concurrency.mjs';
30
33
 
31
34
  const localInterfaceProblem = problem => ['interface-missing','interface-kind-invalid','native-reason-missing','interface-draft-incomplete','duplicate-selector-word'].includes(problem.code);
32
35
  const unboundPortError = message => Object.assign(new Error(message), { unboundPort: true });
@@ -46,6 +49,12 @@ function formatAdvice(root, visible, paths, workspace) {
46
49
  for (const path of paths) visit(path);
47
50
  return lines;
48
51
  }
52
+ function isPlainProseUiPromptText(text) {
53
+ if (typeof text !== 'string' || !text) return false;
54
+ if (interfaceBlocks(text).length > 0 || text.includes('<summary>Runtime interface</summary>') || text.includes('<pdd-interface>')) return false;
55
+ const low = text.toLowerCase();
56
+ return low.includes('render') || low.includes('<main') || low.includes('html') || low.includes('data-pdd-op');
57
+ }
49
58
  function hasMissingPromptInterface(root, found, startPaths) {
50
59
  const seen = new Set(), queue = [...startPaths];
51
60
  while (queue.length) {
@@ -59,6 +68,29 @@ function hasMissingPromptInterface(root, found, startPaths) {
59
68
  }
60
69
  return false;
61
70
  }
71
+ function hasMissingNonUiPromptInterface(root, found, startPaths) {
72
+ const seen = new Set(), queue = [...startPaths];
73
+ while (queue.length) {
74
+ const path = queue.shift();
75
+ if (typeof path !== 'string' || seen.has(path) || !found.visible.has(path)) continue;
76
+ seen.add(path);
77
+ let prompt;
78
+ try { prompt = readPrompt(root, found.visible, path, found.workspace); } catch { continue; }
79
+ if (prompt.error === 'interface-missing') {
80
+ if (!isPlainProseUiPromptText(prompt.text)) return true;
81
+ continue;
82
+ }
83
+ for (const call of Array.isArray(prompt.interface?.calls) ? prompt.interface.calls : []) if (typeof call?.target === 'string') queue.push(call.target);
84
+ }
85
+ return false;
86
+ }
87
+ function withTryTab(url, tab) {
88
+ try {
89
+ const parsed = new URL(url);
90
+ parsed.searchParams.set('tab', tab);
91
+ return parsed.href;
92
+ } catch { return url; }
93
+ }
62
94
  const diagnosticBatch = record => record?.diagnostic_subset === true || record?.rows?.some(row=>row?.diagnostic_subset === true);
63
95
  const entryPaths = tests => tests.filter(test => !test.error).flatMap(test => (Array.isArray(test.doc?.steps) ? test.doc.steps : []).map(step => step?.entry_path));
64
96
 
@@ -84,6 +116,8 @@ const POST_MS = 90_000, GET_MS = 30_000, TRY_MS = 300_000, MAX_READS = 8, PROGRE
84
116
  const AGENT_WAIT_MIN = 1.5;
85
117
  // Under load a POST can time out and its job appear 3 to 4 min later: read a lost answer's ID for 5 min.
86
118
  const LOST_READ_MS = 300_000;
119
+ // Unresolved prior local batch reservations automatically expire after 24 hours (override via PDD_PRIOR_RESERVATION_TTL_HOURS).
120
+ const PRIOR_RESERVATION_TTL_MS = 24 * 60 * 60 * 1000;
87
121
 
88
122
  class Stop extends Error { constructor(exitCode, message) { super(message); this.exitCode = exitCode; } }
89
123
  function requestedCalls(raw) {
@@ -93,6 +127,53 @@ function requestedCalls(raw) {
93
127
  throw new Stop(2, '--max-calls must be a whole number from 1 to 1000, the interpreter maximum.');
94
128
  return Number(raw);
95
129
  }
130
+ function parseTimeoutMinutes(raw, flagName, { allowZero = false } = {}) {
131
+ if (raw === undefined) return null;
132
+ const value = Number(raw);
133
+ if (typeof raw === 'boolean' || raw === '' || !Number.isFinite(value) || (allowZero ? value < 0 : value <= 0)) {
134
+ throw new Stop(2, `${flagName} must be a positive number of minutes.`);
135
+ }
136
+ return value;
137
+ }
138
+ function batchDeadlineOf(context) {
139
+ if (context.batchDeadline !== undefined) return context.batchDeadline;
140
+ return context.deadline ?? Infinity;
141
+ }
142
+ function rowDeadline(context, row) {
143
+ const batchEnd = batchDeadlineOf(context);
144
+ const storyEnd = row?.story_deadline ?? Infinity;
145
+ return Math.min(batchEnd, storyEnd);
146
+ }
147
+ function rowExpired(context, row, now = context.ports.now()) {
148
+ return now >= rowDeadline(context, row);
149
+ }
150
+ function ensureConcurrencyState(context) {
151
+ if (!context.concurrency) {
152
+ const ceiling = checkConcurrencyLimit(context);
153
+ const initial = Number.isSafeInteger(context.checkWindow) && context.checkWindow >= 1
154
+ ? Math.min(ceiling, context.checkWindow) : ceiling;
155
+ context.concurrency = createAdaptiveConcurrency({ ceiling, initial });
156
+ }
157
+ context.checkWindow = context.concurrency.window;
158
+ return context.concurrency;
159
+ }
160
+ function backoffCheckWindow(context, signalKey = null, reason = 'server busy') {
161
+ if (context.reading) return;
162
+ const state = ensureConcurrencyState(context);
163
+ const transition = recordContention(state, signalKey, { reason });
164
+ context.checkWindow = state.window;
165
+ if (transition.changed) {
166
+ line(context.ports.stderr, `Adaptive concurrency: reducing active check limit from ${transition.previous} to ${transition.current} (${reason}).`);
167
+ }
168
+ }
169
+ function recoverCheckWindow(context, successKey = null) {
170
+ if (context.reading || !context.concurrency) return;
171
+ const transition = recordCleanSuccess(context.concurrency, successKey);
172
+ context.checkWindow = context.concurrency.window;
173
+ if (transition.changed) {
174
+ line(context.ports.stderr, `Adaptive concurrency: increasing active check limit from ${transition.previous} to ${transition.current} after clean completions.`);
175
+ }
176
+ }
96
177
 
97
178
  function sampleOptions(options) {
98
179
  const parse = value => {
@@ -229,7 +310,7 @@ function withDefaults(ports) {
229
310
  return executable ? spawnSync(executable, args, { encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'], timeout: 60_000 })
230
311
  : { status: null, error: { code: 'ENOENT' } };
231
312
  }),
232
- now: ports.now ?? Date.now, randomUUID: ports.randomUUID ?? randomUUID, pollMs: ports.pollMs ?? 2000, postMs: ports.postMs ?? POST_MS,
313
+ now: ports.now ?? Date.now, randomUUID: ports.randomUUID ?? randomUUID, pollMs: ports.pollMs ?? 2000, pollMsExplicit: ports.pollMs !== undefined, pollDelay: elapsedMs => adaptivePollMs(elapsedMs, ports.pollMs), postMs: ports.postMs ?? POST_MS,
233
314
  interactive: ports.interactive ?? (!!process.stdout.isTTY && !!process.stdin.isTTY), watchMs: ports.watchMs ?? 5000, stdin: ports.stdin ?? process.stdin,
234
315
  sleep: ports.sleep ?? ((ms, signal) => new Promise(done => {
235
316
  if (signal?.aborted) { done(); return; }
@@ -555,6 +636,37 @@ async function readBaselineReport(context, plan, identity) {
555
636
  return project(partial ? 'partial' : 'available');
556
637
  }
557
638
 
639
+ const snapshotReferenceMap = references => new Map(references.map(ref => [`${ref.kind}:${ref.target}`, ref.value_json]));
640
+
641
+ function validStorySnapshot(snapshot, story, tests) {
642
+ return isObject(snapshot) && snapshot.story_path === story
643
+ && !(Array.isArray(snapshot.unavailable) && snapshot.unavailable.length > 0)
644
+ && Array.isArray(snapshot.tests) && tests.every(test => snapshot.tests.includes(test))
645
+ && Array.isArray(snapshot.files) && snapshot.files.length > 0
646
+ && snapshot.files.every(file => isObject(file) && typeof file.path === 'string' && /^[a-f0-9]{64}$/.test(file.sha256 ?? ''))
647
+ && Array.isArray(snapshot.references)
648
+ && snapshot.references.every(ref => isObject(ref) && typeof ref.kind === 'string' && typeof ref.target === 'string');
649
+ }
650
+
651
+ function sameStoryFootprint(saved, live) {
652
+ if (!isObject(saved) || !isObject(live) || saved.unavailable?.length || live.unavailable?.length) return false;
653
+ if (!Array.isArray(saved.files) || !Array.isArray(live.files) || !Array.isArray(saved.references) || !Array.isArray(live.references)) return false;
654
+ if (!isDeepStrictEqual(saved.files, live.files)) return false;
655
+ const before = snapshotReferenceMap(saved.references), now = snapshotReferenceMap(live.references);
656
+ if (before.size !== now.size) return false;
657
+ for (const [key, value] of before) if (!now.has(key) || now.get(key) !== value) return false;
658
+ return true;
659
+ }
660
+
661
+ function unsavedPostOutcome(row) {
662
+ return ['not_run', 'busy', 'stop', 'refused'].includes(row.post_verdict)
663
+ || row.recovery_state === 'not_run'
664
+ || row.state === 'not_run'
665
+ || row.state === 'not run'
666
+ || (!row.post_verdict && row.busy === true && (row.recovery_state === 'waiting' || row.state === 'waiting'))
667
+ || (!row.post_verdict && row.recovery_state === 'refused' && Array.isArray(row.refusals) && row.refusals.length > 0);
668
+ }
669
+
558
670
  // Read receipts without StateStore.folder: status must never allocate or mutate runtime state.
559
671
  export async function savedStoryEvidence(input, ports = {}) {
560
672
  return createSavedStoryEvidenceReader(ports)(input);
@@ -602,33 +714,75 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
602
714
  // Older batches saved the display basename; only a unique captured path can recover its identity.
603
715
  const rows = batch.rows.map(row => {
604
716
  if (row.story.endsWith('.md')) return row;
717
+ if (relativeFile(row.story_path) && row.story_path.endsWith('.md') && basename(row.story_path, '.md') === row.story) {
718
+ return { ...row, story: row.story_path };
719
+ }
605
720
  const candidates = [...new Set((Array.isArray(batch.files) ? batch.files : []).filter(file => relativeFile(file)
606
721
  && file.endsWith('.md') && basename(file, '.md') === row.story))];
607
722
  return candidates.length === 1 ? { ...row, story: candidates[0] } : null;
608
723
  });
609
724
  if (rows.some(row => row === null)) { warning(path, Error('missing or ambiguous Story identity')); continue; }
610
- let current = false;
725
+ const selected = new Map(), sent = new Map(), grouped = new Map(), extra = new Map();
726
+ for (const row of rows) {
727
+ if (!selected.has(row.story)) selected.set(row.story, new Set());
728
+ selected.get(row.story).add(row.test);
729
+ }
730
+ const storyCurrent = new Map();
611
731
  if (comparisonRoot !== null && /^[a-f0-9]{64}$/.test(batch.source_sha256 ?? '')) {
612
- try {
613
- const folder = await real(comparisonRoot), tests = [...new Set(batch.rows.map(row => row.test))].sort();
614
- const excludeFixtureProjects = batch.exclude_fixture_projects === true;
615
- const key = JSON.stringify([folder, tests, excludeFixtureProjects]);
616
- if (!captures.has(key)) captures.set(key, Promise.resolve().then(() => capture(folder, { tests, appMap: null, ...(excludeFixtureProjects ? { excludeFixtureProjects: true } : {}) }))
617
- .then(source => ({ sha256: source.sha256 })).catch(error => ({ error })));
618
- const source = await captures.get(key);
619
- if (source.error) throw source.error;
620
- current = source.sha256 === batch.source_sha256;
621
- } catch (error) { if (error?.unboundPort) throw error; warning(path, error); }
732
+ const compareFolder = await real(comparisonRoot);
733
+ const excludeFixtureProjects = batch.exclude_fixture_projects === true;
734
+ const allowMissingInterfaces = batch.lazy_interfaces === true;
735
+ const captureMemo = tests => {
736
+ const key = JSON.stringify([compareFolder, tests, excludeFixtureProjects, ...(allowMissingInterfaces ? [true] : [])]);
737
+ if (!captures.has(key)) captures.set(key, Promise.resolve()
738
+ .then(() => capture(compareFolder, { tests, appMap: null, ...(excludeFixtureProjects ? { excludeFixtureProjects: true } : {}), ...(allowMissingInterfaces ? { allowMissingInterfaces: true } : {}) }))
739
+ .then(source => ({ sha256: source?.sha256, stories: Array.isArray(source?.stories) ? source.stories : null }))
740
+ .catch(error => ({ error })));
741
+ return captures.get(key);
742
+ };
743
+ let batchCurrentPromise = null;
744
+ const getBatchCurrent = () => {
745
+ if (!batchCurrentPromise) batchCurrentPromise = (async () => {
746
+ try {
747
+ const tests = [...new Set(rows.map(row => row.test))].sort();
748
+ const source = await captureMemo(tests);
749
+ if (source.error) throw source.error;
750
+ return source.sha256 === batch.source_sha256;
751
+ } catch (error) {
752
+ if (error?.unboundPort) throw error;
753
+ warning(path, error);
754
+ return false;
755
+ }
756
+ })();
757
+ return batchCurrentPromise;
758
+ };
759
+ const snapshots = Array.isArray(batch.contract_snapshots) ? batch.contract_snapshots : [];
760
+ for (const [story, testSet] of selected) {
761
+ const storyTests = [...testSet].sort();
762
+ const snapshot = snapshots.find(item => validStorySnapshot(item, story, storyTests));
763
+ if (snapshot) {
764
+ try {
765
+ const source = await captureMemo(storyTests);
766
+ if (source.error) throw source.error;
767
+ if (Array.isArray(source.stories)) {
768
+ const live = source.stories.find(item => item?.story_path === story);
769
+ storyCurrent.set(story, sameStoryFootprint(snapshot, live));
770
+ continue;
771
+ }
772
+ } catch (error) {
773
+ if (error?.unboundPort) throw error;
774
+ warning(path, error);
775
+ storyCurrent.set(story, false);
776
+ continue;
777
+ }
778
+ }
779
+ storyCurrent.set(story, await getBatchCurrent());
780
+ }
622
781
  }
623
- const selected = new Map(), sent = new Map(), grouped = new Map(), extra = new Map();
624
782
  // withTests: the failed checks, refusals and states of each Story's rows, and the rows that were never sent.
625
783
  const note = (story, add) => { const was = extra.get(story) ?? { failed: 0, failedSteps: [], refusals: [], states: [], codes: [], fixes: [], sent: false }; extra.set(story, add(was)); };
626
784
  const codesOf = list => Array.isArray(list) ? list.map(item => item?.code).filter(code => typeof code === 'string') : [];
627
785
  const fixesOf = list => Array.isArray(list) ? list.map(item => item?.fix).filter(fix => typeof fix === 'string' && fix.trim()) : [];
628
- for (const row of rows) {
629
- if (!selected.has(row.story)) selected.set(row.story, new Set());
630
- selected.get(row.story).add(row.test);
631
- }
632
786
  for (const row of rows) {
633
787
  note(row.story, was => ({ ...was, refusals: [...new Set([...was.refusals, ...codesOf(row.refusals)])], fixes: [...new Set([...was.fixes, ...fixesOf(row.refusals)])],
634
788
  states: [...new Set([...was.states, ...(typeof row.recovery_state === 'string' ? [row.recovery_state] : [])])],
@@ -637,6 +791,9 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
637
791
  if (!sent.has(row.story)) sent.set(row.story, new Set());
638
792
  sent.get(row.story).add(row.test);
639
793
  let pass = false;
794
+ let rowOwnPassed = false;
795
+ const rowPassedKeys = new Set();
796
+ const rowRequiredKeys = new Set();
640
797
  const id = row.request_ids.at(-1);
641
798
  if (typeof id === 'string' && UUID.test(id)) {
642
799
  const receiptPath = join(folder, `${id}.json`);
@@ -662,12 +819,47 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
662
819
  && view.criteria.passed === row.criteria_total && view.checks?.total > 0 && view.checks.passed === view.checks.total
663
820
  && Array.isArray(criteria) && new Set(criteria.map(item => item?.criterion_id)).size === row.criteria_total
664
821
  && criteria.every(item => authored.includes(item?.criterion_id) && item.status === 'passed');
822
+ const ownUnchecked = new Set(ownNotCheckedOf(row).map(item => item?.criterion_id).filter(Boolean));
823
+ const { keyFor } = rowCriterionKeys(row);
824
+ for (const cid of authored) {
825
+ const key = keyFor(cid);
826
+ if (key) rowRequiredKeys.add(key);
827
+ }
828
+ if (view.state === 'passed' && Number.isInteger(row.criteria_total) && row.criteria_total > 0
829
+ && authored.length === row.criteria_total && view.checks?.total > 0 && view.checks.passed === view.checks.total
830
+ && Array.isArray(criteria) && criteria.every(item => authored.includes(item?.criterion_id) && !['failed', 'unknown'].includes(item?.status))) {
831
+ const passedById = new Set(criteria.filter(item => item?.status === 'passed' && !ownUnchecked.has(item.criterion_id)).map(item => item.criterion_id));
832
+ const ownRequired = authored.filter(cid => !ownUnchecked.has(cid));
833
+ if (ownRequired.length > 0 && ownRequired.every(cid => passedById.has(cid))) {
834
+ rowOwnPassed = true;
835
+ for (const cid of passedById) {
836
+ const key = keyFor(cid);
837
+ if (key) rowPassedKeys.add(key);
838
+ }
839
+ }
840
+ }
665
841
  }
666
- } catch (error) { warning(receiptPath, error); }
842
+ } catch (error) {
843
+ if (!(error?.code === 'ENOENT' && unsavedPostOutcome(row))) warning(receiptPath, error);
844
+ }
667
845
  }
668
846
  const at = Number.isFinite(row.ended_at) ? row.ended_at : Date.parse(batch.created_at) || 0;
669
847
  const previous = grouped.get(row.story);
670
- grouped.set(row.story, { story: row.story, pass: pass && (previous?.pass ?? true), current, result: 'no verdict', at: Math.max(previous?.at ?? at, at) });
848
+ const current = storyCurrent.get(row.story) ?? false;
849
+ const passedKeys = previous?.passedKeys ?? new Set();
850
+ for (const key of rowPassedKeys) passedKeys.add(key);
851
+ const requiredKeys = previous?.requiredKeys ?? new Set();
852
+ for (const key of rowRequiredKeys) requiredKeys.add(key);
853
+ grouped.set(row.story, {
854
+ story: row.story,
855
+ pass: pass && (previous?.pass ?? true),
856
+ ownPassed: rowOwnPassed && (previous?.ownPassed ?? true),
857
+ passedKeys,
858
+ requiredKeys,
859
+ current,
860
+ result: 'no verdict',
861
+ at: Math.max(previous?.at ?? at, at),
862
+ });
671
863
  }
672
864
  // withTests: pdd's own fix texts of a Story's refusals (its saved warnings, then each refusal's fix).
673
865
  const advised = story => {
@@ -677,14 +869,19 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
677
869
  return { ...info, advice: [...new Set([...warned, ...fixes])].slice(0, 3).map(text => text.slice(0, 800)) };
678
870
  };
679
871
  for (const row of grouped.values()) {
680
- if (row.pass && sent.get(row.story).size !== selected.get(row.story).size) continue;
681
- if (row.pass) row.result = '✓';
682
- stories.push(withTests ? { ...row, tests: [...selected.get(row.story)].sort(), ...advised(row.story), sent: true } : row);
872
+ const siblingCount = selected.get(row.story)?.size ?? 0;
873
+ const sentCount = sent.get(row.story)?.size ?? 0;
874
+ const unionPass = siblingCount > 1 && sentCount === siblingCount && row.ownPassed
875
+ && row.requiredKeys.size > 0 && [...row.requiredKeys].every(key => row.passedKeys.has(key));
876
+ const storyPass = row.pass || unionPass;
877
+ if (storyPass && sentCount !== siblingCount) continue;
878
+ const entry = { story: row.story, pass: storyPass, current: row.current, result: storyPass ? '✓' : 'no verdict', at: row.at };
879
+ stories.push(withTests ? { ...entry, tests: [...selected.get(row.story)].sort(), ...advised(row.story), sent: true } : entry);
683
880
  }
684
881
  // withTests: a Story whose tests were never sent (refused before execution, interrupted) is listed too.
685
882
  if (withTests) for (const story of extra.keys()) if (!grouped.has(story)) {
686
883
  const at = Math.max(0, ...rows.filter(row => row.story === story).map(row => Number.isFinite(row.ended_at) ? row.ended_at : Date.parse(batch.created_at) || 0));
687
- stories.push({ story, pass: false, current, result: 'not sent', at, tests: [...selected.get(story)].sort(), ...advised(story), sent: false });
884
+ stories.push({ story, pass: false, current: storyCurrent.get(story) ?? false, result: 'not sent', at, tests: [...selected.get(story)].sort(), ...advised(story), sent: false });
688
885
  }
689
886
  }
690
887
  return { stories, warnings: [...new Set(warnings)] };
@@ -941,6 +1138,60 @@ class StateStore {
941
1138
  unlinkSync(join(this.dir, 'github-user.json'));
942
1139
  } catch { /* ignore absent or unremovable cache file */ }
943
1140
  }
1141
+ originKey(origin) { return createHash('sha256').update(String(origin)).digest('hex').slice(0, 16); }
1142
+ readOriginCapabilities(origin, now = Date.now()) {
1143
+ try {
1144
+ if (typeof origin !== 'string' || !origin || statOrNull(this.dir)?.isSymbolicLink()) return null;
1145
+ const dir = join(this.dir, 'origin-capabilities');
1146
+ if (statOrNull(dir)?.isSymbolicLink()) return null;
1147
+ const path = join(dir, `${this.originKey(origin)}.json`), stat = statOrNull(path);
1148
+ if (!stat?.isFile() || stat.isSymbolicLink()) return null;
1149
+ const record = JSON.parse(readFileSync(path, 'utf8'));
1150
+ if (!isObject(record) || record.origin !== origin || record.lazy_interfaces !== true) return null;
1151
+ if (!Array.isArray(record.features) || !record.features.every(item => typeof item === 'string') || !record.features.includes('lazy-interfaces')) return null;
1152
+ const observedAt = Date.parse(record.observed_at);
1153
+ if (!Number.isFinite(observedAt) || now - observedAt > CAPABILITY_CACHE_TTL_MS) return null;
1154
+ return { origin, lazy_interfaces: true, features: record.features, engine_sha: typeof record.engine_sha === 'string' ? record.engine_sha : null, observed_at: record.observed_at };
1155
+ } catch { return null; }
1156
+ }
1157
+ writeOriginCapabilities(origin, { features, engine_sha = null } = {}, now = Date.now()) {
1158
+ if (typeof origin !== 'string' || !origin) return false;
1159
+ if (!Array.isArray(features) || !features.every(item => typeof item === 'string') || !features.includes('lazy-interfaces')) {
1160
+ this.deleteOriginCapabilities(origin);
1161
+ return false;
1162
+ }
1163
+ let folder;
1164
+ try {
1165
+ if (statOrNull(this.dir)?.isSymbolicLink()) return false;
1166
+ const dir = join(this.dir, 'origin-capabilities');
1167
+ if (statOrNull(dir)?.isSymbolicLink()) return false;
1168
+ folder = this.folder('origin-capabilities');
1169
+ } catch { return false; }
1170
+ const path = join(folder, `${this.originKey(origin)}.json`);
1171
+ if (statOrNull(path)?.isSymbolicLink()) return false;
1172
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
1173
+ let text = `${JSON.stringify({ origin, lazy_interfaces: true, features, engine_sha: typeof engine_sha === 'string' ? engine_sha : null, observed_at: new Date(now).toISOString() }, null, 2)}\n`;
1174
+ for (const secret of this.secrets) if (secret) text = text.split(secret).join('[secret]');
1175
+ try {
1176
+ const fd = openSync(temporary, 'wx', 0o600);
1177
+ try { chmodSync(temporary, 0o600); writeSync(fd, text); } finally { closeSync(fd); }
1178
+ renameSync(temporary, path);
1179
+ return true;
1180
+ } catch {
1181
+ try { unlinkSync(temporary); } catch { /* ignore temp cleanup failure */ }
1182
+ return false;
1183
+ }
1184
+ }
1185
+ deleteOriginCapabilities(origin) {
1186
+ try {
1187
+ if (typeof origin !== 'string' || !origin || statOrNull(this.dir)?.isSymbolicLink()) return;
1188
+ const dir = join(this.dir, 'origin-capabilities');
1189
+ if (statOrNull(dir)?.isSymbolicLink()) return;
1190
+ const path = join(dir, `${this.originKey(origin)}.json`);
1191
+ if (statOrNull(path)?.isSymbolicLink()) return;
1192
+ unlinkSync(path);
1193
+ } catch { /* ignore absent or unremovable cache file */ }
1194
+ }
944
1195
  // Exclusive create: a second POST with the same request ID is impossible.
945
1196
  posted(folder, id) {
946
1197
  const fd = openSync(join(folder, `${id}.posted`), 'wx', 0o600);
@@ -1189,7 +1440,13 @@ const unadmittedCallErrors = new WeakMap();
1189
1440
 
1190
1441
  // HTTP to the runtime. The token stays in this object and in request headers only.
1191
1442
  class Runtime {
1192
- constructor({ origin, token, ports, signal, auth, programJson = false }) { Object.assign(this, { origin, token, ports, signal, auth, programJson }); this.sources = new WeakMap(); }
1443
+ constructor({ origin, token, ports, signal, auth, programJson = false }) {
1444
+ Object.assign(this, { origin, token, ports, signal, auth, programJson });
1445
+ this.sources = new WeakMap();
1446
+ this.uploadedSources = new Set();
1447
+ this.uploadingSources = new Map();
1448
+ this.sourceUploadDisabled = false;
1449
+ }
1193
1450
  async sendOnce(path, init, ms) {
1194
1451
  const readSignal = init?.method === 'GET' ? init.signal : null;
1195
1452
  if (this.signal?.aborted || readSignal?.aborted) return { lost: true };
@@ -1209,9 +1466,10 @@ class Runtime {
1209
1466
  } catch (error) { return lostReply(error, this.origin); } finally { clearTimeout(timer); this.signal?.removeEventListener('abort', stop); readSignal?.removeEventListener('abort', stop); }
1210
1467
  }
1211
1468
  async send(path, init, ms) {
1469
+ const pathname = path.split('?')[0];
1212
1470
  const previousToken = this.auth?.identity.token ?? this.token;
1213
1471
  const first = await this.sendOnce(path, init, ms);
1214
- if (this.auth && path !== '/v1/capacity' && [200, 202].includes(first.status)) this.auth.verifiedByServer = true;
1472
+ if (this.auth && pathname !== '/v1/capacity' && [200, 202].includes(first.status)) this.auth.verifiedByServer = true;
1215
1473
  if (first.status !== 401 || !this.auth) return first;
1216
1474
  this.auth.store?.deleteGithubUser();
1217
1475
  if (!this.auth.identity.fromCache || this.auth.identity.refreshedAfter401) return first;
@@ -1227,11 +1485,11 @@ class Runtime {
1227
1485
  } catch (error) {
1228
1486
  if (error instanceof Stop) { this.auth.store?.deleteGithubUser(); return first; }
1229
1487
  // The initial 401 refused execution, and refresh failed before a retry.
1230
- if (init?.method === 'POST' && (path === '/v1/try' || /^\/v1\/try\/[^/]+\/call$/.test(path) || /\/screen\/api\/(act|app\/open)$/.test(path))) {
1488
+ if (init?.method === 'POST' && (pathname === '/v1/try' || /^\/v1\/try\/[^/]+\/call$/.test(pathname) || /\/screen\/api\/(act|app\/open)$/.test(pathname))) {
1231
1489
  if (error === null || !['object', 'function'].includes(typeof error)) error = new Error(String(error));
1232
- if (path === '/v1/try') unadmittedTryErrors.add(error);
1233
- if (/\/screen\/api\/(act|app\/open)$/.test(path)) unadmittedScreenErrors.add(error);
1234
- if (/^\/v1\/try\/[^/]+\/call$/.test(path)) unadmittedCallErrors.set(this, error);
1490
+ if (pathname === '/v1/try') unadmittedTryErrors.add(error);
1491
+ if (/\/screen\/api\/(act|app\/open)$/.test(pathname)) unadmittedScreenErrors.add(error);
1492
+ if (/^\/v1\/try\/[^/]+\/call$/.test(pathname)) unadmittedCallErrors.set(this, error);
1235
1493
  }
1236
1494
  throw error;
1237
1495
  }
@@ -1242,8 +1500,8 @@ class Runtime {
1242
1500
  const expectedOwner = typeof this.auth.expectedOwnerLogin === 'function' ? this.auth.expectedOwnerLogin() : this.auth.expectedOwnerLogin;
1243
1501
  if (expectedOwner && refreshed.login !== expectedOwner) {
1244
1502
  const error = this.auth.ownerMismatchError(expectedOwner);
1245
- if (path === '/v1/try' && init?.method === 'POST') unadmittedTryErrors.add(error);
1246
- if (init?.method === 'POST' && /\/screen\/api\/(act|app\/open)$/.test(path)) unadmittedScreenErrors.add(error);
1503
+ if (pathname === '/v1/try' && init?.method === 'POST') unadmittedTryErrors.add(error);
1504
+ if (init?.method === 'POST' && /\/screen\/api\/(act|app\/open)$/.test(pathname)) unadmittedScreenErrors.add(error);
1247
1505
  throw error;
1248
1506
  }
1249
1507
  if (this.auth.verifiedByServer && refreshed.token === previousToken) {
@@ -1252,10 +1510,96 @@ class Runtime {
1252
1510
  }
1253
1511
  const retry = await this.sendOnce(path, init, ms);
1254
1512
  if (retry.status === 401) this.auth.store?.deleteGithubUser();
1255
- else if (path !== '/v1/capacity' && [200, 202].includes(retry.status)) this.auth.verifiedByServer = true;
1513
+ else if (pathname !== '/v1/capacity' && [200, 202].includes(retry.status)) this.auth.verifiedByServer = true;
1256
1514
  return retry;
1257
1515
  }
1258
- post(path, request, tar, timeoutMs = this.ports.postMs) {
1516
+ async streamOnce(path, init, { timeoutMs = GET_MS, idleMs = SSE_IDLE_MS, onEvent, signal } = {}) {
1517
+ const readSignal = signal ?? (init?.method === 'GET' ? init.signal : null);
1518
+ if (this.signal?.aborted || readSignal?.aborted) return { streamed: false, lost: true };
1519
+ const controller = new AbortController(), stop = () => controller.abort();
1520
+ const headerTimer = setTimeout(stop, Math.min(GET_MS, Number.isFinite(timeoutMs) ? Math.max(1, timeoutMs) : GET_MS));
1521
+ const overallTimer = Number.isFinite(timeoutMs) && timeoutMs > 0 ? setTimeout(stop, timeoutMs) : null;
1522
+ this.signal?.addEventListener('abort', stop, { once: true });
1523
+ readSignal?.addEventListener('abort', stop, { once: true });
1524
+ const bearer = this.auth?.identity.token ?? this.token;
1525
+ const resolved = typeof init?.body === 'function' ? { ...init, body: init.body() } : init;
1526
+ try {
1527
+ const response = await this.ports.fetch(new URL(path, this.origin), { ...resolved, redirect: 'manual', signal: controller.signal,
1528
+ headers: { Accept: 'text/event-stream, application/json', ...resolved?.headers, Authorization: `Bearer ${bearer}` } });
1529
+ clearTimeout(headerTimer);
1530
+ if (response.status === 200 && isSseContentType(response.headers) && typeof response.body?.getReader === 'function') {
1531
+ const parseJson = this.programJson ? parseProgramJson : JSON.parse;
1532
+ const result = await parseSseStream(response.body, { onEvent, signal: controller.signal, idleMs, parseJson });
1533
+ return { streamed: true, status: response.status, headers: response.headers, ...result };
1534
+ }
1535
+ const text = await response.text();
1536
+ let json = null;
1537
+ try { json = this.programJson ? parseProgramJson(text) : JSON.parse(text); } catch { json = null; }
1538
+ return { streamed: false, status: response.status, headers: response.headers, text, json };
1539
+ } catch (error) { return { streamed: false, ...lostReply(error, this.origin) }; }
1540
+ finally { clearTimeout(headerTimer); if (overallTimer) clearTimeout(overallTimer); this.signal?.removeEventListener('abort', stop); readSignal?.removeEventListener('abort', stop); }
1541
+ }
1542
+ async stream(path, init = {}, options = {}) {
1543
+ const pathname = path.split('?')[0];
1544
+ const previousToken = this.auth?.identity.token ?? this.token;
1545
+ const first = await this.streamOnce(path, init, options);
1546
+ if (this.auth && pathname !== '/v1/capacity' && [200, 202].includes(first.status)) this.auth.verifiedByServer = true;
1547
+ if (first.streamed || first.status !== 401 || !this.auth) return first;
1548
+ this.auth.store?.deleteGithubUser();
1549
+ if (!this.auth.identity.fromCache || this.auth.identity.refreshedAfter401) return first;
1550
+ this.auth.identity.fromCache = false;
1551
+ this.auth.identity.refreshedAfter401 = true;
1552
+ let refreshed;
1553
+ try {
1554
+ refreshed = signIn(this.ports.gh, this.auth.store, this.ports, {
1555
+ forceRefresh: true,
1556
+ afterHttp401: true,
1557
+ exitCode: this.auth.signInExitCode,
1558
+ });
1559
+ } catch (error) {
1560
+ if (error instanceof Stop) { this.auth.store?.deleteGithubUser(); return first; }
1561
+ throw error;
1562
+ }
1563
+ Object.assign(this.auth.identity, refreshed, { fromCache: false, refreshedAfter401: true });
1564
+ this.token = refreshed.token;
1565
+ if (Array.isArray(this.auth.secrets) && !this.auth.secrets.includes(refreshed.token)) this.auth.secrets.push(refreshed.token);
1566
+ await this.auth.onRefresh?.(this.auth.identity);
1567
+ const expectedOwner = typeof this.auth.expectedOwnerLogin === 'function' ? this.auth.expectedOwnerLogin() : this.auth.expectedOwnerLogin;
1568
+ if (expectedOwner && refreshed.login !== expectedOwner) throw this.auth.ownerMismatchError(expectedOwner);
1569
+ if (this.auth.verifiedByServer && refreshed.token === previousToken) {
1570
+ this.auth.store?.deleteGithubUser();
1571
+ return first;
1572
+ }
1573
+ const retry = await this.streamOnce(path, init, options);
1574
+ if (retry.status === 401) this.auth.store?.deleteGithubUser();
1575
+ else if (pathname !== '/v1/capacity' && [200, 202].includes(retry.status)) this.auth.verifiedByServer = true;
1576
+ return retry;
1577
+ }
1578
+ async uploadSource(sha256Hex, tar, timeoutMs = this.ports.postMs) {
1579
+ if (this.sourceUploadDisabled || !tar || typeof sha256Hex !== 'string' || !/^[a-f0-9]{64}$/.test(sha256Hex)) return false;
1580
+ if (this.uploadedSources.has(sha256Hex)) return true;
1581
+ if (this.uploadingSources.has(sha256Hex)) return this.uploadingSources.get(sha256Hex);
1582
+ const pending = (async () => {
1583
+ let source = this.sources.get(tar);
1584
+ if (!source) { source = new Blob([tar], { type: 'application/x-tar' }); this.sources.set(tar, source); }
1585
+ const reply = await this.send('/v1/sources', {
1586
+ method: 'POST',
1587
+ headers: { 'Content-Type': 'application/x-tar', 'X-Source-Sha256': sha256Hex },
1588
+ body: () => source,
1589
+ }, timeoutMs);
1590
+ if (reply.status === 200 && reply.json?.source_sha256 === sha256Hex) {
1591
+ this.uploadedSources.add(sha256Hex);
1592
+ return true;
1593
+ }
1594
+ if ([404, 405, 415, 501].includes(reply.status)) this.sourceUploadDisabled = true;
1595
+ return false;
1596
+ })().finally(() => {
1597
+ if (this.uploadingSources.get(sha256Hex) === pending) this.uploadingSources.delete(sha256Hex);
1598
+ });
1599
+ this.uploadingSources.set(sha256Hex, pending);
1600
+ return pending;
1601
+ }
1602
+ async post(path, request, tar, timeoutMs = this.ports.postMs, options = undefined) {
1259
1603
  const makeForm = () => {
1260
1604
  const form = new FormData();
1261
1605
  form.set('request', new Blob([JSON.stringify(request)], { type: 'application/json' }), 'request.json');
@@ -1264,9 +1608,47 @@ class Runtime {
1264
1608
  form.set('source', source, 'source.tar');
1265
1609
  return form;
1266
1610
  };
1267
- return this.send(path, { method: 'POST', body: makeForm }, timeoutMs);
1611
+ const sha = options?.dedup === true && !this.sourceUploadDisabled && tar && typeof request?.source_sha256 === 'string' && /^[a-f0-9]{64}$/.test(request.source_sha256)
1612
+ ? request.source_sha256 : null;
1613
+ const postInline = async () => {
1614
+ const reply = await this.send(path, { method: 'POST', body: makeForm }, timeoutMs);
1615
+ if (sha && [200, 202].includes(reply.status)) this.uploadedSources.add(sha);
1616
+ return reply;
1617
+ };
1618
+ if (!sha) return postInline();
1619
+ if (options?.inlineFirst === true && !this.uploadedSources.has(sha)) return postInline();
1620
+ if (!this.uploadedSources.has(sha)) {
1621
+ const uploaded = await this.uploadSource(sha, tar, timeoutMs);
1622
+ if (!uploaded) return postInline();
1623
+ }
1624
+ const reply = await this.send(path, {
1625
+ method: 'POST',
1626
+ headers: { 'Content-Type': 'application/json' },
1627
+ body: () => JSON.stringify(request),
1628
+ }, timeoutMs);
1629
+ const code = reply.json?.error?.code ?? reply.json?.code;
1630
+ if ([404, 409, 422].includes(reply.status) && code === 'source-not-found'
1631
+ && reply.json?.job_created !== true && reply.json?.dispatch !== 'unknown') {
1632
+ this.uploadedSources.delete(sha);
1633
+ return postInline();
1634
+ }
1635
+ if (reply.status === 415 && code === 'unsupported-content-type'
1636
+ && reply.json?.job_created !== true && reply.json?.dispatch !== 'unknown') {
1637
+ this.sourceUploadDisabled = true;
1638
+ this.uploadedSources.delete(sha);
1639
+ return postInline();
1640
+ }
1641
+ return reply;
1642
+ }
1643
+ get(id, timeoutMs = GET_MS, { waitSeconds = 0 } = {}) {
1644
+ const headers = waitSeconds > 0 ? preferWaitHeaders(waitSeconds) : undefined;
1645
+ const ms = waitSeconds > 0 ? Math.max(timeoutMs, waitSeconds * 1000 + 10_000) : timeoutMs;
1646
+ return this.send(`/v1/runs/${id}`, { method: 'GET', ...(headers ? { headers } : {}) }, ms);
1647
+ }
1648
+ streamRun(id, options = {}) {
1649
+ const path = options.useEventsPath ? `/v1/runs/${id}/events` : `/v1/runs/${id}`;
1650
+ return this.stream(path, { method: 'GET' }, options);
1268
1651
  }
1269
- get(id, timeoutMs = GET_MS) { return this.send(`/v1/runs/${id}`, { method: 'GET' }, timeoutMs); }
1270
1652
  reopen(id) { return this.send(`/v1/try/${id}/reopen`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }, this.ports.postMs); }
1271
1653
  stop(tryId, requestId) { return this.send(`/v1/try/${tryId}`, { method: 'DELETE', headers: { 'X-Request-Id': requestId } }, this.ports.postMs); }
1272
1654
  }
@@ -1335,12 +1717,22 @@ export async function checkRuntimeHealth({ env = process.env } = {}, givenPorts
1335
1717
  // Only capacity refusals that prove no execution can authorize a fresh check ID.
1336
1718
  function capacityDelay(refusal, headers) {
1337
1719
  const code = refusal?.code ?? '';
1338
- const capacity = /(?:^|-)(?:queue|capacity|busy)(?:-|$)|^server-full$/.test(code);
1339
- if (!capacity || (code !== 'check-queue-timeout' && code !== 'server-full' && refusal.details?.retryable !== true)) return null;
1720
+ const capacity = /(?:^|-)(?:queue|capacity|busy)(?:-|$)|^(?:server-full|rate-limited)$/.test(code);
1721
+ if (!capacity) return null;
1722
+ const retryable = code === 'check-queue-timeout' || code === 'server-full' || refusal?.details?.retryable === true
1723
+ || (code === 'rate-limited' && refusal?.details?.retryable !== false && (Boolean(headers?.get?.('retry-after')) || typeof refusal?.details?.retry_after === 'number'));
1724
+ if (!retryable) return null;
1340
1725
  if (headers?.get?.('retry-after')) return retryAfter(headers);
1341
- const seconds = refusal.details?.retry_after;
1726
+ const seconds = refusal?.details?.retry_after;
1342
1727
  return (typeof seconds === 'number' && Number.isFinite(seconds) && seconds > 0 ? Math.min(300, Math.max(1, seconds)) : 5) * 1000;
1343
1728
  }
1729
+ function preAdmissionRateLimited(record) {
1730
+ if (!isObject(record) || record.error?.code !== 'rate-limited') return false;
1731
+ if (record.dispatch !== 'not_started' || record.job_created !== false || record.state !== 'refused') return false;
1732
+ if (record.error?.details?.retryable === false) return false;
1733
+ return ['usage', 'report', 'result', 'provider_calls', 'accounting_complete', 'calls', 'known_calls', 'unknown_calls', 'checks']
1734
+ .every(key => !Object.hasOwn(record, key));
1735
+ }
1344
1736
  function safeAdmission(reply) {
1345
1737
  const json = reply.json, report = json?.result?.report;
1346
1738
  return !(json?.usage && Object.hasOwn(json.usage, 'calls') && json.usage.calls !== 0)
@@ -1348,6 +1740,7 @@ function safeAdmission(reply) {
1348
1740
  && !(report && Object.hasOwn(report, 'provider_calls') && report.provider_calls !== 0) && !report?.samples?.some(sample => sample?.steps?.some(step => step?.checks?.length));
1349
1741
  }
1350
1742
  function accountingProof(record) {
1743
+ if (preAdmissionRateLimited(record)) return true;
1351
1744
  const usage = record?.usage, result = record?.result, reports = [record?.report, result?.report].filter(isObject);
1352
1745
  if (!isObject(usage)) return false;
1353
1746
  const supplied = (object, key) => isObject(object) && Object.hasOwn(object, key);
@@ -1393,7 +1786,8 @@ function checkCapacity(answer, headers) {
1393
1786
  return capacityRefusal([answer.result?.report?.refusal, ...(Array.isArray(answer.result?.refusals) ? answer.result.refusals : [])], headers);
1394
1787
  }
1395
1788
  function admissionCapacityCandidate(record, headers) {
1396
- return capacityDelay(record?.error, headers) !== null || record?.error?.code === 'maintenance';
1789
+ return capacityDelay(record?.error, headers) !== null || record?.error?.code === 'maintenance'
1790
+ || (record?.error?.code === 'rate-limited' && record?.dispatch === 'not_started' && record?.error?.details?.retryable !== false);
1397
1791
  }
1398
1792
  function isAdmissionCapacityRecord(record) {
1399
1793
  return isObject(record) && isObject(record.error);
@@ -1401,8 +1795,8 @@ function isAdmissionCapacityRecord(record) {
1401
1795
  function admissionMatches(record, id) {
1402
1796
  if (!isObject(record)) return false;
1403
1797
  for (const surface of [record, record.result].filter(isObject)) {
1404
- for (const key of ['requestId', 'id']) if (Object.hasOwn(surface, key) && surface[key] !== id) return false;
1405
- if (Object.hasOwn(surface, 'command') && surface.command !== 'check') return false;
1798
+ for (const key of ['requestId', 'id']) if (surface[key] != null && surface[key] !== id) return false;
1799
+ if (surface.command != null && surface.command !== 'check') return false;
1406
1800
  }
1407
1801
  return true;
1408
1802
  }
@@ -1484,6 +1878,9 @@ function capacityRetryAllowed(context, row) {
1484
1878
  return terminal.length > 0 && terminal.every(answer => checkCapacityCandidate(answer) && accountingProof(answer));
1485
1879
  }
1486
1880
  function usagePart(record) {
1881
+ if (preAdmissionRateLimited(record)) {
1882
+ return { known: 0, unknown: 0, complete: true, total: 0, zeroWork: true, tokens: tokenUsageOf(record, { incomplete: false }) };
1883
+ }
1487
1884
  const usage = isObject(record?.usage) ? record.usage : {}, result = isObject(record?.result) ? record.result : {}, reports = [record?.report, result?.report].filter(isObject);
1488
1885
  const counter = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined;
1489
1886
  const surfaces = [record, usage, result, ...reports];
@@ -1596,7 +1993,7 @@ function markBusy(context, row, wait, observedAt = context.ports.now(), legacy =
1596
1993
  checks: null, criteria: null, all_checks: [], failed_checks: [], why: null, next_step: null,
1597
1994
  note: { code: 'check-busy', message: 'The interpreter is busy. No checks ran for this attempt. Retry this batch later.' } });
1598
1995
  Object.assign(row, accumulatedAccounting(context, row));
1599
- if (!context.reading) context.checkWindow = 1;
1996
+ if (!context.reading) backoffCheckWindow(context, id ?? `${row.test}:${row.request_ids.length}`, 'server busy / 429');
1600
1997
  }
1601
1998
 
1602
1999
  const restarted = answer => answer?.command === 'check' && answer.state === 'unknown' && [answer.result?.report?.refusal, ...(Array.isArray(answer.result?.refusals) ? answer.result.refusals : [])].some(item => item?.code === 'service-restarted');
@@ -1668,9 +2065,13 @@ function localLimit(context) {
1668
2065
  if (raw === undefined) return context.localLimit = Infinity;
1669
2066
  const value = Number(raw);
1670
2067
  if (/^[1-9][0-9]*$/.test(String(raw)) && Number.isSafeInteger(value)) return context.localLimit = value;
1671
- line(context.ports.stderr, 'Warning: PDD_MAX_JOBS must be a positive safe integer; using no local cap.');
2068
+ line(context.ports.stderr, `Warning: PDD_MAX_JOBS must be a positive safe integer; using default concurrency (${DEFAULT_CHECK_CONCURRENCY}) and no local cap.`);
1672
2069
  return context.localLimit = Infinity;
1673
2070
  }
2071
+ function checkConcurrencyLimit(context) {
2072
+ const limit = localLimit(context);
2073
+ return Number.isFinite(limit) ? limit : DEFAULT_CHECK_CONCURRENCY;
2074
+ }
1674
2075
  function uploadLimit(context) {
1675
2076
  if (context.uploadLimit !== undefined) return context.uploadLimit;
1676
2077
  const raw = context.ports.env.PDD_MAX_UPLOADS;
@@ -1816,38 +2217,125 @@ async function readCapacity(context, deadline, refresh) {
1816
2217
  }
1817
2218
  }
1818
2219
  }
2220
+ const CAPABILITY_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
2221
+ const CAPACITY_PROBE_ATTEMPTS = 3;
2222
+ const CAPACITY_PROBE_ATTEMPT_MS = 10_000;
2223
+ const CAPACITY_PROBE_BACKOFF_MS = [250, 750];
2224
+
2225
+ function capacityStopMessage(reply) {
2226
+ if (!reply || reply.lost) return null;
2227
+ const blocked = blockingAnswer(reply);
2228
+ return blocked || (reply.status === 401 ? AUTH_TEXT : gateText(reply) ? 'The runtime opens soon.' : null);
2229
+ }
2230
+ function isDefinitiveCapacityReply(reply) {
2231
+ if (!reply || reply.lost) return false;
2232
+ if (reply.status === 200 && isObject(reply.json) && (Array.isArray(reply.json.features) || Object.hasOwn(reply.json, 'maintenance'))) return true;
2233
+ return reply.status === 404 && isObject(reply.json);
2234
+ }
2235
+ function isRetryableCapacityFailure(reply) {
2236
+ if (reply === null) return true;
2237
+ if (reply.lost) return !reply.unreachable;
2238
+ return reply.status === 408 || reply.status === 429 || reply.status >= 500;
2239
+ }
2240
+ function capacityProbeDelay(reply, attempt) {
2241
+ const fallback = CAPACITY_PROBE_BACKOFF_MS[Math.min(attempt, CAPACITY_PROBE_BACKOFF_MS.length - 1)];
2242
+ if (!reply || reply.lost || ![429, 503].includes(reply.status)) return fallback;
2243
+ const raw = reply.headers?.get?.('retry-after'), seconds = Number(raw);
2244
+ if (raw && /^\d+$/.test(raw.trim()) && Number.isFinite(seconds) && seconds > 0) {
2245
+ return Math.min(2_000, Math.max(200, seconds * 1000));
2246
+ }
2247
+ return fallback;
2248
+ }
2249
+ function shouldSendLazyInterfaces(context) {
2250
+ if (context.serverFeatures?.includes('lazy-interfaces')) return true;
2251
+ return context.allowMissingInterfaces === true && context.capacityDefinitive !== true;
2252
+ }
1819
2253
  async function probeLazyInterfaces(context, origin, store) {
1820
2254
  if (context.lazyInterfacesProbed) return !!context.allowMissingInterfaces;
1821
2255
  context.lazyInterfacesProbed = true;
1822
- let identity;
1823
- try { identity = signIn(context.ports.gh, store, context.ports, { exitCode: context.doorMode ? 125 : 5 }); }
1824
- catch (error) { if (error instanceof Stop) return false; throw error; }
1825
- if(context.liveLocal)context.localOwner??=identity.login;
1826
- const auth = authSession({ identity, store, ports: context.ports, signInExitCode: context.doorMode ? 125 : 5, ...(context.liveLocal?{expectedOwnerLogin:context.localOwner,ownerMismatchError:()=>new Stop(5,'live-local-owner-changed')}:{}) });
2256
+ let identity = context.identity ?? null;
2257
+ if (!identity) {
2258
+ try { identity = signIn(context.ports.gh, store, context.ports, { exitCode: context.doorMode ? 125 : 5 }); }
2259
+ catch (error) { if (error instanceof Stop) return false; throw error; }
2260
+ }
2261
+ if (context.liveLocal) context.localOwner ??= identity.login;
2262
+ const auth = context.auth ?? authSession({ identity, store, ports: context.ports, signInExitCode: context.doorMode ? 125 : 5, ...(context.liveLocal ? { expectedOwnerLogin: context.localOwner, ownerMismatchError: () => new Stop(5, 'live-local-owner-changed') } : {}) });
1827
2263
  const probe = { origin, identity, ports: context.ports, signal: context.signal, interrupted: context.interrupted, auth };
1828
- const reply = await readCapacity(probe, context.ports.now() + GET_MS, false);
1829
- if (reply?.status !== 200 || !Array.isArray(reply.json?.features)) return false;
2264
+ const probeDeadline = context.ports.now() + GET_MS;
2265
+ let reply = null;
2266
+ for (let attempt = 0; attempt < CAPACITY_PROBE_ATTEMPTS; attempt++) {
2267
+ if (context.interrupted || context.signal?.aborted) break;
2268
+ const remaining = probeDeadline - context.ports.now();
2269
+ if (remaining <= 0) break;
2270
+ const attemptDeadline = context.ports.now() + Math.min(CAPACITY_PROBE_ATTEMPT_MS, remaining);
2271
+ reply = await readCapacity(probe, attemptDeadline, attempt > 0);
2272
+ const stop = capacityStopMessage(reply);
2273
+ if (stop) throw new Stop(context.doorMode ? 125 : 5, stop);
2274
+ if (isDefinitiveCapacityReply(reply)) {
2275
+ const features = reply.status === 200 && Array.isArray(reply.json?.features) ? reply.json.features : [];
2276
+ const engineSha = reply.status === 200 ? reply.json?.engine_sha ?? null : null;
2277
+ const supportsLazy = features.includes('lazy-interfaces') || features.some(feature => /^hybrid(?:-|$)/.test(feature));
2278
+ if (supportsLazy) store?.writeOriginCapabilities(origin, { features, engine_sha: engineSha }, context.ports.now());
2279
+ else store?.deleteOriginCapabilities(origin);
2280
+ context.probedIdentity = identity;
2281
+ context.serverFeatures = features;
2282
+ context.serverEngineSha = engineSha;
2283
+ context.allowMissingInterfaces = supportsLazy;
2284
+ context.capacityDefinitive = true;
2285
+ return supportsLazy;
2286
+ }
2287
+ if (!isRetryableCapacityFailure(reply) || attempt + 1 >= CAPACITY_PROBE_ATTEMPTS) break;
2288
+ const delay = Math.min(capacityProbeDelay(reply, attempt), Math.max(0, probeDeadline - context.ports.now()));
2289
+ if (delay <= 0) break;
2290
+ await context.ports.sleep(delay, context.signal);
2291
+ }
2292
+ if (context.interrupted || context.signal?.aborted) throw new Stop(context.doorMode ? 125 : 3, 'Stopped before sending.');
2293
+ const cached = store?.readOriginCapabilities(origin, context.ports.now()) ?? null;
1830
2294
  context.probedIdentity = identity;
1831
- context.serverFeatures = reply.json.features;
1832
- context.serverEngineSha = reply.json.engine_sha ?? null;
1833
- context.allowMissingInterfaces = reply.json.features.includes('lazy-interfaces');
1834
- return context.allowMissingInterfaces;
2295
+ context.allowMissingInterfaces = true;
2296
+ context.capacityDefinitive = false;
2297
+ if (cached) {
2298
+ context.serverFeatures = cached.features;
2299
+ context.serverEngineSha = cached.engine_sha ?? null;
2300
+ if (!context.capacityWarning) {
2301
+ context.capacityWarning = true;
2302
+ line(context.ports.stderr, 'Warning: interpreter capacity could not be read; using cached lazy-interfaces capability for this interpreter.');
2303
+ }
2304
+ } else if (!context.capacityWarning) {
2305
+ context.capacityWarning = true;
2306
+ line(context.ports.stderr, 'Warning: interpreter capacity could not be read; continuing with ordinary interpreter admission.');
2307
+ }
2308
+ return true;
1835
2309
  }
1836
2310
  async function capacityReady(context, deadline, busyRow = null) {
1837
2311
  let refresh = !!context.admissionMaintenance;
1838
2312
  while (!context.interrupted && !context.stopped && !context.sendError && context.ports.now() < deadline) {
1839
2313
  const reply = await readCapacity(context, deadline, refresh);
1840
2314
  if (reply === null || context.interrupted || context.signal?.aborted || context.ports.now() >= deadline) return false;
1841
- const blocked = blockingAnswer(reply);
1842
- const stop = blocked || (reply.status === 401 ? AUTH_TEXT : gateText(reply) ? 'The runtime opens soon.' : null);
2315
+ const stop = capacityStopMessage(reply);
1843
2316
  if (stop) { context.stopped = { code: 'blocked', message: stop }; throw new Stop(5, stop); }
1844
- const understood = reply.status === 404 || reply.status === 200 && isObject(reply.json) && Object.hasOwn(reply.json, 'maintenance');
2317
+ const understood = reply.status === 404 || reply.status === 200 && isObject(reply.json) && (Object.hasOwn(reply.json, 'maintenance') || Array.isArray(reply.json.features));
1845
2318
  // The interpreter declares what it supports; pdd names the tests to lint only when it says so.
1846
- context.serverFeatures = reply.status === 200 && Array.isArray(reply.json?.features) ? reply.json.features : [];
1847
- context.serverEngineSha = reply.status === 200 ? reply.json?.engine_sha ?? null : null;
1848
- if (!understood && !context.capacityWarning) {
1849
- context.capacityWarning = true;
1850
- line(context.ports.stderr, 'Warning: interpreter capacity could not be read; continuing with ordinary interpreter admission.');
2319
+ if (understood) {
2320
+ context.serverFeatures = reply.status === 200 && Array.isArray(reply.json?.features) ? reply.json.features : [];
2321
+ context.serverEngineSha = reply.status === 200 ? reply.json?.engine_sha ?? null : null;
2322
+ context.capacityDefinitive = true;
2323
+ if (reply.status === 200 && context.serverFeatures.includes('lazy-interfaces')) {
2324
+ context.store?.writeOriginCapabilities(context.origin, { features: context.serverFeatures, engine_sha: context.serverEngineSha }, context.ports.now());
2325
+ } else if (reply.status === 200 || isObject(reply.json)) {
2326
+ context.store?.deleteOriginCapabilities(context.origin);
2327
+ }
2328
+ } else {
2329
+ if (!context.serverFeatures?.length) {
2330
+ const cached = context.store?.readOriginCapabilities(context.origin, context.ports.now()) ?? null;
2331
+ context.serverFeatures = cached ? cached.features : (context.serverFeatures ?? []);
2332
+ if (cached && context.serverEngineSha == null) context.serverEngineSha = cached.engine_sha ?? null;
2333
+ }
2334
+ if (context.serverEngineSha === undefined) context.serverEngineSha = null;
2335
+ if (!context.capacityWarning) {
2336
+ context.capacityWarning = true;
2337
+ line(context.ports.stderr, 'Warning: interpreter capacity could not be read; continuing with ordinary interpreter admission.');
2338
+ }
1851
2339
  }
1852
2340
  const now = context.ports.now();
1853
2341
  const maintenance = reply.status === 200 ? reply.json?.maintenance : null, until = Date.parse(maintenance?.until);
@@ -1928,12 +2416,19 @@ function judgePost(reply, id, command, secrets) {
1928
2416
  return sameJob(reply.json, id, command) ? { kind: 'accepted', answer: reply.json, wait: checkCapacity(reply.json, reply.headers) } : { kind: 'unknown', why: 'The interpreter answered with another request ID or command.' };
1929
2417
  }
1930
2418
  if (reply.status === 429) {
1931
- return error?.code === 'server-full' && reply.json?.dispatch === 'not_started' && safeAdmission(reply) ? { kind: 'busy', wait: retryAfter(reply.headers), admission: reply.json }
1932
- : { kind: 'not_run', note: note('The interpreter is busy. Try again later.') };
2419
+ const retryable429 = (error?.code === 'server-full' || (error?.code === 'rate-limited' && error?.details?.retryable !== false))
2420
+ && reply.json?.dispatch === 'not_started' && safeAdmission(reply);
2421
+ if (retryable429 && command === 'check') {
2422
+ if (!admissionMatches(reply.json, id) || !accountingProof(reply.json))
2423
+ return { kind: 'unknown', why: 'Check capacity accounting is incomplete or conflicting.', admission: reply.json, capacity_uncertain: true };
2424
+ return { kind: 'busy', wait: retryAfter(reply.headers), admission: reply.json };
2425
+ }
2426
+ return retryable429 ? { kind: 'busy', wait: retryAfter(reply.headers), admission: reply.json }
2427
+ : { kind: 'not_run', note: note('The interpreter is busy. Try again later.'), contention: true };
1933
2428
  }
1934
2429
  if (gateText(reply)) return { kind: 'stop', note: { code: null, message: 'The runtime opens soon.' } };
1935
2430
  if (reply.status === 401) return { kind: 'stop', note: { code: cleanText(error?.code, secrets) || 'auth-required', message: AUTH_TEXT } };
1936
- if (reply.status === 503 && /^(?:pool-low-room|pool-copy-[a-z-]+|github-unavailable)$/.test(error?.code ?? '')) return { kind: 'not_run', note: note('Try again later.') };
2431
+ if (reply.status === 503 && /^(?:pool-low-room|pool-copy-[a-z-]+|github-unavailable)$/.test(error?.code ?? '')) return { kind: 'not_run', note: note('Try again later.'), contention: true };
1937
2432
  if ([400, 413, 415, 422].includes(reply.status) && error?.code) {
1938
2433
  return { kind: 'refused', refusal: { code: cleanText(error.code, secrets), section: cleanText(error.section, secrets) || null, message: cleanText(error.message, secrets) || null,
1939
2434
  engine_message: reply.json.details ? cleanText(JSON.stringify(reply.json.details), secrets) : null,
@@ -1954,6 +2449,7 @@ function judgeGet(reply, id, command) {
1954
2449
  if (reply.status === 410) return { kind: 'unknown', why: 'The result expired.', status: 410 };
1955
2450
  if (reply.status === 401) return { kind: 'auth' };
1956
2451
  if (gateText(reply)) return { kind: 'gate' };
2452
+ if (reply.status === 429) return { kind: 'again', contention: true };
1957
2453
  return { kind: 'again' };
1958
2454
  }
1959
2455
 
@@ -1986,6 +2482,22 @@ function localSetup(cwd, words, ports) {
1986
2482
  const sentTests = rows => rows.filter(row => !row.unsent && !row.native_only?.length).map(row => row.test);
1987
2483
  const unmatchedLines = found => (found.orphans ?? []).map(item => `Warning: ${item.line}`);
1988
2484
 
2485
+ function untestedMatchesWords(item, words) {
2486
+ return words.some(raw => {
2487
+ const word = String(raw ?? '').replace(/^\.\//, '');
2488
+ if (!word) return false;
2489
+ return item.storyPath === word || item.story === word || word === '.'
2490
+ || (!word.startsWith('../') && word !== '..' && item.storyPath?.startsWith(`${word.replace(/\/$/, '')}/`));
2491
+ });
2492
+ }
2493
+
2494
+ function scopedDiscoveryWarnings(found, words = []) {
2495
+ const warnings = found?.warnings ?? [];
2496
+ if (!words.length || !(found?.untested?.length)) return [...warnings];
2497
+ const hidden = new Set(found.untested.filter(item => !untestedMatchesWords(item, words)).map(item => `Warning: ${item.line}`));
2498
+ return hidden.size ? warnings.filter(text => !hidden.has(text)) : [...warnings];
2499
+ }
2500
+
1989
2501
  function storyList(found, ports) {
1990
2502
  return [...found.tests.map(test => ` ${test.story} ${test.path}${test.title && test.title !== test.story ? ` (${test.title})` : ''}`),
1991
2503
  ...(found.untested ?? []).map(item => ` ${item.story} no test (expected ${ports.expectedTestPath(item.storyPath)})`)];
@@ -2025,6 +2537,137 @@ const incompleteCriteria = row => {
2025
2537
  message:'The Story is not a full pass: some criteria were not checked.'}});
2026
2538
  };
2027
2539
 
2540
+ function ownNotCheckedOf(row) {
2541
+ if (Array.isArray(row?.own_not_checked)) return row.own_not_checked;
2542
+ if (Array.isArray(row?.not_checked)) return row.not_checked;
2543
+ return [];
2544
+ }
2545
+
2546
+ function rowStoryKey(row) {
2547
+ if (typeof row?.story_path === 'string' && row.story_path.trim()) return `path:${row.story_path.trim()}`;
2548
+ if (typeof row?.story === 'string' && row.story.trim() && row.story !== '-') return `story:${row.story.trim()}`;
2549
+ return null;
2550
+ }
2551
+
2552
+ function rowCriterionKeys(row) {
2553
+ const texts = isObject(row?.criterion_texts) ? row.criterion_texts : {};
2554
+ const entries = Object.entries(texts).filter(([id, text]) => typeof id === 'string' && id && typeof text === 'string');
2555
+ const counts = new Map();
2556
+ for (const [, text] of entries) counts.set(text, (counts.get(text) ?? 0) + 1);
2557
+ const byId = new Map();
2558
+ for (const [id, text] of entries) {
2559
+ byId.set(id, counts.get(text) === 1 ? `text:${text}` : `id:${id}`);
2560
+ }
2561
+ const keyFor = (criterionId, text = texts[criterionId]) => {
2562
+ if (typeof criterionId === 'string' && byId.has(criterionId)) return byId.get(criterionId);
2563
+ if (typeof text === 'string' && text && (counts.get(text) ?? 0) <= 1) return `text:${text}`;
2564
+ return typeof criterionId === 'string' && criterionId ? `id:${criterionId}` : null;
2565
+ };
2566
+ return { entries, byId, keyFor };
2567
+ }
2568
+
2569
+ function rowPassedOwnChecks(row) {
2570
+ if (!row || row.unsent || row.native_only?.length || row.diagnostic_subset === true || row.diagnostic === true) return false;
2571
+ if (row.refusals?.length || failedCheckCount(row) > 0) return false;
2572
+ if (row.state === 'passed') return true;
2573
+ return row.state === 'not_run' && row.note?.code === 'criteria-not-checked';
2574
+ }
2575
+
2576
+ function contributedCriterionKeys(row, context) {
2577
+ if (!rowPassedOwnChecks(row)) return [];
2578
+ const { entries, keyFor } = rowCriterionKeys(row);
2579
+ const ownUnchecked = new Set(ownNotCheckedOf(row).map(item => item?.criterion_id).filter(Boolean));
2580
+ if (context?.intent === 'lint-only' || row.phase === 'lint') {
2581
+ return entries.filter(([id]) => !ownUnchecked.has(id)).map(([id, text]) => keyFor(id, text)).filter(Boolean);
2582
+ }
2583
+ if (Array.isArray(row.verified_passed_criteria)) {
2584
+ return row.verified_passed_criteria
2585
+ .filter(item => item?.criterion_id && !ownUnchecked.has(item.criterion_id))
2586
+ .map(item => keyFor(item.criterion_id, item.text))
2587
+ .filter(Boolean);
2588
+ }
2589
+ if (row.cached && row.state === 'passed') {
2590
+ return entries.filter(([id]) => !ownUnchecked.has(id)).map(([id, text]) => keyFor(id, text)).filter(Boolean);
2591
+ }
2592
+ return [];
2593
+ }
2594
+
2595
+ function failedCriterionKeys(row) {
2596
+ const { keyFor } = rowCriterionKeys(row);
2597
+ const out = [];
2598
+ for (const item of row?.verified_failed_criteria ?? []) {
2599
+ const key = keyFor(item?.criterion_id, item?.text);
2600
+ if (key) out.push(key);
2601
+ }
2602
+ for (const check of row?.failed_checks ?? []) {
2603
+ const key = keyFor(check?.criterion_id);
2604
+ if (key) out.push(key);
2605
+ }
2606
+ return out;
2607
+ }
2608
+
2609
+ // Reconcile criteria-not-checked across passing sibling variant files for the same Story
2610
+ // within the same executed batch, keeping single-file verification strictly fail-closed.
2611
+ function reconcileStoryCriteria(rows, context = null) {
2612
+ if (!Array.isArray(rows) || !rows.length) return;
2613
+ const groups = new Map();
2614
+ for (const row of rows) {
2615
+ const key = rowStoryKey(row);
2616
+ if (!key) {
2617
+ incompleteCriteria(row);
2618
+ continue;
2619
+ }
2620
+ if (!groups.has(key)) groups.set(key, []);
2621
+ groups.get(key).push(row);
2622
+ }
2623
+ for (const group of groups.values()) {
2624
+ const covered = new Set();
2625
+ const failed = new Set();
2626
+ if (group.length > 1) {
2627
+ for (const row of group) {
2628
+ for (const key of failedCriterionKeys(row)) failed.add(key);
2629
+ for (const key of contributedCriterionKeys(row, context)) covered.add(key);
2630
+ }
2631
+ for (const key of failed) covered.delete(key);
2632
+ }
2633
+ for (const row of group) {
2634
+ const ownUnchecked = ownNotCheckedOf(row);
2635
+ if (!ownUnchecked.length) {
2636
+ incompleteCriteria(row);
2637
+ continue;
2638
+ }
2639
+ if (!row.own_not_checked) row.own_not_checked = ownUnchecked.map(item => ({ ...item }));
2640
+ if (group.length > 1 && rowPassedOwnChecks(row)) {
2641
+ const { keyFor } = rowCriterionKeys(row);
2642
+ const remaining = ownUnchecked.filter(item => {
2643
+ const key = keyFor(item?.criterion_id, item?.text);
2644
+ return !key || !covered.has(key);
2645
+ });
2646
+ const siblingCovered = ownUnchecked.length - remaining.length;
2647
+ if (remaining.length) row.not_checked = remaining;
2648
+ else delete row.not_checked;
2649
+ if (!remaining.length) {
2650
+ if (row.own_criteria) {
2651
+ const total = Math.max(row.own_criteria.passed, row.own_criteria.total - siblingCovered);
2652
+ row.criteria = { passed: row.own_criteria.passed, total };
2653
+ }
2654
+ if (row.state === 'not_run' && row.note?.code === 'criteria-not-checked') {
2655
+ row.state = 'passed';
2656
+ row.note = null;
2657
+ }
2658
+ } else {
2659
+ if (row.own_criteria) row.criteria = { ...row.own_criteria };
2660
+ incompleteCriteria(row);
2661
+ }
2662
+ } else {
2663
+ row.not_checked = ownUnchecked.map(item => ({ ...item }));
2664
+ if (row.own_criteria) row.criteria = { ...row.own_criteria };
2665
+ incompleteCriteria(row);
2666
+ }
2667
+ }
2668
+ }
2669
+ }
2670
+
2028
2671
  function capturedCriteria(rows, capture) {
2029
2672
  let broken = false;
2030
2673
  for (const row of rows.filter(row=>!row.unsent)) {
@@ -2045,8 +2688,13 @@ function capturedCriteria(rows, capture) {
2045
2688
  const exemptions=Array.isArray(doc.check_exemptions)?doc.check_exemptions:[];
2046
2689
  const unchecked=exemptions.filter(item=>isObject(item)&&item.reason==='out-of-scope').map(item=>({
2047
2690
  criterion_id:item.criterion_id,text:row.criterion_texts[item.criterion_id],reason:item.detail}));
2048
- if (unchecked.length) row.not_checked=unchecked;
2049
- else delete row.not_checked;
2691
+ if (unchecked.length) {
2692
+ row.not_checked=unchecked;
2693
+ row.own_not_checked=unchecked.map(item=>({...item}));
2694
+ } else {
2695
+ delete row.not_checked;
2696
+ delete row.own_not_checked;
2697
+ }
2050
2698
  }
2051
2699
  return broken;
2052
2700
  }
@@ -2254,6 +2902,8 @@ function applyAnswer(row, answer, context, observedWait = null, observedAt = con
2254
2902
  if (capacityUncertain) row.capacity_uncertain = true;
2255
2903
  else if (capacitySafe) row.capacity_uncertain = false;
2256
2904
  row.cache_identity = answerCacheIdentity(answer);
2905
+ const savedOriginalCalls = answer?.result?.report?.saved_answer?.original_provider_calls;
2906
+ row.saved_answer_original_calls = Number.isSafeInteger(savedOriginalCalls) && savedOriginalCalls >= 0 ? savedOriginalCalls : null;
2257
2907
  // Evidence is no newer than its original batch, even when read much later.
2258
2908
  const times = [context.startedAt, ...[answer?.finished_at, answer?.completed_at, answer?.ended_at].map(value => typeof value === 'number' ? value : Date.parse(value))].filter(Number.isFinite);
2259
2909
  row.cache_sample_at = times.length ? Math.min(...times) : null;
@@ -2270,6 +2920,8 @@ function applyAnswer(row, answer, context, observedWait = null, observedAt = con
2270
2920
  const advice = noVerdictAdvice(answer, view);
2271
2921
  const firstDiagnosis = view.failed_checks.find(check => check.diagnosis) ?? null, failed = view.state === 'failed';
2272
2922
  Object.assign(row, { state: view.state, checks: view.checks, criteria: view.criteria, failed_checks: view.failed_checks, all_checks: view.all_checks,
2923
+ ...(view.step_details?.length ? { step_details: view.step_details } : {}),
2924
+ ...(view.draft_interfaces?.length ? { draft_interfaces: view.draft_interfaces } : {}),
2273
2925
  ...(Object.hasOwn(view, 'field_agreement') ? { field_agreement: view.field_agreement } : {}),
2274
2926
  ...(view.sample_divergence ? { sample_divergence: view.sample_divergence } : {}),
2275
2927
  refusals: view.refusals.map((item, index) => interfaceDiagnostic(item,
@@ -2292,15 +2944,41 @@ function applyAnswer(row, answer, context, observedWait = null, observedAt = con
2292
2944
  if (capacityUncertain) markCapacityUnknown(context, row);
2293
2945
  else if (wait !== null) markBusy(context, row, observedWait ?? wait, observedAt, context.reading && observedWait === null);
2294
2946
  else { row.busy = false; row.can_retry = false; row.note = view.note; }
2295
- if (row.not_checked?.length) {
2296
- const unchecked = new Set(row.not_checked.map(item=>item.criterion_id));
2297
- const results = answer?.result?.report?.criterion_results;
2947
+ const ownNotChecked = ownNotCheckedOf(row);
2948
+ if (ownNotChecked.length) {
2949
+ row.own_not_checked = ownNotChecked.map(item => ({ ...item }));
2950
+ row.not_checked = ownNotChecked.map(item => ({ ...item }));
2951
+ } else {
2952
+ delete row.not_checked;
2953
+ delete row.own_not_checked;
2954
+ }
2955
+ const results = answer?.result?.report?.criterion_results;
2956
+ const unchecked = new Set(ownNotChecked.map(item => item.criterion_id));
2957
+ row.verified_passed_criteria = Array.isArray(results)
2958
+ ? results.filter(item => isObject(item) && item.status === 'passed' && typeof item.criterion_id === 'string' && !unchecked.has(item.criterion_id))
2959
+ .map(item => ({ criterion_id: item.criterion_id, text: row.criterion_texts?.[item.criterion_id] }))
2960
+ : null;
2961
+ row.verified_failed_criteria = Array.isArray(results)
2962
+ ? results.filter(item => isObject(item) && item.status === 'failed' && typeof item.criterion_id === 'string')
2963
+ .map(item => ({ criterion_id: item.criterion_id, text: row.criterion_texts?.[item.criterion_id] }))
2964
+ : [];
2965
+ if (ownNotChecked.length) {
2298
2966
  row.criteria = {passed:Array.isArray(results) ? results.filter(item=>item.status==='passed'&&!unchecked.has(item.criterion_id)).length : 0,total:row.criteria_total};
2299
2967
  }
2968
+ row.own_criteria = row.criteria ? { ...row.criteria } : null;
2300
2969
  incompleteCriteria(row);
2970
+ if (Array.isArray(context?.rows) && context.rows.includes(row)) reconcileStoryCriteria(context.rows, context);
2301
2971
  if (row.state === 'refused') addHints(row, context.root, context.visible);
2302
2972
  if (ENDED.has(row.state) && row.sent_at && !row.ended_at && !context.reading) row.ended_at = context.ports.now();
2303
2973
  row.seconds = !ENDED.has(row.state) ? null : row.sent_at && row.ended_at ? (row.ended_at - row.sent_at) / 1000 : row.server_seconds;
2974
+ if (!context.reading && context.concurrency && row.request_ids?.length) {
2975
+ const latestId = row.request_ids.at(-1);
2976
+ if (row.provider || row.time_limit) {
2977
+ backoffCheckWindow(context, `provider:${latestId}`, row.provider?.code || 'provider contention');
2978
+ } else if (['passed', 'failed'].includes(row.state) && !row.cached && !row.busy) {
2979
+ recoverCheckWindow(context, latestId);
2980
+ }
2981
+ }
2304
2982
  }
2305
2983
 
2306
2984
  function nativeSourceIdentity(context, rows) {
@@ -2311,6 +2989,9 @@ function nativeSourceIdentity(context, rows) {
2311
2989
  }
2312
2990
 
2313
2991
  // The saved local-layout contract is deliberately distinct from legacy native-only batches.
2992
+ const LOCAL_LINT_REASON_MESSAGE = 'local structural, scenario, app-map, hygiene, and SVG checks ran; remote cross-prompt lint not run';
2993
+ const LOCAL_LINT_LEGACY_REASON_MESSAGE = 'checked SVG layout only; prompts not checked';
2994
+ const LOCAL_LINT_REASON_MESSAGES = new Set([LOCAL_LINT_REASON_MESSAGE, LOCAL_LINT_LEGACY_REASON_MESSAGE]);
2314
2995
  function localLayoutResult(batch, summary) {
2315
2996
  const keys = (value, names) => value && typeof value === 'object' && !Array.isArray(value)
2316
2997
  && isDeepStrictEqual(Object.keys(value).sort(), names.split(' ').sort());
@@ -2327,7 +3008,7 @@ function localLayoutResult(batch, summary) {
2327
3008
  || !Array.isArray(batch.problems) || !batch.problems.every(item => (keys(item, 'code path message') || keys(item, 'code path message section')) && Object.values(item).every(value => typeof value === 'string'))
2328
3009
  || !Array.isArray(batch.rows) || batch.rows.length || !keys(batch.lint, 'state lint_state reason request_ids')
2329
3010
  || batch.lint.state !== 'partial' || batch.lint.lint_state !== 'partial'
2330
- || !isDeepStrictEqual(batch.lint.reason, {code:'local-only',message:'checked SVG layout only; prompts not checked'})
3011
+ || !keys(batch.lint.reason, 'code message') || batch.lint.reason.code !== 'local-only' || !LOCAL_LINT_REASON_MESSAGES.has(batch.lint.reason.message)
2331
3012
  || !Array.isArray(batch.lint.request_ids) || batch.lint.request_ids.length) return null;
2332
3013
  const result = {batch:batch.batch,repo:batch.root,exit_code:batch.exit_code,state:'partial',lint_state:'partial',reason:batch.lint.reason,
2333
3014
  local_only:true,local_scope:batch.local_scope,summary_line:batch.summary_line,warnings:batch.warnings,problems:batch.problems,rows:[],report_url:null};
@@ -2346,7 +3027,7 @@ async function saveLocalLayout(context, {root, tests, prompts, warnings, problem
2346
3027
  try {
2347
3028
  const record = {version:1,batch,root,created_at:new Date(now).toISOString(),intent:'lint-only',local_only:true,source_sha256:null,
2348
3029
  local_scope:{tests:[...new Set(tests)].sort(),prompts:[...new Set(prompts)].sort()},summary_line:summary,exit_code:problems.length ? 4 : 0,
2349
- warnings,problems,rows:[],lint:{state:'partial',lint_state:'partial',reason:resultOutcome({state:'partial',note:{code:'local-only',message:'checked SVG layout only; prompts not checked'}}).reason,request_ids:[]}};
3030
+ warnings,problems,rows:[],lint:{state:'partial',lint_state:'partial',reason:resultOutcome({state:'partial',note:{code:'local-only',message:LOCAL_LINT_REASON_MESSAGE}}).reason,request_ids:[]}};
2350
3031
  const projection = localLayoutResult(record,null);
2351
3032
  if (!projection) throw new Error('Local lint record cannot satisfy the saved result contract, including safe inspected scope.');
2352
3033
  const result = {...projection,exit_code:record.exit_code,summary_line:record.summary_line};
@@ -2379,12 +3060,14 @@ function batchRecord(context) {
2379
3060
  return { version: 1, batch, origin, root, ...(context.stepIds?.length ? {diagnostic:true,diagnostic_subset:true,selected_steps:rows.flatMap(row=>row.selected_steps ?? [])} : {}), ...(maintenance ? { maintenance, retry_after: maintenance.retry_after } : {}), check_plan: context.checkPlan ?? null, ...(context.checkSelection ? {check_selection:context.checkSelection,baseline_report:context.baselineReport} : {}), head: context.head, login: identity.login, user_id: identity.userId,
2380
3061
  ...(context.liveLocal || context.liveLocalSaved ? {live_local:true} : {}),
2381
3062
  source_sha256: capture.sha256, files: capture.files.map(file => file.path), bytes: capture.bytes, timeout_min: context.timeoutMin,
3063
+ ...(context.batchTimeoutMin != null ? { batch_timeout_min: context.batchTimeoutMin } : {}),
2382
3064
  ...(context.singleAttempt ? {single_attempt:true} : {}), ...(context.maxTotalCalls != null ? {max_total_calls:context.maxTotalCalls} : {}),
2383
3065
  ...(context.checkOptions ? {check_options:context.checkOptions} : {}),
2384
3066
  source_selection: context.sourceSelection ?? {tests:sentTests(rows),exclude_fixture_projects:context.excludeFixtureProjects === true},
2385
3067
  native_source: context.nativeSource ?? null,
2386
3068
  ...(context.localOnly ? {local_only:true} : {}),
2387
3069
  ...(context.allowMissingInterfaces ? {lazy_interfaces:true} : {}),
3070
+ ...(context.reservationsReconciledAt ? {reservations_reconciled_at:context.reservationsReconciledAt} : {}),
2388
3071
  exclude_fixture_projects: context.excludeFixtureProjects === true,
2389
3072
  created_at: new Date(context.startedAt).toISOString(), intent: context.intent, lint: lint ? { ...lint, recovery_state: lint.state, ...resultOutcome(lint.public_result ?? lint) } : lint, warnings, coverage: context.coverage,
2390
3073
  contract_snapshots: capture.stories,
@@ -2394,12 +3077,13 @@ function batchRecord(context) {
2394
3077
  ...(row.sample_divergence ? {sample_divergence:row.sample_divergence} : {}),
2395
3078
  ...(row.diagnostic || row.diagnostic_subset === true ? { ...(row.diagnostic ? {diagnostic:true} : {}), diagnostic_subset:true, selected_steps:row.selected_steps ?? [] } : {}),
2396
3079
  ...(!row.request_ids.length && Object.hasOwn(row, 'calls') ? { calls: row.calls } : {}),
2397
- ...(row.unsent ? { unsent: true } : {}), ...(row.not_checked?.length ? {not_checked:row.not_checked} : {}), progress: row.progress, ahead: row.ahead, phase: row.phase, post_verdict: row.post_verdict ?? null, binding_plan: row.binding_plan, compatibility: row.compatibility, client_advice: row.client_advice, report_url: row.report_url, refusals: row.refusals, note: row.note ?? null, why: row.why ?? null, next_step: row.next_step ?? null,
3080
+ ...(row.unsent ? { unsent: true } : {}), ...(row.not_checked?.length ? {not_checked:row.not_checked} : {}), ...(row.own_not_checked?.length && !isDeepStrictEqual(row.own_not_checked, row.not_checked ?? []) ? {own_not_checked:row.own_not_checked} : {}), progress: row.progress, ahead: row.ahead, phase: row.phase, post_verdict: row.post_verdict ?? null, binding_plan: row.binding_plan, compatibility: row.compatibility, client_advice: row.client_advice, report_url: row.report_url, refusals: row.refusals, note: row.note ?? null, why: row.why ?? null, next_step: row.next_step ?? null,
2398
3081
  sent_at: row.sent_at ?? null, ended_at: row.ended_at ?? null, max_calls: row.max_calls, warnings: row.warnings, steps: row.steps, criteria_total: row.criteria_total,
2399
3082
  reservation: row.reservation ?? null, restart_used: !!row.restart_used,
2400
3083
  busy: !!row.busy, can_retry: !!row.can_retry, eligible: !!row.eligible, retry_at: row.retry_at ?? null,
2401
3084
  ...(row.known_calls !== undefined ? { known_calls: row.known_calls } : {}), ...(row.unknown_calls !== undefined ? { unknown_calls: row.unknown_calls } : {}),
2402
3085
  ...(row.accounting_complete !== undefined ? { accounting_complete: row.accounting_complete } : {}), ...(row.capacity_uncertain ? { capacity_uncertain: true } : {}),
3086
+ ...(row.reservation_reconciled ? { reservation_reconciled: row.reservation_reconciled } : {}),
2403
3087
  busy_request_id: row.busy_request_id ?? null, busy_observed_at: row.busy_observed_at ?? null, capacity_until: row.capacity_until ?? null,
2404
3088
  engine_sha: row.engine_sha ?? null, requested_model: row.requested_model ?? null, cache_identity: row.cache_identity ?? null,
2405
3089
  checks: row.checks ?? null, criteria: row.criteria ?? null, failed_checks: (row.failed_checks ?? []).map(({ normal_result, ...check }) => check),
@@ -2471,10 +3155,69 @@ function adoptClaims(context, row) {
2471
3155
  }
2472
3156
  }
2473
3157
  }
2474
- function readUnresolvedPriorReservations(root, env, excludeBatch = null) {
3158
+ function priorReservationTtlMs(env = {}) {
3159
+ const raw = env?.PDD_PRIOR_RESERVATION_TTL_HOURS;
3160
+ if (raw !== undefined && raw !== null && String(raw).trim() !== '') {
3161
+ const hours = Number(raw);
3162
+ if (Number.isFinite(hours) && hours > 0) return Math.round(hours * 3_600_000);
3163
+ }
3164
+ return PRIOR_RESERVATION_TTL_MS;
3165
+ }
3166
+ function batchIdTimestampMs(name) {
3167
+ const match = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})-/.exec(String(name ?? ''));
3168
+ if (!match) return null;
3169
+ const ms = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), Number(match[6]));
3170
+ return Number.isFinite(ms) ? ms : null;
3171
+ }
3172
+ function reservationTimestampMs(name, saved, row = null) {
3173
+ if (row && Number.isFinite(row.ended_at)) return row.ended_at;
3174
+ if (row && Number.isFinite(row.sent_at)) return row.sent_at;
3175
+ if (typeof saved?.created_at === 'string' && Number.isFinite(Date.parse(saved.created_at))) return Date.parse(saved.created_at);
3176
+ return batchIdTimestampMs(name);
3177
+ }
3178
+ function rowReservationCleared(row) {
3179
+ return isObject(row?.reservation_reconciled) && row.reservation_reconciled.cleared === true;
3180
+ }
3181
+ function rowNeedsReservationCheck(row) {
3182
+ if (!isObject(row) || rowReservationCleared(row)) return false;
3183
+ const ids = Array.isArray(row.request_ids) ? row.request_ids.filter(id => typeof id === 'string' && id.length > 0) : [];
3184
+ if (!ids.length && !row.dispatchIncomplete) return false;
3185
+ const state = row.recovery_state ?? row.state;
3186
+ return ['sending', 'queued', 'running', 'unknown'].includes(state)
3187
+ || row.calls === 'unknown'
3188
+ || row.accounting_complete === false
3189
+ || row.dispatchIncomplete === true;
3190
+ }
3191
+ function localRowSettledFromReceipts(store, folder, ids) {
3192
+ if (!store || !folder || !Array.isArray(ids) || !ids.length) return { settled: false, known_calls: 0, state: null };
3193
+ const probeContext = { store, folder };
3194
+ let totalCalls = 0;
3195
+ let lastState = null;
3196
+ for (const id of ids) {
3197
+ const hasCapacityEvidence = attemptHasCapacityEvidence(probeContext, id);
3198
+ if (hasCapacityEvidence && attemptConfirmedZeroCapacity(probeContext, id)) {
3199
+ lastState = 'refused';
3200
+ continue;
3201
+ }
3202
+ const latest = store.read(join(folder, `${id}.json`));
3203
+ if (!latest || !sameJob(latest, id, 'check') || !accountingEnd(latest, id)) {
3204
+ return { settled: false, known_calls: 0, state: null };
3205
+ }
3206
+ const unknownWithoutExplicitProof = latest.state === 'unknown'
3207
+ && ![latest, latest.usage, latest.result, latest.report, latest.result?.report].some(s => isObject(s) && s.accounting_complete === true);
3208
+ if (hasCapacityEvidence || unknownWithoutExplicitProof) return { settled: false, known_calls: 0, state: null };
3209
+ const part = attemptAccounting(probeContext, id);
3210
+ if (!part.complete || !Number.isSafeInteger(part.total)) return { settled: false, known_calls: 0, state: null };
3211
+ totalCalls += part.total;
3212
+ lastState = latest.state;
3213
+ }
3214
+ return { settled: true, known_calls: totalCalls, state: lastState };
3215
+ }
3216
+ function readUnresolvedPriorReservations(root, env, excludeBatch = null, { now = Date.now(), ttlMs = priorReservationTtlMs(env), includeExpired = false } = {}) {
2475
3217
  const empty = { count: 0, reserved_calls: 0, batches: [] };
2476
3218
  try {
2477
- const wanted = realish(root), dir = join(stateDirectory(env, root), 'batches');
3219
+ const wanted = realish(root), stateDir = stateDirectory(env, root), dir = join(stateDir, 'batches');
3220
+ const store = new StateStore(stateDir);
2478
3221
  let names;
2479
3222
  try { names = readdirSync(dir); } catch { return empty; }
2480
3223
  let count = 0, reserved_calls = 0;
@@ -2487,11 +3230,17 @@ function readUnresolvedPriorReservations(root, env, excludeBatch = null) {
2487
3230
  if (!isObject(saved) || saved.intent !== 'check' || typeof saved.root !== 'string' || realish(saved.root) !== wanted || !Array.isArray(saved.rows)) continue;
2488
3231
  let batchHasUnresolved = false;
2489
3232
  for (const row of saved.rows) {
3233
+ if (rowReservationCleared(row)) continue;
2490
3234
  const ids = Array.isArray(row?.request_ids) ? row.request_ids : [];
2491
3235
  if (!ids.length) continue;
2492
3236
  const state = row.recovery_state ?? row.state;
2493
3237
  const openOrUnknown = ['sending', 'queued', 'running', 'unknown'].includes(state) || row.calls === 'unknown' || row.accounting_complete === false;
2494
3238
  if (!openOrUnknown) continue;
3239
+ if (localRowSettledFromReceipts(store, folder, ids).settled) continue;
3240
+ if (!includeExpired) {
3241
+ const ts = reservationTimestampMs(name, saved, row);
3242
+ if (ts !== null && Number.isFinite(now) && Number.isFinite(ttlMs) && now - ts >= ttlMs) continue;
3243
+ }
2495
3244
  const key = typeof row.test === 'string' ? createHash('sha256').update(row.test).digest('hex') : null;
2496
3245
  let cap = 0;
2497
3246
  for (let attempt = 0; attempt < ids.length; attempt++) {
@@ -2561,7 +3310,8 @@ function budgetRowsForContext(context, excludePendingRow = null) {
2561
3310
  }
2562
3311
  const part = context.folder ? attemptAccounting(context, id) : { known: row.known_calls ?? 0, unknown: row.unknown_calls ?? 1, complete: row.accounting_complete === true, total: typeof row.calls === 'number' ? row.calls : null };
2563
3312
  const isLatest = index === ids.length - 1;
2564
- const activeLost = row.state === 'unknown' && row.lost && now < Math.min(context.deadline ?? Infinity, row.read_until ?? context.deadline ?? Infinity);
3313
+ const rowEnd = rowDeadline(context, row);
3314
+ const activeLost = row.state === 'unknown' && row.lost && now < Math.min(rowEnd, row.read_until ?? rowEnd);
2565
3315
  const terminalReceipt = latest && sameJob(latest, id, 'check') && accountingEnd(latest, id);
2566
3316
  const unknownWithoutExplicitProof = latest?.state === 'unknown'
2567
3317
  && ![latest, latest?.usage, latest?.result, latest?.report, latest?.result?.report].some(s => isObject(s) && s.accounting_complete === true);
@@ -2611,11 +3361,30 @@ function applyBudgetDecisionStop(context, row, decision) {
2611
3361
  saveBatch(context);
2612
3362
  }
2613
3363
  function markDeadline(context, rows) {
2614
- if (context.interrupted || !Number.isFinite(context.deadline) || context.ports.now() < context.deadline) return;
2615
- for (const row of rows) if (!row.time_limit && (['ready', 'waiting', 'sending', 'queued', 'running'].includes(row.state)
2616
- || row.state === 'unknown' && row.lost || heldForLint(row) || row.busy && row.can_retry)) {
2617
- row.note = { code: context.timeoutMin && !context.agentLimit ? 'timeout-flag' : 'deadline',
2618
- message: context.timeoutMin && !context.agentLimit ? `Stopped waiting at --timeout ${context.timeoutMin} min.` : 'The wait deadline ended.' };
3364
+ if (context.interrupted) return;
3365
+ const now = context.ports.now();
3366
+ const batchEnd = batchDeadlineOf(context);
3367
+ const overallEnd = context.deadline ?? Infinity;
3368
+ const batchExpired = Number.isFinite(batchEnd) && now >= batchEnd;
3369
+ const overallExpired = Number.isFinite(overallEnd) && now >= overallEnd;
3370
+ for (const row of rows) {
3371
+ if (row.time_limit) continue;
3372
+ const isLint = row === context.lint;
3373
+ const storyEnd = !isLint && Number.isFinite(row.story_deadline) ? row.story_deadline : Infinity;
3374
+ const storyExpired = Number.isFinite(storyEnd) && now >= storyEnd;
3375
+ if (!batchExpired && !overallExpired && !storyExpired) continue;
3376
+ if (['ready', 'waiting', 'sending', 'queued', 'running'].includes(row.state)
3377
+ || row.state === 'unknown' && row.lost || heldForLint(row) || row.busy && row.can_retry) {
3378
+ if (storyExpired && (!batchExpired || storyEnd <= batchEnd)) {
3379
+ row.note = { code: context.timeoutMin != null && !context.agentLimit ? 'timeout-flag' : 'deadline',
3380
+ message: context.timeoutMin != null && !context.agentLimit ? `Stopped waiting at --timeout ${context.timeoutMin} min.` : 'The wait deadline ended.' };
3381
+ } else if (batchExpired && context.explicitBatchTimeout) {
3382
+ row.note = { code: 'timeout-flag', message: `Stopped waiting at --batch-timeout ${context.batchTimeoutMin} min.` };
3383
+ } else {
3384
+ row.note = { code: context.timeoutMin != null && !context.agentLimit ? 'timeout-flag' : 'deadline',
3385
+ message: context.timeoutMin != null && !context.agentLimit ? `Stopped waiting at --timeout ${context.timeoutMin} min.` : 'The wait deadline ended.' };
3386
+ }
3387
+ }
2619
3388
  }
2620
3389
  }
2621
3390
 
@@ -2628,6 +3397,7 @@ function saveBatch(context) {
2628
3397
  if (!row.busy && ['unknown', 'queued', 'running', 'sending'].includes(row.state) && answer && sameJob(answer, id, 'check')
2629
3398
  && ['passed', 'failed', 'refused'].includes(answer.state) && checkCapacity(answer) === null) applyAnswer(row, answer, context);
2630
3399
  }
3400
+ reconcileStoryCriteria(context.rows, context);
2631
3401
  context.store.write(join(context.folder, 'batch.json'), batchRecord(context));
2632
3402
  }
2633
3403
  function saveAnswerAt(store, folder, id, json) {
@@ -2654,7 +3424,18 @@ async function postJob(context, path, command, request, row, timeoutMs, deadline
2654
3424
  if (row) delete row.prior_restart_snapshot; // Dispatch is now uncertain; never roll it back.
2655
3425
  if (row) { if (!row.request_ids.includes(id)) row.request_ids.push(id); row.sent_at ??= context.ports.now(); row.state = 'sending'; row.phase = 'server'; row.calls = 'unknown'; row.post_verdict = 'uncertain'; }
2656
3426
  saveBatch(context);
2657
- const reply = await context.runtime.post(path, request, context.capture.tar, Math.max(1, Math.min(timeoutMs, deadline - context.ports.now())));
3427
+ const dedup = Boolean(context.serverFeatures?.includes('source-upload-v1'));
3428
+ const pendingChecks = command === 'check'
3429
+ ? (context.rows ?? []).filter(item => !item.unsent && ['ready', 'waiting', 'sending'].includes(item.state)).length
3430
+ : 0;
3431
+ const inlineFirst = command === 'lint' || (command === 'check' && pendingChecks <= 1);
3432
+ const reply = await context.runtime.post(
3433
+ path,
3434
+ request,
3435
+ context.capture.tar,
3436
+ Math.max(1, Math.min(timeoutMs, deadline - context.ports.now())),
3437
+ dedup ? { dedup: true, inlineFirst } : undefined,
3438
+ );
2658
3439
  const verdict = judgePost(reply, id, command, context.secrets);
2659
3440
  verdict.observed_at = context.ports.now();
2660
3441
  if (row && verdict.answer && ['queued', 'running', 'passed', 'failed'].includes(outcomeFor(verdict.answer, { kind: 'check' }).state))
@@ -2670,16 +3451,20 @@ async function postJob(context, path, command, request, row, timeoutMs, deadline
2670
3451
 
2671
3452
  // POST one check and fold the answer into its row.
2672
3453
  async function sendCheck(context, row) {
3454
+ if (row.story_deadline === undefined) {
3455
+ row.story_deadline = context.timeoutMin != null ? context.ports.now() + context.timeoutMin * 60_000 : Infinity;
3456
+ }
3457
+ const deadline = rowDeadline(context, row);
2673
3458
  row.admitting = true;
2674
- try { await sendCheckAttempt(context, row); }
3459
+ try { await sendCheckAttempt(context, row, deadline); }
2675
3460
  finally {
2676
3461
  context.preparingDispatches?.delete(row);
2677
- if (!row.awaiting_budget || context.interrupted || context.ports.now() >= context.deadline) restoreReplacement(row);
3462
+ if (!row.awaiting_budget || context.interrupted || context.ports.now() >= deadline) restoreReplacement(row);
2678
3463
  row.budget_in_flight = 0; row.admitting = false;
2679
3464
  }
2680
3465
  }
2681
- async function sendCheckAttempt(context, row) {
2682
- if (context.interrupted || context.ports.now() >= context.deadline || !['ready', 'waiting'].includes(row.state)) return;
3466
+ async function sendCheckAttempt(context, row, deadline = rowDeadline(context, row)) {
3467
+ if (context.interrupted || context.ports.now() >= deadline || !['ready', 'waiting'].includes(row.state)) return;
2683
3468
  if (context.checkOptions && context.checkOptions.samples > row.max_calls) throw new Stop(2, 'samples exceeds this test’s total max_calls allowance.');
2684
3469
  // Recheck the saved raw cohort immediately before any capacity-driven new ID.
2685
3470
  // The one structured restart replacement has its own durable fuse and remains allowed.
@@ -2687,7 +3472,7 @@ async function sendCheckAttempt(context, row) {
2687
3472
  markCapacityUnknown(context, row);
2688
3473
  return;
2689
3474
  }
2690
- if (row.busy && row.request_ids.length && !await capacityReady(context, context.deadline, row)) return;
3475
+ if (row.busy && row.request_ids.length && !await capacityReady(context, deadline, row)) return;
2691
3476
  const candidateForRow = () => ({
2692
3477
  test: row.test,
2693
3478
  kind: row.restart_pending && !row.transient_pending ? 'restart-replacement' : 'initial',
@@ -2707,7 +3492,7 @@ async function sendCheckAttempt(context, row) {
2707
3492
  row.awaiting_budget = false;
2708
3493
  row.budget_in_flight = preDecision.effective_max_calls;
2709
3494
  const attempt = row.request_ids.length, previousCalls = row.restart_used || row.restart_pending ? accumulatedCalls(context, row) : 0;
2710
- if (!await admission(context, 'check', row)) {
3495
+ if (!await admission(context, 'check', row, deadline)) {
2711
3496
  if (context.interrupted && interruptedAdmissions.has(row)) Object.assign(row, { state: 'not_run', calls: previousCalls, phase: 'local', note: { code: null, message: 'Stopped before sending.' } });
2712
3497
  return;
2713
3498
  }
@@ -2720,7 +3505,7 @@ async function sendCheckAttempt(context, row) {
2720
3505
  }
2721
3506
  adoptClaims(context, row);
2722
3507
  if (row.request_ids.length !== attempt) delete row.prior_restart_snapshot;
2723
- if (row.request_ids.length !== attempt || !['ready', 'waiting'].includes(row.state) || context.interrupted || context.ports.now() >= context.deadline) {
3508
+ if (row.request_ids.length !== attempt || !['ready', 'waiting'].includes(row.state) || context.interrupted || context.ports.now() >= deadline) {
2724
3509
  await finishReservation(context, row, { state: 'not_run' });
2725
3510
  if (context.interrupted && row.request_ids.length === attempt && ['ready', 'waiting'].includes(row.state)) Object.assign(row, { state: 'not_run', calls: previousCalls, phase: 'local', note: { code: null, message: 'Stopped before sending.' } });
2726
3511
  return;
@@ -2786,7 +3571,7 @@ async function sendCheckAttempt(context, row) {
2786
3571
  try { writeSync(fd, JSON.stringify(dispatchClaim)); }
2787
3572
  finally { closeSync(fd); }
2788
3573
  (context.preparingDispatches ??= new WeakMap()).set(row, dispatchClaim);
2789
- if (context.interrupted || context.ports.now() >= context.deadline) {
3574
+ if (context.interrupted || context.ports.now() >= deadline) {
2790
3575
  preserveUnsentReplacement(context, row, path);
2791
3576
  await finishReservation(context, row, { state: 'not_run' });
2792
3577
  adoptClaims(context, row);
@@ -2804,10 +3589,10 @@ async function sendCheckAttempt(context, row) {
2804
3589
  ...(context.freshChecks || context.checkOptions?.fresh ? { fresh: true } : {}),
2805
3590
  ...(context.checkOptions ? { samples: context.checkOptions.samples,
2806
3591
  ...(context.checkOptions.step_ids ? { step_ids: context.checkOptions.step_ids } : {}) } : {}),
2807
- ...(context.serverFeatures?.includes('lazy-interfaces') ? { lazy_interfaces: true } : {}),
3592
+ ...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}),
2808
3593
  ...sourceProvenance(context) };
2809
3594
  let verdict;
2810
- try { verdict = await context.postCheck(request, row, Math.max(1, Math.min(context.ports.postMs, context.deadline - context.ports.now()))); }
3595
+ try { verdict = await context.postCheck(request, row, Math.max(1, Math.min(context.ports.postMs, deadline - context.ports.now())), deadline); }
2811
3596
  catch (error) {
2812
3597
  // Registration may throw before postJob starts dispatch. Keep the original
2813
3598
  // receipt while this invocation can still prove its exact claim was unsent.
@@ -2827,15 +3612,18 @@ async function sendCheckAttempt(context, row) {
2827
3612
  if (row.request_ids.length > 1 && !capacityRetryAllowed(context, row)) markCapacityUnknown(context, row);
2828
3613
  else markBusy(context, row, verdict.wait, verdict.observed_at);
2829
3614
  }
2830
- else if (verdict.kind === 'not_run') Object.assign(row, { state: 'not_run', note: verdict.note });
3615
+ else if (verdict.kind === 'not_run') {
3616
+ if (verdict.contention) backoffCheckWindow(context, id, verdict.note?.code || 'HTTP 429');
3617
+ Object.assign(row, { state: 'not_run', note: verdict.note });
3618
+ }
2831
3619
  else if (verdict.kind === 'stop') { Object.assign(row, { state: 'not_run', note: verdict.note }); context.stopped = verdict.note; if (verdict.blocked) context.blocked = verdict.note.message; }
2832
3620
  else if (verdict.kind === 'refused') Object.assign(row, { state: 'refused', refusals: [verdict.refusal] });
2833
3621
  // An explicit caller deadline also bounds recovery of a lost POST answer.
2834
3622
  else {
3623
+ const readUntil = Number.isFinite(deadline) ? deadline : context.ports.now() + LOST_READ_MS;
2835
3624
  if (verdict.capacity_uncertain) markCapacityUnknown(context, row);
2836
- else Object.assign(row, { state: 'unknown', why: verdict.why, lost: true, read_until: Number.isFinite(context.deadline)
2837
- ? context.deadline : context.ports.now() + LOST_READ_MS });
2838
- row.lost = true; row.read_until = Number.isFinite(context.deadline) ? context.deadline : context.ports.now() + LOST_READ_MS;
3625
+ else Object.assign(row, { state: 'unknown', why: verdict.why, lost: true, read_until: readUntil });
3626
+ row.lost = true; row.read_until = readUntil;
2839
3627
  }
2840
3628
  }
2841
3629
 
@@ -2850,10 +3638,12 @@ function sourceProvenance(context, capture = context?.capture) {
2850
3638
 
2851
3639
  // GET one open row once.
2852
3640
  async function readRow(context, row, deadline = Infinity) {
2853
- const id = row.request_ids.at(-1), end = Math.min(context.deadline, deadline, row.lost ? row.read_until ?? context.deadline : context.deadline);
3641
+ const rowEnd = rowDeadline(context, row);
3642
+ const id = row.request_ids.at(-1), end = Math.min(rowEnd, deadline, row.lost ? row.read_until ?? rowEnd : rowEnd);
2854
3643
  if (!id || context.interrupted || context.ports.now() >= end) return;
2855
3644
  const verdict = judgeGet(await context.runtime.get(id, Math.max(1, Math.min(GET_MS, (end ?? Infinity) - context.ports.now()))), id, 'check');
2856
3645
  verdict.observed_at = context.ports.now();
3646
+ if (verdict.kind === 'again' && verdict.contention) backoffCheckWindow(context, `get:${id}:${Math.floor(verdict.observed_at / 5000)}`, 'HTTP 429');
2857
3647
  // A network problem while reading says so once; pdd keeps reading the same IDs.
2858
3648
  if (verdict.kind === 'again' && verdict.why && !context.readTrouble) line(context.ports.stderr, `pdd cannot read the results right now (${verdict.why}). It keeps trying.`);
2859
3649
  if (verdict.kind !== 'again') context.readTrouble = false; else if (verdict.why) context.readTrouble = true;
@@ -2949,9 +3739,11 @@ function readRecentLint(context) {
2949
3739
  // Every lint asks for complete per-test verdicts: only they can admit a test.
2950
3740
  async function runLint(context) {
2951
3741
  const agent = context.agentLimit ?? !context.ports.interactive;
2952
- const lintEnd = context.intent === 'check' && !context.checkDeadlineStarted
3742
+ const batchLintCap = context.batchTimeoutMin != null ? context.startedAt + context.batchTimeoutMin * 60_000 : Infinity;
3743
+ const baseLintEnd = context.intent === 'check' && !context.checkDeadlineStarted
2953
3744
  ? context.timeoutMin ? context.startedAt + Math.min(context.timeoutMin * 60_000, context.ports.interactive ? Infinity : AGENT_WAIT_MIN * 60_000) : Infinity
2954
3745
  : context.batch ? context.deadline : Math.min(context.deadline, agent ? context.startedAt + AGENT_WAIT_MIN * 60_000 : Infinity);
3746
+ const lintEnd = Math.min(baseLintEnd, batchLintCap);
2955
3747
  const tick = progressTicker(context.ports.stderr, context.ports.now);
2956
3748
  let paused = false;
2957
3749
  const stopped = () => ({ kind: 'not_run', note: { code: 'interrupted', message: paused ? stoppedPause(context, context.lint, 'lint')
@@ -2959,9 +3751,10 @@ async function runLint(context) {
2959
3751
  const busy = () => {
2960
3752
  if (context.interrupted) return stopped();
2961
3753
  const ended = context.ports.now() >= lintEnd;
3754
+ const explicitBatch = ended && context.explicitBatchTimeout && lintEnd === batchLintCap;
2962
3755
  const explicit = ended && context.explicitTimeout && lintEnd === context.deadline;
2963
- const note = { code: ended ? explicit ? 'timeout-flag' : 'deadline' : 'lint-busy',
2964
- message: `${explicit ? `Stopped waiting at --timeout ${context.timeoutMin} min. ` : ''}Your wait ended while pdd waited for ${context.waitCause ?? 'server capacity'}. No checks ran. Run the same pdd command again later.` };
3756
+ const note = { code: ended ? (explicit || explicitBatch) ? 'timeout-flag' : 'deadline' : 'lint-busy',
3757
+ message: `${explicitBatch ? `Stopped waiting at --batch-timeout ${context.batchTimeoutMin} min. ` : explicit ? `Stopped waiting at --timeout ${context.timeoutMin} min. ` : ''}Your wait ended while pdd waited for ${context.waitCause ?? 'server capacity'}. No checks ran. Run the same pdd command again later.` };
2965
3758
  Object.assign(context.lint, { state: 'not_run', note });
2966
3759
  return { kind: 'not_run', note };
2967
3760
  };
@@ -3029,7 +3822,7 @@ async function runLint(context) {
3029
3822
  const request = { requestId: context.ports.randomUUID(), source_sha256: context.capture.sha256, complete: true, ...named,
3030
3823
  ...sourceProvenance(context),
3031
3824
  ...(selectedCap != null ? { max_calls: selectedCap } : {}),
3032
- ...(context.serverFeatures?.includes('lazy-interfaces') ? { lazy_interfaces: true } : {}) };
3825
+ ...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}) };
3033
3826
  context.lint.request_ids.push(request.requestId);
3034
3827
  const verdict = await postJob(context, '/v1/lint', 'lint', request, null, Math.max(1, Math.min(context.ports.postMs, lintEnd - context.ports.now())), lintEnd);
3035
3828
  if (verdict.kind === 'busy') { if (await pause(verdict.wait, verdict.maintenance)) continue; return busy(); }
@@ -3040,10 +3833,17 @@ async function runLint(context) {
3040
3833
  let readEnd = verdict.kind === 'unknown' && !Number.isFinite(lintEnd)
3041
3834
  ? context.ports.now() + LOST_READ_MS : lintEnd;
3042
3835
  let answer = verdict.answer ?? null, id = request.requestId, lost = false;
3836
+ const lintPollStart = context.ports.now();
3837
+ const lintLongPoll = !context.ports.pollMsExplicit && context.serverFeatures?.includes('wait-prefer-v1');
3043
3838
  while (!['passed', 'failed', 'refused', 'unknown'].includes(answer?.state) && context.ports.now() < readEnd && !context.interrupted) {
3044
- await context.ports.sleep(Math.min(context.ports.pollMs, Math.max(0, readEnd - context.ports.now())), context.signal);
3045
- if (context.interrupted || context.ports.now() >= readEnd) break;
3046
- const read = judgeGet(await context.runtime.get(id, Math.max(1, Math.min(GET_MS, readEnd - context.ports.now()))), id, 'lint');
3839
+ if (!lintLongPoll) {
3840
+ const delay = context.ports.pollDelay(context.ports.now() - lintPollStart);
3841
+ await context.ports.sleep(Math.min(delay, Math.max(0, readEnd - context.ports.now())), context.signal);
3842
+ if (context.interrupted || context.ports.now() >= readEnd) break;
3843
+ }
3844
+ const remainingMs = Math.max(1, readEnd - context.ports.now());
3845
+ const waitSeconds = lintLongPoll ? Math.min(WAIT_PREFER_RUN_SECONDS, Math.max(1, Math.floor(remainingMs / 1000))) : 0;
3846
+ const read = judgeGet(await context.runtime.get(id, Math.max(1, Math.min(GET_MS, remainingMs)), { waitSeconds }), id, 'lint');
3047
3847
  if (read.kind === 'state') {
3048
3848
  answer = read.answer;
3049
3849
  if (['queued', 'running'].includes(answer.state)) readEnd = lintEnd;
@@ -3052,7 +3852,13 @@ async function runLint(context) {
3052
3852
  else if (read.kind === 'unknown') { lost = true; break; }
3053
3853
  else if (read.kind === 'blocked') throw new Stop(5, read.message);
3054
3854
  else if (read.kind === 'auth' || read.kind === 'gate') return { kind: 'stop', note: { code: null, message: read.kind === 'auth' ? AUTH_TEXT : 'The runtime opens soon.' } };
3055
- if (!['passed', 'failed', 'refused', 'unknown'].includes(answer?.state)) tick(`Still checking the files: ${waitWord(answer, read)}`);
3855
+ if (!['passed', 'failed', 'refused', 'unknown'].includes(answer?.state)) {
3856
+ tick(`Still checking the files: ${waitWord(answer, read)}`);
3857
+ if (lintLongPoll) {
3858
+ const delay = context.ports.pollDelay(context.ports.now() - lintPollStart);
3859
+ await context.ports.sleep(Math.min(delay, Math.max(0, readEnd - context.ports.now())), context.signal);
3860
+ }
3861
+ }
3056
3862
  }
3057
3863
  if (!lost && answer?.state === 'refused' && safeAdmission({ json: answer })) {
3058
3864
  const refusals = [answer.result?.report?.refusal, ...(Array.isArray(answer.result?.refusals) ? answer.result.refusals : [])];
@@ -3093,7 +3899,8 @@ async function checkBatch(context, rows, priorLint = null) {
3093
3899
  const lint = priorLint ?? await runLint(context);
3094
3900
  if (context.intent === 'check' && !context.checkDeadlineStarted) {
3095
3901
  context.checkDeadlineStarted = true;
3096
- context.deadline = context.timeoutMin ? ports.now() + context.timeoutMin * 60_000 : Infinity;
3902
+ context.batchDeadline = context.batchTimeoutMin != null ? ports.now() + context.batchTimeoutMin * 60_000 : Infinity;
3903
+ context.deadline = context.batchDeadline;
3097
3904
  }
3098
3905
  context.lastCheckLint = lint;
3099
3906
  context.lint.state = lint.answer?.state ?? lint.kind;
@@ -3134,18 +3941,30 @@ async function runScheduledChecks(context, rows, toSend) {
3134
3941
  // Saved live-local observations may poll original IDs, but cannot admit work.
3135
3942
  if (context.liveLocalSaved) toSend = [];
3136
3943
  const { ports } = context;
3137
- context.checkWindow ??= localLimit(context);
3944
+ ensureConcurrencyState(context);
3138
3945
  for (const row of toSend) row.attempts = 0;
3946
+ if (context.timeoutMin != null) {
3947
+ const startNow = ports.now();
3948
+ for (const row of rows) {
3949
+ if (isOpen(row) && row.story_deadline === undefined) {
3950
+ row.story_deadline = startNow + context.timeoutMin * 60_000;
3951
+ }
3952
+ }
3953
+ }
3139
3954
  const pendingSends = new Map(), uploads = uploadLimit(context);
3140
3955
  // Refill on a POST's settlement even while the polling loop awaits GETs.
3141
3956
  // Waiting rows stay outside admission and dispatch-claim allocation.
3142
3957
  const pumpSends = () => {
3143
- if (context.liveLocalSaved || context.interrupted || context.readStop || context.stopped || context.sendError || ports.now() >= context.deadline) return;
3144
- const active = rows.filter(occupiesSlot).length;
3958
+ const now = ports.now();
3959
+ if (context.liveLocalSaved || context.interrupted || context.readStop || context.stopped || context.sendError || now >= batchDeadlineOf(context)) return;
3960
+ const active = rows.filter(row => occupiesSlot(row) && !rowExpired(context, row, now)).length;
3145
3961
  const available = Math.max(0, Math.min(uploads - pendingSends.size, context.checkWindow - active - pendingSends.size));
3146
3962
  const eligible = toSend.filter(row => !pendingSends.has(row) && !row.awaiting_budget && ['ready', 'waiting'].includes(row.state)
3147
- && (!row.retry_at || ports.now() >= row.retry_at));
3963
+ && !rowExpired(context, row, now) && (!row.retry_at || now >= row.retry_at));
3148
3964
  for (const row of eligible.slice(0, available)) {
3965
+ if (row.story_deadline === undefined) {
3966
+ row.story_deadline = context.timeoutMin != null ? now + context.timeoutMin * 60_000 : Infinity;
3967
+ }
3149
3968
  const pending = sendCheck(context, row).catch(error => { context.sendError ??= error; }).finally(() => {
3150
3969
  pendingSends.delete(row);
3151
3970
  if (!row.awaiting_budget) {
@@ -3158,12 +3977,98 @@ async function runScheduledChecks(context, rows, toSend) {
3158
3977
  };
3159
3978
  let waitingShown = -1;
3160
3979
  const progress = context.checkProgress ??= { startedAt: ports.now(), shownAt: ports.now() };
3161
- const readable = row => isOpen(row) && ports.now() < Math.min(context.deadline, row.lost ? row.read_until ?? context.deadline : context.deadline);
3980
+ const pollStartedAt = ports.now();
3981
+ const readable = row => {
3982
+ if (!isOpen(row)) return false;
3983
+ const rowEnd = rowDeadline(context, row);
3984
+ const end = Math.min(rowEnd, row.lost ? row.read_until ?? rowEnd : rowEnd);
3985
+ return ports.now() < end;
3986
+ };
3987
+ const sseEnabled = !ports.pollMsExplicit && Boolean(context.serverFeatures?.includes('sse-stream-v1'));
3988
+ const activeStreams = new Map();
3989
+ let wakeResolve = null;
3990
+ const notifyWake = () => { if (wakeResolve) { const fn = wakeResolve; wakeResolve = null; fn(); } };
3991
+ const formatStageEvent = (row, json) => {
3992
+ const p = isObject(json.progress) ? json.progress : {};
3993
+ const stage = typeof json.stage === 'string' && json.stage ? json.stage : (typeof p.stage === 'string' ? p.stage : json.state);
3994
+ const stepPart = typeof p.steps_done === 'number' && typeof p.steps_total === 'number' && p.steps_total > 0
3995
+ ? `step ${Math.min(p.steps_done + 1, p.steps_total)}/${p.steps_total}${typeof p.step === 'string' && p.step ? ` (${p.step})` : ''}`
3996
+ : typeof p.step === 'string' && p.step ? p.step : stage;
3997
+ return `${row.test}: ${stepPart}`;
3998
+ };
3999
+ const abortExpiredStreams = () => {
4000
+ for (const [row, entry] of activeStreams) {
4001
+ if (!readable(row)) {
4002
+ entry.controller.abort();
4003
+ activeStreams.delete(row);
4004
+ }
4005
+ }
4006
+ };
4007
+ const syncRowStreams = () => {
4008
+ abortExpiredStreams();
4009
+ if (!sseEnabled || context.interrupted || context.readStop) return;
4010
+ for (const row of rows.filter(readable)) {
4011
+ const id = row.request_ids.at(-1);
4012
+ if (!id) continue;
4013
+ const existing = activeStreams.get(row);
4014
+ if (existing && existing.id === id) continue;
4015
+ if (existing) { existing.controller.abort(); activeStreams.delete(row); }
4016
+ if (activeStreams.size >= MAX_READS) break;
4017
+ const controller = new AbortController();
4018
+ const onSignal = () => controller.abort();
4019
+ context.signal?.addEventListener('abort', onSignal, { once: true });
4020
+ const rowEnd = rowDeadline(context, row);
4021
+ const end = Math.min(rowEnd, row.lost ? row.read_until ?? rowEnd : rowEnd);
4022
+ let lastStageKey = '';
4023
+ const entry = { id, controller };
4024
+ activeStreams.set(row, entry);
4025
+ entry.promise = context.runtime.streamRun(id, {
4026
+ useEventsPath: true,
4027
+ signal: controller.signal,
4028
+ timeoutMs: Math.max(1, end - ports.now()),
4029
+ onEvent: ({ event, json }) => {
4030
+ if (!isObject(json) || !sameJob(json, id, 'check')) return false;
4031
+ const enriched = (typeof json.stage === 'string' && json.stage && json.state === 'running')
4032
+ ? { ...json, progress: { ...(isObject(json.progress) ? json.progress : {}), stage: json.stage } }
4033
+ : json;
4034
+ if (event === 'done' || ENDED.has(enriched.state)) {
4035
+ saveAnswer(context, id, enriched);
4036
+ queueProgress(context, enriched);
4037
+ applyAnswer(row, enriched, context, null, ports.now());
4038
+ row.lost = false;
4039
+ finishReservation(context, row, enriched).finally(notifyWake);
4040
+ return true;
4041
+ }
4042
+ if (event === 'accepted' || event === 'progress') {
4043
+ saveAnswer(context, id, enriched);
4044
+ queueProgress(context, enriched);
4045
+ applyAnswer(row, enriched, context, null, ports.now());
4046
+ row.lost = false;
4047
+ if (event === 'progress') {
4048
+ const key = `${enriched.state}|${enriched.stage ?? ''}|${enriched.progress?.steps_done ?? ''}|${enriched.progress?.step ?? ''}`;
4049
+ if (key !== lastStageKey) {
4050
+ lastStageKey = key;
4051
+ progress.shownAt = ports.now();
4052
+ line(ports.stderr, `Progress: ${formatStageEvent(row, enriched)}`);
4053
+ }
4054
+ }
4055
+ }
4056
+ return false;
4057
+ },
4058
+ }).catch(() => null).finally(() => {
4059
+ context.signal?.removeEventListener('abort', onSignal);
4060
+ if (activeStreams.get(row) === entry) activeStreams.delete(row);
4061
+ notifyWake();
4062
+ });
4063
+ }
4064
+ };
3162
4065
  try {
3163
4066
  while (!context.interrupted && !context.readStop) {
3164
- // Never count an uncertain dispatched job as a free slot, even if it cannot currently be read.
3165
- const active = rows.filter(occupiesSlot).length;
3166
- if (!context.stopped && ports.now() < context.deadline && active < context.checkWindow) {
4067
+ abortExpiredStreams();
4068
+ // Never count an uncertain dispatched job as a free slot while active within its deadline.
4069
+ const now = ports.now();
4070
+ const active = rows.filter(row => occupiesSlot(row) && !rowExpired(context, row, now)).length;
4071
+ if (!context.stopped && now < batchDeadlineOf(context) && active < context.checkWindow) {
3167
4072
  pumpSends();
3168
4073
  // Admission can wait while previously dispatched rows continue to be read.
3169
4074
  if (!active && pendingSends.size) await Promise.race(pendingSends.values());
@@ -3171,7 +4076,7 @@ async function runScheduledChecks(context, rows, toSend) {
3171
4076
  saveBatch(context);
3172
4077
  }
3173
4078
  if (context.blocked && !rows.some(isOpen)) throw new Stop(5, context.blocked);
3174
- const waiting = toSend.filter(row => row.state === 'waiting');
4079
+ const waiting = toSend.filter(row => row.state === 'waiting' && !rowExpired(context, row));
3175
4080
  if (waiting.length !== waitingShown) {
3176
4081
  if (waiting.length) line(ports.stderr, `⏳ PDD is busy right now. ${waiting.length} of your checks ${waiting.length === 1 ? 'is' : 'are'} waiting to start. You are not charged while you wait.`);
3177
4082
  waitingShown = waiting.length;
@@ -3180,32 +4085,57 @@ async function runScheduledChecks(context, rows, toSend) {
3180
4085
  const earlyRestarts = await recoverRestarts(context);
3181
4086
  if (!context.liveLocalSaved) for (const row of rows.filter(row => row.state === 'ready' && (row.restart_used || row.restart_pending))) if (!toSend.includes(row)) toSend.push(row);
3182
4087
  if (earlyRestarts.length) { for (const item of toSend) item.awaiting_budget = false; pumpSends(); }
3183
- const pending = toSend.some(row => ['ready', 'waiting'].includes(row.state));
3184
- if (pending && active >= context.checkWindow && !rows.some(readable)) break;
3185
- if ((!pending || context.stopped || ports.now() >= context.deadline) && !rows.some(readable) && !pendingSends.size) break;
3186
- if (ports.now() - progress.shownAt >= PROGRESS_MS) { progress.shownAt = ports.now(); line(ports.stderr, progressLine(rows, progress.shownAt - progress.startedAt)); }
3187
- const end = context.deadline;
3188
- await ports.sleep(Math.max(0, Math.min(ports.pollMs, end - ports.now())), context.signal);
4088
+ const loopNow = ports.now();
4089
+ const activeAfter = rows.filter(row => occupiesSlot(row) && !rowExpired(context, row, loopNow)).length;
4090
+ const pending = toSend.some(row => ['ready', 'waiting'].includes(row.state) && !rowExpired(context, row, loopNow));
4091
+ if (pending && activeAfter >= context.checkWindow && !rows.some(readable) && !pendingSends.size) break;
4092
+ if ((!pending || context.stopped || loopNow >= batchDeadlineOf(context)) && !rows.some(readable) && !pendingSends.size) break;
4093
+ if (loopNow - progress.shownAt >= PROGRESS_MS) { progress.shownAt = loopNow; line(ports.stderr, progressLine(rows, progress.shownAt - progress.startedAt)); }
4094
+ syncRowStreams();
4095
+ const deadlines = [batchDeadlineOf(context)];
4096
+ for (const row of rows) {
4097
+ if (readable(row)) {
4098
+ const rowEnd = rowDeadline(context, row);
4099
+ deadlines.push(Math.min(rowEnd, row.lost ? row.read_until ?? rowEnd : rowEnd));
4100
+ } else if (['ready', 'waiting'].includes(row.state) && !rowExpired(context, row, loopNow)) {
4101
+ deadlines.push(rowDeadline(context, row));
4102
+ }
4103
+ }
4104
+ const end = Math.min(...deadlines);
4105
+ const delay = ports.pollDelay(loopNow - pollStartedAt);
4106
+ const waitMs = Math.max(0, Math.min(activeStreams.size ? PROGRESS_MS : delay, end - loopNow));
4107
+ if (activeStreams.size) {
4108
+ const wake = new Promise(resolve => { wakeResolve = resolve; });
4109
+ await Promise.race([ports.sleep(waitMs, context.signal), wake]);
4110
+ wakeResolve = null;
4111
+ } else {
4112
+ await ports.sleep(waitMs, context.signal);
4113
+ }
3189
4114
  if (context.interrupted) break;
3190
- await eachLimited(rows.filter(readable), MAX_READS, row => readRow(context, row));
4115
+ const unstreamed = rows.filter(row => readable(row) && !activeStreams.has(row));
4116
+ if (unstreamed.length) await eachLimited(unstreamed, MAX_READS, row => readRow(context, row));
3191
4117
  for (const item of toSend) item.awaiting_budget = false;
3192
4118
  await recoverRestarts(context);
3193
4119
  if (!context.liveLocalSaved) for (const row of rows.filter(row => row.state === 'ready' && (row.restart_used || row.restart_pending))) if (!toSend.includes(row)) toSend.push(row);
3194
4120
  saveBatch(context);
3195
4121
  }
3196
4122
  } catch (error) { context.sendError ??= error; throw error; }
3197
- finally { await Promise.all(pendingSends.values()); }
4123
+ finally {
4124
+ for (const entry of activeStreams.values()) entry.controller.abort();
4125
+ await Promise.all([...pendingSends.values(), ...[...activeStreams.values()].map(entry => entry.promise)]);
4126
+ }
3198
4127
  if (context.sendError) throw context.sendError;
3199
4128
  const stoppedEarly = context.interrupted || !!context.readStop;
3200
- context.timedOut ||= !stoppedEarly && ports.now() >= context.deadline && rows.some(isOpen);
4129
+ context.timedOut ||= !stoppedEarly && rows.some(row => isOpen(row) && rowExpired(context, row));
3201
4130
  for (const row of toSend) {
3202
4131
  restoreReplacement(row); // A budget-held replacement may never have reached sendCheck.
3203
4132
  if (['ready', 'waiting'].includes(row.state)) Object.assign(row, { state: 'not_run', calls: row.restart_used || row.restart_pending ? accumulatedCalls(context, row) : 0, busy: true, can_retry: true,
3204
4133
  phase: row.request_ids.length ? 'server' : 'local', note: { code: 'check-busy', message: context.interrupted && row.busy && row.request_ids.length
3205
4134
  ? stoppedPause(context, row, 'check') : row.request_ids.length
3206
4135
  ? 'The interpreter stayed busy. No checks ran for this attempt. Retry this batch later.' : 'Held locally; this check was not sent. Retry this batch later.' } });
4136
+ const rowEnd = rowDeadline(context, row);
3207
4137
  if (row.state === 'unknown' && row.lost) row.why ??= stoppedEarly ? 'pdd stopped before it could read this run.'
3208
- : Number.isFinite(context.deadline) ? 'pdd could not read this run before the timeout.' : 'pdd could not read this run for 5 min after its answer was lost.';
4138
+ : Number.isFinite(rowEnd) ? 'pdd could not read this run before the timeout.' : 'pdd could not read this run for 5 min after its answer was lost.';
3209
4139
  }
3210
4140
  }
3211
4141
 
@@ -3226,6 +4156,7 @@ function printResult(context, rows, extra = {}) {
3226
4156
  return printLintResult(context, rows, lintProblems(context, answer), context.warnings ?? [], answer);
3227
4157
  }
3228
4158
  markDeadline(context, rows);
4159
+ reconcileStoryCriteria(rows, context);
3229
4160
  rows = rows.map(row => heldForLint(row) && !row.dispatchIncomplete ? { ...row, calls: 0 } : row);
3230
4161
  const { ports } = context, exitCode = context.localOnly && context.checkPlan?.full && context.checkPlan.prerequisites.length ? 4
3231
4162
  : ports.exitCodeFor(rows, { interrupted: context.interrupted, lintUnknown: context.lintUnknown || context.lintPending });
@@ -3233,7 +4164,7 @@ function printResult(context, rows, extra = {}) {
3233
4164
  const warnings = [...(context.warnings ?? []), ...engines.map(sha => `Warning: the interpreter engine is ${cleanText(sha).slice(0, 12)}, but pdd's local checks copy engine ${ENGINE_SHA.slice(0, 12)}. The engine stays the judge.`)];
3234
4165
  const coverage = exitCode === 5 && context.coverage?.runtime?.native_only === 0
3235
4166
  ? Object.fromEntries(Object.entries(context.coverage).filter(([key])=>key !== 'runtime')) : context.coverage;
3236
- const summary = renderJson({ batch: context.batch ?? null, repo: context.root, sourceSha256: context.capture?.sha256 ?? null, coverage, rows, exitCode, summaryLine: context.noFailed ? 'No failed Stories. 0 AI calls.' : summaryLine(rows, null, ports),
4167
+ const summary = renderJson({ batch: context.batch ?? null, repo: context.root, sourceSha256: context.capture?.sha256 ?? null, coverage, rows, exitCode, details: Boolean(context.details), summaryLine: context.noFailed ? 'No failed Stories. 0 AI calls.' : summaryLine(rows, null, ports),
3237
4168
  warnings: [...new Set([...warnings, ...(context.unmatched ?? [])]), ...rows.flatMap(row => (row.warnings ?? []).map(text => `${row.test}: ${text}`))] }, ports);
3238
4169
  if (context.intent === 'lint-only') {
3239
4170
  const id = context.lint?.request_ids?.at(-1), answer = id && context.store.read(join(context.folder, `${id}.json`));
@@ -3259,7 +4190,7 @@ function printResult(context, rows, extra = {}) {
3259
4190
  if (context.stopped && (!context.json || context.stopped.message === AUTH_TEXT)) line(ports.stderr, context.stopped.message);
3260
4191
  const scrub = text => (context.secrets ?? []).reduce((value, secret) => secret ? value.split(secret).join('[secret]') : value, text);
3261
4192
  if (context.json) line(ports.stdout, scrub(JSON.stringify(summary)));
3262
- else ports.stdout.write(scrub(renderText({ batch: context.batch, rows, coverage: context.coverage, warnings, details: context.details, timeoutMin: context.timeoutMin,
4193
+ else ports.stdout.write(scrub(renderText({ batch: context.batch, rows, coverage: context.coverage, warnings, details: context.details, timeoutMin: context.timeoutMin, batchTimeoutMin: context.batchTimeoutMin,
3263
4194
  now: ports.now(), noFailed: context.noFailed, interrupted: context.interrupted || !!context.readStop, reading: !!context.reading, exitCode, secrets: context.secrets, ...extra }, ports)));
3264
4195
  if (!context.json && summary.report_url) line(ports.stdout, `Report: ${summary.report_url}`);
3265
4196
  if (!context.json) for (const value of checkPlanResultLines(summary.check_scope)) line(ports.stdout, scrub(value));
@@ -3328,6 +4259,7 @@ function runFiles(cwd, words, options, ports) {
3328
4259
  // Locally the selected prompts' limits and interface format gates, SVG advice and privacy/capture checks run.
3329
4260
  async function runLintOnly(context, cwd, words, options, setRelease) {
3330
4261
  const { ports } = context, origin = runtimeOrigin(ports.env), { root, found, normalized } = localSetup(cwd, words, ports);
4262
+ found.warnings = scopedDiscoveryWarnings(found, normalized);
3331
4263
  context.excludeFixtureProjects = words.length === 0;
3332
4264
  const promptArgs = words.length > 0 && normalized.every(word => word.endsWith('.prompt.md') && found.visible.has(word));
3333
4265
  const paths = promptArgs ? normalized : (words.length ? undefined : [...found.discoveryVisible].filter(path => path.endsWith('.prompt.md')));
@@ -3386,7 +4318,7 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
3386
4318
  const activeLocalProblem = problem => localInterfaceProblem(problem) && !(allowMissingInterfaces && problem.code === 'interface-missing');
3387
4319
  context.coverage = bindingCoverage({ root, found, selected, includeRuntime:true, allowMissingInterfaces });
3388
4320
  // A test that the test name rule cannot use is refused here and never sent; the other tests are linted.
3389
- const rows = selected.map(test => ({ test: test.path, story: test.story, title: test.title, state: 'ready', phase: 'lint',
4321
+ const rows = selected.map(test => ({ test: test.path, story: test.story, story_path: test.storyPath, title: test.title, state: 'ready', phase: 'lint',
3390
4322
  refusals: [], request_ids: [], warnings: [], steps: Array.isArray(test.doc?.steps) ? test.doc.steps.filter(isObject) : [],
3391
4323
  app_maps: declaredMaps(test.doc),
3392
4324
  criterion_texts: Object.fromEntries((Array.isArray(test.doc?.criteria) ? test.doc.criteria : []).filter(isObject).map(item => [item.id, item.text])),
@@ -3458,7 +4390,12 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
3458
4390
  // Lint keeps engine validation ownership; only attach structural incomplete-coverage facts.
3459
4391
  for (const row of rows.filter(row => !row.unsent)) {
3460
4392
  const test = selected.find(test => test.path === row.test), checked = preflight({root,found,selected:[test],allowMissingInterfaces}).rows[0];
3461
- if (checked.not_checked?.length) Object.assign(row, {not_checked:checked.not_checked,criteria_total:checked.criteria_total});
4393
+ if (checked.not_checked?.length) Object.assign(row, {
4394
+ not_checked:checked.not_checked,
4395
+ own_not_checked:checked.not_checked.map(item=>({...item})),
4396
+ criteria_total:checked.criteria_total,
4397
+ criterion_texts:{...(row.criterion_texts ?? {}),...Object.fromEntries(checked.not_checked.map(item=>[item.criterion_id,item.text]))},
4398
+ });
3462
4399
  if (checked.refusals.some(item=>item.code==='unchecked-criteria')) Object.assign(row,
3463
4400
  {state:'refused',phase:'local',unsent:true,refusals:checked.refusals});
3464
4401
  }
@@ -3536,6 +4473,7 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
3536
4473
  : { state: outcome.state, refusals: outcome.refusals, ...(outcome.reason ? { note: { code: outcome.code || 'no-server-verdict', message: outcome.reason } } : {}) });
3537
4474
  incompleteCriteria(row);
3538
4475
  }
4476
+ reconcileStoryCriteria(rows, context);
3539
4477
  Object.assign(context.lint, { state: answer?.state ?? lint.kind, unknown: rows.some(row => row.state === 'unknown'), pending: false, public_result: resultOverall(rows) });
3540
4478
  saveBatch(context);
3541
4479
  return printLintResult(context, rows, problems, found.warnings, answer);
@@ -3572,7 +4510,7 @@ function printLintResult(context, rows, problems, warnings = [], answer = null)
3572
4510
  const matching = (listed ?? []).filter(item => item?.path === row.test);
3573
4511
  row.call_preflight = matching.length === 1 ? matching[0].call_preflight ?? null : null;
3574
4512
  }
3575
- rows.forEach(incompleteCriteria);
4513
+ reconcileStoryCriteria(rows, context);
3576
4514
  rows = [...rows.filter(row=>row.unsent),...rows.filter(row=>!row.unsent)];
3577
4515
  for (const row of rows) for (const problem of row.refusals ?? []) {
3578
4516
  // pdd's own per-test words stay on the row; every server or reached-prompt problem is listed once.
@@ -3706,6 +4644,7 @@ async function readUnsentLint(context, rows) {
3706
4644
  incompleteCriteria(row);
3707
4645
  if (!busy && outcome.state === 'unknown') context.lintUnknown = lint.unknown = true;
3708
4646
  }
4647
+ reconcileStoryCriteria(rows, context);
3709
4648
  lint.public_result = resultOverall([...judged.values()]);
3710
4649
  }
3711
4650
 
@@ -3802,8 +4741,12 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
3802
4741
  context.cacheReadInvocation = true;
3803
4742
  const { store, ports, root } = context;
3804
4743
  const progress = context.checkProgress ??= { startedAt: ports.now(), shownAt: ports.now() };
3805
- const timeout = options['--timeout'] === undefined ? quiet ? AGENT_WAIT_MIN : null : Number(options['--timeout']);
3806
- context.deadline ??= timeout === null ? Infinity : ports.now() + timeout * 60_000;
4744
+ const timeout = options['--timeout'] === undefined ? quiet ? AGENT_WAIT_MIN : null : parseTimeoutMinutes(options['--timeout'], '--timeout', { allowZero: true });
4745
+ const batchTimeout = parseTimeoutMinutes(options['--batch-timeout'], '--batch-timeout', { allowZero: true });
4746
+ const readStart = ports.now();
4747
+ context.batchTimeoutMin = batchTimeout;
4748
+ context.batchDeadline ??= batchTimeout === null ? Infinity : readStart + batchTimeout * 60_000;
4749
+ context.deadline ??= timeout === null ? context.batchDeadline : Math.min(context.batchDeadline, readStart + timeout * 60_000);
3807
4750
  context.timeoutMin = timeout; context.agentLimit = false;
3808
4751
  const name = batchWord ?? store.read(join(store.dir,'repos',`${store.repoKey(root)}.json`))?.last_batch;
3809
4752
  if (!name || !BATCH.test(name)) throw new Stop(2, name ? 'BATCH looks like 20261027-092747-k3f9.' : 'No saved check for this repository. Run pdd test first.');
@@ -3844,7 +4787,7 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
3844
4787
  allowSavedLocalReadFallback: !quiet && isLocalSavedBatchRead(context, saved),
3845
4788
  });
3846
4789
  if (identity.login !== saved.login) throw new Stop(5, `These runs belong to ${saved.login}. Run: gh auth switch -u ${saved.login}`);
3847
- Object.assign(context, { liveLocalSaved:saved.live_local===true,singleAttempt: context.singleAttempt || saved.single_attempt === true, allowMissingInterfaces: saved.lazy_interfaces === true, maxTotalCalls: Number.isSafeInteger(saved.max_total_calls) && saved.max_total_calls >= 1 ? saved.max_total_calls : null, excludeFixtureProjects: saved.exclude_fixture_projects === true, batch: name, origin: saved.origin, sourceSelection:saved.source_selection, nativeSource:saved.native_source, coverage: saved.coverage, maintenance: saved.maintenance ?? null, identity, intent: saved.intent, secrets: [identity.token], warnings: saved.warnings ?? [],
4790
+ Object.assign(context, { liveLocalSaved:saved.live_local===true,singleAttempt: context.singleAttempt || saved.single_attempt === true, allowMissingInterfaces: saved.lazy_interfaces === true, maxTotalCalls: Number.isSafeInteger(saved.max_total_calls) && saved.max_total_calls >= 1 ? saved.max_total_calls : null, excludeFixtureProjects: saved.exclude_fixture_projects === true, reservationsReconciledAt: saved.reservations_reconciled_at ?? null, batch: name, origin: saved.origin, sourceSelection:saved.source_selection, nativeSource:saved.native_source, coverage: saved.coverage, maintenance: saved.maintenance ?? null, identity, intent: saved.intent, secrets: [identity.token], warnings: saved.warnings ?? [],
3848
4791
  capture: { sha256: saved.source_sha256, files: saved.files.map(path => ({ path })), bytes: saved.bytes, stories:saved.contract_snapshots }, lint: saved.lint, head: saved.head, startedAt: Date.parse(saved.created_at) });
3849
4792
  runtimeOrigin({ PDD_RUNTIME_URL: saved.origin });
3850
4793
  context.auth = authSession({
@@ -3906,7 +4849,8 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
3906
4849
  if (admission?.error?.code === 'maintenance') {
3907
4850
  context.maintenance ??= normalizeMaintenance(admission.maintenance ?? admission.error.details, ports.now(), context.secrets);
3908
4851
  }
3909
- const wait = capacityDelay(admission.error) ?? maintenanceDelay(admission, ports.now());
4852
+ const wait = capacityDelay(admission.error) ?? maintenanceDelay(admission, ports.now())
4853
+ ?? (admission?.error?.code === 'rate-limited' && admission?.dispatch === 'not_started' && admission?.error?.details?.retryable !== false ? 5000 : null);
3910
4854
  if (wait !== null && accountingProof(admission) && capacityRetryAllowed(context, row)) { markBusy(context, row, wait); return; }
3911
4855
  markCapacityUnknown(context, row);
3912
4856
  }
@@ -3946,12 +4890,14 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
3946
4890
  await readRow(context, row, context.deadline);
3947
4891
  if (row.state === 'unknown' && row.lost) row.why ??= 'pdd could not read this run yet.';
3948
4892
  });
4893
+ const lintPendingStart = ports.now();
3949
4894
  while (context.lintPending && !context.interrupted && !context.readStop && ports.now() < context.deadline) {
3950
4895
  if (ports.now() - progress.shownAt >= PROGRESS_MS) {
3951
4896
  progress.shownAt = ports.now();
3952
4897
  line(ports.stderr, progressLine(rows, progress.shownAt - progress.startedAt));
3953
4898
  }
3954
- await ports.sleep(Math.max(0, Math.min(ports.pollMs, context.deadline - ports.now())), context.signal);
4899
+ const delay = ports.pollDelay(ports.now() - lintPendingStart);
4900
+ await ports.sleep(Math.max(0, Math.min(delay, context.deadline - ports.now())), context.signal);
3955
4901
  if (context.interrupted || ports.now() >= context.deadline) break;
3956
4902
  await readUnsentLint(context, rows);
3957
4903
  await eachLimited(rows.filter(isOpen), MAX_READS, row => readRow(context, row));
@@ -3959,8 +4905,16 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
3959
4905
  }
3960
4906
  const continued = await continueHeld(context, candidates, saved) ?? [];
3961
4907
  const replacements = await recoverRestarts(context);
4908
+ const newSends = new Set([...continued, ...replacements]);
4909
+ if (timeout !== null) {
4910
+ const readDeadline = readStart + timeout * 60_000;
4911
+ for (const row of rows) if (!newSends.has(row) && row.story_deadline === undefined) row.story_deadline = readDeadline;
4912
+ }
3962
4913
  if (continued.length || replacements.length || !quiet && rows.some(isOpen)) {
3963
- if (continued.length) context.reading = false;
4914
+ if (continued.length) {
4915
+ context.reading = false;
4916
+ if (!quiet) context.deadline = context.batchDeadline;
4917
+ }
3964
4918
  await runScheduledChecks(context, rows, [...continued, ...replacements]);
3965
4919
  }
3966
4920
  context.savedTestCache = saved.test_cache;
@@ -3978,7 +4932,7 @@ async function recoverRestarts(context) {
3978
4932
  return !row.restart_used && !statOrNull(claimPath(context, row).replace(/\.0\.dispatch\.json$/, '.restart.json'))
3979
4933
  && !row.restart_pending && !row.admitting && !context.restartDecisions?.has(id) && sameJob(answer, id, 'check') && (restarted(answer) || transientDrop(answer));
3980
4934
  });
3981
- if (!eligible.length || context.interrupted || context.ports.now() >= context.deadline) return [];
4935
+ if (!eligible.length || context.interrupted || context.ports.now() >= batchDeadlineOf(context)) return [];
3982
4936
  if (context.singleAttempt) {
3983
4937
  context.restartDecisions ??= new Set();
3984
4938
  for (const row of eligible) {
@@ -4023,7 +4977,7 @@ async function recoverRestarts(context) {
4023
4977
  const drops = admitted.filter(row => transientDrop(context.store.read(join(context.folder, `${row.request_ids.at(-1)}.json`))));
4024
4978
  // Backoff precedes the source recapture, so edits during the wait cannot
4025
4979
  // authorize a replacement of the original selected source.
4026
- if (drops.length && !await waitBudget(context, 1000)) return [];
4980
+ if (drops.length && !await waitBudget(context, 1000, batchDeadlineOf(context))) return [];
4027
4981
  let capture;
4028
4982
  try { capture = (!drops.length && context.recoveredSourceCapture) || context.ports.captureSource(context.root, { tests: sentTests(context.rows), appMap: null, excludeFixtureProjects: context.excludeFixtureProjects, ...(context.allowMissingInterfaces ? { allowMissingInterfaces: true } : {}) }); }
4029
4983
  catch (error) {
@@ -4037,7 +4991,7 @@ async function recoverRestarts(context) {
4037
4991
  lintDiagnostics(context, lint, context.rows);
4038
4992
  const selected = [];
4039
4993
  for (const row of admitted) {
4040
- if (context.interrupted || context.ports.now() >= context.deadline || !validSavedCheck(row)) continue;
4994
+ if (context.interrupted || rowExpired(context, row) || !validSavedCheck(row)) continue;
4041
4995
  const transient = drops.includes(row);
4042
4996
  const decision = evaluateCheckBudget({
4043
4997
  max_total_calls: context.maxTotalCalls ?? null,
@@ -4065,8 +5019,12 @@ async function recoverRestarts(context) {
4065
5019
 
4066
5020
  async function runRetry(context, name, options) {
4067
5021
  const { ports } = context;
4068
- const timeout = options['--timeout'] === undefined ? AGENT_WAIT_MIN : Number(options['--timeout']);
4069
- context.deadline = ports.now() + timeout * 60_000;
5022
+ const timeout = options['--timeout'] === undefined ? AGENT_WAIT_MIN : parseTimeoutMinutes(options['--timeout'], '--timeout');
5023
+ const batchTimeout = parseTimeoutMinutes(options['--batch-timeout'], '--batch-timeout');
5024
+ const retryStart = ports.now();
5025
+ context.batchTimeoutMin = batchTimeout;
5026
+ context.batchDeadline = batchTimeout === null ? Infinity : retryStart + batchTimeout * 60_000;
5027
+ context.deadline = Math.min(context.batchDeadline, retryStart + timeout * 60_000);
4070
5028
  const rows = await runRead(context, name, true, options, true);
4071
5029
  if (context.localLayout) {
4072
5030
  line(ports.stderr,'For new evidence, run a fresh pdd lint --local.');
@@ -4074,7 +5032,7 @@ async function runRetry(context, name, options) {
4074
5032
  }
4075
5033
  if (context.intent !== undefined && context.intent !== 'check') throw new Stop(2, 'The saved batch has no Check intent. Start a fresh selected pdd test.');
4076
5034
  if (context.localOnly) return () => printResult(context, rows);
4077
- if (context.interrupted || ports.now() >= context.deadline) return () => printResult(context, rows);
5035
+ if (context.interrupted || ports.now() >= context.deadline || ports.now() >= context.batchDeadline) return () => printResult(context, rows);
4078
5036
  const capture = Array.isArray(context.capture.sources) ? context.capture : context.ports.captureSource(context.root, { tests: sentTests(rows), appMap: null, excludeFixtureProjects: context.excludeFixtureProjects });
4079
5037
  if (capture.sha256 !== context.capture.sha256) throw new Stop(2, 'The saved source no longer matches: source changed. Start a fresh selected pdd test instead.');
4080
5038
  capture.stories = context.capture.stories;
@@ -4086,8 +5044,8 @@ async function runRetry(context, name, options) {
4086
5044
  const selected = retryable.filter(row => lintAdmits(lint, row, context.capture));
4087
5045
  if (retryable.length && !selected.length) throw new Stop(2, 'The saved lint cannot authorize recovery. Start a fresh selected pdd test.');
4088
5046
  if (selected.length) lintDiagnostics(context, lint, rows);
4089
- Object.assign(context, { capture, reading: false, timeoutMin: timeout });
4090
- for (const row of selected) row.state = row.retry_at > ports.now() ? 'waiting' : 'ready';
5047
+ Object.assign(context, { capture, reading: false, timeoutMin: timeout, deadline: context.batchDeadline });
5048
+ for (const row of selected) { delete row.story_deadline; row.state = row.retry_at > ports.now() ? 'waiting' : 'ready'; }
4091
5049
  if (selected.length) line(ports.stderr, `Retrying ${selected.length} unstarted check${selected.length === 1 ? '' : 's'}…`);
4092
5050
  await runScheduledChecks(context, rows, selected);
4093
5051
  saveBatch(context);
@@ -4170,6 +5128,7 @@ async function refreshCheckBatches(context, identity, origin, id, answer) {
4170
5128
  if (sameJob(receipt, latest, 'check')) applyAnswer(row, receipt, projection);
4171
5129
  return row;
4172
5130
  });
5131
+ reconcileStoryCriteria(rows, projection);
4173
5132
  const cache = await openTestCache(projection, root, false);
4174
5133
  cache.tokens = new Map(saved.test_cache.tokens);
4175
5134
  await finishTestAttempts(cache, rows, capture);
@@ -4341,16 +5300,16 @@ async function closeLocalBridges(context) {
4341
5300
  // Its lifetime covers scheduler waits, recovery and every phase of a retry.
4342
5301
  async function withCheckRun(context, run) {
4343
5302
  let ownership;
4344
- context.postCheck = async (request, row, timeoutMs) => {
5303
+ context.postCheck = async (request, row, timeoutMs, deadline = rowDeadline(context, row)) => {
4345
5304
  if(context.liveLocal) {
4346
5305
  const bridge=await newLocalBridge(context,'check',request.requestId);
4347
5306
  request={...request,resource_mode:'live',resource_setup:bridge.resource_setup};
4348
- const verdict=await postJob(context,'/v1/check','check',request,row,timeoutMs,context.deadline);
5307
+ const verdict=await postJob(context,'/v1/check','check',request,row,timeoutMs,deadline);
4349
5308
  if(verdict.kind==='accepted'&&!ENDED.has(verdict.answer?.state))await startLocalBridge(context,bridge,request.requestId);
4350
5309
  return verdict;
4351
5310
  }
4352
5311
  // Probes and diagnostic subsets own no ordinary pass generation or cache identity evidence.
4353
- if (context.stepIds?.length || context.checkOptions) return postJob(context, '/v1/check', 'check', request, row, timeoutMs, context.deadline);
5312
+ if (context.stepIds?.length || context.checkOptions) return postJob(context, '/v1/check', 'check', request, row, timeoutMs, deadline);
4354
5313
  ownership ??= (async () => {
4355
5314
  if (!context.testCache) {
4356
5315
  const cache = context.testCache = await openTestCache(context, context.root, false);
@@ -4361,7 +5320,7 @@ async function withCheckRun(context, run) {
4361
5320
  if (!cache.disabled && !cache.mark) await cacheTransaction(cache, data => markTestAttempt(cache, data));
4362
5321
  })();
4363
5322
  await ownership;
4364
- return postJob(context, '/v1/check', 'check', request, row, timeoutMs, context.deadline);
5323
+ return postJob(context, '/v1/check', 'check', request, row, timeoutMs, deadline);
4365
5324
  };
4366
5325
  let result;
4367
5326
  try { result = await run(); }
@@ -4377,7 +5336,7 @@ async function withCheckRun(context, run) {
4377
5336
  // pdd test. Returns the exit code.
4378
5337
  export async function runCheck({ words = [], options = {}, cwd = process.cwd(), cache = false, client, workflow } = {}, givenPorts = {}) {
4379
5338
  const ports = withDefaults(givenPorts);
4380
- const context = { ports, clientVersion: client?.version ?? ports.clientVersion ?? null, workflow, singleAttempt: ports.env.PDD_CHECK_SINGLE_ATTEMPT === '1', cacheEnabled: cache || !!options['--lf'] || !!options['--cache-clear'], freshChecks: !!options['--cache-clear'], json: options['--json'] === true, details: Boolean(options['--details'] || options.details), explicitTimeout: options['--timeout'] !== undefined, interrupted: false, warnings: [] };
5339
+ const context = { ports, clientVersion: client?.version ?? ports.clientVersion ?? null, workflow, singleAttempt: ports.env.PDD_CHECK_SINGLE_ATTEMPT === '1', cacheEnabled: cache || !!options['--lf'] || !!options['--cache-clear'], freshChecks: !!options['--cache-clear'], json: options['--json'] === true, details: Boolean(options['--details'] || options.details), explicitTimeout: options['--timeout'] !== undefined, explicitBatchTimeout: options['--batch-timeout'] !== undefined, interrupted: false, warnings: [] };
4381
5340
  let release = () => {};
4382
5341
  try {
4383
5342
  context.liveLocal=liveLocalOptions(options,'check');
@@ -4387,13 +5346,13 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
4387
5346
  if (!context.checkOptions && options['--step'] !== undefined) {
4388
5347
  const values = Array.isArray(options['--step']) ? options['--step'] : [options['--step']];
4389
5348
  if (!values.length || values.some(value=>typeof value !== 'string' || !value.trim())) throw new Stop(2, '--step needs one or more nonblank step IDs.');
4390
- if (['--read','--retry','--request','--files','--explain-bindings','--lint','--local','--affected','--full','--journeys','--journey','--parts','--screen','--drawing','--look'].some(key=>options[key] !== undefined)) throw new Stop(2, '--step accepts an ordinary new test selection; start a fresh selected pdd test.');
5349
+ if (['--read','--retry','--reconcile','--reconcile-stale','--request','--files','--explain-bindings','--lint','--local','--affected','--full','--journeys','--journey','--parts','--screen','--drawing','--look'].some(key=>options[key] !== undefined)) throw new Stop(2, '--step accepts an ordinary new test selection; start a fresh selected pdd test.');
4391
5350
  context.stepIds = [...new Set(values)]; context.cacheEnabled = false;
4392
5351
  }
4393
- if (options['--affected'] !== undefined && (options['--affected'] !== true || words.length || Object.keys(options).some(key => !['--affected','--json','--details','--timeout','--max-calls','--max-total-calls','--no-restart-replacement','--cache-clear'].includes(key))))
4394
- throw new Stop(2, '--affected accepts no Stories and only --cache-clear, --json, --details, --timeout, --max-calls, --max-total-calls and --no-restart-replacement.');
5352
+ if (options['--affected'] !== undefined && (options['--affected'] !== true || words.length || Object.keys(options).some(key => !['--affected','--json','--details','--timeout','--batch-timeout','--max-calls','--max-total-calls','--no-restart-replacement','--cache-clear'].includes(key))))
5353
+ throw new Stop(2, '--affected accepts no Stories and only --cache-clear, --json, --details, --timeout, --batch-timeout, --max-calls, --max-total-calls and --no-restart-replacement.');
4395
5354
  if(options['--journeys']!==undefined){
4396
- if(options['--journeys']!==true||words.length>1||['--read','--retry','--request','--screen','--drawing','--look'].some(key=>options[key]!==undefined))throw new Stop(2,'Use pdd test --journeys [JOURNEY] with normal test options.');
5355
+ if(options['--journeys']!==true||words.length>1||['--read','--retry','--reconcile','--reconcile-stale','--request','--screen','--drawing','--look'].some(key=>options[key]!==undefined))throw new Stop(2,'Use pdd test --journeys [JOURNEY] with normal test options.');
4397
5356
  const {root,found}=localSetup(cwd,[],ports);
4398
5357
  try { words=selectJourneys(found.tests.map(test=>({testPath:test.path,storyPath:test.storyPath})),words[0],ports); } catch(error) { if (error?.unboundPort) throw error; throw new Stop(2,error.message); }
4399
5358
  if(!words.length)throw new Stop(2,'No root product journeys found.');
@@ -4537,15 +5496,19 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
4537
5496
  const selectorInfo = selectorLintForPrompts({ root, visible: new Set(gitFiles(root)), paths: inspectedPrompts, workspace });
4538
5497
  context.selectorTableLines = selectorInfo.tableLines;
4539
5498
  const hygiene = lintLocalHygiene({ root, files, promptPaths, tests: selectedTests, workspace }, ports);
4540
- const warnings = [...new Set([...advice, ...selectorInfo.warnings, ...preflightWarnings, ...ports.lintSvgLayouts({ root, files, promptPaths }), ...hygiene])], summary = `partial: checked SVG layout only; prompts not checked (local-only). ${warnings.length} warnings. 0 AI calls. No checks were sent.`;
5499
+ const warnings = [...new Set([...advice, ...selectorInfo.warnings, ...preflightWarnings, ...ports.lintSvgLayouts({ root, files, promptPaths }), ...hygiene])];
5500
+ const localOutcome = problems.length ? `found ${problems.length} problem${problems.length === 1 ? '' : 's'}` : 'passed';
5501
+ const summary = `partial: local structural, scenario, app-map, hygiene, and SVG checks ${localOutcome}; remote cross-prompt lint not run (local-only). ${warnings.length} warnings. 0 AI calls. No checks were sent.`;
4541
5502
  const result = await saveLocalLayout(context,{root,tests,prompts:promptPaths ?? files.filter(path => path.endsWith('.prompt.md')),warnings,problems,summary});
4542
5503
  return printLocalLayout(context,result);
4543
5504
  } catch (error) { if (error?.unboundPort) throw error; throw new Stop(2, error.message); }
4544
5505
  }
4545
- const modes = ['--read', '--retry', '--files', '--explain-bindings', '--request', '--lint'].filter(name => options[name] !== undefined);
4546
- const others = Object.keys(options).filter(name => !modes.includes(name) && !(modes[0] === '--retry' && ['--json', '--details', '--timeout'].includes(name)) && !(name === '--json' && ['--read', '--request', '--lint', '--files', '--explain-bindings'].includes(modes[0])) && !(name === '--timeout' && ['--read', '--lint'].includes(modes[0])) && !(name === '--max-calls' && modes[0] === '--lint') && !(name === '--app-map' && modes[0] === '--files'));
4547
- if (modes.length > 1 || (modes.length && others.length) || (['--request', '--retry'].includes(modes[0]) && words.length)
5506
+ const modes = ['--read', '--retry', '--reconcile', '--reconcile-stale', '--files', '--explain-bindings', '--request', '--lint'].filter(name => options[name] !== undefined);
5507
+ const others = Object.keys(options).filter(name => !modes.includes(name) && !(['--retry', '--read'].includes(modes[0]) && ['--json', '--details', '--timeout', '--batch-timeout'].includes(name)) && !(name === '--json' && ['--request', '--reconcile', '--reconcile-stale', '--lint', '--files', '--explain-bindings'].includes(modes[0])) && !(name === '--timeout' && ['--lint'].includes(modes[0])) && !(name === '--max-calls' && modes[0] === '--lint') && !(name === '--app-map' && modes[0] === '--files'));
5508
+ if (modes.length > 1 || (modes.length && others.length) || (['--request', '--retry', '--reconcile', '--reconcile-stale'].includes(modes[0]) && words.length)
4548
5509
  || (modes[0] === '--read' && words.length > 1) || (!modes.length && options['--app-map'] !== undefined)) throw new Stop(2, 'This mix of options does not work together. Run pdd test --help.');
5510
+ if (modes[0] === '--reconcile') return await runReconcileCommand(context, options['--reconcile'], cwd, givenPorts);
5511
+ if (modes[0] === '--reconcile-stale') return await runReconcileStaleCommand(context, options['--reconcile-stale'], cwd, givenPorts);
4549
5512
  if (modes[0] === '--request') { release = interruptible(context); return await runRequest(context, options['--request'], cwd); }
4550
5513
  const root = repoRoot(cwd);
4551
5514
  if (modes[0] === '--explain-bindings') return runExplainBindings(cwd, words, options, ports);
@@ -4574,7 +5537,7 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
4574
5537
  coverage: { available: false, bound: null, total: null, modules: [] }, problems: [{ code: 'binding-invalid', path: 'pdd-bindings.json', message: error.message }], rows: [], warnings: [] }));
4575
5538
  else if (context.coverage && error.exitCode !== 5) {
4576
5539
  if (context.json) line(ports.stdout, JSON.stringify({ batch: context.batch ?? null, repo: context.root, exit_code: error.exitCode,
4577
- coverage: context.coverage, lint_state: error.exitCode === 3 ? 'partial' : 'not run', ...resultOutcome({ state: error.exitCode === 3 ? 'partial' : 'not run', note: { code: error.exitCode === 3 && context.timeoutMin ? 'timeout-flag' : 'no-server-verdict', message: error.message } }), problems: [], rows: [], warnings: context.warnings, message: error.message }));
5540
+ coverage: context.coverage, lint_state: error.exitCode === 3 ? 'partial' : 'not run', ...resultOutcome({ state: error.exitCode === 3 ? 'partial' : 'not run', note: { code: error.exitCode === 3 && (context.timeoutMin != null || context.batchTimeoutMin != null) ? 'timeout-flag' : 'no-server-verdict', message: error.message } }), problems: [], rows: [], warnings: context.warnings, message: error.message }));
4578
5541
  else line(ports.stdout, coverageText(context.coverage));
4579
5542
  }
4580
5543
  return error.exitCode;
@@ -4626,7 +5589,11 @@ function safeCachePath(fs, path, { directory = false, create = false } = {}) {
4626
5589
  at = join(at, parts[index]);
4627
5590
  const isDir = index < parts.length - 1 || directory;
4628
5591
  let stat = cacheStat(fs, at);
4629
- if (!stat && create && isDir) { fs.mkdir(at, { mode: 0o700 }); stat = fs.lstat(at); }
5592
+ if (!stat && create && isDir) {
5593
+ try { fs.mkdir(at, { mode: 0o700 }); }
5594
+ catch (error) { if (error?.code !== 'EEXIST') throw error; }
5595
+ stat = fs.lstat(at);
5596
+ }
4630
5597
  if (!stat) { if (index < parts.length - 1) throw new Error('missing cache parent'); continue; }
4631
5598
  if (stat.isSymbolicLink() || (isDir ? !stat.isDirectory() : !stat.isFile())) throw new Error('unsafe cache path');
4632
5599
  }
@@ -4637,8 +5604,10 @@ function validTestCache(value) {
4637
5604
  const path = text => typeof text === 'string' && text.length > 0 && text.length <= 4096 && !text.startsWith('/') && !text.split('/').some(part => !part || part === '.' || part === '..');
4638
5605
  const hash = text => typeof text === 'string' && /^[a-f0-9]{64}$/.test(text);
4639
5606
  const counts = value => value == null || keys(value, ['passed', 'total']) && ['passed', 'total'].every(key => Number.isSafeInteger(value[key]) && value[key] >= 0) && value.passed <= value.total;
4640
- const evidence = row => keys(row, ['checks', 'criteria', 'criteria_total', 'draft']) && counts(row.checks) && counts(row.criteria)
4641
- && (row.criteria_total === undefined || Number.isSafeInteger(row.criteria_total) && row.criteria_total >= 0) && typeof row.draft === 'boolean';
5607
+ const evidence = row => keys(row, ['checks', 'criteria', 'criteria_total', 'draft', 'calls', 'max_calls']) && counts(row.checks) && counts(row.criteria)
5608
+ && (row.criteria_total === undefined || Number.isSafeInteger(row.criteria_total) && row.criteria_total >= 0) && typeof row.draft === 'boolean'
5609
+ && (row.calls === undefined || Number.isSafeInteger(row.calls) && row.calls >= 0)
5610
+ && (row.max_calls === undefined || Number.isSafeInteger(row.max_calls) && row.max_calls >= 1);
4642
5611
  if (!keys(value, ['schema_version', 'generation', 'epoch', 'stories', 'latest_identity']) || typeof value.epoch !== 'string' || !UUID.test(value.epoch) || value.schema_version !== 1 || !Number.isSafeInteger(value.generation) || value.generation < 0 || !isObject(value.stories) || Object.keys(value.stories).length > 10000) return false;
4643
5612
  const latest = value.latest_identity;
4644
5613
  if (latest !== undefined && (!keys(latest, ['engine_sha', 'models', 'observed_at', 'sampled_at', 'engine_shas', 'conflict', 'clean', 'written_at', 'in_progress', 'cohort'])
@@ -4656,13 +5625,26 @@ function validTestCache(value) {
4656
5625
  || ![latest.observed_at, latest.sampled_at].every(at => typeof at === 'string' && Number.isFinite(Date.parse(at)) && new Date(at).toISOString() === at))) return false;
4657
5626
  return Object.entries(value.stories).every(([name, row]) => path(name) && keys(row, ['generation', 'outcome', 'pass']) && Number.isSafeInteger(row.generation) && row.generation >= 0 && row.generation <= value.generation
4658
5627
  && ['passed', 'failed', 'refused', 'not_run', 'unknown'].includes(row.outcome)
4659
- && (row.pass === undefined || (row.outcome === 'passed' && keys(row.pass, ['fingerprint', 'passed_at', 'tests', 'rows', 'engine_sha', 'requested_model']) && hash(row.pass.fingerprint)
5628
+ && (row.pass === undefined || (row.outcome === 'passed' && keys(row.pass, ['fingerprint', 'passed_at', 'tests', 'rows', 'engine_sha', 'requested_model', 'calls_used', 'max_calls']) && hash(row.pass.fingerprint)
5629
+ && (row.pass.calls_used === undefined || Number.isSafeInteger(row.pass.calls_used) && row.pass.calls_used >= 0)
5630
+ && (row.pass.max_calls === undefined || row.pass.max_calls === null || Number.isSafeInteger(row.pass.max_calls) && row.pass.max_calls >= 1)
4660
5631
  && typeof row.pass.passed_at === 'string' && Number.isFinite(Date.parse(row.pass.passed_at)) && new Date(row.pass.passed_at).toISOString() === row.pass.passed_at
4661
5632
  && Array.isArray(row.pass.tests) && row.pass.tests.length > 0 && row.pass.tests.every(path) && new Set(row.pass.tests).size === row.pass.tests.length
4662
5633
  && keys(row.pass.rows, row.pass.tests) && Object.keys(row.pass.rows).length === row.pass.tests.length && row.pass.tests.every(test => evidence(row.pass.rows[test])))));
4663
5634
  }
4664
- function cacheWarning(cache, recovered = false) {
4665
- const message = 'Warning: test cache unavailable or damaged; running selected Stories without reuse. To reset, run pdd test --cache-clear.';
5635
+ function summarizeCacheError(cache, error) {
5636
+ if (!error) return null;
5637
+ const secrets = cache?.context?.secrets ?? [];
5638
+ const code = typeof error?.code === 'string' && error.code.trim() ? cleanText(error.code, secrets).slice(0, 40) : '';
5639
+ const msg = typeof error?.message === 'string' && error.message.trim() ? cleanText(error.message, secrets).slice(0, 140) : '';
5640
+ if (code && msg) return msg.startsWith(code) ? msg : `${code}: ${msg}`;
5641
+ return code || msg || null;
5642
+ }
5643
+ function cacheWarning(cache, recovered = false, error = null) {
5644
+ const detail = summarizeCacheError(cache, error);
5645
+ const message = detail
5646
+ ? `Warning: test cache unavailable or damaged (${detail}); running selected Stories without reuse. To reset, run pdd test --cache-clear.`
5647
+ : 'Warning: test cache unavailable or damaged; running selected Stories without reuse. To reset, run pdd test --cache-clear.';
4666
5648
  if (!cache.warned) cache.warningIndex = cache.context.warnings.push(message) - 1;
4667
5649
  else if (cache.recoveredWarning) cache.context.warnings[cache.warningIndex] = message;
4668
5650
  cache.recoveredWarning = false;
@@ -4783,7 +5765,7 @@ async function acquireCacheGuard(cache) {
4783
5765
  if (!Number.isSafeInteger(ticket)) throw new Error('cache ticket overflow');
4784
5766
  fs.write(join(own, 'ticket.tmp'), JSON.stringify(ticket), { flag: 'wx', mode: 0o600 });
4785
5767
  fs.rename(join(own, 'ticket.tmp'), join(own, 'ticket.json'));
4786
- for (let attempt = 0; attempt < 30; attempt++) {
5768
+ for (let attempt = 0; attempt < 100; attempt++) {
4787
5769
  if (!peers().some(peer => peer.ticket === null || peer.ticket < ticket || peer.ticket === ticket && peer.name < name)) return () => remove(own);
4788
5770
  await cache.context.ports.sleep(10);
4789
5771
  }
@@ -4796,7 +5778,7 @@ async function cacheTransaction(cache, operation, clear = false) {
4796
5778
  try {
4797
5779
  safeCachePath(cache.fs, cache.dir, { directory: true });
4798
5780
  releaseGuard = await acquireCacheGuard(cache);
4799
- for (let attempt = 0; attempt < 30; attempt++) {
5781
+ for (let attempt = 0; attempt < 100; attempt++) {
4800
5782
  try {
4801
5783
  cache.fs.mkdir(cache.lock); locked = true;
4802
5784
  owner = { pid: process.pid, token: cache.fs.nonce() };
@@ -4836,7 +5818,7 @@ async function cacheTransaction(cache, operation, clear = false) {
4836
5818
  try { snapshot = readTestCache(cache); }
4837
5819
  catch (error) {
4838
5820
  safeCachePath(cache.fs, cache.path);
4839
- cacheWarning(cache, true);
5821
+ cacheWarning(cache, true, error);
4840
5822
  // A new namespace prevents an earlier in-flight generation from matching.
4841
5823
  snapshot = { data: freshTestCache(cache), history: false };
4842
5824
  }
@@ -4861,16 +5843,16 @@ async function cacheTransaction(cache, operation, clear = false) {
4861
5843
  try { cache.fs.unlink(path); } catch (error) { if (error.code !== 'ENOENT') throw error; }
4862
5844
  }
4863
5845
  return result;
4864
- } catch { cacheWarning(cache); return null; }
5846
+ } catch (error) { cacheWarning(cache, false, error); return null; }
4865
5847
  finally {
4866
5848
  if (locked) try {
4867
5849
  const path = join(cache.lock, 'owner.json');
4868
5850
  safeCachePath(cache.fs, path);
4869
5851
  if (owner && isDeepStrictEqual(JSON.parse(cache.fs.read(path, 'utf8', 128)), owner)) {
4870
5852
  cache.fs.unlink(path); cache.fs.rmdir(cache.lock);
4871
- } else cacheWarning(cache);
4872
- } catch { cacheWarning(cache); }
4873
- if (releaseGuard) try { releaseGuard(); } catch { cacheWarning(cache); }
5853
+ } else cacheWarning(cache, false, new Error('cache lock ownership changed'));
5854
+ } catch (error) { cacheWarning(cache, false, error); }
5855
+ if (releaseGuard) try { releaseGuard(); } catch (error) { cacheWarning(cache, false, error); }
4874
5856
  }
4875
5857
  }
4876
5858
  async function openTestCache(context, root, clear, visible) {
@@ -4918,7 +5900,7 @@ async function openTestCache(context, root, clear, visible) {
4918
5900
  cache.history = false;
4919
5901
  }
4920
5902
  }, clear);
4921
- } catch { cacheWarning(cache); }
5903
+ } catch (error) { cacheWarning(cache, false, error); }
4922
5904
  return cache;
4923
5905
  }
4924
5906
  function storyFingerprint(cache, capture, story, options, origin) {
@@ -4927,7 +5909,7 @@ function storyFingerprint(cache, capture, story, options, origin) {
4927
5909
  const rawPaths = [...new Set([story, ...footprint.tests, ...footprint.files.filter(file => file.path.endsWith('.prompt.md')).map(file => file.path)])].sort();
4928
5910
  const raw = rawPaths.map(path => [path, capture.raw_file_hashes?.[path] ?? (path.endsWith('.prompt.md') ? capture.raw_prompt_hashes?.[path] : undefined)]);
4929
5911
  if (raw.some(([, hash]) => !hash)) return null;
4930
- return cache.context.ports.cacheHash(Buffer.from(JSON.stringify({ footprint, raw, origin, max_calls: options['--max-calls'] ?? null, pdd_version: cache.context.clientVersion ?? null })));
5912
+ return cache.context.ports.cacheHash(Buffer.from(JSON.stringify({ footprint, raw, origin, pdd_version: cache.context.clientVersion ?? null })));
4931
5913
  }
4932
5914
  // The captured footprint owns reachability; inspect its captured declarations without
4933
5915
  // inventing another dependency graph or reading a later version of a source file.
@@ -4998,6 +5980,46 @@ function eligibleCachePass(pass, now) {
4998
5980
  function identityFingerprint(cache, fingerprint, identity) {
4999
5981
  return cache.context.ports.cacheHash(Buffer.from(JSON.stringify({ fingerprint, engine_sha: identity?.engine_sha ?? null, requested_model: identity?.requested_model ?? null })));
5000
5982
  }
5983
+ function liveInProgressMarks(cache, marks) {
5984
+ const isAlive = cache.context.ports.isAlive ?? (pid => { try { process.kill(pid, 0); return true; } catch (error) { return error.code !== 'ESRCH'; } });
5985
+ return (marks ?? []).filter(mark => isAlive(mark.pid));
5986
+ }
5987
+ function hasVerifiedIdentityRecord(record) {
5988
+ return !!record && record.conflict === false
5989
+ && typeof record.engine_sha === 'string' && record.engine_sha.trim() && record.engine_sha.trim().toLowerCase() !== 'unknown'
5990
+ && Array.isArray(record.models) && record.models.length === 1
5991
+ && typeof record.models[0] === 'string' && record.models[0].trim() && record.models[0].trim().toLowerCase() !== 'unknown'
5992
+ && (record.engine_shas ?? [record.engine_sha]).every(value => value === record.engine_sha);
5993
+ }
5994
+ function verifiedIdentityMatchesPass(cache, record, pass, story) {
5995
+ if (!record || !pass) return false;
5996
+ if (cleanRecordMatches(record, pass)) return true;
5997
+ if (!hasVerifiedIdentityRecord(record)) return false;
5998
+ if (!observedIdentityMatches(record, pass)) return false;
5999
+ const live = liveInProgressMarks(cache, record.in_progress);
6000
+ if (!live.length) return record.clean === true || record.conflict === false;
6001
+ const cohort = record.cohort;
6002
+ if (!cohort || cohort.valid === false) return false;
6003
+ if (cohort.engine_sha !== null && cohort.engine_sha !== pass.engine_sha) return false;
6004
+ if (cohort.requested_model !== null && cohort.requested_model !== pass.requested_model) return false;
6005
+ const liveTokens = new Set(live.map(mark => mark.token));
6006
+ for (const member of cohort.members ?? []) {
6007
+ if (liveTokens.has(member.token) && member.stories.includes(story)) return false;
6008
+ }
6009
+ return live.every(mark => (cohort.members ?? []).some(member => member.token === mark.token));
6010
+ }
6011
+ function passSatisfiesMaxCalls(pass, own) {
6012
+ for (const row of own) {
6013
+ if (!Number.isSafeInteger(row.max_calls) || row.max_calls < 1) continue;
6014
+ const savedRow = pass?.rows?.[row.test];
6015
+ const required = Number.isSafeInteger(savedRow?.calls) ? savedRow.calls
6016
+ : Number.isSafeInteger(pass?.calls_used) ? pass.calls_used
6017
+ : Number.isSafeInteger(savedRow?.max_calls) ? savedRow.max_calls
6018
+ : Number.isSafeInteger(pass?.max_calls) ? pass.max_calls : 0;
6019
+ if (row.max_calls < required) return false;
6020
+ }
6021
+ return true;
6022
+ }
5001
6023
  // Call only while holding the cache transaction; normal and saved-read sends
5002
6024
  // share ownership so another invocation cannot reuse evidence while either runs.
5003
6025
  function markTestAttempt(cache, data) {
@@ -5015,15 +6037,17 @@ function markTestAttempt(cache, data) {
5015
6037
  cache.mark = { token: cache.fs.nonce(), pid: cache.context.ports.pid ?? process.pid, started_at: cache.context.ports.now() };
5016
6038
  const latest = data.latest_identity ?? { engine_sha: null, models: [], clean: false, conflict: true,
5017
6039
  sampled_at: new Date(0).toISOString(), observed_at: new Date(cache.context.ports.now()).toISOString() };
5018
- const isAlive = cache.context.ports.isAlive ?? (pid => { try { process.kill(pid, 0); return true; } catch (error) { return error.code !== 'ESRCH'; } });
5019
6040
  // Eligibility already saw every mark, including dead owners. Only now retire
5020
6041
  // dead marks; live owners must survive another invocation's finish.
5021
6042
  const oldMarks = latest.in_progress ?? [];
5022
- const live = oldMarks.filter(mark => isAlive(mark.pid));
6043
+ const live = liveInProgressMarks(cache, oldMarks);
5023
6044
  const stories = [...cache.tokens.keys()];
5024
- if (!oldMarks.length) latest.cohort = { members: [], valid: true, engine_sha: null, requested_model: null, floor: Date.parse(latest.sampled_at) };
5025
- else if (!latest.cohort || live.length !== oldMarks.length || !oldMarks.every(mark => latest.cohort.members.some(member => member.token === mark.token))) latest.cohort = { members: [], valid: false, engine_sha: null, requested_model: null, floor: Date.parse(latest.sampled_at) };
5026
- if (cache.mark.started_at <= latest.cohort.floor) latest.cohort.valid = false;
6045
+ const verifiedBase = hasVerifiedIdentityRecord(latest);
6046
+ if (!live.length) {
6047
+ latest.cohort = { members: [], valid: true, engine_sha: verifiedBase ? latest.engine_sha : null, requested_model: verifiedBase ? latest.models[0] : null, floor: Date.parse(latest.sampled_at) };
6048
+ } else if (!latest.cohort || !live.every(mark => latest.cohort.members.some(member => member.token === mark.token))) {
6049
+ latest.cohort = { members: [], valid: false, engine_sha: null, requested_model: null, floor: Date.parse(latest.sampled_at) };
6050
+ }
5027
6051
  if (latest.cohort.members.some(member => member.stories.some(story => stories.includes(story)))) latest.cohort.valid = false;
5028
6052
  latest.cohort.members.push({ token: cache.mark.token, stories });
5029
6053
  latest.in_progress = [...live, cache.mark];
@@ -5041,14 +6065,21 @@ async function beginTestAttempts(cache, rows, capture, options, origin, force =
5041
6065
  const fingerprint = capture ? storyFingerprint(cache, capture, story, options, origin) : null;
5042
6066
  const pass = data.stories[story]?.pass;
5043
6067
  const eligible = eligibleCachePass(pass, cache.context.ports.now()) && fingerprint && pass.fingerprint === identityFingerprint(cache, fingerprint, pass) && own.every(row => row.state === 'ready' && pass.tests.includes(row.test));
6068
+ const budgetAllows = !eligible || passSatisfiesMaxCalls(pass, own);
5044
6069
  const identity = data.latest_identity;
5045
- const knownDrift = identity && cleanRecordMatches(identity, { engine_sha: identity.engine_sha, requested_model: identity.models?.[0] }) && ((identity.engine_sha && identity.engine_sha !== pass?.engine_sha) || (identity.models?.length === 1 && identity.models[0] !== pass?.requested_model));
6070
+ const knownDrift = hasVerifiedIdentityRecord(identity) && ((identity.engine_sha && identity.engine_sha !== pass?.engine_sha) || (identity.models?.length === 1 && identity.models[0] !== pass?.requested_model));
5046
6071
  const reason = capture && declarationCacheReason(capture, story, own.map(row => row.test))
5047
6072
  || (Number.isFinite(Date.parse(pass?.passed_at)) && cache.context.ports.now() - Date.parse(pass.passed_at) > 7 * 86400000 ? 'runs again: saved pass is older than seven days' : null)
5048
- || (eligible && !cleanRecordMatches(identity, pass) ? (knownDrift ? 'runs again: interpreter build or model changed' : 'runs again: cache identity is unverified') : null);
6073
+ || (eligible && !budgetAllows ? 'runs again: --max-calls is lower than the saved pass call count' : null)
6074
+ || (eligible && !verifiedIdentityMatchesPass(cache, identity, pass, story) ? (knownDrift ? 'runs again: interpreter build or model changed' : 'runs again: cache identity is unverified') : null);
5049
6075
  if (reason) for (const row of own) row.cache_reason ??= reason;
5050
- if (!force && !reason && [undefined, '', '0', 'false'].includes(cache.context.ports.env.CI) && eligibleCachePass(pass, cache.context.ports.now()) && fingerprint && pass?.fingerprint === identityFingerprint(cache, fingerprint, pass) && own.every(row => row.state === 'ready' && pass.tests.includes(row.test))) {
5051
- for (const row of own) Object.assign(row, pass.rows[row.test], { state: 'passed', cached: true, cache_identity: { engine_sha: pass.engine_sha, requested_model: pass.requested_model }, passed_at: pass.passed_at, phase: 'cache', calls: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, cached_input_share: null, seconds: 0, request_ids: [], report_url: null });
6076
+ if (!force && !reason && [undefined, '', '0', 'false'].includes(cache.context.ports.env.CI) && eligible && budgetAllows) {
6077
+ for (const row of own) {
6078
+ const { checks, criteria, criteria_total, draft } = pass.rows[row.test];
6079
+ delete row.not_checked;
6080
+ delete row.own_not_checked;
6081
+ Object.assign(row, { checks, criteria, criteria_total, draft, state: 'passed', cached: true, cache_identity: { engine_sha: pass.engine_sha, requested_model: pass.requested_model }, passed_at: pass.passed_at, phase: 'cache', calls: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, cached_input_share: null, seconds: 0, request_ids: [], report_url: null });
6082
+ }
5052
6083
  continue;
5053
6084
  }
5054
6085
  const generation = ++data.generation;
@@ -5066,42 +6097,100 @@ async function finishTestAttempts(cache, rows, capture) {
5066
6097
  await cacheTransaction(cache, data => {
5067
6098
  const observations = cache.context.observedTestIdentities ?? [];
5068
6099
  const previous = data.latest_identity;
5069
- const identity = { engine_sha: observations.find(item => item.engine_sha)?.engine_sha ?? null,
5070
- requested_model: observations.flatMap(item => item.models).find(Boolean) ?? null };
6100
+ const observedEngines = [...new Set(observations.map(item => item.engine_sha).filter(Boolean))];
6101
+ const observedModels = [...new Set(observations.flatMap(item => item.models).filter(Boolean))];
6102
+ const hasObservedConflict = observedEngines.length > 1 || observedModels.length > 1 || observations.some(item => item.conflict);
6103
+ const identity = {
6104
+ engine_sha: observedEngines.length === 1 ? observedEngines[0] : null,
6105
+ requested_model: observedModels.length === 1 ? observedModels[0] : null,
6106
+ };
5071
6107
  const terminalObservations = observations.filter(item => item.terminal);
5072
- const complete = terminalObservations.length > 0 && terminalObservations.every(item => item.complete)
5073
- && observations.every(item => observedIdentityMatches(item, identity));
6108
+ const identityVerified = !hasObservedConflict && !!identity.engine_sha && !!identity.requested_model && terminalObservations.length > 0;
5074
6109
  const marks = previous?.in_progress ?? [];
5075
6110
  const ownMark = mark => !!cache.mark && mark.token === cache.mark.token;
5076
- const remaining = marks.filter(mark => !ownMark(mark));
5077
- const unchanged = cache.identitySnapshot === JSON.stringify(previous ?? null);
6111
+ const liveRemaining = liveInProgressMarks(cache, marks.filter(mark => !ownMark(mark)));
5078
6112
  const cohort = previous?.cohort;
5079
- const member = cohort?.members.find(item => ownMark(item));
5080
- const ordinary = !!member && marks.some(ownMark) && !cache.context.cacheReadInvocation && !cache.context.checkRunFailed && Number.isFinite(cache.context.startedAt) && cache.context.startedAt > cohort.floor && complete;
5081
- if (cohort) {
5082
- cohort.valid &&= ordinary && marks.every(mark => cohort.members.some(item => item.token === mark.token));
5083
- if (cohort.engine_sha !== null && cohort.engine_sha !== identity.engine_sha || cohort.requested_model !== null && cohort.requested_model !== identity.requested_model) cohort.valid = false;
5084
- if (cohort.engine_sha === null) cohort.engine_sha = identity.engine_sha;
5085
- if (cohort.requested_model === null) cohort.requested_model = identity.requested_model;
5086
- }
5087
- const clean = !remaining.length && ordinary && (unchanged && (!previous || cache.context.startedAt > Date.parse(previous.sampled_at)) || cohort?.valid === true && cohort.members.length > 1);
5088
- data.latest_identity = { engine_sha: identity.engine_sha, models: identity.requested_model ? [identity.requested_model] : [],
5089
- in_progress: remaining, ...(remaining.length && cohort ? { cohort } : {}), clean, conflict: !clean, sampled_at: new Date(Number.isFinite(cache.context.startedAt) ? cache.context.startedAt : 0).toISOString(),
5090
- written_at: new Date(cache.context.ports.now()).toISOString(), observed_at: new Date(cache.context.ports.now()).toISOString() };
6113
+ const nowIso = new Date(cache.context.ports.now()).toISOString();
6114
+ if (cache.context.cacheReadInvocation) {
6115
+ if (previous && marks.some(ownMark)) {
6116
+ data.latest_identity = { ...previous, in_progress: liveRemaining, ...(liveRemaining.length && cohort ? { cohort } : {}) };
6117
+ if (!liveRemaining.length) delete data.latest_identity.cohort;
6118
+ }
6119
+ } else if (!observations.length) {
6120
+ // No server response was observed (e.g., local error/interrupt before HTTP settlement).
6121
+ // Retire our in-progress mark without erasing a previously verified identity.
6122
+ if (previous) {
6123
+ const preservedClean = !liveRemaining.length && hasVerifiedIdentityRecord(previous);
6124
+ const next = { ...previous, in_progress: liveRemaining, clean: preservedClean, conflict: !hasVerifiedIdentityRecord(previous), written_at: nowIso, observed_at: nowIso };
6125
+ if (liveRemaining.length && cohort) next.cohort = cohort;
6126
+ else delete next.cohort;
6127
+ data.latest_identity = next;
6128
+ }
6129
+ } else {
6130
+ let cohortConflict = false;
6131
+ if (cohort) {
6132
+ if (!identityVerified) {
6133
+ cohort.valid = false;
6134
+ cohortConflict = true;
6135
+ } else {
6136
+ if ((cohort.engine_sha !== null && cohort.engine_sha !== identity.engine_sha)
6137
+ || (cohort.requested_model !== null && cohort.requested_model !== identity.requested_model)) {
6138
+ cohort.valid = false;
6139
+ cohortConflict = true;
6140
+ }
6141
+ if (cohort.engine_sha === null) cohort.engine_sha = identity.engine_sha;
6142
+ if (cohort.requested_model === null) cohort.requested_model = identity.requested_model;
6143
+ if (cohort.valid === false) cohortConflict = true;
6144
+ }
6145
+ }
6146
+ const clean = !liveRemaining.length && identityVerified && !cohortConflict;
6147
+ const conflict = hasObservedConflict || cohortConflict || !identityVerified;
6148
+ data.latest_identity = {
6149
+ engine_sha: identity.engine_sha,
6150
+ models: identity.requested_model ? [identity.requested_model] : [],
6151
+ in_progress: liveRemaining,
6152
+ ...(liveRemaining.length && cohort ? { cohort } : {}),
6153
+ clean,
6154
+ conflict,
6155
+ sampled_at: new Date(Number.isFinite(cache.context.startedAt) ? cache.context.startedAt : 0).toISOString(),
6156
+ written_at: nowIso,
6157
+ observed_at: nowIso,
6158
+ };
6159
+ }
5091
6160
  for (const [story, token] of cache.tokens) {
5092
6161
  if (data.epoch !== token.epoch || data.stories[story]?.generation !== token.generation) continue;
5093
6162
  const own = rows.filter(row => row.story_path === story && !row.cached), footprint = capture.stories?.find(item => item.story_path === story);
5094
6163
  const complete = footprint?.tests.length === own.length && footprint.tests.every(test => own.some(row => row.test === test));
5095
6164
  const outcome = own.some(row => row.state === 'failed') ? 'failed' : own.some(row => row.state === 'refused') ? 'refused' : own.some(row => row.state === 'not_run') ? 'not_run' : complete && own.length && own.every(row => row.state === 'passed' && typeof row.calls === 'number' && row.accounting_complete === true) && !cache.context.interrupted && !cache.context.lintUnknown ? 'passed' : 'unknown';
5096
6165
  const record = data.stories[story] = { generation: token.generation, outcome: outcome !== 'passed' && data.stories[story]?.outcome === 'failed' ? 'failed' : outcome };
5097
- const identity = own[0]?.cache_identity;
5098
- const consistent = identity && own.every(row => sameCacheIdentity(identity, row.cache_identity))
5099
- && rows.filter(row => !row.cached && row.cache_identity).every(row => sameCacheIdentity(identity, row.cache_identity))
5100
- && observations.every(observed => observedIdentityMatches(observed, identity));
6166
+ const rowIdentity = own[0]?.cache_identity;
6167
+ const consistent = rowIdentity && own.every(row => sameCacheIdentity(rowIdentity, row.cache_identity))
6168
+ && rows.filter(row => !row.cached && row.cache_identity).every(row => sameCacheIdentity(rowIdentity, row.cache_identity))
6169
+ && observations.every(observed => observedIdentityMatches(observed, rowIdentity));
5101
6170
  const sampledAt = Math.min(cache.context.startedAt, ...own.map(row => row.cache_sample_at).filter(Number.isFinite));
5102
6171
  if (outcome === 'passed' && token.fingerprint && consistent && Number.isFinite(sampledAt)) {
5103
- record.pass = { ...identity, fingerprint: identityFingerprint(cache, token.fingerprint, identity), tests: footprint.tests, passed_at: new Date(sampledAt).toISOString(),
5104
- rows: Object.fromEntries(own.map(row => [row.test, { checks: row.checks, criteria: row.criteria, criteria_total: row.criteria_total, draft: !!row.draft }])) };
6172
+ const effectiveCalls = row => Math.max(
6173
+ typeof row.calls === 'number' ? row.calls : 0,
6174
+ Number.isSafeInteger(row.saved_answer_original_calls) && row.saved_answer_original_calls >= 0 ? row.saved_answer_original_calls : 0,
6175
+ );
6176
+ const callsUsed = Math.max(0, ...own.map(effectiveCalls));
6177
+ const maxCallsValues = own.map(row => row.max_calls).filter(value => Number.isSafeInteger(value) && value >= 1);
6178
+ record.pass = {
6179
+ ...rowIdentity,
6180
+ fingerprint: identityFingerprint(cache, token.fingerprint, rowIdentity),
6181
+ tests: footprint.tests,
6182
+ passed_at: new Date(sampledAt).toISOString(),
6183
+ calls_used: callsUsed,
6184
+ max_calls: maxCallsValues.length ? Math.max(...maxCallsValues) : null,
6185
+ rows: Object.fromEntries(own.map(row => [row.test, {
6186
+ checks: row.checks,
6187
+ criteria: row.criteria,
6188
+ criteria_total: row.criteria_total,
6189
+ draft: !!row.draft,
6190
+ calls: effectiveCalls(row),
6191
+ ...(Number.isSafeInteger(row.max_calls) && row.max_calls >= 1 ? { max_calls: row.max_calls } : {}),
6192
+ }])),
6193
+ };
5105
6194
  }
5106
6195
  }
5107
6196
  });
@@ -5145,7 +6234,8 @@ async function runBatch(context, cwd, words, options, setRelease) {
5145
6234
  context.visible = found.visible; context.origin = origin; context.excludeFixtureProjects = words.length === 0;
5146
6235
  // Ordinary Check waits for completion in every shell unless a limit is explicit.
5147
6236
  context.agentLimit = false;
5148
- context.timeoutMin = options['--timeout'] !== undefined ? Number(options['--timeout']) : null;
6237
+ context.timeoutMin = parseTimeoutMinutes(options['--timeout'], '--timeout');
6238
+ context.batchTimeoutMin = parseTimeoutMinutes(options['--batch-timeout'], '--batch-timeout');
5149
6239
  let selected = select(found, normalized, root, ports);
5150
6240
  const diagnostic = context.stepIds?.length > 0;
5151
6241
  const preliminary = diagnostic ? preflight({root,found,selected,allowMissingInterfaces:true,stepIds:context.stepIds}) : null;
@@ -5195,7 +6285,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5195
6285
  discoveryChanged ||= !isDeepStrictEqual(initialDiscovery,discoveryScope(current.found));
5196
6286
  return current;
5197
6287
  };
5198
- const priorReservations = readUnresolvedPriorReservations(root, ports.env, context.batch ?? null);
6288
+ const priorReservations = readUnresolvedPriorReservations(root, ports.env, context.batch ?? null, { now: ports.now() });
5199
6289
  const planPolicyOptions = {
5200
6290
  maxCalls: options['--max-calls'] !== undefined ? Number(options['--max-calls']) : null,
5201
6291
  maxTotalCalls: context.maxTotalCalls ?? null,
@@ -5213,9 +6303,13 @@ async function runBatch(context, cwd, words, options, setRelease) {
5213
6303
  // only this attempt's mark, leaving its invalidations and other owners intact.
5214
6304
  if (cache?.mark) await cacheTransaction(cache, data => {
5215
6305
  if (data.latest_identity?.in_progress) {
5216
- data.latest_identity.in_progress = data.latest_identity.in_progress.filter(mark=>mark.token!==cache.mark.token);
5217
- Object.assign(data.latest_identity,{clean:false,conflict:true});
5218
- if (data.latest_identity.cohort) data.latest_identity.cohort.valid = false;
6306
+ const remaining = liveInProgressMarks(cache, data.latest_identity.in_progress.filter(mark=>mark.token!==cache.mark.token));
6307
+ data.latest_identity.in_progress = remaining;
6308
+ if (!remaining.length) {
6309
+ delete data.latest_identity.cohort;
6310
+ const preserved = hasVerifiedIdentityRecord(data.latest_identity);
6311
+ Object.assign(data.latest_identity, { clean: preserved, conflict: !preserved });
6312
+ }
5219
6313
  }
5220
6314
  });
5221
6315
  if (context.testCache === cache) context.testCache = null;
@@ -5262,6 +6356,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5262
6356
  if (test?.error) row.unsent = true;
5263
6357
  row.criterion_texts = Object.fromEntries([...(Array.isArray(test?.doc?.criteria) ? test.doc.criteria : []).filter(isObject).map(item => [item.id, item.text]),
5264
6358
  ...(row.not_checked??[]).map(item=>[item.criterion_id,item.text])]);
6359
+ if (row.not_checked?.length) row.own_not_checked = row.not_checked.map(item => ({ ...item }));
5265
6360
  }
5266
6361
  if (options['--max-calls'] !== undefined) for (const row of rows) row.max_calls = Number(options['--max-calls']);
5267
6362
  if (context.checkOptions) for (const row of rows) {
@@ -5291,7 +6386,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5291
6386
  }
5292
6387
 
5293
6388
  const scopedOwnership = words.length > 0 || affected || selected.length < found.tests.length;
5294
- context.warnings.push(...found.warnings, ...checked.warnings, ...sharedSourceFiles(root, found.discoveryVisible ?? found.visible, { ...(scopedOwnership ? { tests: selected } : {}), workspace: found.workspace }, ports));
6389
+ context.warnings.push(...scopedDiscoveryWarnings(found, normalized), ...checked.warnings, ...sharedSourceFiles(root, found.discoveryVisible ?? found.visible, { ...(scopedOwnership ? { tests: selected } : {}), workspace: found.workspace }, ports));
5295
6390
  context.unmatched = unmatchedLines(found);
5296
6391
  if (cache) await beginTestAttempts(cache, rows.filter(row => row.state !== 'ready'), null, options, origin);
5297
6392
  if (!rows.some(row => row.state === 'ready')) { if (rows.some(row => row.native_only?.length)) await saveLocalNativeResult(context, rows, 'check'); return printResult(context, rows); }
@@ -5325,9 +6420,13 @@ async function runBatch(context, cwd, words, options, setRelease) {
5325
6420
  catch (error) {
5326
6421
  if (cache?.mark) await cacheTransaction(cache, data => {
5327
6422
  if (data.latest_identity?.in_progress) {
5328
- data.latest_identity.in_progress = data.latest_identity.in_progress.filter(mark => mark.token !== cache.mark.token);
5329
- Object.assign(data.latest_identity, { clean: false, conflict: true });
5330
- if (data.latest_identity.cohort) data.latest_identity.cohort.valid = false;
6423
+ const remaining = liveInProgressMarks(cache, data.latest_identity.in_progress.filter(mark => mark.token !== cache.mark.token));
6424
+ data.latest_identity.in_progress = remaining;
6425
+ if (!remaining.length) {
6426
+ delete data.latest_identity.cohort;
6427
+ const preserved = hasVerifiedIdentityRecord(data.latest_identity);
6428
+ Object.assign(data.latest_identity, { clean: preserved, conflict: !preserved });
6429
+ }
5331
6430
  }
5332
6431
  });
5333
6432
  throw error;
@@ -5340,7 +6439,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5340
6439
  if(context.liveLocal)context.localOwner??=identity.login;
5341
6440
  const startedAt = ports.now(), batch = batchId(startedAt, ports.randomUUID);
5342
6441
  const head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
5343
- Object.assign(context, { capture, identity, batch, startedAt, deadline: Infinity, rows,
6442
+ Object.assign(context, { capture, identity, batch, startedAt, deadline: Infinity, batchDeadline: Infinity, rows,
5344
6443
  intent: 'check', head: capture.source_commit ?? (head.status === 0 ? head.stdout.trim() : null), secrets: [identity.token], lint: { request_ids: [], state: null } });
5345
6444
  context.folder = context.store.folder('batches', batch);
5346
6445
  setRelease(interruptible(context));
@@ -5364,7 +6463,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5364
6463
  for (const row of rerun) {
5365
6464
  const original = originals.get(row.test), storyPath = row.story_path, texts = row.criterion_texts, appMaps = row.app_maps;
5366
6465
  for (const key of Object.keys(row)) delete row[key];
5367
- Object.assign(row, original, { story_path: storyPath, criterion_texts: texts, ...(appMaps?.length ? { app_maps: appMaps } : {}), cache_reason: 'runs again: interpreter build or model changed' });
6466
+ Object.assign(row, original, { story_path: storyPath, criterion_texts: texts, ...(original.not_checked?.length ? { own_not_checked: original.not_checked.map(item => ({ ...item })) } : {}), ...(appMaps?.length ? { app_maps: appMaps } : {}), cache_reason: 'runs again: interpreter build or model changed' });
5368
6467
  if (options['--max-calls'] !== undefined) row.max_calls = Number(options['--max-calls']);
5369
6468
  }
5370
6469
  await beginTestAttempts(cache, rerun, capture, options, origin, true);
@@ -5384,13 +6483,21 @@ async function runBatch(context, cwd, words, options, setRelease) {
5384
6483
  // ---- pdd simulate ----
5385
6484
 
5386
6485
  // The app map for the Screen tab: --app-map, else app-map.json at the root, else app/app-map.json.
5387
- // An app map is a Git-visible JSON object with schema_version prompt-runtime.app-map.v1 and a name (the engine's first checks).
6486
+ // An app map is a Git-visible JSON object with screens and optional compact fields (v1 or v2).
5388
6487
  const APP_MAP_VERSION = 'prompt-runtime.app-map.v1';
6488
+ const APP_MAP_VERSIONS = new Set(['prompt-runtime.app-map.v1', 'prompt-runtime.app-map.v2']);
5389
6489
  function appMapProblem(root, path) {
5390
6490
  let doc;
5391
6491
  try { doc = JSON.parse(readFileSync(join(root, path), 'utf8')); } catch { return 'it is not JSON'; }
5392
- if (!isObject(doc) || doc.schema_version !== APP_MAP_VERSION) return `its schema_version is not "${APP_MAP_VERSION}"`;
5393
- if (typeof doc.name !== 'string' || !doc.name) return 'it has no "name"';
6492
+ if (!isObject(doc)) return 'it is not a JSON object';
6493
+ if (Object.hasOwn(doc, 'schema_version') && !APP_MAP_VERSIONS.has(doc.schema_version)) return `its schema_version is not "${APP_MAP_VERSION}"`;
6494
+ if (Object.hasOwn(doc, 'name') && (typeof doc.name !== 'string' || !doc.name)) return 'its "name" must be a nonempty string';
6495
+ const hasScreens = Array.isArray(doc.screens) && doc.screens.length > 0;
6496
+ const hasV1Name = doc.schema_version === APP_MAP_VERSION && typeof doc.name === 'string' && doc.name.length > 0;
6497
+ if (!hasScreens && !hasV1Name) {
6498
+ if (doc.schema_version === APP_MAP_VERSION && !Object.hasOwn(doc, 'screens')) return 'it has no "name"';
6499
+ return 'it has no "screens"';
6500
+ }
5394
6501
  return null;
5395
6502
  }
5396
6503
 
@@ -5484,7 +6591,11 @@ function simulationSelection(root, found, words, appMap, options, ports) {
5484
6591
  const hasHttp = rows.some(row => row.http.size);
5485
6592
  const screens = appMap ? JSON.parse(readFileSync(join(root, appMap), 'utf8')).screens : [];
5486
6593
  const mapped = Array.isArray(screens) && selected.some(test => (Array.isArray(test.doc?.steps) ? test.doc.steps : []).some(step => step && screens.some(screen => screen?.source === 'operation' && screen.prompt_path === step.entry_path && screen.operation === step.operation)));
5487
- const typed = words.length && !cli.size && !hasHttp && !mapped;
6594
+ const plainUi = !appMap && !cli.size && !hasHttp && selected.some(test => (Array.isArray(test.doc?.steps) ? test.doc.steps : []).some(step => {
6595
+ if (!step || typeof step.entry_path !== 'string' || !found.visible.has(step.entry_path)) return false;
6596
+ try { return isPlainProseUiPromptText(readPrompt(root, found.visible, step.entry_path, found.workspace).text); } catch { return false; }
6597
+ }));
6598
+ const typed = words.length && !cli.size && !hasHttp && !mapped && !plainUi;
5488
6599
  const page = options['--page'] || options['--agent'] !== undefined || options['--tab'] !== undefined;
5489
6600
  const forcedCli = options['--cli'] || options['--shell'];
5490
6601
  if (forcedCli && cli.size !== 1) {
@@ -5508,16 +6619,45 @@ function simulationSelection(root, found, words, appMap, options, ports) {
5508
6619
  // The seed establishes saved-case/session identity, not a preferred view.
5509
6620
  if (cli.size === 1) seed = rows.find(row => row.cli.size).test;
5510
6621
  else if (hasHttp) seed = rows.find(row => row.http.size).test;
5511
- const tab = options['--tab'] ?? (options['--cli'] ? 'terminal' : appMap && (!words.length || mapped || !typed) ? 'screen' : 'call');
6622
+ const tab = options['--tab'] ?? (options['--cli'] ? 'terminal' : (appMap && (!words.length || mapped || !typed)) || plainUi ? 'screen' : 'call');
5512
6623
  return { test: seed, selected, tab, typed: typed && tab === 'call' && options['--serve'] === undefined };
5513
6624
  }
5514
6625
 
5515
6626
  async function readUntil(context, id, command, isDone, ms, label, acceptAnswer = null) {
5516
- const end = Math.min(context.deadline ?? Infinity, context.ports.now() + ms), tick = progressTicker(context.ports.stderr, context.ports.now);
5517
- let last = null;
6627
+ const startedAt = context.ports.now(), end = Math.min(context.deadline ?? Infinity, startedAt + ms), tick = progressTicker(context.ports.stderr, context.ports.now);
6628
+ let last = null, serverSupportsSse = false;
5518
6629
  for (;;) {
5519
6630
  if (context.interrupted || context.ports.now() >= end) return { answer: last, open: true };
5520
- const read = judgeGet(await context.runtime.get(id, Math.max(1, Math.min(GET_MS, end - context.ports.now()))), id, command);
6631
+ const remainingMs = Math.max(1, end - context.ports.now());
6632
+ let read;
6633
+ if (!context.ports.pollMsExplicit) {
6634
+ let streamUnknownWhy = null;
6635
+ const streamReply = await context.runtime.streamRun(id, {
6636
+ useEventsPath: serverSupportsSse,
6637
+ timeoutMs: remainingMs,
6638
+ onEvent: ({ event, json }) => {
6639
+ if (!isObject(json) || !sameJob(json, id, command)) return false;
6640
+ if (acceptAnswer && !acceptAnswer(json)) { streamUnknownWhy = 'The receipt could not be verified.'; return true; }
6641
+ last = json;
6642
+ queueProgress(context, last);
6643
+ context.store.write(join(context.store.folder('tries'), `${id}.json`), last);
6644
+ if (isDone(last)) return true;
6645
+ if (label && event === 'progress') tick(`${label}: ${waitWord(last, null)}`);
6646
+ return false;
6647
+ },
6648
+ });
6649
+ if (streamReply.streamed) {
6650
+ serverSupportsSse = true;
6651
+ if (streamUnknownWhy) return { unknownWhy: streamUnknownWhy };
6652
+ if (last && isDone(last)) return { answer: last };
6653
+ if (context.interrupted || context.ports.now() >= end) return { answer: last, open: true };
6654
+ await context.ports.sleep(context.ports.pollDelay(context.ports.now() - startedAt), context.signal);
6655
+ continue;
6656
+ }
6657
+ read = judgeGet(streamReply, id, command);
6658
+ } else {
6659
+ read = judgeGet(await context.runtime.get(id, Math.max(1, Math.min(GET_MS, remainingMs))), id, command);
6660
+ }
5521
6661
  if (read.kind === 'state' && acceptAnswer && !acceptAnswer(read.answer)) return { unknownWhy: 'The receipt could not be verified.' };
5522
6662
  if (read.kind === 'state') { last = read.answer; queueProgress(context, last); context.store.write(join(context.store.folder('tries'), `${id}.json`), last); if (isDone(last)) return { answer: last }; }
5523
6663
  else if (read.kind === 'unknown') return { unknownWhy: read.why };
@@ -5525,7 +6665,8 @@ async function readUntil(context, id, command, isDone, ms, label, acceptAnswer =
5525
6665
  else if (read.kind === 'blocked') throw new Stop(5, read.message);
5526
6666
  if (label) tick(`${label}: ${waitWord(last, read)}`);
5527
6667
  if (context.interrupted || context.ports.now() >= end) return { answer: last, open: true };
5528
- await context.ports.sleep(context.ports.pollMs, context.signal);
6668
+ const delay = context.ports.pollDelay(context.ports.now() - startedAt);
6669
+ await context.ports.sleep(Math.min(delay, Math.max(0, end - context.ports.now())), context.signal);
5529
6670
  }
5530
6671
  }
5531
6672
 
@@ -5593,24 +6734,29 @@ async function stopTry(context, record) {
5593
6734
  function trySourceSelection(record, path) {
5594
6735
  const scope = record.simulation_scope;
5595
6736
  if (scope === undefined) return { tests: [path] };
5596
- if (!isObject(scope) || !Array.isArray(scope.tests) || !scope.tests.length
5597
- || !scope.tests.every(test => typeof test === 'string') || !scope.tests.includes(path)
6737
+ const entries = Array.isArray(scope.tests) && scope.tests.length
6738
+ ? scope.tests
6739
+ : typeof scope.entry === 'string' && scope.entry ? [scope.entry] : null;
6740
+ if (!isObject(scope) || !Array.isArray(scope.tests) || !entries
6741
+ || !entries.every(test => typeof test === 'string') || !entries.includes(path)
5598
6742
  || !(scope.appMap === null || typeof scope.appMap === 'string')) {
5599
6743
  throw new Stop(4, 'The saved whole-project source scope is unavailable. Run pdd simulate --new.');
5600
6744
  }
5601
- return { tests: scope.tests, appMap: scope.appMap };
6745
+ return { tests: entries, appMap: scope.appMap };
5602
6746
  }
5603
6747
 
5604
6748
  function tryPromptProblem(root, found, test, record, capture, ports) {
5605
6749
  const hashes=record.prompt_hashes;
5606
- if (!capture && record.simulation_scope?.appMap) capture = ports.captureSource(root, trySourceSelection(record, test?.path));
6750
+ if (!capture && record.simulation_scope?.appMap) capture = ports.captureSource(root, trySourceSelection(record, test?.path ?? record.entry));
5607
6751
  if (!capture && isObject(hashes)) {
5608
6752
  const files=sourceFilePort(root,found.visible), sources=[], references=[], raw_prompt_hashes={};
5609
6753
  for (const path of Object.keys(hashes)) {
5610
- const prepared=readPrompt(root,found.visible,path);
6754
+ const prepared=readPrompt(root,found.visible,path,found.workspace);
5611
6755
  if (!prepared.text) return 'A prompt changed or this Try has no source record.';
5612
- sources.push({path,bytes:Buffer.from(executableInterfaceText(prepared.text),'utf8')});references.push(...(prepared.references??[]));
5613
- raw_prompt_hashes[path]=sha256(Buffer.from(files.read({path}).content,'utf8'));
6756
+ const rawText = typeof prepared.rawText === 'string' ? prepared.rawText : files.read({path}).content;
6757
+ const effectiveText = executableInterfaceText(prepared.text);
6758
+ sources.push({path,bytes:Buffer.from(effectiveText,'utf8')});references.push(...(prepared.references??[]));
6759
+ raw_prompt_hashes[path]=sha256(Buffer.from(rawText,'utf8'));
5614
6760
  }
5615
6761
  capture={sources,references,raw_prompt_hashes};
5616
6762
  }
@@ -5618,7 +6764,10 @@ function tryPromptProblem(root, found, test, record, capture, ports) {
5618
6764
  const scope = record.simulation_scope, map = capture.sources.find(file => file.path === scope.appMap);
5619
6765
  if (!/^[a-f0-9]{64}$/.test(scope.appMapHash ?? '') || !map || sha256(map.bytes) !== scope.appMapHash) return 'The saved simulation app map changed or its source baseline is unavailable.';
5620
6766
  }
5621
- if (!isObject(hashes) || !Object.keys(hashes).length || (test && !test.doc?.steps?.every(step=>typeof hashes[step.entry_path]==='string'))
6767
+ const missingEntryHash = Array.isArray(test?.doc?.steps)
6768
+ ? !test.doc.steps.every(step=>typeof hashes?.[step.entry_path]==='string')
6769
+ : typeof record.entry === 'string' ? typeof hashes?.[record.entry] !== 'string' : false;
6770
+ if (!isObject(hashes) || !Object.keys(hashes).length || missingEntryHash
5622
6771
  || !Object.entries(hashes).every(([path,expected])=>found.visible.has(path) && capture.raw_prompt_hashes[path]===expected)) return 'A prompt changed or this Try has no source record.';
5623
6772
  const current=Object.fromEntries(capture.sources.filter(file=>file.path.endsWith('.prompt.md')).map(file=>[file.path,sha256(file.bytes)]));
5624
6773
  if (isObject(record.effective_prompt_hashes) && Object.keys(hashes).every(path=>typeof record.effective_prompt_hashes[path]==='string')) {
@@ -5798,9 +6947,9 @@ function programSelection(cwd, word, ports, givenMap) {
5798
6947
  let map;
5799
6948
  try { map = JSON.parse(sourceFilePort(root, visible).read({ path }).content); }
5800
6949
  catch (error) { if (error instanceof RuntimeWorkspaceError) throw error; throw new Stop(2, 'Select a readable app map containing valid JSON.'); }
5801
- if (!isObject(map) || map.schema_version !== 'prompt-runtime.app-map.v1' || !Array.isArray(map.screens)) throw new Stop(2, 'Select a valid app map with executable screens.');
5802
- if (explicit && (typeof map.name !== 'string' || !map.name)) throw new Stop(2, 'The selected app map has no name. See RUNBOOK.md §13.');
5803
- const initial = map.screens.find(screen => screen.id === map.initial_screen), first = initial?.source === 'operation' ? initial : map.screens.find(screen => screen.source === 'operation');
6950
+ if (!isObject(map) || (Object.hasOwn(map, 'schema_version') && !APP_MAP_VERSIONS.has(map.schema_version)) || !Array.isArray(map.screens) || !map.screens.length) throw new Stop(2, 'Select a valid app map with executable screens.');
6951
+ if (explicit && Object.hasOwn(map, 'name') && (typeof map.name !== 'string' || !map.name)) throw new Stop(2, 'The selected app map has an invalid name. See RUNBOOK.md §13.');
6952
+ const initial = map.screens.find(screen => screen.id === (map.initial_screen ?? map.screens[0]?.id)), first = (initial?.source ?? 'operation') === 'operation' ? initial : map.screens.find(screen => (screen.source ?? 'operation') === 'operation');
5804
6953
  if (!first || typeof first.prompt_path !== 'string' || !first.prompt_path.endsWith('.prompt.md') || !visible.has(first.prompt_path)) throw new Stop(2, 'This app map has no executable prompt.');
5805
6954
  return first.prompt_path;
5806
6955
  };
@@ -5820,13 +6969,19 @@ function programSelection(cwd, word, ports, givenMap) {
5820
6969
  if (!visible.has(path) || mapEntry(path) !== entry) throw new Stop(4, 'The pinned program source or map changed. Use --new after reconciling this session.');
5821
6970
  return path;
5822
6971
  };
5823
- return { root, visible, entry, appMap, validatePinnedMap, screen: isMap };
6972
+ let plainUiPrompt = false;
6973
+ if (!isMap) {
6974
+ try { plainUiPrompt = isPlainProseUiPromptText(sourceFilePort(root, visible).read({ path: entry }).content); } catch { plainUiPrompt = false; }
6975
+ }
6976
+ return { root, visible, entry, appMap, validatePinnedMap, screen: isMap, plainUiPrompt };
5824
6977
  }
5825
6978
  async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
5826
6979
  const { ports } = context, selected = programSelection(cwd, word, ports, options['--app-map']), { root, entry } = selected;
5827
6980
  if (options['--data'] !== undefined && options['--fresh'] !== undefined) throw new Stop(2, 'Choose --data FILE or --fresh, not both.');
5828
6981
  if (options['--fresh'] !== undefined && options['--fresh'] !== true) throw new Stop(2, '--fresh takes no value.');
6982
+ if (options['--tab'] !== undefined && !['screen', 'terminal', 'call', 'world'].includes(options['--tab'])) throw new Stop(2, '--tab must be one of screen, terminal, call or world.');
5829
6983
  if (options['--serve'] !== undefined && options['--serve'] !== true && (!/^[0-9]+$/.test(String(options['--serve'])) || !Number.isInteger(Number(options['--serve'])) || Number(options['--serve']) > 65535)) throw new Stop(2, '--serve needs a port from 0 to 65535.');
6984
+ const openInPage = selected.screen || selected.plainUiPrompt || options['--page'] === true || options['--tab'] !== undefined;
5830
6985
  const store = stateFor(ports.env, root), files = programFiles(root, entry, store); let seeded = null;
5831
6986
  if (options['--data'] !== undefined) {
5832
6987
  if (typeof options['--data'] !== 'string') throw new Stop(2, '--data needs a JSON file.');
@@ -5840,12 +6995,13 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
5840
6995
  throw new Stop(2, 'The live program keeps its pinned app map. Use --new to select a different app map.');
5841
6996
  const appMap = !selected.screen && !options['--new'] && record?.app_map
5842
6997
  ? selected.validatePinnedMap(record.app_map) : selected.appMap;
6998
+ const requestedTab = options['--tab'] ?? (selected.screen || selected.plainUiPrompt || appMap ? 'screen' : 'call');
5843
6999
  const capture = ports.captureSource(root, { tests: [entry], appMap });
5844
7000
  const origin = runtimeOrigin(ports.env), identity = signIn(ports.gh, store, ports);
5845
7001
  if (record && (record.login !== identity.login || record.origin !== origin)) throw new Stop(5, 'This program session belongs to another owner or interpreter. Use its original owner and address.');
5846
7002
  Object.assign(context, { root, cwd, origin, identity, store, capture, visible: selected.visible, appMap, programEntry: entry,
5847
7003
  programTarget: relative(root, resolve(cwd, word)).split(sep).join('/'), programFiles: files,
5848
- secrets: [identity.token], startedAt: ports.now(), deadline: ports.now() + TRY_MS, lint: { request_ids: [], state: null }, rows: [], timeoutMin: 5, folder: store.folder('tries'), doorMode: options['--serve'] !== undefined || !selected.screen });
7004
+ secrets: [identity.token], startedAt: ports.now(), deadline: ports.now() + TRY_MS, lint: { request_ids: [], state: null }, rows: [], timeoutMin: 5, folder: store.folder('tries'), doorMode: options['--serve'] !== undefined || !openInPage });
5849
7005
  releaseInterrupt = interruptible(context);
5850
7006
  context.auth = authSession({ identity, store, ports, secrets: context.secrets, expectedOwnerLogin: () => record?.login ?? identity.login, ownerMismatchError: () => new Stop(5, 'This program belongs to another owner.') });
5851
7007
  context.runtime = new Runtime({ origin, token: identity.token, ports, signal: context.signal, auth: context.auth, programJson: true });
@@ -5879,10 +7035,12 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
5879
7035
  if (!await admission(context, 'try', setup)) throw new Stop(5, 'The program setup wait ended before sending.');
5880
7036
  const request = { requestId: ports.randomUUID(), source_sha256: capture.sha256, entry,
5881
7037
  initial_world: seeded?.initial_world ?? (options['--fresh'] ? {} : files.read()), ...(seeded?.simulation ? { simulation: seeded.simulation } : {}),
5882
- ...(appMap ? { app_map: appMap } : {}), tab: selected.screen ? 'screen' : 'call', max_calls: requestedBudget ?? 300, ...sourceProvenance(context, capture) };
7038
+ ...(options['--fresh'] === true ? { fresh: true } : {}),
7039
+ ...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}),
7040
+ ...(appMap ? { app_map: appMap } : {}), tab: requestedTab, max_calls: requestedBudget ?? 300, ...sourceProvenance(context, capture) };
5883
7041
  setup.request_ids.push(request.requestId);
5884
7042
  if (await recordRuntimeRequest(setup.reservation, request.requestId, slotPorts(context)) === false || context.interrupted) throw new Stop(3, 'Stopped before sending the program.');
5885
- record = { id: request.requestId, entry, origin, login: identity.login, source_sha256: capture.sha256, max_calls: request.max_calls, ...setup,
7043
+ record = { id: request.requestId, root, entry, origin, login: identity.login, source_sha256: capture.sha256, max_calls: request.max_calls, ...setup,
5886
7044
  prompt_hashes: capture.raw_prompt_hashes, effective_prompt_hashes: Object.fromEntries(capture.sources.filter(file => file.path.endsWith('.prompt.md')).map(file => [file.path, sha256(file.bytes)])),
5887
7045
  app_map: appMap, app_map_hash: appMap ? sha256(capture.sources.find(file => file.path === appMap).bytes) : null };
5888
7046
  files.set(record); store.posted(context.folder, record.id);
@@ -5971,9 +7129,16 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
5971
7129
  } finally { done(); }
5972
7130
  };
5973
7131
  unlock(); released = true;
5974
- if (options['--serve'] !== undefined || !selected.screen) return await (await import('./try-http.mjs')).openServe(context, { path: entry, programEntry: entry, title: entry }, record.id, { ...options, '--serve': options['--serve'] === true ? 8080 : options['--serve'] ?? 8080 });
5975
- line(ports.stdout, `Program ready: ${link}`);
5976
- if (!options['--no-open']) await ports.openUrl(link);
7132
+ if (options['--serve'] !== undefined || !openInPage) return await (await import('./try-http.mjs')).openServe(context, { path: entry, programEntry: entry, title: entry }, record.id, { ...options, '--serve': options['--serve'] === true ? 8080 : options['--serve'] ?? 8080 });
7133
+ let openLink = link;
7134
+ if (options['--tab'] === undefined && requestedTab !== 'screen') {
7135
+ try {
7136
+ const model = await context.runtime.send(`/v1/try/${record.id}/model`, { method: 'GET' }, GET_MS);
7137
+ if (model.status === 200 && model.json?.app_map === true) openLink = withTryTab(link, 'screen');
7138
+ } catch { /* Preserve the confirmed link when optional model inspection is unavailable. */ }
7139
+ }
7140
+ line(ports.stdout, `Program ready: ${openLink}`);
7141
+ if (!options['--no-open']) await ports.openUrl(openLink);
5977
7142
  try {
5978
7143
  do {
5979
7144
  const done = files.lock();
@@ -6220,7 +7385,7 @@ async function runDirectProgram({words,options,cwd}, ports) {
6220
7385
  if (row.state !== 'ready') throw Object.assign(new Stop(125,row.refusals?.map(item=>item.message||item.code).join('; ')||'The interpreter refused this program.'),{fix:row.raw_refusals?.find(item=>item.fix)?.fix});
6221
7386
  const setup = {request_ids:[],reservation:null};
6222
7387
  if (!await admission(context,'try',setup)) throw new Stop(125,'The interpreter could not admit this program.');
6223
- const lazyInterfaces=context.serverFeatures?.includes('lazy-interfaces')===true;
7388
+ const lazyInterfaces=shouldSendLazyInterfaces(context);
6224
7389
  const id=ports.randomUUID(), request={requestId:id,source_sha256:context.capture.sha256,seed:test.path,max_calls:400,tab:'terminal',...(lazyInterfaces?{lazy_interfaces:true}:{})};
6225
7390
  await recordRuntimeRequest(setup.reservation,id,slotPorts(context));
6226
7391
  descriptor={version:1,directProgram:true,root,prompt:promptPath,operation,login:identity.login,origin,sessionId:id,sourceHash,setupPending:true,
@@ -6251,7 +7416,7 @@ async function runDirectProgram({words,options,cwd}, ports) {
6251
7416
  const inputProblems=checkInput(input,selected.entry.input_schema,0).refusals;
6252
7417
  if(inputProblems.length)throw new Stop(125,inputProblems.map(problem=>problem.message).join('; '));
6253
7418
  descriptor={...descriptor,operation:selected.entry.operation,inputSchema:selected.entry.input_schema,draft:context.draft,
6254
- lazyInterfaces:context.serverFeatures?context.serverFeatures.includes('lazy-interfaces'):descriptor.lazyInterfaces===true};
7419
+ lazyInterfaces:context.serverFeatures||context.allowMissingInterfaces?shouldSendLazyInterfaces(context):descriptor.lazyInterfaces===true};
6255
7420
  directPrivate(descriptorPath,descriptor);
6256
7421
  if (context.interrupted) throw new Stop(130,'Stopped before the command was sent.');
6257
7422
  return await doors.openCli({root,visible,ports:{...ports,signal:context.signal},store,identity,origin,runtime:context.runtime,
@@ -6266,7 +7431,7 @@ async function runDirectProgram({words,options,cwd}, ports) {
6266
7431
  function shouldUseDirectProgram(words, options, cwd) {
6267
7432
  if (typeof words[0] !== 'string' || !words[0].endsWith('.prompt.md')) return false;
6268
7433
  if (words.length > 1 || ['--show-data', '-q', '--quiet'].some(key => options[key] !== undefined)) return true;
6269
- if (['--serve', '--page', '--tab', '--cli', '--shell', '--no-open', '--new', '--stop', '--app-map', '--max-calls'].some(key => options[key] !== undefined)) return false;
7434
+ if (['--serve', '--page', '--tab', '--cli', '--shell', '--no-open', '--no-wait', '--new', '--stop', '--app-map', '--max-calls', '--agent'].some(key => options[key] !== undefined)) return false;
6270
7435
  try {
6271
7436
  const text = readFileSync(resolve(cwd, words[0]), 'utf8');
6272
7437
  return /\b(?:cli|argv|stdin|stdout|exit_code|command-line)\b/i.test(text);
@@ -6436,7 +7601,7 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
6436
7601
  if(options['--product']!==undefined&&!productMode || !productMode&&['--parts','--journey'].some(key=>options[key]!==undefined))throw new Stop(2,'--parts and --journey require --product.');
6437
7602
  if(productMode&&options['--app-map']!==undefined)throw new Stop(2,'--product builds its map; omit --app-map.');
6438
7603
  const requestedBudget = requestedCalls(options['--max-calls']);
6439
- if (words.length === 1 && (words[0].endsWith('.prompt.md') || basename(words[0]) === 'app-map.json')) return await runProgramTry({ cwd, word: words[0], options, context, requestedBudget });
7604
+ if (!options['--stop'] && words.length === 1 && (words[0].endsWith('.prompt.md') || basename(words[0]) === 'app-map.json')) return await runProgramTry({ cwd, word: words[0], options, context, requestedBudget });
6440
7605
  if (options['--agent'] !== undefined && (typeof options['--agent'] !== 'string' || !options['--agent'].trim() || ['--no-wait','--stop','--save-last','--cli','--shell','--serve'].some(key => options[key] !== undefined))) throw new Stop(2, '--agent chooses a configured agent name for an ordinary connected pdd simulate; omit --no-wait and door modes.');
6441
7606
  const doorModes = [options['--cli'] || options['--shell'], options['--serve'] !== undefined, options['--page'] || options['--tab'] !== undefined || options['--agent'] !== undefined, options['--save-last']].filter(Boolean);
6442
7607
  if (doorModes.length > 1 || (doorModes.length && options['--stop'])
@@ -6454,11 +7619,22 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
6454
7619
  const identity = signIn(ports.gh, store, ports);
6455
7620
  return await (await import('./try-doors.mjs')).saveLast({ root, store, identity, ports, test });
6456
7621
  }
6457
- if (options['--stop'] && (options['--tab'] || options['--new'] || options['--no-open'] || options['--no-wait'] || options['--app-map'] !== undefined || productMode || requestedBudget !== null)) throw new Stop(2, 'pdd simulate --stop takes only a STORY. Run pdd simulate --help.');
7622
+ if (options['--fresh'] !== undefined && options['--fresh'] !== true) throw new Stop(2, '--fresh takes no value.');
7623
+ if (options['--stop'] && (options['--tab'] || options['--new'] || options['--fresh'] || options['--no-open'] || options['--no-wait'] || options['--app-map'] !== undefined || productMode || requestedBudget !== null)) throw new Stop(2, 'pdd simulate --stop takes only a STORY. Run pdd simulate --help.');
6458
7624
  if (words.length > 1) throw new Stop(2, 'pdd simulate takes one STORY.');
6459
7625
  const origin = runtimeOrigin(ports.env);
6460
7626
  if (options['--stop']) return await stopByName(context, cwd, words, origin);
6461
7627
  const { root, found, normalized } = localSetup(cwd, words, ports), store = stateFor(ports.env, root);
7628
+ if (!productMode && !normalized.length && !found.tests.length && !(found.untested?.length)) {
7629
+ const workspace = found.workspace ?? loadRuntimeWorkspace({ root });
7630
+ const standalonePrompts = [...(found.discoveryVisible ?? found.visible)]
7631
+ .filter(path => path.endsWith('.prompt.md') && allowsRuntimePath(workspace, path))
7632
+ .sort();
7633
+ if (standalonePrompts.length === 1) {
7634
+ const targetWord = relative(realpathSync(cwd), join(realpathSync(root), standalonePrompts[0])).split(sep).join('/') || standalonePrompts[0];
7635
+ return await runProgramTry({ cwd, word: targetWord, options, context, requestedBudget });
7636
+ }
7637
+ }
6462
7638
  await prepareLiveManifest(context,options,root);
6463
7639
  const repoState = store.repo(root);
6464
7640
  if (!productMode && normalized.length && !options['--new']) {
@@ -6468,8 +7644,10 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
6468
7644
  const productSetup = options['--product'] ? { parts: options['--parts']?.split(',').map(p => p.trim()) ?? null, journey: options['--journey'] ?? null } : null;
6469
7645
  const localSelected = productSetup ? [productTest(found, normalized, options['--journey'], root, ports)]
6470
7646
  : normalized.length ? [oneTest(found, normalized, root, ports)] : [...found.tests].sort((a, b) => a.path.localeCompare(b.path));
6471
- const allowMissingInterfaces = hasMissingPromptInterface(root, found, entryPaths(localSelected))
6472
- ? await probeLazyInterfaces(context, origin, store) : false;
7647
+ const localEntryPaths = entryPaths(localSelected);
7648
+ const allowMissingInterfaces = hasMissingPromptInterface(root, found, localEntryPaths)
7649
+ ? (hasMissingNonUiPromptInterface(root, found, localEntryPaths) ? await probeLazyInterfaces(context, origin, store) : true)
7650
+ : false;
6473
7651
  const checked = preflight({ root, found, selected: localSelected, allowMissingInterfaces }), rows = localRows(checked.rows);
6474
7652
  for (const item of rows) item.app_maps = declaredMaps(localSelected.find(candidate => candidate.path === item.test)?.doc);
6475
7653
  const refused = rows.find(row => row.state === 'refused');
@@ -6632,7 +7810,8 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
6632
7810
  for (;;) {
6633
7811
  if (!await admission(context, 'try', setup)) throw new Stop(context.interrupted ? 3 : 5, context.interrupted ? 'Stopped before sending.' : 'The interpreter stayed busy until the Try setup wait ended. No new Try was sent.');
6634
7812
  request = { requestId: ports.randomUUID(), source_sha256: capture.sha256, seed: test.path, max_calls: requestedBudget ?? 400, ...(appMap ? { app_map: appMap } : {}), ...(prepared ? {product_parts:prepared.composition.product_parts} : {}),
6635
- ...(context.serverFeatures?.includes('lazy-interfaces') ? { lazy_interfaces: true } : {}),
7813
+ ...(options['--fresh'] === true ? { fresh: true } : {}),
7814
+ ...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}),
6636
7815
  ...sourceProvenance(context, capture),
6637
7816
  tab };
6638
7817
  let localBridge;
@@ -6647,7 +7826,8 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
6647
7826
  await store.updateRepo(root, current => ({ ...current, tries: { ...current.tries, [test.path]: tryRecord } }));
6648
7827
  store.posted(context.folder, request.requestId);
6649
7828
  line(ports.stderr, `Starting your Try: sending ${capture.files.length} files, ${formatSize(capture.bytes)}${note ? ` ${note}` : ''}…`);
6650
- reply = await context.runtime.post('/v1/try', request, capture.tar, Math.max(1, Math.min(ports.postMs, context.deadline - ports.now())));
7829
+ const dedupTry = context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: true } : undefined;
7830
+ reply = await context.runtime.post('/v1/try', request, capture.tar, Math.max(1, Math.min(ports.postMs, context.deadline - ports.now())), dedupTry);
6651
7831
  verdict = judgePost(reply, request.requestId, 'try', context.secrets);
6652
7832
  if (verdict.maintenance) maintenanceNotice(context, verdict, reply);
6653
7833
  if (verdict.answer) { store.write(join(context.folder, `${request.requestId}.json`), verdict.answer); queueProgress(context, verdict.answer); await finishReservation(context, setup, verdict.answer); }
@@ -6718,18 +7898,48 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
6718
7898
  } finally { await closeLocalBridges(context);release();for(const lease of context.caseWriteLeases?.values()??[])lease.release(); await Promise.all([...(context.reservations ?? [])].map(reservation => releaseRuntimeSlot(reservation, { ended: false }, slotPorts(context)))); }
6719
7899
  }
6720
7900
 
6721
- // pdd simulate --stop [STORY]: find the Try by its exact Try ID or story/test selector in the state record, so it works on any branch (real-user issue 14).
7901
+ // pdd simulate --stop [STORY]: find the Try by its exact Try ID or story/test/prompt selector in the state record, so it works on any branch (real-user issue 14).
6722
7902
  async function stopByName(context, cwd, words, origin) {
6723
- const { ports } = context, root = repoRoot(cwd), store = stateFor(ports.env, root), repoState = store.repo(root);
6724
- const entries = Object.entries(repoState.tries ?? {}), word = words[0]?.replace(/^\.\//, '');
6725
- const names = entries.map(([path, record]) => record.story ?? basename(path, '.json')).join(', ') || 'none';
6726
- const records = entries.map(([path, record]) => ({
6727
- id: String(record.id ?? ''),
6728
- test_path: path,
6729
- test_name: basename(path, '.json'),
6730
- story: String(record.story ?? basename(path, '.json')),
6731
- story_path: String(record.storyPath ?? ''),
6732
- }));
7903
+ const { ports } = context, root = repoRoot(cwd), realRoot = realpathSync(root), store = stateFor(ports.env, root), repoState = store.repo(root);
7904
+ const storyEntries = Object.entries(repoState.tries ?? {}).map(([path, record]) => ({ kind: 'story', path, record }));
7905
+ const programEntries = [];
7906
+ const programsDir = join(store.dir, 'programs');
7907
+ if (statOrNull(programsDir)?.isDirectory()) {
7908
+ for (const name of readdirSync(programsDir).sort()) {
7909
+ if (!name.endsWith('.json')) continue;
7910
+ const metaPath = join(programsDir, name);
7911
+ let record;
7912
+ try { record = store.read(metaPath); } catch { continue; }
7913
+ if (!isObject(record) || !UUID.test(record.id ?? '') || typeof record.entry !== 'string') continue;
7914
+ const matchesRepo = name === `${sha256(realRoot + '\0' + record.entry)}.json` || name === `${sha256(root + '\0' + record.entry)}.json`;
7915
+ if (!matchesRepo) continue;
7916
+ programEntries.push({ kind: 'program', path: record.entry, metaPath, record });
7917
+ }
7918
+ }
7919
+ const entries = [...storyEntries, ...programEntries];
7920
+ let word = words[0]?.replace(/^\.\//, '');
7921
+ if (words[0] !== undefined) {
7922
+ const rel = relative(realRoot, resolve(realpathSync(cwd), words[0])).split(sep).join('/');
7923
+ if (rel && !rel.startsWith('../') && entries.some(item => item.path === rel || item.record.storyPath === rel || item.record.app_map === rel)) {
7924
+ word = rel;
7925
+ }
7926
+ }
7927
+ const names = entries.map(item => item.kind === 'program' ? item.record.entry : (item.record.story ?? basename(item.path, '.json'))).join(', ') || 'none';
7928
+ const records = entries.map(item => item.kind === 'program'
7929
+ ? {
7930
+ id: String(item.record.id ?? ''),
7931
+ test_path: item.record.entry,
7932
+ test_name: basename(item.record.entry, '.prompt.md'),
7933
+ story: basename(item.record.entry),
7934
+ story_path: String(item.record.app_map ?? item.record.entry),
7935
+ }
7936
+ : {
7937
+ id: String(item.record.id ?? ''),
7938
+ test_path: item.path,
7939
+ test_name: basename(item.path, '.json'),
7940
+ story: String(item.record.story ?? basename(item.path, '.json')),
7941
+ story_path: String(item.record.storyPath ?? ''),
7942
+ });
6733
7943
  let picked;
6734
7944
  try {
6735
7945
  picked = selectTryToStop({ ...(word !== undefined ? { selector: word } : {}), records });
@@ -6737,8 +7947,9 @@ async function stopByName(context, cwd, words, origin) {
6737
7947
  throw new Stop(2, word !== undefined ? `No open Try for "${cleanText(word)}". Open Try links: ${names}.`
6738
7948
  : entries.length ? `Name the Try to stop. Open Try links: ${names}.` : 'No open Try in this repository.');
6739
7949
  }
6740
- const [path, record] = entries.find(([candidatePath, candidate]) => candidatePath === picked.test_path && String(candidate.id ?? '') === picked.id);
6741
- const title = record.title ?? record.story ?? path;
7950
+ const selected = entries.find(item => item.path === picked.test_path && String(item.record.id ?? '') === picked.id);
7951
+ const { path, record } = selected;
7952
+ const title = record.title ?? record.story ?? record.entry ?? path;
6742
7953
  Object.assign(context, { root, store, origin });
6743
7954
  const identity = signIn(ports.gh, store, ports);
6744
7955
  context.secrets = [identity.token];
@@ -6753,7 +7964,12 @@ async function stopByName(context, cwd, words, origin) {
6753
7964
  context.runtime = new Runtime({ origin: record.origin ?? origin, token: identity.token, ports, auth: context.auth });
6754
7965
  line(ports.stderr, `Stopping the Try for "${title}"…`);
6755
7966
  await stopTry(context, record);
6756
- await store.updateRepo(root, current => { if (current.tries?.[path]?.id === record.id) delete current.tries[path]; return current; });
7967
+ if (selected.kind === 'program') {
7968
+ const current = store.read(selected.metaPath);
7969
+ if (current?.id === record.id) store.write(selected.metaPath, null);
7970
+ } else {
7971
+ await store.updateRepo(root, current => { if (current.tries?.[path]?.id === record.id) delete current.tries[path]; return current; });
7972
+ }
6757
7973
  line(ports.stdout, `The Try link for "${title}" is stopped.`);
6758
7974
  return 0;
6759
7975
  }
@@ -6857,6 +8073,9 @@ const validSha256Hex = value => typeof value === 'string' && /^[0-9a-f]{64}$/i.t
6857
8073
  const validEngineHex = value => typeof value === 'string' && /^[0-9a-f]{8,40}$/i.test(value) ? value.toLowerCase() : null;
6858
8074
 
6859
8075
  async function showTry(context, test, link, options, tryId, reused = false, session, answer = null, record = null) {
8076
+ if (options['--tab'] === undefined && answer?.result?.app_map === true && !options['--cli'] && options['--serve'] === undefined) {
8077
+ link = withTryTab(link, 'screen');
8078
+ }
6860
8079
  if (context.typedForm) line(context.ports.stderr, "This Story's operation takes typed input, so it opens on the Form tab.");
6861
8080
  const budget = Number.isSafeInteger(session?.max_calls) && session.max_calls > 0 && Number.isSafeInteger(session?.remaining_calls)
6862
8081
  && session.remaining_calls >= 0 && session.remaining_calls <= session.max_calls
@@ -7469,7 +8688,8 @@ async function doorWorldObservation(runtime,sessionId,report,actionId) {
7469
8688
  ?state.json.actions.find(action=>action.action_id===actionId):null;
7470
8689
  if(matched)observation={...observation,
7471
8690
  ...(Object.hasOwn(matched,'input_world')?{input_world:matched.input_world}:{}),
7472
- ...(Object.hasOwn(matched,'world')?{world:matched.world}:{})};
8691
+ ...(Object.hasOwn(matched,'world')?{world:matched.world}:{}),
8692
+ ...(isObject(matched.calls)?{calls:matched.calls}:{})};
7473
8693
  } catch { /* Observation is optional; the confirmed result remains confirmed. */ }
7474
8694
  return observation;
7475
8695
  }
@@ -7581,8 +8801,9 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
7581
8801
  const runtime = new Runtime({ origin, token: identity.token, ports, signal: ports.signal, auth, programJson: Boolean(descriptor.programEntry) });
7582
8802
  try {
7583
8803
  descriptor.beforeProgramDispatch?.(id);
8804
+ const callWaitSeconds = Math.min(WAIT_PREFER_CALL_SECONDS, Math.max(0, Math.floor((ports.postMs - 5_000) / 1000)));
7584
8805
  const reply = descriptor.directProgram && descriptor.recoverRequestId ? { status: 202 } : await runtime.send(`/v1/try/${sessionId}/call`, { method: 'POST',
7585
- headers: { 'Content-Type': 'application/json' }, body: runBody }, ports.postMs);
8806
+ headers: preferWaitHeaders(callWaitSeconds, { 'Content-Type': 'application/json' }), body: runBody }, ports.postMs);
7586
8807
  if (reply.status && ![200, 202].includes(reply.status)) {
7587
8808
  knownOutcome = isPreExecutionRefusal(reply);
7588
8809
  preExecutionRefusal = knownOutcome;
@@ -7597,8 +8818,9 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
7597
8818
  && (!Object.hasOwn(reply.json, 'session_id') || reply.json.session_id === sessionId)
7598
8819
  && (!Object.hasOwn(reply.json.result?.session ?? {}, 'id') || reply.json.result.session.id === sessionId);
7599
8820
  if ([200, 202].includes(reply.status) && reply.json && !pendingExistingCall && !programReceiptMatches(reply.json, id, 'call', sessionId)) throw new Stop(125, 'The interpreter returned a different command.' + recovery);
7600
- const end = ports.now() + 900_000;
7601
- let answer = null;
8821
+ const pollStartedAt = ports.now(), end = pollStartedAt + 900_000;
8822
+ let answer = reply.status === 200 && reply.json && ENDED.has(reply.json.state) ? reply.json : null;
8823
+ let serverSupportsSse = false;
7602
8824
  for (;;) {
7603
8825
  if (ports.signal?.aborted) throw new Stop(125, 'The local server stopped; this command result is unknown. Do not repeat it automatically.' + recovery);
7604
8826
  if (answer && !programReceiptMatches(answer, id, 'call', sessionId)) throw new Stop(125, 'The interpreter returned a different command.' + recovery);
@@ -7631,8 +8853,14 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
7631
8853
  throw Object.assign(new Stop(125, cleanText(why?.engine_message || why?.message || why?.code || 'The command result is unknown. Do not repeat it automatically.', secrets) + (['failed', 'refused'].includes(answer.state) ? '' : recovery)), { tryUsage: usage,fix:why?.fix });
7632
8854
  }
7633
8855
  knownOutcome = true;
7634
- const observation = typeof projected.action_id === 'string' || descriptor.directProgram
8856
+ const hasEmbeddedWorld = Object.hasOwn(answer.result ?? {}, 'world');
8857
+ const hasEmbeddedInputWorld = Object.hasOwn(answer.result ?? {}, 'input_world') || Object.hasOwn(rawReport ?? {}, 'input_world');
8858
+ const observation = !(hasEmbeddedWorld && hasEmbeddedInputWorld) && (typeof projected.action_id === 'string' || descriptor.directProgram)
7635
8859
  ? await doorWorldObservation(runtime,sessionId,rawReport,projected.action_id) : rawReport ?? {};
8860
+ const recordedCalls = isObject(rawReport?.calls) ? rawReport.calls
8861
+ : isObject(observation?.calls) ? observation.calls : undefined;
8862
+ const recordingAvailable = typeof rawReport?.recording_available === 'boolean'
8863
+ ? rawReport.recording_available : undefined;
7636
8864
  const confirmed = {
7637
8865
  id,
7638
8866
  actionId: projected.action_id,
@@ -7641,8 +8869,10 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
7641
8869
  error: projected.outcome === 'program_error' ? reportError : null,
7642
8870
  usage,
7643
8871
  callChain: rawReport?.call_chain,
7644
- inputWorld: observation.input_world,
7645
- world: Object.hasOwn(answer.result ?? {}, 'world') ? answer.result.world : observation.world,
8872
+ inputWorld: Object.hasOwn(answer.result ?? {}, 'input_world') ? answer.result.input_world : observation.input_world,
8873
+ world: hasEmbeddedWorld ? answer.result.world : observation.world,
8874
+ ...(recordedCalls !== undefined ? { calls: recordedCalls } : {}),
8875
+ ...(recordingAvailable !== undefined ? { recordingAvailable } : {}),
7646
8876
  };
7647
8877
  if (sourcePins && projected.outcome === 'result') await store.updateLastRun(root, current => current?.id !== id ? undefined : ({state:'confirmed',
7648
8878
  descriptor:{root,sessionId,origin,login,prompt,operation,...sourcePins},
@@ -7668,7 +8898,33 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
7668
8898
  if (!answer || !ENDED.has(answer.state)) throw new Stop(125, 'The command result is unknown. Do not repeat it automatically.' + recovery);
7669
8899
  continue;
7670
8900
  }
7671
- await ports.sleep(ports.pollMs, ports.signal);
8901
+ await ports.sleep(ports.pollDelay(ports.now() - pollStartedAt), ports.signal);
8902
+ continue;
8903
+ }
8904
+ if (!ports.pollMsExplicit) {
8905
+ let streamedDone = null;
8906
+ const streamReply = await runtime.streamRun(id, {
8907
+ useEventsPath: serverSupportsSse,
8908
+ timeoutMs: Math.max(1, end - ports.now()),
8909
+ onEvent: ({ event, json }) => {
8910
+ if (isObject(json) && (event === 'done' || ENDED.has(json.state))) {
8911
+ streamedDone = json;
8912
+ return true;
8913
+ }
8914
+ return false;
8915
+ },
8916
+ });
8917
+ if (streamReply.streamed) {
8918
+ serverSupportsSse = true;
8919
+ if (streamedDone) { answer = streamedDone; continue; }
8920
+ if (ports.signal?.aborted) throw new Stop(125, 'The local server stopped; this command result is unknown. Do not repeat it automatically.' + recovery);
8921
+ await ports.sleep(ports.pollDelay(ports.now() - pollStartedAt), ports.signal);
8922
+ continue;
8923
+ }
8924
+ if ([401, 403, 410].includes(streamReply.status)) throw new Stop(125, cleanText(streamReply.json?.error?.message || (streamReply.status === 401 ? AUTH_TEXT : 'The command could not be read. Do not repeat it automatically.'), secrets) + recovery);
8925
+ answer = [200, 202].includes(streamReply.status) ? streamReply.json : null;
8926
+ if (answer && ENDED.has(answer.state)) continue;
8927
+ await ports.sleep(ports.pollDelay(ports.now() - pollStartedAt), ports.signal);
7672
8928
  continue;
7673
8929
  }
7674
8930
  await ports.sleep(ports.pollMs, ports.signal);
@@ -7761,6 +9017,756 @@ export async function observeTryCall({ cwd = process.cwd(), story, tryId, runId
7761
9017
  });
7762
9018
  }
7763
9019
 
9020
+ export async function reconcileCheckReceipt({ cwd = process.cwd(), requestId, origin: explicitOrigin } = {}, givenPorts = {}) {
9021
+ const targetRequestId = String(requestId ?? '');
9022
+ if (!UUID.test(targetRequestId)) {
9023
+ throw Object.assign(new Error(`Invalid CHECK request UUID "${cleanText(targetRequestId)}". Pass the original external request UUID.`), { code: 'invalid-request-id' });
9024
+ }
9025
+ const ports = withDefaults(givenPorts);
9026
+ let store;
9027
+ try {
9028
+ const root = repoRoot(cwd);
9029
+ store = stateFor(ports.env, root);
9030
+ } catch (error) {
9031
+ if (error instanceof Stop && error.exitCode === 2 && error.message.includes('PDD_STATE_DIR')) throw error;
9032
+ store = new StateStore(resolve(ports.env.PDD_STATE_DIR || join(ports.env.HOME || homedir(), '.pdd', 'runtime')));
9033
+ }
9034
+ const origin = runtimeOrigin(explicitOrigin ? { PDD_RUNTIME_URL: explicitOrigin } : ports.env);
9035
+ const identity = signIn(ports.gh, store, ports);
9036
+ const secrets = [identity.token];
9037
+ const auth = authSession({ identity, store, ports, secrets });
9038
+ const runtime = new Runtime({ origin, token: identity.token, ports, signal: ports.signal, auth });
9039
+ const reply = await runtime.send(`/v1/runs/${encodeURIComponent(targetRequestId)}/reconciliation`, { method: 'GET' }, GET_MS);
9040
+ return projectCheckReconciliation({
9041
+ request_id: targetRequestId,
9042
+ status: reply.status ?? 0,
9043
+ body: reply.json,
9044
+ });
9045
+ }
9046
+
9047
+ async function queryHostedCheckReconciliation(runtime, requestId) {
9048
+ const reply = await runtime.send(`/v1/runs/${encodeURIComponent(requestId)}/reconciliation`, { method: 'GET' }, GET_MS);
9049
+ const status = reply.status ?? 0;
9050
+ if (status === 200) {
9051
+ const projected = projectCheckReconciliation({ request_id: requestId, status, body: reply.json });
9052
+ if (projected.accounting.status === 'complete_zero') {
9053
+ return {
9054
+ request_id: requestId,
9055
+ status: 'settled',
9056
+ cleared: true,
9057
+ known_calls: 0,
9058
+ accounting_complete: true,
9059
+ disposition_state: projected.disposition.state,
9060
+ refusal_code: projected.disposition.refusal_code,
9061
+ proof_basis: projected.evidence.proof_basis,
9062
+ reason: 'Authoritative server reconciliation confirmed 0 calls and no dispatch.',
9063
+ };
9064
+ }
9065
+ if (projected.accounting.status === 'complete_dispatched') {
9066
+ return {
9067
+ request_id: requestId,
9068
+ status: 'settled',
9069
+ cleared: true,
9070
+ known_calls: projected.accounting.known_calls,
9071
+ accounting_complete: true,
9072
+ disposition_state: projected.disposition.state,
9073
+ refusal_code: projected.disposition.refusal_code,
9074
+ proof_basis: projected.evidence.proof_basis,
9075
+ reason: `Authoritative server reconciliation confirmed terminal ${projected.disposition.state} (${projected.accounting.known_calls} calls).`,
9076
+ };
9077
+ }
9078
+ if (projected.disposition.expired || projected.disposition.purged) {
9079
+ return {
9080
+ request_id: requestId,
9081
+ status: 'expired',
9082
+ cleared: true,
9083
+ known_calls: null,
9084
+ accounting_complete: false,
9085
+ disposition_state: projected.disposition.state,
9086
+ refusal_code: projected.disposition.refusal_code,
9087
+ reason: 'Hosted run evidence has expired on the server; historical unknown usage retained.',
9088
+ };
9089
+ }
9090
+ if (projected.disposition.terminal === true) {
9091
+ return {
9092
+ request_id: requestId,
9093
+ status: 'terminated',
9094
+ cleared: true,
9095
+ known_calls: null,
9096
+ accounting_complete: false,
9097
+ disposition_state: projected.disposition.state,
9098
+ refusal_code: projected.disposition.refusal_code,
9099
+ reason: `Hosted run terminated (${projected.disposition.state}${projected.disposition.refusal_code ? `: ${projected.disposition.refusal_code}` : ''}); historical unknown usage retained.`,
9100
+ };
9101
+ }
9102
+ if (['queued', 'running'].includes(projected.disposition.state)) {
9103
+ return {
9104
+ request_id: requestId,
9105
+ status: 'active',
9106
+ cleared: false,
9107
+ known_calls: null,
9108
+ accounting_complete: false,
9109
+ disposition_state: projected.disposition.state,
9110
+ refusal_code: null,
9111
+ reason: `Hosted run is still ${projected.disposition.state}; reservation retained.`,
9112
+ };
9113
+ }
9114
+ return {
9115
+ request_id: requestId,
9116
+ status: 'unavailable',
9117
+ cleared: false,
9118
+ known_calls: null,
9119
+ accounting_complete: false,
9120
+ disposition_state: projected.disposition.state,
9121
+ refusal_code: projected.disposition.refusal_code,
9122
+ reason: projected.retry.safe_next_action,
9123
+ };
9124
+ }
9125
+ if (status === 410) {
9126
+ return {
9127
+ request_id: requestId,
9128
+ status: 'expired',
9129
+ cleared: true,
9130
+ known_calls: null,
9131
+ accounting_complete: false,
9132
+ disposition_state: 'unknown',
9133
+ refusal_code: null,
9134
+ reason: 'Hosted run evidence expired (HTTP 410); historical unknown usage retained.',
9135
+ };
9136
+ }
9137
+ if (status === 404 && reply.json?.error?.code === 'run-not-found') {
9138
+ return {
9139
+ request_id: requestId,
9140
+ status: 'not-found',
9141
+ cleared: true,
9142
+ known_calls: null,
9143
+ accounting_complete: false,
9144
+ disposition_state: 'unknown',
9145
+ refusal_code: null,
9146
+ reason: 'No hosted run exists for this request ID (HTTP 404); historical unknown usage retained.',
9147
+ };
9148
+ }
9149
+ if (status === 405 || status === 501 || (status === 404 && reply.json?.error?.code !== 'run-not-found')) {
9150
+ const fallback = await runtime.get(requestId);
9151
+ const fbStatus = fallback.status ?? 0;
9152
+ if (fbStatus === 404) {
9153
+ return {
9154
+ request_id: requestId,
9155
+ status: 'not-found',
9156
+ cleared: true,
9157
+ known_calls: null,
9158
+ accounting_complete: false,
9159
+ disposition_state: 'unknown',
9160
+ refusal_code: null,
9161
+ reason: 'No hosted run exists for this request ID (HTTP 404); historical unknown usage retained.',
9162
+ };
9163
+ }
9164
+ if (fbStatus === 410) {
9165
+ return {
9166
+ request_id: requestId,
9167
+ status: 'expired',
9168
+ cleared: true,
9169
+ known_calls: null,
9170
+ accounting_complete: false,
9171
+ disposition_state: 'unknown',
9172
+ refusal_code: null,
9173
+ reason: 'Hosted run evidence expired (HTTP 410); historical unknown usage retained.',
9174
+ };
9175
+ }
9176
+ if ((fbStatus === 200 || fbStatus === 202) && sameJob(fallback.json, requestId, 'check')) {
9177
+ const job = fallback.json;
9178
+ if (['queued', 'running'].includes(job.state)) {
9179
+ return {
9180
+ request_id: requestId,
9181
+ status: 'active',
9182
+ cleared: false,
9183
+ known_calls: null,
9184
+ accounting_complete: false,
9185
+ disposition_state: job.state,
9186
+ refusal_code: null,
9187
+ reason: `Hosted run is still ${job.state}; reservation retained.`,
9188
+ };
9189
+ }
9190
+ if (accountingEnd(job, requestId)) {
9191
+ const part = usagePart(job);
9192
+ const unknownWithoutExplicitProof = job.state === 'unknown'
9193
+ && ![job, job.usage, job.result, job.report, job.result?.report].some(s => isObject(s) && s.accounting_complete === true);
9194
+ if (!unknownWithoutExplicitProof && part.complete && Number.isSafeInteger(part.total)) {
9195
+ return {
9196
+ request_id: requestId,
9197
+ status: 'settled',
9198
+ cleared: true,
9199
+ known_calls: part.total,
9200
+ accounting_complete: true,
9201
+ disposition_state: job.state,
9202
+ refusal_code: job.result?.report?.refusal?.code ?? job.result?.refusals?.[0]?.code ?? null,
9203
+ reason: `Hosted run settled as ${job.state} (${part.total} calls).`,
9204
+ };
9205
+ }
9206
+ return {
9207
+ request_id: requestId,
9208
+ status: 'terminated',
9209
+ cleared: true,
9210
+ known_calls: null,
9211
+ accounting_complete: false,
9212
+ disposition_state: job.state,
9213
+ refusal_code: job.result?.report?.refusal?.code ?? job.result?.refusals?.[0]?.code ?? null,
9214
+ reason: `Hosted run terminated (${job.state}); historical unknown usage retained.`,
9215
+ };
9216
+ }
9217
+ }
9218
+ return {
9219
+ request_id: requestId,
9220
+ status: 'unavailable',
9221
+ cleared: false,
9222
+ known_calls: null,
9223
+ accounting_complete: false,
9224
+ disposition_state: 'unknown',
9225
+ refusal_code: null,
9226
+ reason: `Hosted run lookup unavailable (HTTP ${fbStatus}).`,
9227
+ };
9228
+ }
9229
+ return {
9230
+ request_id: requestId,
9231
+ status: 'unavailable',
9232
+ cleared: false,
9233
+ known_calls: null,
9234
+ accounting_complete: false,
9235
+ disposition_state: 'unknown',
9236
+ refusal_code: null,
9237
+ reason: `Hosted reconciliation lookup unavailable (HTTP ${status}).`,
9238
+ };
9239
+ }
9240
+
9241
+ async function reconcileBatchInternal({ root, store, batchId, explicitOrigin = null, ports, sessionCache = null, localExpirePastTtlOnly = false }) {
9242
+ const folder = join(store.dir, 'batches', batchId);
9243
+ const batchPath = join(folder, 'batch.json');
9244
+ if (!statOrNull(batchPath)) {
9245
+ throw Object.assign(new Stop(2, `No saved batch ${batchId}.`), { code: 'batch-not-found' });
9246
+ }
9247
+ const now = ports.now();
9248
+ const ttlMs = priorReservationTtlMs(ports.env);
9249
+ const ttlHours = Math.round((ttlMs / 3_600_000) * 100) / 100;
9250
+ const reconciledAt = new Date(now).toISOString();
9251
+ const lockContext = { store, ports, root, folder };
9252
+ await ownBatch(lockContext, batchId);
9253
+ try {
9254
+ const saved = store.read(batchPath);
9255
+ if (!isObject(saved) || !Array.isArray(saved.rows)) {
9256
+ throw Object.assign(new Stop(2, `Saved batch ${batchId} is unreadable or invalid.`), { code: 'invalid-batch' });
9257
+ }
9258
+ if (typeof saved.root !== 'string' || realish(saved.root) !== realish(root)) {
9259
+ throw Object.assign(new Stop(2, 'This saved batch belongs to a different repository.'), { code: 'wrong-repo' });
9260
+ }
9261
+ if (saved.intent !== 'check' && !(saved.version === 1 && saved.intent === undefined)) {
9262
+ throw Object.assign(new Stop(2, `Saved batch ${batchId} has no Check intent.`), { code: 'not-check-batch' });
9263
+ }
9264
+ const adoptContext = { store, folder, ports };
9265
+ const unresolvedRows = [];
9266
+ for (const row of saved.rows) {
9267
+ if (!isObject(row)) continue;
9268
+ if (!Array.isArray(row.request_ids)) row.request_ids = [];
9269
+ adoptClaims(adoptContext, row);
9270
+ if (rowNeedsReservationCheck(row)) unresolvedRows.push(row);
9271
+ }
9272
+ if (!unresolvedRows.length) {
9273
+ return {
9274
+ schema_version: 'pdd-runtime.batch-reconciliation.v1',
9275
+ batch: batchId,
9276
+ repo: root,
9277
+ reconciled_at: reconciledAt,
9278
+ ttl_hours: ttlHours,
9279
+ status: 'already-resolved',
9280
+ cleared_count: 0,
9281
+ settled_count: 0,
9282
+ expired_count: 0,
9283
+ terminated_count: 0,
9284
+ active_count: 0,
9285
+ unavailable_count: 0,
9286
+ remaining_unresolved_count: 0,
9287
+ rows: [],
9288
+ };
9289
+ }
9290
+
9291
+ const origin = runtimeOrigin(explicitOrigin ? { PDD_RUNTIME_URL: explicitOrigin } : saved.origin ? { PDD_RUNTIME_URL: saved.origin } : ports.env);
9292
+ let runtime = null;
9293
+ let runtimeError = null;
9294
+ const ensureRuntime = () => {
9295
+ if (runtime) return runtime;
9296
+ if (runtimeError) throw runtimeError;
9297
+ try {
9298
+ let identity = sessionCache?.identity ?? null;
9299
+ if (!identity) {
9300
+ identity = signIn(ports.gh, store, ports);
9301
+ if (sessionCache) sessionCache.identity = identity;
9302
+ }
9303
+ if (saved.login && identity.login !== saved.login) {
9304
+ throw new Stop(5, `These runs belong to ${saved.login}. Run: gh auth switch -u ${saved.login}`);
9305
+ }
9306
+ const cacheKey = `${origin}\0${saved.login ?? ''}`;
9307
+ let cached = sessionCache?.runtimes?.get(cacheKey);
9308
+ if (!cached) {
9309
+ const secrets = [identity.token];
9310
+ const auth = authSession({
9311
+ identity,
9312
+ store,
9313
+ ports,
9314
+ secrets,
9315
+ ...(saved.login ? {
9316
+ expectedOwnerLogin: saved.login,
9317
+ ownerMismatchError: owner => new Stop(5, `These runs belong to ${owner}. Run: gh auth switch -u ${owner}`),
9318
+ } : {}),
9319
+ });
9320
+ cached = new Runtime({ origin, token: identity.token, ports, signal: ports.signal, auth });
9321
+ sessionCache?.runtimes?.set(cacheKey, cached);
9322
+ }
9323
+ runtime = cached;
9324
+ return runtime;
9325
+ } catch (error) {
9326
+ runtimeError = error;
9327
+ throw error;
9328
+ }
9329
+ };
9330
+
9331
+ const rowReports = [];
9332
+ let mutated = false;
9333
+ let clearedCount = 0, settledCount = 0, expiredCount = 0, terminatedCount = 0, activeCount = 0, unavailableCount = 0;
9334
+
9335
+ for (const row of unresolvedRows) {
9336
+ const ids = Array.isArray(row.request_ids) ? [...row.request_ids] : [];
9337
+ const previousState = row.recovery_state ?? row.state ?? 'unknown';
9338
+ const ts = reservationTimestampMs(batchId, saved, row);
9339
+ const pastTtl = ts !== null && Number.isFinite(now) && Number.isFinite(ttlMs) && now - ts >= ttlMs;
9340
+
9341
+ const localSettled = !row.dispatchIncomplete && ids.length > 0 ? localRowSettledFromReceipts(store, folder, ids) : { settled: false };
9342
+ if (localSettled.settled) {
9343
+ row.calls = localSettled.known_calls;
9344
+ row.known_calls = localSettled.known_calls;
9345
+ row.unknown_calls = 0;
9346
+ row.accounting_complete = true;
9347
+ if (localSettled.state && ['sending', 'queued', 'running', 'unknown'].includes(previousState)) {
9348
+ row.recovery_state = localSettled.state;
9349
+ row.state = localSettled.state;
9350
+ }
9351
+ row.reservation_reconciled = {
9352
+ cleared: true,
9353
+ status: 'settled',
9354
+ source: 'local-receipt',
9355
+ at: reconciledAt,
9356
+ request_ids: ids,
9357
+ calls: localSettled.known_calls,
9358
+ };
9359
+ mutated = true;
9360
+ clearedCount += 1;
9361
+ settledCount += 1;
9362
+ rowReports.push({
9363
+ test: row.test ?? '-',
9364
+ request_ids: ids,
9365
+ previous_state: previousState,
9366
+ status: 'settled',
9367
+ cleared: true,
9368
+ calls: localSettled.known_calls,
9369
+ accounting_complete: true,
9370
+ attempts: [],
9371
+ reason: `Settled locally from saved receipts (${localSettled.known_calls} calls).`,
9372
+ });
9373
+ continue;
9374
+ }
9375
+
9376
+ if (pastTtl && (localExpirePastTtlOnly || !ids.length || row.dispatchIncomplete)) {
9377
+ row.can_retry = false;
9378
+ row.busy = false;
9379
+ row.reservation_reconciled = {
9380
+ cleared: true,
9381
+ status: 'ttl-expired',
9382
+ at: reconciledAt,
9383
+ request_ids: ids,
9384
+ ttl_hours: ttlHours,
9385
+ };
9386
+ mutated = true;
9387
+ clearedCount += 1;
9388
+ expiredCount += 1;
9389
+ rowReports.push({
9390
+ test: row.test ?? '-',
9391
+ request_ids: ids,
9392
+ previous_state: previousState,
9393
+ status: 'ttl-expired',
9394
+ cleared: true,
9395
+ calls: row.calls ?? 'unknown',
9396
+ accounting_complete: false,
9397
+ attempts: [],
9398
+ reason: `Reservation exceeded bounded ${ttlHours}h TTL; cleared locally while preserving historical unknown usage.`,
9399
+ });
9400
+ continue;
9401
+ }
9402
+
9403
+ if (!ids.length || row.dispatchIncomplete) {
9404
+ unavailableCount += 1;
9405
+ rowReports.push({
9406
+ test: row.test ?? '-',
9407
+ request_ids: ids,
9408
+ previous_state: previousState,
9409
+ status: 'unavailable',
9410
+ cleared: false,
9411
+ calls: row.calls ?? 'unknown',
9412
+ accounting_complete: false,
9413
+ attempts: [],
9414
+ reason: 'Interrupted dispatch claim has no recoverable request UUID and is still within TTL; reservation retained.',
9415
+ });
9416
+ continue;
9417
+ }
9418
+
9419
+ let activeRuntime;
9420
+ try {
9421
+ activeRuntime = ensureRuntime();
9422
+ } catch (error) {
9423
+ if (pastTtl && !(error instanceof Stop && error.exitCode === 5 && String(error.message).includes('These runs belong to'))) {
9424
+ row.can_retry = false;
9425
+ row.busy = false;
9426
+ row.reservation_reconciled = {
9427
+ cleared: true,
9428
+ status: 'ttl-expired',
9429
+ at: reconciledAt,
9430
+ request_ids: ids,
9431
+ ttl_hours: ttlHours,
9432
+ };
9433
+ mutated = true;
9434
+ clearedCount += 1;
9435
+ expiredCount += 1;
9436
+ rowReports.push({
9437
+ test: row.test ?? '-',
9438
+ request_ids: ids,
9439
+ previous_state: previousState,
9440
+ status: 'ttl-expired',
9441
+ cleared: true,
9442
+ calls: row.calls ?? 'unknown',
9443
+ accounting_complete: false,
9444
+ attempts: [],
9445
+ reason: `Server reconciliation unavailable and reservation exceeded bounded ${ttlHours}h TTL; cleared locally while preserving historical unknown usage.`,
9446
+ });
9447
+ continue;
9448
+ }
9449
+ throw error;
9450
+ }
9451
+
9452
+ const attempts = [];
9453
+ for (const id of ids) {
9454
+ if (!UUID.test(id)) {
9455
+ attempts.push({ request_id: id, status: 'unavailable', cleared: false, known_calls: null, accounting_complete: false, disposition_state: 'unknown', refusal_code: null, reason: 'Invalid request UUID.' });
9456
+ continue;
9457
+ }
9458
+ attempts.push(await queryHostedCheckReconciliation(activeRuntime, id));
9459
+ }
9460
+
9461
+ if (attempts.some(attempt => attempt.status === 'active')) {
9462
+ activeCount += 1;
9463
+ rowReports.push({
9464
+ test: row.test ?? '-',
9465
+ request_ids: ids,
9466
+ previous_state: previousState,
9467
+ status: 'active',
9468
+ cleared: false,
9469
+ calls: row.calls ?? 'unknown',
9470
+ accounting_complete: false,
9471
+ attempts,
9472
+ reason: 'At least one hosted Check attempt is still queued or running; reservation retained.',
9473
+ });
9474
+ continue;
9475
+ }
9476
+
9477
+ if (attempts.some(attempt => attempt.status === 'unavailable')) {
9478
+ if (pastTtl) {
9479
+ row.can_retry = false;
9480
+ row.busy = false;
9481
+ row.reservation_reconciled = {
9482
+ cleared: true,
9483
+ status: 'ttl-expired',
9484
+ at: reconciledAt,
9485
+ request_ids: ids,
9486
+ ttl_hours: ttlHours,
9487
+ };
9488
+ mutated = true;
9489
+ clearedCount += 1;
9490
+ expiredCount += 1;
9491
+ rowReports.push({
9492
+ test: row.test ?? '-',
9493
+ request_ids: ids,
9494
+ previous_state: previousState,
9495
+ status: 'ttl-expired',
9496
+ cleared: true,
9497
+ calls: row.calls ?? 'unknown',
9498
+ accounting_complete: false,
9499
+ attempts,
9500
+ reason: `Server reconciliation unavailable and reservation exceeded bounded ${ttlHours}h TTL; cleared locally while preserving historical unknown usage.`,
9501
+ });
9502
+ } else {
9503
+ unavailableCount += 1;
9504
+ rowReports.push({
9505
+ test: row.test ?? '-',
9506
+ request_ids: ids,
9507
+ previous_state: previousState,
9508
+ status: 'unavailable',
9509
+ cleared: false,
9510
+ calls: row.calls ?? 'unknown',
9511
+ accounting_complete: false,
9512
+ attempts,
9513
+ reason: 'Server reconciliation is currently unavailable for this within-TTL batch; reservation retained.',
9514
+ });
9515
+ }
9516
+ continue;
9517
+ }
9518
+
9519
+ if (attempts.every(attempt => attempt.status === 'settled')) {
9520
+ const totalCalls = attempts.reduce((sum, attempt) => sum + (Number.isSafeInteger(attempt.known_calls) ? attempt.known_calls : 0), 0);
9521
+ const latestState = attempts.at(-1)?.disposition_state ?? null;
9522
+ row.calls = totalCalls;
9523
+ row.known_calls = totalCalls;
9524
+ row.unknown_calls = 0;
9525
+ row.accounting_complete = true;
9526
+ if (latestState && ['sending', 'queued', 'running', 'unknown'].includes(previousState)) {
9527
+ row.recovery_state = latestState;
9528
+ row.state = latestState;
9529
+ }
9530
+ row.reservation_reconciled = {
9531
+ cleared: true,
9532
+ status: 'settled',
9533
+ source: 'server-reconciliation',
9534
+ at: reconciledAt,
9535
+ request_ids: ids,
9536
+ calls: totalCalls,
9537
+ };
9538
+ mutated = true;
9539
+ clearedCount += 1;
9540
+ settledCount += 1;
9541
+ rowReports.push({
9542
+ test: row.test ?? '-',
9543
+ request_ids: ids,
9544
+ previous_state: previousState,
9545
+ status: 'settled',
9546
+ cleared: true,
9547
+ calls: totalCalls,
9548
+ accounting_complete: true,
9549
+ attempts,
9550
+ reason: `Settled via server reconciliation (${totalCalls} calls).`,
9551
+ });
9552
+ continue;
9553
+ }
9554
+
9555
+ // All attempts terminated, expired, or not-found without complete accounting: preserve honest unknown usage & no-retry, clear stale reservation.
9556
+ const rowStatus = attempts.some(attempt => attempt.status === 'terminated')
9557
+ ? 'terminated'
9558
+ : attempts.some(attempt => attempt.status === 'expired')
9559
+ ? 'expired'
9560
+ : 'not-found';
9561
+ const refusalCode = attempts.find(attempt => attempt.refusal_code)?.refusal_code ?? null;
9562
+ row.can_retry = false;
9563
+ row.busy = false;
9564
+ row.reservation_reconciled = {
9565
+ cleared: true,
9566
+ status: rowStatus,
9567
+ source: 'server-reconciliation',
9568
+ at: reconciledAt,
9569
+ request_ids: ids,
9570
+ ...(refusalCode ? { refusal_code: refusalCode } : {}),
9571
+ };
9572
+ mutated = true;
9573
+ clearedCount += 1;
9574
+ if (rowStatus === 'terminated') terminatedCount += 1;
9575
+ else expiredCount += 1;
9576
+ rowReports.push({
9577
+ test: row.test ?? '-',
9578
+ request_ids: ids,
9579
+ previous_state: previousState,
9580
+ status: rowStatus,
9581
+ cleared: true,
9582
+ calls: row.calls ?? 'unknown',
9583
+ accounting_complete: false,
9584
+ attempts,
9585
+ reason: attempts.map(attempt => attempt.reason).join(' '),
9586
+ });
9587
+ }
9588
+
9589
+ if (mutated) {
9590
+ saved.reservations_reconciled_at = reconciledAt;
9591
+ store.write(batchPath, saved);
9592
+ }
9593
+
9594
+ const remainingUnresolved = activeCount + unavailableCount;
9595
+ const batchStatus = remainingUnresolved === 0
9596
+ ? 'reconciled'
9597
+ : clearedCount > 0
9598
+ ? 'partial'
9599
+ : activeCount > 0
9600
+ ? 'active'
9601
+ : 'unavailable';
9602
+ return {
9603
+ schema_version: 'pdd-runtime.batch-reconciliation.v1',
9604
+ batch: batchId,
9605
+ repo: root,
9606
+ reconciled_at: reconciledAt,
9607
+ ttl_hours: ttlHours,
9608
+ status: batchStatus,
9609
+ cleared_count: clearedCount,
9610
+ settled_count: settledCount,
9611
+ expired_count: expiredCount,
9612
+ terminated_count: terminatedCount,
9613
+ active_count: activeCount,
9614
+ unavailable_count: unavailableCount,
9615
+ remaining_unresolved_count: remainingUnresolved,
9616
+ rows: rowReports,
9617
+ };
9618
+ } finally {
9619
+ lockContext.releaseBatch?.();
9620
+ }
9621
+ }
9622
+
9623
+ export async function reconcileCheckBatch({ cwd = process.cwd(), batchId, origin: explicitOrigin } = {}, givenPorts = {}) {
9624
+ const targetBatch = String(batchId ?? '');
9625
+ if (!BATCH.test(targetBatch)) {
9626
+ throw Object.assign(new Error(`Invalid local batch ID "${cleanText(targetBatch)}". Pass a batch ID like 20261107-182617-8r61.`), { code: 'invalid-batch-id', exitCode: 2 });
9627
+ }
9628
+ const ports = withDefaults(givenPorts);
9629
+ const root = repoRoot(cwd);
9630
+ const store = stateFor(ports.env, root);
9631
+ return await reconcileBatchInternal({ root, store, batchId: targetBatch, explicitOrigin, ports });
9632
+ }
9633
+
9634
+ export async function reconcileStaleReservations({ cwd = process.cwd(), origin: explicitOrigin } = {}, givenPorts = {}) {
9635
+ const ports = withDefaults(givenPorts);
9636
+ const root = repoRoot(cwd);
9637
+ const store = stateFor(ports.env, root);
9638
+ const now = ports.now();
9639
+ const ttlMs = priorReservationTtlMs(ports.env);
9640
+ const ttlHours = Math.round((ttlMs / 3_600_000) * 100) / 100;
9641
+ const reconciledAt = new Date(now).toISOString();
9642
+ const priorAll = readUnresolvedPriorReservations(root, ports.env, null, { now, ttlMs, includeExpired: true });
9643
+ const sessionCache = { identity: null, runtimes: new Map() };
9644
+ const batches = [];
9645
+ let batchesCleared = 0, clearedCount = 0, remainingUnresolved = 0;
9646
+
9647
+ for (const batchId of priorAll.batches) {
9648
+ try {
9649
+ const result = await reconcileBatchInternal({
9650
+ root,
9651
+ store,
9652
+ batchId,
9653
+ explicitOrigin,
9654
+ ports,
9655
+ sessionCache,
9656
+ localExpirePastTtlOnly: true,
9657
+ });
9658
+ batches.push(result);
9659
+ clearedCount += result.cleared_count;
9660
+ remainingUnresolved += result.remaining_unresolved_count;
9661
+ if (result.remaining_unresolved_count === 0) batchesCleared += 1;
9662
+ } catch (error) {
9663
+ if (error instanceof Stop && error.exitCode === 3 && String(error.message).includes('Another pdd test command is using batch')) {
9664
+ batches.push({
9665
+ schema_version: 'pdd-runtime.batch-reconciliation.v1',
9666
+ batch: batchId,
9667
+ repo: root,
9668
+ reconciled_at: reconciledAt,
9669
+ ttl_hours: ttlHours,
9670
+ status: 'active',
9671
+ cleared_count: 0,
9672
+ settled_count: 0,
9673
+ expired_count: 0,
9674
+ terminated_count: 0,
9675
+ active_count: 1,
9676
+ unavailable_count: 0,
9677
+ remaining_unresolved_count: 1,
9678
+ rows: [],
9679
+ reason: error.message,
9680
+ });
9681
+ remainingUnresolved += 1;
9682
+ continue;
9683
+ }
9684
+ throw error;
9685
+ }
9686
+ }
9687
+
9688
+ return {
9689
+ schema_version: 'pdd-runtime.stale-reconciliation.v1',
9690
+ repo: root,
9691
+ reconciled_at: reconciledAt,
9692
+ ttl_hours: ttlHours,
9693
+ batches_inspected: batches.length,
9694
+ batches_cleared: batchesCleared,
9695
+ cleared_count: clearedCount,
9696
+ remaining_unresolved_count: remainingUnresolved,
9697
+ batches,
9698
+ };
9699
+ }
9700
+
9701
+ function formatCheckReconciliationLines(result) {
9702
+ const lines = [
9703
+ `CHECK reconciliation (${result.request_id}):`,
9704
+ ` State: ${result.disposition.state} (terminal: ${result.disposition.terminal}${result.disposition.refusal_code ? `, refusal: ${result.disposition.refusal_code}` : ''}${result.disposition.expired ? ', expired' : ''})`,
9705
+ ` Dispatch: ${result.dispatch.status} (proven: ${result.dispatch.proven})`,
9706
+ ` Accounting: ${result.accounting.status} (complete: ${result.accounting.accounting_complete}, calls: ${result.accounting.calls})`,
9707
+ ` Retry blocked: ${result.retry.blocked}`,
9708
+ ` Next action: ${result.retry.safe_next_action}`,
9709
+ ];
9710
+ return lines;
9711
+ }
9712
+
9713
+ function formatBatchReconciliationLines(result) {
9714
+ if (!result.rows.length && result.status === 'already-resolved') {
9715
+ return [`Batch ${result.batch}: no unresolved prior reservations remain.`];
9716
+ }
9717
+ const parts = [];
9718
+ if (result.settled_count) parts.push(`${result.settled_count} settled`);
9719
+ if (result.terminated_count) parts.push(`${result.terminated_count} terminated`);
9720
+ if (result.expired_count) parts.push(`${result.expired_count} expired`);
9721
+ const breakdown = parts.length ? ` (${parts.join(', ')})` : '';
9722
+ const lines = [
9723
+ `Reconciled batch ${result.batch}: ${result.cleared_count} cleared${breakdown}, ${result.remaining_unresolved_count} remaining unresolved.`,
9724
+ ];
9725
+ for (const row of result.rows) {
9726
+ lines.push(` ${row.test}: ${row.status} (calls: ${row.calls}; cleared: ${row.cleared ? 'yes' : 'no'}) — ${row.reason}`);
9727
+ }
9728
+ return lines;
9729
+ }
9730
+
9731
+ function formatStaleReconciliationLines(result) {
9732
+ if (result.batches_inspected === 0) {
9733
+ return ['No unresolved prior reservations found for this repository.'];
9734
+ }
9735
+ const lines = [
9736
+ `Reconciled ${result.batches_inspected} prior batch${result.batches_inspected === 1 ? '' : 'es'}: ${result.cleared_count} reservation${result.cleared_count === 1 ? '' : 's'} cleared, ${result.remaining_unresolved_count} remaining unresolved.`,
9737
+ ];
9738
+ for (const batch of result.batches) {
9739
+ if (batch.reason) lines.push(` ${batch.batch}: ${batch.status} — ${batch.reason}`);
9740
+ else lines.push(` ${batch.batch}: ${batch.status} (${batch.cleared_count} cleared, ${batch.remaining_unresolved_count} remaining)`);
9741
+ }
9742
+ return lines;
9743
+ }
9744
+
9745
+ async function runReconcileCommand(context, rawTarget, cwd, givenPorts) {
9746
+ const target = typeof rawTarget === 'string' ? rawTarget.trim() : '';
9747
+ if (!UUID.test(target) && !BATCH.test(target)) {
9748
+ throw new Stop(2, `Invalid --reconcile target "${cleanText(String(rawTarget ?? ''))}". Pass a CHECK request UUID or a local batch ID (e.g. 20261107-182617-8r61).`);
9749
+ }
9750
+ if (UUID.test(target)) {
9751
+ const result = await reconcileCheckReceipt({ cwd, requestId: target }, givenPorts);
9752
+ if (context.json) line(context.ports.stdout, JSON.stringify(result));
9753
+ else for (const text of formatCheckReconciliationLines(result)) line(context.ports.stdout, text);
9754
+ return result.available === true ? 0 : 3;
9755
+ }
9756
+ const result = await reconcileCheckBatch({ cwd, batchId: target }, givenPorts);
9757
+ if (context.json) line(context.ports.stdout, JSON.stringify(result));
9758
+ else for (const text of formatBatchReconciliationLines(result)) line(context.ports.stdout, text);
9759
+ return result.remaining_unresolved_count === 0 ? 0 : 3;
9760
+ }
9761
+
9762
+ async function runReconcileStaleCommand(context, rawFlag, cwd, givenPorts) {
9763
+ if (rawFlag !== true) throw new Stop(2, '--reconcile-stale takes no value.');
9764
+ const result = await reconcileStaleReservations({ cwd }, givenPorts);
9765
+ if (context.json) line(context.ports.stdout, JSON.stringify(result));
9766
+ else for (const text of formatStaleReconciliationLines(result)) line(context.ports.stdout, text);
9767
+ return result.remaining_unresolved_count === 0 ? 0 : 3;
9768
+ }
9769
+
7764
9770
  export async function readTryOwner({ cwd = process.cwd(), story, tryId } = {}, givenPorts = {}) {
7765
9771
  const ports = withDefaults(givenPorts), root = repoRoot(cwd), found = ports.findTests({ root }), store = stateFor(ports.env, root);
7766
9772
  const repo = store.repo(root);
@@ -8091,7 +10097,8 @@ export async function admitProgram(context, capture, { entry, appMap, initial_wo
8091
10097
  const registered = await recordRuntimeRequest(setup.reservation, id, slotPorts(context));
8092
10098
  if (registered === false || context.interrupted) { await finishReservation(context, setup, { state: 'not_run' }); throw problem('Stopped before program setup was sent.'); }
8093
10099
  store.posted(context.folder, id);
8094
- const reply = await context.runtime.post('/v1/try', request, capture.tar, ports.postMs);
10100
+ const dedupTry = context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: true } : undefined;
10101
+ const reply = await context.runtime.post('/v1/try', request, capture.tar, ports.postMs, dedupTry);
8095
10102
  const verdict = judgePost(reply, id, 'try', context.secrets);
8096
10103
  if (verdict.answer) store.write(join(context.folder, `${id}.json`), verdict.answer);
8097
10104
  if (verdict.kind === 'busy') {