@promptdriven/runtime-client 1.1.1 → 1.1.3

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';
@@ -12,25 +12,26 @@ import { bindingPlanLines, bindingRefusals } from './runtime-binding-plan.mjs';
12
12
  import { buildCheckPlan, checkPlanResults, checkPlanLines, checkPlanResultLines, selectCheckTests, baselineReport, evaluateCheckBudget } from './runtime-check-plan.mjs';
13
13
  import { projectCheckReconciliation } from './runtime-check-reconcile.mjs';
14
14
  import {loadRuntimeWorkspace,allowsRuntimePath,requireRuntimePath,RuntimeWorkspaceError} from './runtime-workspace.mjs';
15
- import { failedCheckCount, hasProgress, outcomeDone, outcomeFor, outcomeOverall, outcomeText, progressText, resultOutcome, resultOverall } from './runtime-outcome.mjs';
15
+ import { failedCheckCount, hasProgress, lintFailClosed, outcomeDone, outcomeFor, outcomeOverall, outcomeText, progressText, resultOutcome, resultOverall } from './runtime-outcome.mjs';
16
16
  import { acquireRuntimeSlot, recordRuntimeRequest, releaseRuntimeSlot, listRuntimeJobs } from './runtime-slots.mjs';
17
17
  import { bindingCoverage } from './runtime-bindings.mjs';
18
18
  import { spawn, spawnSync } from 'node:child_process';
19
19
  import { createHash, randomUUID } from 'node:crypto';
20
- import { chmodSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, readSync, renameSync, rmdirSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';
20
+ import { chmodSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, readSync, renameSync, rmSync, rmdirSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';
21
21
  import { isDeepStrictEqual, types } from 'node:util';
22
22
  import { homedir, hostname } from 'node:os';
23
23
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
24
24
  import { createInterface } from 'node:readline';
25
25
  import { DRAFT_SERVER_TEXT, PreflightError, TEST_SCHEMA, LIMITS, captureSource, tarFiles, scenarioShapeRefusal, checkInput, fillHashes, lintLocalHygiene, sharedSourceFiles, findTests, formatSize, gitFiles, otherFiles,
26
- discoveryRefusal, preflight, hasPromptInterface, interfaceBlocks, interfaceFindings, executableInterfaceText, readPrompt, promptMarkdownTargets, formatWarningLines, schemaKeywordWarningLines, missingCliImplementationWarnings, prepareHashSelection, sourceFilePort, exactNumberSpelling, sha256, STALE_HINT, staleHint } from './runtime-preflight.mjs';
26
+ discoveryRefusal, preflight, hasPromptInterface, interfaceBlocks, interfaceFindings, executableInterfaceText, readPrompt, promptMarkdownTargets, formatWarningLines, schemaKeywordWarningLines, missingCliImplementationWarnings, plainMarkdownCallsProblems, prepareHashSelection, sourceFilePort, exactNumberSpelling, sha256, STALE_HINT, staleHint } from './runtime-preflight.mjs';
27
27
  import { catalogRecords, compareCopies } from './contract-refs.mjs';
28
28
  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
- const localInterfaceProblem = problem => ['interface-missing','interface-kind-invalid','native-reason-missing','interface-draft-incomplete','duplicate-selector-word'].includes(problem.code);
34
+ const localInterfaceProblem = problem => ['interface-missing','interface-kind-invalid','native-reason-missing','interface-draft-incomplete','duplicate-selector-word','invalid-calls-syntax','unknown-target','unknown-target-operation'].includes(problem.code);
34
35
  const unboundPortError = message => Object.assign(new Error(message), { unboundPort: true });
35
36
  // The preflight owner's local format advice (#3206): an explicit full kind in a draft and unsupported schema
36
37
  // keywords are warnings in lint and the files preview, never refusals; the engine is the one place that refuses.
@@ -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,12 @@ 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;
121
+ // Completed/reconciled local batch directories older than 14 days are eligible for automatic GC (override via PDD_BATCH_RETENTION_DAYS; 0 disables).
122
+ const DEFAULT_BATCH_RETENTION_DAYS = 14;
123
+ const BATCH_GC_INTERVAL_MS = 60 * 60 * 1000;
124
+ const RESERVATION_INDEX_FILE = 'reservation-index.json';
89
125
 
90
126
  class Stop extends Error { constructor(exitCode, message) { super(message); this.exitCode = exitCode; } }
91
127
  function requestedCalls(raw) {
@@ -95,6 +131,53 @@ function requestedCalls(raw) {
95
131
  throw new Stop(2, '--max-calls must be a whole number from 1 to 1000, the interpreter maximum.');
96
132
  return Number(raw);
97
133
  }
134
+ function parseTimeoutMinutes(raw, flagName, { allowZero = false } = {}) {
135
+ if (raw === undefined) return null;
136
+ const value = Number(raw);
137
+ if (typeof raw === 'boolean' || raw === '' || !Number.isFinite(value) || (allowZero ? value < 0 : value <= 0)) {
138
+ throw new Stop(2, `${flagName} must be a positive number of minutes.`);
139
+ }
140
+ return value;
141
+ }
142
+ function batchDeadlineOf(context) {
143
+ if (context.batchDeadline !== undefined) return context.batchDeadline;
144
+ return context.deadline ?? Infinity;
145
+ }
146
+ function rowDeadline(context, row) {
147
+ const batchEnd = batchDeadlineOf(context);
148
+ const storyEnd = row?.story_deadline ?? Infinity;
149
+ return Math.min(batchEnd, storyEnd);
150
+ }
151
+ function rowExpired(context, row, now = context.ports.now()) {
152
+ return now >= rowDeadline(context, row);
153
+ }
154
+ function ensureConcurrencyState(context) {
155
+ if (!context.concurrency) {
156
+ const ceiling = checkConcurrencyLimit(context);
157
+ const initial = Number.isSafeInteger(context.checkWindow) && context.checkWindow >= 1
158
+ ? Math.min(ceiling, context.checkWindow) : ceiling;
159
+ context.concurrency = createAdaptiveConcurrency({ ceiling, initial });
160
+ }
161
+ context.checkWindow = context.concurrency.window;
162
+ return context.concurrency;
163
+ }
164
+ function backoffCheckWindow(context, signalKey = null, reason = 'server busy') {
165
+ if (context.reading) return;
166
+ const state = ensureConcurrencyState(context);
167
+ const transition = recordContention(state, signalKey, { reason });
168
+ context.checkWindow = state.window;
169
+ if (transition.changed) {
170
+ line(context.ports.stderr, `Adaptive concurrency: reducing active check limit from ${transition.previous} to ${transition.current} (${reason}).`);
171
+ }
172
+ }
173
+ function recoverCheckWindow(context, successKey = null) {
174
+ if (context.reading || !context.concurrency) return;
175
+ const transition = recordCleanSuccess(context.concurrency, successKey);
176
+ context.checkWindow = context.concurrency.window;
177
+ if (transition.changed) {
178
+ line(context.ports.stderr, `Adaptive concurrency: increasing active check limit from ${transition.previous} to ${transition.current} after clean completions.`);
179
+ }
180
+ }
98
181
 
99
182
  function sampleOptions(options) {
100
183
  const parse = value => {
@@ -546,7 +629,7 @@ async function readBaselineReport(context, plan, identity) {
546
629
  catch { partial=true;warn('Some original Check receipts are missing, corrupt or mismatched.'); }
547
630
  for (const answer of originals) {
548
631
  const secrets = [...(context.secrets??[]),identity.token].filter(Boolean);
549
- const view = projectAnswer(answer,{origin:saved.origin,steps:row.steps??[],criterionTexts:row.criterion_texts??{},test:row.test,secrets});
632
+ const view = projectAnswer(answer,{origin:saved.origin,steps:row.steps??[],criterionTexts:row.criterion_texts??{},test:row.test,secrets,clauseTable:saved.clauses??null});
550
633
  retain(view,id,'receipt',validLink(cleanText(answer.report_url,secrets),saved.origin,'report'));
551
634
  }
552
635
  } catch { partial=true;warn('Some original Check receipts are missing, corrupt or mismatched.'); }
@@ -712,13 +795,16 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
712
795
  if (!sent.has(row.story)) sent.set(row.story, new Set());
713
796
  sent.get(row.story).add(row.test);
714
797
  let pass = false;
798
+ let rowOwnPassed = false;
799
+ const rowPassedKeys = new Set();
800
+ const rowRequiredKeys = new Set();
715
801
  const id = row.request_ids.at(-1);
716
802
  if (typeof id === 'string' && UUID.test(id)) {
717
803
  const receiptPath = join(folder, `${id}.json`);
718
804
  try {
719
805
  const answer = JSON.parse(await read(receiptPath));
720
806
  if (answer?.requestId === id && answer.id === id && answer.command === 'check') {
721
- const view = projectAnswer(answer, { origin: batch.origin, steps: row.steps ?? [], criterionTexts: row.criterion_texts ?? {}, test: row.test });
807
+ const view = projectAnswer(answer, { origin: batch.origin, steps: row.steps ?? [], criterionTexts: row.criterion_texts ?? {}, test: row.test, clauseTable: batch.clauses ?? null });
722
808
  const failedChecks = Array.isArray(view.failed_checks) ? view.failed_checks : [];
723
809
  note(row.story, was => ({ ...was, failed: was.failed + failedChecks.length,
724
810
  failedSteps: [...new Set([...was.failedSteps, ...failedChecks.map(check => check?.step_id).filter(step => typeof step === 'string' && step)])].slice(0, 10),
@@ -737,6 +823,25 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
737
823
  && view.criteria.passed === row.criteria_total && view.checks?.total > 0 && view.checks.passed === view.checks.total
738
824
  && Array.isArray(criteria) && new Set(criteria.map(item => item?.criterion_id)).size === row.criteria_total
739
825
  && criteria.every(item => authored.includes(item?.criterion_id) && item.status === 'passed');
826
+ const ownUnchecked = new Set(ownNotCheckedOf(row).map(item => item?.criterion_id).filter(Boolean));
827
+ const { keyFor } = rowCriterionKeys(row);
828
+ for (const cid of authored) {
829
+ const key = keyFor(cid);
830
+ if (key) rowRequiredKeys.add(key);
831
+ }
832
+ if (view.state === 'passed' && Number.isInteger(row.criteria_total) && row.criteria_total > 0
833
+ && authored.length === row.criteria_total && view.checks?.total > 0 && view.checks.passed === view.checks.total
834
+ && Array.isArray(criteria) && criteria.every(item => authored.includes(item?.criterion_id) && !['failed', 'unknown'].includes(item?.status))) {
835
+ const passedById = new Set(criteria.filter(item => item?.status === 'passed' && !ownUnchecked.has(item.criterion_id)).map(item => item.criterion_id));
836
+ const ownRequired = authored.filter(cid => !ownUnchecked.has(cid));
837
+ if (ownRequired.length > 0 && ownRequired.every(cid => passedById.has(cid))) {
838
+ rowOwnPassed = true;
839
+ for (const cid of passedById) {
840
+ const key = keyFor(cid);
841
+ if (key) rowPassedKeys.add(key);
842
+ }
843
+ }
844
+ }
740
845
  }
741
846
  } catch (error) {
742
847
  if (!(error?.code === 'ENOENT' && unsavedPostOutcome(row))) warning(receiptPath, error);
@@ -745,7 +850,20 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
745
850
  const at = Number.isFinite(row.ended_at) ? row.ended_at : Date.parse(batch.created_at) || 0;
746
851
  const previous = grouped.get(row.story);
747
852
  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) });
853
+ const passedKeys = previous?.passedKeys ?? new Set();
854
+ for (const key of rowPassedKeys) passedKeys.add(key);
855
+ const requiredKeys = previous?.requiredKeys ?? new Set();
856
+ for (const key of rowRequiredKeys) requiredKeys.add(key);
857
+ grouped.set(row.story, {
858
+ story: row.story,
859
+ pass: pass && (previous?.pass ?? true),
860
+ ownPassed: rowOwnPassed && (previous?.ownPassed ?? true),
861
+ passedKeys,
862
+ requiredKeys,
863
+ current,
864
+ result: 'no verdict',
865
+ at: Math.max(previous?.at ?? at, at),
866
+ });
749
867
  }
750
868
  // withTests: pdd's own fix texts of a Story's refusals (its saved warnings, then each refusal's fix).
751
869
  const advised = story => {
@@ -755,9 +873,14 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
755
873
  return { ...info, advice: [...new Set([...warned, ...fixes])].slice(0, 3).map(text => text.slice(0, 800)) };
756
874
  };
757
875
  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);
876
+ const siblingCount = selected.get(row.story)?.size ?? 0;
877
+ const sentCount = sent.get(row.story)?.size ?? 0;
878
+ const unionPass = siblingCount > 1 && sentCount === siblingCount && row.ownPassed
879
+ && row.requiredKeys.size > 0 && [...row.requiredKeys].every(key => row.passedKeys.has(key));
880
+ const storyPass = row.pass || unionPass;
881
+ if (storyPass && sentCount !== siblingCount) continue;
882
+ const entry = { story: row.story, pass: storyPass, current: row.current, result: storyPass ? '✓' : 'no verdict', at: row.at };
883
+ stories.push(withTests ? { ...entry, tests: [...selected.get(row.story)].sort(), ...advised(row.story), sent: true } : entry);
761
884
  }
762
885
  // withTests: a Story whose tests were never sent (refused before execution, interrupted) is listed too.
763
886
  if (withTests) for (const story of extra.keys()) if (!grouped.has(story)) {
@@ -803,7 +926,7 @@ export async function resendableStoryChecks({ root, since = 0 }, ports = {}) {
803
926
  let answer = null;
804
927
  try { answer = typeof id === 'string' && UUID.test(id) ? JSON.parse(await read(join(directory, name, `${id}.json`))) : null; } catch { answer = null; }
805
928
  if (!sameJob(answer, id, 'check')) return 'other';
806
- const view = projectAnswer(answer, { origin: batch.origin, steps: row.steps ?? [], criterionTexts: row.criterion_texts ?? {}, test: row.test });
929
+ const view = projectAnswer(answer, { origin: batch.origin, steps: row.steps ?? [], criterionTexts: row.criterion_texts ?? {}, test: row.test, clauseTable: batch.clauses ?? null });
807
930
  if (answer.state === 'failed' || view.failed_checks?.length) return 'failed';
808
931
  return answer.state === 'unknown' ? 'noVerdict' : 'other';
809
932
  };
@@ -1308,10 +1431,16 @@ function retryAfter(headers) {
1308
1431
  const UNREACHABLE = { ENOTFOUND: 'the address was not found', EAI_AGAIN: 'the address was not found', ECONNREFUSED: 'the connection was refused',
1309
1432
  EHOSTUNREACH: 'there is no network route to it', ENETUNREACH: 'there is no network route to it', UND_ERR_CONNECT_TIMEOUT: 'the connection timed out' };
1310
1433
  function lostReply(error, origin) {
1311
- const code = String(error?.cause?.code ?? error?.code ?? ''), cert = /CERT|SELF_SIGNED|UNABLE_TO_VERIFY|ERR_TLS/.test(code);
1434
+ // Node fetch aborts throw DOMException [AbortError] with numeric code === 20 (ABORT_ERR).
1435
+ // Treat client-side aborts/timeouts as "no answer in time" rather than "connection failed: 20".
1436
+ if (!error?.cause?.code && (error?.name === 'AbortError' || error?.name === 'TimeoutError')) {
1437
+ return { lost: true, why: 'no answer in time' };
1438
+ }
1439
+ const rawCode = error?.cause?.code ?? error?.code;
1440
+ const code = rawCode == null ? '' : String(rawCode), cert = /CERT|SELF_SIGNED|UNABLE_TO_VERIFY|ERR_TLS/.test(code);
1312
1441
  const reason = UNREACHABLE[code] ?? (cert ? 'its TLS certificate was not accepted' : null);
1313
1442
  if (reason) return { lost: true, unreachable: `pdd could not reach the PDD interpreter at ${origin}: ${reason} (${code}). Nothing was sent. Check your network and PDD_RUNTIME_URL, then run the command again.` };
1314
- return { lost: true, why: code ? `connection failed: ${code}` : error?.name === 'AbortError' ? 'no answer in time' : null };
1443
+ return { lost: true, why: code ? `connection failed: ${code}` : null };
1315
1444
  }
1316
1445
  const AUTH_TEXT = 'The PDD interpreter did not accept your GitHub login (HTTP 401). Run gh auth login, then run the command again.';
1317
1446
  const isPreExecutionRefusal = reply => reply.status >= 400 && reply.status < 500 && reply.status !== 408;
@@ -1321,7 +1450,13 @@ const unadmittedCallErrors = new WeakMap();
1321
1450
 
1322
1451
  // HTTP to the runtime. The token stays in this object and in request headers only.
1323
1452
  class Runtime {
1324
- constructor({ origin, token, ports, signal, auth, programJson = false }) { Object.assign(this, { origin, token, ports, signal, auth, programJson }); this.sources = new WeakMap(); }
1453
+ constructor({ origin, token, ports, signal, auth, programJson = false }) {
1454
+ Object.assign(this, { origin, token, ports, signal, auth, programJson });
1455
+ this.sources = new WeakMap();
1456
+ this.uploadedSources = new Set();
1457
+ this.uploadingSources = new Map();
1458
+ this.sourceUploadDisabled = false;
1459
+ }
1325
1460
  async sendOnce(path, init, ms) {
1326
1461
  const readSignal = init?.method === 'GET' ? init.signal : null;
1327
1462
  if (this.signal?.aborted || readSignal?.aborted) return { lost: true };
@@ -1450,7 +1585,31 @@ class Runtime {
1450
1585
  else if (pathname !== '/v1/capacity' && [200, 202].includes(retry.status)) this.auth.verifiedByServer = true;
1451
1586
  return retry;
1452
1587
  }
1453
- post(path, request, tar, timeoutMs = this.ports.postMs) {
1588
+ async uploadSource(sha256Hex, tar, timeoutMs = this.ports.postMs) {
1589
+ if (this.sourceUploadDisabled || !tar || typeof sha256Hex !== 'string' || !/^[a-f0-9]{64}$/.test(sha256Hex)) return false;
1590
+ if (this.uploadedSources.has(sha256Hex)) return true;
1591
+ if (this.uploadingSources.has(sha256Hex)) return this.uploadingSources.get(sha256Hex);
1592
+ const pending = (async () => {
1593
+ let source = this.sources.get(tar);
1594
+ if (!source) { source = new Blob([tar], { type: 'application/x-tar' }); this.sources.set(tar, source); }
1595
+ const reply = await this.send('/v1/sources', {
1596
+ method: 'POST',
1597
+ headers: { 'Content-Type': 'application/x-tar', 'X-Source-Sha256': sha256Hex },
1598
+ body: () => source,
1599
+ }, timeoutMs);
1600
+ if (reply.status === 200 && reply.json?.source_sha256 === sha256Hex) {
1601
+ this.uploadedSources.add(sha256Hex);
1602
+ return true;
1603
+ }
1604
+ if ([404, 405, 415, 501].includes(reply.status)) this.sourceUploadDisabled = true;
1605
+ return false;
1606
+ })().finally(() => {
1607
+ if (this.uploadingSources.get(sha256Hex) === pending) this.uploadingSources.delete(sha256Hex);
1608
+ });
1609
+ this.uploadingSources.set(sha256Hex, pending);
1610
+ return pending;
1611
+ }
1612
+ async post(path, request, tar, timeoutMs = this.ports.postMs, options = undefined) {
1454
1613
  const makeForm = () => {
1455
1614
  const form = new FormData();
1456
1615
  form.set('request', new Blob([JSON.stringify(request)], { type: 'application/json' }), 'request.json');
@@ -1459,7 +1618,37 @@ class Runtime {
1459
1618
  form.set('source', source, 'source.tar');
1460
1619
  return form;
1461
1620
  };
1462
- return this.send(path, { method: 'POST', body: makeForm }, timeoutMs);
1621
+ const sha = options?.dedup === true && !this.sourceUploadDisabled && tar && typeof request?.source_sha256 === 'string' && /^[a-f0-9]{64}$/.test(request.source_sha256)
1622
+ ? request.source_sha256 : null;
1623
+ const postInline = async () => {
1624
+ const reply = await this.send(path, { method: 'POST', body: makeForm }, timeoutMs);
1625
+ if (sha && [200, 202].includes(reply.status)) this.uploadedSources.add(sha);
1626
+ return reply;
1627
+ };
1628
+ if (!sha) return postInline();
1629
+ if (options?.inlineFirst === true && !this.uploadedSources.has(sha)) return postInline();
1630
+ if (!this.uploadedSources.has(sha)) {
1631
+ const uploaded = await this.uploadSource(sha, tar, timeoutMs);
1632
+ if (!uploaded) return postInline();
1633
+ }
1634
+ const reply = await this.send(path, {
1635
+ method: 'POST',
1636
+ headers: { 'Content-Type': 'application/json' },
1637
+ body: () => JSON.stringify(request),
1638
+ }, timeoutMs);
1639
+ const code = reply.json?.error?.code ?? reply.json?.code;
1640
+ if ([404, 409, 422].includes(reply.status) && code === 'source-not-found'
1641
+ && reply.json?.job_created !== true && reply.json?.dispatch !== 'unknown') {
1642
+ this.uploadedSources.delete(sha);
1643
+ return postInline();
1644
+ }
1645
+ if (reply.status === 415 && code === 'unsupported-content-type'
1646
+ && reply.json?.job_created !== true && reply.json?.dispatch !== 'unknown') {
1647
+ this.sourceUploadDisabled = true;
1648
+ this.uploadedSources.delete(sha);
1649
+ return postInline();
1650
+ }
1651
+ return reply;
1463
1652
  }
1464
1653
  get(id, timeoutMs = GET_MS, { waitSeconds = 0 } = {}) {
1465
1654
  const headers = waitSeconds > 0 ? preferWaitHeaders(waitSeconds) : undefined;
@@ -1764,8 +1953,10 @@ function accumulatedAccounting(context, row) {
1764
1953
  const unknown = parts.reduce((sum, part) => sum + part.unknown, 0), complete = parts.every(part => part.complete);
1765
1954
  const total = complete ? parts.reduce((sum, part) => sum + part.total, 0) : null;
1766
1955
  const dispatched = complete ? parts.filter(part => !part.zeroWork) : [];
1767
- const sumToken = key => complete && dispatched.length > 0 && dispatched.every(part => typeof part.tokens[key] === 'number')
1768
- ? dispatched.reduce((sum, part) => sum + part.tokens[key], 0) : 'unknown';
1956
+ const sumToken = key => complete && parts.length > 0 && dispatched.length === 0
1957
+ ? 0
1958
+ : complete && dispatched.length > 0 && dispatched.every(part => typeof part.tokens[key] === 'number')
1959
+ ? dispatched.reduce((sum, part) => sum + part.tokens[key], 0) : 'unknown';
1769
1960
  const input_tokens = sumToken('input_tokens');
1770
1961
  const cached_input_tokens = typeof input_tokens === 'number' ? sumToken('cached_input_tokens') : 'unknown';
1771
1962
  const output_tokens = sumToken('output_tokens');
@@ -1814,7 +2005,7 @@ function markBusy(context, row, wait, observedAt = context.ports.now(), legacy =
1814
2005
  checks: null, criteria: null, all_checks: [], failed_checks: [], why: null, next_step: null,
1815
2006
  note: { code: 'check-busy', message: 'The interpreter is busy. No checks ran for this attempt. Retry this batch later.' } });
1816
2007
  Object.assign(row, accumulatedAccounting(context, row));
1817
- if (!context.reading) context.checkWindow = 1;
2008
+ if (!context.reading) backoffCheckWindow(context, id ?? `${row.test}:${row.request_ids.length}`, 'server busy / 429');
1818
2009
  }
1819
2010
 
1820
2011
  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 +2077,13 @@ function localLimit(context) {
1886
2077
  if (raw === undefined) return context.localLimit = Infinity;
1887
2078
  const value = Number(raw);
1888
2079
  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.');
2080
+ 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
2081
  return context.localLimit = Infinity;
1891
2082
  }
2083
+ function checkConcurrencyLimit(context) {
2084
+ const limit = localLimit(context);
2085
+ return Number.isFinite(limit) ? limit : DEFAULT_CHECK_CONCURRENCY;
2086
+ }
1892
2087
  function uploadLimit(context) {
1893
2088
  if (context.uploadLimit !== undefined) return context.uploadLimit;
1894
2089
  const raw = context.ports.env.PDD_MAX_UPLOADS;
@@ -2091,7 +2286,7 @@ async function probeLazyInterfaces(context, origin, store) {
2091
2286
  if (isDefinitiveCapacityReply(reply)) {
2092
2287
  const features = reply.status === 200 && Array.isArray(reply.json?.features) ? reply.json.features : [];
2093
2288
  const engineSha = reply.status === 200 ? reply.json?.engine_sha ?? null : null;
2094
- const supportsLazy = features.includes('lazy-interfaces');
2289
+ const supportsLazy = features.includes('lazy-interfaces') || features.some(feature => /^hybrid(?:-|$)/.test(feature));
2095
2290
  if (supportsLazy) store?.writeOriginCapabilities(origin, { features, engine_sha: engineSha }, context.ports.now());
2096
2291
  else store?.deleteOriginCapabilities(origin);
2097
2292
  context.probedIdentity = identity;
@@ -2241,11 +2436,11 @@ function judgePost(reply, id, command, secrets) {
2241
2436
  return { kind: 'busy', wait: retryAfter(reply.headers), admission: reply.json };
2242
2437
  }
2243
2438
  return retryable429 ? { kind: 'busy', wait: retryAfter(reply.headers), admission: reply.json }
2244
- : { kind: 'not_run', note: note('The interpreter is busy. Try again later.') };
2439
+ : { kind: 'not_run', note: note('The interpreter is busy. Try again later.'), contention: true };
2245
2440
  }
2246
2441
  if (gateText(reply)) return { kind: 'stop', note: { code: null, message: 'The runtime opens soon.' } };
2247
2442
  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.') };
2443
+ 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
2444
  if ([400, 413, 415, 422].includes(reply.status) && error?.code) {
2250
2445
  return { kind: 'refused', refusal: { code: cleanText(error.code, secrets), section: cleanText(error.section, secrets) || null, message: cleanText(error.message, secrets) || null,
2251
2446
  engine_message: reply.json.details ? cleanText(JSON.stringify(reply.json.details), secrets) : null,
@@ -2266,6 +2461,7 @@ function judgeGet(reply, id, command) {
2266
2461
  if (reply.status === 410) return { kind: 'unknown', why: 'The result expired.', status: 410 };
2267
2462
  if (reply.status === 401) return { kind: 'auth' };
2268
2463
  if (gateText(reply)) return { kind: 'gate' };
2464
+ if (reply.status === 429) return { kind: 'again', contention: true };
2269
2465
  return { kind: 'again' };
2270
2466
  }
2271
2467
 
@@ -2353,6 +2549,137 @@ const incompleteCriteria = row => {
2353
2549
  message:'The Story is not a full pass: some criteria were not checked.'}});
2354
2550
  };
2355
2551
 
2552
+ function ownNotCheckedOf(row) {
2553
+ if (Array.isArray(row?.own_not_checked)) return row.own_not_checked;
2554
+ if (Array.isArray(row?.not_checked)) return row.not_checked;
2555
+ return [];
2556
+ }
2557
+
2558
+ function rowStoryKey(row) {
2559
+ if (typeof row?.story_path === 'string' && row.story_path.trim()) return `path:${row.story_path.trim()}`;
2560
+ if (typeof row?.story === 'string' && row.story.trim() && row.story !== '-') return `story:${row.story.trim()}`;
2561
+ return null;
2562
+ }
2563
+
2564
+ function rowCriterionKeys(row) {
2565
+ const texts = isObject(row?.criterion_texts) ? row.criterion_texts : {};
2566
+ const entries = Object.entries(texts).filter(([id, text]) => typeof id === 'string' && id && typeof text === 'string');
2567
+ const counts = new Map();
2568
+ for (const [, text] of entries) counts.set(text, (counts.get(text) ?? 0) + 1);
2569
+ const byId = new Map();
2570
+ for (const [id, text] of entries) {
2571
+ byId.set(id, counts.get(text) === 1 ? `text:${text}` : `id:${id}`);
2572
+ }
2573
+ const keyFor = (criterionId, text = texts[criterionId]) => {
2574
+ if (typeof criterionId === 'string' && byId.has(criterionId)) return byId.get(criterionId);
2575
+ if (typeof text === 'string' && text && (counts.get(text) ?? 0) <= 1) return `text:${text}`;
2576
+ return typeof criterionId === 'string' && criterionId ? `id:${criterionId}` : null;
2577
+ };
2578
+ return { entries, byId, keyFor };
2579
+ }
2580
+
2581
+ function rowPassedOwnChecks(row) {
2582
+ if (!row || row.unsent || row.native_only?.length || row.diagnostic_subset === true || row.diagnostic === true) return false;
2583
+ if (row.refusals?.length || failedCheckCount(row) > 0) return false;
2584
+ if (row.state === 'passed') return true;
2585
+ return row.state === 'not_run' && row.note?.code === 'criteria-not-checked';
2586
+ }
2587
+
2588
+ function contributedCriterionKeys(row, context) {
2589
+ if (!rowPassedOwnChecks(row)) return [];
2590
+ const { entries, keyFor } = rowCriterionKeys(row);
2591
+ const ownUnchecked = new Set(ownNotCheckedOf(row).map(item => item?.criterion_id).filter(Boolean));
2592
+ if (context?.intent === 'lint-only' || row.phase === 'lint') {
2593
+ return entries.filter(([id]) => !ownUnchecked.has(id)).map(([id, text]) => keyFor(id, text)).filter(Boolean);
2594
+ }
2595
+ if (Array.isArray(row.verified_passed_criteria)) {
2596
+ return row.verified_passed_criteria
2597
+ .filter(item => item?.criterion_id && !ownUnchecked.has(item.criterion_id))
2598
+ .map(item => keyFor(item.criterion_id, item.text))
2599
+ .filter(Boolean);
2600
+ }
2601
+ if (row.cached && row.state === 'passed') {
2602
+ return entries.filter(([id]) => !ownUnchecked.has(id)).map(([id, text]) => keyFor(id, text)).filter(Boolean);
2603
+ }
2604
+ return [];
2605
+ }
2606
+
2607
+ function failedCriterionKeys(row) {
2608
+ const { keyFor } = rowCriterionKeys(row);
2609
+ const out = [];
2610
+ for (const item of row?.verified_failed_criteria ?? []) {
2611
+ const key = keyFor(item?.criterion_id, item?.text);
2612
+ if (key) out.push(key);
2613
+ }
2614
+ for (const check of row?.failed_checks ?? []) {
2615
+ const key = keyFor(check?.criterion_id);
2616
+ if (key) out.push(key);
2617
+ }
2618
+ return out;
2619
+ }
2620
+
2621
+ // Reconcile criteria-not-checked across passing sibling variant files for the same Story
2622
+ // within the same executed batch, keeping single-file verification strictly fail-closed.
2623
+ function reconcileStoryCriteria(rows, context = null) {
2624
+ if (!Array.isArray(rows) || !rows.length) return;
2625
+ const groups = new Map();
2626
+ for (const row of rows) {
2627
+ const key = rowStoryKey(row);
2628
+ if (!key) {
2629
+ incompleteCriteria(row);
2630
+ continue;
2631
+ }
2632
+ if (!groups.has(key)) groups.set(key, []);
2633
+ groups.get(key).push(row);
2634
+ }
2635
+ for (const group of groups.values()) {
2636
+ const covered = new Set();
2637
+ const failed = new Set();
2638
+ if (group.length > 1) {
2639
+ for (const row of group) {
2640
+ for (const key of failedCriterionKeys(row)) failed.add(key);
2641
+ for (const key of contributedCriterionKeys(row, context)) covered.add(key);
2642
+ }
2643
+ for (const key of failed) covered.delete(key);
2644
+ }
2645
+ for (const row of group) {
2646
+ const ownUnchecked = ownNotCheckedOf(row);
2647
+ if (!ownUnchecked.length) {
2648
+ incompleteCriteria(row);
2649
+ continue;
2650
+ }
2651
+ if (!row.own_not_checked) row.own_not_checked = ownUnchecked.map(item => ({ ...item }));
2652
+ if (group.length > 1 && rowPassedOwnChecks(row)) {
2653
+ const { keyFor } = rowCriterionKeys(row);
2654
+ const remaining = ownUnchecked.filter(item => {
2655
+ const key = keyFor(item?.criterion_id, item?.text);
2656
+ return !key || !covered.has(key);
2657
+ });
2658
+ const siblingCovered = ownUnchecked.length - remaining.length;
2659
+ if (remaining.length) row.not_checked = remaining;
2660
+ else delete row.not_checked;
2661
+ if (!remaining.length) {
2662
+ if (row.own_criteria) {
2663
+ const total = Math.max(row.own_criteria.passed, row.own_criteria.total - siblingCovered);
2664
+ row.criteria = { passed: row.own_criteria.passed, total };
2665
+ }
2666
+ if (row.state === 'not_run' && row.note?.code === 'criteria-not-checked') {
2667
+ row.state = 'passed';
2668
+ row.note = null;
2669
+ }
2670
+ } else {
2671
+ if (row.own_criteria) row.criteria = { ...row.own_criteria };
2672
+ incompleteCriteria(row);
2673
+ }
2674
+ } else {
2675
+ row.not_checked = ownUnchecked.map(item => ({ ...item }));
2676
+ if (row.own_criteria) row.criteria = { ...row.own_criteria };
2677
+ incompleteCriteria(row);
2678
+ }
2679
+ }
2680
+ }
2681
+ }
2682
+
2356
2683
  function capturedCriteria(rows, capture) {
2357
2684
  let broken = false;
2358
2685
  for (const row of rows.filter(row=>!row.unsent)) {
@@ -2373,8 +2700,13 @@ function capturedCriteria(rows, capture) {
2373
2700
  const exemptions=Array.isArray(doc.check_exemptions)?doc.check_exemptions:[];
2374
2701
  const unchecked=exemptions.filter(item=>isObject(item)&&item.reason==='out-of-scope').map(item=>({
2375
2702
  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;
2703
+ if (unchecked.length) {
2704
+ row.not_checked=unchecked;
2705
+ row.own_not_checked=unchecked.map(item=>({...item}));
2706
+ } else {
2707
+ delete row.not_checked;
2708
+ delete row.own_not_checked;
2709
+ }
2378
2710
  }
2379
2711
  return broken;
2380
2712
  }
@@ -2398,16 +2730,35 @@ function captureIndependent(root, rows, ports, options) {
2398
2730
  try { captured=capture(sentTests(rows)); }
2399
2731
  catch (error) {
2400
2732
  if (!sourceUnavailable(error)) throw error;
2733
+ const candidates = rows.filter(row => !row.unsent);
2401
2734
  let broken = false;
2402
- for (const row of rows.filter(row => !row.unsent)) {
2403
- try { capture([row.test]); }
2404
- catch (own) {
2405
- if (!sourceUnavailable(own)) throw own;
2406
- broken = true;
2407
- line(ports.stderr, own.message);
2408
- refuseSource(row, own);
2735
+ const isolate = list => {
2736
+ if (!list.length) return;
2737
+ if (list.length === 1) {
2738
+ const row = list[0];
2739
+ try { capture([row.test]); }
2740
+ catch (own) {
2741
+ if (!sourceUnavailable(own)) throw own;
2742
+ broken = true;
2743
+ line(ports.stderr, own.message);
2744
+ refuseSource(row, own);
2745
+ }
2746
+ return;
2409
2747
  }
2410
- }
2748
+ if (list.length <= 4) {
2749
+ for (const row of list) isolate([row]);
2750
+ return;
2751
+ }
2752
+ const mid = Math.floor(list.length / 2);
2753
+ for (const half of [list.slice(0, mid), list.slice(mid)]) {
2754
+ try { capture(half.map(row => row.test)); }
2755
+ catch (halfError) {
2756
+ if (!sourceUnavailable(halfError)) throw halfError;
2757
+ isolate(half);
2758
+ }
2759
+ }
2760
+ };
2761
+ isolate(candidates);
2411
2762
  if (!broken) throw error; // Aggregate limits and unstable/shared failures retain their rules.
2412
2763
  return captureIndependent(root,rows,ports,options);
2413
2764
  }
@@ -2596,10 +2947,12 @@ function applyAnswer(row, answer, context, observedWait = null, observedAt = con
2596
2947
  models: models.filter(knownIdentity), terminal, complete: terminal && !!row.cache_identity
2597
2948
  && (accounting.accounting_complete ?? accounting.complete) === true && !capacityUncertain,
2598
2949
  observed_at: new Date(context.ports.now()).toISOString() });
2599
- const view = projectAnswer(answer, { origin: context.origin, secrets: context.secrets, steps: row.steps ?? [], criterionTexts: row.criterion_texts ?? {}, test: row.test, capacityUncertain });
2950
+ const view = projectAnswer(answer, { origin: context.origin, secrets: context.secrets, steps: row.steps ?? [], criterionTexts: row.criterion_texts ?? {}, test: row.test, capacityUncertain, clauseTable: row.clause_table ?? context.capture?.clauses ?? null });
2600
2951
  const advice = noVerdictAdvice(answer, view);
2601
2952
  const firstDiagnosis = view.failed_checks.find(check => check.diagnosis) ?? null, failed = view.state === 'failed';
2953
+ const baseWarnings = (row.warnings ?? []).filter(text => !/^Warning: dropped \d+ unknown clause citations? from the interpreter\.$/.test(text));
2602
2954
  Object.assign(row, { state: view.state, checks: view.checks, criteria: view.criteria, failed_checks: view.failed_checks, all_checks: view.all_checks,
2955
+ warnings: [...baseWarnings, ...(view.clause_warnings ?? [])],
2603
2956
  ...(view.step_details?.length ? { step_details: view.step_details } : {}),
2604
2957
  ...(view.draft_interfaces?.length ? { draft_interfaces: view.draft_interfaces } : {}),
2605
2958
  ...(Object.hasOwn(view, 'field_agreement') ? { field_agreement: view.field_agreement } : {}),
@@ -2624,15 +2977,41 @@ function applyAnswer(row, answer, context, observedWait = null, observedAt = con
2624
2977
  if (capacityUncertain) markCapacityUnknown(context, row);
2625
2978
  else if (wait !== null) markBusy(context, row, observedWait ?? wait, observedAt, context.reading && observedWait === null);
2626
2979
  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;
2980
+ const ownNotChecked = ownNotCheckedOf(row);
2981
+ if (ownNotChecked.length) {
2982
+ row.own_not_checked = ownNotChecked.map(item => ({ ...item }));
2983
+ row.not_checked = ownNotChecked.map(item => ({ ...item }));
2984
+ } else {
2985
+ delete row.not_checked;
2986
+ delete row.own_not_checked;
2987
+ }
2988
+ const results = answer?.result?.report?.criterion_results;
2989
+ const unchecked = new Set(ownNotChecked.map(item => item.criterion_id));
2990
+ row.verified_passed_criteria = Array.isArray(results)
2991
+ ? results.filter(item => isObject(item) && item.status === 'passed' && typeof item.criterion_id === 'string' && !unchecked.has(item.criterion_id))
2992
+ .map(item => ({ criterion_id: item.criterion_id, text: row.criterion_texts?.[item.criterion_id] }))
2993
+ : null;
2994
+ row.verified_failed_criteria = Array.isArray(results)
2995
+ ? results.filter(item => isObject(item) && item.status === 'failed' && typeof item.criterion_id === 'string')
2996
+ .map(item => ({ criterion_id: item.criterion_id, text: row.criterion_texts?.[item.criterion_id] }))
2997
+ : [];
2998
+ if (ownNotChecked.length) {
2630
2999
  row.criteria = {passed:Array.isArray(results) ? results.filter(item=>item.status==='passed'&&!unchecked.has(item.criterion_id)).length : 0,total:row.criteria_total};
2631
3000
  }
3001
+ row.own_criteria = row.criteria ? { ...row.criteria } : null;
2632
3002
  incompleteCriteria(row);
3003
+ if (Array.isArray(context?.rows) && context.rows.includes(row)) reconcileStoryCriteria(context.rows, context);
2633
3004
  if (row.state === 'refused') addHints(row, context.root, context.visible);
2634
3005
  if (ENDED.has(row.state) && row.sent_at && !row.ended_at && !context.reading) row.ended_at = context.ports.now();
2635
3006
  row.seconds = !ENDED.has(row.state) ? null : row.sent_at && row.ended_at ? (row.ended_at - row.sent_at) / 1000 : row.server_seconds;
3007
+ if (!context.reading && context.concurrency && row.request_ids?.length) {
3008
+ const latestId = row.request_ids.at(-1);
3009
+ if (row.provider || row.time_limit) {
3010
+ backoffCheckWindow(context, `provider:${latestId}`, row.provider?.code || 'provider contention');
3011
+ } else if (['passed', 'failed'].includes(row.state) && !row.cached && !row.busy) {
3012
+ recoverCheckWindow(context, latestId);
3013
+ }
3014
+ }
2636
3015
  }
2637
3016
 
2638
3017
  function nativeSourceIdentity(context, rows) {
@@ -2643,6 +3022,9 @@ function nativeSourceIdentity(context, rows) {
2643
3022
  }
2644
3023
 
2645
3024
  // The saved local-layout contract is deliberately distinct from legacy native-only batches.
3025
+ const LOCAL_LINT_REASON_MESSAGE = 'local structural, scenario, app-map, hygiene, and SVG checks ran; remote cross-prompt lint not run';
3026
+ const LOCAL_LINT_LEGACY_REASON_MESSAGE = 'checked SVG layout only; prompts not checked';
3027
+ const LOCAL_LINT_REASON_MESSAGES = new Set([LOCAL_LINT_REASON_MESSAGE, LOCAL_LINT_LEGACY_REASON_MESSAGE]);
2646
3028
  function localLayoutResult(batch, summary) {
2647
3029
  const keys = (value, names) => value && typeof value === 'object' && !Array.isArray(value)
2648
3030
  && isDeepStrictEqual(Object.keys(value).sort(), names.split(' ').sort());
@@ -2659,7 +3041,7 @@ function localLayoutResult(batch, summary) {
2659
3041
  || !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
3042
  || !Array.isArray(batch.rows) || batch.rows.length || !keys(batch.lint, 'state lint_state reason request_ids')
2661
3043
  || 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'})
3044
+ || !keys(batch.lint.reason, 'code message') || batch.lint.reason.code !== 'local-only' || !LOCAL_LINT_REASON_MESSAGES.has(batch.lint.reason.message)
2663
3045
  || !Array.isArray(batch.lint.request_ids) || batch.lint.request_ids.length) return null;
2664
3046
  const result = {batch:batch.batch,repo:batch.root,exit_code:batch.exit_code,state:'partial',lint_state:'partial',reason:batch.lint.reason,
2665
3047
  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 +3060,7 @@ async function saveLocalLayout(context, {root, tests, prompts, warnings, problem
2678
3060
  try {
2679
3061
  const record = {version:1,batch,root,created_at:new Date(now).toISOString(),intent:'lint-only',local_only:true,source_sha256:null,
2680
3062
  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:[]}};
3063
+ 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
3064
  const projection = localLayoutResult(record,null);
2683
3065
  if (!projection) throw new Error('Local lint record cannot satisfy the saved result contract, including safe inspected scope.');
2684
3066
  const result = {...projection,exit_code:record.exit_code,summary_line:record.summary_line};
@@ -2711,12 +3093,15 @@ function batchRecord(context) {
2711
3093
  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
3094
  ...(context.liveLocal || context.liveLocalSaved ? {live_local:true} : {}),
2713
3095
  source_sha256: capture.sha256, files: capture.files.map(file => file.path), bytes: capture.bytes, timeout_min: context.timeoutMin,
3096
+ ...(Array.isArray(capture.clauses) && capture.clauses.length ? { clauses: capture.clauses } : {}),
3097
+ ...(context.batchTimeoutMin != null ? { batch_timeout_min: context.batchTimeoutMin } : {}),
2714
3098
  ...(context.singleAttempt ? {single_attempt:true} : {}), ...(context.maxTotalCalls != null ? {max_total_calls:context.maxTotalCalls} : {}),
2715
3099
  ...(context.checkOptions ? {check_options:context.checkOptions} : {}),
2716
3100
  source_selection: context.sourceSelection ?? {tests:sentTests(rows),exclude_fixture_projects:context.excludeFixtureProjects === true},
2717
3101
  native_source: context.nativeSource ?? null,
2718
3102
  ...(context.localOnly ? {local_only:true} : {}),
2719
3103
  ...(context.allowMissingInterfaces ? {lazy_interfaces:true} : {}),
3104
+ ...(context.reservationsReconciledAt ? {reservations_reconciled_at:context.reservationsReconciledAt} : {}),
2720
3105
  exclude_fixture_projects: context.excludeFixtureProjects === true,
2721
3106
  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
3107
  contract_snapshots: capture.stories,
@@ -2726,12 +3111,13 @@ function batchRecord(context) {
2726
3111
  ...(row.sample_divergence ? {sample_divergence:row.sample_divergence} : {}),
2727
3112
  ...(row.diagnostic || row.diagnostic_subset === true ? { ...(row.diagnostic ? {diagnostic:true} : {}), diagnostic_subset:true, selected_steps:row.selected_steps ?? [] } : {}),
2728
3113
  ...(!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,
3114
+ ...(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
3115
  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
3116
  reservation: row.reservation ?? null, restart_used: !!row.restart_used,
2732
3117
  busy: !!row.busy, can_retry: !!row.can_retry, eligible: !!row.eligible, retry_at: row.retry_at ?? null,
2733
3118
  ...(row.known_calls !== undefined ? { known_calls: row.known_calls } : {}), ...(row.unknown_calls !== undefined ? { unknown_calls: row.unknown_calls } : {}),
2734
3119
  ...(row.accounting_complete !== undefined ? { accounting_complete: row.accounting_complete } : {}), ...(row.capacity_uncertain ? { capacity_uncertain: true } : {}),
3120
+ ...(row.reservation_reconciled ? { reservation_reconciled: row.reservation_reconciled } : {}),
2735
3121
  busy_request_id: row.busy_request_id ?? null, busy_observed_at: row.busy_observed_at ?? null, capacity_until: row.capacity_until ?? null,
2736
3122
  engine_sha: row.engine_sha ?? null, requested_model: row.requested_model ?? null, cache_identity: row.cache_identity ?? null,
2737
3123
  checks: row.checks ?? null, criteria: row.criteria ?? null, failed_checks: (row.failed_checks ?? []).map(({ normal_result, ...check }) => check),
@@ -2803,27 +3189,300 @@ function adoptClaims(context, row) {
2803
3189
  }
2804
3190
  }
2805
3191
  }
2806
- function readUnresolvedPriorReservations(root, env, excludeBatch = null) {
3192
+ function priorReservationTtlMs(env = {}) {
3193
+ const raw = env?.PDD_PRIOR_RESERVATION_TTL_HOURS;
3194
+ if (raw !== undefined && raw !== null && String(raw).trim() !== '') {
3195
+ const hours = Number(raw);
3196
+ if (Number.isFinite(hours) && hours > 0) return Math.round(hours * 3_600_000);
3197
+ }
3198
+ return PRIOR_RESERVATION_TTL_MS;
3199
+ }
3200
+ function batchIdTimestampMs(name) {
3201
+ const match = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})-/.exec(String(name ?? ''));
3202
+ if (!match) return null;
3203
+ const ms = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), Number(match[6]));
3204
+ return Number.isFinite(ms) ? ms : null;
3205
+ }
3206
+ function reservationTimestampMs(name, saved, row = null) {
3207
+ if (row && Number.isFinite(row.ended_at)) return row.ended_at;
3208
+ if (row && Number.isFinite(row.sent_at)) return row.sent_at;
3209
+ if (typeof saved?.created_at === 'string' && Number.isFinite(Date.parse(saved.created_at))) return Date.parse(saved.created_at);
3210
+ return batchIdTimestampMs(name);
3211
+ }
3212
+ function rowReservationCleared(row) {
3213
+ return isObject(row?.reservation_reconciled) && row.reservation_reconciled.cleared === true;
3214
+ }
3215
+ function rowNeedsReservationCheck(row) {
3216
+ if (!isObject(row) || rowReservationCleared(row)) return false;
3217
+ const ids = Array.isArray(row.request_ids) ? row.request_ids.filter(id => typeof id === 'string' && id.length > 0) : [];
3218
+ if (!ids.length && !row.dispatchIncomplete) return false;
3219
+ const state = row.recovery_state ?? row.state;
3220
+ return ['sending', 'queued', 'running', 'unknown'].includes(state)
3221
+ || row.calls === 'unknown'
3222
+ || row.accounting_complete === false
3223
+ || row.dispatchIncomplete === true;
3224
+ }
3225
+ function localRowSettledFromReceipts(store, folder, ids) {
3226
+ if (!store || !folder || !Array.isArray(ids) || !ids.length) return { settled: false, known_calls: 0, state: null };
3227
+ const probeContext = { store, folder };
3228
+ let totalCalls = 0;
3229
+ let lastState = null;
3230
+ for (const id of ids) {
3231
+ const hasCapacityEvidence = attemptHasCapacityEvidence(probeContext, id);
3232
+ if (hasCapacityEvidence && attemptConfirmedZeroCapacity(probeContext, id)) {
3233
+ lastState = 'refused';
3234
+ continue;
3235
+ }
3236
+ const latest = store.read(join(folder, `${id}.json`));
3237
+ if (!latest || !sameJob(latest, id, 'check') || !accountingEnd(latest, id)) {
3238
+ return { settled: false, known_calls: 0, state: null };
3239
+ }
3240
+ const unknownWithoutExplicitProof = latest.state === 'unknown'
3241
+ && ![latest, latest.usage, latest.result, latest.report, latest.result?.report].some(s => isObject(s) && s.accounting_complete === true);
3242
+ if (hasCapacityEvidence || unknownWithoutExplicitProof) return { settled: false, known_calls: 0, state: null };
3243
+ const part = attemptAccounting(probeContext, id);
3244
+ if (!part.complete || !Number.isSafeInteger(part.total)) return { settled: false, known_calls: 0, state: null };
3245
+ totalCalls += part.total;
3246
+ lastState = latest.state;
3247
+ }
3248
+ return { settled: true, known_calls: totalCalls, state: lastState };
3249
+ }
3250
+ function batchRetentionMs(env = {}) {
3251
+ const raw = env?.PDD_BATCH_RETENTION_DAYS;
3252
+ if (raw !== undefined && raw !== null && String(raw).trim() !== '') {
3253
+ const days = Number(raw);
3254
+ if (Number.isFinite(days)) return days > 0 ? Math.round(days * 86_400_000) : null;
3255
+ }
3256
+ return DEFAULT_BATCH_RETENTION_DAYS * 86_400_000;
3257
+ }
3258
+ function fileFingerprint(path) {
3259
+ try {
3260
+ const st = lstatSync(path, { bigint: true });
3261
+ if (!st.isFile() || st.isSymbolicLink()) return null;
3262
+ return {
3263
+ ino: String(st.ino),
3264
+ size: Number(st.size),
3265
+ mtimeNs: String(st.mtimeNs),
3266
+ ctimeNs: String(st.ctimeNs),
3267
+ mtimeMs: Number(st.mtimeNs / 1_000_000n),
3268
+ };
3269
+ } catch { return null; }
3270
+ }
3271
+ function sameFingerprint(entry, fp) {
3272
+ return isObject(entry) && fp !== null
3273
+ && entry.ino === fp.ino && entry.size === fp.size
3274
+ && entry.mtimeNs === fp.mtimeNs && entry.ctimeNs === fp.ctimeNs;
3275
+ }
3276
+ function readReservationIndex(stateDir) {
3277
+ const empty = { version: 1, last_gc_at: null, batches: {} };
3278
+ try {
3279
+ if (statOrNull(stateDir)?.isSymbolicLink()) return empty;
3280
+ const indexPath = join(stateDir, RESERVATION_INDEX_FILE);
3281
+ const st = statOrNull(indexPath);
3282
+ if (!st?.isFile() || st.isSymbolicLink()) return empty;
3283
+ const parsed = JSON.parse(readFileSync(indexPath, 'utf8'));
3284
+ if (!isObject(parsed) || parsed.version !== 1 || !isObject(parsed.batches)) return empty;
3285
+ return {
3286
+ version: 1,
3287
+ last_gc_at: Number.isFinite(parsed.last_gc_at) ? parsed.last_gc_at : null,
3288
+ batches: { ...parsed.batches },
3289
+ };
3290
+ } catch { return empty; }
3291
+ }
3292
+ function writeReservationIndex(stateDir, index) {
3293
+ try {
3294
+ if (statOrNull(stateDir)?.isSymbolicLink()) return;
3295
+ if (!statOrNull(stateDir)?.isDirectory()) return;
3296
+ const indexPath = join(stateDir, RESERVATION_INDEX_FILE);
3297
+ if (statOrNull(indexPath)?.isSymbolicLink()) return;
3298
+ const temporary = `${indexPath}.${process.pid}.${randomUUID()}.tmp`;
3299
+ const payload = `${JSON.stringify({ version: 1, last_gc_at: index.last_gc_at ?? null, batches: index.batches })}\n`;
3300
+ writeFileSync(temporary, payload, { mode: 0o600 });
3301
+ chmodSync(temporary, 0o600);
3302
+ renameSync(temporary, indexPath);
3303
+ } catch { /* advisory cache; ignore read-only or concurrent write failures */ }
3304
+ }
3305
+ function extractBatchReservationSummary(name, saved, fp) {
3306
+ const base = { ino: fp.ino, size: fp.size, mtimeNs: fp.mtimeNs, ctimeNs: fp.ctimeNs };
3307
+ if (!isObject(saved) || typeof saved.root !== 'string' || !Array.isArray(saved.rows)) {
3308
+ return { ...base, intent: typeof saved?.intent === 'string' ? saved.intent : null, root: null, unresolved: [] };
3309
+ }
3310
+ const intent = typeof saved.intent === 'string' ? saved.intent : null;
3311
+ const resolvedRoot = realish(saved.root);
3312
+ if (intent !== 'check') {
3313
+ return { ...base, intent, root: resolvedRoot, unresolved: [] };
3314
+ }
3315
+ const unresolved = [];
3316
+ for (const row of saved.rows) {
3317
+ if (rowReservationCleared(row)) continue;
3318
+ const ids = Array.isArray(row?.request_ids) ? row.request_ids.filter(id => typeof id === 'string' && id.length > 0) : [];
3319
+ if (!ids.length) continue;
3320
+ const state = row.recovery_state ?? row.state;
3321
+ const openOrUnknown = ['sending', 'queued', 'running', 'unknown'].includes(state) || row.calls === 'unknown' || row.accounting_complete === false;
3322
+ if (!openOrUnknown) continue;
3323
+ unresolved.push({
3324
+ test: typeof row.test === 'string' ? row.test : null,
3325
+ request_ids: ids,
3326
+ max_calls: Number.isSafeInteger(row.max_calls) && row.max_calls >= 1 ? row.max_calls : 0,
3327
+ known_calls: Number.isSafeInteger(row.known_calls) ? row.known_calls : 0,
3328
+ unknown_calls: Number.isSafeInteger(row.unknown_calls) ? row.unknown_calls : 0,
3329
+ ts: reservationTimestampMs(name, saved, row),
3330
+ });
3331
+ }
3332
+ return { ...base, intent: 'check', root: resolvedRoot, unresolved };
3333
+ }
3334
+ function updateBatchReservationIndex(stateDir, batchName, saved) {
3335
+ try {
3336
+ if (!stateDir || !BATCH.test(String(batchName ?? ''))) return;
3337
+ const fp = fileFingerprint(join(stateDir, 'batches', batchName, 'batch.json'));
3338
+ if (!fp) return;
3339
+ const index = readReservationIndex(stateDir);
3340
+ index.batches[batchName] = extractBatchReservationSummary(batchName, saved, fp);
3341
+ writeReservationIndex(stateDir, index);
3342
+ } catch { /* advisory cache */ }
3343
+ }
3344
+ function batchLockIsLive(folder) {
3345
+ const lockPath = join(folder, 'batch.lock');
3346
+ const st = statOrNull(lockPath);
3347
+ if (!st) return false;
3348
+ if (st.isSymbolicLink() || !st.isFile()) return true;
3349
+ try {
3350
+ const info = JSON.parse(readFileSync(lockPath, 'utf8'));
3351
+ if (!Number.isSafeInteger(info?.pid) || info.pid <= 0) return true;
3352
+ if (info.host && info.host !== hostname()) return true;
3353
+ try { process.kill(info.pid, 0); return true; }
3354
+ catch (error) { return error?.code !== 'ESRCH'; }
3355
+ } catch { return true; }
3356
+ }
3357
+ function readProtectedLastBatches(stateDir) {
3358
+ const protectedIds = new Set();
3359
+ const reposDir = join(stateDir, 'repos');
3360
+ if (statOrNull(reposDir)?.isSymbolicLink() || !statOrNull(reposDir)?.isDirectory()) return protectedIds;
3361
+ let files;
3362
+ try { files = readdirSync(reposDir); } catch { return protectedIds; }
3363
+ for (const file of files) {
3364
+ if (!file.endsWith('.json')) continue;
3365
+ const p = join(reposDir, file);
3366
+ const st = statOrNull(p);
3367
+ if (!st?.isFile() || st.isSymbolicLink()) continue;
3368
+ try {
3369
+ const record = JSON.parse(readFileSync(p, 'utf8'));
3370
+ if (typeof record?.last_batch === 'string' && BATCH.test(record.last_batch)) protectedIds.add(record.last_batch);
3371
+ } catch { /* ignore corrupt repo metadata */ }
3372
+ }
3373
+ return protectedIds;
3374
+ }
3375
+ export function pruneOldBatches({ stateDir, env = process.env, now = Date.now(), excludeBatches = [], force = false } = {}) {
3376
+ const result = { pruned: [], skipped_active: 0, skipped_unreconciled: 0, skipped_recent: 0 };
3377
+ const retentionMs = batchRetentionMs(env);
3378
+ if (retentionMs === null) return result;
3379
+ const resolvedState = stateDir || resolve(env.PDD_STATE_DIR || join(env.HOME || homedir(), '.pdd', 'runtime'));
3380
+ if (statOrNull(resolvedState)?.isSymbolicLink()) return result;
3381
+ const dir = join(resolvedState, 'batches');
3382
+ const dirStat = statOrNull(dir);
3383
+ if (!dirStat?.isDirectory() || dirStat.isSymbolicLink()) return result;
3384
+ const index = readReservationIndex(resolvedState);
3385
+ if (!force && Number.isFinite(index.last_gc_at) && Number.isFinite(now) && now - index.last_gc_at < BATCH_GC_INTERVAL_MS) {
3386
+ return result;
3387
+ }
3388
+ let names;
3389
+ try { names = readdirSync(dir); } catch { return result; }
3390
+ const protectedIds = readProtectedLastBatches(resolvedState);
3391
+ for (const id of Array.isArray(excludeBatches) ? excludeBatches : []) if (typeof id === 'string') protectedIds.add(id);
3392
+ const store = new StateStore(resolvedState);
3393
+ const wallClock = Math.abs(now - Date.now()) <= 60_000;
3394
+ for (const name of names.filter(item => typeof item === 'string' && BATCH.test(item)).sort()) {
3395
+ if (protectedIds.has(name)) { result.skipped_active += 1; continue; }
3396
+ const folder = join(dir, name);
3397
+ const folderStat = statOrNull(folder);
3398
+ if (!folderStat?.isDirectory() || folderStat.isSymbolicLink()) continue;
3399
+ const batchTs = batchIdTimestampMs(name);
3400
+ if (batchTs === null || !Number.isFinite(now) || now - batchTs < retentionMs) {
3401
+ result.skipped_recent += 1;
3402
+ continue;
3403
+ }
3404
+ if (batchLockIsLive(folder)) {
3405
+ result.skipped_active += 1;
3406
+ continue;
3407
+ }
3408
+ const fp = fileFingerprint(join(folder, 'batch.json'));
3409
+ if (!fp) continue;
3410
+ if (!force && wallClock && now - fp.mtimeMs < retentionMs) {
3411
+ result.skipped_recent += 1;
3412
+ continue;
3413
+ }
3414
+ let summary = sameFingerprint(index.batches[name], fp) ? index.batches[name] : null;
3415
+ if (!summary) {
3416
+ let saved;
3417
+ try { saved = JSON.parse(readFileSync(join(folder, 'batch.json'), 'utf8')); } catch { continue; }
3418
+ summary = extractBatchReservationSummary(name, saved, fp);
3419
+ index.batches[name] = summary;
3420
+ }
3421
+ if (summary.root === null || !['check', 'lint-only', 'lint'].includes(summary.intent)) continue;
3422
+ if (Array.isArray(summary.unresolved) && summary.unresolved.length > 0) {
3423
+ const allSettled = summary.unresolved.every(row => localRowSettledFromReceipts(store, folder, row.request_ids).settled);
3424
+ if (!allSettled) {
3425
+ result.skipped_unreconciled += 1;
3426
+ continue;
3427
+ }
3428
+ }
3429
+ try {
3430
+ rmSync(folder, { recursive: true, force: true });
3431
+ delete index.batches[name];
3432
+ result.pruned.push(name);
3433
+ } catch { /* ignore concurrent removal or permission error */ }
3434
+ }
3435
+ index.last_gc_at = now;
3436
+ writeReservationIndex(resolvedState, index);
3437
+ return result;
3438
+ }
3439
+ function readUnresolvedPriorReservations(root, env, excludeBatch = null, { now = Date.now(), ttlMs = priorReservationTtlMs(env), includeExpired = false } = {}) {
2807
3440
  const empty = { count: 0, reserved_calls: 0, batches: [] };
2808
3441
  try {
2809
- const wanted = realish(root), dir = join(stateDirectory(env, root), 'batches');
3442
+ const wanted = realish(root), stateDir = stateDirectory(env, root), dir = join(stateDir, 'batches');
3443
+ const store = new StateStore(stateDir);
2810
3444
  let names;
2811
3445
  try { names = readdirSync(dir); } catch { return empty; }
3446
+ const validNames = names.filter(item => typeof item === 'string' && BATCH.test(item)).sort();
3447
+ const validSet = new Set(validNames);
3448
+ const index = readReservationIndex(stateDir);
3449
+ let indexDirty = false;
3450
+ for (const key of Object.keys(index.batches)) {
3451
+ if (!validSet.has(key)) { delete index.batches[key]; indexDirty = true; }
3452
+ }
3453
+ const wallClock = Math.abs(now - Date.now()) <= 60_000;
2812
3454
  let count = 0, reserved_calls = 0;
2813
3455
  const batches = [];
2814
- for (const name of names.filter(item => typeof item === 'string' && BATCH.test(item) && item !== excludeBatch).sort()) {
3456
+ for (const name of validNames) {
3457
+ if (name === excludeBatch) continue;
2815
3458
  const folder = join(dir, name);
2816
- if (!statOrNull(folder)?.isDirectory() || statOrNull(folder)?.isSymbolicLink()) continue;
2817
- let saved;
2818
- try { saved = JSON.parse(readFileSync(join(folder, 'batch.json'), 'utf8')); } catch { continue; }
2819
- if (!isObject(saved) || saved.intent !== 'check' || typeof saved.root !== 'string' || realish(saved.root) !== wanted || !Array.isArray(saved.rows)) continue;
3459
+ const folderStat = statOrNull(folder);
3460
+ if (!folderStat?.isDirectory() || folderStat.isSymbolicLink()) continue;
3461
+ const fp = fileFingerprint(join(folder, 'batch.json'));
3462
+ if (!fp) continue;
3463
+ let summary = sameFingerprint(index.batches[name], fp) ? index.batches[name] : null;
3464
+ if (!summary) {
3465
+ const batchTs = batchIdTimestampMs(name);
3466
+ if (!includeExpired && wallClock && Number.isFinite(now) && Number.isFinite(ttlMs)
3467
+ && batchTs !== null && now - batchTs >= ttlMs && now - fp.mtimeMs >= ttlMs) {
3468
+ continue;
3469
+ }
3470
+ let saved;
3471
+ try { saved = JSON.parse(readFileSync(join(folder, 'batch.json'), 'utf8')); } catch { continue; }
3472
+ summary = extractBatchReservationSummary(name, saved, fp);
3473
+ index.batches[name] = summary;
3474
+ indexDirty = true;
3475
+ }
3476
+ if (summary.intent !== 'check' || summary.root !== wanted || !Array.isArray(summary.unresolved) || !summary.unresolved.length) continue;
2820
3477
  let batchHasUnresolved = false;
2821
- for (const row of saved.rows) {
3478
+ for (const row of summary.unresolved) {
2822
3479
  const ids = Array.isArray(row?.request_ids) ? row.request_ids : [];
2823
3480
  if (!ids.length) continue;
2824
- const state = row.recovery_state ?? row.state;
2825
- const openOrUnknown = ['sending', 'queued', 'running', 'unknown'].includes(state) || row.calls === 'unknown' || row.accounting_complete === false;
2826
- if (!openOrUnknown) continue;
3481
+ if (localRowSettledFromReceipts(store, folder, ids).settled) continue;
3482
+ if (!includeExpired) {
3483
+ const ts = Number.isFinite(row.ts) ? row.ts : batchIdTimestampMs(name);
3484
+ if (ts !== null && Number.isFinite(now) && Number.isFinite(ttlMs) && now - ts >= ttlMs) continue;
3485
+ }
2827
3486
  const key = typeof row.test === 'string' ? createHash('sha256').update(row.test).digest('hex') : null;
2828
3487
  let cap = 0;
2829
3488
  for (let attempt = 0; attempt < ids.length; attempt++) {
@@ -2843,6 +3502,7 @@ function readUnresolvedPriorReservations(root, env, excludeBatch = null) {
2843
3502
  }
2844
3503
  if (batchHasUnresolved) batches.push(name);
2845
3504
  }
3505
+ if (indexDirty) writeReservationIndex(stateDir, index);
2846
3506
  return { count, reserved_calls, batches };
2847
3507
  } catch { return empty; }
2848
3508
  }
@@ -2893,7 +3553,8 @@ function budgetRowsForContext(context, excludePendingRow = null) {
2893
3553
  }
2894
3554
  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
3555
  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);
3556
+ const rowEnd = rowDeadline(context, row);
3557
+ const activeLost = row.state === 'unknown' && row.lost && now < Math.min(rowEnd, row.read_until ?? rowEnd);
2897
3558
  const terminalReceipt = latest && sameJob(latest, id, 'check') && accountingEnd(latest, id);
2898
3559
  const unknownWithoutExplicitProof = latest?.state === 'unknown'
2899
3560
  && ![latest, latest?.usage, latest?.result, latest?.report, latest?.result?.report].some(s => isObject(s) && s.accounting_complete === true);
@@ -2943,11 +3604,30 @@ function applyBudgetDecisionStop(context, row, decision) {
2943
3604
  saveBatch(context);
2944
3605
  }
2945
3606
  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.' };
3607
+ if (context.interrupted) return;
3608
+ const now = context.ports.now();
3609
+ const batchEnd = batchDeadlineOf(context);
3610
+ const overallEnd = context.deadline ?? Infinity;
3611
+ const batchExpired = Number.isFinite(batchEnd) && now >= batchEnd;
3612
+ const overallExpired = Number.isFinite(overallEnd) && now >= overallEnd;
3613
+ for (const row of rows) {
3614
+ if (row.time_limit) continue;
3615
+ const isLint = row === context.lint;
3616
+ const storyEnd = !isLint && Number.isFinite(row.story_deadline) ? row.story_deadline : Infinity;
3617
+ const storyExpired = Number.isFinite(storyEnd) && now >= storyEnd;
3618
+ if (!batchExpired && !overallExpired && !storyExpired) continue;
3619
+ if (['ready', 'waiting', 'sending', 'queued', 'running'].includes(row.state)
3620
+ || row.state === 'unknown' && row.lost || heldForLint(row) || row.busy && row.can_retry) {
3621
+ if (storyExpired && (!batchExpired || storyEnd <= batchEnd)) {
3622
+ row.note = { code: context.timeoutMin != null && !context.agentLimit ? 'timeout-flag' : 'deadline',
3623
+ message: context.timeoutMin != null && !context.agentLimit ? `Stopped waiting at --timeout ${context.timeoutMin} min.` : 'The wait deadline ended.' };
3624
+ } else if (batchExpired && context.explicitBatchTimeout) {
3625
+ row.note = { code: 'timeout-flag', message: `Stopped waiting at --batch-timeout ${context.batchTimeoutMin} min.` };
3626
+ } else {
3627
+ row.note = { code: context.timeoutMin != null && !context.agentLimit ? 'timeout-flag' : 'deadline',
3628
+ message: context.timeoutMin != null && !context.agentLimit ? `Stopped waiting at --timeout ${context.timeoutMin} min.` : 'The wait deadline ended.' };
3629
+ }
3630
+ }
2951
3631
  }
2952
3632
  }
2953
3633
 
@@ -2960,7 +3640,10 @@ function saveBatch(context) {
2960
3640
  if (!row.busy && ['unknown', 'queued', 'running', 'sending'].includes(row.state) && answer && sameJob(answer, id, 'check')
2961
3641
  && ['passed', 'failed', 'refused'].includes(answer.state) && checkCapacity(answer) === null) applyAnswer(row, answer, context);
2962
3642
  }
2963
- context.store.write(join(context.folder, 'batch.json'), batchRecord(context));
3643
+ reconcileStoryCriteria(context.rows, context);
3644
+ const record = batchRecord(context);
3645
+ context.store.write(join(context.folder, 'batch.json'), record);
3646
+ updateBatchReservationIndex(context.store.dir, context.batch, record);
2964
3647
  }
2965
3648
  function saveAnswerAt(store, folder, id, json) {
2966
3649
  if (!isObject(json)) return;
@@ -2986,7 +3669,19 @@ async function postJob(context, path, command, request, row, timeoutMs, deadline
2986
3669
  if (row) delete row.prior_restart_snapshot; // Dispatch is now uncertain; never roll it back.
2987
3670
  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
3671
  saveBatch(context);
2989
- const reply = await context.runtime.post(path, request, context.capture.tar, Math.max(1, Math.min(timeoutMs, deadline - context.ports.now())));
3672
+ const dedup = Boolean(context.serverFeatures?.includes('source-upload-v1'));
3673
+ const pendingChecks = command === 'check'
3674
+ ? (context.rows ?? []).filter(item => !item.unsent && ['ready', 'waiting', 'sending'].includes(item.state)).length
3675
+ : 0;
3676
+ const inlineFirst = (command === 'lint' || (command === 'check' && pendingChecks <= 1))
3677
+ && (!dedup || Buffer.byteLength(JSON.stringify(request), 'utf8') <= 60_000);
3678
+ const reply = await context.runtime.post(
3679
+ path,
3680
+ request,
3681
+ context.capture.tar,
3682
+ Math.max(1, Math.min(timeoutMs, deadline - context.ports.now())),
3683
+ dedup ? { dedup: true, inlineFirst } : undefined,
3684
+ );
2990
3685
  const verdict = judgePost(reply, id, command, context.secrets);
2991
3686
  verdict.observed_at = context.ports.now();
2992
3687
  if (row && verdict.answer && ['queued', 'running', 'passed', 'failed'].includes(outcomeFor(verdict.answer, { kind: 'check' }).state))
@@ -3002,16 +3697,20 @@ async function postJob(context, path, command, request, row, timeoutMs, deadline
3002
3697
 
3003
3698
  // POST one check and fold the answer into its row.
3004
3699
  async function sendCheck(context, row) {
3700
+ if (row.story_deadline === undefined) {
3701
+ row.story_deadline = context.timeoutMin != null ? context.ports.now() + context.timeoutMin * 60_000 : Infinity;
3702
+ }
3703
+ const deadline = rowDeadline(context, row);
3005
3704
  row.admitting = true;
3006
- try { await sendCheckAttempt(context, row); }
3705
+ try { await sendCheckAttempt(context, row, deadline); }
3007
3706
  finally {
3008
3707
  context.preparingDispatches?.delete(row);
3009
- if (!row.awaiting_budget || context.interrupted || context.ports.now() >= context.deadline) restoreReplacement(row);
3708
+ if (!row.awaiting_budget || context.interrupted || context.ports.now() >= deadline) restoreReplacement(row);
3010
3709
  row.budget_in_flight = 0; row.admitting = false;
3011
3710
  }
3012
3711
  }
3013
- async function sendCheckAttempt(context, row) {
3014
- if (context.interrupted || context.ports.now() >= context.deadline || !['ready', 'waiting'].includes(row.state)) return;
3712
+ async function sendCheckAttempt(context, row, deadline = rowDeadline(context, row)) {
3713
+ if (context.interrupted || context.ports.now() >= deadline || !['ready', 'waiting'].includes(row.state)) return;
3015
3714
  if (context.checkOptions && context.checkOptions.samples > row.max_calls) throw new Stop(2, 'samples exceeds this test’s total max_calls allowance.');
3016
3715
  // Recheck the saved raw cohort immediately before any capacity-driven new ID.
3017
3716
  // The one structured restart replacement has its own durable fuse and remains allowed.
@@ -3019,7 +3718,7 @@ async function sendCheckAttempt(context, row) {
3019
3718
  markCapacityUnknown(context, row);
3020
3719
  return;
3021
3720
  }
3022
- if (row.busy && row.request_ids.length && !await capacityReady(context, context.deadline, row)) return;
3721
+ if (row.busy && row.request_ids.length && !await capacityReady(context, deadline, row)) return;
3023
3722
  const candidateForRow = () => ({
3024
3723
  test: row.test,
3025
3724
  kind: row.restart_pending && !row.transient_pending ? 'restart-replacement' : 'initial',
@@ -3039,7 +3738,7 @@ async function sendCheckAttempt(context, row) {
3039
3738
  row.awaiting_budget = false;
3040
3739
  row.budget_in_flight = preDecision.effective_max_calls;
3041
3740
  const attempt = row.request_ids.length, previousCalls = row.restart_used || row.restart_pending ? accumulatedCalls(context, row) : 0;
3042
- if (!await admission(context, 'check', row)) {
3741
+ if (!await admission(context, 'check', row, deadline)) {
3043
3742
  if (context.interrupted && interruptedAdmissions.has(row)) Object.assign(row, { state: 'not_run', calls: previousCalls, phase: 'local', note: { code: null, message: 'Stopped before sending.' } });
3044
3743
  return;
3045
3744
  }
@@ -3052,7 +3751,7 @@ async function sendCheckAttempt(context, row) {
3052
3751
  }
3053
3752
  adoptClaims(context, row);
3054
3753
  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) {
3754
+ if (row.request_ids.length !== attempt || !['ready', 'waiting'].includes(row.state) || context.interrupted || context.ports.now() >= deadline) {
3056
3755
  await finishReservation(context, row, { state: 'not_run' });
3057
3756
  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
3757
  return;
@@ -3118,7 +3817,7 @@ async function sendCheckAttempt(context, row) {
3118
3817
  try { writeSync(fd, JSON.stringify(dispatchClaim)); }
3119
3818
  finally { closeSync(fd); }
3120
3819
  (context.preparingDispatches ??= new WeakMap()).set(row, dispatchClaim);
3121
- if (context.interrupted || context.ports.now() >= context.deadline) {
3820
+ if (context.interrupted || context.ports.now() >= deadline) {
3122
3821
  preserveUnsentReplacement(context, row, path);
3123
3822
  await finishReservation(context, row, { state: 'not_run' });
3124
3823
  adoptClaims(context, row);
@@ -3132,14 +3831,17 @@ async function sendCheckAttempt(context, row) {
3132
3831
  row.sent_at = context.ports.now(); row.ended_at = null; row.retry_at = null; row.busy = false; row.can_retry = false;
3133
3832
  row.busy_request_id = null; row.busy_observed_at = null; row.capacity_until = null; row.busy_display = null;
3134
3833
  row.phase = 'server';
3834
+ const clauseTable = clauseTableForRow(context, row);
3835
+ if (clauseTable) row.clause_table = clauseTable;
3135
3836
  const request = { requestId: id, source_sha256: context.capture.sha256, scenario: row.test, max_calls: effectiveMaxCalls,
3136
3837
  ...(context.freshChecks || context.checkOptions?.fresh ? { fresh: true } : {}),
3137
3838
  ...(context.checkOptions ? { samples: context.checkOptions.samples,
3138
3839
  ...(context.checkOptions.step_ids ? { step_ids: context.checkOptions.step_ids } : {}) } : {}),
3139
3840
  ...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}),
3841
+ ...(clauseTable ? { clause_table: clauseTable } : {}),
3140
3842
  ...sourceProvenance(context) };
3141
3843
  let verdict;
3142
- try { verdict = await context.postCheck(request, row, Math.max(1, Math.min(context.ports.postMs, context.deadline - context.ports.now()))); }
3844
+ try { verdict = await context.postCheck(request, row, Math.max(1, Math.min(context.ports.postMs, deadline - context.ports.now())), deadline); }
3143
3845
  catch (error) {
3144
3846
  // Registration may throw before postJob starts dispatch. Keep the original
3145
3847
  // receipt while this invocation can still prove its exact claim was unsent.
@@ -3159,18 +3861,37 @@ async function sendCheckAttempt(context, row) {
3159
3861
  if (row.request_ids.length > 1 && !capacityRetryAllowed(context, row)) markCapacityUnknown(context, row);
3160
3862
  else markBusy(context, row, verdict.wait, verdict.observed_at);
3161
3863
  }
3162
- else if (verdict.kind === 'not_run') Object.assign(row, { state: 'not_run', note: verdict.note });
3864
+ else if (verdict.kind === 'not_run') {
3865
+ if (verdict.contention) backoffCheckWindow(context, id, verdict.note?.code || 'HTTP 429');
3866
+ Object.assign(row, { state: 'not_run', note: verdict.note });
3867
+ }
3163
3868
  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
3869
  else if (verdict.kind === 'refused') Object.assign(row, { state: 'refused', refusals: [verdict.refusal] });
3165
3870
  // An explicit caller deadline also bounds recovery of a lost POST answer.
3166
3871
  else {
3872
+ const readUntil = Number.isFinite(deadline) ? deadline : context.ports.now() + LOST_READ_MS;
3167
3873
  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;
3874
+ else Object.assign(row, { state: 'unknown', why: verdict.why, lost: true, read_until: readUntil });
3875
+ row.lost = true; row.read_until = readUntil;
3171
3876
  }
3172
3877
  }
3173
3878
 
3879
+ function clauseTableForRow(context, row) {
3880
+ if (!context?.serverFeatures?.includes('clause-citations-v1')) return null;
3881
+ const allClauses = Array.isArray(context?.capture?.clauses) ? context.capture.clauses : [];
3882
+ if (!allClauses.length) return null;
3883
+ const stories = Array.isArray(context?.capture?.stories) ? context.capture.stories : [];
3884
+ const footprint = stories.find(story => Array.isArray(story?.tests) && story.tests.includes(row?.test) && Array.isArray(story?.files));
3885
+ if (footprint) {
3886
+ const promptPaths = new Set(footprint.files.map(file => file?.path).filter(path => typeof path === 'string' && path.endsWith('.prompt.md')));
3887
+ if (promptPaths.size > 0) {
3888
+ const scoped = allClauses.filter(clause => promptPaths.has(clause.path));
3889
+ if (scoped.length) return scoped;
3890
+ }
3891
+ }
3892
+ return allClauses;
3893
+ }
3894
+
3174
3895
  function sourceProvenance(context, capture = context?.capture) {
3175
3896
  if (!context?.serverFeatures?.includes('source-provenance') || typeof capture?.source_commit !== 'string') return {};
3176
3897
  let dirty_files = Array.isArray(capture.dirty_files) ? capture.dirty_files : [];
@@ -3182,10 +3903,12 @@ function sourceProvenance(context, capture = context?.capture) {
3182
3903
 
3183
3904
  // GET one open row once.
3184
3905
  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);
3906
+ const rowEnd = rowDeadline(context, row);
3907
+ const id = row.request_ids.at(-1), end = Math.min(rowEnd, deadline, row.lost ? row.read_until ?? rowEnd : rowEnd);
3186
3908
  if (!id || context.interrupted || context.ports.now() >= end) return;
3187
3909
  const verdict = judgeGet(await context.runtime.get(id, Math.max(1, Math.min(GET_MS, (end ?? Infinity) - context.ports.now()))), id, 'check');
3188
3910
  verdict.observed_at = context.ports.now();
3911
+ if (verdict.kind === 'again' && verdict.contention) backoffCheckWindow(context, `get:${id}:${Math.floor(verdict.observed_at / 5000)}`, 'HTTP 429');
3189
3912
  // A network problem while reading says so once; pdd keeps reading the same IDs.
3190
3913
  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
3914
  if (verdict.kind !== 'again') context.readTrouble = false; else if (verdict.why) context.readTrouble = true;
@@ -3254,6 +3977,7 @@ function lintReceiptTransaction(context, action) {
3254
3977
  function passingLintReceipt(context, answer) {
3255
3978
  return UUID.test(answer?.requestId ?? '') && sameJob(answer, answer.requestId, 'lint') && answer.state === 'passed'
3256
3979
  && (answer.result?.report?.lint?.complete === true || answer.result?.problems_complete === true)
3980
+ && !lintFailClosed(answer)
3257
3981
  && context.rows.length > 0 && context.rows.every(row => !row.unsent && !row.native_only?.length && lintAdmits(answer, row, context.capture));
3258
3982
  }
3259
3983
  function rememberRecentLint(context, answer) {
@@ -3281,9 +4005,11 @@ function readRecentLint(context) {
3281
4005
  // Every lint asks for complete per-test verdicts: only they can admit a test.
3282
4006
  async function runLint(context) {
3283
4007
  const agent = context.agentLimit ?? !context.ports.interactive;
3284
- const lintEnd = context.intent === 'check' && !context.checkDeadlineStarted
4008
+ const batchLintCap = context.batchTimeoutMin != null ? context.startedAt + context.batchTimeoutMin * 60_000 : Infinity;
4009
+ const baseLintEnd = context.intent === 'check' && !context.checkDeadlineStarted
3285
4010
  ? context.timeoutMin ? context.startedAt + Math.min(context.timeoutMin * 60_000, context.ports.interactive ? Infinity : AGENT_WAIT_MIN * 60_000) : Infinity
3286
4011
  : context.batch ? context.deadline : Math.min(context.deadline, agent ? context.startedAt + AGENT_WAIT_MIN * 60_000 : Infinity);
4012
+ const lintEnd = Math.min(baseLintEnd, batchLintCap);
3287
4013
  const tick = progressTicker(context.ports.stderr, context.ports.now);
3288
4014
  let paused = false;
3289
4015
  const stopped = () => ({ kind: 'not_run', note: { code: 'interrupted', message: paused ? stoppedPause(context, context.lint, 'lint')
@@ -3291,9 +4017,10 @@ async function runLint(context) {
3291
4017
  const busy = () => {
3292
4018
  if (context.interrupted) return stopped();
3293
4019
  const ended = context.ports.now() >= lintEnd;
4020
+ const explicitBatch = ended && context.explicitBatchTimeout && lintEnd === batchLintCap;
3294
4021
  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.` };
4022
+ const note = { code: ended ? (explicit || explicitBatch) ? 'timeout-flag' : 'deadline' : 'lint-busy',
4023
+ 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
4024
  Object.assign(context.lint, { state: 'not_run', note });
3298
4025
  return { kind: 'not_run', note };
3299
4026
  };
@@ -3438,7 +4165,8 @@ async function checkBatch(context, rows, priorLint = null) {
3438
4165
  const lint = priorLint ?? await runLint(context);
3439
4166
  if (context.intent === 'check' && !context.checkDeadlineStarted) {
3440
4167
  context.checkDeadlineStarted = true;
3441
- context.deadline = context.timeoutMin ? ports.now() + context.timeoutMin * 60_000 : Infinity;
4168
+ context.batchDeadline = context.batchTimeoutMin != null ? ports.now() + context.batchTimeoutMin * 60_000 : Infinity;
4169
+ context.deadline = context.batchDeadline;
3442
4170
  }
3443
4171
  context.lastCheckLint = lint;
3444
4172
  context.lint.state = lint.answer?.state ?? lint.kind;
@@ -3463,8 +4191,11 @@ async function checkBatch(context, rows, priorLint = null) {
3463
4191
  for (const [row, outcome] of verdicts) if (outcome.state !== 'passed') notSent(...unsentByLint(outcome), row);
3464
4192
  const refused = sendable.filter(row => row.state === 'refused').length, held = sendable.length - toSend.length - refused;
3465
4193
  context.lintUnknown = context.lint.unknown = [...verdicts.values()].some(outcome => outcome.state === 'unknown');
3466
- if (!toSend.length && !refused) return;
3467
- if (toSend.length) lintDiagnostics(context, lint.answer, sendable);
4194
+ if (!toSend.length && !refused) {
4195
+ lintDiagnostics(context, lint.answer, sendable);
4196
+ return;
4197
+ }
4198
+ lintDiagnostics(context, lint.answer, sendable);
3468
4199
  const judged = toSend.length === sendable.length ? 'Lint passed.' : [refused ? `Lint refused ${refused} of ${sendable.length} tests.` : '',
3469
4200
  held ? `Lint gave no verdict for ${held} of ${sendable.length} tests.` : ''].filter(Boolean).join(' ');
3470
4201
  line(ports.stderr, judged);
@@ -3479,18 +4210,30 @@ async function runScheduledChecks(context, rows, toSend) {
3479
4210
  // Saved live-local observations may poll original IDs, but cannot admit work.
3480
4211
  if (context.liveLocalSaved) toSend = [];
3481
4212
  const { ports } = context;
3482
- context.checkWindow ??= localLimit(context);
4213
+ ensureConcurrencyState(context);
3483
4214
  for (const row of toSend) row.attempts = 0;
4215
+ if (context.timeoutMin != null) {
4216
+ const startNow = ports.now();
4217
+ for (const row of rows) {
4218
+ if (isOpen(row) && row.story_deadline === undefined) {
4219
+ row.story_deadline = startNow + context.timeoutMin * 60_000;
4220
+ }
4221
+ }
4222
+ }
3484
4223
  const pendingSends = new Map(), uploads = uploadLimit(context);
3485
4224
  // Refill on a POST's settlement even while the polling loop awaits GETs.
3486
4225
  // Waiting rows stay outside admission and dispatch-claim allocation.
3487
4226
  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;
4227
+ const now = ports.now();
4228
+ if (context.liveLocalSaved || context.interrupted || context.readStop || context.stopped || context.sendError || now >= batchDeadlineOf(context)) return;
4229
+ const active = rows.filter(row => occupiesSlot(row) && !rowExpired(context, row, now)).length;
3490
4230
  const available = Math.max(0, Math.min(uploads - pendingSends.size, context.checkWindow - active - pendingSends.size));
3491
4231
  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));
4232
+ && !rowExpired(context, row, now) && (!row.retry_at || now >= row.retry_at));
3493
4233
  for (const row of eligible.slice(0, available)) {
4234
+ if (row.story_deadline === undefined) {
4235
+ row.story_deadline = context.timeoutMin != null ? now + context.timeoutMin * 60_000 : Infinity;
4236
+ }
3494
4237
  const pending = sendCheck(context, row).catch(error => { context.sendError ??= error; }).finally(() => {
3495
4238
  pendingSends.delete(row);
3496
4239
  if (!row.awaiting_budget) {
@@ -3504,9 +4247,15 @@ async function runScheduledChecks(context, rows, toSend) {
3504
4247
  let waitingShown = -1;
3505
4248
  const progress = context.checkProgress ??= { startedAt: ports.now(), shownAt: ports.now() };
3506
4249
  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);
4250
+ const readable = row => {
4251
+ if (!isOpen(row)) return false;
4252
+ const rowEnd = rowDeadline(context, row);
4253
+ const end = Math.min(rowEnd, row.lost ? row.read_until ?? rowEnd : rowEnd);
4254
+ return ports.now() < end;
4255
+ };
3508
4256
  const sseEnabled = !ports.pollMsExplicit && Boolean(context.serverFeatures?.includes('sse-stream-v1'));
3509
4257
  const activeStreams = new Map();
4258
+ const sseBackoff = new WeakMap();
3510
4259
  let wakeResolve = null;
3511
4260
  const notifyWake = () => { if (wakeResolve) { const fn = wakeResolve; wakeResolve = null; fn(); } };
3512
4261
  const formatStageEvent = (row, json) => {
@@ -3517,11 +4266,25 @@ async function runScheduledChecks(context, rows, toSend) {
3517
4266
  : typeof p.step === 'string' && p.step ? p.step : stage;
3518
4267
  return `${row.test}: ${stepPart}`;
3519
4268
  };
4269
+ const abortExpiredStreams = () => {
4270
+ for (const [row, entry] of activeStreams) {
4271
+ if (!readable(row)) {
4272
+ entry.controller.abort();
4273
+ activeStreams.delete(row);
4274
+ }
4275
+ }
4276
+ };
3520
4277
  const syncRowStreams = () => {
4278
+ abortExpiredStreams();
3521
4279
  if (!sseEnabled || context.interrupted || context.readStop) return;
4280
+ const now = ports.now();
3522
4281
  for (const row of rows.filter(readable)) {
4282
+ // Do not open SSE streams for unconfirmed lost-POST rows; poll via readRow until confirmed open.
4283
+ if (row.lost) continue;
3523
4284
  const id = row.request_ids.at(-1);
3524
4285
  if (!id) continue;
4286
+ const backoff = sseBackoff.get(row);
4287
+ if (backoff && backoff.id === id && now < backoff.retryAt) continue;
3525
4288
  const existing = activeStreams.get(row);
3526
4289
  if (existing && existing.id === id) continue;
3527
4290
  if (existing) { existing.controller.abort(); activeStreams.delete(row); }
@@ -3529,8 +4292,10 @@ async function runScheduledChecks(context, rows, toSend) {
3529
4292
  const controller = new AbortController();
3530
4293
  const onSignal = () => controller.abort();
3531
4294
  context.signal?.addEventListener('abort', onSignal, { once: true });
3532
- const end = Math.min(context.deadline, row.lost ? row.read_until ?? context.deadline : context.deadline);
4295
+ const rowEnd = rowDeadline(context, row);
4296
+ const end = Math.min(rowEnd, row.lost ? row.read_until ?? rowEnd : rowEnd);
3533
4297
  let lastStageKey = '';
4298
+ let receivedEvent = false;
3534
4299
  const entry = { id, controller };
3535
4300
  activeStreams.set(row, entry);
3536
4301
  entry.promise = context.runtime.streamRun(id, {
@@ -3539,6 +4304,8 @@ async function runScheduledChecks(context, rows, toSend) {
3539
4304
  timeoutMs: Math.max(1, end - ports.now()),
3540
4305
  onEvent: ({ event, json }) => {
3541
4306
  if (!isObject(json) || !sameJob(json, id, 'check')) return false;
4307
+ receivedEvent = true;
4308
+ sseBackoff.delete(row);
3542
4309
  const enriched = (typeof json.stage === 'string' && json.stage && json.state === 'running')
3543
4310
  ? { ...json, progress: { ...(isObject(json.progress) ? json.progress : {}), stage: json.stage } }
3544
4311
  : json;
@@ -3566,18 +4333,43 @@ async function runScheduledChecks(context, rows, toSend) {
3566
4333
  }
3567
4334
  return false;
3568
4335
  },
3569
- }).catch(() => null).finally(() => {
4336
+ }).then(result => {
4337
+ if (result?.status === 429) {
4338
+ backoffCheckWindow(context, `sse:${id}:${Math.floor(ports.now() / 5000)}`, 'HTTP 429');
4339
+ }
4340
+ const failed = !receivedEvent && (!result?.streamed || !result?.completed);
4341
+ if (failed && !controller.signal.aborted && !context.interrupted) {
4342
+ const prev = sseBackoff.get(row);
4343
+ const failures = (prev && prev.id === id ? prev.failures : 0) + 1;
4344
+ const wait = [429, 503].includes(result?.status)
4345
+ ? retryAfter(result.headers)
4346
+ : Math.min(30_000, 2_000 * 2 ** Math.min(failures - 1, 4));
4347
+ sseBackoff.set(row, { id, failures, retryAt: ports.now() + wait });
4348
+ }
4349
+ return { failed };
4350
+ }).catch(() => {
4351
+ if (!controller.signal.aborted && !context.interrupted) {
4352
+ const prev = sseBackoff.get(row);
4353
+ const failures = (prev && prev.id === id ? prev.failures : 0) + 1;
4354
+ sseBackoff.set(row, { id, failures, retryAt: ports.now() + Math.min(30_000, 2_000 * 2 ** Math.min(failures - 1, 4)) });
4355
+ }
4356
+ return { failed: true };
4357
+ }).then(({ failed }) => {
3570
4358
  context.signal?.removeEventListener('abort', onSignal);
3571
4359
  if (activeStreams.get(row) === entry) activeStreams.delete(row);
3572
- notifyWake();
4360
+ // Only wake the loop immediately when the stream produced a real event/completion;
4361
+ // a rejected/404/429 stream falls back to normal pollDelay without busy-looping.
4362
+ if (!failed || receivedEvent) notifyWake();
3573
4363
  });
3574
4364
  }
3575
4365
  };
3576
4366
  try {
3577
4367
  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) {
4368
+ abortExpiredStreams();
4369
+ // Never count an uncertain dispatched job as a free slot while active within its deadline.
4370
+ const now = ports.now();
4371
+ const active = rows.filter(row => occupiesSlot(row) && !rowExpired(context, row, now)).length;
4372
+ if (!context.stopped && now < batchDeadlineOf(context) && active < context.checkWindow) {
3581
4373
  pumpSends();
3582
4374
  // Admission can wait while previously dispatched rows continue to be read.
3583
4375
  if (!active && pendingSends.size) await Promise.race(pendingSends.values());
@@ -3585,7 +4377,7 @@ async function runScheduledChecks(context, rows, toSend) {
3585
4377
  saveBatch(context);
3586
4378
  }
3587
4379
  if (context.blocked && !rows.some(isOpen)) throw new Stop(5, context.blocked);
3588
- const waiting = toSend.filter(row => row.state === 'waiting');
4380
+ const waiting = toSend.filter(row => row.state === 'waiting' && !rowExpired(context, row));
3589
4381
  if (waiting.length !== waitingShown) {
3590
4382
  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
4383
  waitingShown = waiting.length;
@@ -3594,14 +4386,27 @@ async function runScheduledChecks(context, rows, toSend) {
3594
4386
  const earlyRestarts = await recoverRestarts(context);
3595
4387
  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
4388
  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)); }
4389
+ const loopNow = ports.now();
4390
+ const activeAfter = rows.filter(row => occupiesSlot(row) && !rowExpired(context, row, loopNow)).length;
4391
+ const pending = toSend.some(row => ['ready', 'waiting'].includes(row.state) && !rowExpired(context, row, loopNow));
4392
+ if (pending && activeAfter >= context.checkWindow && !rows.some(readable) && !pendingSends.size) break;
4393
+ if ((!pending || context.stopped || loopNow >= batchDeadlineOf(context)) && !rows.some(readable) && !pendingSends.size) break;
4394
+ if (loopNow - progress.shownAt >= PROGRESS_MS) { progress.shownAt = loopNow; line(ports.stderr, progressLine(rows, progress.shownAt - progress.startedAt)); }
3601
4395
  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()));
4396
+ const deadlines = [batchDeadlineOf(context)];
4397
+ for (const row of rows) {
4398
+ if (readable(row)) {
4399
+ const rowEnd = rowDeadline(context, row);
4400
+ deadlines.push(Math.min(rowEnd, row.lost ? row.read_until ?? rowEnd : rowEnd));
4401
+ } else if (['ready', 'waiting'].includes(row.state) && !rowExpired(context, row, loopNow)) {
4402
+ deadlines.push(rowDeadline(context, row));
4403
+ }
4404
+ }
4405
+ const end = Math.min(...deadlines);
4406
+ const delay = ports.pollDelay(loopNow - pollStartedAt);
4407
+ const hasUnstreamed = rows.some(row => readable(row) && !activeStreams.has(row));
4408
+ const cadence = activeStreams.size && !hasUnstreamed ? PROGRESS_MS : delay;
4409
+ const waitMs = Math.max(0, Math.min(cadence, end - loopNow));
3605
4410
  if (activeStreams.size) {
3606
4411
  const wake = new Promise(resolve => { wakeResolve = resolve; });
3607
4412
  await Promise.race([ports.sleep(waitMs, context.signal), wake]);
@@ -3624,15 +4429,16 @@ async function runScheduledChecks(context, rows, toSend) {
3624
4429
  }
3625
4430
  if (context.sendError) throw context.sendError;
3626
4431
  const stoppedEarly = context.interrupted || !!context.readStop;
3627
- context.timedOut ||= !stoppedEarly && ports.now() >= context.deadline && rows.some(isOpen);
4432
+ context.timedOut ||= !stoppedEarly && rows.some(row => isOpen(row) && rowExpired(context, row));
3628
4433
  for (const row of toSend) {
3629
4434
  restoreReplacement(row); // A budget-held replacement may never have reached sendCheck.
3630
4435
  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
4436
  phase: row.request_ids.length ? 'server' : 'local', note: { code: 'check-busy', message: context.interrupted && row.busy && row.request_ids.length
3632
4437
  ? stoppedPause(context, row, 'check') : row.request_ids.length
3633
4438
  ? '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.' } });
4439
+ const rowEnd = rowDeadline(context, row);
3634
4440
  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.';
4441
+ : 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
4442
  }
3637
4443
  }
3638
4444
 
@@ -3653,6 +4459,7 @@ function printResult(context, rows, extra = {}) {
3653
4459
  return printLintResult(context, rows, lintProblems(context, answer), context.warnings ?? [], answer);
3654
4460
  }
3655
4461
  markDeadline(context, rows);
4462
+ reconcileStoryCriteria(rows, context);
3656
4463
  rows = rows.map(row => heldForLint(row) && !row.dispatchIncomplete ? { ...row, calls: 0 } : row);
3657
4464
  const { ports } = context, exitCode = context.localOnly && context.checkPlan?.full && context.checkPlan.prerequisites.length ? 4
3658
4465
  : ports.exitCodeFor(rows, { interrupted: context.interrupted, lintUnknown: context.lintUnknown || context.lintPending });
@@ -3686,7 +4493,7 @@ function printResult(context, rows, extra = {}) {
3686
4493
  if (context.stopped && (!context.json || context.stopped.message === AUTH_TEXT)) line(ports.stderr, context.stopped.message);
3687
4494
  const scrub = text => (context.secrets ?? []).reduce((value, secret) => secret ? value.split(secret).join('[secret]') : value, text);
3688
4495
  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,
4496
+ else ports.stdout.write(scrub(renderText({ batch: context.batch, rows, coverage: context.coverage, warnings, details: context.details, timeoutMin: context.timeoutMin, batchTimeoutMin: context.batchTimeoutMin,
3690
4497
  now: ports.now(), noFailed: context.noFailed, interrupted: context.interrupted || !!context.readStop, reading: !!context.reading, exitCode, secrets: context.secrets, ...extra }, ports)));
3691
4498
  if (!context.json && summary.report_url) line(ports.stdout, `Report: ${summary.report_url}`);
3692
4499
  if (!context.json) for (const value of checkPlanResultLines(summary.check_scope)) line(ports.stdout, scrub(value));
@@ -3729,11 +4536,11 @@ function runFiles(cwd, words, options, ports) {
3729
4536
  const appMap = options['--app-map'] === undefined ? null : appMapFor(found, options['--app-map'], cwd, root, ports.stderr);
3730
4537
  for (const path of found.excludedFixtureProjects ?? []) line(ports.stderr, `Warning: skipped nested fixture project ${path}.`);
3731
4538
  const capture = captureIndependent(root, rows, ports, {appMap,excludeFixtureProjects:words.length === 0,allowMissingInterfaces:true})
3732
- ?? {files:[],reads:[],bytes:0};
4539
+ ?? {files:[],reads:[],bytes:0,clauses:[]};
3733
4540
  const broken = rows.filter(row => row.unsent && row.refusals.length), exitCode = broken.length ? 4 : 0;
3734
4541
  const summary = `${capture.files.length} files, ${formatSize(capture.bytes)} (${capture.bytes} bytes). ${otherFiles(capture.files, found).length} of them are not prompt, story or test files.${broken.length ? ` ${broken.length} tests could not run.` : ''}`;
3735
4542
  if (options['--json']) {
3736
- line(ports.stdout, JSON.stringify({repo:root,exit_code:exitCode,summary_line:summary,source_sha256:capture.sha256 ?? null,rows:[...rows.filter(row=>row.unsent).map(row=>({...row,...resultOutcome(row)})),...rows.filter(row=>!row.unsent)],files:capture.files,coverage,...(advice.length ? {warnings:advice} : {})}));
4543
+ line(ports.stdout, JSON.stringify({repo:root,exit_code:exitCode,summary_line:summary,source_sha256:capture.sha256 ?? null,rows:[...rows.filter(row=>row.unsent).map(row=>({...row,...resultOutcome(row)})),...rows.filter(row=>!row.unsent)],files:capture.files,clauses:capture.clauses ?? [],coverage,...(advice.length ? {warnings:advice} : {})}));
3737
4544
  return exitCode;
3738
4545
  }
3739
4546
  for (const row of broken) for (const problem of row.refusals) {
@@ -3814,7 +4621,7 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
3814
4621
  const activeLocalProblem = problem => localInterfaceProblem(problem) && !(allowMissingInterfaces && problem.code === 'interface-missing');
3815
4622
  context.coverage = bindingCoverage({ root, found, selected, includeRuntime:true, allowMissingInterfaces });
3816
4623
  // 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',
4624
+ const rows = selected.map(test => ({ test: test.path, story: test.story, story_path: test.storyPath, title: test.title, state: 'ready', phase: 'lint',
3818
4625
  refusals: [], request_ids: [], warnings: [], steps: Array.isArray(test.doc?.steps) ? test.doc.steps.filter(isObject) : [],
3819
4626
  app_maps: declaredMaps(test.doc),
3820
4627
  criterion_texts: Object.fromEntries((Array.isArray(test.doc?.criteria) ? test.doc.criteria : []).filter(isObject).map(item => [item.id, item.text])),
@@ -3886,7 +4693,12 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
3886
4693
  // Lint keeps engine validation ownership; only attach structural incomplete-coverage facts.
3887
4694
  for (const row of rows.filter(row => !row.unsent)) {
3888
4695
  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});
4696
+ if (checked.not_checked?.length) Object.assign(row, {
4697
+ not_checked:checked.not_checked,
4698
+ own_not_checked:checked.not_checked.map(item=>({...item})),
4699
+ criteria_total:checked.criteria_total,
4700
+ criterion_texts:{...(row.criterion_texts ?? {}),...Object.fromEntries(checked.not_checked.map(item=>[item.criterion_id,item.text]))},
4701
+ });
3890
4702
  if (checked.refusals.some(item=>item.code==='unchecked-criteria')) Object.assign(row,
3891
4703
  {state:'refused',phase:'local',unsent:true,refusals:checked.refusals});
3892
4704
  }
@@ -3964,6 +4776,7 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
3964
4776
  : { state: outcome.state, refusals: outcome.refusals, ...(outcome.reason ? { note: { code: outcome.code || 'no-server-verdict', message: outcome.reason } } : {}) });
3965
4777
  incompleteCriteria(row);
3966
4778
  }
4779
+ reconcileStoryCriteria(rows, context);
3967
4780
  Object.assign(context.lint, { state: answer?.state ?? lint.kind, unknown: rows.some(row => row.state === 'unknown'), pending: false, public_result: resultOverall(rows) });
3968
4781
  saveBatch(context);
3969
4782
  return printLintResult(context, rows, problems, found.warnings, answer);
@@ -3989,34 +4802,119 @@ function lintProblems(context, answer, refusal = null) {
3989
4802
  section: cleanText(item.section, context.secrets) || null, message: cleanText(item.message, context.secrets) || null, hint: null }, item, context.root, context.secrets);
3990
4803
  if (!problems.some(p => p.code === problem.code && p.path === problem.path && p.section === problem.section)) problems.push(problem);
3991
4804
  }
4805
+ const topRefusals = [
4806
+ ...(Array.isArray(answer?.result?.refusals) ? answer.result.refusals.filter(isObject) : []),
4807
+ ...(isObject(answer?.result?.report?.refusal) ? [answer.result.report.refusal] : []),
4808
+ ];
4809
+ for (const item of topRefusals) {
4810
+ const code = cleanText(item.code, context.secrets) || 'lint-refused';
4811
+ if (code === 'lint-refused') continue;
4812
+ const reason = cleanText(item.reason, context.secrets), fix = cleanText(item.fix, context.secrets);
4813
+ const problem = interfaceDiagnostic({ code, path: cleanText(item.file ?? item.path, context.secrets) || null,
4814
+ section: cleanText(item.at ?? item.section, context.secrets) || null,
4815
+ message: cleanText(item.message, context.secrets) || [reason, fix].filter(Boolean).join(' ') || null, hint: null,
4816
+ severity: cleanText(item.severity, context.secrets) || 'error' }, item, context.root, context.secrets);
4817
+ if (!problems.some(p => p.code === problem.code && p.path === problem.path && p.section === problem.section)) problems.push(problem);
4818
+ }
3992
4819
  return problems;
3993
4820
  }
3994
4821
 
3995
4822
  function printLintResult(context, rows, problems, warnings = [], answer = null) {
3996
4823
  const { ports, batch, root } = context;
4824
+ const remoteProblems = [...problems];
3997
4825
  problems = [...problems];
3998
4826
  for (const row of rows) {
3999
4827
  const listed = [answer?.result?.tests, answer?.result?.report?.lint?.tests].find(items => Array.isArray(items) && items.some(item => item?.path === row.test));
4000
4828
  const matching = (listed ?? []).filter(item => item?.path === row.test);
4001
4829
  row.call_preflight = matching.length === 1 ? matching[0].call_preflight ?? null : null;
4002
4830
  }
4003
- rows.forEach(incompleteCriteria);
4831
+ reconcileStoryCriteria(rows, context);
4004
4832
  rows = [...rows.filter(row=>row.unsent),...rows.filter(row=>!row.unsent)];
4005
4833
  for (const row of rows) for (const problem of row.refusals ?? []) {
4006
4834
  // pdd's own per-test words stay on the row; every server or reached-prompt problem is listed once.
4007
4835
  if (problem.code === 'lint-refused' && !problem.path) continue;
4008
4836
  if (!problems.some(item => item.code === problem.code && (item.path ?? null) === (problem.path ?? null))) problems.push({ ...problem, path: problem.path ?? null, section: null });
4009
4837
  }
4838
+ const reportedCoverage = (answer?.result?.capabilities_complete === false || answer?.result?.report?.lint?.capabilities_complete === false)
4839
+ ? false
4840
+ : (answer?.result?.capabilities_complete ?? answer?.result?.report?.lint?.capabilities_complete);
4841
+ const capabilityCoverage = typeof reportedCoverage === 'boolean' ? reportedCoverage : null;
4842
+ const answerFailClosed = answer ? lintFailClosed(answer, remoteProblems) : null;
4843
+ const hasRemoteBlockingProblems = remoteProblems.some(item => item.severity !== 'warning');
4844
+ const hasLintIncompleteProblem = remoteProblems.some(item => item.code === 'lint-incomplete');
4010
4845
  const localRefusal = context.localOnly && (problems.some(item => item.severity !== 'warning') || rows.some(row => row.state === 'refused'));
4011
- const passing = rows.filter(row => row.state === 'passed').length, lintState = outcomeOverall(rows), exitCode = localRefusal ? 4 : context.ports.exitCodeFor(rows);
4846
+ const refusalCode = cleanText(answerFailClosed?.code ?? remoteProblems.find(item => item.severity !== 'warning')?.code, context.secrets) || 'lint-refused';
4847
+ const refusalMessage = cleanText(answerFailClosed?.message ?? remoteProblems.find(item => item.severity !== 'warning')?.message, context.secrets) || 'The interpreter refused lint.';
4848
+ const incompleteCode = cleanText(answerFailClosed?.code ?? 'lint-incomplete', context.secrets) || 'lint-incomplete';
4849
+ const incompleteMessage = cleanText(answerFailClosed?.message, context.secrets) || 'Lint did not finish. No pass was established.';
4850
+ let overrodePassingRows = false;
4851
+ let overrodeToRefused = false;
4852
+ let overrodeToIncomplete = false;
4853
+ if (answer) {
4854
+ const reachedChecked = Array.isArray(answer?.result?.report?.program?.prompts) || Array.isArray(answer?.result?.report?.program?.refused_prompts);
4855
+ rows = rows.map(row => {
4856
+ if (row.state !== 'passed') return row;
4857
+ const rowFail = lintFailClosed(answer, remoteProblems, {
4858
+ test: row.test,
4859
+ applicableMaps: Array.isArray(row.app_maps) ? row.app_maps : undefined,
4860
+ testPassed: true,
4861
+ reachedChecked,
4862
+ });
4863
+ if (!rowFail) return row;
4864
+ overrodePassingRows = true;
4865
+ if (rowFail.kind === 'refused') {
4866
+ overrodeToRefused = true;
4867
+ const code = cleanText(rowFail.code, context.secrets) || refusalCode;
4868
+ const message = cleanText(rowFail.message, context.secrets) || refusalMessage;
4869
+ return { ...row, state: 'refused', refusals: row.refusals?.length ? row.refusals : [{ code, message }] };
4870
+ }
4871
+ overrodeToIncomplete = true;
4872
+ const code = cleanText(rowFail.code, context.secrets) || incompleteCode;
4873
+ const message = cleanText(rowFail.message, context.secrets) || incompleteMessage;
4874
+ return { ...row, state: 'not_run', note: row.note ?? { code, message } };
4875
+ });
4876
+ }
4877
+ const hasPassingRow = rows.some(row => row.state === 'passed');
4878
+ const allRowsPassed = rows.length > 0 && rows.every(row => row.state === 'passed');
4879
+ const applicableMapSet = new Set(rows.flatMap(row => Array.isArray(row.app_maps) ? row.app_maps : []));
4880
+ const answerAppMaps = new Set([
4881
+ ...(Array.isArray(answer?.result?.app_maps) ? answer.result.app_maps : []),
4882
+ ...(Array.isArray(answer?.result?.report?.lint?.app_maps) ? answer.result.report.lint.app_maps : []),
4883
+ ].map(item => item?.path).filter(p => typeof p === 'string' && p.length > 0));
4884
+ const onlyNonApplicableAppMapRefusals = allRowsPassed
4885
+ && answerAppMaps.size > 0
4886
+ && (answerFailClosed?.refusals?.length ?? 0) > 0
4887
+ && answerFailClosed.refusals.every(item => {
4888
+ const target = item?.file ?? item?.path ?? null;
4889
+ return typeof target === 'string' && answerAppMaps.has(target) && !applicableMapSet.has(target);
4890
+ });
4891
+ const remoteRefusal = Boolean(answer) && !onlyNonApplicableAppMapRefusals && (overrodeToRefused
4892
+ || ((!hasPassingRow || allRowsPassed) && (answerFailClosed?.kind === 'refused' || (!context.localOnly && hasRemoteBlockingProblems))));
4893
+ const remoteIncomplete = Boolean(answer) && !remoteRefusal && (overrodeToIncomplete || (!hasPassingRow && (answerFailClosed?.kind === 'incomplete' || hasLintIncompleteProblem)));
4894
+ const failClosedRefusal = localRefusal || remoteRefusal;
4895
+ const baseExitCode = context.ports.exitCodeFor(rows);
4896
+ const exitCode = localRefusal ? 4 : remoteRefusal ? (baseExitCode === 5 && rows.some(row => row.state === 'not_run' && !overrodeToIncomplete) ? 5 : 4) : remoteIncomplete ? (baseExitCode === 4 ? 4 : 5) : baseExitCode;
4897
+ let overall = resultOverall(rows);
4898
+ if (remoteRefusal && overall.state !== 'refused') {
4899
+ overall = { state: 'refused', reason: { code: refusalCode, message: refusalMessage } };
4900
+ } else if (remoteIncomplete && overall.state === 'passed') {
4901
+ overall = { state: 'not run', reason: { code: incompleteCode, message: incompleteMessage } };
4902
+ }
4903
+ const passing = (failClosedRefusal || remoteIncomplete) ? 0 : rows.filter(row => row.state === 'passed').length;
4012
4904
  const omitted = rows.filter(row=>row.native_only?.length && !row.refusals?.length).length;
4013
4905
  const broken = rows.filter(row=>row.unsent && (!row.native_only?.length || row.refusals?.length)).length, unchecked = rows.reduce((n,row)=>n+(row.not_checked?.length??0),0);
4014
- const summary = `Lint: ${passing} of ${rows.length} tests pass.${broken ? ` ${broken} tests could not run.` : ''}${omitted ? ` ${omitted} native-only tests omitted.` : ''}${unchecked ? ` ${unchecked} criteria not checked. The Story is not a full pass.` : ''} 0 AI calls. No checks were sent.`;
4015
- const reportedCoverage = answer?.result?.capabilities_complete ?? answer?.result?.report?.lint?.capabilities_complete;
4016
- const capabilityCoverage = typeof reportedCoverage === 'boolean' ? reportedCoverage : null;
4906
+ const contradictoryPassed = answer?.result?.passed === true || answer?.result?.report?.passed === true;
4907
+ const allRowsHaveSpecificRefusal = rows.length > 0 && rows.every(row => row.refusals?.some(r =>
4908
+ r.path && (r.path === row.test || (row.app_maps ?? []).includes(r.path) || r.reached)));
4909
+ const summaryPrefix = remoteRefusal && (overrodePassingRows || contradictoryPassed || answerFailClosed?.lintIncomplete || answerFailClosed?.capabilitiesIncomplete || (answerFailClosed?.answerRefused && !allRowsHaveSpecificRefusal))
4910
+ ? `Lint refused (${refusalCode}):`
4911
+ : remoteIncomplete
4912
+ ? `Lint incomplete (${incompleteCode}):`
4913
+ : 'Lint:';
4914
+ const summary = `${summaryPrefix} ${passing} of ${rows.length} tests pass.${broken ? ` ${broken} tests could not run.` : ''}${omitted ? ` ${omitted} native-only tests omitted.` : ''}${unchecked ? ` ${unchecked} criteria not checked. The Story is not a full pass.` : ''} 0 AI calls. No checks were sent.`;
4017
4915
  const reportUrl = validLink(cleanText(answer?.report_url, context.secrets), context.origin, 'report');
4018
4916
  const maintenance = activeMaintenance(context);
4019
- const result = { batch, repo: root, exit_code: exitCode, lint_state: resultOverall(rows).state, ...resultOverall(rows), ...(maintenance ? { maintenance, retry_after: maintenance.retry_after } : {}), report_url: reportUrl, summary_line: summary, capabilities_complete: capabilityCoverage, coverage: context.coverage, problems,
4917
+ const result = { batch, repo: root, exit_code: exitCode, lint_state: overall.state, ...overall, ...(maintenance ? { maintenance, retry_after: maintenance.retry_after } : {}), report_url: reportUrl, summary_line: summary, capabilities_complete: capabilityCoverage, coverage: context.coverage, problems,
4020
4918
  rows: rows.map(row => ({ story: row.story, title: row.title, test: row.test, ...(row.native_only?.length ? {native_only:row.native_only,note:row.note} : {}), ...resultOutcome(row), refusals: row.refusals, ...(row.unsent?{unsent:true}:{}), ...(row.not_checked?.length?{not_checked:row.not_checked}:{}), call_preflight: row.call_preflight ?? null, binding_plan: row.binding_plan, ...(row.binding_plan?{binding_diagnostics:bindingRefusals(row.binding_plan,row.compatibility)}:{}), compatibility: row.compatibility, client_advice: row.client_advice })), warnings: [...new Set([...(context.warnings ?? []), ...(context.unmatched ?? [])])] };
4021
4919
  result.call_preflight_context = answer?.result?.call_preflight_context ?? answer?.result?.report?.lint?.call_preflight_context ?? null;
4022
4920
  result.call_preflight_requested_cap = context.lint?.selected_cap ?? null;
@@ -4134,6 +5032,7 @@ async function readUnsentLint(context, rows) {
4134
5032
  incompleteCriteria(row);
4135
5033
  if (!busy && outcome.state === 'unknown') context.lintUnknown = lint.unknown = true;
4136
5034
  }
5035
+ reconcileStoryCriteria(rows, context);
4137
5036
  lint.public_result = resultOverall([...judged.values()]);
4138
5037
  }
4139
5038
 
@@ -4230,8 +5129,12 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
4230
5129
  context.cacheReadInvocation = true;
4231
5130
  const { store, ports, root } = context;
4232
5131
  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;
5132
+ const timeout = options['--timeout'] === undefined ? quiet ? AGENT_WAIT_MIN : null : parseTimeoutMinutes(options['--timeout'], '--timeout', { allowZero: true });
5133
+ const batchTimeout = parseTimeoutMinutes(options['--batch-timeout'], '--batch-timeout', { allowZero: true });
5134
+ const readStart = ports.now();
5135
+ context.batchTimeoutMin = batchTimeout;
5136
+ context.batchDeadline ??= batchTimeout === null ? Infinity : readStart + batchTimeout * 60_000;
5137
+ context.deadline ??= timeout === null ? context.batchDeadline : Math.min(context.batchDeadline, readStart + timeout * 60_000);
4235
5138
  context.timeoutMin = timeout; context.agentLimit = false;
4236
5139
  const name = batchWord ?? store.read(join(store.dir,'repos',`${store.repoKey(root)}.json`))?.last_batch;
4237
5140
  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,8 +5175,8 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
4272
5175
  allowSavedLocalReadFallback: !quiet && isLocalSavedBatchRead(context, saved),
4273
5176
  });
4274
5177
  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 ?? [],
4276
- 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) });
5178
+ 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 ?? [],
5179
+ capture: { sha256: saved.source_sha256, files: saved.files.map(path => ({ path })), ...(Array.isArray(saved.clauses) ? { clauses: saved.clauses } : {}), bytes: saved.bytes, stories:saved.contract_snapshots }, lint: saved.lint, head: saved.head, startedAt: Date.parse(saved.created_at) });
4277
5180
  runtimeOrigin({ PDD_RUNTIME_URL: saved.origin });
4278
5181
  context.auth = authSession({
4279
5182
  identity,
@@ -4349,7 +5252,7 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
4349
5252
  if (row.final && (ports.now() >= (context.deadline ?? Infinity) || context.interrupted)) return;
4350
5253
  // A saved unknown row whose verified receipt already carries failed checks preserves them across --timeout 0 and failed/unknown polls.
4351
5254
  if (row.state === 'unknown' && answer && sameJob(answer, id, 'check') && answer.state === 'unknown'
4352
- && failedCheckCount(projectAnswer(answer, { origin: context.origin, secrets: context.secrets, steps: row.steps ?? [], criterionTexts: row.criterion_texts ?? {}, test: row.test })) > 0) {
5255
+ && failedCheckCount(projectAnswer(answer, { origin: context.origin, secrets: context.secrets, steps: row.steps ?? [], criterionTexts: row.criterion_texts ?? {}, test: row.test, clauseTable: context.capture?.clauses ?? null })) > 0) {
4353
5256
  const legacyLostWhy = row.lost === undefined && row.why ? row.why : null;
4354
5257
  applyAnswer(row, answer, context);
4355
5258
  row.lost = false;
@@ -4390,8 +5293,16 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
4390
5293
  }
4391
5294
  const continued = await continueHeld(context, candidates, saved) ?? [];
4392
5295
  const replacements = await recoverRestarts(context);
5296
+ const newSends = new Set([...continued, ...replacements]);
5297
+ if (timeout !== null) {
5298
+ const readDeadline = readStart + timeout * 60_000;
5299
+ for (const row of rows) if (!newSends.has(row) && row.story_deadline === undefined) row.story_deadline = readDeadline;
5300
+ }
4393
5301
  if (continued.length || replacements.length || !quiet && rows.some(isOpen)) {
4394
- if (continued.length) context.reading = false;
5302
+ if (continued.length) {
5303
+ context.reading = false;
5304
+ if (!quiet) context.deadline = context.batchDeadline;
5305
+ }
4395
5306
  await runScheduledChecks(context, rows, [...continued, ...replacements]);
4396
5307
  }
4397
5308
  context.savedTestCache = saved.test_cache;
@@ -4409,7 +5320,7 @@ async function recoverRestarts(context) {
4409
5320
  return !row.restart_used && !statOrNull(claimPath(context, row).replace(/\.0\.dispatch\.json$/, '.restart.json'))
4410
5321
  && !row.restart_pending && !row.admitting && !context.restartDecisions?.has(id) && sameJob(answer, id, 'check') && (restarted(answer) || transientDrop(answer));
4411
5322
  });
4412
- if (!eligible.length || context.interrupted || context.ports.now() >= context.deadline) return [];
5323
+ if (!eligible.length || context.interrupted || context.ports.now() >= batchDeadlineOf(context)) return [];
4413
5324
  if (context.singleAttempt) {
4414
5325
  context.restartDecisions ??= new Set();
4415
5326
  for (const row of eligible) {
@@ -4454,7 +5365,7 @@ async function recoverRestarts(context) {
4454
5365
  const drops = admitted.filter(row => transientDrop(context.store.read(join(context.folder, `${row.request_ids.at(-1)}.json`))));
4455
5366
  // Backoff precedes the source recapture, so edits during the wait cannot
4456
5367
  // authorize a replacement of the original selected source.
4457
- if (drops.length && !await waitBudget(context, 1000)) return [];
5368
+ if (drops.length && !await waitBudget(context, 1000, batchDeadlineOf(context))) return [];
4458
5369
  let capture;
4459
5370
  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
5371
  catch (error) {
@@ -4468,7 +5379,7 @@ async function recoverRestarts(context) {
4468
5379
  lintDiagnostics(context, lint, context.rows);
4469
5380
  const selected = [];
4470
5381
  for (const row of admitted) {
4471
- if (context.interrupted || context.ports.now() >= context.deadline || !validSavedCheck(row)) continue;
5382
+ if (context.interrupted || rowExpired(context, row) || !validSavedCheck(row)) continue;
4472
5383
  const transient = drops.includes(row);
4473
5384
  const decision = evaluateCheckBudget({
4474
5385
  max_total_calls: context.maxTotalCalls ?? null,
@@ -4496,8 +5407,12 @@ async function recoverRestarts(context) {
4496
5407
 
4497
5408
  async function runRetry(context, name, options) {
4498
5409
  const { ports } = context;
4499
- const timeout = options['--timeout'] === undefined ? AGENT_WAIT_MIN : Number(options['--timeout']);
4500
- context.deadline = ports.now() + timeout * 60_000;
5410
+ const timeout = options['--timeout'] === undefined ? AGENT_WAIT_MIN : parseTimeoutMinutes(options['--timeout'], '--timeout', { allowZero: true });
5411
+ const batchTimeout = parseTimeoutMinutes(options['--batch-timeout'], '--batch-timeout', { allowZero: true });
5412
+ const retryStart = ports.now();
5413
+ context.batchTimeoutMin = batchTimeout;
5414
+ context.batchDeadline = batchTimeout === null ? Infinity : retryStart + batchTimeout * 60_000;
5415
+ context.deadline = Math.min(context.batchDeadline, retryStart + timeout * 60_000);
4501
5416
  const rows = await runRead(context, name, true, options, true);
4502
5417
  if (context.localLayout) {
4503
5418
  line(ports.stderr,'For new evidence, run a fresh pdd lint --local.');
@@ -4505,7 +5420,7 @@ async function runRetry(context, name, options) {
4505
5420
  }
4506
5421
  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
5422
  if (context.localOnly) return () => printResult(context, rows);
4508
- if (context.interrupted || ports.now() >= context.deadline) return () => printResult(context, rows);
5423
+ if (context.interrupted || ports.now() >= context.deadline || ports.now() >= context.batchDeadline) return () => printResult(context, rows);
4509
5424
  const capture = Array.isArray(context.capture.sources) ? context.capture : context.ports.captureSource(context.root, { tests: sentTests(rows), appMap: null, excludeFixtureProjects: context.excludeFixtureProjects });
4510
5425
  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
5426
  capture.stories = context.capture.stories;
@@ -4517,8 +5432,16 @@ async function runRetry(context, name, options) {
4517
5432
  const selected = retryable.filter(row => lintAdmits(lint, row, context.capture));
4518
5433
  if (retryable.length && !selected.length) throw new Stop(2, 'The saved lint cannot authorize recovery. Start a fresh selected pdd test.');
4519
5434
  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';
5435
+ Object.assign(context, { capture, reading: false, timeoutMin: timeout, deadline: context.batchDeadline });
5436
+ for (const row of selected) {
5437
+ if (row.retry_at > ports.now()) {
5438
+ row.story_deadline = retryStart + timeout * 60_000;
5439
+ row.state = 'waiting';
5440
+ } else {
5441
+ delete row.story_deadline;
5442
+ row.state = 'ready';
5443
+ }
5444
+ }
4522
5445
  if (selected.length) line(ports.stderr, `Retrying ${selected.length} unstarted check${selected.length === 1 ? '' : 's'}…`);
4523
5446
  await runScheduledChecks(context, rows, selected);
4524
5447
  saveBatch(context);
@@ -4601,6 +5524,7 @@ async function refreshCheckBatches(context, identity, origin, id, answer) {
4601
5524
  if (sameJob(receipt, latest, 'check')) applyAnswer(row, receipt, projection);
4602
5525
  return row;
4603
5526
  });
5527
+ reconcileStoryCriteria(rows, projection);
4604
5528
  const cache = await openTestCache(projection, root, false);
4605
5529
  cache.tokens = new Map(saved.test_cache.tokens);
4606
5530
  await finishTestAttempts(cache, rows, capture);
@@ -4772,16 +5696,16 @@ async function closeLocalBridges(context) {
4772
5696
  // Its lifetime covers scheduler waits, recovery and every phase of a retry.
4773
5697
  async function withCheckRun(context, run) {
4774
5698
  let ownership;
4775
- context.postCheck = async (request, row, timeoutMs) => {
5699
+ context.postCheck = async (request, row, timeoutMs, deadline = rowDeadline(context, row)) => {
4776
5700
  if(context.liveLocal) {
4777
5701
  const bridge=await newLocalBridge(context,'check',request.requestId);
4778
5702
  request={...request,resource_mode:'live',resource_setup:bridge.resource_setup};
4779
- const verdict=await postJob(context,'/v1/check','check',request,row,timeoutMs,context.deadline);
5703
+ const verdict=await postJob(context,'/v1/check','check',request,row,timeoutMs,deadline);
4780
5704
  if(verdict.kind==='accepted'&&!ENDED.has(verdict.answer?.state))await startLocalBridge(context,bridge,request.requestId);
4781
5705
  return verdict;
4782
5706
  }
4783
5707
  // 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);
5708
+ if (context.stepIds?.length || context.checkOptions) return postJob(context, '/v1/check', 'check', request, row, timeoutMs, deadline);
4785
5709
  ownership ??= (async () => {
4786
5710
  if (!context.testCache) {
4787
5711
  const cache = context.testCache = await openTestCache(context, context.root, false);
@@ -4792,7 +5716,7 @@ async function withCheckRun(context, run) {
4792
5716
  if (!cache.disabled && !cache.mark) await cacheTransaction(cache, data => markTestAttempt(cache, data));
4793
5717
  })();
4794
5718
  await ownership;
4795
- return postJob(context, '/v1/check', 'check', request, row, timeoutMs, context.deadline);
5719
+ return postJob(context, '/v1/check', 'check', request, row, timeoutMs, deadline);
4796
5720
  };
4797
5721
  let result;
4798
5722
  try { result = await run(); }
@@ -4808,7 +5732,7 @@ async function withCheckRun(context, run) {
4808
5732
  // pdd test. Returns the exit code.
4809
5733
  export async function runCheck({ words = [], options = {}, cwd = process.cwd(), cache = false, client, workflow } = {}, givenPorts = {}) {
4810
5734
  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: [] };
5735
+ 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
5736
  let release = () => {};
4813
5737
  try {
4814
5738
  context.liveLocal=liveLocalOptions(options,'check');
@@ -4818,13 +5742,13 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
4818
5742
  if (!context.checkOptions && options['--step'] !== undefined) {
4819
5743
  const values = Array.isArray(options['--step']) ? options['--step'] : [options['--step']];
4820
5744
  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.');
5745
+ 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
5746
  context.stepIds = [...new Set(values)]; context.cacheEnabled = false;
4823
5747
  }
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.');
5748
+ 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))))
5749
+ 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
5750
  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.');
5751
+ 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
5752
  const {root,found}=localSetup(cwd,[],ports);
4829
5753
  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
5754
  if(!words.length)throw new Stop(2,'No root product journeys found.');
@@ -4968,15 +5892,19 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
4968
5892
  const selectorInfo = selectorLintForPrompts({ root, visible: new Set(gitFiles(root)), paths: inspectedPrompts, workspace });
4969
5893
  context.selectorTableLines = selectorInfo.tableLines;
4970
5894
  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.`;
5895
+ const warnings = [...new Set([...advice, ...selectorInfo.warnings, ...preflightWarnings, ...ports.lintSvgLayouts({ root, files, promptPaths }), ...hygiene])];
5896
+ const localOutcome = problems.length ? `found ${problems.length} problem${problems.length === 1 ? '' : 's'}` : 'passed';
5897
+ 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
5898
  const result = await saveLocalLayout(context,{root,tests,prompts:promptPaths ?? files.filter(path => path.endsWith('.prompt.md')),warnings,problems,summary});
4973
5899
  return printLocalLayout(context,result);
4974
5900
  } catch (error) { if (error?.unboundPort) throw error; throw new Stop(2, error.message); }
4975
5901
  }
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)
5902
+ const modes = ['--read', '--retry', '--reconcile', '--reconcile-stale', '--files', '--explain-bindings', '--request', '--lint'].filter(name => options[name] !== undefined);
5903
+ 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'));
5904
+ if (modes.length > 1 || (modes.length && others.length) || (['--request', '--retry', '--reconcile', '--reconcile-stale'].includes(modes[0]) && words.length)
4979
5905
  || (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.');
5906
+ if (modes[0] === '--reconcile') return await runReconcileCommand(context, options['--reconcile'], cwd, givenPorts);
5907
+ if (modes[0] === '--reconcile-stale') return await runReconcileStaleCommand(context, options['--reconcile-stale'], cwd, givenPorts);
4980
5908
  if (modes[0] === '--request') { release = interruptible(context); return await runRequest(context, options['--request'], cwd); }
4981
5909
  const root = repoRoot(cwd);
4982
5910
  if (modes[0] === '--explain-bindings') return runExplainBindings(cwd, words, options, ports);
@@ -5005,7 +5933,7 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
5005
5933
  coverage: { available: false, bound: null, total: null, modules: [] }, problems: [{ code: 'binding-invalid', path: 'pdd-bindings.json', message: error.message }], rows: [], warnings: [] }));
5006
5934
  else if (context.coverage && error.exitCode !== 5) {
5007
5935
  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 }));
5936
+ 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
5937
  else line(ports.stdout, coverageText(context.coverage));
5010
5938
  }
5011
5939
  return error.exitCode;
@@ -5233,7 +6161,7 @@ async function acquireCacheGuard(cache) {
5233
6161
  if (!Number.isSafeInteger(ticket)) throw new Error('cache ticket overflow');
5234
6162
  fs.write(join(own, 'ticket.tmp'), JSON.stringify(ticket), { flag: 'wx', mode: 0o600 });
5235
6163
  fs.rename(join(own, 'ticket.tmp'), join(own, 'ticket.json'));
5236
- for (let attempt = 0; attempt < 100; attempt++) {
6164
+ for (let attempt = 0; attempt < 30; attempt++) {
5237
6165
  if (!peers().some(peer => peer.ticket === null || peer.ticket < ticket || peer.ticket === ticket && peer.name < name)) return () => remove(own);
5238
6166
  await cache.context.ports.sleep(10);
5239
6167
  }
@@ -5246,7 +6174,7 @@ async function cacheTransaction(cache, operation, clear = false) {
5246
6174
  try {
5247
6175
  safeCachePath(cache.fs, cache.dir, { directory: true });
5248
6176
  releaseGuard = await acquireCacheGuard(cache);
5249
- for (let attempt = 0; attempt < 100; attempt++) {
6177
+ for (let attempt = 0; attempt < 30; attempt++) {
5250
6178
  try {
5251
6179
  cache.fs.mkdir(cache.lock); locked = true;
5252
6180
  owner = { pid: process.pid, token: cache.fs.nonce() };
@@ -5510,12 +6438,12 @@ function markTestAttempt(cache, data) {
5510
6438
  const oldMarks = latest.in_progress ?? [];
5511
6439
  const live = liveInProgressMarks(cache, oldMarks);
5512
6440
  const stories = [...cache.tokens.keys()];
5513
- const verifiedBase = hasVerifiedIdentityRecord(latest);
5514
- if (!live.length) {
5515
- latest.cohort = { members: [], valid: true, engine_sha: verifiedBase ? latest.engine_sha : null, requested_model: verifiedBase ? latest.models[0] : null, floor: Date.parse(latest.sampled_at) };
5516
- } else if (!latest.cohort || !live.every(mark => latest.cohort.members.some(member => member.token === mark.token))) {
6441
+ if (!oldMarks.length) {
6442
+ latest.cohort = { members: [], valid: true, engine_sha: null, requested_model: null, floor: Date.parse(latest.sampled_at) };
6443
+ } else if (!latest.cohort || live.length !== oldMarks.length || !oldMarks.every(mark => latest.cohort.members.some(member => member.token === mark.token))) {
5517
6444
  latest.cohort = { members: [], valid: false, engine_sha: null, requested_model: null, floor: Date.parse(latest.sampled_at) };
5518
6445
  }
6446
+ if (cache.mark.started_at <= latest.cohort.floor) latest.cohort.valid = false;
5519
6447
  if (latest.cohort.members.some(member => member.stories.some(story => stories.includes(story)))) latest.cohort.valid = false;
5520
6448
  latest.cohort.members.push({ token: cache.mark.token, stories });
5521
6449
  latest.in_progress = [...live, cache.mark];
@@ -5535,15 +6463,17 @@ async function beginTestAttempts(cache, rows, capture, options, origin, force =
5535
6463
  const eligible = eligibleCachePass(pass, cache.context.ports.now()) && fingerprint && pass.fingerprint === identityFingerprint(cache, fingerprint, pass) && own.every(row => row.state === 'ready' && pass.tests.includes(row.test));
5536
6464
  const budgetAllows = !eligible || passSatisfiesMaxCalls(pass, own);
5537
6465
  const identity = data.latest_identity;
5538
- const knownDrift = hasVerifiedIdentityRecord(identity) && ((identity.engine_sha && identity.engine_sha !== pass?.engine_sha) || (identity.models?.length === 1 && identity.models[0] !== pass?.requested_model));
6466
+ const knownDrift = identity && cleanRecordMatches(identity, { engine_sha: identity.engine_sha, requested_model: identity.models?.[0] }) && ((identity.engine_sha && identity.engine_sha !== pass?.engine_sha) || (identity.models?.length === 1 && identity.models[0] !== pass?.requested_model));
5539
6467
  const reason = capture && declarationCacheReason(capture, story, own.map(row => row.test))
5540
6468
  || (Number.isFinite(Date.parse(pass?.passed_at)) && cache.context.ports.now() - Date.parse(pass.passed_at) > 7 * 86400000 ? 'runs again: saved pass is older than seven days' : null)
5541
6469
  || (eligible && !budgetAllows ? 'runs again: --max-calls is lower than the saved pass call count' : null)
5542
- || (eligible && !verifiedIdentityMatchesPass(cache, identity, pass, story) ? (knownDrift ? 'runs again: interpreter build or model changed' : 'runs again: cache identity is unverified') : null);
6470
+ || (eligible && !cleanRecordMatches(identity, pass) ? (knownDrift ? 'runs again: interpreter build or model changed' : 'runs again: cache identity is unverified') : null);
5543
6471
  if (reason) for (const row of own) row.cache_reason ??= reason;
5544
6472
  if (!force && !reason && [undefined, '', '0', 'false'].includes(cache.context.ports.env.CI) && eligible && budgetAllows) {
5545
6473
  for (const row of own) {
5546
6474
  const { checks, criteria, criteria_total, draft } = pass.rows[row.test];
6475
+ delete row.not_checked;
6476
+ delete row.own_not_checked;
5547
6477
  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
6478
  }
5549
6479
  continue;
@@ -5563,66 +6493,28 @@ async function finishTestAttempts(cache, rows, capture) {
5563
6493
  await cacheTransaction(cache, data => {
5564
6494
  const observations = cache.context.observedTestIdentities ?? [];
5565
6495
  const previous = data.latest_identity;
5566
- const observedEngines = [...new Set(observations.map(item => item.engine_sha).filter(Boolean))];
5567
- const observedModels = [...new Set(observations.flatMap(item => item.models).filter(Boolean))];
5568
- const hasObservedConflict = observedEngines.length > 1 || observedModels.length > 1 || observations.some(item => item.conflict);
5569
- const identity = {
5570
- engine_sha: observedEngines.length === 1 ? observedEngines[0] : null,
5571
- requested_model: observedModels.length === 1 ? observedModels[0] : null,
5572
- };
6496
+ const identity = { engine_sha: observations.find(item => item.engine_sha)?.engine_sha ?? null,
6497
+ requested_model: observations.flatMap(item => item.models).find(Boolean) ?? null };
5573
6498
  const terminalObservations = observations.filter(item => item.terminal);
5574
- const identityVerified = !hasObservedConflict && !!identity.engine_sha && !!identity.requested_model && terminalObservations.length > 0;
6499
+ const complete = terminalObservations.length > 0 && terminalObservations.every(item => item.complete)
6500
+ && observations.every(item => observedIdentityMatches(item, identity));
5575
6501
  const marks = previous?.in_progress ?? [];
5576
6502
  const ownMark = mark => !!cache.mark && mark.token === cache.mark.token;
5577
- const liveRemaining = liveInProgressMarks(cache, marks.filter(mark => !ownMark(mark)));
6503
+ const remaining = marks.filter(mark => !ownMark(mark));
6504
+ const unchanged = cache.identitySnapshot === JSON.stringify(previous ?? null);
5578
6505
  const cohort = previous?.cohort;
5579
- const nowIso = new Date(cache.context.ports.now()).toISOString();
5580
- if (cache.context.cacheReadInvocation) {
5581
- if (previous && marks.some(ownMark)) {
5582
- data.latest_identity = { ...previous, in_progress: liveRemaining, ...(liveRemaining.length && cohort ? { cohort } : {}) };
5583
- if (!liveRemaining.length) delete data.latest_identity.cohort;
5584
- }
5585
- } else if (!observations.length) {
5586
- // No server response was observed (e.g., local error/interrupt before HTTP settlement).
5587
- // Retire our in-progress mark without erasing a previously verified identity.
5588
- if (previous) {
5589
- const preservedClean = !liveRemaining.length && hasVerifiedIdentityRecord(previous);
5590
- const next = { ...previous, in_progress: liveRemaining, clean: preservedClean, conflict: !hasVerifiedIdentityRecord(previous), written_at: nowIso, observed_at: nowIso };
5591
- if (liveRemaining.length && cohort) next.cohort = cohort;
5592
- else delete next.cohort;
5593
- data.latest_identity = next;
5594
- }
5595
- } else {
5596
- let cohortConflict = false;
5597
- if (cohort) {
5598
- if (!identityVerified) {
5599
- cohort.valid = false;
5600
- cohortConflict = true;
5601
- } else {
5602
- if ((cohort.engine_sha !== null && cohort.engine_sha !== identity.engine_sha)
5603
- || (cohort.requested_model !== null && cohort.requested_model !== identity.requested_model)) {
5604
- cohort.valid = false;
5605
- cohortConflict = true;
5606
- }
5607
- if (cohort.engine_sha === null) cohort.engine_sha = identity.engine_sha;
5608
- if (cohort.requested_model === null) cohort.requested_model = identity.requested_model;
5609
- if (cohort.valid === false) cohortConflict = true;
5610
- }
5611
- }
5612
- const clean = !liveRemaining.length && identityVerified && !cohortConflict;
5613
- const conflict = hasObservedConflict || cohortConflict || !identityVerified;
5614
- data.latest_identity = {
5615
- engine_sha: identity.engine_sha,
5616
- models: identity.requested_model ? [identity.requested_model] : [],
5617
- in_progress: liveRemaining,
5618
- ...(liveRemaining.length && cohort ? { cohort } : {}),
5619
- clean,
5620
- conflict,
5621
- sampled_at: new Date(Number.isFinite(cache.context.startedAt) ? cache.context.startedAt : 0).toISOString(),
5622
- written_at: nowIso,
5623
- observed_at: nowIso,
5624
- };
5625
- }
6506
+ const member = cohort?.members.find(item => ownMark(item));
6507
+ const ordinary = !!member && marks.some(ownMark) && !cache.context.cacheReadInvocation && !cache.context.checkRunFailed && Number.isFinite(cache.context.startedAt) && cache.context.startedAt > cohort.floor && complete;
6508
+ if (cohort) {
6509
+ cohort.valid &&= ordinary && marks.every(mark => cohort.members.some(item => item.token === mark.token));
6510
+ if (cohort.engine_sha !== null && cohort.engine_sha !== identity.engine_sha || cohort.requested_model !== null && cohort.requested_model !== identity.requested_model) cohort.valid = false;
6511
+ if (cohort.engine_sha === null) cohort.engine_sha = identity.engine_sha;
6512
+ if (cohort.requested_model === null) cohort.requested_model = identity.requested_model;
6513
+ }
6514
+ const clean = !remaining.length && ordinary && (unchanged && (!previous || cache.context.startedAt > Date.parse(previous.sampled_at)) || cohort?.valid === true && cohort.members.length > 1);
6515
+ data.latest_identity = { engine_sha: identity.engine_sha, models: identity.requested_model ? [identity.requested_model] : [],
6516
+ in_progress: remaining, ...(remaining.length && cohort ? { cohort } : {}), clean, conflict: !clean, sampled_at: new Date(Number.isFinite(cache.context.startedAt) ? cache.context.startedAt : 0).toISOString(),
6517
+ written_at: new Date(cache.context.ports.now()).toISOString(), observed_at: new Date(cache.context.ports.now()).toISOString() };
5626
6518
  for (const [story, token] of cache.tokens) {
5627
6519
  if (data.epoch !== token.epoch || data.stories[story]?.generation !== token.generation) continue;
5628
6520
  const own = rows.filter(row => row.story_path === story && !row.cached), footprint = capture.stories?.find(item => item.story_path === story);
@@ -5700,7 +6592,8 @@ async function runBatch(context, cwd, words, options, setRelease) {
5700
6592
  context.visible = found.visible; context.origin = origin; context.excludeFixtureProjects = words.length === 0;
5701
6593
  // Ordinary Check waits for completion in every shell unless a limit is explicit.
5702
6594
  context.agentLimit = false;
5703
- context.timeoutMin = options['--timeout'] !== undefined ? Number(options['--timeout']) : null;
6595
+ context.timeoutMin = parseTimeoutMinutes(options['--timeout'], '--timeout');
6596
+ context.batchTimeoutMin = parseTimeoutMinutes(options['--batch-timeout'], '--batch-timeout');
5704
6597
  let selected = select(found, normalized, root, ports);
5705
6598
  const diagnostic = context.stepIds?.length > 0;
5706
6599
  const preliminary = diagnostic ? preflight({root,found,selected,allowMissingInterfaces:true,stepIds:context.stepIds}) : null;
@@ -5750,7 +6643,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5750
6643
  discoveryChanged ||= !isDeepStrictEqual(initialDiscovery,discoveryScope(current.found));
5751
6644
  return current;
5752
6645
  };
5753
- const priorReservations = readUnresolvedPriorReservations(root, ports.env, context.batch ?? null);
6646
+ const priorReservations = readUnresolvedPriorReservations(root, ports.env, context.batch ?? null, { now: ports.now() });
5754
6647
  const planPolicyOptions = {
5755
6648
  maxCalls: options['--max-calls'] !== undefined ? Number(options['--max-calls']) : null,
5756
6649
  maxTotalCalls: context.maxTotalCalls ?? null,
@@ -5768,13 +6661,9 @@ async function runBatch(context, cwd, words, options, setRelease) {
5768
6661
  // only this attempt's mark, leaving its invalidations and other owners intact.
5769
6662
  if (cache?.mark) await cacheTransaction(cache, data => {
5770
6663
  if (data.latest_identity?.in_progress) {
5771
- const remaining = liveInProgressMarks(cache, data.latest_identity.in_progress.filter(mark=>mark.token!==cache.mark.token));
5772
- data.latest_identity.in_progress = remaining;
5773
- if (!remaining.length) {
5774
- delete data.latest_identity.cohort;
5775
- const preserved = hasVerifiedIdentityRecord(data.latest_identity);
5776
- Object.assign(data.latest_identity, { clean: preserved, conflict: !preserved });
5777
- }
6664
+ data.latest_identity.in_progress = data.latest_identity.in_progress.filter(mark=>mark.token!==cache.mark.token);
6665
+ Object.assign(data.latest_identity,{clean:false,conflict:true});
6666
+ if (data.latest_identity.cohort) data.latest_identity.cohort.valid = false;
5778
6667
  }
5779
6668
  });
5780
6669
  if (context.testCache === cache) context.testCache = null;
@@ -5821,6 +6710,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5821
6710
  if (test?.error) row.unsent = true;
5822
6711
  row.criterion_texts = Object.fromEntries([...(Array.isArray(test?.doc?.criteria) ? test.doc.criteria : []).filter(isObject).map(item => [item.id, item.text]),
5823
6712
  ...(row.not_checked??[]).map(item=>[item.criterion_id,item.text])]);
6713
+ if (row.not_checked?.length) row.own_not_checked = row.not_checked.map(item => ({ ...item }));
5824
6714
  }
5825
6715
  if (options['--max-calls'] !== undefined) for (const row of rows) row.max_calls = Number(options['--max-calls']);
5826
6716
  if (context.checkOptions) for (const row of rows) {
@@ -5884,13 +6774,9 @@ async function runBatch(context, cwd, words, options, setRelease) {
5884
6774
  catch (error) {
5885
6775
  if (cache?.mark) await cacheTransaction(cache, data => {
5886
6776
  if (data.latest_identity?.in_progress) {
5887
- const remaining = liveInProgressMarks(cache, data.latest_identity.in_progress.filter(mark => mark.token !== cache.mark.token));
5888
- data.latest_identity.in_progress = remaining;
5889
- if (!remaining.length) {
5890
- delete data.latest_identity.cohort;
5891
- const preserved = hasVerifiedIdentityRecord(data.latest_identity);
5892
- Object.assign(data.latest_identity, { clean: preserved, conflict: !preserved });
5893
- }
6777
+ data.latest_identity.in_progress = data.latest_identity.in_progress.filter(mark => mark.token !== cache.mark.token);
6778
+ Object.assign(data.latest_identity, { clean: false, conflict: true });
6779
+ if (data.latest_identity.cohort) data.latest_identity.cohort.valid = false;
5894
6780
  }
5895
6781
  });
5896
6782
  throw error;
@@ -5903,7 +6789,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5903
6789
  if(context.liveLocal)context.localOwner??=identity.login;
5904
6790
  const startedAt = ports.now(), batch = batchId(startedAt, ports.randomUUID);
5905
6791
  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,
6792
+ Object.assign(context, { capture, identity, batch, startedAt, deadline: Infinity, batchDeadline: Infinity, rows,
5907
6793
  intent: 'check', head: capture.source_commit ?? (head.status === 0 ? head.stdout.trim() : null), secrets: [identity.token], lint: { request_ids: [], state: null } });
5908
6794
  context.folder = context.store.folder('batches', batch);
5909
6795
  setRelease(interruptible(context));
@@ -5927,12 +6813,12 @@ async function runBatch(context, cwd, words, options, setRelease) {
5927
6813
  for (const row of rerun) {
5928
6814
  const original = originals.get(row.test), storyPath = row.story_path, texts = row.criterion_texts, appMaps = row.app_maps;
5929
6815
  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' });
6816
+ 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
6817
  if (options['--max-calls'] !== undefined) row.max_calls = Number(options['--max-calls']);
5932
6818
  }
5933
6819
  await beginTestAttempts(cache, rerun, capture, options, origin, true);
5934
6820
  const stopReason = context.interrupted ? 'interrupted' : context.readStop ? 'reading stopped'
5935
- : ports.now() >= context.deadline ? 'time limit reached' : context.stopped ? 'stopped' : null;
6821
+ : context.timedOut || ports.now() >= context.deadline ? 'time limit reached' : context.stopped ? 'stopped' : null;
5936
6822
  if (stopReason) {
5937
6823
  for (const row of rerun) Object.assign(row, { state: 'not_run', calls: 0, seconds: 0, phase: 'local', busy: false,
5938
6824
  note: { code: null, message: `not sent: ${stopReason}` }, why: `not sent: ${stopReason}` });
@@ -5941,6 +6827,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
5941
6827
  }
5942
6828
  }
5943
6829
  saveBatch(context);
6830
+ try { pruneOldBatches({ stateDir: context.store.dir, env: ports.env, now: ports.now(), excludeBatches: [context.batch] }); } catch { /* best-effort retention GC */ }
5944
6831
  return () => printResult(context, rows);
5945
6832
  }
5946
6833
 
@@ -5976,7 +6863,7 @@ function appMapFor(found, given, cwd, root, stderr) {
5976
6863
  requireRuntimePath(loadRuntimeWorkspace({root}),{path:rel,from:'App map'});
5977
6864
  if (!found.visible.has(rel)) throw new Stop(2, `--app-map ${cleanText(given)} is not a Git-visible file in this repository.`);
5978
6865
  const problem = appMapProblem(root, rel);
5979
- if (problem) throw new Stop(2, `--app-map ${cleanText(given)} is not an app map: ${problem}. An app map is a JSON file with "schema_version": "${APP_MAP_VERSION}". See RUNBOOK.md §13.`);
6866
+ if (problem) throw new Stop(2, `--app-map ${cleanText(given)} is not an app map: ${problem}. An app map is a JSON file with "schema_version": "${APP_MAP_VERSION}". See the pdd skill reference ui-and-screens.md, or run pdd help prompting.`);
5980
6867
  return rel;
5981
6868
  }
5982
6869
 
@@ -6023,7 +6910,14 @@ function tryCommand(test, setup, suffix='', target=test.story) {
6023
6910
  }
6024
6911
 
6025
6912
  // Read the authored interfaces, never scenario output, to choose an interaction.
6026
- function programEntries(root, found, test) {
6913
+ function isPlainCliStep(prompt, step) {
6914
+ if (!prompt || prompt.error !== 'interface-missing' || typeof prompt.text !== 'string') return false;
6915
+ if (!isObject(step?.input) || !Array.isArray(step.input.argv) || !step.input.argv.every(word => typeof word === 'string')) return false;
6916
+ return /\b(?:cli|argv|stdout|stderr|exit_code|command-line)\b/i.test(prompt.text)
6917
+ || (Array.isArray(step.checks) && step.checks.some(c => c?.target === 'result' && ['/stdout', '/stderr', '/exit_code'].includes(c?.path)));
6918
+ }
6919
+
6920
+ function programEntries(root, found, test, { allowMissingInterfaces = false } = {}) {
6027
6921
  const cli = new Set(), http = new Set();
6028
6922
  for (const step of Array.isArray(test.doc?.steps) ? test.doc.steps : []) {
6029
6923
  if (!step || typeof step.entry_path !== 'string' || typeof step.operation !== 'string') continue;
@@ -6031,31 +6925,39 @@ function programEntries(root, found, test) {
6031
6925
  const entries = Array.isArray(prompt.interface?.entries) ? prompt.interface.entries : [];
6032
6926
  const conventions = Array.isArray(prompt.interface?.conventions) ? prompt.interface.conventions : [];
6033
6927
  const index = entries.findIndex(entry => entry?.operation === step.operation);
6034
- if (!(index >= 0)) continue;
6035
- const entry = entries[index], key = `${step.entry_path}#${step.operation}`;
6036
- if (['input_schema', 'result_schema'].every(name => conventions.some(c => c?.path === `/entries/${index}/${name}` && c.convention === 'cli'))) cli.add(key);
6037
- if (typeof entry.input_schema?.title === 'string' && /^HTTP (GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) \/\S*$/.test(entry.input_schema.title)) http.add(key);
6928
+ const key = `${step.entry_path}#${step.operation}`;
6929
+ if (index >= 0) {
6930
+ const entry = entries[index];
6931
+ if (['input_schema', 'result_schema'].every(name => conventions.some(c => c?.path === `/entries/${index}/${name}` && c.convention === 'cli'))) cli.add(key);
6932
+ if (typeof entry.input_schema?.title === 'string' && /^HTTP (GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) \/\S*$/.test(entry.input_schema.title)) http.add(key);
6933
+ } else if (allowMissingInterfaces && isPlainCliStep(prompt, step)) {
6934
+ cli.add(key);
6935
+ }
6038
6936
  }
6039
6937
  return { test, cli, http };
6040
6938
  }
6041
6939
 
6042
- function simulationSelection(root, found, words, appMap, options, ports) {
6940
+ function simulationSelection(root, found, words, appMap, options, ports, { allowMissingInterfaces = false } = {}) {
6043
6941
  const all = [...found.tests].sort((a, b) => a.path.localeCompare(b.path));
6044
6942
  if (!all.length) throw new Stop(2, 'No Stories are available to simulate.');
6045
6943
  const selected = words.length ? [oneTest(found, words, root, ports)] : all;
6046
- const rows = selected.map(test => programEntries(root, found, test));
6944
+ const rows = selected.map(test => programEntries(root, found, test, { allowMissingInterfaces }));
6047
6945
  const eligibleNames = predicate => [...new Set(all.flatMap(test => {
6048
6946
  const selectedRow = rows.find(row => row.test === test);
6049
6947
  // Selected source was read strictly above. Unselected failures cannot turn
6050
6948
  // advisory eligible-name discovery into a new source requirement.
6051
- try { return predicate(selectedRow ?? programEntries(root, found, test)) ? [test.story] : []; }
6949
+ try { return predicate(selectedRow ?? programEntries(root, found, test, { allowMissingInterfaces })) ? [test.story] : []; }
6052
6950
  catch { return []; }
6053
6951
  }))].sort();
6054
6952
  const cli = new Set(rows.flatMap(row => [...row.cli]));
6055
6953
  const hasHttp = rows.some(row => row.http.size);
6056
6954
  const screens = appMap ? JSON.parse(readFileSync(join(root, appMap), 'utf8')).screens : [];
6057
6955
  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;
6956
+ const plainUi = !appMap && !cli.size && !hasHttp && selected.some(test => (Array.isArray(test.doc?.steps) ? test.doc.steps : []).some(step => {
6957
+ if (!step || typeof step.entry_path !== 'string' || !found.visible.has(step.entry_path)) return false;
6958
+ try { return isPlainProseUiPromptText(readPrompt(root, found.visible, step.entry_path, found.workspace).text); } catch { return false; }
6959
+ }));
6960
+ const typed = words.length && !cli.size && !hasHttp && !mapped && !plainUi;
6059
6961
  const page = options['--page'] || options['--agent'] !== undefined || options['--tab'] !== undefined;
6060
6962
  const forcedCli = options['--cli'] || options['--shell'];
6061
6963
  if (forcedCli && cli.size !== 1) {
@@ -6079,7 +6981,7 @@ function simulationSelection(root, found, words, appMap, options, ports) {
6079
6981
  // The seed establishes saved-case/session identity, not a preferred view.
6080
6982
  if (cli.size === 1) seed = rows.find(row => row.cli.size).test;
6081
6983
  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');
6984
+ const tab = options['--tab'] ?? (options['--cli'] ? 'terminal' : (appMap && (!words.length || mapped || !typed)) || plainUi ? 'screen' : 'call');
6083
6985
  return { test: seed, selected, tab, typed: typed && tab === 'call' && options['--serve'] === undefined };
6084
6986
  }
6085
6987
 
@@ -6194,24 +7096,29 @@ async function stopTry(context, record) {
6194
7096
  function trySourceSelection(record, path) {
6195
7097
  const scope = record.simulation_scope;
6196
7098
  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)
7099
+ const entries = Array.isArray(scope.tests) && scope.tests.length
7100
+ ? scope.tests
7101
+ : typeof scope.entry === 'string' && scope.entry ? [scope.entry] : null;
7102
+ if (!isObject(scope) || !Array.isArray(scope.tests) || !entries
7103
+ || !entries.every(test => typeof test === 'string') || !entries.includes(path)
6199
7104
  || !(scope.appMap === null || typeof scope.appMap === 'string')) {
6200
7105
  throw new Stop(4, 'The saved whole-project source scope is unavailable. Run pdd simulate --new.');
6201
7106
  }
6202
- return { tests: scope.tests, appMap: scope.appMap };
7107
+ return { tests: entries, appMap: scope.appMap };
6203
7108
  }
6204
7109
 
6205
7110
  function tryPromptProblem(root, found, test, record, capture, ports) {
6206
7111
  const hashes=record.prompt_hashes;
6207
- if (!capture && record.simulation_scope?.appMap) capture = ports.captureSource(root, trySourceSelection(record, test?.path));
7112
+ if (!capture && record.simulation_scope?.appMap) capture = ports.captureSource(root, trySourceSelection(record, test?.path ?? record.entry));
6208
7113
  if (!capture && isObject(hashes)) {
6209
7114
  const files=sourceFilePort(root,found.visible), sources=[], references=[], raw_prompt_hashes={};
6210
7115
  for (const path of Object.keys(hashes)) {
6211
- const prepared=readPrompt(root,found.visible,path);
7116
+ const prepared=readPrompt(root,found.visible,path,found.workspace);
6212
7117
  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'));
7118
+ const rawText = typeof prepared.rawText === 'string' ? prepared.rawText : files.read({path}).content;
7119
+ const effectiveText = executableInterfaceText(prepared.text);
7120
+ sources.push({path,bytes:Buffer.from(effectiveText,'utf8')});references.push(...(prepared.references??[]));
7121
+ raw_prompt_hashes[path]=sha256(Buffer.from(rawText,'utf8'));
6215
7122
  }
6216
7123
  capture={sources,references,raw_prompt_hashes};
6217
7124
  }
@@ -6219,7 +7126,10 @@ function tryPromptProblem(root, found, test, record, capture, ports) {
6219
7126
  const scope = record.simulation_scope, map = capture.sources.find(file => file.path === scope.appMap);
6220
7127
  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
7128
  }
6222
- if (!isObject(hashes) || !Object.keys(hashes).length || (test && !test.doc?.steps?.every(step=>typeof hashes[step.entry_path]==='string'))
7129
+ const missingEntryHash = Array.isArray(test?.doc?.steps)
7130
+ ? !test.doc.steps.every(step=>typeof hashes?.[step.entry_path]==='string')
7131
+ : typeof record.entry === 'string' ? typeof hashes?.[record.entry] !== 'string' : false;
7132
+ if (!isObject(hashes) || !Object.keys(hashes).length || missingEntryHash
6223
7133
  || !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
7134
  const current=Object.fromEntries(capture.sources.filter(file=>file.path.endsWith('.prompt.md')).map(file=>[file.path,sha256(file.bytes)]));
6225
7135
  if (isObject(record.effective_prompt_hashes) && Object.keys(hashes).every(path=>typeof record.effective_prompt_hashes[path]==='string')) {
@@ -6400,7 +7310,7 @@ function programSelection(cwd, word, ports, givenMap) {
6400
7310
  try { map = JSON.parse(sourceFilePort(root, visible).read({ path }).content); }
6401
7311
  catch (error) { if (error instanceof RuntimeWorkspaceError) throw error; throw new Stop(2, 'Select a readable app map containing valid JSON.'); }
6402
7312
  if (!isObject(map) || (Object.hasOwn(map, 'schema_version') && !APP_MAP_VERSIONS.has(map.schema_version)) || !Array.isArray(map.screens) || !map.screens.length) throw new Stop(2, 'Select a valid app map with executable screens.');
6403
- if (explicit && Object.hasOwn(map, 'name') && (typeof map.name !== 'string' || !map.name)) throw new Stop(2, 'The selected app map has an invalid name. See RUNBOOK.md §13.');
7313
+ if (explicit && Object.hasOwn(map, 'name') && (typeof map.name !== 'string' || !map.name)) throw new Stop(2, 'The selected app map has an invalid name. See the pdd skill reference ui-and-screens.md, or run pdd help prompting.');
6404
7314
  const initial = map.screens.find(screen => screen.id === (map.initial_screen ?? map.screens[0]?.id)), first = (initial?.source ?? 'operation') === 'operation' ? initial : map.screens.find(screen => (screen.source ?? 'operation') === 'operation');
6405
7315
  if (!first || typeof first.prompt_path !== 'string' || !first.prompt_path.endsWith('.prompt.md') || !visible.has(first.prompt_path)) throw new Stop(2, 'This app map has no executable prompt.');
6406
7316
  return first.prompt_path;
@@ -6408,9 +7318,9 @@ function programSelection(cwd, word, ports, givenMap) {
6408
7318
  const entry = isMap ? mapEntry(selected) : selected;
6409
7319
  let appMap = isMap ? selected : null;
6410
7320
  if (givenMap !== undefined) {
6411
- if (typeof givenMap !== 'string' || !givenMap) throw new Stop(2, '--app-map needs a Git-visible map path. See RUNBOOK.md §13.');
7321
+ if (typeof givenMap !== 'string' || !givenMap) throw new Stop(2, '--app-map needs a Git-visible map path. See the pdd skill reference ui-and-screens.md, or run pdd help prompting.');
6412
7322
  const path = canonical(givenMap);
6413
- if (mapEntry(path, true) !== entry) throw new Stop(2, 'The selected app map does not name this program as its executable entry. See RUNBOOK.md §13.');
7323
+ if (mapEntry(path, true) !== entry) throw new Stop(2, 'The selected app map does not name this program as its executable entry. See the pdd skill reference ui-and-screens.md, or run pdd help prompting.');
6414
7324
  appMap = path;
6415
7325
  }
6416
7326
  if (!appMap) for (const path of ['app-map.json', 'app/app-map.json']) {
@@ -6421,13 +7331,20 @@ function programSelection(cwd, word, ports, givenMap) {
6421
7331
  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
7332
  return path;
6423
7333
  };
6424
- return { root, visible, entry, appMap, validatePinnedMap, screen: isMap };
7334
+ let plainUiPrompt = false;
7335
+ if (!isMap) {
7336
+ try { plainUiPrompt = isPlainProseUiPromptText(sourceFilePort(root, visible).read({ path: entry }).content); } catch { plainUiPrompt = false; }
7337
+ }
7338
+ return { root, visible, entry, appMap, validatePinnedMap, screen: isMap, plainUiPrompt };
6425
7339
  }
6426
7340
  async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
6427
7341
  const { ports } = context, selected = programSelection(cwd, word, ports, options['--app-map']), { root, entry } = selected;
6428
7342
  if (options['--data'] !== undefined && options['--fresh'] !== undefined) throw new Stop(2, 'Choose --data FILE or --fresh, not both.');
6429
7343
  if (options['--fresh'] !== undefined && options['--fresh'] !== true) throw new Stop(2, '--fresh takes no value.');
7344
+ 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
7345
  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.');
7346
+ const cliDoor = options['--cli'] === true || options['--shell'] === true;
7347
+ const openInPage = !cliDoor && (selected.screen || selected.plainUiPrompt || options['--page'] === true || options['--tab'] !== undefined);
6431
7348
  const store = stateFor(ports.env, root), files = programFiles(root, entry, store); let seeded = null;
6432
7349
  if (options['--data'] !== undefined) {
6433
7350
  if (typeof options['--data'] !== 'string') throw new Stop(2, '--data needs a JSON file.');
@@ -6441,12 +7358,27 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
6441
7358
  throw new Stop(2, 'The live program keeps its pinned app map. Use --new to select a different app map.');
6442
7359
  const appMap = !selected.screen && !options['--new'] && record?.app_map
6443
7360
  ? selected.validatePinnedMap(record.app_map) : selected.appMap;
6444
- const capture = ports.captureSource(root, { tests: [entry], appMap });
6445
- const origin = runtimeOrigin(ports.env), identity = signIn(ports.gh, store, ports);
7361
+ const requestedTab = options['--tab'] ?? (cliDoor ? 'terminal' : (selected.screen || selected.plainUiPrompt || appMap ? 'screen' : 'call'));
7362
+ const origin = runtimeOrigin(ports.env);
7363
+ const hasMissing = hasMissingPromptInterface(root, { visible: selected.visible, workspace: loadRuntimeWorkspace({ root }) }, [entry]);
7364
+ const allowMissingInterfaces = hasMissing ? (selected.plainUiPrompt ? true : await probeLazyInterfaces(context, origin, store)) : false;
7365
+ const capture = ports.captureSource(root, { tests: [entry], appMap, ...(allowMissingInterfaces ? { allowMissingInterfaces: true } : {}) });
7366
+ const capturedPrompts = new Map();
7367
+ const callsProblems = [];
7368
+ for (const file of capture.sources) {
7369
+ if (!file.path.endsWith('.prompt.md')) continue;
7370
+ let prompt;
7371
+ try { prompt = readPrompt(root, selected.visible, file.path); } catch { continue; }
7372
+ capturedPrompts.set(file.path, prompt);
7373
+ callsProblems.push(...plainMarkdownCallsProblems(root, selected.visible, prompt, capturedPrompts));
7374
+ }
7375
+ if (callsProblems.length) throw new Stop(cliDoor ? 125 : 4, callsProblems.map(item => item.message).join('; '));
7376
+ const identity = context.probedIdentity ?? signIn(ports.gh, store, ports);
6446
7377
  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
7378
  Object.assign(context, { root, cwd, origin, identity, store, capture, visible: selected.visible, appMap, programEntry: entry,
7379
+ allowMissingInterfaces,
6448
7380
  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 });
7381
+ secrets: [...(context.secrets ?? []), identity.token], startedAt: ports.now(), deadline: ports.now() + TRY_MS, lint: { request_ids: [], state: null }, rows: [], timeoutMin: 5, folder: store.folder('tries'), doorMode: cliDoor || options['--serve'] !== undefined || !openInPage });
6450
7382
  releaseInterrupt = interruptible(context);
6451
7383
  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
7384
  context.runtime = new Runtime({ origin, token: identity.token, ports, signal: context.signal, auth: context.auth, programJson: true });
@@ -6481,10 +7413,11 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
6481
7413
  const request = { requestId: ports.randomUUID(), source_sha256: capture.sha256, entry,
6482
7414
  initial_world: seeded?.initial_world ?? (options['--fresh'] ? {} : files.read()), ...(seeded?.simulation ? { simulation: seeded.simulation } : {}),
6483
7415
  ...(options['--fresh'] === true ? { fresh: true } : {}),
6484
- ...(appMap ? { app_map: appMap } : {}), tab: selected.screen ? 'screen' : 'call', max_calls: requestedBudget ?? 300, ...sourceProvenance(context, capture) };
7416
+ ...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}),
7417
+ ...(appMap ? { app_map: appMap } : {}), tab: requestedTab, max_calls: requestedBudget ?? 300, ...sourceProvenance(context, capture) };
6485
7418
  setup.request_ids.push(request.requestId);
6486
7419
  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,
7420
+ record = { id: request.requestId, root, entry, origin, login: identity.login, source_sha256: capture.sha256, max_calls: request.max_calls, ...setup,
6488
7421
  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
7422
  app_map: appMap, app_map_hash: appMap ? sha256(capture.sources.find(file => file.path === appMap).bytes) : null };
6490
7423
  files.set(record); store.posted(context.folder, record.id);
@@ -6573,9 +7506,17 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
6573
7506
  } finally { done(); }
6574
7507
  };
6575
7508
  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);
7509
+ if (cliDoor) return await (await import('./try-doors.mjs')).openCli(context, { path: entry, programEntry: entry, title: entry }, record.id, options);
7510
+ 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 });
7511
+ let openLink = link;
7512
+ if (options['--tab'] === undefined && requestedTab !== 'screen') {
7513
+ try {
7514
+ const model = await context.runtime.send(`/v1/try/${record.id}/model`, { method: 'GET' }, GET_MS);
7515
+ if (model.status === 200 && model.json?.app_map === true) openLink = withTryTab(link, 'screen');
7516
+ } catch { /* Preserve the confirmed link when optional model inspection is unavailable. */ }
7517
+ }
7518
+ line(ports.stdout, `Program ready: ${openLink}`);
7519
+ if (!options['--no-open']) await ports.openUrl(openLink);
6579
7520
  try {
6580
7521
  do {
6581
7522
  const done = files.lock();
@@ -6716,6 +7657,16 @@ async function runDirectProgram({words,options,cwd}, ports) {
6716
7657
  let last = directPrivate(lastPath), pendingCall = last?.state === 'unknown' && last.id;
6717
7658
  if(!pendingCall&&!descriptor?.setupPending)directPrivate(lastPath,{state:'unknown',id:null,input:{argv:words.slice(1)}});
6718
7659
  const capture = directCapture(root,promptPath,ports,selected.unadmitted), sourceHash = capture.sha256;
7660
+ const directPrompts = new Map();
7661
+ const directCallsProblems = [];
7662
+ for (const file of capture.sources) {
7663
+ if (!file.path.endsWith('.prompt.md')) continue;
7664
+ let prompt;
7665
+ try { prompt = readPrompt(root, visible, file.path, workspace); } catch { continue; }
7666
+ directPrompts.set(file.path, prompt);
7667
+ directCallsProblems.push(...plainMarkdownCallsProblems(root, visible, prompt, directPrompts, workspace));
7668
+ }
7669
+ if (directCallsProblems.length) throw Object.assign(new Stop(125, directCallsProblems.map(item => item.message).join('; ')), { fix: directCallsProblems[0].hint });
6719
7670
  context.draft=descriptor?.sourceHash===sourceHash&&descriptor.draft===true||capture.sources.some(file=>file.path.endsWith('.prompt.md')&&/"status"\s*:\s*"draft"/.test(file.bytes.toString('utf8')));
6720
7671
  const store = stateFor(ports.env,root), origin = runtimeOrigin(ports.env), identity = signIn(ports.gh,store,ports,{exitCode:125});
6721
7672
  secrets = [identity.token];
@@ -6868,7 +7819,7 @@ async function runDirectProgram({words,options,cwd}, ports) {
6868
7819
  function shouldUseDirectProgram(words, options, cwd) {
6869
7820
  if (typeof words[0] !== 'string' || !words[0].endsWith('.prompt.md')) return false;
6870
7821
  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;
7822
+ if (['--serve', '--allow-origins', '--trust-proxy', '--serve-token', '--serve-header', '--page', '--tab', '--cli', '--shell', '--no-open', '--no-wait', '--new', '--stop', '--app-map', '--max-calls', '--agent'].some(key => options[key] !== undefined)) return false;
6872
7823
  try {
6873
7824
  const text = readFileSync(resolve(cwd, words[0]), 'utf8');
6874
7825
  return /\b(?:cli|argv|stdin|stdout|exit_code|command-line)\b/i.test(text);
@@ -6879,7 +7830,7 @@ function shouldUseDirectProgram(words, options, cwd) {
6879
7830
 
6880
7831
  function shouldUseTypedTry(words, options, cwd) {
6881
7832
  if (typeof words[0] !== 'string' || !words[0].endsWith('.prompt.md')) return false;
6882
- if (['--serve', '--page', '--tab', '--cli', '--shell', '--no-open', '--new', '--stop', '--app-map', '--max-calls', '--data', '--fresh', '--show-data', '-q', '--quiet'].some(key => options[key] !== undefined)) return false;
7833
+ if (['--serve', '--allow-origins', '--trust-proxy', '--serve-token', '--serve-header', '--page', '--tab', '--cli', '--shell', '--no-open', '--new', '--stop', '--app-map', '--max-calls', '--data', '--fresh', '--show-data', '-q', '--quiet'].some(key => options[key] !== undefined)) return false;
6883
7834
  try {
6884
7835
  const text = readFileSync(resolve(cwd, words[0]), 'utf8');
6885
7836
  const blocks = interfaceBlocks(text);
@@ -7038,7 +7989,20 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7038
7989
  if(options['--product']!==undefined&&!productMode || !productMode&&['--parts','--journey'].some(key=>options[key]!==undefined))throw new Stop(2,'--parts and --journey require --product.');
7039
7990
  if(productMode&&options['--app-map']!==undefined)throw new Stop(2,'--product builds its map; omit --app-map.');
7040
7991
  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 });
7992
+ const hasServeExtras = ['--allow-origins', '--trust-proxy', '--serve-token', '--serve-header'].some(key => options[key] !== undefined);
7993
+ if (hasServeExtras && options['--serve'] === undefined) {
7994
+ throw new Stop(2, '--allow-origins, --trust-proxy, --serve-token and --serve-header require --serve.');
7995
+ }
7996
+ if (hasServeExtras) {
7997
+ let parsedServe;
7998
+ try { parsedServe = (await import('./try-http.mjs')).parseServeOptions(options); }
7999
+ catch (error) { throw new Stop(2, error.message); }
8000
+ if (parsedServe.serveToken) {
8001
+ context.secrets = [...(context.secrets ?? []), parsedServe.serveToken];
8002
+ recordSecret(ports, parsedServe.serveToken);
8003
+ }
8004
+ }
8005
+ 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
8006
  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
8007
  const doorModes = [options['--cli'] || options['--shell'], options['--serve'] !== undefined, options['--page'] || options['--tab'] !== undefined || options['--agent'] !== undefined, options['--save-last']].filter(Boolean);
7044
8008
  if (doorModes.length > 1 || (doorModes.length && options['--stop'])
@@ -7062,6 +8026,16 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7062
8026
  const origin = runtimeOrigin(ports.env);
7063
8027
  if (options['--stop']) return await stopByName(context, cwd, words, origin);
7064
8028
  const { root, found, normalized } = localSetup(cwd, words, ports), store = stateFor(ports.env, root);
8029
+ if (!productMode && !normalized.length && !found.tests.length && !(found.untested?.length)) {
8030
+ const workspace = found.workspace ?? loadRuntimeWorkspace({ root });
8031
+ const standalonePrompts = [...(found.discoveryVisible ?? found.visible)]
8032
+ .filter(path => path.endsWith('.prompt.md') && allowsRuntimePath(workspace, path))
8033
+ .sort();
8034
+ if (standalonePrompts.length === 1) {
8035
+ const targetWord = relative(realpathSync(cwd), join(realpathSync(root), standalonePrompts[0])).split(sep).join('/') || standalonePrompts[0];
8036
+ return await runProgramTry({ cwd, word: targetWord, options, context, requestedBudget });
8037
+ }
8038
+ }
7065
8039
  await prepareLiveManifest(context,options,root);
7066
8040
  const repoState = store.repo(root);
7067
8041
  if (!productMode && normalized.length && !options['--new']) {
@@ -7071,8 +8045,10 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7071
8045
  const productSetup = options['--product'] ? { parts: options['--parts']?.split(',').map(p => p.trim()) ?? null, journey: options['--journey'] ?? null } : null;
7072
8046
  const localSelected = productSetup ? [productTest(found, normalized, options['--journey'], root, ports)]
7073
8047
  : 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;
8048
+ const localEntryPaths = entryPaths(localSelected);
8049
+ const allowMissingInterfaces = hasMissingPromptInterface(root, found, localEntryPaths)
8050
+ ? (hasMissingNonUiPromptInterface(root, found, localEntryPaths) ? await probeLazyInterfaces(context, origin, store) : true)
8051
+ : false;
7076
8052
  const checked = preflight({ root, found, selected: localSelected, allowMissingInterfaces }), rows = localRows(checked.rows);
7077
8053
  for (const item of rows) item.app_maps = declaredMaps(localSelected.find(candidate => candidate.path === item.test)?.doc);
7078
8054
  const refused = rows.find(row => row.state === 'refused');
@@ -7092,7 +8068,8 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7092
8068
  const boundedCapture = !productSetup && loadRuntimeWorkspace({root}).configured && localSelected.length ? ports.captureSource(root, { tests: localSelected.map(item => item.path), appMap, ...captureExtra }) : null;
7093
8069
  let { test, selected, tab, typed } = productSetup
7094
8070
  ? { test: localSelected[0], selected: localSelected, tab: options['--tab'] ?? (options['--cli'] || options['--shell'] ? 'terminal' : 'screen'), typed: false }
7095
- : simulationSelection(root, found, normalized, appMap, options, ports);
8071
+ : simulationSelection(root, found, normalized, appMap, options, ports, { allowMissingInterfaces });
8072
+ context.allowMissingInterfaces = allowMissingInterfaces;
7096
8073
  if (productSetup && options['--shell']) options['--cli'] = true;
7097
8074
  const wholeRecords = productSetup || normalized.length ? [] : Object.entries(repoState.tries ?? {}).filter(([, value]) => isObject(value.simulation_scope));
7098
8075
  if (wholeRecords.length > 1) throw new Stop(2, 'Several whole-project simulations are saved. Stop a named Try with pdd simulate --stop STORY before opening the whole project.');
@@ -7135,7 +8112,7 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7135
8112
  if(context.agentConnection&&loadRuntimeWorkspace({root}).configured)throw new Stop(5,'Bounded agent connection is unavailable: installed CLI controls do not establish packet-only context. Use the ordinary simulator without an agent connection.');
7136
8113
  const identity = context.probedIdentity ?? signIn(ports.gh, context.store, ports, { exitCode: context.doorMode ? 125 : 5 });
7137
8114
  if(context.liveLocal)context.localOwner??=identity.login;
7138
- Object.assign(context, { capture, identity, secrets: [identity.token], startedAt: ports.now(), deadline: ports.now() + TRY_MS, lint: { request_ids: [], state: null },
8115
+ Object.assign(context, { capture, identity, secrets: [...(context.secrets ?? []), identity.token], startedAt: ports.now(), deadline: ports.now() + TRY_MS, lint: { request_ids: [], state: null },
7139
8116
  batch: null, rows, timeoutMin: TRY_MS / 60_000, agentLimit: false, head: null });
7140
8117
  context.folder = store.folder('tries');
7141
8118
  release = interruptible(context);
@@ -7251,7 +8228,8 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7251
8228
  await store.updateRepo(root, current => ({ ...current, tries: { ...current.tries, [test.path]: tryRecord } }));
7252
8229
  store.posted(context.folder, request.requestId);
7253
8230
  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())));
8231
+ const dedupTry = context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: true } : undefined;
8232
+ reply = await context.runtime.post('/v1/try', request, capture.tar, Math.max(1, Math.min(ports.postMs, context.deadline - ports.now())), dedupTry);
7255
8233
  verdict = judgePost(reply, request.requestId, 'try', context.secrets);
7256
8234
  if (verdict.maintenance) maintenanceNotice(context, verdict, reply);
7257
8235
  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 +8300,48 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7322
8300
  } 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
8301
  }
7324
8302
 
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).
8303
+ // 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
8304
  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
- }));
8305
+ const { ports } = context, root = repoRoot(cwd), realRoot = realpathSync(root), store = stateFor(ports.env, root), repoState = store.repo(root);
8306
+ const storyEntries = Object.entries(repoState.tries ?? {}).map(([path, record]) => ({ kind: 'story', path, record }));
8307
+ const programEntries = [];
8308
+ const programsDir = join(store.dir, 'programs');
8309
+ if (statOrNull(programsDir)?.isDirectory()) {
8310
+ for (const name of readdirSync(programsDir).sort()) {
8311
+ if (!name.endsWith('.json')) continue;
8312
+ const metaPath = join(programsDir, name);
8313
+ let record;
8314
+ try { record = store.read(metaPath); } catch { continue; }
8315
+ if (!isObject(record) || !UUID.test(record.id ?? '') || typeof record.entry !== 'string') continue;
8316
+ const matchesRepo = name === `${sha256(realRoot + '\0' + record.entry)}.json` || name === `${sha256(root + '\0' + record.entry)}.json`;
8317
+ if (!matchesRepo) continue;
8318
+ programEntries.push({ kind: 'program', path: record.entry, metaPath, record });
8319
+ }
8320
+ }
8321
+ const entries = [...storyEntries, ...programEntries];
8322
+ let word = words[0]?.replace(/^\.\//, '');
8323
+ if (words[0] !== undefined) {
8324
+ const rel = relative(realRoot, resolve(realpathSync(cwd), words[0])).split(sep).join('/');
8325
+ if (rel && !rel.startsWith('../') && entries.some(item => item.path === rel || item.record.storyPath === rel || item.record.app_map === rel)) {
8326
+ word = rel;
8327
+ }
8328
+ }
8329
+ const names = entries.map(item => item.kind === 'program' ? item.record.entry : (item.record.story ?? basename(item.path, '.json'))).join(', ') || 'none';
8330
+ const records = entries.map(item => item.kind === 'program'
8331
+ ? {
8332
+ id: String(item.record.id ?? ''),
8333
+ test_path: item.record.entry,
8334
+ test_name: basename(item.record.entry, '.prompt.md'),
8335
+ story: basename(item.record.entry),
8336
+ story_path: String(item.record.app_map ?? item.record.entry),
8337
+ }
8338
+ : {
8339
+ id: String(item.record.id ?? ''),
8340
+ test_path: item.path,
8341
+ test_name: basename(item.path, '.json'),
8342
+ story: String(item.record.story ?? basename(item.path, '.json')),
8343
+ story_path: String(item.record.storyPath ?? ''),
8344
+ });
7337
8345
  let picked;
7338
8346
  try {
7339
8347
  picked = selectTryToStop({ ...(word !== undefined ? { selector: word } : {}), records });
@@ -7341,8 +8349,9 @@ async function stopByName(context, cwd, words, origin) {
7341
8349
  throw new Stop(2, word !== undefined ? `No open Try for "${cleanText(word)}". Open Try links: ${names}.`
7342
8350
  : entries.length ? `Name the Try to stop. Open Try links: ${names}.` : 'No open Try in this repository.');
7343
8351
  }
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;
8352
+ const selected = entries.find(item => item.path === picked.test_path && String(item.record.id ?? '') === picked.id);
8353
+ const { path, record } = selected;
8354
+ const title = record.title ?? record.story ?? record.entry ?? path;
7346
8355
  Object.assign(context, { root, store, origin });
7347
8356
  const identity = signIn(ports.gh, store, ports);
7348
8357
  context.secrets = [identity.token];
@@ -7357,7 +8366,12 @@ async function stopByName(context, cwd, words, origin) {
7357
8366
  context.runtime = new Runtime({ origin: record.origin ?? origin, token: identity.token, ports, auth: context.auth });
7358
8367
  line(ports.stderr, `Stopping the Try for "${title}"…`);
7359
8368
  await stopTry(context, record);
7360
- await store.updateRepo(root, current => { if (current.tries?.[path]?.id === record.id) delete current.tries[path]; return current; });
8369
+ if (selected.kind === 'program') {
8370
+ const current = store.read(selected.metaPath);
8371
+ if (current?.id === record.id) store.write(selected.metaPath, null);
8372
+ } else {
8373
+ await store.updateRepo(root, current => { if (current.tries?.[path]?.id === record.id) delete current.tries[path]; return current; });
8374
+ }
7361
8375
  line(ports.stdout, `The Try link for "${title}" is stopped.`);
7362
8376
  return 0;
7363
8377
  }
@@ -7404,7 +8418,7 @@ async function checkLint(context, rows) {
7404
8418
  const APP_MAP_RULES = { 'ambiguous-handler': 'on one screen, all taps of one kind must match by the same key',
7405
8419
  'template-reference-schema': 'a field that gets a value from the screen ($ref) must be a plain {"type": "string"}',
7406
8420
  'invalid-after-step': 'an after step has the wrong fields' };
7407
- const AFTER_STEP_SHAPE_HELP = 'Write each after step as {"handler": {"prompt_path": "...", "operation": "..."}, "input": {...}, "bind": "/field"} (RUNBOOK §13).';
8421
+ const AFTER_STEP_SHAPE_HELP = 'Write each after step as {"handler": {"prompt_path": "...", "operation": "..."}, "input": {...}, "bind": "/field"} (see the pdd skill reference ui-and-screens.md, or run pdd help prompting).';
7408
8422
  const GENERIC_REFUSAL = /^The runtime refused this (?:job|run)\b/;
7409
8423
  const isAppMapCode = code => Object.hasOwn(APP_MAP_RULES, code) || code === 'invalid-clipboard-action' || /^(?:after|app-map|invalid-app-map)-/.test(code);
7410
8424
  function normalizeTryRefusals(context, refusals) {
@@ -7445,7 +8459,7 @@ function trySetupRefused(context, test, appMap, refusals, reportUrl) {
7445
8459
  line(context.ports.stdout, `The Try could not start: ${mapped ? 'the app map was refused' : 'the server refused it'} (${why}).`);
7446
8460
  line(context.ports.stdout, fix ? `${fix}${needsAfterHelp ? ` ${AFTER_STEP_SHAPE_HELP}` : ''} Then ${again}`
7447
8461
  : needsAfterHelp ? `${mapped ? `Fix ${target}. ` : ''}${AFTER_STEP_SHAPE_HELP} Then ${again}`
7448
- : mapped ? `Fix ${target} (RUNBOOK §13), then ${again}`
8462
+ : mapped ? `Fix ${target} (see the pdd skill reference ui-and-screens.md, or run pdd help prompting), then ${again}`
7449
8463
  : `Fix what it names, then ${again}${reportUrl ? ` Details: ${reportUrl}` : ''}`);
7450
8464
  return 4;
7451
8465
  }
@@ -7461,6 +8475,9 @@ const validSha256Hex = value => typeof value === 'string' && /^[0-9a-f]{64}$/i.t
7461
8475
  const validEngineHex = value => typeof value === 'string' && /^[0-9a-f]{8,40}$/i.test(value) ? value.toLowerCase() : null;
7462
8476
 
7463
8477
  async function showTry(context, test, link, options, tryId, reused = false, session, answer = null, record = null) {
8478
+ if (options['--tab'] === undefined && answer?.result?.app_map === true && !options['--cli'] && options['--serve'] === undefined) {
8479
+ link = withTryTab(link, 'screen');
8480
+ }
7464
8481
  if (context.typedForm) line(context.ports.stderr, "This Story's operation takes typed input, so it opens on the Form tab.");
7465
8482
  const budget = Number.isSafeInteger(session?.max_calls) && session.max_calls > 0 && Number.isSafeInteger(session?.remaining_calls)
7466
8483
  && session.remaining_calls >= 0 && session.remaining_calls <= session.max_calls
@@ -8073,7 +9090,8 @@ async function doorWorldObservation(runtime,sessionId,report,actionId) {
8073
9090
  ?state.json.actions.find(action=>action.action_id===actionId):null;
8074
9091
  if(matched)observation={...observation,
8075
9092
  ...(Object.hasOwn(matched,'input_world')?{input_world:matched.input_world}:{}),
8076
- ...(Object.hasOwn(matched,'world')?{world:matched.world}:{})};
9093
+ ...(Object.hasOwn(matched,'world')?{world:matched.world}:{}),
9094
+ ...(isObject(matched.calls)?{calls:matched.calls}:{})};
8077
9095
  } catch { /* Observation is optional; the confirmed result remains confirmed. */ }
8078
9096
  return observation;
8079
9097
  }
@@ -8234,13 +9252,17 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
8234
9252
  const limit = stepTimeLimit(answer, { steps: [{ step_id: operation }], secrets: secrets });
8235
9253
  const why = answer.result?.refusals?.[0];
8236
9254
  if (limit) throw Object.assign(new Stop(125, `${limit.message} ${limit.fix}${recovery}`), { tryUsage: usage });
8237
- throw Object.assign(new Stop(125, cleanText(why?.engine_message || why?.message || why?.code || 'The command result is unknown. Do not repeat it automatically.', secrets) + (['failed', 'refused'].includes(answer.state) ? '' : recovery)), { tryUsage: usage,fix:why?.fix });
9255
+ throw Object.assign(new Stop(125, cleanText(why?.engine_message || why?.message || why?.code || reportError?.message || reportError?.code || 'The command result is unknown. Do not repeat it automatically.', secrets) + (['failed', 'refused'].includes(answer.state) ? '' : recovery)), { tryUsage: usage,fix:why?.fix });
8238
9256
  }
8239
9257
  knownOutcome = true;
8240
9258
  const hasEmbeddedWorld = Object.hasOwn(answer.result ?? {}, 'world');
8241
9259
  const hasEmbeddedInputWorld = Object.hasOwn(answer.result ?? {}, 'input_world') || Object.hasOwn(rawReport ?? {}, 'input_world');
8242
9260
  const observation = !(hasEmbeddedWorld && hasEmbeddedInputWorld) && (typeof projected.action_id === 'string' || descriptor.directProgram)
8243
9261
  ? await doorWorldObservation(runtime,sessionId,rawReport,projected.action_id) : rawReport ?? {};
9262
+ const recordedCalls = isObject(rawReport?.calls) ? rawReport.calls
9263
+ : isObject(observation?.calls) ? observation.calls : undefined;
9264
+ const recordingAvailable = typeof rawReport?.recording_available === 'boolean'
9265
+ ? rawReport.recording_available : undefined;
8244
9266
  const confirmed = {
8245
9267
  id,
8246
9268
  actionId: projected.action_id,
@@ -8251,6 +9273,8 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
8251
9273
  callChain: rawReport?.call_chain,
8252
9274
  inputWorld: Object.hasOwn(answer.result ?? {}, 'input_world') ? answer.result.input_world : observation.input_world,
8253
9275
  world: hasEmbeddedWorld ? answer.result.world : observation.world,
9276
+ ...(recordedCalls !== undefined ? { calls: recordedCalls } : {}),
9277
+ ...(recordingAvailable !== undefined ? { recordingAvailable } : {}),
8254
9278
  };
8255
9279
  if (sourcePins && projected.outcome === 'result') await store.updateLastRun(root, current => current?.id !== id ? undefined : ({state:'confirmed',
8256
9280
  descriptor:{root,sessionId,origin,login,prompt,operation,...sourcePins},
@@ -8422,6 +9446,730 @@ export async function reconcileCheckReceipt({ cwd = process.cwd(), requestId, or
8422
9446
  });
8423
9447
  }
8424
9448
 
9449
+ async function queryHostedCheckReconciliation(runtime, requestId) {
9450
+ const reply = await runtime.send(`/v1/runs/${encodeURIComponent(requestId)}/reconciliation`, { method: 'GET' }, GET_MS);
9451
+ const status = reply.status ?? 0;
9452
+ if (status === 200) {
9453
+ const projected = projectCheckReconciliation({ request_id: requestId, status, body: reply.json });
9454
+ if (projected.accounting.status === 'complete_zero') {
9455
+ return {
9456
+ request_id: requestId,
9457
+ status: 'settled',
9458
+ cleared: true,
9459
+ known_calls: 0,
9460
+ accounting_complete: true,
9461
+ disposition_state: projected.disposition.state,
9462
+ refusal_code: projected.disposition.refusal_code,
9463
+ proof_basis: projected.evidence.proof_basis,
9464
+ reason: 'Authoritative server reconciliation confirmed 0 calls and no dispatch.',
9465
+ };
9466
+ }
9467
+ if (projected.accounting.status === 'complete_dispatched') {
9468
+ return {
9469
+ request_id: requestId,
9470
+ status: 'settled',
9471
+ cleared: true,
9472
+ known_calls: projected.accounting.known_calls,
9473
+ accounting_complete: true,
9474
+ disposition_state: projected.disposition.state,
9475
+ refusal_code: projected.disposition.refusal_code,
9476
+ proof_basis: projected.evidence.proof_basis,
9477
+ reason: `Authoritative server reconciliation confirmed terminal ${projected.disposition.state} (${projected.accounting.known_calls} calls).`,
9478
+ };
9479
+ }
9480
+ if (projected.disposition.expired || projected.disposition.purged) {
9481
+ return {
9482
+ request_id: requestId,
9483
+ status: 'expired',
9484
+ cleared: true,
9485
+ known_calls: null,
9486
+ accounting_complete: false,
9487
+ disposition_state: projected.disposition.state,
9488
+ refusal_code: projected.disposition.refusal_code,
9489
+ reason: 'Hosted run evidence has expired on the server; historical unknown usage retained.',
9490
+ };
9491
+ }
9492
+ if (projected.disposition.terminal === true) {
9493
+ return {
9494
+ request_id: requestId,
9495
+ status: 'terminated',
9496
+ cleared: true,
9497
+ known_calls: null,
9498
+ accounting_complete: false,
9499
+ disposition_state: projected.disposition.state,
9500
+ refusal_code: projected.disposition.refusal_code,
9501
+ reason: `Hosted run terminated (${projected.disposition.state}${projected.disposition.refusal_code ? `: ${projected.disposition.refusal_code}` : ''}); historical unknown usage retained.`,
9502
+ };
9503
+ }
9504
+ if (['queued', 'running'].includes(projected.disposition.state)) {
9505
+ return {
9506
+ request_id: requestId,
9507
+ status: 'active',
9508
+ cleared: false,
9509
+ known_calls: null,
9510
+ accounting_complete: false,
9511
+ disposition_state: projected.disposition.state,
9512
+ refusal_code: null,
9513
+ reason: `Hosted run is still ${projected.disposition.state}; reservation retained.`,
9514
+ };
9515
+ }
9516
+ return {
9517
+ request_id: requestId,
9518
+ status: 'unavailable',
9519
+ cleared: false,
9520
+ known_calls: null,
9521
+ accounting_complete: false,
9522
+ disposition_state: projected.disposition.state,
9523
+ refusal_code: projected.disposition.refusal_code,
9524
+ reason: projected.retry.safe_next_action,
9525
+ };
9526
+ }
9527
+ if (status === 410) {
9528
+ return {
9529
+ request_id: requestId,
9530
+ status: 'expired',
9531
+ cleared: true,
9532
+ known_calls: null,
9533
+ accounting_complete: false,
9534
+ disposition_state: 'unknown',
9535
+ refusal_code: null,
9536
+ reason: 'Hosted run evidence expired (HTTP 410); historical unknown usage retained.',
9537
+ };
9538
+ }
9539
+ if (status === 404 && reply.json?.error?.code === 'run-not-found') {
9540
+ return {
9541
+ request_id: requestId,
9542
+ status: 'not-found',
9543
+ cleared: true,
9544
+ known_calls: null,
9545
+ accounting_complete: false,
9546
+ disposition_state: 'unknown',
9547
+ refusal_code: null,
9548
+ reason: 'No hosted run exists for this request ID (HTTP 404); historical unknown usage retained.',
9549
+ };
9550
+ }
9551
+ if (status === 405 || status === 501 || (status === 404 && reply.json?.error?.code !== 'run-not-found')) {
9552
+ const fallback = await runtime.get(requestId);
9553
+ const fbStatus = fallback.status ?? 0;
9554
+ if (fbStatus === 404) {
9555
+ return {
9556
+ request_id: requestId,
9557
+ status: 'not-found',
9558
+ cleared: true,
9559
+ known_calls: null,
9560
+ accounting_complete: false,
9561
+ disposition_state: 'unknown',
9562
+ refusal_code: null,
9563
+ reason: 'No hosted run exists for this request ID (HTTP 404); historical unknown usage retained.',
9564
+ };
9565
+ }
9566
+ if (fbStatus === 410) {
9567
+ return {
9568
+ request_id: requestId,
9569
+ status: 'expired',
9570
+ cleared: true,
9571
+ known_calls: null,
9572
+ accounting_complete: false,
9573
+ disposition_state: 'unknown',
9574
+ refusal_code: null,
9575
+ reason: 'Hosted run evidence expired (HTTP 410); historical unknown usage retained.',
9576
+ };
9577
+ }
9578
+ if ((fbStatus === 200 || fbStatus === 202) && sameJob(fallback.json, requestId, 'check')) {
9579
+ const job = fallback.json;
9580
+ if (['queued', 'running'].includes(job.state)) {
9581
+ return {
9582
+ request_id: requestId,
9583
+ status: 'active',
9584
+ cleared: false,
9585
+ known_calls: null,
9586
+ accounting_complete: false,
9587
+ disposition_state: job.state,
9588
+ refusal_code: null,
9589
+ reason: `Hosted run is still ${job.state}; reservation retained.`,
9590
+ };
9591
+ }
9592
+ if (accountingEnd(job, requestId)) {
9593
+ const part = usagePart(job);
9594
+ const unknownWithoutExplicitProof = job.state === 'unknown'
9595
+ && ![job, job.usage, job.result, job.report, job.result?.report].some(s => isObject(s) && s.accounting_complete === true);
9596
+ if (!unknownWithoutExplicitProof && part.complete && Number.isSafeInteger(part.total)) {
9597
+ return {
9598
+ request_id: requestId,
9599
+ status: 'settled',
9600
+ cleared: true,
9601
+ known_calls: part.total,
9602
+ accounting_complete: true,
9603
+ disposition_state: job.state,
9604
+ refusal_code: job.result?.report?.refusal?.code ?? job.result?.refusals?.[0]?.code ?? null,
9605
+ reason: `Hosted run settled as ${job.state} (${part.total} calls).`,
9606
+ };
9607
+ }
9608
+ return {
9609
+ request_id: requestId,
9610
+ status: 'terminated',
9611
+ cleared: true,
9612
+ known_calls: null,
9613
+ accounting_complete: false,
9614
+ disposition_state: job.state,
9615
+ refusal_code: job.result?.report?.refusal?.code ?? job.result?.refusals?.[0]?.code ?? null,
9616
+ reason: `Hosted run terminated (${job.state}); historical unknown usage retained.`,
9617
+ };
9618
+ }
9619
+ }
9620
+ return {
9621
+ request_id: requestId,
9622
+ status: 'unavailable',
9623
+ cleared: false,
9624
+ known_calls: null,
9625
+ accounting_complete: false,
9626
+ disposition_state: 'unknown',
9627
+ refusal_code: null,
9628
+ reason: `Hosted run lookup unavailable (HTTP ${fbStatus}).`,
9629
+ };
9630
+ }
9631
+ return {
9632
+ request_id: requestId,
9633
+ status: 'unavailable',
9634
+ cleared: false,
9635
+ known_calls: null,
9636
+ accounting_complete: false,
9637
+ disposition_state: 'unknown',
9638
+ refusal_code: null,
9639
+ reason: `Hosted reconciliation lookup unavailable (HTTP ${status}).`,
9640
+ };
9641
+ }
9642
+
9643
+ async function reconcileBatchInternal({ root, store, batchId, explicitOrigin = null, ports, sessionCache = null, localExpirePastTtlOnly = false }) {
9644
+ const folder = join(store.dir, 'batches', batchId);
9645
+ const batchPath = join(folder, 'batch.json');
9646
+ if (!statOrNull(batchPath)) {
9647
+ throw Object.assign(new Stop(2, `No saved batch ${batchId}.`), { code: 'batch-not-found' });
9648
+ }
9649
+ const now = ports.now();
9650
+ const ttlMs = priorReservationTtlMs(ports.env);
9651
+ const ttlHours = Math.round((ttlMs / 3_600_000) * 100) / 100;
9652
+ const reconciledAt = new Date(now).toISOString();
9653
+ const lockContext = { store, ports, root, folder };
9654
+ await ownBatch(lockContext, batchId);
9655
+ try {
9656
+ const saved = store.read(batchPath);
9657
+ if (!isObject(saved) || !Array.isArray(saved.rows)) {
9658
+ throw Object.assign(new Stop(2, `Saved batch ${batchId} is unreadable or invalid.`), { code: 'invalid-batch' });
9659
+ }
9660
+ if (typeof saved.root !== 'string' || realish(saved.root) !== realish(root)) {
9661
+ throw Object.assign(new Stop(2, 'This saved batch belongs to a different repository.'), { code: 'wrong-repo' });
9662
+ }
9663
+ if (saved.intent !== 'check' && !(saved.version === 1 && saved.intent === undefined)) {
9664
+ throw Object.assign(new Stop(2, `Saved batch ${batchId} has no Check intent.`), { code: 'not-check-batch' });
9665
+ }
9666
+ const adoptContext = { store, folder, ports };
9667
+ const unresolvedRows = [];
9668
+ for (const row of saved.rows) {
9669
+ if (!isObject(row)) continue;
9670
+ if (!Array.isArray(row.request_ids)) row.request_ids = [];
9671
+ adoptClaims(adoptContext, row);
9672
+ if (rowNeedsReservationCheck(row)) unresolvedRows.push(row);
9673
+ }
9674
+ if (!unresolvedRows.length) {
9675
+ return {
9676
+ schema_version: 'pdd-runtime.batch-reconciliation.v1',
9677
+ batch: batchId,
9678
+ repo: root,
9679
+ reconciled_at: reconciledAt,
9680
+ ttl_hours: ttlHours,
9681
+ status: 'already-resolved',
9682
+ cleared_count: 0,
9683
+ settled_count: 0,
9684
+ expired_count: 0,
9685
+ terminated_count: 0,
9686
+ active_count: 0,
9687
+ unavailable_count: 0,
9688
+ remaining_unresolved_count: 0,
9689
+ rows: [],
9690
+ };
9691
+ }
9692
+
9693
+ const origin = runtimeOrigin(explicitOrigin ? { PDD_RUNTIME_URL: explicitOrigin } : saved.origin ? { PDD_RUNTIME_URL: saved.origin } : ports.env);
9694
+ let runtime = null;
9695
+ let runtimeError = null;
9696
+ const ensureRuntime = () => {
9697
+ if (runtime) return runtime;
9698
+ if (runtimeError) throw runtimeError;
9699
+ try {
9700
+ let identity = sessionCache?.identity ?? null;
9701
+ if (!identity) {
9702
+ identity = signIn(ports.gh, store, ports);
9703
+ if (sessionCache) sessionCache.identity = identity;
9704
+ }
9705
+ if (saved.login && identity.login !== saved.login) {
9706
+ throw new Stop(5, `These runs belong to ${saved.login}. Run: gh auth switch -u ${saved.login}`);
9707
+ }
9708
+ const cacheKey = `${origin}\0${saved.login ?? ''}`;
9709
+ let cached = sessionCache?.runtimes?.get(cacheKey);
9710
+ if (!cached) {
9711
+ const secrets = [identity.token];
9712
+ const auth = authSession({
9713
+ identity,
9714
+ store,
9715
+ ports,
9716
+ secrets,
9717
+ ...(saved.login ? {
9718
+ expectedOwnerLogin: saved.login,
9719
+ ownerMismatchError: owner => new Stop(5, `These runs belong to ${owner}. Run: gh auth switch -u ${owner}`),
9720
+ } : {}),
9721
+ });
9722
+ cached = new Runtime({ origin, token: identity.token, ports, signal: ports.signal, auth });
9723
+ sessionCache?.runtimes?.set(cacheKey, cached);
9724
+ }
9725
+ runtime = cached;
9726
+ return runtime;
9727
+ } catch (error) {
9728
+ runtimeError = error;
9729
+ throw error;
9730
+ }
9731
+ };
9732
+
9733
+ const rowReports = [];
9734
+ let mutated = false;
9735
+ let clearedCount = 0, settledCount = 0, expiredCount = 0, terminatedCount = 0, activeCount = 0, unavailableCount = 0;
9736
+
9737
+ for (const row of unresolvedRows) {
9738
+ const ids = Array.isArray(row.request_ids) ? [...row.request_ids] : [];
9739
+ const previousState = row.recovery_state ?? row.state ?? 'unknown';
9740
+ const ts = reservationTimestampMs(batchId, saved, row);
9741
+ const pastTtl = ts !== null && Number.isFinite(now) && Number.isFinite(ttlMs) && now - ts >= ttlMs;
9742
+
9743
+ const localSettled = !row.dispatchIncomplete && ids.length > 0 ? localRowSettledFromReceipts(store, folder, ids) : { settled: false };
9744
+ if (localSettled.settled) {
9745
+ row.calls = localSettled.known_calls;
9746
+ row.known_calls = localSettled.known_calls;
9747
+ row.unknown_calls = 0;
9748
+ row.accounting_complete = true;
9749
+ if (localSettled.state && ['sending', 'queued', 'running', 'unknown'].includes(previousState)) {
9750
+ row.recovery_state = localSettled.state;
9751
+ row.state = localSettled.state;
9752
+ }
9753
+ row.reservation_reconciled = {
9754
+ cleared: true,
9755
+ status: 'settled',
9756
+ source: 'local-receipt',
9757
+ at: reconciledAt,
9758
+ request_ids: ids,
9759
+ calls: localSettled.known_calls,
9760
+ };
9761
+ mutated = true;
9762
+ clearedCount += 1;
9763
+ settledCount += 1;
9764
+ rowReports.push({
9765
+ test: row.test ?? '-',
9766
+ request_ids: ids,
9767
+ previous_state: previousState,
9768
+ status: 'settled',
9769
+ cleared: true,
9770
+ calls: localSettled.known_calls,
9771
+ accounting_complete: true,
9772
+ attempts: [],
9773
+ reason: `Settled locally from saved receipts (${localSettled.known_calls} calls).`,
9774
+ });
9775
+ continue;
9776
+ }
9777
+
9778
+ if (pastTtl && (localExpirePastTtlOnly || !ids.length || row.dispatchIncomplete)) {
9779
+ row.can_retry = false;
9780
+ row.busy = false;
9781
+ row.reservation_reconciled = {
9782
+ cleared: true,
9783
+ status: 'ttl-expired',
9784
+ at: reconciledAt,
9785
+ request_ids: ids,
9786
+ ttl_hours: ttlHours,
9787
+ };
9788
+ mutated = true;
9789
+ clearedCount += 1;
9790
+ expiredCount += 1;
9791
+ rowReports.push({
9792
+ test: row.test ?? '-',
9793
+ request_ids: ids,
9794
+ previous_state: previousState,
9795
+ status: 'ttl-expired',
9796
+ cleared: true,
9797
+ calls: row.calls ?? 'unknown',
9798
+ accounting_complete: false,
9799
+ attempts: [],
9800
+ reason: `Reservation exceeded bounded ${ttlHours}h TTL; cleared locally while preserving historical unknown usage.`,
9801
+ });
9802
+ continue;
9803
+ }
9804
+
9805
+ if (!ids.length || row.dispatchIncomplete) {
9806
+ unavailableCount += 1;
9807
+ rowReports.push({
9808
+ test: row.test ?? '-',
9809
+ request_ids: ids,
9810
+ previous_state: previousState,
9811
+ status: 'unavailable',
9812
+ cleared: false,
9813
+ calls: row.calls ?? 'unknown',
9814
+ accounting_complete: false,
9815
+ attempts: [],
9816
+ reason: 'Interrupted dispatch claim has no recoverable request UUID and is still within TTL; reservation retained.',
9817
+ });
9818
+ continue;
9819
+ }
9820
+
9821
+ let activeRuntime;
9822
+ try {
9823
+ activeRuntime = ensureRuntime();
9824
+ } catch (error) {
9825
+ if (pastTtl && !(error instanceof Stop && error.exitCode === 5 && String(error.message).includes('These runs belong to'))) {
9826
+ row.can_retry = false;
9827
+ row.busy = false;
9828
+ row.reservation_reconciled = {
9829
+ cleared: true,
9830
+ status: 'ttl-expired',
9831
+ at: reconciledAt,
9832
+ request_ids: ids,
9833
+ ttl_hours: ttlHours,
9834
+ };
9835
+ mutated = true;
9836
+ clearedCount += 1;
9837
+ expiredCount += 1;
9838
+ rowReports.push({
9839
+ test: row.test ?? '-',
9840
+ request_ids: ids,
9841
+ previous_state: previousState,
9842
+ status: 'ttl-expired',
9843
+ cleared: true,
9844
+ calls: row.calls ?? 'unknown',
9845
+ accounting_complete: false,
9846
+ attempts: [],
9847
+ reason: `Server reconciliation unavailable and reservation exceeded bounded ${ttlHours}h TTL; cleared locally while preserving historical unknown usage.`,
9848
+ });
9849
+ continue;
9850
+ }
9851
+ throw error;
9852
+ }
9853
+
9854
+ const attempts = [];
9855
+ for (const id of ids) {
9856
+ if (!UUID.test(id)) {
9857
+ 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.' });
9858
+ continue;
9859
+ }
9860
+ attempts.push(await queryHostedCheckReconciliation(activeRuntime, id));
9861
+ }
9862
+
9863
+ if (attempts.some(attempt => attempt.status === 'active')) {
9864
+ activeCount += 1;
9865
+ rowReports.push({
9866
+ test: row.test ?? '-',
9867
+ request_ids: ids,
9868
+ previous_state: previousState,
9869
+ status: 'active',
9870
+ cleared: false,
9871
+ calls: row.calls ?? 'unknown',
9872
+ accounting_complete: false,
9873
+ attempts,
9874
+ reason: 'At least one hosted Check attempt is still queued or running; reservation retained.',
9875
+ });
9876
+ continue;
9877
+ }
9878
+
9879
+ if (attempts.some(attempt => attempt.status === 'unavailable')) {
9880
+ if (pastTtl) {
9881
+ row.can_retry = false;
9882
+ row.busy = false;
9883
+ row.reservation_reconciled = {
9884
+ cleared: true,
9885
+ status: 'ttl-expired',
9886
+ at: reconciledAt,
9887
+ request_ids: ids,
9888
+ ttl_hours: ttlHours,
9889
+ };
9890
+ mutated = true;
9891
+ clearedCount += 1;
9892
+ expiredCount += 1;
9893
+ rowReports.push({
9894
+ test: row.test ?? '-',
9895
+ request_ids: ids,
9896
+ previous_state: previousState,
9897
+ status: 'ttl-expired',
9898
+ cleared: true,
9899
+ calls: row.calls ?? 'unknown',
9900
+ accounting_complete: false,
9901
+ attempts,
9902
+ reason: `Server reconciliation unavailable and reservation exceeded bounded ${ttlHours}h TTL; cleared locally while preserving historical unknown usage.`,
9903
+ });
9904
+ } else {
9905
+ unavailableCount += 1;
9906
+ rowReports.push({
9907
+ test: row.test ?? '-',
9908
+ request_ids: ids,
9909
+ previous_state: previousState,
9910
+ status: 'unavailable',
9911
+ cleared: false,
9912
+ calls: row.calls ?? 'unknown',
9913
+ accounting_complete: false,
9914
+ attempts,
9915
+ reason: 'Server reconciliation is currently unavailable for this within-TTL batch; reservation retained.',
9916
+ });
9917
+ }
9918
+ continue;
9919
+ }
9920
+
9921
+ if (attempts.every(attempt => attempt.status === 'settled')) {
9922
+ const totalCalls = attempts.reduce((sum, attempt) => sum + (Number.isSafeInteger(attempt.known_calls) ? attempt.known_calls : 0), 0);
9923
+ const latestState = attempts.at(-1)?.disposition_state ?? null;
9924
+ row.calls = totalCalls;
9925
+ row.known_calls = totalCalls;
9926
+ row.unknown_calls = 0;
9927
+ row.accounting_complete = true;
9928
+ if (latestState && ['sending', 'queued', 'running', 'unknown'].includes(previousState)) {
9929
+ row.recovery_state = latestState;
9930
+ row.state = latestState;
9931
+ }
9932
+ row.reservation_reconciled = {
9933
+ cleared: true,
9934
+ status: 'settled',
9935
+ source: 'server-reconciliation',
9936
+ at: reconciledAt,
9937
+ request_ids: ids,
9938
+ calls: totalCalls,
9939
+ };
9940
+ mutated = true;
9941
+ clearedCount += 1;
9942
+ settledCount += 1;
9943
+ rowReports.push({
9944
+ test: row.test ?? '-',
9945
+ request_ids: ids,
9946
+ previous_state: previousState,
9947
+ status: 'settled',
9948
+ cleared: true,
9949
+ calls: totalCalls,
9950
+ accounting_complete: true,
9951
+ attempts,
9952
+ reason: `Settled via server reconciliation (${totalCalls} calls).`,
9953
+ });
9954
+ continue;
9955
+ }
9956
+
9957
+ // All attempts terminated, expired, or not-found without complete accounting: preserve honest unknown usage & no-retry, clear stale reservation.
9958
+ const rowStatus = attempts.some(attempt => attempt.status === 'terminated')
9959
+ ? 'terminated'
9960
+ : attempts.some(attempt => attempt.status === 'expired')
9961
+ ? 'expired'
9962
+ : 'not-found';
9963
+ const refusalCode = attempts.find(attempt => attempt.refusal_code)?.refusal_code ?? null;
9964
+ row.can_retry = false;
9965
+ row.busy = false;
9966
+ row.reservation_reconciled = {
9967
+ cleared: true,
9968
+ status: rowStatus,
9969
+ source: 'server-reconciliation',
9970
+ at: reconciledAt,
9971
+ request_ids: ids,
9972
+ ...(refusalCode ? { refusal_code: refusalCode } : {}),
9973
+ };
9974
+ mutated = true;
9975
+ clearedCount += 1;
9976
+ if (rowStatus === 'terminated') terminatedCount += 1;
9977
+ else expiredCount += 1;
9978
+ rowReports.push({
9979
+ test: row.test ?? '-',
9980
+ request_ids: ids,
9981
+ previous_state: previousState,
9982
+ status: rowStatus,
9983
+ cleared: true,
9984
+ calls: row.calls ?? 'unknown',
9985
+ accounting_complete: false,
9986
+ attempts,
9987
+ reason: attempts.map(attempt => attempt.reason).join(' '),
9988
+ });
9989
+ }
9990
+
9991
+ if (mutated) {
9992
+ saved.reservations_reconciled_at = reconciledAt;
9993
+ store.write(batchPath, saved);
9994
+ updateBatchReservationIndex(store.dir, batchId, saved);
9995
+ }
9996
+
9997
+ const remainingUnresolved = activeCount + unavailableCount;
9998
+ const batchStatus = remainingUnresolved === 0
9999
+ ? 'reconciled'
10000
+ : clearedCount > 0
10001
+ ? 'partial'
10002
+ : activeCount > 0
10003
+ ? 'active'
10004
+ : 'unavailable';
10005
+ return {
10006
+ schema_version: 'pdd-runtime.batch-reconciliation.v1',
10007
+ batch: batchId,
10008
+ repo: root,
10009
+ reconciled_at: reconciledAt,
10010
+ ttl_hours: ttlHours,
10011
+ status: batchStatus,
10012
+ cleared_count: clearedCount,
10013
+ settled_count: settledCount,
10014
+ expired_count: expiredCount,
10015
+ terminated_count: terminatedCount,
10016
+ active_count: activeCount,
10017
+ unavailable_count: unavailableCount,
10018
+ remaining_unresolved_count: remainingUnresolved,
10019
+ rows: rowReports,
10020
+ };
10021
+ } finally {
10022
+ lockContext.releaseBatch?.();
10023
+ }
10024
+ }
10025
+
10026
+ export async function reconcileCheckBatch({ cwd = process.cwd(), batchId, origin: explicitOrigin } = {}, givenPorts = {}) {
10027
+ const targetBatch = String(batchId ?? '');
10028
+ if (!BATCH.test(targetBatch)) {
10029
+ 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 });
10030
+ }
10031
+ const ports = withDefaults(givenPorts);
10032
+ const root = repoRoot(cwd);
10033
+ const store = stateFor(ports.env, root);
10034
+ return await reconcileBatchInternal({ root, store, batchId: targetBatch, explicitOrigin, ports });
10035
+ }
10036
+
10037
+ export async function reconcileStaleReservations({ cwd = process.cwd(), origin: explicitOrigin } = {}, givenPorts = {}) {
10038
+ const ports = withDefaults(givenPorts);
10039
+ const root = repoRoot(cwd);
10040
+ const store = stateFor(ports.env, root);
10041
+ const now = ports.now();
10042
+ const ttlMs = priorReservationTtlMs(ports.env);
10043
+ const ttlHours = Math.round((ttlMs / 3_600_000) * 100) / 100;
10044
+ const reconciledAt = new Date(now).toISOString();
10045
+ const priorAll = readUnresolvedPriorReservations(root, ports.env, null, { now, ttlMs, includeExpired: true });
10046
+ const sessionCache = { identity: null, runtimes: new Map() };
10047
+ const batches = [];
10048
+ let batchesCleared = 0, clearedCount = 0, remainingUnresolved = 0;
10049
+
10050
+ for (const batchId of priorAll.batches) {
10051
+ try {
10052
+ const result = await reconcileBatchInternal({
10053
+ root,
10054
+ store,
10055
+ batchId,
10056
+ explicitOrigin,
10057
+ ports,
10058
+ sessionCache,
10059
+ localExpirePastTtlOnly: true,
10060
+ });
10061
+ batches.push(result);
10062
+ clearedCount += result.cleared_count;
10063
+ remainingUnresolved += result.remaining_unresolved_count;
10064
+ if (result.remaining_unresolved_count === 0) batchesCleared += 1;
10065
+ } catch (error) {
10066
+ if (error instanceof Stop && error.exitCode === 3 && String(error.message).includes('Another pdd test command is using batch')) {
10067
+ batches.push({
10068
+ schema_version: 'pdd-runtime.batch-reconciliation.v1',
10069
+ batch: batchId,
10070
+ repo: root,
10071
+ reconciled_at: reconciledAt,
10072
+ ttl_hours: ttlHours,
10073
+ status: 'active',
10074
+ cleared_count: 0,
10075
+ settled_count: 0,
10076
+ expired_count: 0,
10077
+ terminated_count: 0,
10078
+ active_count: 1,
10079
+ unavailable_count: 0,
10080
+ remaining_unresolved_count: 1,
10081
+ rows: [],
10082
+ reason: error.message,
10083
+ });
10084
+ remainingUnresolved += 1;
10085
+ continue;
10086
+ }
10087
+ throw error;
10088
+ }
10089
+ }
10090
+
10091
+ return {
10092
+ schema_version: 'pdd-runtime.stale-reconciliation.v1',
10093
+ repo: root,
10094
+ reconciled_at: reconciledAt,
10095
+ ttl_hours: ttlHours,
10096
+ batches_inspected: batches.length,
10097
+ batches_cleared: batchesCleared,
10098
+ cleared_count: clearedCount,
10099
+ remaining_unresolved_count: remainingUnresolved,
10100
+ batches,
10101
+ };
10102
+ }
10103
+
10104
+ function formatCheckReconciliationLines(result) {
10105
+ const lines = [
10106
+ `CHECK reconciliation (${result.request_id}):`,
10107
+ ` State: ${result.disposition.state} (terminal: ${result.disposition.terminal}${result.disposition.refusal_code ? `, refusal: ${result.disposition.refusal_code}` : ''}${result.disposition.expired ? ', expired' : ''})`,
10108
+ ` Dispatch: ${result.dispatch.status} (proven: ${result.dispatch.proven})`,
10109
+ ` Accounting: ${result.accounting.status} (complete: ${result.accounting.accounting_complete}, calls: ${result.accounting.calls})`,
10110
+ ` Retry blocked: ${result.retry.blocked}`,
10111
+ ` Next action: ${result.retry.safe_next_action}`,
10112
+ ];
10113
+ return lines;
10114
+ }
10115
+
10116
+ function formatBatchReconciliationLines(result) {
10117
+ if (!result.rows.length && result.status === 'already-resolved') {
10118
+ return [`Batch ${result.batch}: no unresolved prior reservations remain.`];
10119
+ }
10120
+ const parts = [];
10121
+ if (result.settled_count) parts.push(`${result.settled_count} settled`);
10122
+ if (result.terminated_count) parts.push(`${result.terminated_count} terminated`);
10123
+ if (result.expired_count) parts.push(`${result.expired_count} expired`);
10124
+ const breakdown = parts.length ? ` (${parts.join(', ')})` : '';
10125
+ const lines = [
10126
+ `Reconciled batch ${result.batch}: ${result.cleared_count} cleared${breakdown}, ${result.remaining_unresolved_count} remaining unresolved.`,
10127
+ ];
10128
+ for (const row of result.rows) {
10129
+ lines.push(` ${row.test}: ${row.status} (calls: ${row.calls}; cleared: ${row.cleared ? 'yes' : 'no'}) — ${row.reason}`);
10130
+ }
10131
+ return lines;
10132
+ }
10133
+
10134
+ function formatStaleReconciliationLines(result) {
10135
+ if (result.batches_inspected === 0) {
10136
+ return ['No unresolved prior reservations found for this repository.'];
10137
+ }
10138
+ const lines = [
10139
+ `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.`,
10140
+ ];
10141
+ for (const batch of result.batches) {
10142
+ if (batch.reason) lines.push(` ${batch.batch}: ${batch.status} — ${batch.reason}`);
10143
+ else lines.push(` ${batch.batch}: ${batch.status} (${batch.cleared_count} cleared, ${batch.remaining_unresolved_count} remaining)`);
10144
+ }
10145
+ return lines;
10146
+ }
10147
+
10148
+ async function runReconcileCommand(context, rawTarget, cwd, givenPorts) {
10149
+ const target = typeof rawTarget === 'string' ? rawTarget.trim() : '';
10150
+ if (!UUID.test(target) && !BATCH.test(target)) {
10151
+ 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).`);
10152
+ }
10153
+ if (UUID.test(target)) {
10154
+ const result = await reconcileCheckReceipt({ cwd, requestId: target }, givenPorts);
10155
+ if (context.json) line(context.ports.stdout, JSON.stringify(result));
10156
+ else for (const text of formatCheckReconciliationLines(result)) line(context.ports.stdout, text);
10157
+ return result.available === true ? 0 : 3;
10158
+ }
10159
+ const result = await reconcileCheckBatch({ cwd, batchId: target }, givenPorts);
10160
+ if (context.json) line(context.ports.stdout, JSON.stringify(result));
10161
+ else for (const text of formatBatchReconciliationLines(result)) line(context.ports.stdout, text);
10162
+ return result.remaining_unresolved_count === 0 ? 0 : 3;
10163
+ }
10164
+
10165
+ async function runReconcileStaleCommand(context, rawFlag, cwd, givenPorts) {
10166
+ if (rawFlag !== true) throw new Stop(2, '--reconcile-stale takes no value.');
10167
+ const result = await reconcileStaleReservations({ cwd }, givenPorts);
10168
+ if (context.json) line(context.ports.stdout, JSON.stringify(result));
10169
+ else for (const text of formatStaleReconciliationLines(result)) line(context.ports.stdout, text);
10170
+ return result.remaining_unresolved_count === 0 ? 0 : 3;
10171
+ }
10172
+
8425
10173
  export async function readTryOwner({ cwd = process.cwd(), story, tryId } = {}, givenPorts = {}) {
8426
10174
  const ports = withDefaults(givenPorts), root = repoRoot(cwd), found = ports.findTests({ root }), store = stateFor(ports.env, root);
8427
10175
  const repo = store.repo(root);
@@ -8723,9 +10471,11 @@ export async function inspectProgram(context, capture, { appMap } = {}) {
8723
10471
  if (verdict.kind === 'busy' && await waitBudget(context, verdict.wait)) continue;
8724
10472
  if (!['accepted','unknown'].includes(verdict.kind)) throw problem(verdict.refusal?.message ?? verdict.note?.message ?? 'Program lint was refused. Fix the prompt and run again.');
8725
10473
  const answer = await readProgramReceipt(context,id,'lint',verdict,context.lint);
10474
+ const failClosed = lintFailClosed(answer);
8726
10475
  if (answer?.state !== 'passed' || answer.result?.report?.lint?.complete !== true && answer.result?.problems_complete !== true
10476
+ || failClosed
8727
10477
  || answer.result?.report?.program?.refused_prompts?.length || answer.result?.refusals?.length) {
8728
- throw problem(answer?.result?.refusals?.[0]?.message ?? answer?.result?.report?.program?.refused_prompts?.[0]?.message ?? 'Program lint did not admit the captured prompts. Fix the prompt or read the saved lint result.');
10478
+ throw problem(failClosed?.message ?? answer?.result?.refusals?.[0]?.message ?? answer?.result?.report?.program?.refused_prompts?.[0]?.message ?? 'Program lint did not admit the captured prompts. Fix the prompt or read the saved lint result.');
8729
10479
  }
8730
10480
  const admittedPrompts = answer.result?.report?.program?.prompts;
8731
10481
  if (!Array.isArray(admittedPrompts) || paths.some(path => !admittedPrompts.some(prompt => prompt?.path === path && !prompt.lint_refusal))) throw problem('Program lint did not identify every captured prompt. Update the PDD interpreter or fix the captured source before running.');
@@ -8752,7 +10502,8 @@ export async function admitProgram(context, capture, { entry, appMap, initial_wo
8752
10502
  const registered = await recordRuntimeRequest(setup.reservation, id, slotPorts(context));
8753
10503
  if (registered === false || context.interrupted) { await finishReservation(context, setup, { state: 'not_run' }); throw problem('Stopped before program setup was sent.'); }
8754
10504
  store.posted(context.folder, id);
8755
- const reply = await context.runtime.post('/v1/try', request, capture.tar, ports.postMs);
10505
+ const dedupTry = context.serverFeatures?.includes('source-upload-v1') ? { dedup: true, inlineFirst: true } : undefined;
10506
+ const reply = await context.runtime.post('/v1/try', request, capture.tar, ports.postMs, dedupTry);
8756
10507
  const verdict = judgePost(reply, id, 'try', context.secrets);
8757
10508
  if (verdict.answer) store.write(join(context.folder, `${id}.json`), verdict.answer);
8758
10509
  if (verdict.kind === 'busy') {