@promptdriven/runtime-client 1.1.1 → 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';
@@ -29,6 +29,7 @@ import { jsonSafe, parseScenarioJson } from './scenario-json.mjs';
29
29
  import { scenarioDerivationRefusal } from './runtime-preflight.mjs';
30
30
  import { OPEN_STATES, causeText, cleanText, progressTicker, projectAnswer, refusalView, renderJson, renderText, summaryLine, stepTimeLimit, tokenUsageOf, tryUsage, validLink, coverageText } from './runtime-output.mjs';
31
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';
32
33
 
33
34
  const localInterfaceProblem = problem => ['interface-missing','interface-kind-invalid','native-reason-missing','interface-draft-incomplete','duplicate-selector-word'].includes(problem.code);
34
35
  const unboundPortError = message => Object.assign(new Error(message), { unboundPort: true });
@@ -48,6 +49,12 @@ function formatAdvice(root, visible, paths, workspace) {
48
49
  for (const path of paths) visit(path);
49
50
  return lines;
50
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
+ }
51
58
  function hasMissingPromptInterface(root, found, startPaths) {
52
59
  const seen = new Set(), queue = [...startPaths];
53
60
  while (queue.length) {
@@ -61,6 +68,29 @@ function hasMissingPromptInterface(root, found, startPaths) {
61
68
  }
62
69
  return false;
63
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
+ }
64
94
  const diagnosticBatch = record => record?.diagnostic_subset === true || record?.rows?.some(row=>row?.diagnostic_subset === true);
65
95
  const entryPaths = tests => tests.filter(test => !test.error).flatMap(test => (Array.isArray(test.doc?.steps) ? test.doc.steps : []).map(step => step?.entry_path));
66
96
 
@@ -86,6 +116,8 @@ const POST_MS = 90_000, GET_MS = 30_000, TRY_MS = 300_000, MAX_READS = 8, PROGRE
86
116
  const AGENT_WAIT_MIN = 1.5;
87
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.
88
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;
89
121
 
90
122
  class Stop extends Error { constructor(exitCode, message) { super(message); this.exitCode = exitCode; } }
91
123
  function requestedCalls(raw) {
@@ -95,6 +127,53 @@ function requestedCalls(raw) {
95
127
  throw new Stop(2, '--max-calls must be a whole number from 1 to 1000, the interpreter maximum.');
96
128
  return Number(raw);
97
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
+ }
98
177
 
99
178
  function sampleOptions(options) {
100
179
  const parse = value => {
@@ -712,6 +791,9 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
712
791
  if (!sent.has(row.story)) sent.set(row.story, new Set());
713
792
  sent.get(row.story).add(row.test);
714
793
  let pass = false;
794
+ let rowOwnPassed = false;
795
+ const rowPassedKeys = new Set();
796
+ const rowRequiredKeys = new Set();
715
797
  const id = row.request_ids.at(-1);
716
798
  if (typeof id === 'string' && UUID.test(id)) {
717
799
  const receiptPath = join(folder, `${id}.json`);
@@ -737,6 +819,25 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
737
819
  && view.criteria.passed === row.criteria_total && view.checks?.total > 0 && view.checks.passed === view.checks.total
738
820
  && Array.isArray(criteria) && new Set(criteria.map(item => item?.criterion_id)).size === row.criteria_total
739
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
+ }
740
841
  }
741
842
  } catch (error) {
742
843
  if (!(error?.code === 'ENOENT' && unsavedPostOutcome(row))) warning(receiptPath, error);
@@ -745,7 +846,20 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
745
846
  const at = Number.isFinite(row.ended_at) ? row.ended_at : Date.parse(batch.created_at) || 0;
746
847
  const previous = grouped.get(row.story);
747
848
  const current = storyCurrent.get(row.story) ?? false;
748
- grouped.set(row.story, { story: row.story, pass: pass && (previous?.pass ?? true), current, result: 'no verdict', at: Math.max(previous?.at ?? at, at) });
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
+ });
749
863
  }
750
864
  // withTests: pdd's own fix texts of a Story's refusals (its saved warnings, then each refusal's fix).
751
865
  const advised = story => {
@@ -755,9 +869,14 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
755
869
  return { ...info, advice: [...new Set([...warned, ...fixes])].slice(0, 3).map(text => text.slice(0, 800)) };
756
870
  };
757
871
  for (const row of grouped.values()) {
758
- if (row.pass && sent.get(row.story).size !== selected.get(row.story).size) continue;
759
- if (row.pass) row.result = '✓';
760
- 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);
761
880
  }
762
881
  // withTests: a Story whose tests were never sent (refused before execution, interrupted) is listed too.
763
882
  if (withTests) for (const story of extra.keys()) if (!grouped.has(story)) {
@@ -1321,7 +1440,13 @@ const unadmittedCallErrors = new WeakMap();
1321
1440
 
1322
1441
  // HTTP to the runtime. The token stays in this object and in request headers only.
1323
1442
  class Runtime {
1324
- 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
+ }
1325
1450
  async sendOnce(path, init, ms) {
1326
1451
  const readSignal = init?.method === 'GET' ? init.signal : null;
1327
1452
  if (this.signal?.aborted || readSignal?.aborted) return { lost: true };
@@ -1450,7 +1575,31 @@ class Runtime {
1450
1575
  else if (pathname !== '/v1/capacity' && [200, 202].includes(retry.status)) this.auth.verifiedByServer = true;
1451
1576
  return retry;
1452
1577
  }
1453
- post(path, request, tar, timeoutMs = this.ports.postMs) {
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) {
1454
1603
  const makeForm = () => {
1455
1604
  const form = new FormData();
1456
1605
  form.set('request', new Blob([JSON.stringify(request)], { type: 'application/json' }), 'request.json');
@@ -1459,7 +1608,37 @@ class Runtime {
1459
1608
  form.set('source', source, 'source.tar');
1460
1609
  return form;
1461
1610
  };
1462
- 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;
1463
1642
  }
1464
1643
  get(id, timeoutMs = GET_MS, { waitSeconds = 0 } = {}) {
1465
1644
  const headers = waitSeconds > 0 ? preferWaitHeaders(waitSeconds) : undefined;
@@ -1814,7 +1993,7 @@ function markBusy(context, row, wait, observedAt = context.ports.now(), legacy =
1814
1993
  checks: null, criteria: null, all_checks: [], failed_checks: [], why: null, next_step: null,
1815
1994
  note: { code: 'check-busy', message: 'The interpreter is busy. No checks ran for this attempt. Retry this batch later.' } });
1816
1995
  Object.assign(row, accumulatedAccounting(context, row));
1817
- if (!context.reading) context.checkWindow = 1;
1996
+ if (!context.reading) backoffCheckWindow(context, id ?? `${row.test}:${row.request_ids.length}`, 'server busy / 429');
1818
1997
  }
1819
1998
 
1820
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');
@@ -1886,9 +2065,13 @@ function localLimit(context) {
1886
2065
  if (raw === undefined) return context.localLimit = Infinity;
1887
2066
  const value = Number(raw);
1888
2067
  if (/^[1-9][0-9]*$/.test(String(raw)) && Number.isSafeInteger(value)) return context.localLimit = value;
1889
- 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.`);
1890
2069
  return context.localLimit = Infinity;
1891
2070
  }
2071
+ function checkConcurrencyLimit(context) {
2072
+ const limit = localLimit(context);
2073
+ return Number.isFinite(limit) ? limit : DEFAULT_CHECK_CONCURRENCY;
2074
+ }
1892
2075
  function uploadLimit(context) {
1893
2076
  if (context.uploadLimit !== undefined) return context.uploadLimit;
1894
2077
  const raw = context.ports.env.PDD_MAX_UPLOADS;
@@ -2091,7 +2274,7 @@ async function probeLazyInterfaces(context, origin, store) {
2091
2274
  if (isDefinitiveCapacityReply(reply)) {
2092
2275
  const features = reply.status === 200 && Array.isArray(reply.json?.features) ? reply.json.features : [];
2093
2276
  const engineSha = reply.status === 200 ? reply.json?.engine_sha ?? null : null;
2094
- const supportsLazy = features.includes('lazy-interfaces');
2277
+ const supportsLazy = features.includes('lazy-interfaces') || features.some(feature => /^hybrid(?:-|$)/.test(feature));
2095
2278
  if (supportsLazy) store?.writeOriginCapabilities(origin, { features, engine_sha: engineSha }, context.ports.now());
2096
2279
  else store?.deleteOriginCapabilities(origin);
2097
2280
  context.probedIdentity = identity;
@@ -2241,11 +2424,11 @@ function judgePost(reply, id, command, secrets) {
2241
2424
  return { kind: 'busy', wait: retryAfter(reply.headers), admission: reply.json };
2242
2425
  }
2243
2426
  return retryable429 ? { kind: 'busy', wait: retryAfter(reply.headers), admission: reply.json }
2244
- : { kind: 'not_run', note: note('The interpreter is busy. Try again later.') };
2427
+ : { kind: 'not_run', note: note('The interpreter is busy. Try again later.'), contention: true };
2245
2428
  }
2246
2429
  if (gateText(reply)) return { kind: 'stop', note: { code: null, message: 'The runtime opens soon.' } };
2247
2430
  if (reply.status === 401) return { kind: 'stop', note: { code: cleanText(error?.code, secrets) || 'auth-required', message: AUTH_TEXT } };
2248
- 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 };
2249
2432
  if ([400, 413, 415, 422].includes(reply.status) && error?.code) {
2250
2433
  return { kind: 'refused', refusal: { code: cleanText(error.code, secrets), section: cleanText(error.section, secrets) || null, message: cleanText(error.message, secrets) || null,
2251
2434
  engine_message: reply.json.details ? cleanText(JSON.stringify(reply.json.details), secrets) : null,
@@ -2266,6 +2449,7 @@ function judgeGet(reply, id, command) {
2266
2449
  if (reply.status === 410) return { kind: 'unknown', why: 'The result expired.', status: 410 };
2267
2450
  if (reply.status === 401) return { kind: 'auth' };
2268
2451
  if (gateText(reply)) return { kind: 'gate' };
2452
+ if (reply.status === 429) return { kind: 'again', contention: true };
2269
2453
  return { kind: 'again' };
2270
2454
  }
2271
2455
 
@@ -2353,6 +2537,137 @@ const incompleteCriteria = row => {
2353
2537
  message:'The Story is not a full pass: some criteria were not checked.'}});
2354
2538
  };
2355
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
+
2356
2671
  function capturedCriteria(rows, capture) {
2357
2672
  let broken = false;
2358
2673
  for (const row of rows.filter(row=>!row.unsent)) {
@@ -2373,8 +2688,13 @@ function capturedCriteria(rows, capture) {
2373
2688
  const exemptions=Array.isArray(doc.check_exemptions)?doc.check_exemptions:[];
2374
2689
  const unchecked=exemptions.filter(item=>isObject(item)&&item.reason==='out-of-scope').map(item=>({
2375
2690
  criterion_id:item.criterion_id,text:row.criterion_texts[item.criterion_id],reason:item.detail}));
2376
- if (unchecked.length) row.not_checked=unchecked;
2377
- 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
+ }
2378
2698
  }
2379
2699
  return broken;
2380
2700
  }
@@ -2624,15 +2944,41 @@ function applyAnswer(row, answer, context, observedWait = null, observedAt = con
2624
2944
  if (capacityUncertain) markCapacityUnknown(context, row);
2625
2945
  else if (wait !== null) markBusy(context, row, observedWait ?? wait, observedAt, context.reading && observedWait === null);
2626
2946
  else { row.busy = false; row.can_retry = false; row.note = view.note; }
2627
- if (row.not_checked?.length) {
2628
- const unchecked = new Set(row.not_checked.map(item=>item.criterion_id));
2629
- 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) {
2630
2966
  row.criteria = {passed:Array.isArray(results) ? results.filter(item=>item.status==='passed'&&!unchecked.has(item.criterion_id)).length : 0,total:row.criteria_total};
2631
2967
  }
2968
+ row.own_criteria = row.criteria ? { ...row.criteria } : null;
2632
2969
  incompleteCriteria(row);
2970
+ if (Array.isArray(context?.rows) && context.rows.includes(row)) reconcileStoryCriteria(context.rows, context);
2633
2971
  if (row.state === 'refused') addHints(row, context.root, context.visible);
2634
2972
  if (ENDED.has(row.state) && row.sent_at && !row.ended_at && !context.reading) row.ended_at = context.ports.now();
2635
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
+ }
2636
2982
  }
2637
2983
 
2638
2984
  function nativeSourceIdentity(context, rows) {
@@ -2643,6 +2989,9 @@ function nativeSourceIdentity(context, rows) {
2643
2989
  }
2644
2990
 
2645
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]);
2646
2995
  function localLayoutResult(batch, summary) {
2647
2996
  const keys = (value, names) => value && typeof value === 'object' && !Array.isArray(value)
2648
2997
  && isDeepStrictEqual(Object.keys(value).sort(), names.split(' ').sort());
@@ -2659,7 +3008,7 @@ function localLayoutResult(batch, summary) {
2659
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'))
2660
3009
  || !Array.isArray(batch.rows) || batch.rows.length || !keys(batch.lint, 'state lint_state reason request_ids')
2661
3010
  || batch.lint.state !== 'partial' || batch.lint.lint_state !== 'partial'
2662
- || !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)
2663
3012
  || !Array.isArray(batch.lint.request_ids) || batch.lint.request_ids.length) return null;
2664
3013
  const result = {batch:batch.batch,repo:batch.root,exit_code:batch.exit_code,state:'partial',lint_state:'partial',reason:batch.lint.reason,
2665
3014
  local_only:true,local_scope:batch.local_scope,summary_line:batch.summary_line,warnings:batch.warnings,problems:batch.problems,rows:[],report_url:null};
@@ -2678,7 +3027,7 @@ async function saveLocalLayout(context, {root, tests, prompts, warnings, problem
2678
3027
  try {
2679
3028
  const record = {version:1,batch,root,created_at:new Date(now).toISOString(),intent:'lint-only',local_only:true,source_sha256:null,
2680
3029
  local_scope:{tests:[...new Set(tests)].sort(),prompts:[...new Set(prompts)].sort()},summary_line:summary,exit_code:problems.length ? 4 : 0,
2681
- 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:[]}};
2682
3031
  const projection = localLayoutResult(record,null);
2683
3032
  if (!projection) throw new Error('Local lint record cannot satisfy the saved result contract, including safe inspected scope.');
2684
3033
  const result = {...projection,exit_code:record.exit_code,summary_line:record.summary_line};
@@ -2711,12 +3060,14 @@ function batchRecord(context) {
2711
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,
2712
3061
  ...(context.liveLocal || context.liveLocalSaved ? {live_local:true} : {}),
2713
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 } : {}),
2714
3064
  ...(context.singleAttempt ? {single_attempt:true} : {}), ...(context.maxTotalCalls != null ? {max_total_calls:context.maxTotalCalls} : {}),
2715
3065
  ...(context.checkOptions ? {check_options:context.checkOptions} : {}),
2716
3066
  source_selection: context.sourceSelection ?? {tests:sentTests(rows),exclude_fixture_projects:context.excludeFixtureProjects === true},
2717
3067
  native_source: context.nativeSource ?? null,
2718
3068
  ...(context.localOnly ? {local_only:true} : {}),
2719
3069
  ...(context.allowMissingInterfaces ? {lazy_interfaces:true} : {}),
3070
+ ...(context.reservationsReconciledAt ? {reservations_reconciled_at:context.reservationsReconciledAt} : {}),
2720
3071
  exclude_fixture_projects: context.excludeFixtureProjects === true,
2721
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,
2722
3073
  contract_snapshots: capture.stories,
@@ -2726,12 +3077,13 @@ function batchRecord(context) {
2726
3077
  ...(row.sample_divergence ? {sample_divergence:row.sample_divergence} : {}),
2727
3078
  ...(row.diagnostic || row.diagnostic_subset === true ? { ...(row.diagnostic ? {diagnostic:true} : {}), diagnostic_subset:true, selected_steps:row.selected_steps ?? [] } : {}),
2728
3079
  ...(!row.request_ids.length && Object.hasOwn(row, 'calls') ? { calls: row.calls } : {}),
2729
- ...(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,
2730
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,
2731
3082
  reservation: row.reservation ?? null, restart_used: !!row.restart_used,
2732
3083
  busy: !!row.busy, can_retry: !!row.can_retry, eligible: !!row.eligible, retry_at: row.retry_at ?? null,
2733
3084
  ...(row.known_calls !== undefined ? { known_calls: row.known_calls } : {}), ...(row.unknown_calls !== undefined ? { unknown_calls: row.unknown_calls } : {}),
2734
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 } : {}),
2735
3087
  busy_request_id: row.busy_request_id ?? null, busy_observed_at: row.busy_observed_at ?? null, capacity_until: row.capacity_until ?? null,
2736
3088
  engine_sha: row.engine_sha ?? null, requested_model: row.requested_model ?? null, cache_identity: row.cache_identity ?? null,
2737
3089
  checks: row.checks ?? null, criteria: row.criteria ?? null, failed_checks: (row.failed_checks ?? []).map(({ normal_result, ...check }) => check),
@@ -2803,10 +3155,69 @@ function adoptClaims(context, row) {
2803
3155
  }
2804
3156
  }
2805
3157
  }
2806
- 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 } = {}) {
2807
3217
  const empty = { count: 0, reserved_calls: 0, batches: [] };
2808
3218
  try {
2809
- 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);
2810
3221
  let names;
2811
3222
  try { names = readdirSync(dir); } catch { return empty; }
2812
3223
  let count = 0, reserved_calls = 0;
@@ -2819,11 +3230,17 @@ function readUnresolvedPriorReservations(root, env, excludeBatch = null) {
2819
3230
  if (!isObject(saved) || saved.intent !== 'check' || typeof saved.root !== 'string' || realish(saved.root) !== wanted || !Array.isArray(saved.rows)) continue;
2820
3231
  let batchHasUnresolved = false;
2821
3232
  for (const row of saved.rows) {
3233
+ if (rowReservationCleared(row)) continue;
2822
3234
  const ids = Array.isArray(row?.request_ids) ? row.request_ids : [];
2823
3235
  if (!ids.length) continue;
2824
3236
  const state = row.recovery_state ?? row.state;
2825
3237
  const openOrUnknown = ['sending', 'queued', 'running', 'unknown'].includes(state) || row.calls === 'unknown' || row.accounting_complete === false;
2826
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
+ }
2827
3244
  const key = typeof row.test === 'string' ? createHash('sha256').update(row.test).digest('hex') : null;
2828
3245
  let cap = 0;
2829
3246
  for (let attempt = 0; attempt < ids.length; attempt++) {
@@ -2893,7 +3310,8 @@ function budgetRowsForContext(context, excludePendingRow = null) {
2893
3310
  }
2894
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 };
2895
3312
  const isLatest = index === ids.length - 1;
2896
- 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);
2897
3315
  const terminalReceipt = latest && sameJob(latest, id, 'check') && accountingEnd(latest, id);
2898
3316
  const unknownWithoutExplicitProof = latest?.state === 'unknown'
2899
3317
  && ![latest, latest?.usage, latest?.result, latest?.report, latest?.result?.report].some(s => isObject(s) && s.accounting_complete === true);
@@ -2943,11 +3361,30 @@ function applyBudgetDecisionStop(context, row, decision) {
2943
3361
  saveBatch(context);
2944
3362
  }
2945
3363
  function markDeadline(context, rows) {
2946
- if (context.interrupted || !Number.isFinite(context.deadline) || context.ports.now() < context.deadline) return;
2947
- for (const row of rows) if (!row.time_limit && (['ready', 'waiting', 'sending', 'queued', 'running'].includes(row.state)
2948
- || row.state === 'unknown' && row.lost || heldForLint(row) || row.busy && row.can_retry)) {
2949
- row.note = { code: context.timeoutMin && !context.agentLimit ? 'timeout-flag' : 'deadline',
2950
- 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
+ }
2951
3388
  }
2952
3389
  }
2953
3390
 
@@ -2960,6 +3397,7 @@ function saveBatch(context) {
2960
3397
  if (!row.busy && ['unknown', 'queued', 'running', 'sending'].includes(row.state) && answer && sameJob(answer, id, 'check')
2961
3398
  && ['passed', 'failed', 'refused'].includes(answer.state) && checkCapacity(answer) === null) applyAnswer(row, answer, context);
2962
3399
  }
3400
+ reconcileStoryCriteria(context.rows, context);
2963
3401
  context.store.write(join(context.folder, 'batch.json'), batchRecord(context));
2964
3402
  }
2965
3403
  function saveAnswerAt(store, folder, id, json) {
@@ -2986,7 +3424,18 @@ async function postJob(context, path, command, request, row, timeoutMs, deadline
2986
3424
  if (row) delete row.prior_restart_snapshot; // Dispatch is now uncertain; never roll it back.
2987
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'; }
2988
3426
  saveBatch(context);
2989
- 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
+ );
2990
3439
  const verdict = judgePost(reply, id, command, context.secrets);
2991
3440
  verdict.observed_at = context.ports.now();
2992
3441
  if (row && verdict.answer && ['queued', 'running', 'passed', 'failed'].includes(outcomeFor(verdict.answer, { kind: 'check' }).state))
@@ -3002,16 +3451,20 @@ async function postJob(context, path, command, request, row, timeoutMs, deadline
3002
3451
 
3003
3452
  // POST one check and fold the answer into its row.
3004
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);
3005
3458
  row.admitting = true;
3006
- try { await sendCheckAttempt(context, row); }
3459
+ try { await sendCheckAttempt(context, row, deadline); }
3007
3460
  finally {
3008
3461
  context.preparingDispatches?.delete(row);
3009
- 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);
3010
3463
  row.budget_in_flight = 0; row.admitting = false;
3011
3464
  }
3012
3465
  }
3013
- async function sendCheckAttempt(context, row) {
3014
- 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;
3015
3468
  if (context.checkOptions && context.checkOptions.samples > row.max_calls) throw new Stop(2, 'samples exceeds this test’s total max_calls allowance.');
3016
3469
  // Recheck the saved raw cohort immediately before any capacity-driven new ID.
3017
3470
  // The one structured restart replacement has its own durable fuse and remains allowed.
@@ -3019,7 +3472,7 @@ async function sendCheckAttempt(context, row) {
3019
3472
  markCapacityUnknown(context, row);
3020
3473
  return;
3021
3474
  }
3022
- 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;
3023
3476
  const candidateForRow = () => ({
3024
3477
  test: row.test,
3025
3478
  kind: row.restart_pending && !row.transient_pending ? 'restart-replacement' : 'initial',
@@ -3039,7 +3492,7 @@ async function sendCheckAttempt(context, row) {
3039
3492
  row.awaiting_budget = false;
3040
3493
  row.budget_in_flight = preDecision.effective_max_calls;
3041
3494
  const attempt = row.request_ids.length, previousCalls = row.restart_used || row.restart_pending ? accumulatedCalls(context, row) : 0;
3042
- if (!await admission(context, 'check', row)) {
3495
+ if (!await admission(context, 'check', row, deadline)) {
3043
3496
  if (context.interrupted && interruptedAdmissions.has(row)) Object.assign(row, { state: 'not_run', calls: previousCalls, phase: 'local', note: { code: null, message: 'Stopped before sending.' } });
3044
3497
  return;
3045
3498
  }
@@ -3052,7 +3505,7 @@ async function sendCheckAttempt(context, row) {
3052
3505
  }
3053
3506
  adoptClaims(context, row);
3054
3507
  if (row.request_ids.length !== attempt) delete row.prior_restart_snapshot;
3055
- 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) {
3056
3509
  await finishReservation(context, row, { state: 'not_run' });
3057
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.' } });
3058
3511
  return;
@@ -3118,7 +3571,7 @@ async function sendCheckAttempt(context, row) {
3118
3571
  try { writeSync(fd, JSON.stringify(dispatchClaim)); }
3119
3572
  finally { closeSync(fd); }
3120
3573
  (context.preparingDispatches ??= new WeakMap()).set(row, dispatchClaim);
3121
- if (context.interrupted || context.ports.now() >= context.deadline) {
3574
+ if (context.interrupted || context.ports.now() >= deadline) {
3122
3575
  preserveUnsentReplacement(context, row, path);
3123
3576
  await finishReservation(context, row, { state: 'not_run' });
3124
3577
  adoptClaims(context, row);
@@ -3139,7 +3592,7 @@ async function sendCheckAttempt(context, row) {
3139
3592
  ...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}),
3140
3593
  ...sourceProvenance(context) };
3141
3594
  let verdict;
3142
- 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); }
3143
3596
  catch (error) {
3144
3597
  // Registration may throw before postJob starts dispatch. Keep the original
3145
3598
  // receipt while this invocation can still prove its exact claim was unsent.
@@ -3159,15 +3612,18 @@ async function sendCheckAttempt(context, row) {
3159
3612
  if (row.request_ids.length > 1 && !capacityRetryAllowed(context, row)) markCapacityUnknown(context, row);
3160
3613
  else markBusy(context, row, verdict.wait, verdict.observed_at);
3161
3614
  }
3162
- 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
+ }
3163
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; }
3164
3620
  else if (verdict.kind === 'refused') Object.assign(row, { state: 'refused', refusals: [verdict.refusal] });
3165
3621
  // An explicit caller deadline also bounds recovery of a lost POST answer.
3166
3622
  else {
3623
+ const readUntil = Number.isFinite(deadline) ? deadline : context.ports.now() + LOST_READ_MS;
3167
3624
  if (verdict.capacity_uncertain) markCapacityUnknown(context, row);
3168
- else Object.assign(row, { state: 'unknown', why: verdict.why, lost: true, read_until: Number.isFinite(context.deadline)
3169
- ? context.deadline : context.ports.now() + LOST_READ_MS });
3170
- 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;
3171
3627
  }
3172
3628
  }
3173
3629
 
@@ -3182,10 +3638,12 @@ function sourceProvenance(context, capture = context?.capture) {
3182
3638
 
3183
3639
  // GET one open row once.
3184
3640
  async function readRow(context, row, deadline = Infinity) {
3185
- 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);
3186
3643
  if (!id || context.interrupted || context.ports.now() >= end) return;
3187
3644
  const verdict = judgeGet(await context.runtime.get(id, Math.max(1, Math.min(GET_MS, (end ?? Infinity) - context.ports.now()))), id, 'check');
3188
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');
3189
3647
  // A network problem while reading says so once; pdd keeps reading the same IDs.
3190
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.`);
3191
3649
  if (verdict.kind !== 'again') context.readTrouble = false; else if (verdict.why) context.readTrouble = true;
@@ -3281,9 +3739,11 @@ function readRecentLint(context) {
3281
3739
  // Every lint asks for complete per-test verdicts: only they can admit a test.
3282
3740
  async function runLint(context) {
3283
3741
  const agent = context.agentLimit ?? !context.ports.interactive;
3284
- 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
3285
3744
  ? context.timeoutMin ? context.startedAt + Math.min(context.timeoutMin * 60_000, context.ports.interactive ? Infinity : AGENT_WAIT_MIN * 60_000) : Infinity
3286
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);
3287
3747
  const tick = progressTicker(context.ports.stderr, context.ports.now);
3288
3748
  let paused = false;
3289
3749
  const stopped = () => ({ kind: 'not_run', note: { code: 'interrupted', message: paused ? stoppedPause(context, context.lint, 'lint')
@@ -3291,9 +3751,10 @@ async function runLint(context) {
3291
3751
  const busy = () => {
3292
3752
  if (context.interrupted) return stopped();
3293
3753
  const ended = context.ports.now() >= lintEnd;
3754
+ const explicitBatch = ended && context.explicitBatchTimeout && lintEnd === batchLintCap;
3294
3755
  const explicit = ended && context.explicitTimeout && lintEnd === context.deadline;
3295
- const note = { code: ended ? explicit ? 'timeout-flag' : 'deadline' : 'lint-busy',
3296
- 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.` };
3297
3758
  Object.assign(context.lint, { state: 'not_run', note });
3298
3759
  return { kind: 'not_run', note };
3299
3760
  };
@@ -3438,7 +3899,8 @@ async function checkBatch(context, rows, priorLint = null) {
3438
3899
  const lint = priorLint ?? await runLint(context);
3439
3900
  if (context.intent === 'check' && !context.checkDeadlineStarted) {
3440
3901
  context.checkDeadlineStarted = true;
3441
- 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;
3442
3904
  }
3443
3905
  context.lastCheckLint = lint;
3444
3906
  context.lint.state = lint.answer?.state ?? lint.kind;
@@ -3479,18 +3941,30 @@ async function runScheduledChecks(context, rows, toSend) {
3479
3941
  // Saved live-local observations may poll original IDs, but cannot admit work.
3480
3942
  if (context.liveLocalSaved) toSend = [];
3481
3943
  const { ports } = context;
3482
- context.checkWindow ??= localLimit(context);
3944
+ ensureConcurrencyState(context);
3483
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
+ }
3484
3954
  const pendingSends = new Map(), uploads = uploadLimit(context);
3485
3955
  // Refill on a POST's settlement even while the polling loop awaits GETs.
3486
3956
  // Waiting rows stay outside admission and dispatch-claim allocation.
3487
3957
  const pumpSends = () => {
3488
- if (context.liveLocalSaved || context.interrupted || context.readStop || context.stopped || context.sendError || ports.now() >= context.deadline) return;
3489
- 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;
3490
3961
  const available = Math.max(0, Math.min(uploads - pendingSends.size, context.checkWindow - active - pendingSends.size));
3491
3962
  const eligible = toSend.filter(row => !pendingSends.has(row) && !row.awaiting_budget && ['ready', 'waiting'].includes(row.state)
3492
- && (!row.retry_at || ports.now() >= row.retry_at));
3963
+ && !rowExpired(context, row, now) && (!row.retry_at || now >= row.retry_at));
3493
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
+ }
3494
3968
  const pending = sendCheck(context, row).catch(error => { context.sendError ??= error; }).finally(() => {
3495
3969
  pendingSends.delete(row);
3496
3970
  if (!row.awaiting_budget) {
@@ -3504,7 +3978,12 @@ async function runScheduledChecks(context, rows, toSend) {
3504
3978
  let waitingShown = -1;
3505
3979
  const progress = context.checkProgress ??= { startedAt: ports.now(), shownAt: ports.now() };
3506
3980
  const pollStartedAt = ports.now();
3507
- const readable = row => isOpen(row) && ports.now() < Math.min(context.deadline, row.lost ? row.read_until ?? context.deadline : context.deadline);
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
+ };
3508
3987
  const sseEnabled = !ports.pollMsExplicit && Boolean(context.serverFeatures?.includes('sse-stream-v1'));
3509
3988
  const activeStreams = new Map();
3510
3989
  let wakeResolve = null;
@@ -3517,7 +3996,16 @@ async function runScheduledChecks(context, rows, toSend) {
3517
3996
  : typeof p.step === 'string' && p.step ? p.step : stage;
3518
3997
  return `${row.test}: ${stepPart}`;
3519
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
+ };
3520
4007
  const syncRowStreams = () => {
4008
+ abortExpiredStreams();
3521
4009
  if (!sseEnabled || context.interrupted || context.readStop) return;
3522
4010
  for (const row of rows.filter(readable)) {
3523
4011
  const id = row.request_ids.at(-1);
@@ -3529,7 +4017,8 @@ async function runScheduledChecks(context, rows, toSend) {
3529
4017
  const controller = new AbortController();
3530
4018
  const onSignal = () => controller.abort();
3531
4019
  context.signal?.addEventListener('abort', onSignal, { once: true });
3532
- const end = Math.min(context.deadline, row.lost ? row.read_until ?? context.deadline : context.deadline);
4020
+ const rowEnd = rowDeadline(context, row);
4021
+ const end = Math.min(rowEnd, row.lost ? row.read_until ?? rowEnd : rowEnd);
3533
4022
  let lastStageKey = '';
3534
4023
  const entry = { id, controller };
3535
4024
  activeStreams.set(row, entry);
@@ -3575,9 +4064,11 @@ async function runScheduledChecks(context, rows, toSend) {
3575
4064
  };
3576
4065
  try {
3577
4066
  while (!context.interrupted && !context.readStop) {
3578
- // Never count an uncertain dispatched job as a free slot, even if it cannot currently be read.
3579
- const active = rows.filter(occupiesSlot).length;
3580
- 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) {
3581
4072
  pumpSends();
3582
4073
  // Admission can wait while previously dispatched rows continue to be read.
3583
4074
  if (!active && pendingSends.size) await Promise.race(pendingSends.values());
@@ -3585,7 +4076,7 @@ async function runScheduledChecks(context, rows, toSend) {
3585
4076
  saveBatch(context);
3586
4077
  }
3587
4078
  if (context.blocked && !rows.some(isOpen)) throw new Stop(5, context.blocked);
3588
- const waiting = toSend.filter(row => row.state === 'waiting');
4079
+ const waiting = toSend.filter(row => row.state === 'waiting' && !rowExpired(context, row));
3589
4080
  if (waiting.length !== waitingShown) {
3590
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.`);
3591
4082
  waitingShown = waiting.length;
@@ -3594,14 +4085,25 @@ async function runScheduledChecks(context, rows, toSend) {
3594
4085
  const earlyRestarts = await recoverRestarts(context);
3595
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);
3596
4087
  if (earlyRestarts.length) { for (const item of toSend) item.awaiting_budget = false; pumpSends(); }
3597
- const pending = toSend.some(row => ['ready', 'waiting'].includes(row.state));
3598
- if (pending && active >= context.checkWindow && !rows.some(readable)) break;
3599
- if ((!pending || context.stopped || ports.now() >= context.deadline) && !rows.some(readable) && !pendingSends.size) break;
3600
- if (ports.now() - progress.shownAt >= PROGRESS_MS) { progress.shownAt = ports.now(); line(ports.stderr, progressLine(rows, progress.shownAt - progress.startedAt)); }
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)); }
3601
4094
  syncRowStreams();
3602
- const end = context.deadline;
3603
- const delay = ports.pollDelay(ports.now() - pollStartedAt);
3604
- const waitMs = Math.max(0, Math.min(activeStreams.size ? PROGRESS_MS : delay, end - ports.now()));
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));
3605
4107
  if (activeStreams.size) {
3606
4108
  const wake = new Promise(resolve => { wakeResolve = resolve; });
3607
4109
  await Promise.race([ports.sleep(waitMs, context.signal), wake]);
@@ -3624,15 +4126,16 @@ async function runScheduledChecks(context, rows, toSend) {
3624
4126
  }
3625
4127
  if (context.sendError) throw context.sendError;
3626
4128
  const stoppedEarly = context.interrupted || !!context.readStop;
3627
- context.timedOut ||= !stoppedEarly && ports.now() >= context.deadline && rows.some(isOpen);
4129
+ context.timedOut ||= !stoppedEarly && rows.some(row => isOpen(row) && rowExpired(context, row));
3628
4130
  for (const row of toSend) {
3629
4131
  restoreReplacement(row); // A budget-held replacement may never have reached sendCheck.
3630
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,
3631
4133
  phase: row.request_ids.length ? 'server' : 'local', note: { code: 'check-busy', message: context.interrupted && row.busy && row.request_ids.length
3632
4134
  ? stoppedPause(context, row, 'check') : row.request_ids.length
3633
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);
3634
4137
  if (row.state === 'unknown' && row.lost) row.why ??= stoppedEarly ? 'pdd stopped before it could read this run.'
3635
- : 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.';
3636
4139
  }
3637
4140
  }
3638
4141
 
@@ -3653,6 +4156,7 @@ function printResult(context, rows, extra = {}) {
3653
4156
  return printLintResult(context, rows, lintProblems(context, answer), context.warnings ?? [], answer);
3654
4157
  }
3655
4158
  markDeadline(context, rows);
4159
+ reconcileStoryCriteria(rows, context);
3656
4160
  rows = rows.map(row => heldForLint(row) && !row.dispatchIncomplete ? { ...row, calls: 0 } : row);
3657
4161
  const { ports } = context, exitCode = context.localOnly && context.checkPlan?.full && context.checkPlan.prerequisites.length ? 4
3658
4162
  : ports.exitCodeFor(rows, { interrupted: context.interrupted, lintUnknown: context.lintUnknown || context.lintPending });
@@ -3686,7 +4190,7 @@ function printResult(context, rows, extra = {}) {
3686
4190
  if (context.stopped && (!context.json || context.stopped.message === AUTH_TEXT)) line(ports.stderr, context.stopped.message);
3687
4191
  const scrub = text => (context.secrets ?? []).reduce((value, secret) => secret ? value.split(secret).join('[secret]') : value, text);
3688
4192
  if (context.json) line(ports.stdout, scrub(JSON.stringify(summary)));
3689
- 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,
3690
4194
  now: ports.now(), noFailed: context.noFailed, interrupted: context.interrupted || !!context.readStop, reading: !!context.reading, exitCode, secrets: context.secrets, ...extra }, ports)));
3691
4195
  if (!context.json && summary.report_url) line(ports.stdout, `Report: ${summary.report_url}`);
3692
4196
  if (!context.json) for (const value of checkPlanResultLines(summary.check_scope)) line(ports.stdout, scrub(value));
@@ -3814,7 +4318,7 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
3814
4318
  const activeLocalProblem = problem => localInterfaceProblem(problem) && !(allowMissingInterfaces && problem.code === 'interface-missing');
3815
4319
  context.coverage = bindingCoverage({ root, found, selected, includeRuntime:true, allowMissingInterfaces });
3816
4320
  // A test that the test name rule cannot use is refused here and never sent; the other tests are linted.
3817
- 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',
3818
4322
  refusals: [], request_ids: [], warnings: [], steps: Array.isArray(test.doc?.steps) ? test.doc.steps.filter(isObject) : [],
3819
4323
  app_maps: declaredMaps(test.doc),
3820
4324
  criterion_texts: Object.fromEntries((Array.isArray(test.doc?.criteria) ? test.doc.criteria : []).filter(isObject).map(item => [item.id, item.text])),
@@ -3886,7 +4390,12 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
3886
4390
  // Lint keeps engine validation ownership; only attach structural incomplete-coverage facts.
3887
4391
  for (const row of rows.filter(row => !row.unsent)) {
3888
4392
  const test = selected.find(test => test.path === row.test), checked = preflight({root,found,selected:[test],allowMissingInterfaces}).rows[0];
3889
- 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
+ });
3890
4399
  if (checked.refusals.some(item=>item.code==='unchecked-criteria')) Object.assign(row,
3891
4400
  {state:'refused',phase:'local',unsent:true,refusals:checked.refusals});
3892
4401
  }
@@ -3964,6 +4473,7 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
3964
4473
  : { state: outcome.state, refusals: outcome.refusals, ...(outcome.reason ? { note: { code: outcome.code || 'no-server-verdict', message: outcome.reason } } : {}) });
3965
4474
  incompleteCriteria(row);
3966
4475
  }
4476
+ reconcileStoryCriteria(rows, context);
3967
4477
  Object.assign(context.lint, { state: answer?.state ?? lint.kind, unknown: rows.some(row => row.state === 'unknown'), pending: false, public_result: resultOverall(rows) });
3968
4478
  saveBatch(context);
3969
4479
  return printLintResult(context, rows, problems, found.warnings, answer);
@@ -4000,7 +4510,7 @@ function printLintResult(context, rows, problems, warnings = [], answer = null)
4000
4510
  const matching = (listed ?? []).filter(item => item?.path === row.test);
4001
4511
  row.call_preflight = matching.length === 1 ? matching[0].call_preflight ?? null : null;
4002
4512
  }
4003
- rows.forEach(incompleteCriteria);
4513
+ reconcileStoryCriteria(rows, context);
4004
4514
  rows = [...rows.filter(row=>row.unsent),...rows.filter(row=>!row.unsent)];
4005
4515
  for (const row of rows) for (const problem of row.refusals ?? []) {
4006
4516
  // pdd's own per-test words stay on the row; every server or reached-prompt problem is listed once.
@@ -4134,6 +4644,7 @@ async function readUnsentLint(context, rows) {
4134
4644
  incompleteCriteria(row);
4135
4645
  if (!busy && outcome.state === 'unknown') context.lintUnknown = lint.unknown = true;
4136
4646
  }
4647
+ reconcileStoryCriteria(rows, context);
4137
4648
  lint.public_result = resultOverall([...judged.values()]);
4138
4649
  }
4139
4650
 
@@ -4230,8 +4741,12 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
4230
4741
  context.cacheReadInvocation = true;
4231
4742
  const { store, ports, root } = context;
4232
4743
  const progress = context.checkProgress ??= { startedAt: ports.now(), shownAt: ports.now() };
4233
- const timeout = options['--timeout'] === undefined ? quiet ? AGENT_WAIT_MIN : null : Number(options['--timeout']);
4234
- 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);
4235
4750
  context.timeoutMin = timeout; context.agentLimit = false;
4236
4751
  const name = batchWord ?? store.read(join(store.dir,'repos',`${store.repoKey(root)}.json`))?.last_batch;
4237
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.');
@@ -4272,7 +4787,7 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
4272
4787
  allowSavedLocalReadFallback: !quiet && isLocalSavedBatchRead(context, saved),
4273
4788
  });
4274
4789
  if (identity.login !== saved.login) throw new Stop(5, `These runs belong to ${saved.login}. Run: gh auth switch -u ${saved.login}`);
4275
- 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 ?? [],
4276
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) });
4277
4792
  runtimeOrigin({ PDD_RUNTIME_URL: saved.origin });
4278
4793
  context.auth = authSession({
@@ -4390,8 +4905,16 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
4390
4905
  }
4391
4906
  const continued = await continueHeld(context, candidates, saved) ?? [];
4392
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
+ }
4393
4913
  if (continued.length || replacements.length || !quiet && rows.some(isOpen)) {
4394
- if (continued.length) context.reading = false;
4914
+ if (continued.length) {
4915
+ context.reading = false;
4916
+ if (!quiet) context.deadline = context.batchDeadline;
4917
+ }
4395
4918
  await runScheduledChecks(context, rows, [...continued, ...replacements]);
4396
4919
  }
4397
4920
  context.savedTestCache = saved.test_cache;
@@ -4409,7 +4932,7 @@ async function recoverRestarts(context) {
4409
4932
  return !row.restart_used && !statOrNull(claimPath(context, row).replace(/\.0\.dispatch\.json$/, '.restart.json'))
4410
4933
  && !row.restart_pending && !row.admitting && !context.restartDecisions?.has(id) && sameJob(answer, id, 'check') && (restarted(answer) || transientDrop(answer));
4411
4934
  });
4412
- if (!eligible.length || context.interrupted || context.ports.now() >= context.deadline) return [];
4935
+ if (!eligible.length || context.interrupted || context.ports.now() >= batchDeadlineOf(context)) return [];
4413
4936
  if (context.singleAttempt) {
4414
4937
  context.restartDecisions ??= new Set();
4415
4938
  for (const row of eligible) {
@@ -4454,7 +4977,7 @@ async function recoverRestarts(context) {
4454
4977
  const drops = admitted.filter(row => transientDrop(context.store.read(join(context.folder, `${row.request_ids.at(-1)}.json`))));
4455
4978
  // Backoff precedes the source recapture, so edits during the wait cannot
4456
4979
  // authorize a replacement of the original selected source.
4457
- if (drops.length && !await waitBudget(context, 1000)) return [];
4980
+ if (drops.length && !await waitBudget(context, 1000, batchDeadlineOf(context))) return [];
4458
4981
  let capture;
4459
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 } : {}) }); }
4460
4983
  catch (error) {
@@ -4468,7 +4991,7 @@ async function recoverRestarts(context) {
4468
4991
  lintDiagnostics(context, lint, context.rows);
4469
4992
  const selected = [];
4470
4993
  for (const row of admitted) {
4471
- if (context.interrupted || context.ports.now() >= context.deadline || !validSavedCheck(row)) continue;
4994
+ if (context.interrupted || rowExpired(context, row) || !validSavedCheck(row)) continue;
4472
4995
  const transient = drops.includes(row);
4473
4996
  const decision = evaluateCheckBudget({
4474
4997
  max_total_calls: context.maxTotalCalls ?? null,
@@ -4496,8 +5019,12 @@ async function recoverRestarts(context) {
4496
5019
 
4497
5020
  async function runRetry(context, name, options) {
4498
5021
  const { ports } = context;
4499
- const timeout = options['--timeout'] === undefined ? AGENT_WAIT_MIN : Number(options['--timeout']);
4500
- 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);
4501
5028
  const rows = await runRead(context, name, true, options, true);
4502
5029
  if (context.localLayout) {
4503
5030
  line(ports.stderr,'For new evidence, run a fresh pdd lint --local.');
@@ -4505,7 +5032,7 @@ async function runRetry(context, name, options) {
4505
5032
  }
4506
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.');
4507
5034
  if (context.localOnly) return () => printResult(context, rows);
4508
- 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);
4509
5036
  const capture = Array.isArray(context.capture.sources) ? context.capture : context.ports.captureSource(context.root, { tests: sentTests(rows), appMap: null, excludeFixtureProjects: context.excludeFixtureProjects });
4510
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.');
4511
5038
  capture.stories = context.capture.stories;
@@ -4517,8 +5044,8 @@ async function runRetry(context, name, options) {
4517
5044
  const selected = retryable.filter(row => lintAdmits(lint, row, context.capture));
4518
5045
  if (retryable.length && !selected.length) throw new Stop(2, 'The saved lint cannot authorize recovery. Start a fresh selected pdd test.');
4519
5046
  if (selected.length) lintDiagnostics(context, lint, rows);
4520
- Object.assign(context, { capture, reading: false, timeoutMin: timeout });
4521
- 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'; }
4522
5049
  if (selected.length) line(ports.stderr, `Retrying ${selected.length} unstarted check${selected.length === 1 ? '' : 's'}…`);
4523
5050
  await runScheduledChecks(context, rows, selected);
4524
5051
  saveBatch(context);
@@ -4601,6 +5128,7 @@ async function refreshCheckBatches(context, identity, origin, id, answer) {
4601
5128
  if (sameJob(receipt, latest, 'check')) applyAnswer(row, receipt, projection);
4602
5129
  return row;
4603
5130
  });
5131
+ reconcileStoryCriteria(rows, projection);
4604
5132
  const cache = await openTestCache(projection, root, false);
4605
5133
  cache.tokens = new Map(saved.test_cache.tokens);
4606
5134
  await finishTestAttempts(cache, rows, capture);
@@ -4772,16 +5300,16 @@ async function closeLocalBridges(context) {
4772
5300
  // Its lifetime covers scheduler waits, recovery and every phase of a retry.
4773
5301
  async function withCheckRun(context, run) {
4774
5302
  let ownership;
4775
- context.postCheck = async (request, row, timeoutMs) => {
5303
+ context.postCheck = async (request, row, timeoutMs, deadline = rowDeadline(context, row)) => {
4776
5304
  if(context.liveLocal) {
4777
5305
  const bridge=await newLocalBridge(context,'check',request.requestId);
4778
5306
  request={...request,resource_mode:'live',resource_setup:bridge.resource_setup};
4779
- 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);
4780
5308
  if(verdict.kind==='accepted'&&!ENDED.has(verdict.answer?.state))await startLocalBridge(context,bridge,request.requestId);
4781
5309
  return verdict;
4782
5310
  }
4783
5311
  // Probes and diagnostic subsets own no ordinary pass generation or cache identity evidence.
4784
- 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);
4785
5313
  ownership ??= (async () => {
4786
5314
  if (!context.testCache) {
4787
5315
  const cache = context.testCache = await openTestCache(context, context.root, false);
@@ -4792,7 +5320,7 @@ async function withCheckRun(context, run) {
4792
5320
  if (!cache.disabled && !cache.mark) await cacheTransaction(cache, data => markTestAttempt(cache, data));
4793
5321
  })();
4794
5322
  await ownership;
4795
- return postJob(context, '/v1/check', 'check', request, row, timeoutMs, context.deadline);
5323
+ return postJob(context, '/v1/check', 'check', request, row, timeoutMs, deadline);
4796
5324
  };
4797
5325
  let result;
4798
5326
  try { result = await run(); }
@@ -4808,7 +5336,7 @@ async function withCheckRun(context, run) {
4808
5336
  // pdd test. Returns the exit code.
4809
5337
  export async function runCheck({ words = [], options = {}, cwd = process.cwd(), cache = false, client, workflow } = {}, givenPorts = {}) {
4810
5338
  const ports = withDefaults(givenPorts);
4811
- 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: [] };
4812
5340
  let release = () => {};
4813
5341
  try {
4814
5342
  context.liveLocal=liveLocalOptions(options,'check');
@@ -4818,13 +5346,13 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
4818
5346
  if (!context.checkOptions && options['--step'] !== undefined) {
4819
5347
  const values = Array.isArray(options['--step']) ? options['--step'] : [options['--step']];
4820
5348
  if (!values.length || values.some(value=>typeof value !== 'string' || !value.trim())) throw new Stop(2, '--step needs one or more nonblank step IDs.');
4821
- 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.');
4822
5350
  context.stepIds = [...new Set(values)]; context.cacheEnabled = false;
4823
5351
  }
4824
- 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))))
4825
- 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.');
4826
5354
  if(options['--journeys']!==undefined){
4827
- 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.');
4828
5356
  const {root,found}=localSetup(cwd,[],ports);
4829
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); }
4830
5358
  if(!words.length)throw new Stop(2,'No root product journeys found.');
@@ -4968,15 +5496,19 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
4968
5496
  const selectorInfo = selectorLintForPrompts({ root, visible: new Set(gitFiles(root)), paths: inspectedPrompts, workspace });
4969
5497
  context.selectorTableLines = selectorInfo.tableLines;
4970
5498
  const hygiene = lintLocalHygiene({ root, files, promptPaths, tests: selectedTests, workspace }, ports);
4971
- 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.`;
4972
5502
  const result = await saveLocalLayout(context,{root,tests,prompts:promptPaths ?? files.filter(path => path.endsWith('.prompt.md')),warnings,problems,summary});
4973
5503
  return printLocalLayout(context,result);
4974
5504
  } catch (error) { if (error?.unboundPort) throw error; throw new Stop(2, error.message); }
4975
5505
  }
4976
- const modes = ['--read', '--retry', '--files', '--explain-bindings', '--request', '--lint'].filter(name => options[name] !== undefined);
4977
- const others = Object.keys(options).filter(name => !modes.includes(name) && !(['--retry', '--read'].includes(modes[0]) && ['--json', '--details', '--timeout'].includes(name)) && !(name === '--json' && ['--request', '--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'));
4978
- 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)
4979
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);
4980
5512
  if (modes[0] === '--request') { release = interruptible(context); return await runRequest(context, options['--request'], cwd); }
4981
5513
  const root = repoRoot(cwd);
4982
5514
  if (modes[0] === '--explain-bindings') return runExplainBindings(cwd, words, options, ports);
@@ -5005,7 +5537,7 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
5005
5537
  coverage: { available: false, bound: null, total: null, modules: [] }, problems: [{ code: 'binding-invalid', path: 'pdd-bindings.json', message: error.message }], rows: [], warnings: [] }));
5006
5538
  else if (context.coverage && error.exitCode !== 5) {
5007
5539
  if (context.json) line(ports.stdout, JSON.stringify({ batch: context.batch ?? null, repo: context.root, exit_code: error.exitCode,
5008
- 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 }));
5009
5541
  else line(ports.stdout, coverageText(context.coverage));
5010
5542
  }
5011
5543
  return error.exitCode;
@@ -5544,6 +6076,8 @@ async function beginTestAttempts(cache, rows, capture, options, origin, force =
5544
6076
  if (!force && !reason && [undefined, '', '0', 'false'].includes(cache.context.ports.env.CI) && eligible && budgetAllows) {
5545
6077
  for (const row of own) {
5546
6078
  const { checks, criteria, criteria_total, draft } = pass.rows[row.test];
6079
+ delete row.not_checked;
6080
+ delete row.own_not_checked;
5547
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 });
5548
6082
  }
5549
6083
  continue;
@@ -5700,7 +6234,8 @@ async function runBatch(context, cwd, words, options, setRelease) {
5700
6234
  context.visible = found.visible; context.origin = origin; context.excludeFixtureProjects = words.length === 0;
5701
6235
  // Ordinary Check waits for completion in every shell unless a limit is explicit.
5702
6236
  context.agentLimit = false;
5703
- 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');
5704
6239
  let selected = select(found, normalized, root, ports);
5705
6240
  const diagnostic = context.stepIds?.length > 0;
5706
6241
  const preliminary = diagnostic ? preflight({root,found,selected,allowMissingInterfaces:true,stepIds:context.stepIds}) : null;
@@ -5750,7 +6285,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5750
6285
  discoveryChanged ||= !isDeepStrictEqual(initialDiscovery,discoveryScope(current.found));
5751
6286
  return current;
5752
6287
  };
5753
- const priorReservations = readUnresolvedPriorReservations(root, ports.env, context.batch ?? null);
6288
+ const priorReservations = readUnresolvedPriorReservations(root, ports.env, context.batch ?? null, { now: ports.now() });
5754
6289
  const planPolicyOptions = {
5755
6290
  maxCalls: options['--max-calls'] !== undefined ? Number(options['--max-calls']) : null,
5756
6291
  maxTotalCalls: context.maxTotalCalls ?? null,
@@ -5821,6 +6356,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5821
6356
  if (test?.error) row.unsent = true;
5822
6357
  row.criterion_texts = Object.fromEntries([...(Array.isArray(test?.doc?.criteria) ? test.doc.criteria : []).filter(isObject).map(item => [item.id, item.text]),
5823
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 }));
5824
6360
  }
5825
6361
  if (options['--max-calls'] !== undefined) for (const row of rows) row.max_calls = Number(options['--max-calls']);
5826
6362
  if (context.checkOptions) for (const row of rows) {
@@ -5903,7 +6439,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5903
6439
  if(context.liveLocal)context.localOwner??=identity.login;
5904
6440
  const startedAt = ports.now(), batch = batchId(startedAt, ports.randomUUID);
5905
6441
  const head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
5906
- Object.assign(context, { capture, identity, batch, startedAt, deadline: Infinity, rows,
6442
+ Object.assign(context, { capture, identity, batch, startedAt, deadline: Infinity, batchDeadline: Infinity, rows,
5907
6443
  intent: 'check', head: capture.source_commit ?? (head.status === 0 ? head.stdout.trim() : null), secrets: [identity.token], lint: { request_ids: [], state: null } });
5908
6444
  context.folder = context.store.folder('batches', batch);
5909
6445
  setRelease(interruptible(context));
@@ -5927,7 +6463,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5927
6463
  for (const row of rerun) {
5928
6464
  const original = originals.get(row.test), storyPath = row.story_path, texts = row.criterion_texts, appMaps = row.app_maps;
5929
6465
  for (const key of Object.keys(row)) delete row[key];
5930
- 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' });
5931
6467
  if (options['--max-calls'] !== undefined) row.max_calls = Number(options['--max-calls']);
5932
6468
  }
5933
6469
  await beginTestAttempts(cache, rerun, capture, options, origin, true);
@@ -6055,7 +6591,11 @@ function simulationSelection(root, found, words, appMap, options, ports) {
6055
6591
  const hasHttp = rows.some(row => row.http.size);
6056
6592
  const screens = appMap ? JSON.parse(readFileSync(join(root, appMap), 'utf8')).screens : [];
6057
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)));
6058
- 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;
6059
6599
  const page = options['--page'] || options['--agent'] !== undefined || options['--tab'] !== undefined;
6060
6600
  const forcedCli = options['--cli'] || options['--shell'];
6061
6601
  if (forcedCli && cli.size !== 1) {
@@ -6079,7 +6619,7 @@ function simulationSelection(root, found, words, appMap, options, ports) {
6079
6619
  // The seed establishes saved-case/session identity, not a preferred view.
6080
6620
  if (cli.size === 1) seed = rows.find(row => row.cli.size).test;
6081
6621
  else if (hasHttp) seed = rows.find(row => row.http.size).test;
6082
- 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');
6083
6623
  return { test: seed, selected, tab, typed: typed && tab === 'call' && options['--serve'] === undefined };
6084
6624
  }
6085
6625
 
@@ -6194,24 +6734,29 @@ async function stopTry(context, record) {
6194
6734
  function trySourceSelection(record, path) {
6195
6735
  const scope = record.simulation_scope;
6196
6736
  if (scope === undefined) return { tests: [path] };
6197
- if (!isObject(scope) || !Array.isArray(scope.tests) || !scope.tests.length
6198
- || !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)
6199
6742
  || !(scope.appMap === null || typeof scope.appMap === 'string')) {
6200
6743
  throw new Stop(4, 'The saved whole-project source scope is unavailable. Run pdd simulate --new.');
6201
6744
  }
6202
- return { tests: scope.tests, appMap: scope.appMap };
6745
+ return { tests: entries, appMap: scope.appMap };
6203
6746
  }
6204
6747
 
6205
6748
  function tryPromptProblem(root, found, test, record, capture, ports) {
6206
6749
  const hashes=record.prompt_hashes;
6207
- 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));
6208
6751
  if (!capture && isObject(hashes)) {
6209
6752
  const files=sourceFilePort(root,found.visible), sources=[], references=[], raw_prompt_hashes={};
6210
6753
  for (const path of Object.keys(hashes)) {
6211
- const prepared=readPrompt(root,found.visible,path);
6754
+ const prepared=readPrompt(root,found.visible,path,found.workspace);
6212
6755
  if (!prepared.text) return 'A prompt changed or this Try has no source record.';
6213
- sources.push({path,bytes:Buffer.from(executableInterfaceText(prepared.text),'utf8')});references.push(...(prepared.references??[]));
6214
- 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'));
6215
6760
  }
6216
6761
  capture={sources,references,raw_prompt_hashes};
6217
6762
  }
@@ -6219,7 +6764,10 @@ function tryPromptProblem(root, found, test, record, capture, ports) {
6219
6764
  const scope = record.simulation_scope, map = capture.sources.find(file => file.path === scope.appMap);
6220
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.';
6221
6766
  }
6222
- 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
6223
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.';
6224
6772
  const current=Object.fromEntries(capture.sources.filter(file=>file.path.endsWith('.prompt.md')).map(file=>[file.path,sha256(file.bytes)]));
6225
6773
  if (isObject(record.effective_prompt_hashes) && Object.keys(hashes).every(path=>typeof record.effective_prompt_hashes[path]==='string')) {
@@ -6421,13 +6969,19 @@ function programSelection(cwd, word, ports, givenMap) {
6421
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.');
6422
6970
  return path;
6423
6971
  };
6424
- 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 };
6425
6977
  }
6426
6978
  async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
6427
6979
  const { ports } = context, selected = programSelection(cwd, word, ports, options['--app-map']), { root, entry } = selected;
6428
6980
  if (options['--data'] !== undefined && options['--fresh'] !== undefined) throw new Stop(2, 'Choose --data FILE or --fresh, not both.');
6429
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.');
6430
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;
6431
6985
  const store = stateFor(ports.env, root), files = programFiles(root, entry, store); let seeded = null;
6432
6986
  if (options['--data'] !== undefined) {
6433
6987
  if (typeof options['--data'] !== 'string') throw new Stop(2, '--data needs a JSON file.');
@@ -6441,12 +6995,13 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
6441
6995
  throw new Stop(2, 'The live program keeps its pinned app map. Use --new to select a different app map.');
6442
6996
  const appMap = !selected.screen && !options['--new'] && record?.app_map
6443
6997
  ? selected.validatePinnedMap(record.app_map) : selected.appMap;
6998
+ const requestedTab = options['--tab'] ?? (selected.screen || selected.plainUiPrompt || appMap ? 'screen' : 'call');
6444
6999
  const capture = ports.captureSource(root, { tests: [entry], appMap });
6445
7000
  const origin = runtimeOrigin(ports.env), identity = signIn(ports.gh, store, ports);
6446
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.');
6447
7002
  Object.assign(context, { root, cwd, origin, identity, store, capture, visible: selected.visible, appMap, programEntry: entry,
6448
7003
  programTarget: relative(root, resolve(cwd, word)).split(sep).join('/'), programFiles: files,
6449
- 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 });
6450
7005
  releaseInterrupt = interruptible(context);
6451
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.') });
6452
7007
  context.runtime = new Runtime({ origin, token: identity.token, ports, signal: context.signal, auth: context.auth, programJson: true });
@@ -6481,10 +7036,11 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
6481
7036
  const request = { requestId: ports.randomUUID(), source_sha256: capture.sha256, entry,
6482
7037
  initial_world: seeded?.initial_world ?? (options['--fresh'] ? {} : files.read()), ...(seeded?.simulation ? { simulation: seeded.simulation } : {}),
6483
7038
  ...(options['--fresh'] === true ? { fresh: true } : {}),
6484
- ...(appMap ? { app_map: appMap } : {}), tab: selected.screen ? 'screen' : 'call', max_calls: requestedBudget ?? 300, ...sourceProvenance(context, capture) };
7039
+ ...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}),
7040
+ ...(appMap ? { app_map: appMap } : {}), tab: requestedTab, max_calls: requestedBudget ?? 300, ...sourceProvenance(context, capture) };
6485
7041
  setup.request_ids.push(request.requestId);
6486
7042
  if (await recordRuntimeRequest(setup.reservation, request.requestId, slotPorts(context)) === false || context.interrupted) throw new Stop(3, 'Stopped before sending the program.');
6487
- 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,
6488
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)])),
6489
7045
  app_map: appMap, app_map_hash: appMap ? sha256(capture.sources.find(file => file.path === appMap).bytes) : null };
6490
7046
  files.set(record); store.posted(context.folder, record.id);
@@ -6573,9 +7129,16 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
6573
7129
  } finally { done(); }
6574
7130
  };
6575
7131
  unlock(); released = true;
6576
- 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 });
6577
- line(ports.stdout, `Program ready: ${link}`);
6578
- 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);
6579
7142
  try {
6580
7143
  do {
6581
7144
  const done = files.lock();
@@ -6868,7 +7431,7 @@ async function runDirectProgram({words,options,cwd}, ports) {
6868
7431
  function shouldUseDirectProgram(words, options, cwd) {
6869
7432
  if (typeof words[0] !== 'string' || !words[0].endsWith('.prompt.md')) return false;
6870
7433
  if (words.length > 1 || ['--show-data', '-q', '--quiet'].some(key => options[key] !== undefined)) return true;
6871
- 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;
6872
7435
  try {
6873
7436
  const text = readFileSync(resolve(cwd, words[0]), 'utf8');
6874
7437
  return /\b(?:cli|argv|stdin|stdout|exit_code|command-line)\b/i.test(text);
@@ -7038,7 +7601,7 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7038
7601
  if(options['--product']!==undefined&&!productMode || !productMode&&['--parts','--journey'].some(key=>options[key]!==undefined))throw new Stop(2,'--parts and --journey require --product.');
7039
7602
  if(productMode&&options['--app-map']!==undefined)throw new Stop(2,'--product builds its map; omit --app-map.');
7040
7603
  const requestedBudget = requestedCalls(options['--max-calls']);
7041
- 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 });
7042
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.');
7043
7606
  const doorModes = [options['--cli'] || options['--shell'], options['--serve'] !== undefined, options['--page'] || options['--tab'] !== undefined || options['--agent'] !== undefined, options['--save-last']].filter(Boolean);
7044
7607
  if (doorModes.length > 1 || (doorModes.length && options['--stop'])
@@ -7062,6 +7625,16 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7062
7625
  const origin = runtimeOrigin(ports.env);
7063
7626
  if (options['--stop']) return await stopByName(context, cwd, words, origin);
7064
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
+ }
7065
7638
  await prepareLiveManifest(context,options,root);
7066
7639
  const repoState = store.repo(root);
7067
7640
  if (!productMode && normalized.length && !options['--new']) {
@@ -7071,8 +7644,10 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7071
7644
  const productSetup = options['--product'] ? { parts: options['--parts']?.split(',').map(p => p.trim()) ?? null, journey: options['--journey'] ?? null } : null;
7072
7645
  const localSelected = productSetup ? [productTest(found, normalized, options['--journey'], root, ports)]
7073
7646
  : normalized.length ? [oneTest(found, normalized, root, ports)] : [...found.tests].sort((a, b) => a.path.localeCompare(b.path));
7074
- const allowMissingInterfaces = hasMissingPromptInterface(root, found, entryPaths(localSelected))
7075
- ? 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;
7076
7651
  const checked = preflight({ root, found, selected: localSelected, allowMissingInterfaces }), rows = localRows(checked.rows);
7077
7652
  for (const item of rows) item.app_maps = declaredMaps(localSelected.find(candidate => candidate.path === item.test)?.doc);
7078
7653
  const refused = rows.find(row => row.state === 'refused');
@@ -7251,7 +7826,8 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7251
7826
  await store.updateRepo(root, current => ({ ...current, tries: { ...current.tries, [test.path]: tryRecord } }));
7252
7827
  store.posted(context.folder, request.requestId);
7253
7828
  line(ports.stderr, `Starting your Try: sending ${capture.files.length} files, ${formatSize(capture.bytes)}${note ? ` ${note}` : ''}…`);
7254
- 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);
7255
7831
  verdict = judgePost(reply, request.requestId, 'try', context.secrets);
7256
7832
  if (verdict.maintenance) maintenanceNotice(context, verdict, reply);
7257
7833
  if (verdict.answer) { store.write(join(context.folder, `${request.requestId}.json`), verdict.answer); queueProgress(context, verdict.answer); await finishReservation(context, setup, verdict.answer); }
@@ -7322,18 +7898,48 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7322
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)))); }
7323
7899
  }
7324
7900
 
7325
- // 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).
7326
7902
  async function stopByName(context, cwd, words, origin) {
7327
- const { ports } = context, root = repoRoot(cwd), store = stateFor(ports.env, root), repoState = store.repo(root);
7328
- const entries = Object.entries(repoState.tries ?? {}), word = words[0]?.replace(/^\.\//, '');
7329
- const names = entries.map(([path, record]) => record.story ?? basename(path, '.json')).join(', ') || 'none';
7330
- const records = entries.map(([path, record]) => ({
7331
- id: String(record.id ?? ''),
7332
- test_path: path,
7333
- test_name: basename(path, '.json'),
7334
- story: String(record.story ?? basename(path, '.json')),
7335
- story_path: String(record.storyPath ?? ''),
7336
- }));
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
+ });
7337
7943
  let picked;
7338
7944
  try {
7339
7945
  picked = selectTryToStop({ ...(word !== undefined ? { selector: word } : {}), records });
@@ -7341,8 +7947,9 @@ async function stopByName(context, cwd, words, origin) {
7341
7947
  throw new Stop(2, word !== undefined ? `No open Try for "${cleanText(word)}". Open Try links: ${names}.`
7342
7948
  : entries.length ? `Name the Try to stop. Open Try links: ${names}.` : 'No open Try in this repository.');
7343
7949
  }
7344
- const [path, record] = entries.find(([candidatePath, candidate]) => candidatePath === picked.test_path && String(candidate.id ?? '') === picked.id);
7345
- 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;
7346
7953
  Object.assign(context, { root, store, origin });
7347
7954
  const identity = signIn(ports.gh, store, ports);
7348
7955
  context.secrets = [identity.token];
@@ -7357,7 +7964,12 @@ async function stopByName(context, cwd, words, origin) {
7357
7964
  context.runtime = new Runtime({ origin: record.origin ?? origin, token: identity.token, ports, auth: context.auth });
7358
7965
  line(ports.stderr, `Stopping the Try for "${title}"…`);
7359
7966
  await stopTry(context, record);
7360
- 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
+ }
7361
7973
  line(ports.stdout, `The Try link for "${title}" is stopped.`);
7362
7974
  return 0;
7363
7975
  }
@@ -7461,6 +8073,9 @@ const validSha256Hex = value => typeof value === 'string' && /^[0-9a-f]{64}$/i.t
7461
8073
  const validEngineHex = value => typeof value === 'string' && /^[0-9a-f]{8,40}$/i.test(value) ? value.toLowerCase() : null;
7462
8074
 
7463
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
+ }
7464
8079
  if (context.typedForm) line(context.ports.stderr, "This Story's operation takes typed input, so it opens on the Form tab.");
7465
8080
  const budget = Number.isSafeInteger(session?.max_calls) && session.max_calls > 0 && Number.isSafeInteger(session?.remaining_calls)
7466
8081
  && session.remaining_calls >= 0 && session.remaining_calls <= session.max_calls
@@ -8073,7 +8688,8 @@ async function doorWorldObservation(runtime,sessionId,report,actionId) {
8073
8688
  ?state.json.actions.find(action=>action.action_id===actionId):null;
8074
8689
  if(matched)observation={...observation,
8075
8690
  ...(Object.hasOwn(matched,'input_world')?{input_world:matched.input_world}:{}),
8076
- ...(Object.hasOwn(matched,'world')?{world:matched.world}:{})};
8691
+ ...(Object.hasOwn(matched,'world')?{world:matched.world}:{}),
8692
+ ...(isObject(matched.calls)?{calls:matched.calls}:{})};
8077
8693
  } catch { /* Observation is optional; the confirmed result remains confirmed. */ }
8078
8694
  return observation;
8079
8695
  }
@@ -8241,6 +8857,10 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
8241
8857
  const hasEmbeddedInputWorld = Object.hasOwn(answer.result ?? {}, 'input_world') || Object.hasOwn(rawReport ?? {}, 'input_world');
8242
8858
  const observation = !(hasEmbeddedWorld && hasEmbeddedInputWorld) && (typeof projected.action_id === 'string' || descriptor.directProgram)
8243
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;
8244
8864
  const confirmed = {
8245
8865
  id,
8246
8866
  actionId: projected.action_id,
@@ -8251,6 +8871,8 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
8251
8871
  callChain: rawReport?.call_chain,
8252
8872
  inputWorld: Object.hasOwn(answer.result ?? {}, 'input_world') ? answer.result.input_world : observation.input_world,
8253
8873
  world: hasEmbeddedWorld ? answer.result.world : observation.world,
8874
+ ...(recordedCalls !== undefined ? { calls: recordedCalls } : {}),
8875
+ ...(recordingAvailable !== undefined ? { recordingAvailable } : {}),
8254
8876
  };
8255
8877
  if (sourcePins && projected.outcome === 'result') await store.updateLastRun(root, current => current?.id !== id ? undefined : ({state:'confirmed',
8256
8878
  descriptor:{root,sessionId,origin,login,prompt,operation,...sourcePins},
@@ -8422,6 +9044,729 @@ export async function reconcileCheckReceipt({ cwd = process.cwd(), requestId, or
8422
9044
  });
8423
9045
  }
8424
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
+
8425
9770
  export async function readTryOwner({ cwd = process.cwd(), story, tryId } = {}, givenPorts = {}) {
8426
9771
  const ports = withDefaults(givenPorts), root = repoRoot(cwd), found = ports.findTests({ root }), store = stateFor(ports.env, root);
8427
9772
  const repo = store.repo(root);
@@ -8752,7 +10097,8 @@ export async function admitProgram(context, capture, { entry, appMap, initial_wo
8752
10097
  const registered = await recordRuntimeRequest(setup.reservation, id, slotPorts(context));
8753
10098
  if (registered === false || context.interrupted) { await finishReservation(context, setup, { state: 'not_run' }); throw problem('Stopped before program setup was sent.'); }
8754
10099
  store.posted(context.folder, id);
8755
- 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);
8756
10102
  const verdict = judgePost(reply, id, 'try', context.secrets);
8757
10103
  if (verdict.answer) store.write(join(context.folder, `${id}.json`), verdict.answer);
8758
10104
  if (verdict.kind === 'busy') {