@promptdriven/runtime-client 1.1.2 → 1.1.4

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.
@@ -12,18 +12,18 @@ 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';
@@ -31,7 +31,7 @@ import { OPEN_STATES, causeText, cleanText, progressTicker, projectAnswer, refus
31
31
  import { adaptivePollMs, isSseContentType, parseSseStream, preferWaitHeaders, SSE_IDLE_MS, WAIT_PREFER_CALL_SECONDS, WAIT_PREFER_RUN_SECONDS } from './runtime-stream.mjs';
32
32
  import { DEFAULT_CHECK_CONCURRENCY, createAdaptiveConcurrency, recordContention, recordCleanSuccess } from './adaptive-concurrency.mjs';
33
33
 
34
- 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);
35
35
  const unboundPortError = message => Object.assign(new Error(message), { unboundPort: true });
36
36
  // The preflight owner's local format advice (#3206): an explicit full kind in a draft and unsupported schema
37
37
  // keywords are warnings in lint and the files preview, never refusals; the engine is the one place that refuses.
@@ -118,6 +118,10 @@ const AGENT_WAIT_MIN = 1.5;
118
118
  const LOST_READ_MS = 300_000;
119
119
  // Unresolved prior local batch reservations automatically expire after 24 hours (override via PDD_PRIOR_RESERVATION_TTL_HOURS).
120
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';
121
125
 
122
126
  class Stop extends Error { constructor(exitCode, message) { super(message); this.exitCode = exitCode; } }
123
127
  function requestedCalls(raw) {
@@ -625,7 +629,7 @@ async function readBaselineReport(context, plan, identity) {
625
629
  catch { partial=true;warn('Some original Check receipts are missing, corrupt or mismatched.'); }
626
630
  for (const answer of originals) {
627
631
  const secrets = [...(context.secrets??[]),identity.token].filter(Boolean);
628
- 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});
629
633
  retain(view,id,'receipt',validLink(cleanText(answer.report_url,secrets),saved.origin,'report'));
630
634
  }
631
635
  } catch { partial=true;warn('Some original Check receipts are missing, corrupt or mismatched.'); }
@@ -800,7 +804,7 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
800
804
  try {
801
805
  const answer = JSON.parse(await read(receiptPath));
802
806
  if (answer?.requestId === id && answer.id === id && answer.command === 'check') {
803
- 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 });
804
808
  const failedChecks = Array.isArray(view.failed_checks) ? view.failed_checks : [];
805
809
  note(row.story, was => ({ ...was, failed: was.failed + failedChecks.length,
806
810
  failedSteps: [...new Set([...was.failedSteps, ...failedChecks.map(check => check?.step_id).filter(step => typeof step === 'string' && step)])].slice(0, 10),
@@ -922,7 +926,7 @@ export async function resendableStoryChecks({ root, since = 0 }, ports = {}) {
922
926
  let answer = null;
923
927
  try { answer = typeof id === 'string' && UUID.test(id) ? JSON.parse(await read(join(directory, name, `${id}.json`))) : null; } catch { answer = null; }
924
928
  if (!sameJob(answer, id, 'check')) return 'other';
925
- 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 });
926
930
  if (answer.state === 'failed' || view.failed_checks?.length) return 'failed';
927
931
  return answer.state === 'unknown' ? 'noVerdict' : 'other';
928
932
  };
@@ -1427,10 +1431,16 @@ function retryAfter(headers) {
1427
1431
  const UNREACHABLE = { ENOTFOUND: 'the address was not found', EAI_AGAIN: 'the address was not found', ECONNREFUSED: 'the connection was refused',
1428
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' };
1429
1433
  function lostReply(error, origin) {
1430
- 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);
1431
1441
  const reason = UNREACHABLE[code] ?? (cert ? 'its TLS certificate was not accepted' : null);
1432
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.` };
1433
- 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 };
1434
1444
  }
1435
1445
  const AUTH_TEXT = 'The PDD interpreter did not accept your GitHub login (HTTP 401). Run gh auth login, then run the command again.';
1436
1446
  const isPreExecutionRefusal = reply => reply.status >= 400 && reply.status < 500 && reply.status !== 408;
@@ -1943,8 +1953,10 @@ function accumulatedAccounting(context, row) {
1943
1953
  const unknown = parts.reduce((sum, part) => sum + part.unknown, 0), complete = parts.every(part => part.complete);
1944
1954
  const total = complete ? parts.reduce((sum, part) => sum + part.total, 0) : null;
1945
1955
  const dispatched = complete ? parts.filter(part => !part.zeroWork) : [];
1946
- const sumToken = key => complete && dispatched.length > 0 && dispatched.every(part => typeof part.tokens[key] === 'number')
1947
- ? 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';
1948
1960
  const input_tokens = sumToken('input_tokens');
1949
1961
  const cached_input_tokens = typeof input_tokens === 'number' ? sumToken('cached_input_tokens') : 'unknown';
1950
1962
  const output_tokens = sumToken('output_tokens');
@@ -2718,16 +2730,35 @@ function captureIndependent(root, rows, ports, options) {
2718
2730
  try { captured=capture(sentTests(rows)); }
2719
2731
  catch (error) {
2720
2732
  if (!sourceUnavailable(error)) throw error;
2733
+ const candidates = rows.filter(row => !row.unsent);
2721
2734
  let broken = false;
2722
- for (const row of rows.filter(row => !row.unsent)) {
2723
- try { capture([row.test]); }
2724
- catch (own) {
2725
- if (!sourceUnavailable(own)) throw own;
2726
- broken = true;
2727
- line(ports.stderr, own.message);
2728
- 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;
2729
2747
  }
2730
- }
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);
2731
2762
  if (!broken) throw error; // Aggregate limits and unstable/shared failures retain their rules.
2732
2763
  return captureIndependent(root,rows,ports,options);
2733
2764
  }
@@ -2916,10 +2947,12 @@ function applyAnswer(row, answer, context, observedWait = null, observedAt = con
2916
2947
  models: models.filter(knownIdentity), terminal, complete: terminal && !!row.cache_identity
2917
2948
  && (accounting.accounting_complete ?? accounting.complete) === true && !capacityUncertain,
2918
2949
  observed_at: new Date(context.ports.now()).toISOString() });
2919
- 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 });
2920
2951
  const advice = noVerdictAdvice(answer, view);
2921
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));
2922
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 ?? [])],
2923
2956
  ...(view.step_details?.length ? { step_details: view.step_details } : {}),
2924
2957
  ...(view.draft_interfaces?.length ? { draft_interfaces: view.draft_interfaces } : {}),
2925
2958
  ...(Object.hasOwn(view, 'field_agreement') ? { field_agreement: view.field_agreement } : {}),
@@ -3060,6 +3093,7 @@ function batchRecord(context) {
3060
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,
3061
3094
  ...(context.liveLocal || context.liveLocalSaved ? {live_local:true} : {}),
3062
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 } : {}),
3063
3097
  ...(context.batchTimeoutMin != null ? { batch_timeout_min: context.batchTimeoutMin } : {}),
3064
3098
  ...(context.singleAttempt ? {single_attempt:true} : {}), ...(context.maxTotalCalls != null ? {max_total_calls:context.maxTotalCalls} : {}),
3065
3099
  ...(context.checkOptions ? {check_options:context.checkOptions} : {}),
@@ -3213,6 +3247,195 @@ function localRowSettledFromReceipts(store, folder, ids) {
3213
3247
  }
3214
3248
  return { settled: true, known_calls: totalCalls, state: lastState };
3215
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
+ }
3216
3439
  function readUnresolvedPriorReservations(root, env, excludeBatch = null, { now = Date.now(), ttlMs = priorReservationTtlMs(env), includeExpired = false } = {}) {
3217
3440
  const empty = { count: 0, reserved_calls: 0, batches: [] };
3218
3441
  try {
@@ -3220,25 +3443,44 @@ function readUnresolvedPriorReservations(root, env, excludeBatch = null, { now =
3220
3443
  const store = new StateStore(stateDir);
3221
3444
  let names;
3222
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;
3223
3454
  let count = 0, reserved_calls = 0;
3224
3455
  const batches = [];
3225
- 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;
3226
3458
  const folder = join(dir, name);
3227
- if (!statOrNull(folder)?.isDirectory() || statOrNull(folder)?.isSymbolicLink()) continue;
3228
- let saved;
3229
- try { saved = JSON.parse(readFileSync(join(folder, 'batch.json'), 'utf8')); } catch { continue; }
3230
- 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;
3231
3477
  let batchHasUnresolved = false;
3232
- for (const row of saved.rows) {
3233
- if (rowReservationCleared(row)) continue;
3478
+ for (const row of summary.unresolved) {
3234
3479
  const ids = Array.isArray(row?.request_ids) ? row.request_ids : [];
3235
3480
  if (!ids.length) continue;
3236
- const state = row.recovery_state ?? row.state;
3237
- const openOrUnknown = ['sending', 'queued', 'running', 'unknown'].includes(state) || row.calls === 'unknown' || row.accounting_complete === false;
3238
- if (!openOrUnknown) continue;
3239
3481
  if (localRowSettledFromReceipts(store, folder, ids).settled) continue;
3240
3482
  if (!includeExpired) {
3241
- const ts = reservationTimestampMs(name, saved, row);
3483
+ const ts = Number.isFinite(row.ts) ? row.ts : batchIdTimestampMs(name);
3242
3484
  if (ts !== null && Number.isFinite(now) && Number.isFinite(ttlMs) && now - ts >= ttlMs) continue;
3243
3485
  }
3244
3486
  const key = typeof row.test === 'string' ? createHash('sha256').update(row.test).digest('hex') : null;
@@ -3260,6 +3502,7 @@ function readUnresolvedPriorReservations(root, env, excludeBatch = null, { now =
3260
3502
  }
3261
3503
  if (batchHasUnresolved) batches.push(name);
3262
3504
  }
3505
+ if (indexDirty) writeReservationIndex(stateDir, index);
3263
3506
  return { count, reserved_calls, batches };
3264
3507
  } catch { return empty; }
3265
3508
  }
@@ -3398,7 +3641,9 @@ function saveBatch(context) {
3398
3641
  && ['passed', 'failed', 'refused'].includes(answer.state) && checkCapacity(answer) === null) applyAnswer(row, answer, context);
3399
3642
  }
3400
3643
  reconcileStoryCriteria(context.rows, context);
3401
- context.store.write(join(context.folder, 'batch.json'), batchRecord(context));
3644
+ const record = batchRecord(context);
3645
+ context.store.write(join(context.folder, 'batch.json'), record);
3646
+ updateBatchReservationIndex(context.store.dir, context.batch, record);
3402
3647
  }
3403
3648
  function saveAnswerAt(store, folder, id, json) {
3404
3649
  if (!isObject(json)) return;
@@ -3428,7 +3673,8 @@ async function postJob(context, path, command, request, row, timeoutMs, deadline
3428
3673
  const pendingChecks = command === 'check'
3429
3674
  ? (context.rows ?? []).filter(item => !item.unsent && ['ready', 'waiting', 'sending'].includes(item.state)).length
3430
3675
  : 0;
3431
- const inlineFirst = command === 'lint' || (command === 'check' && pendingChecks <= 1);
3676
+ const inlineFirst = (command === 'lint' || (command === 'check' && pendingChecks <= 1))
3677
+ && (!dedup || Buffer.byteLength(JSON.stringify(request), 'utf8') <= 60_000);
3432
3678
  const reply = await context.runtime.post(
3433
3679
  path,
3434
3680
  request,
@@ -3585,11 +3831,14 @@ async function sendCheckAttempt(context, row, deadline = rowDeadline(context, ro
3585
3831
  row.sent_at = context.ports.now(); row.ended_at = null; row.retry_at = null; row.busy = false; row.can_retry = false;
3586
3832
  row.busy_request_id = null; row.busy_observed_at = null; row.capacity_until = null; row.busy_display = null;
3587
3833
  row.phase = 'server';
3834
+ const clauseTable = clauseTableForRow(context, row);
3835
+ if (clauseTable) row.clause_table = clauseTable;
3588
3836
  const request = { requestId: id, source_sha256: context.capture.sha256, scenario: row.test, max_calls: effectiveMaxCalls,
3589
3837
  ...(context.freshChecks || context.checkOptions?.fresh ? { fresh: true } : {}),
3590
3838
  ...(context.checkOptions ? { samples: context.checkOptions.samples,
3591
3839
  ...(context.checkOptions.step_ids ? { step_ids: context.checkOptions.step_ids } : {}) } : {}),
3592
3840
  ...(shouldSendLazyInterfaces(context) ? { lazy_interfaces: true } : {}),
3841
+ ...(clauseTable ? { clause_table: clauseTable } : {}),
3593
3842
  ...sourceProvenance(context) };
3594
3843
  let verdict;
3595
3844
  try { verdict = await context.postCheck(request, row, Math.max(1, Math.min(context.ports.postMs, deadline - context.ports.now())), deadline); }
@@ -3627,6 +3876,22 @@ async function sendCheckAttempt(context, row, deadline = rowDeadline(context, ro
3627
3876
  }
3628
3877
  }
3629
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
+
3630
3895
  function sourceProvenance(context, capture = context?.capture) {
3631
3896
  if (!context?.serverFeatures?.includes('source-provenance') || typeof capture?.source_commit !== 'string') return {};
3632
3897
  let dirty_files = Array.isArray(capture.dirty_files) ? capture.dirty_files : [];
@@ -3712,6 +3977,7 @@ function lintReceiptTransaction(context, action) {
3712
3977
  function passingLintReceipt(context, answer) {
3713
3978
  return UUID.test(answer?.requestId ?? '') && sameJob(answer, answer.requestId, 'lint') && answer.state === 'passed'
3714
3979
  && (answer.result?.report?.lint?.complete === true || answer.result?.problems_complete === true)
3980
+ && !lintFailClosed(answer)
3715
3981
  && context.rows.length > 0 && context.rows.every(row => !row.unsent && !row.native_only?.length && lintAdmits(answer, row, context.capture));
3716
3982
  }
3717
3983
  function rememberRecentLint(context, answer) {
@@ -3925,8 +4191,11 @@ async function checkBatch(context, rows, priorLint = null) {
3925
4191
  for (const [row, outcome] of verdicts) if (outcome.state !== 'passed') notSent(...unsentByLint(outcome), row);
3926
4192
  const refused = sendable.filter(row => row.state === 'refused').length, held = sendable.length - toSend.length - refused;
3927
4193
  context.lintUnknown = context.lint.unknown = [...verdicts.values()].some(outcome => outcome.state === 'unknown');
3928
- if (!toSend.length && !refused) return;
3929
- 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);
3930
4199
  const judged = toSend.length === sendable.length ? 'Lint passed.' : [refused ? `Lint refused ${refused} of ${sendable.length} tests.` : '',
3931
4200
  held ? `Lint gave no verdict for ${held} of ${sendable.length} tests.` : ''].filter(Boolean).join(' ');
3932
4201
  line(ports.stderr, judged);
@@ -3986,6 +4255,7 @@ async function runScheduledChecks(context, rows, toSend) {
3986
4255
  };
3987
4256
  const sseEnabled = !ports.pollMsExplicit && Boolean(context.serverFeatures?.includes('sse-stream-v1'));
3988
4257
  const activeStreams = new Map();
4258
+ const sseBackoff = new WeakMap();
3989
4259
  let wakeResolve = null;
3990
4260
  const notifyWake = () => { if (wakeResolve) { const fn = wakeResolve; wakeResolve = null; fn(); } };
3991
4261
  const formatStageEvent = (row, json) => {
@@ -4007,9 +4277,14 @@ async function runScheduledChecks(context, rows, toSend) {
4007
4277
  const syncRowStreams = () => {
4008
4278
  abortExpiredStreams();
4009
4279
  if (!sseEnabled || context.interrupted || context.readStop) return;
4280
+ const now = ports.now();
4010
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;
4011
4284
  const id = row.request_ids.at(-1);
4012
4285
  if (!id) continue;
4286
+ const backoff = sseBackoff.get(row);
4287
+ if (backoff && backoff.id === id && now < backoff.retryAt) continue;
4013
4288
  const existing = activeStreams.get(row);
4014
4289
  if (existing && existing.id === id) continue;
4015
4290
  if (existing) { existing.controller.abort(); activeStreams.delete(row); }
@@ -4020,6 +4295,7 @@ async function runScheduledChecks(context, rows, toSend) {
4020
4295
  const rowEnd = rowDeadline(context, row);
4021
4296
  const end = Math.min(rowEnd, row.lost ? row.read_until ?? rowEnd : rowEnd);
4022
4297
  let lastStageKey = '';
4298
+ let receivedEvent = false;
4023
4299
  const entry = { id, controller };
4024
4300
  activeStreams.set(row, entry);
4025
4301
  entry.promise = context.runtime.streamRun(id, {
@@ -4028,6 +4304,8 @@ async function runScheduledChecks(context, rows, toSend) {
4028
4304
  timeoutMs: Math.max(1, end - ports.now()),
4029
4305
  onEvent: ({ event, json }) => {
4030
4306
  if (!isObject(json) || !sameJob(json, id, 'check')) return false;
4307
+ receivedEvent = true;
4308
+ sseBackoff.delete(row);
4031
4309
  const enriched = (typeof json.stage === 'string' && json.stage && json.state === 'running')
4032
4310
  ? { ...json, progress: { ...(isObject(json.progress) ? json.progress : {}), stage: json.stage } }
4033
4311
  : json;
@@ -4055,10 +4333,33 @@ async function runScheduledChecks(context, rows, toSend) {
4055
4333
  }
4056
4334
  return false;
4057
4335
  },
4058
- }).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 }) => {
4059
4358
  context.signal?.removeEventListener('abort', onSignal);
4060
4359
  if (activeStreams.get(row) === entry) activeStreams.delete(row);
4061
- 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();
4062
4363
  });
4063
4364
  }
4064
4365
  };
@@ -4103,7 +4404,9 @@ async function runScheduledChecks(context, rows, toSend) {
4103
4404
  }
4104
4405
  const end = Math.min(...deadlines);
4105
4406
  const delay = ports.pollDelay(loopNow - pollStartedAt);
4106
- const waitMs = Math.max(0, Math.min(activeStreams.size ? PROGRESS_MS : delay, end - loopNow));
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));
4107
4410
  if (activeStreams.size) {
4108
4411
  const wake = new Promise(resolve => { wakeResolve = resolve; });
4109
4412
  await Promise.race([ports.sleep(waitMs, context.signal), wake]);
@@ -4233,11 +4536,11 @@ function runFiles(cwd, words, options, ports) {
4233
4536
  const appMap = options['--app-map'] === undefined ? null : appMapFor(found, options['--app-map'], cwd, root, ports.stderr);
4234
4537
  for (const path of found.excludedFixtureProjects ?? []) line(ports.stderr, `Warning: skipped nested fixture project ${path}.`);
4235
4538
  const capture = captureIndependent(root, rows, ports, {appMap,excludeFixtureProjects:words.length === 0,allowMissingInterfaces:true})
4236
- ?? {files:[],reads:[],bytes:0};
4539
+ ?? {files:[],reads:[],bytes:0,clauses:[]};
4237
4540
  const broken = rows.filter(row => row.unsent && row.refusals.length), exitCode = broken.length ? 4 : 0;
4238
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.` : ''}`;
4239
4542
  if (options['--json']) {
4240
- 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} : {})}));
4241
4544
  return exitCode;
4242
4545
  }
4243
4546
  for (const row of broken) for (const problem of row.refusals) {
@@ -4499,11 +4802,26 @@ function lintProblems(context, answer, refusal = null) {
4499
4802
  section: cleanText(item.section, context.secrets) || null, message: cleanText(item.message, context.secrets) || null, hint: null }, item, context.root, context.secrets);
4500
4803
  if (!problems.some(p => p.code === problem.code && p.path === problem.path && p.section === problem.section)) problems.push(problem);
4501
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
+ }
4502
4819
  return problems;
4503
4820
  }
4504
4821
 
4505
4822
  function printLintResult(context, rows, problems, warnings = [], answer = null) {
4506
4823
  const { ports, batch, root } = context;
4824
+ const remoteProblems = [...problems];
4507
4825
  problems = [...problems];
4508
4826
  for (const row of rows) {
4509
4827
  const listed = [answer?.result?.tests, answer?.result?.report?.lint?.tests].find(items => Array.isArray(items) && items.some(item => item?.path === row.test));
@@ -4517,16 +4835,86 @@ function printLintResult(context, rows, problems, warnings = [], answer = null)
4517
4835
  if (problem.code === 'lint-refused' && !problem.path) continue;
4518
4836
  if (!problems.some(item => item.code === problem.code && (item.path ?? null) === (problem.path ?? null))) problems.push({ ...problem, path: problem.path ?? null, section: null });
4519
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');
4520
4845
  const localRefusal = context.localOnly && (problems.some(item => item.severity !== 'warning') || rows.some(row => row.state === 'refused'));
4521
- 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;
4522
4904
  const omitted = rows.filter(row=>row.native_only?.length && !row.refusals?.length).length;
4523
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);
4524
- 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.`;
4525
- const reportedCoverage = answer?.result?.capabilities_complete ?? answer?.result?.report?.lint?.capabilities_complete;
4526
- 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.`;
4527
4915
  const reportUrl = validLink(cleanText(answer?.report_url, context.secrets), context.origin, 'report');
4528
4916
  const maintenance = activeMaintenance(context);
4529
- 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,
4530
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 ?? [])])] };
4531
4919
  result.call_preflight_context = answer?.result?.call_preflight_context ?? answer?.result?.report?.lint?.call_preflight_context ?? null;
4532
4920
  result.call_preflight_requested_cap = context.lint?.selected_cap ?? null;
@@ -4788,7 +5176,7 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
4788
5176
  });
4789
5177
  if (identity.login !== saved.login) throw new Stop(5, `These runs belong to ${saved.login}. Run: gh auth switch -u ${saved.login}`);
4790
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 ?? [],
4791
- capture: { sha256: saved.source_sha256, files: saved.files.map(path => ({ path })), bytes: saved.bytes, stories:saved.contract_snapshots }, lint: saved.lint, head: saved.head, startedAt: Date.parse(saved.created_at) });
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) });
4792
5180
  runtimeOrigin({ PDD_RUNTIME_URL: saved.origin });
4793
5181
  context.auth = authSession({
4794
5182
  identity,
@@ -4864,7 +5252,7 @@ async function runRead(context, batchWord, quiet = false, options = {}, retry =
4864
5252
  if (row.final && (ports.now() >= (context.deadline ?? Infinity) || context.interrupted)) return;
4865
5253
  // A saved unknown row whose verified receipt already carries failed checks preserves them across --timeout 0 and failed/unknown polls.
4866
5254
  if (row.state === 'unknown' && answer && sameJob(answer, id, 'check') && answer.state === 'unknown'
4867
- && 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) {
4868
5256
  const legacyLostWhy = row.lost === undefined && row.why ? row.why : null;
4869
5257
  applyAnswer(row, answer, context);
4870
5258
  row.lost = false;
@@ -5019,8 +5407,8 @@ async function recoverRestarts(context) {
5019
5407
 
5020
5408
  async function runRetry(context, name, options) {
5021
5409
  const { ports } = context;
5022
- const timeout = options['--timeout'] === undefined ? AGENT_WAIT_MIN : parseTimeoutMinutes(options['--timeout'], '--timeout');
5023
- const batchTimeout = parseTimeoutMinutes(options['--batch-timeout'], '--batch-timeout');
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 });
5024
5412
  const retryStart = ports.now();
5025
5413
  context.batchTimeoutMin = batchTimeout;
5026
5414
  context.batchDeadline = batchTimeout === null ? Infinity : retryStart + batchTimeout * 60_000;
@@ -5045,7 +5433,15 @@ async function runRetry(context, name, options) {
5045
5433
  if (retryable.length && !selected.length) throw new Stop(2, 'The saved lint cannot authorize recovery. Start a fresh selected pdd test.');
5046
5434
  if (selected.length) lintDiagnostics(context, lint, rows);
5047
5435
  Object.assign(context, { capture, reading: false, timeoutMin: timeout, deadline: context.batchDeadline });
5048
- for (const row of selected) { delete row.story_deadline; row.state = row.retry_at > ports.now() ? 'waiting' : 'ready'; }
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
+ }
5049
5445
  if (selected.length) line(ports.stderr, `Retrying ${selected.length} unstarted check${selected.length === 1 ? '' : 's'}…`);
5050
5446
  await runScheduledChecks(context, rows, selected);
5051
5447
  saveBatch(context);
@@ -5765,7 +6161,7 @@ async function acquireCacheGuard(cache) {
5765
6161
  if (!Number.isSafeInteger(ticket)) throw new Error('cache ticket overflow');
5766
6162
  fs.write(join(own, 'ticket.tmp'), JSON.stringify(ticket), { flag: 'wx', mode: 0o600 });
5767
6163
  fs.rename(join(own, 'ticket.tmp'), join(own, 'ticket.json'));
5768
- for (let attempt = 0; attempt < 100; attempt++) {
6164
+ for (let attempt = 0; attempt < 30; attempt++) {
5769
6165
  if (!peers().some(peer => peer.ticket === null || peer.ticket < ticket || peer.ticket === ticket && peer.name < name)) return () => remove(own);
5770
6166
  await cache.context.ports.sleep(10);
5771
6167
  }
@@ -5778,7 +6174,7 @@ async function cacheTransaction(cache, operation, clear = false) {
5778
6174
  try {
5779
6175
  safeCachePath(cache.fs, cache.dir, { directory: true });
5780
6176
  releaseGuard = await acquireCacheGuard(cache);
5781
- for (let attempt = 0; attempt < 100; attempt++) {
6177
+ for (let attempt = 0; attempt < 30; attempt++) {
5782
6178
  try {
5783
6179
  cache.fs.mkdir(cache.lock); locked = true;
5784
6180
  owner = { pid: process.pid, token: cache.fs.nonce() };
@@ -6042,12 +6438,12 @@ function markTestAttempt(cache, data) {
6042
6438
  const oldMarks = latest.in_progress ?? [];
6043
6439
  const live = liveInProgressMarks(cache, oldMarks);
6044
6440
  const stories = [...cache.tokens.keys()];
6045
- const verifiedBase = hasVerifiedIdentityRecord(latest);
6046
- if (!live.length) {
6047
- latest.cohort = { members: [], valid: true, engine_sha: verifiedBase ? latest.engine_sha : null, requested_model: verifiedBase ? latest.models[0] : null, floor: Date.parse(latest.sampled_at) };
6048
- } else if (!latest.cohort || !live.every(mark => latest.cohort.members.some(member => member.token === mark.token))) {
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))) {
6049
6444
  latest.cohort = { members: [], valid: false, engine_sha: null, requested_model: null, floor: Date.parse(latest.sampled_at) };
6050
6445
  }
6446
+ if (cache.mark.started_at <= latest.cohort.floor) latest.cohort.valid = false;
6051
6447
  if (latest.cohort.members.some(member => member.stories.some(story => stories.includes(story)))) latest.cohort.valid = false;
6052
6448
  latest.cohort.members.push({ token: cache.mark.token, stories });
6053
6449
  latest.in_progress = [...live, cache.mark];
@@ -6067,11 +6463,11 @@ async function beginTestAttempts(cache, rows, capture, options, origin, force =
6067
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));
6068
6464
  const budgetAllows = !eligible || passSatisfiesMaxCalls(pass, own);
6069
6465
  const identity = data.latest_identity;
6070
- 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));
6071
6467
  const reason = capture && declarationCacheReason(capture, story, own.map(row => row.test))
6072
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)
6073
6469
  || (eligible && !budgetAllows ? 'runs again: --max-calls is lower than the saved pass call count' : null)
6074
- || (eligible && !verifiedIdentityMatchesPass(cache, identity, pass, story) ? (knownDrift ? 'runs again: interpreter build or model changed' : 'runs again: cache identity is unverified') : null);
6470
+ || (eligible && !cleanRecordMatches(identity, pass) ? (knownDrift ? 'runs again: interpreter build or model changed' : 'runs again: cache identity is unverified') : null);
6075
6471
  if (reason) for (const row of own) row.cache_reason ??= reason;
6076
6472
  if (!force && !reason && [undefined, '', '0', 'false'].includes(cache.context.ports.env.CI) && eligible && budgetAllows) {
6077
6473
  for (const row of own) {
@@ -6097,66 +6493,28 @@ async function finishTestAttempts(cache, rows, capture) {
6097
6493
  await cacheTransaction(cache, data => {
6098
6494
  const observations = cache.context.observedTestIdentities ?? [];
6099
6495
  const previous = data.latest_identity;
6100
- const observedEngines = [...new Set(observations.map(item => item.engine_sha).filter(Boolean))];
6101
- const observedModels = [...new Set(observations.flatMap(item => item.models).filter(Boolean))];
6102
- const hasObservedConflict = observedEngines.length > 1 || observedModels.length > 1 || observations.some(item => item.conflict);
6103
- const identity = {
6104
- engine_sha: observedEngines.length === 1 ? observedEngines[0] : null,
6105
- requested_model: observedModels.length === 1 ? observedModels[0] : null,
6106
- };
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 };
6107
6498
  const terminalObservations = observations.filter(item => item.terminal);
6108
- 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));
6109
6501
  const marks = previous?.in_progress ?? [];
6110
6502
  const ownMark = mark => !!cache.mark && mark.token === cache.mark.token;
6111
- 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);
6112
6505
  const cohort = previous?.cohort;
6113
- const nowIso = new Date(cache.context.ports.now()).toISOString();
6114
- if (cache.context.cacheReadInvocation) {
6115
- if (previous && marks.some(ownMark)) {
6116
- data.latest_identity = { ...previous, in_progress: liveRemaining, ...(liveRemaining.length && cohort ? { cohort } : {}) };
6117
- if (!liveRemaining.length) delete data.latest_identity.cohort;
6118
- }
6119
- } else if (!observations.length) {
6120
- // No server response was observed (e.g., local error/interrupt before HTTP settlement).
6121
- // Retire our in-progress mark without erasing a previously verified identity.
6122
- if (previous) {
6123
- const preservedClean = !liveRemaining.length && hasVerifiedIdentityRecord(previous);
6124
- const next = { ...previous, in_progress: liveRemaining, clean: preservedClean, conflict: !hasVerifiedIdentityRecord(previous), written_at: nowIso, observed_at: nowIso };
6125
- if (liveRemaining.length && cohort) next.cohort = cohort;
6126
- else delete next.cohort;
6127
- data.latest_identity = next;
6128
- }
6129
- } else {
6130
- let cohortConflict = false;
6131
- if (cohort) {
6132
- if (!identityVerified) {
6133
- cohort.valid = false;
6134
- cohortConflict = true;
6135
- } else {
6136
- if ((cohort.engine_sha !== null && cohort.engine_sha !== identity.engine_sha)
6137
- || (cohort.requested_model !== null && cohort.requested_model !== identity.requested_model)) {
6138
- cohort.valid = false;
6139
- cohortConflict = true;
6140
- }
6141
- if (cohort.engine_sha === null) cohort.engine_sha = identity.engine_sha;
6142
- if (cohort.requested_model === null) cohort.requested_model = identity.requested_model;
6143
- if (cohort.valid === false) cohortConflict = true;
6144
- }
6145
- }
6146
- const clean = !liveRemaining.length && identityVerified && !cohortConflict;
6147
- const conflict = hasObservedConflict || cohortConflict || !identityVerified;
6148
- data.latest_identity = {
6149
- engine_sha: identity.engine_sha,
6150
- models: identity.requested_model ? [identity.requested_model] : [],
6151
- in_progress: liveRemaining,
6152
- ...(liveRemaining.length && cohort ? { cohort } : {}),
6153
- clean,
6154
- conflict,
6155
- sampled_at: new Date(Number.isFinite(cache.context.startedAt) ? cache.context.startedAt : 0).toISOString(),
6156
- written_at: nowIso,
6157
- observed_at: nowIso,
6158
- };
6159
- }
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() };
6160
6518
  for (const [story, token] of cache.tokens) {
6161
6519
  if (data.epoch !== token.epoch || data.stories[story]?.generation !== token.generation) continue;
6162
6520
  const own = rows.filter(row => row.story_path === story && !row.cached), footprint = capture.stories?.find(item => item.story_path === story);
@@ -6303,13 +6661,9 @@ async function runBatch(context, cwd, words, options, setRelease) {
6303
6661
  // only this attempt's mark, leaving its invalidations and other owners intact.
6304
6662
  if (cache?.mark) await cacheTransaction(cache, data => {
6305
6663
  if (data.latest_identity?.in_progress) {
6306
- const remaining = liveInProgressMarks(cache, data.latest_identity.in_progress.filter(mark=>mark.token!==cache.mark.token));
6307
- data.latest_identity.in_progress = remaining;
6308
- if (!remaining.length) {
6309
- delete data.latest_identity.cohort;
6310
- const preserved = hasVerifiedIdentityRecord(data.latest_identity);
6311
- Object.assign(data.latest_identity, { clean: preserved, conflict: !preserved });
6312
- }
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;
6313
6667
  }
6314
6668
  });
6315
6669
  if (context.testCache === cache) context.testCache = null;
@@ -6420,13 +6774,9 @@ async function runBatch(context, cwd, words, options, setRelease) {
6420
6774
  catch (error) {
6421
6775
  if (cache?.mark) await cacheTransaction(cache, data => {
6422
6776
  if (data.latest_identity?.in_progress) {
6423
- const remaining = liveInProgressMarks(cache, data.latest_identity.in_progress.filter(mark => mark.token !== cache.mark.token));
6424
- data.latest_identity.in_progress = remaining;
6425
- if (!remaining.length) {
6426
- delete data.latest_identity.cohort;
6427
- const preserved = hasVerifiedIdentityRecord(data.latest_identity);
6428
- Object.assign(data.latest_identity, { clean: preserved, conflict: !preserved });
6429
- }
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;
6430
6780
  }
6431
6781
  });
6432
6782
  throw error;
@@ -6468,7 +6818,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
6468
6818
  }
6469
6819
  await beginTestAttempts(cache, rerun, capture, options, origin, true);
6470
6820
  const stopReason = context.interrupted ? 'interrupted' : context.readStop ? 'reading stopped'
6471
- : 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;
6472
6822
  if (stopReason) {
6473
6823
  for (const row of rerun) Object.assign(row, { state: 'not_run', calls: 0, seconds: 0, phase: 'local', busy: false,
6474
6824
  note: { code: null, message: `not sent: ${stopReason}` }, why: `not sent: ${stopReason}` });
@@ -6477,6 +6827,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
6477
6827
  }
6478
6828
  }
6479
6829
  saveBatch(context);
6830
+ try { pruneOldBatches({ stateDir: context.store.dir, env: ports.env, now: ports.now(), excludeBatches: [context.batch] }); } catch { /* best-effort retention GC */ }
6480
6831
  return () => printResult(context, rows);
6481
6832
  }
6482
6833
 
@@ -6512,7 +6863,7 @@ function appMapFor(found, given, cwd, root, stderr) {
6512
6863
  requireRuntimePath(loadRuntimeWorkspace({root}),{path:rel,from:'App map'});
6513
6864
  if (!found.visible.has(rel)) throw new Stop(2, `--app-map ${cleanText(given)} is not a Git-visible file in this repository.`);
6514
6865
  const problem = appMapProblem(root, rel);
6515
- 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.`);
6516
6867
  return rel;
6517
6868
  }
6518
6869
 
@@ -6559,7 +6910,14 @@ function tryCommand(test, setup, suffix='', target=test.story) {
6559
6910
  }
6560
6911
 
6561
6912
  // Read the authored interfaces, never scenario output, to choose an interaction.
6562
- 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 } = {}) {
6563
6921
  const cli = new Set(), http = new Set();
6564
6922
  for (const step of Array.isArray(test.doc?.steps) ? test.doc.steps : []) {
6565
6923
  if (!step || typeof step.entry_path !== 'string' || typeof step.operation !== 'string') continue;
@@ -6567,24 +6925,28 @@ function programEntries(root, found, test) {
6567
6925
  const entries = Array.isArray(prompt.interface?.entries) ? prompt.interface.entries : [];
6568
6926
  const conventions = Array.isArray(prompt.interface?.conventions) ? prompt.interface.conventions : [];
6569
6927
  const index = entries.findIndex(entry => entry?.operation === step.operation);
6570
- if (!(index >= 0)) continue;
6571
- const entry = entries[index], key = `${step.entry_path}#${step.operation}`;
6572
- if (['input_schema', 'result_schema'].every(name => conventions.some(c => c?.path === `/entries/${index}/${name}` && c.convention === 'cli'))) cli.add(key);
6573
- 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
+ }
6574
6936
  }
6575
6937
  return { test, cli, http };
6576
6938
  }
6577
6939
 
6578
- function simulationSelection(root, found, words, appMap, options, ports) {
6940
+ function simulationSelection(root, found, words, appMap, options, ports, { allowMissingInterfaces = false } = {}) {
6579
6941
  const all = [...found.tests].sort((a, b) => a.path.localeCompare(b.path));
6580
6942
  if (!all.length) throw new Stop(2, 'No Stories are available to simulate.');
6581
6943
  const selected = words.length ? [oneTest(found, words, root, ports)] : all;
6582
- const rows = selected.map(test => programEntries(root, found, test));
6944
+ const rows = selected.map(test => programEntries(root, found, test, { allowMissingInterfaces }));
6583
6945
  const eligibleNames = predicate => [...new Set(all.flatMap(test => {
6584
6946
  const selectedRow = rows.find(row => row.test === test);
6585
6947
  // Selected source was read strictly above. Unselected failures cannot turn
6586
6948
  // advisory eligible-name discovery into a new source requirement.
6587
- try { return predicate(selectedRow ?? programEntries(root, found, test)) ? [test.story] : []; }
6949
+ try { return predicate(selectedRow ?? programEntries(root, found, test, { allowMissingInterfaces })) ? [test.story] : []; }
6588
6950
  catch { return []; }
6589
6951
  }))].sort();
6590
6952
  const cli = new Set(rows.flatMap(row => [...row.cli]));
@@ -6948,7 +7310,7 @@ function programSelection(cwd, word, ports, givenMap) {
6948
7310
  try { map = JSON.parse(sourceFilePort(root, visible).read({ path }).content); }
6949
7311
  catch (error) { if (error instanceof RuntimeWorkspaceError) throw error; throw new Stop(2, 'Select a readable app map containing valid JSON.'); }
6950
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.');
6951
- if (explicit && Object.hasOwn(map, 'name') && (typeof map.name !== 'string' || !map.name)) throw new Stop(2, 'The selected app map has an invalid name. See RUNBOOK.md §13.');
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.');
6952
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');
6953
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.');
6954
7316
  return first.prompt_path;
@@ -6956,9 +7318,9 @@ function programSelection(cwd, word, ports, givenMap) {
6956
7318
  const entry = isMap ? mapEntry(selected) : selected;
6957
7319
  let appMap = isMap ? selected : null;
6958
7320
  if (givenMap !== undefined) {
6959
- 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.');
6960
7322
  const path = canonical(givenMap);
6961
- 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.');
6962
7324
  appMap = path;
6963
7325
  }
6964
7326
  if (!appMap) for (const path of ['app-map.json', 'app/app-map.json']) {
@@ -6981,7 +7343,8 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
6981
7343
  if (options['--fresh'] !== undefined && options['--fresh'] !== true) throw new Stop(2, '--fresh takes no value.');
6982
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.');
6983
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.');
6984
- const openInPage = selected.screen || selected.plainUiPrompt || options['--page'] === true || options['--tab'] !== undefined;
7346
+ const cliDoor = options['--cli'] === true || options['--shell'] === true;
7347
+ const openInPage = !cliDoor && (selected.screen || selected.plainUiPrompt || options['--page'] === true || options['--tab'] !== undefined);
6985
7348
  const store = stateFor(ports.env, root), files = programFiles(root, entry, store); let seeded = null;
6986
7349
  if (options['--data'] !== undefined) {
6987
7350
  if (typeof options['--data'] !== 'string') throw new Stop(2, '--data needs a JSON file.');
@@ -6995,13 +7358,27 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
6995
7358
  throw new Stop(2, 'The live program keeps its pinned app map. Use --new to select a different app map.');
6996
7359
  const appMap = !selected.screen && !options['--new'] && record?.app_map
6997
7360
  ? selected.validatePinnedMap(record.app_map) : selected.appMap;
6998
- const requestedTab = options['--tab'] ?? (selected.screen || selected.plainUiPrompt || appMap ? 'screen' : 'call');
6999
- const capture = ports.captureSource(root, { tests: [entry], appMap });
7000
- 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);
7001
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.');
7002
7378
  Object.assign(context, { root, cwd, origin, identity, store, capture, visible: selected.visible, appMap, programEntry: entry,
7379
+ allowMissingInterfaces,
7003
7380
  programTarget: relative(root, resolve(cwd, word)).split(sep).join('/'), programFiles: files,
7004
- secrets: [identity.token], startedAt: ports.now(), deadline: ports.now() + TRY_MS, lint: { request_ids: [], state: null }, rows: [], timeoutMin: 5, folder: store.folder('tries'), doorMode: options['--serve'] !== undefined || !openInPage });
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 });
7005
7382
  releaseInterrupt = interruptible(context);
7006
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.') });
7007
7384
  context.runtime = new Runtime({ origin, token: identity.token, ports, signal: context.signal, auth: context.auth, programJson: true });
@@ -7129,6 +7506,7 @@ async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
7129
7506
  } finally { done(); }
7130
7507
  };
7131
7508
  unlock(); released = true;
7509
+ if (cliDoor) return await (await import('./try-doors.mjs')).openCli(context, { path: entry, programEntry: entry, title: entry }, record.id, options);
7132
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 });
7133
7511
  let openLink = link;
7134
7512
  if (options['--tab'] === undefined && requestedTab !== 'screen') {
@@ -7279,6 +7657,16 @@ async function runDirectProgram({words,options,cwd}, ports) {
7279
7657
  let last = directPrivate(lastPath), pendingCall = last?.state === 'unknown' && last.id;
7280
7658
  if(!pendingCall&&!descriptor?.setupPending)directPrivate(lastPath,{state:'unknown',id:null,input:{argv:words.slice(1)}});
7281
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 });
7282
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')));
7283
7671
  const store = stateFor(ports.env,root), origin = runtimeOrigin(ports.env), identity = signIn(ports.gh,store,ports,{exitCode:125});
7284
7672
  secrets = [identity.token];
@@ -7431,7 +7819,7 @@ async function runDirectProgram({words,options,cwd}, ports) {
7431
7819
  function shouldUseDirectProgram(words, options, cwd) {
7432
7820
  if (typeof words[0] !== 'string' || !words[0].endsWith('.prompt.md')) return false;
7433
7821
  if (words.length > 1 || ['--show-data', '-q', '--quiet'].some(key => options[key] !== undefined)) return true;
7434
- if (['--serve', '--page', '--tab', '--cli', '--shell', '--no-open', '--no-wait', '--new', '--stop', '--app-map', '--max-calls', '--agent'].some(key => options[key] !== undefined)) return false;
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;
7435
7823
  try {
7436
7824
  const text = readFileSync(resolve(cwd, words[0]), 'utf8');
7437
7825
  return /\b(?:cli|argv|stdin|stdout|exit_code|command-line)\b/i.test(text);
@@ -7442,7 +7830,7 @@ function shouldUseDirectProgram(words, options, cwd) {
7442
7830
 
7443
7831
  function shouldUseTypedTry(words, options, cwd) {
7444
7832
  if (typeof words[0] !== 'string' || !words[0].endsWith('.prompt.md')) return false;
7445
- 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;
7446
7834
  try {
7447
7835
  const text = readFileSync(resolve(cwd, words[0]), 'utf8');
7448
7836
  const blocks = interfaceBlocks(text);
@@ -7601,6 +7989,19 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7601
7989
  if(options['--product']!==undefined&&!productMode || !productMode&&['--parts','--journey'].some(key=>options[key]!==undefined))throw new Stop(2,'--parts and --journey require --product.');
7602
7990
  if(productMode&&options['--app-map']!==undefined)throw new Stop(2,'--product builds its map; omit --app-map.');
7603
7991
  const requestedBudget = requestedCalls(options['--max-calls']);
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
+ }
7604
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 });
7605
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.');
7606
8007
  const doorModes = [options['--cli'] || options['--shell'], options['--serve'] !== undefined, options['--page'] || options['--tab'] !== undefined || options['--agent'] !== undefined, options['--save-last']].filter(Boolean);
@@ -7667,7 +8068,8 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7667
8068
  const boundedCapture = !productSetup && loadRuntimeWorkspace({root}).configured && localSelected.length ? ports.captureSource(root, { tests: localSelected.map(item => item.path), appMap, ...captureExtra }) : null;
7668
8069
  let { test, selected, tab, typed } = productSetup
7669
8070
  ? { test: localSelected[0], selected: localSelected, tab: options['--tab'] ?? (options['--cli'] || options['--shell'] ? 'terminal' : 'screen'), typed: false }
7670
- : simulationSelection(root, found, normalized, appMap, options, ports);
8071
+ : simulationSelection(root, found, normalized, appMap, options, ports, { allowMissingInterfaces });
8072
+ context.allowMissingInterfaces = allowMissingInterfaces;
7671
8073
  if (productSetup && options['--shell']) options['--cli'] = true;
7672
8074
  const wholeRecords = productSetup || normalized.length ? [] : Object.entries(repoState.tries ?? {}).filter(([, value]) => isObject(value.simulation_scope));
7673
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.');
@@ -7710,7 +8112,7 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
7710
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.');
7711
8113
  const identity = context.probedIdentity ?? signIn(ports.gh, context.store, ports, { exitCode: context.doorMode ? 125 : 5 });
7712
8114
  if(context.liveLocal)context.localOwner??=identity.login;
7713
- 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 },
7714
8116
  batch: null, rows, timeoutMin: TRY_MS / 60_000, agentLimit: false, head: null });
7715
8117
  context.folder = store.folder('tries');
7716
8118
  release = interruptible(context);
@@ -8016,7 +8418,7 @@ async function checkLint(context, rows) {
8016
8418
  const APP_MAP_RULES = { 'ambiguous-handler': 'on one screen, all taps of one kind must match by the same key',
8017
8419
  'template-reference-schema': 'a field that gets a value from the screen ($ref) must be a plain {"type": "string"}',
8018
8420
  'invalid-after-step': 'an after step has the wrong fields' };
8019
- 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).';
8020
8422
  const GENERIC_REFUSAL = /^The runtime refused this (?:job|run)\b/;
8021
8423
  const isAppMapCode = code => Object.hasOwn(APP_MAP_RULES, code) || code === 'invalid-clipboard-action' || /^(?:after|app-map|invalid-app-map)-/.test(code);
8022
8424
  function normalizeTryRefusals(context, refusals) {
@@ -8057,7 +8459,7 @@ function trySetupRefused(context, test, appMap, refusals, reportUrl) {
8057
8459
  line(context.ports.stdout, `The Try could not start: ${mapped ? 'the app map was refused' : 'the server refused it'} (${why}).`);
8058
8460
  line(context.ports.stdout, fix ? `${fix}${needsAfterHelp ? ` ${AFTER_STEP_SHAPE_HELP}` : ''} Then ${again}`
8059
8461
  : needsAfterHelp ? `${mapped ? `Fix ${target}. ` : ''}${AFTER_STEP_SHAPE_HELP} Then ${again}`
8060
- : 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}`
8061
8463
  : `Fix what it names, then ${again}${reportUrl ? ` Details: ${reportUrl}` : ''}`);
8062
8464
  return 4;
8063
8465
  }
@@ -8850,7 +9252,7 @@ async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {
8850
9252
  const limit = stepTimeLimit(answer, { steps: [{ step_id: operation }], secrets: secrets });
8851
9253
  const why = answer.result?.refusals?.[0];
8852
9254
  if (limit) throw Object.assign(new Stop(125, `${limit.message} ${limit.fix}${recovery}`), { tryUsage: usage });
8853
- throw Object.assign(new Stop(125, cleanText(why?.engine_message || why?.message || why?.code || 'The command result is unknown. Do not repeat it automatically.', secrets) + (['failed', 'refused'].includes(answer.state) ? '' : recovery)), { tryUsage: usage,fix:why?.fix });
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 });
8854
9256
  }
8855
9257
  knownOutcome = true;
8856
9258
  const hasEmbeddedWorld = Object.hasOwn(answer.result ?? {}, 'world');
@@ -9589,6 +9991,7 @@ async function reconcileBatchInternal({ root, store, batchId, explicitOrigin = n
9589
9991
  if (mutated) {
9590
9992
  saved.reservations_reconciled_at = reconciledAt;
9591
9993
  store.write(batchPath, saved);
9994
+ updateBatchReservationIndex(store.dir, batchId, saved);
9592
9995
  }
9593
9996
 
9594
9997
  const remainingUnresolved = activeCount + unavailableCount;
@@ -10068,9 +10471,11 @@ export async function inspectProgram(context, capture, { appMap } = {}) {
10068
10471
  if (verdict.kind === 'busy' && await waitBudget(context, verdict.wait)) continue;
10069
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.');
10070
10473
  const answer = await readProgramReceipt(context,id,'lint',verdict,context.lint);
10474
+ const failClosed = lintFailClosed(answer);
10071
10475
  if (answer?.state !== 'passed' || answer.result?.report?.lint?.complete !== true && answer.result?.problems_complete !== true
10476
+ || failClosed
10072
10477
  || answer.result?.report?.program?.refused_prompts?.length || answer.result?.refusals?.length) {
10073
- 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.');
10074
10479
  }
10075
10480
  const admittedPrompts = answer.result?.report?.program?.prompts;
10076
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.');