@promptdriven/runtime-client 1.0.0 → 1.1.0
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.
- package/package.json +1 -1
- package/src/runtime/agent-chat.mjs +55 -8
- package/src/runtime/index.mjs +32 -1
- package/src/runtime/live-local-bridge.mjs +178 -0
- package/src/runtime/live-local.mjs +181 -0
- package/src/runtime/run-program.mjs +797 -0
- package/src/runtime/runtime-bindings.mjs +22 -12
- package/src/runtime/runtime-check-plan.mjs +1 -1
- package/src/runtime/runtime-client.mjs +2009 -218
- package/src/runtime/runtime-outcome.mjs +63 -2
- package/src/runtime/runtime-output.mjs +46 -8
- package/src/runtime/runtime-preflight.mjs +793 -79
- package/src/runtime/runtime-slots.mjs +75 -4
- package/src/runtime/scenario-json.mjs +167 -1
- package/src/runtime/secret-redaction.mjs +3 -2
- package/src/runtime/try-doors.mjs +425 -59
- package/src/runtime/try-http.mjs +40 -14
- package/src/runtime/try-update-policy.mjs +43 -0
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
// Generated from prompts/cli/runtime-client.prompt.md (sha256:
|
|
1
|
+
// Generated from prompts/cli/runtime-client.prompt.md (sha256: bc46a590b2b1b2fbd0d35e45ea8e329d99805c2d0eff806e55d768ac45916a3e).
|
|
2
2
|
import { composeProductTry, selectJourneys, productTapCallBound } from './product-composition.mjs';
|
|
3
3
|
import { bindExistingTry, projectTryCall, projectTryObservation, selectTryToStop } from './try-session.mjs';
|
|
4
|
-
import {expandSource, parseJsonValue, stringifyJsonValue} from './contract-refs.mjs';
|
|
4
|
+
import {expandSource, parseJsonValue, stringifyJsonValue, jsonNumberIdentity} from './contract-refs.mjs';
|
|
5
5
|
import { describeCallPreflight } from './lint-call-preflight.mjs';
|
|
6
6
|
import { describeCompatibility, describeLintDiagnostics } from './lint-compatibility-display.mjs';
|
|
7
7
|
import { isRecentLintReceipt } from './runtime-lint-receipt.mjs';
|
|
8
|
+
import { createLocalCommandBridge } from './live-local-bridge.mjs';
|
|
9
|
+
import { compileLocalManifest, validateLocalManifest } from './live-local.mjs';
|
|
8
10
|
import { rememberSecrets as fallbackRememberSecrets } from './secret-redaction.mjs';
|
|
9
11
|
import { bindingPlanLines, bindingRefusals } from './runtime-binding-plan.mjs';
|
|
10
12
|
import { buildCheckPlan, checkPlanResults, checkPlanLines, checkPlanResultLines, selectCheckTests, baselineReport, evaluateCheckBudget } from './runtime-check-plan.mjs';
|
|
@@ -15,16 +17,18 @@ import { bindingCoverage } from './runtime-bindings.mjs';
|
|
|
15
17
|
import { spawn, spawnSync } from 'node:child_process';
|
|
16
18
|
import { createHash, randomUUID } from 'node:crypto';
|
|
17
19
|
import { chmodSync, closeSync, constants, fstatSync, fsyncSync, lstatSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, readSync, renameSync, rmdirSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';
|
|
18
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
20
|
+
import { isDeepStrictEqual, types } from 'node:util';
|
|
19
21
|
import { homedir, hostname } from 'node:os';
|
|
20
22
|
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
21
23
|
import { createInterface } from 'node:readline';
|
|
22
|
-
import { DRAFT_SERVER_TEXT, PreflightError, TEST_SCHEMA, captureSource, scenarioShapeRefusal, checkInput, fillHashes, lintLocalHygiene, sharedSourceFiles, findTests, formatSize, gitFiles, otherFiles,
|
|
23
|
-
discoveryRefusal, preflight, hasPromptInterface, interfaceBlocks, interfaceFindings, executableInterfaceText, readPrompt, formatWarningLines, schemaKeywordWarningLines, missingCliImplementationWarnings, prepareHashSelection, sourceFilePort, sha256, STALE_HINT, staleHint } from './runtime-preflight.mjs';
|
|
24
|
+
import { DRAFT_SERVER_TEXT, PreflightError, TEST_SCHEMA, LIMITS, captureSource, tarFiles, scenarioShapeRefusal, checkInput, fillHashes, lintLocalHygiene, sharedSourceFiles, findTests, formatSize, gitFiles, otherFiles,
|
|
25
|
+
discoveryRefusal, preflight, hasPromptInterface, interfaceBlocks, interfaceFindings, executableInterfaceText, readPrompt, promptMarkdownTargets, formatWarningLines, schemaKeywordWarningLines, missingCliImplementationWarnings, prepareHashSelection, sourceFilePort, exactNumberSpelling, sha256, STALE_HINT, staleHint } from './runtime-preflight.mjs';
|
|
24
26
|
import { catalogRecords, compareCopies } from './contract-refs.mjs';
|
|
27
|
+
import { jsonSafe, parseScenarioJson } from './scenario-json.mjs';
|
|
28
|
+
import { scenarioDerivationRefusal } from './runtime-preflight.mjs';
|
|
25
29
|
import { OPEN_STATES, causeText, cleanText, progressTicker, projectAnswer, refusalView, renderJson, renderText, summaryLine, stepTimeLimit, tokenUsageOf, tryUsage, validLink, coverageText } from './runtime-output.mjs';
|
|
26
30
|
|
|
27
|
-
const localInterfaceProblem = problem => ['interface-missing','interface-kind-invalid','native-reason-missing','interface-draft-incomplete'].includes(problem.code);
|
|
31
|
+
const localInterfaceProblem = problem => ['interface-missing','interface-kind-invalid','native-reason-missing','interface-draft-incomplete','duplicate-selector-word'].includes(problem.code);
|
|
28
32
|
const unboundPortError = message => Object.assign(new Error(message), { unboundPort: true });
|
|
29
33
|
// The preflight owner's local format advice (#3206): an explicit full kind in a draft and unsupported schema
|
|
30
34
|
// keywords are warnings in lint and the files preview, never refusals; the engine is the one place that refuses.
|
|
@@ -55,6 +59,7 @@ function hasMissingPromptInterface(root, found, startPaths) {
|
|
|
55
59
|
}
|
|
56
60
|
return false;
|
|
57
61
|
}
|
|
62
|
+
const diagnosticBatch = record => record?.diagnostic_subset === true || record?.rows?.some(row=>row?.diagnostic_subset === true);
|
|
58
63
|
const entryPaths = tests => tests.filter(test => !test.error).flatMap(test => (Array.isArray(test.doc?.steps) ? test.doc.steps : []).map(step => step?.entry_path));
|
|
59
64
|
|
|
60
65
|
// The one place in pdd that names the PDD runtime address; PDD_RUNTIME_URL overrides it.
|
|
@@ -88,6 +93,60 @@ function requestedCalls(raw) {
|
|
|
88
93
|
throw new Stop(2, '--max-calls must be a whole number from 1 to 1000, the interpreter maximum.');
|
|
89
94
|
return Number(raw);
|
|
90
95
|
}
|
|
96
|
+
|
|
97
|
+
function sampleOptions(options) {
|
|
98
|
+
const parse = value => {
|
|
99
|
+
const number = typeof value === 'string' && /^[0-9]+$/.test(value) ? Number(value) : value;
|
|
100
|
+
if (!Number.isSafeInteger(number) || number < 2 || number > 5) throw new Stop(2, 'samples must be an integer from 2 through 5.');
|
|
101
|
+
return number;
|
|
102
|
+
};
|
|
103
|
+
if (!Object.hasOwn(options, 'samples') && !Object.hasOwn(options, '--samples')) return null;
|
|
104
|
+
const samples = parse(Object.hasOwn(options, 'samples') ? options.samples : options['--samples']);
|
|
105
|
+
if (Object.hasOwn(options, 'samples') && Object.hasOwn(options, '--samples') && samples !== parse(options['--samples'])) throw new Stop(2, 'Conflicting samples options.');
|
|
106
|
+
if (['--lf', '--cache-clear'].some(key => Object.hasOwn(options, key))) throw new Stop(2, 'samples cannot be combined with --lf or --cache-clear: probes bypass the ordinary cache and already request fresh samples.');
|
|
107
|
+
if (['--lint', '--files', '--local', '--read', '--retry', '--request', '--screen', '--drawing', '--look', '--explain-bindings', '--live', '--live-local'].some(key => Object.hasOwn(options, key))
|
|
108
|
+
|| options.resource_mode === 'live' || options['--resource-mode'] === 'live') throw new Stop(2, 'samples requires a normal simulated Check.');
|
|
109
|
+
const cap = requestedCalls(options['--max-calls']);
|
|
110
|
+
if (cap !== null && samples > cap) throw new Stop(2, 'samples exceeds the total --max-calls allowance.');
|
|
111
|
+
const supplied = Object.hasOwn(options, 'step_ids'), thin = Object.hasOwn(options, '--step');
|
|
112
|
+
const step_ids = supplied ? options.step_ids : thin ? [options['--step']] : undefined;
|
|
113
|
+
if ((supplied || thin) && (!Array.isArray(step_ids) || !step_ids.length || step_ids.some(id => typeof id !== 'string' || !id.trim()) || new Set(step_ids).size !== step_ids.length)) throw new Stop(2, 'Select nonempty unique step IDs.');
|
|
114
|
+
if (supplied && thin && (step_ids.length !== 1 || step_ids[0] !== options['--step'])) throw new Stop(2, 'Conflicting selected step options.');
|
|
115
|
+
return { samples, fresh: true, ...(step_ids ? { step_ids: [...step_ids] } : {}) };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function validateSampleSelection(selected, checkOptions, root, found) {
|
|
119
|
+
if (!checkOptions) return;
|
|
120
|
+
const references = value => {
|
|
121
|
+
if (!value || typeof value !== 'object') return [];
|
|
122
|
+
return [...(isObject(value.$step_result) ? [value.$step_result.step_id] : []), ...Object.values(value).flatMap(references)];
|
|
123
|
+
};
|
|
124
|
+
for (const test of selected) {
|
|
125
|
+
const doc = test.doc, steps = doc?.steps ?? [], ids = checkOptions.step_ids;
|
|
126
|
+
const seen = new Set(), resources = [], visit = path => {
|
|
127
|
+
if (!path || seen.has(path)) return;
|
|
128
|
+
seen.add(path);
|
|
129
|
+
let prompt;
|
|
130
|
+
try { prompt = readPrompt(root, found.visible, path, found.workspace); } catch { return; }
|
|
131
|
+
resources.push(...(prompt.interface?.resources ?? []));
|
|
132
|
+
for (const call of prompt.interface?.calls ?? []) visit(call.target);
|
|
133
|
+
};
|
|
134
|
+
for (const step of steps) visit(step.entry_path);
|
|
135
|
+
const live = value => value && typeof value === 'object' && (value.resource_mode === 'live' || value.mode === 'live' || value.action === 'live');
|
|
136
|
+
const liveBindings = bindings => Array.isArray(bindings) ? bindings.some(row => live(row.binding)) : Object.values(bindings ?? {}).some(live);
|
|
137
|
+
if (liveBindings(doc?.simulation) || steps.some(step => liveBindings(step.simulation_overrides)) || resources.some(resource => live(resource) || resource.operations?.some(live))) throw new Stop(2, 'samples requires simulated resources.');
|
|
138
|
+
if (!ids) continue;
|
|
139
|
+
if (ids.some(id => !steps.some(step => step.step_id === id))) throw new Stop(2, `Unknown selected step ID. Authored IDs: ${steps.map(step => step.step_id).join(', ')}. Run the full Story or select authored IDs.`);
|
|
140
|
+
const chosen = new Set(ids);
|
|
141
|
+
for (const step of steps.filter(step => chosen.has(step.step_id))) if (references(step).some(id => !chosen.has(id)))
|
|
142
|
+
throw new Stop(2, 'Selected steps depend on an omitted predecessor. Run the full Story.');
|
|
143
|
+
// A retained resource world can depend on unselected earlier operations. Without
|
|
144
|
+
// a replay contract, only a prefix or a resource-free selection is reproducible.
|
|
145
|
+
const last = Math.max(...steps.map((step, index) => chosen.has(step.step_id) ? index : -1));
|
|
146
|
+
if (steps.slice(0, last).some(step => !chosen.has(step.step_id)) && (Object.keys(doc?.simulation ?? {}).length || resources.some(resource => resource.kind !== 'compute')))
|
|
147
|
+
throw new Stop(2, 'Selected resource state may depend on an omitted predecessor. Run the full Story.');
|
|
148
|
+
}
|
|
149
|
+
}
|
|
91
150
|
function requestedTotalCalls(raw) {
|
|
92
151
|
if (raw === undefined) return null;
|
|
93
152
|
if (!(typeof raw === 'number' || typeof raw === 'string' && /^[1-9][0-9]{0,5}$/.test(raw))
|
|
@@ -164,7 +223,7 @@ function withDefaults(ports) {
|
|
|
164
223
|
throw unboundPortError('Exit code port (exitCodeFor or exitFor) is not bound.');
|
|
165
224
|
};
|
|
166
225
|
return {
|
|
167
|
-
env, baselineFiles: ports.baselineFiles, baselineIdentity: ports.baselineIdentity, checkPlanPorts: ports.checkPlanPorts, tryLauncherUrl: ports.tryLauncherUrl, redaction: ports.redaction, redactSecrets: ports.redactSecrets, rememberSecrets: ports.rememberSecrets, clientVersion: ports.clientVersion, workflowBaseSha: ports.workflowBaseSha, headerPrompts: ports.headerPrompts, resolveOwners: ports.resolveOwners, promptClaims: ports.promptClaims, isTestOwnedPath: ports.isTestOwnedPath, evidenceEligibility: ports.evidenceEligibility, readEvidenceEligibility: ports.readEvidenceEligibility, evidencePorts: ports.evidencePorts, allRuns: ports.allRuns, assessNativeEvidence: ports.assessNativeEvidence, usableResult: ports.usableResult, resultLines: ports.resultLines, parseProductDocuments: ports.parseProductDocuments, parseProductWorldWriters: ports.parseProductWorldWriters, loadAgentDefinitions: ports.loadAgentDefinitions, agents: ports.agents, guidePorts: ports.guidePorts, askApproval: ports.askApproval, promptPath: ports.promptPath, lineReader: ports.lineReader ?? defaultLineReader, lintSvgLayouts: ports.lintSvgLayouts, compareScreen: ports.compareScreen, formatScreenComparison: ports.formatScreenComparison, caseHandoff:ports.caseHandoff, cacheFiles: ports.cacheFiles ?? nativeCacheFiles, cacheHash: ports.cacheHash ?? sha256, acquireBatchLock: ports.acquireBatchLock ?? acquireRuntimeBatchLock, timers: ports.timers, random: ports.random, findTests: findTestsBound, captureSource: captureSourceBound, fillHashes: fillHashesBound, prepareHashSelection: ports.prepareHashSelection, isStoryPath: ports.isStoryPath, hasAcceptance: ports.hasAcceptance, matchTests: ports.matchTests, orphanSummary: ports.orphanSummary, selectTests: selectTestsBound, expectedTestPath: expectedTestPathBound, whyNoTests: whyNoTestsBound, noTestsMessage, exitCodeFor: exitCodeForBound, exitFor: ports.exitFor, promptTestsLabel: ports.promptTestsLabel, slotFiles: ports.slotFiles, isAlive: ports.isAlive, pid: ports.pid, agentBridge: ports.agentBridge, discoverAgents: ports.discoverAgents, askAgent: ports.askAgent, signal: ports.signal, ghPath: ports.ghPath, shell: ports.shell, serve: ports.serve, stdout: ports.stdout ?? process.stdout, stderr: ports.stderr ?? process.stderr, fetch: ports.fetch ?? globalThis.fetch,
|
|
226
|
+
liveLocal: ports.liveLocal, env, files:ports.files, fault:ports.fault, host:ports.host, directInvoke:ports.directInvoke===true, baselineFiles: ports.baselineFiles, baselineIdentity: ports.baselineIdentity, checkPlanPorts: ports.checkPlanPorts, tryLauncherUrl: ports.tryLauncherUrl, redaction: ports.redaction, redactSecrets: ports.redactSecrets, rememberSecrets: ports.rememberSecrets, clientVersion: ports.clientVersion, workflowBaseSha: ports.workflowBaseSha, headerPrompts: ports.headerPrompts, resolveOwners: ports.resolveOwners, promptClaims: ports.promptClaims, isTestOwnedPath: ports.isTestOwnedPath, evidenceEligibility: ports.evidenceEligibility, readEvidenceEligibility: ports.readEvidenceEligibility, evidencePorts: ports.evidencePorts, allRuns: ports.allRuns, assessNativeEvidence: ports.assessNativeEvidence, usableResult: ports.usableResult, resultLines: ports.resultLines, parseProductDocuments: ports.parseProductDocuments, parseProductWorldWriters: ports.parseProductWorldWriters, loadAgentDefinitions: ports.loadAgentDefinitions, agents: ports.agents, guidePorts: ports.guidePorts, askApproval: ports.askApproval, promptPath: ports.promptPath, lineReader: ports.lineReader ?? defaultLineReader, lintSvgLayouts: ports.lintSvgLayouts, compareScreen: ports.compareScreen, formatScreenComparison: ports.formatScreenComparison, caseHandoff:ports.caseHandoff, onDoorRequest:ports.onDoorRequest, cacheFiles: ports.cacheFiles ?? nativeCacheFiles, cacheHash: ports.cacheHash ?? sha256, acquireBatchLock: ports.acquireBatchLock ?? acquireRuntimeBatchLock, timers: ports.timers, random: ports.random, findTests: findTestsBound, captureSource: captureSourceBound, fillHashes: fillHashesBound, prepareHashSelection: ports.prepareHashSelection, isStoryPath: ports.isStoryPath, hasAcceptance: ports.hasAcceptance, matchTests: ports.matchTests, orphanSummary: ports.orphanSummary, selectTests: selectTestsBound, expectedTestPath: expectedTestPathBound, whyNoTests: whyNoTestsBound, noTestsMessage, exitCodeFor: exitCodeForBound, exitFor: ports.exitFor, promptTestsLabel: ports.promptTestsLabel, slotFiles: ports.slotFiles, isAlive: ports.isAlive, pid: ports.pid, agentBridge: ports.agentBridge, discoverAgents: ports.discoverAgents, askAgent: ports.askAgent, signal: ports.signal, ghPath: ports.ghPath, shell: ports.shell ?? ((shell, shellEnv, shellRoot) => new Promise((done,reject)=>{const child=spawn(shell,['-i'],{cwd:shellRoot??process.cwd(),env:shellEnv,stdio:'inherit'});child.on('error',reject);child.on('exit',(code,signal)=>done(code??(signal?128:0)));})), serve: ports.serve, stdout: ports.stdout ?? process.stdout, stderr: ports.stderr ?? process.stderr, fetch: ports.fetch ?? globalThis.fetch,
|
|
168
227
|
gh: ports.gh ?? (args => {
|
|
169
228
|
const executable = authExecutable(env, ports.ghPath);
|
|
170
229
|
return executable ? spawnSync(executable, args, { encoding: 'utf8', env, stdio: ['ignore', 'pipe', 'pipe'], timeout: 60_000 })
|
|
@@ -245,7 +304,7 @@ export function readContractHistory({root,env = process.env},ports={}) {
|
|
|
245
304
|
for (const name of entries.sort()) {
|
|
246
305
|
if (!BATCH.test(name) || !statOrNull(join(directory,name))?.isDirectory() || statOrNull(join(directory,name))?.isSymbolicLink()) continue;
|
|
247
306
|
const folder=join(directory,name), saved=read(join(folder,'batch.json'));
|
|
248
|
-
if (!saved || saved.intent === 'lint-only' || !Array.isArray(saved.rows)) continue;
|
|
307
|
+
if (!saved || diagnosticBatch(saved) || saved.intent === 'lint-only' || !Array.isArray(saved.rows)) continue;
|
|
249
308
|
const eligibility=(ports.evidenceEligibility??ports.readEvidenceEligibility??(() => ({state:'unavailable',reason:'workflow evidence eligibility port is not bound'})))({root,producerRoot:saved.root,tests:[...new Set(saved.rows.map(row=>row?.test))],source_sha256:saved.source_sha256,runId:saved.association?.runId??null,stage:saved.association?.stage??null},{env,...ports.evidencePorts});
|
|
250
309
|
if(eligibility.state!=='eligible'&&(saved.root!==root||saved.association))continue;
|
|
251
310
|
for (const row of saved.rows) {
|
|
@@ -275,7 +334,8 @@ export function readContractHistory({root,env = process.env},ports={}) {
|
|
|
275
334
|
|
|
276
335
|
const AFFECTED_DISCLAIMER = 'Affected checks only; this is not a full workflow pass. Required full-pass gates still apply.';
|
|
277
336
|
function selectedCheckScope(plan, rows, selection) {
|
|
278
|
-
const scope = checkPlanResults(plan, rows);
|
|
337
|
+
const scope = checkPlanResults(plan, rows.map(row => (row.diagnostic || row.diagnostic_subset) && row.state === 'passed' ? {...row,state:'unknown'} : row));
|
|
338
|
+
if (scope && rows.some(row => row.diagnostic || row.diagnostic_subset)) scope.guidance = `Diagnostic step subset; run the full Story for certification. ${scope.guidance ?? ''}`.trim();
|
|
279
339
|
if (scope && selection?.mode === 'affected' && scope.baseline.unresolved.length && !plan.prerequisites?.length) {
|
|
280
340
|
const selected = scope.target.failures.length ? `Repair target failures: ${scope.target.failures.join(', ')}. `
|
|
281
341
|
: scope.target.unresolved.length ? `Read the saved batch for unresolved selected checks: ${scope.target.unresolved.join(', ')}. ` : '';
|
|
@@ -325,6 +385,7 @@ async function readBaselineReport(context, plan, identity) {
|
|
|
325
385
|
const folder = join(directory,name); let saved;
|
|
326
386
|
try { saved = await read(join(folder,'batch.json')); }
|
|
327
387
|
catch { partial=true;warn('Some saved Check batches are unreadable or corrupt.');continue; }
|
|
388
|
+
if (diagnosticBatch(saved)) continue;
|
|
328
389
|
if (saved?.intent !== 'check' && (Object.hasOwn(saved ?? {},'intent') || !Array.isArray(saved?.rows) || !saved.rows.every(row=>isObject(row) && validSavedCheck(row)))) continue;
|
|
329
390
|
if (saved.version !== 1 || saved.batch !== name || !Array.isArray(saved.rows) || typeof saved.root !== 'string') {
|
|
330
391
|
partial=true;warn('Some saved Check batches have invalid original identity.');continue;
|
|
@@ -529,6 +590,7 @@ async function readSavedStoryEvidence({ root, comparisonRoot = root, withTests =
|
|
|
529
590
|
batch = JSON.parse(await read(path));
|
|
530
591
|
if (!isObject(batch) || batch.version !== 1 || batch.batch !== name || typeof batch.root !== 'string' || !Array.isArray(batch.rows)) throw Error('invalid batch');
|
|
531
592
|
} catch (error) { warning(path, error); continue; }
|
|
593
|
+
if (diagnosticBatch(batch)) continue;
|
|
532
594
|
if (!anyRoot && await real(batch.root) !== wanted) continue;
|
|
533
595
|
const legacy = !Object.hasOwn(batch, 'intent');
|
|
534
596
|
if (batch.intent !== 'check') {
|
|
@@ -648,6 +710,7 @@ export async function resendableStoryChecks({ root, since = 0 }, ports = {}) {
|
|
|
648
710
|
let batch;
|
|
649
711
|
try { batch = JSON.parse(await read(join(directory, name, 'batch.json'))); } catch { continue; }
|
|
650
712
|
if (!isObject(batch) || batch.batch !== name || batch.intent !== 'check' || typeof batch.root !== 'string' || !Array.isArray(batch.rows)) continue;
|
|
713
|
+
if (diagnosticBatch(batch)) continue;
|
|
651
714
|
if (since > 0 && !(Date.parse(batch.created_at) >= since) || await real(batch.root) !== wanted) continue;
|
|
652
715
|
const files = Array.isArray(batch.files) ? batch.files : [];
|
|
653
716
|
const storyOf = row => typeof row?.story !== 'string' ? null : row.story.endsWith('.md') ? row.story
|
|
@@ -696,6 +759,125 @@ function validGithubUser(record) {
|
|
|
696
759
|
}
|
|
697
760
|
const isGithubRateLimit = text => typeof text === 'string' && /rate limit|secondary rate limit|abuse detection/i.test(text);
|
|
698
761
|
|
|
762
|
+
function knownCredentialReplacer(secrets) {
|
|
763
|
+
const literals=[...new Set(secrets.filter(value=>typeof value==='string'&&value))].sort((a,b)=>b.length-a.length);
|
|
764
|
+
const redact=value=>literals.reduce((text,secret)=>text.split(secret).join('[secret]'),value);
|
|
765
|
+
const remapped=new WeakMap();
|
|
766
|
+
return (_key,value)=>{
|
|
767
|
+
if(typeof value==='string')return redact(value);
|
|
768
|
+
// Keep native raw-number spelling after toJSON evaluation.
|
|
769
|
+
if(!isObject(value))return value;
|
|
770
|
+
if(JSON.isRawJSON(value)){
|
|
771
|
+
if(!value.rawJSON.startsWith('"'))return value;
|
|
772
|
+
const text=JSON.parse(value.rawJSON),masked=redact(text);
|
|
773
|
+
return masked===text?value:masked;
|
|
774
|
+
}
|
|
775
|
+
if(remapped.has(value))return remapped.get(value);
|
|
776
|
+
const keys=Object.keys(value),names=keys.map(redact);
|
|
777
|
+
if(keys.every((key,index)=>key===names[index]))return value;
|
|
778
|
+
const used=new Set(keys.filter((key,index)=>key===names[index]));
|
|
779
|
+
const result=Object.fromEntries(keys.map((key,index)=>{
|
|
780
|
+
const masked=names[index];let name=masked;
|
|
781
|
+
// Reserve ordinary keys and retain each credential-bearing collision value.
|
|
782
|
+
if(masked!==key)for(let suffix=2;used.has(name);suffix++)name=`${masked} (${suffix})`;
|
|
783
|
+
used.add(name);return [name,value[key]];
|
|
784
|
+
}));
|
|
785
|
+
remapped.set(value,result);return result;
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
function stringifyStateJson(value, secrets) {
|
|
790
|
+
const replacer = knownCredentialReplacer(secrets);
|
|
791
|
+
const chunks = [];
|
|
792
|
+
const ancestors = new Set();
|
|
793
|
+
const stack = [];
|
|
794
|
+
const emit = (holder, key, prefix, inArray = false) => {
|
|
795
|
+
let item = holder[key];
|
|
796
|
+
const kind = typeof item;
|
|
797
|
+
if (item !== null && (kind === 'object' || kind === 'function' || kind === 'bigint')) {
|
|
798
|
+
const toJSON = item.toJSON;
|
|
799
|
+
if (typeof toJSON === 'function') item = Reflect.apply(toJSON, item, [key]);
|
|
800
|
+
}
|
|
801
|
+
item = replacer(key, item);
|
|
802
|
+
if (types.isNumberObject(item)) item = +item;
|
|
803
|
+
else if (types.isStringObject(item)) item = replacer(key, String(item));
|
|
804
|
+
else if (types.isBooleanObject(item)) item = Boolean.prototype.valueOf.call(item);
|
|
805
|
+
if (typeof item === 'bigint' || types.isBigIntObject(item)) throw new TypeError('Do not know how to serialize a BigInt');
|
|
806
|
+
|
|
807
|
+
if (typeof item !== 'object' || item === null || JSON.isRawJSON(item)) {
|
|
808
|
+
let text;
|
|
809
|
+
if (JSON.isRawJSON(item)) text = item.rawJSON;
|
|
810
|
+
else if (typeof item !== 'function') text = JSON.stringify(item);
|
|
811
|
+
if (text === undefined && !inArray) return false;
|
|
812
|
+
chunks.push(prefix, text ?? 'null');
|
|
813
|
+
return true;
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
if (ancestors.has(item)) throw new TypeError('Converting circular structure to JSON');
|
|
817
|
+
const array = Array.isArray(item);
|
|
818
|
+
const keys = array ? null : Object.keys(item);
|
|
819
|
+
const length = array ? Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Math.trunc(+item.length) || 0)) : keys.length;
|
|
820
|
+
chunks.push(prefix, array ? '[' : '{');
|
|
821
|
+
ancestors.add(item);
|
|
822
|
+
stack.push({ item, keys, length, index: 0, wrote: false });
|
|
823
|
+
return true;
|
|
824
|
+
};
|
|
825
|
+
|
|
826
|
+
if (!emit({ '': value }, '', '')) return undefined;
|
|
827
|
+
while (stack.length) {
|
|
828
|
+
const frame = stack.at(-1);
|
|
829
|
+
const { item, keys, length } = frame;
|
|
830
|
+
if (frame.index === length) {
|
|
831
|
+
stack.pop();
|
|
832
|
+
ancestors.delete(item);
|
|
833
|
+
if (frame.wrote) chunks.push(`\n${' '.repeat(stack.length)}`);
|
|
834
|
+
chunks.push(keys ? '}' : ']');
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
const key = keys ? keys[frame.index] : String(frame.index);
|
|
838
|
+
frame.index++;
|
|
839
|
+
const prefix = `${frame.wrote ? ',' : ''}\n${' '.repeat(stack.length)}${keys ? `${JSON.stringify(key)}: ` : ''}`;
|
|
840
|
+
frame.wrote = emit(item, key, prefix, !keys) || frame.wrote;
|
|
841
|
+
}
|
|
842
|
+
return chunks.join('');
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
function parseStateJson(text) {
|
|
846
|
+
// Let the native parser validate the document and resolve duplicate keys.
|
|
847
|
+
// A second parse supplies the original number text at those same locations.
|
|
848
|
+
const value = JSON.parse(text);
|
|
849
|
+
const token = /"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g;
|
|
850
|
+
const chunks = [];
|
|
851
|
+
let start = 0;
|
|
852
|
+
for (let match; (match = token.exec(text));) {
|
|
853
|
+
if (match[0] === '"') {
|
|
854
|
+
let end = token.lastIndex;
|
|
855
|
+
while (text[end] !== '"') end += text[end] === '\\' ? 2 : 1;
|
|
856
|
+
token.lastIndex = end + 1;
|
|
857
|
+
continue;
|
|
858
|
+
}
|
|
859
|
+
chunks.push(text.slice(start, match.index), `"${match[0]}"`);
|
|
860
|
+
start = token.lastIndex;
|
|
861
|
+
}
|
|
862
|
+
if (!chunks.length) return value;
|
|
863
|
+
chunks.push(text.slice(start));
|
|
864
|
+
|
|
865
|
+
const source = JSON.parse(chunks.join(''));
|
|
866
|
+
if (typeof value === 'number') return programJsonNumber(value, source);
|
|
867
|
+
const stack = [[value, source]];
|
|
868
|
+
while (stack.length) {
|
|
869
|
+
const [item, tokens] = stack.pop();
|
|
870
|
+
for (const key of Object.keys(item)) {
|
|
871
|
+
const child = item[key];
|
|
872
|
+
if (typeof child === 'number') item[key] = programJsonNumber(child, tokens[key]);
|
|
873
|
+
else if (typeof child === 'object' && child !== null) stack.push([child, tokens[key]]);
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
return value;
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
const REPO_SNAPSHOT = Symbol('repository snapshot');
|
|
880
|
+
|
|
699
881
|
class StateStore {
|
|
700
882
|
constructor(dir) { this.dir = dir; this.secrets = []; }
|
|
701
883
|
folder(...parts) {
|
|
@@ -706,12 +888,11 @@ class StateStore {
|
|
|
706
888
|
// The token never reaches a file, even when a server answer echoes it.
|
|
707
889
|
write(path, value) {
|
|
708
890
|
const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
709
|
-
|
|
710
|
-
for (const secret of this.secrets) text = text.split(secret).join('[secret]');
|
|
891
|
+
const text = `${stringifyStateJson(value, this.secrets)}\n`;
|
|
711
892
|
writeFileSync(temporary, text, { mode: 0o600 });
|
|
712
893
|
chmodSync(temporary, 0o600); renameSync(temporary, path);
|
|
713
894
|
}
|
|
714
|
-
read(path) { try { return
|
|
895
|
+
read(path) { try { return parseStateJson(readFileSync(path, 'utf8')); } catch { return null; } }
|
|
715
896
|
readGithubUser() {
|
|
716
897
|
try {
|
|
717
898
|
if (statOrNull(this.dir)?.isSymbolicLink()) return null;
|
|
@@ -766,13 +947,51 @@ class StateStore {
|
|
|
766
947
|
try { writeSync(fd, `${id}\n`); } finally { closeSync(fd); }
|
|
767
948
|
}
|
|
768
949
|
repoKey(root) { return createHash('sha256').update(realpathSync(root)).digest('hex').slice(0, 16); }
|
|
769
|
-
repo(root) {
|
|
770
|
-
|
|
950
|
+
repo(root) {
|
|
951
|
+
const value = this.read(join(this.folder('repos'), `${this.repoKey(root)}.json`)) ?? { root: realpathSync(root), last_batch: null, tries: {} };
|
|
952
|
+
value[REPO_SNAPSHOT] = JSON.parse(JSON.stringify(value));
|
|
953
|
+
return value;
|
|
954
|
+
}
|
|
955
|
+
withRepoLock(root, action) {
|
|
956
|
+
return withRepositoryRunLockAsync(join(this.folder('repos'), `${this.repoKey(root)}.json`), action);
|
|
957
|
+
}
|
|
958
|
+
updateRepo(root, update) {
|
|
959
|
+
return withRepositoryRunLock(root, this, () => {
|
|
960
|
+
const next = update(this.repo(root));
|
|
961
|
+
if (next !== undefined) this.write(join(this.folder('repos'), `${this.repoKey(root)}.json`), next);
|
|
962
|
+
return next;
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
saveRepo(root, value) {
|
|
966
|
+
const baseline = value[REPO_SNAPSHOT];
|
|
967
|
+
const patch = (old, next, current) => {
|
|
968
|
+
if (isDeepStrictEqual(old, next)) return current;
|
|
969
|
+
if (isObject(old) && isObject(next) && isObject(current)) {
|
|
970
|
+
const out = { ...current };
|
|
971
|
+
for (const key of new Set([...Object.keys(old), ...Object.keys(next)])) {
|
|
972
|
+
if (isDeepStrictEqual(old[key], next[key])) continue;
|
|
973
|
+
if (!Object.hasOwn(next, key)) { if (isDeepStrictEqual(current[key], old[key])) delete out[key]; }
|
|
974
|
+
else if (['last_run', 'last_door'].includes(key) && !isDeepStrictEqual(current[key], old[key])) continue;
|
|
975
|
+
else out[key] = patch(old[key], next[key], current[key]);
|
|
976
|
+
}
|
|
977
|
+
return out;
|
|
978
|
+
}
|
|
979
|
+
return next;
|
|
980
|
+
};
|
|
981
|
+
return this.updateRepo(root, current => baseline ? patch(baseline, value, current) : { ...current, ...value });
|
|
982
|
+
}
|
|
983
|
+
updateLastRun(root, update) {
|
|
984
|
+
return this.withRepoLock(root, () => this.updateRepo(root, current => {
|
|
985
|
+
const last = update(current.last_run);
|
|
986
|
+
return last === undefined ? undefined : { ...current, last_run: last };
|
|
987
|
+
}));
|
|
988
|
+
}
|
|
771
989
|
}
|
|
772
990
|
|
|
773
991
|
// Native boundary: one owner from the fresh batch load through the final saves.
|
|
774
|
-
export async function acquireRuntimeBatchLock(folder,
|
|
775
|
-
|
|
992
|
+
export async function acquireRuntimeBatchLock(folder, options = {}) { return acquireNativeBatchLock(folder, options); }
|
|
993
|
+
function acquireNativeBatchLock(folder, { onWarning = () => {}, name = 'batch.lock' } = {}) {
|
|
994
|
+
const lock = join(folder, name);
|
|
776
995
|
const owner = { pid: process.pid, host: hostname(), started_at: new Date().toISOString() };
|
|
777
996
|
const problem = (code, path, record) => Object.assign(new Error(code), { code, lock: path, owner: record });
|
|
778
997
|
const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
|
|
@@ -843,6 +1062,50 @@ export async function acquireRuntimeBatchLock(folder, { onWarning = () => {} } =
|
|
|
843
1062
|
return release;
|
|
844
1063
|
}
|
|
845
1064
|
|
|
1065
|
+
const repositoryLocks = new Set();
|
|
1066
|
+
|
|
1067
|
+
function repositoryRunLockFolder(repoState) {
|
|
1068
|
+
const folder = repoState.replace(/\.json$/, '.last-run');
|
|
1069
|
+
mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
1070
|
+
if (!lstatSync(folder).isDirectory()) throw new Stop(125, 'Refusing an unsafe Try lock folder.');
|
|
1071
|
+
chmodSync(folder, 0o700);
|
|
1072
|
+
return folder;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
function runWithOwnedRepositoryLock(folder, release, action) {
|
|
1076
|
+
repositoryLocks.add(folder);
|
|
1077
|
+
try { return action(); } finally { repositoryLocks.delete(folder); release(); }
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
export function withRepositoryRunLock(root, store, action) {
|
|
1081
|
+
const folder = repositoryRunLockFolder(join(store.folder('repos'), `${store.repoKey(root)}.json`));
|
|
1082
|
+
if (repositoryLocks.has(folder)) return action();
|
|
1083
|
+
const until = Date.now() + 10000;
|
|
1084
|
+
let release;
|
|
1085
|
+
for (;;) {
|
|
1086
|
+
try { release = acquireNativeBatchLock(folder); break; }
|
|
1087
|
+
catch (error) {
|
|
1088
|
+
if (error.code !== 'BATCH_LOCK_BUSY' || Date.now() >= until) throw error;
|
|
1089
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
return runWithOwnedRepositoryLock(folder, release, action);
|
|
1093
|
+
}
|
|
1094
|
+
|
|
1095
|
+
export async function withRepositoryRunLockAsync(repoState, action) {
|
|
1096
|
+
const folder = repositoryRunLockFolder(repoState);
|
|
1097
|
+
const until = Date.now() + 2000;
|
|
1098
|
+
let release;
|
|
1099
|
+
for (;;) {
|
|
1100
|
+
try { release = acquireNativeBatchLock(folder); break; }
|
|
1101
|
+
catch (error) {
|
|
1102
|
+
if (error.code !== 'BATCH_LOCK_BUSY' || Date.now() >= until) throw error;
|
|
1103
|
+
await new Promise(resolve => setTimeout(resolve, 10));
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
return runWithOwnedRepositoryLock(folder, release, action);
|
|
1107
|
+
}
|
|
1108
|
+
|
|
846
1109
|
async function ownBatch(context, name) {
|
|
847
1110
|
if (context.releaseBatch) return;
|
|
848
1111
|
try {
|
|
@@ -856,6 +1119,8 @@ async function ownBatch(context, name) {
|
|
|
856
1119
|
}
|
|
857
1120
|
}
|
|
858
1121
|
|
|
1122
|
+
// Direct invocation stores and diagnostics share credentials across sign-ins.
|
|
1123
|
+
const typedInvocationSecrets = new WeakMap();
|
|
859
1124
|
function recordSecret(ports, ...values) {
|
|
860
1125
|
const remember = ports?.redaction?.remember;
|
|
861
1126
|
if (remember) remember(...values);
|
|
@@ -870,7 +1135,7 @@ function signIn(gh, store, ports, { forceRefresh = false, afterHttp401 = false,
|
|
|
870
1135
|
const value = token.status === 0 ? String(token.stdout ?? '').trim() : '';
|
|
871
1136
|
if (!value) throw new Stop(exitCode, 'Run gh auth login');
|
|
872
1137
|
recordSecret(ports, value);
|
|
873
|
-
if (store) store.secrets = [...new Set([...(store.secrets ?? []), value])];
|
|
1138
|
+
if (store) store.secrets = typedInvocationSecrets.get(ports?.rememberSecrets) ?? [...new Set([...(store.secrets ?? []), value])];
|
|
874
1139
|
const tokenSha256 = sha256(Buffer.from(value, 'utf8'));
|
|
875
1140
|
const cached = store ? store.readGithubUser() : null;
|
|
876
1141
|
const matchingCached = cached && cached.token_sha256 === tokenSha256 ? cached : null;
|
|
@@ -917,15 +1182,21 @@ function lostReply(error, origin) {
|
|
|
917
1182
|
return { lost: true, why: code ? `connection failed: ${code}` : error?.name === 'AbortError' ? 'no answer in time' : null };
|
|
918
1183
|
}
|
|
919
1184
|
const AUTH_TEXT = 'The PDD interpreter did not accept your GitHub login (HTTP 401). Run gh auth login, then run the command again.';
|
|
1185
|
+
const isPreExecutionRefusal = reply => reply.status >= 400 && reply.status < 500 && reply.status !== 408;
|
|
1186
|
+
const unadmittedTryErrors = new WeakSet();
|
|
1187
|
+
const unadmittedScreenErrors = new WeakSet();
|
|
1188
|
+
const unadmittedCallErrors = new WeakMap();
|
|
920
1189
|
|
|
921
1190
|
// HTTP to the runtime. The token stays in this object and in request headers only.
|
|
922
1191
|
class Runtime {
|
|
923
|
-
constructor({ origin, token, ports, signal, auth }) { Object.assign(this, { origin, token, ports, signal, auth }); this.sources = new WeakMap(); }
|
|
1192
|
+
constructor({ origin, token, ports, signal, auth, programJson = false }) { Object.assign(this, { origin, token, ports, signal, auth, programJson }); this.sources = new WeakMap(); }
|
|
924
1193
|
async sendOnce(path, init, ms) {
|
|
925
|
-
|
|
1194
|
+
const readSignal = init?.method === 'GET' ? init.signal : null;
|
|
1195
|
+
if (this.signal?.aborted || readSignal?.aborted) return { lost: true };
|
|
926
1196
|
const controller = new AbortController(), stop = () => controller.abort();
|
|
927
1197
|
const timer = setTimeout(stop, ms);
|
|
928
1198
|
this.signal?.addEventListener('abort', stop, { once: true });
|
|
1199
|
+
readSignal?.addEventListener('abort', stop, { once: true });
|
|
929
1200
|
const bearer = this.auth?.identity.token ?? this.token;
|
|
930
1201
|
const resolved = typeof init?.body === 'function' ? { ...init, body: init.body() } : init;
|
|
931
1202
|
try {
|
|
@@ -933,9 +1204,9 @@ class Runtime {
|
|
|
933
1204
|
headers: { ...resolved?.headers, Authorization: `Bearer ${bearer}` } });
|
|
934
1205
|
const text = await response.text();
|
|
935
1206
|
let json = null;
|
|
936
|
-
try { json = JSON.parse(text); } catch { json = null; }
|
|
1207
|
+
try { json = this.programJson ? parseProgramJson(text) : JSON.parse(text); } catch { json = null; }
|
|
937
1208
|
return { status: response.status, headers: response.headers, text, json };
|
|
938
|
-
} catch (error) { return lostReply(error, this.origin); } finally { clearTimeout(timer); this.signal?.removeEventListener('abort', stop); }
|
|
1209
|
+
} catch (error) { return lostReply(error, this.origin); } finally { clearTimeout(timer); this.signal?.removeEventListener('abort', stop); readSignal?.removeEventListener('abort', stop); }
|
|
939
1210
|
}
|
|
940
1211
|
async send(path, init, ms) {
|
|
941
1212
|
const previousToken = this.auth?.identity.token ?? this.token;
|
|
@@ -955,14 +1226,26 @@ class Runtime {
|
|
|
955
1226
|
});
|
|
956
1227
|
} catch (error) {
|
|
957
1228
|
if (error instanceof Stop) { this.auth.store?.deleteGithubUser(); return first; }
|
|
1229
|
+
// The initial 401 refused execution, and refresh failed before a retry.
|
|
1230
|
+
if (init?.method === 'POST' && (path === '/v1/try' || /^\/v1\/try\/[^/]+\/call$/.test(path) || /\/screen\/api\/(act|app\/open)$/.test(path))) {
|
|
1231
|
+
if (error === null || !['object', 'function'].includes(typeof error)) error = new Error(String(error));
|
|
1232
|
+
if (path === '/v1/try') unadmittedTryErrors.add(error);
|
|
1233
|
+
if (/\/screen\/api\/(act|app\/open)$/.test(path)) unadmittedScreenErrors.add(error);
|
|
1234
|
+
if (/^\/v1\/try\/[^/]+\/call$/.test(path)) unadmittedCallErrors.set(this, error);
|
|
1235
|
+
}
|
|
958
1236
|
throw error;
|
|
959
1237
|
}
|
|
960
1238
|
Object.assign(this.auth.identity, refreshed, { fromCache: false, refreshedAfter401: true });
|
|
961
1239
|
this.token = refreshed.token;
|
|
962
1240
|
if (Array.isArray(this.auth.secrets) && !this.auth.secrets.includes(refreshed.token)) this.auth.secrets.push(refreshed.token);
|
|
963
|
-
this.auth.onRefresh?.(this.auth.identity);
|
|
1241
|
+
await this.auth.onRefresh?.(this.auth.identity);
|
|
964
1242
|
const expectedOwner = typeof this.auth.expectedOwnerLogin === 'function' ? this.auth.expectedOwnerLogin() : this.auth.expectedOwnerLogin;
|
|
965
|
-
if (expectedOwner && refreshed.login !== expectedOwner)
|
|
1243
|
+
if (expectedOwner && refreshed.login !== expectedOwner) {
|
|
1244
|
+
const error = this.auth.ownerMismatchError(expectedOwner);
|
|
1245
|
+
if (path === '/v1/try' && init?.method === 'POST') unadmittedTryErrors.add(error);
|
|
1246
|
+
if (init?.method === 'POST' && /\/screen\/api\/(act|app\/open)$/.test(path)) unadmittedScreenErrors.add(error);
|
|
1247
|
+
throw error;
|
|
1248
|
+
}
|
|
966
1249
|
if (this.auth.verifiedByServer && refreshed.token === previousToken) {
|
|
967
1250
|
this.auth.store?.deleteGithubUser();
|
|
968
1251
|
return first;
|
|
@@ -1009,6 +1292,8 @@ function blockingAnswer(reply) {
|
|
|
1009
1292
|
}
|
|
1010
1293
|
|
|
1011
1294
|
const sameJob = (json, id, command) => isObject(json) && json.requestId === id && json.id === id && json.command === command && JOB_STATES.has(json.state);
|
|
1295
|
+
const sameTryReceipt = (json, id) => sameJob(json, id, 'try')
|
|
1296
|
+
&& (!Object.hasOwn(json.result?.session ?? {}, 'id') || json.result.session.id === id);
|
|
1012
1297
|
const gateText = reply => reply.status === 503 && !reply.json && String(reply.text ?? '').includes('The runtime opens soon.');
|
|
1013
1298
|
|
|
1014
1299
|
// The free interpreter health check for Autopilot: one GET /v1/capacity with the gh token, the same read that admission
|
|
@@ -1172,14 +1457,15 @@ function capacityHistorySafe(context, row) {
|
|
|
1172
1457
|
function structuredRestartOrigin(context, row) {
|
|
1173
1458
|
const fuse = claimPath(context, row).replace(/\.0\.dispatch\.json$/, '.restart.json');
|
|
1174
1459
|
if (row.restart_used !== true || !statOrNull(fuse)) return null;
|
|
1460
|
+
const transient = context.store.read(fuse)?.transient === true;
|
|
1175
1461
|
const origins = (row.request_ids ?? []).filter(id => {
|
|
1176
1462
|
const latest = context.store.read(join(context.folder, `${id}.json`));
|
|
1177
1463
|
const prior = context.store.read(join(context.folder, `${id}.observations.json`));
|
|
1178
1464
|
const history = [...(Array.isArray(prior) ? prior : []), ...(latest ? [latest] : [])]
|
|
1179
1465
|
.filter((item, index, list) => list.findIndex(other => isDeepStrictEqual(other, item)) === index);
|
|
1180
1466
|
const terminal = history.filter(answer => accountingEnd(answer, id));
|
|
1181
|
-
return history.length > 0 && history.every(answer => sameJob(answer, id, 'check'))
|
|
1182
|
-
&& terminal.length > 0 && terminal.every(restarted);
|
|
1467
|
+
return history.length > 0 && history.every(answer => sameJob(answer, id, 'check') && (!transient || transientDrop(answer, false)))
|
|
1468
|
+
&& terminal.length > 0 && terminal.every(answer => restarted(answer) || transient && transientDrop(answer));
|
|
1183
1469
|
});
|
|
1184
1470
|
return origins.length === 1 ? origins[0] : null;
|
|
1185
1471
|
}
|
|
@@ -1314,6 +1600,65 @@ function markBusy(context, row, wait, observedAt = context.ports.now(), legacy =
|
|
|
1314
1600
|
}
|
|
1315
1601
|
|
|
1316
1602
|
const restarted = answer => answer?.command === 'check' && answer.state === 'unknown' && [answer.result?.report?.refusal, ...(Array.isArray(answer.result?.refusals) ? answer.result.refusals : [])].some(item => item?.code === 'service-restarted');
|
|
1603
|
+
// Follow interpreter metadata surfaces, never arbitrary application values.
|
|
1604
|
+
function transientDrop(answer, terminal = true) {
|
|
1605
|
+
if (terminal && !['unknown', 'refused'].includes(answer?.state)) return false;
|
|
1606
|
+
if (stepTimeLimit(answer)) return false;
|
|
1607
|
+
const allowed = new Set(['no-server-verdict', 'graph-provider-failure']), reasons = [];
|
|
1608
|
+
let forbidden = false;
|
|
1609
|
+
const visit = (value, refusal = false) => {
|
|
1610
|
+
if (!value || typeof value !== 'object') return;
|
|
1611
|
+
if (failedCheckCount(value) > 0 || value.passed === false || value.status === 'failed' || value.state === 'failed'
|
|
1612
|
+
|| value.verdict === 'failed' || value.verdict === 'fail' || value.retryable === false
|
|
1613
|
+
|| typeof value.failed === 'number' && value.failed > 0) forbidden = true;
|
|
1614
|
+
if (refusal && typeof value.code === 'string') reasons.push(value.code);
|
|
1615
|
+
if (value.failed_checks !== undefined && (!Array.isArray(value.failed_checks) || value.failed_checks.length)) forbidden = true;
|
|
1616
|
+
if (value.resource_mode !== undefined && value.resource_mode !== 'simulated') forbidden = true;
|
|
1617
|
+
for (const key of ['report', 'checks', 'criterion_results', 'criteria', 'samples', 'steps', 'capabilities', 'lint', 'tests', 'resources', 'operations', 'edges', 'evaluation']) {
|
|
1618
|
+
const child = value[key];
|
|
1619
|
+
if (Array.isArray(child)) for (const item of child) visit(item);
|
|
1620
|
+
else if (child && typeof child === 'object') visit(child);
|
|
1621
|
+
}
|
|
1622
|
+
for (const key of ['refusals', 'refusal', 'reason', 'note', 'error']) {
|
|
1623
|
+
const child = value[key];
|
|
1624
|
+
if (Array.isArray(child)) for (const item of child) visit(item, true);
|
|
1625
|
+
else if (child && typeof child === 'object') visit(child, true);
|
|
1626
|
+
}
|
|
1627
|
+
// Refusal details can carry structured nested causes and retryability.
|
|
1628
|
+
// Domain payloads (input/result/expected/actual) stay outside this traversal.
|
|
1629
|
+
if (refusal) { visit(value.details, true); visit(value.failure_cause, true); }
|
|
1630
|
+
};
|
|
1631
|
+
visit(answer); visit(answer?.result);
|
|
1632
|
+
return !forbidden && (!terminal || reasons.length > 0) && reasons.every(code => allowed.has(code));
|
|
1633
|
+
}
|
|
1634
|
+
function transientHistory(context, row) {
|
|
1635
|
+
return row.request_ids.every(id => {
|
|
1636
|
+
if (attemptConfirmedZeroCapacity(context, id)) return true;
|
|
1637
|
+
const latest = context.store.read(join(context.folder, `${id}.json`));
|
|
1638
|
+
const history = context.store.read(join(context.folder, `${id}.observations.json`));
|
|
1639
|
+
return latest && (history == null || Array.isArray(history)) && [...(Array.isArray(history) ? history : []), latest]
|
|
1640
|
+
.every(answer => sameJob(answer, id, 'check') && transientDrop(answer, false));
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
function deterministicStory(context, row) {
|
|
1644
|
+
const story = row.story_path, footprint = context.capture.stories?.find(item => item.story_path === story);
|
|
1645
|
+
const tests = context.rows.filter(item => item.story_path === story).map(item => item.test);
|
|
1646
|
+
if (!footprint || footprint.unavailable || !Array.isArray(footprint.files) || !tests.length) return false;
|
|
1647
|
+
const sources = new Map((context.capture.sources ?? []).map(file => [file.path, file.bytes]));
|
|
1648
|
+
for (const file of footprint.files.filter(file => file.path.endsWith('.prompt.md'))) {
|
|
1649
|
+
const bytes = sources.get(file.path);
|
|
1650
|
+
if (!bytes) return false;
|
|
1651
|
+
// Initial lazy-interface admission does not prove which resources a replay could use.
|
|
1652
|
+
try { if (!interfaceBlocks(Buffer.from(bytes).toString('utf8')).length) return false; }
|
|
1653
|
+
catch { return false; }
|
|
1654
|
+
}
|
|
1655
|
+
for (const path of tests) {
|
|
1656
|
+
let doc; try { doc = JSON.parse(Buffer.from(sources.get(path)).toString('utf8')); } catch { return false; }
|
|
1657
|
+
if (doc.resource_mode !== undefined && doc.resource_mode !== 'simulated'
|
|
1658
|
+
|| (doc.steps ?? []).some(step => step.resource_mode !== undefined && step.resource_mode !== 'simulated')) return false;
|
|
1659
|
+
}
|
|
1660
|
+
return declarationCacheReason(context.capture, story, tests) === null;
|
|
1661
|
+
}
|
|
1317
1662
|
const confirmedEnd = answer => ['passed', 'failed', 'refused', 'not_run'].includes(answer?.state) || restarted(answer);
|
|
1318
1663
|
const accountingEnd = (answer, id) => sameJob(answer, id, 'check')
|
|
1319
1664
|
&& (confirmedEnd(answer) || answer.state === 'unknown');
|
|
@@ -1477,7 +1822,8 @@ async function probeLazyInterfaces(context, origin, store) {
|
|
|
1477
1822
|
let identity;
|
|
1478
1823
|
try { identity = signIn(context.ports.gh, store, context.ports, { exitCode: context.doorMode ? 125 : 5 }); }
|
|
1479
1824
|
catch (error) { if (error instanceof Stop) return false; throw error; }
|
|
1480
|
-
|
|
1825
|
+
if(context.liveLocal)context.localOwner??=identity.login;
|
|
1826
|
+
const auth = authSession({ identity, store, ports: context.ports, signInExitCode: context.doorMode ? 125 : 5, ...(context.liveLocal?{expectedOwnerLogin:context.localOwner,ownerMismatchError:()=>new Stop(5,'live-local-owner-changed')}:{}) });
|
|
1481
1827
|
const probe = { origin, identity, ports: context.ports, signal: context.signal, interrupted: context.interrupted, auth };
|
|
1482
1828
|
const reply = await readCapacity(probe, context.ports.now() + GET_MS, false);
|
|
1483
1829
|
if (reply?.status !== 200 || !Array.isArray(reply.json?.features)) return false;
|
|
@@ -1653,7 +1999,21 @@ function select(found, words, root, ports) {
|
|
|
1653
1999
|
return selected;
|
|
1654
2000
|
}
|
|
1655
2001
|
|
|
1656
|
-
|
|
2002
|
+
function derivationProblems(root, found, selected) {
|
|
2003
|
+
const reader = sourceFilePort(root, found.visible, found.workspace);
|
|
2004
|
+
return selected.flatMap(test => {
|
|
2005
|
+
if (test.error) return [];
|
|
2006
|
+
let doc;
|
|
2007
|
+
try {
|
|
2008
|
+
const text = reader.read({path:test.path}).content;
|
|
2009
|
+
doc = parseScenarioJson(expandSource({path:test.path,text,format:'scenario'}, reader).text);
|
|
2010
|
+
} catch { return []; } // Existing source and shape admission own unrelated failures.
|
|
2011
|
+
const problem = scenarioDerivationRefusal(doc);
|
|
2012
|
+
return problem ? [{code:problem.code,path:test.path,section:problem.section,message:`${test.path} ${problem.section}: ${problem.message}`}] : [];
|
|
2013
|
+
});
|
|
2014
|
+
}
|
|
2015
|
+
|
|
2016
|
+
const localRows = rows => rows.map(row => ({ ...row, ...(row.refusals.length ? {unsent:true,steps:jsonSafe(row.steps)} : {}), state: row.refusals.length ? 'refused' : row.native_only?.length ? 'not_run' : 'ready', phase: row.refusals.length || row.native_only?.length ? 'local' : 'server',
|
|
1657
2017
|
...(row.native_only?.length ? {unsent:true,note:{code:'native-only',message:row.native_only.map(item => `${item.path}: ${item.reason}`).join('; ')}} : {}),
|
|
1658
2018
|
refusals:row.refusals.map(item=>({...item,hint:item.hint??'Fix the named test or prompt rule, then run the selection again.'})),
|
|
1659
2019
|
request_ids: [], calls: 0, report_url: null, checks: null, failed_checks: [], all_checks: [] }));
|
|
@@ -1670,14 +2030,15 @@ function capturedCriteria(rows, capture) {
|
|
|
1670
2030
|
for (const row of rows.filter(row=>!row.unsent)) {
|
|
1671
2031
|
const source = capture.sources?.find(source=>source.path===row.test);
|
|
1672
2032
|
if (!source) continue;
|
|
1673
|
-
let doc; try { doc=
|
|
2033
|
+
let doc; try { doc=parseScenarioJson(Buffer.from(source.bytes).toString('utf8')); } catch { /* Refuse captured invalid bytes below. */ }
|
|
1674
2034
|
const shape=scenarioShapeRefusal(doc,row.test);
|
|
1675
2035
|
if (shape) {
|
|
1676
|
-
const
|
|
1677
|
-
|
|
2036
|
+
const derivation = shape.code.startsWith('scenario-derivation-');
|
|
2037
|
+
const error=Object.assign(new PreflightError(4,`${row.test}${derivation ? ` ${shape.section}` : ''}: ${shape.message}`),
|
|
2038
|
+
{code:shape.code,...(derivation ? {section:shape.section} : {}),hint:'Fix the named test JSON, schema version, criteria and steps, then run the selection again.'});
|
|
1678
2039
|
refuseSource(row,error);broken=true;continue;
|
|
1679
2040
|
}
|
|
1680
|
-
row.steps=doc.steps;
|
|
2041
|
+
row.steps=jsonSafe(doc.steps);
|
|
1681
2042
|
row.app_maps=declaredMaps(doc);
|
|
1682
2043
|
row.criteria_total=doc.criteria.length;
|
|
1683
2044
|
row.criterion_texts=Object.fromEntries(doc.criteria.filter(isObject).map(item=>[item.id,item.text]));
|
|
@@ -1694,7 +2055,7 @@ function capturedCriteria(rows, capture) {
|
|
|
1694
2055
|
const sourceUnavailable = error => !error.selection && (error instanceof PreflightError && error.exitCode === 4 || ['EACCES','EPERM','EISDIR'].includes(error.code));
|
|
1695
2056
|
function refuseSource(row, error) {
|
|
1696
2057
|
if (error.not_checked?.length) Object.assign(row, {not_checked:error.not_checked,criteria_total:error.criteria_total});
|
|
1697
|
-
Object.assign(row, {state:'refused',phase:'local',unsent:true,calls:0,refusals:[{code:error.code ?? 'source-unavailable',
|
|
2058
|
+
Object.assign(row, {state:'refused',phase:'local',unsent:true,calls:0,steps:jsonSafe(row.steps),refusals:[{code:error.code ?? 'source-unavailable',
|
|
1698
2059
|
section:error.section ?? 'source',message:error.message,hint:error.hint ?? 'Restore the named dependency, make it readable, or correct its declared path.'}]});
|
|
1699
2060
|
}
|
|
1700
2061
|
function captureIndependent(root, rows, ports, options) {
|
|
@@ -1746,7 +2107,7 @@ function recoverSourceContext(context) {
|
|
|
1746
2107
|
if (context.sourceRecoveryAttempted) return false;
|
|
1747
2108
|
context.sourceRecoveryAttempted = true;
|
|
1748
2109
|
try {
|
|
1749
|
-
const capture = context.ports.captureSource(context.root, { tests: sentTests(context.rows), appMap: null, excludeFixtureProjects: context.excludeFixtureProjects, ...(context.allowMissingInterfaces ? { allowMissingInterfaces: true } : {}) });
|
|
2110
|
+
const capture = context.ports.captureSource(context.root, { tests: sentTests(context.rows), appMap: null, excludeFixtureProjects: context.excludeFixtureProjects, ...(context.stepIds?.length ? {stepIds:context.stepIds} : {}), ...(context.allowMissingInterfaces ? { allowMissingInterfaces: true } : {}) });
|
|
1750
2111
|
if (capture.sha256 !== context.capture.sha256) { context.sourceRecoveryMismatch = true; return false; }
|
|
1751
2112
|
capture.stories = context.capture.stories;
|
|
1752
2113
|
context.capture = capture;
|
|
@@ -1909,6 +2270,8 @@ function applyAnswer(row, answer, context, observedWait = null, observedAt = con
|
|
|
1909
2270
|
const advice = noVerdictAdvice(answer, view);
|
|
1910
2271
|
const firstDiagnosis = view.failed_checks.find(check => check.diagnosis) ?? null, failed = view.state === 'failed';
|
|
1911
2272
|
Object.assign(row, { state: view.state, checks: view.checks, criteria: view.criteria, failed_checks: view.failed_checks, all_checks: view.all_checks,
|
|
2273
|
+
...(Object.hasOwn(view, 'field_agreement') ? { field_agreement: view.field_agreement } : {}),
|
|
2274
|
+
...(view.sample_divergence ? { sample_divergence: view.sample_divergence } : {}),
|
|
1912
2275
|
refusals: view.refusals.map((item, index) => interfaceDiagnostic(item,
|
|
1913
2276
|
(answer?.result?.refusals ?? [answer?.result?.report?.refusal])[index], context.root, context.secrets)), calls: view.calls,
|
|
1914
2277
|
input_tokens: view.input_tokens, cached_input_tokens: view.cached_input_tokens, output_tokens: view.output_tokens, cached_input_share: view.cached_input_share,
|
|
@@ -1974,11 +2337,11 @@ function localLayoutResult(batch, summary) {
|
|
|
1974
2337
|
|
|
1975
2338
|
function printLocalLayout(context, result) {
|
|
1976
2339
|
if (result.exit_code === 2) line(context.ports.stderr,'Could not save local lint result. Run a fresh pdd lint --local after fixing the state folder.');
|
|
1977
|
-
line(context.ports.stdout, context.json ? JSON.stringify(result) : [...result.problems.map(item => `${item.code}: ${item.message}`), ...result.warnings, result.summary_line].join('\n'));
|
|
2340
|
+
line(context.ports.stdout, context.json ? JSON.stringify(result) : [...result.problems.map(item => `${item.code}: ${item.message}`), ...result.warnings, ...(context.selectorTableLines ?? []), result.summary_line].join('\n'));
|
|
1978
2341
|
return result.exit_code;
|
|
1979
2342
|
}
|
|
1980
2343
|
|
|
1981
|
-
function saveLocalLayout(context, {root, tests, prompts, warnings, problems, summary}) {
|
|
2344
|
+
async function saveLocalLayout(context, {root, tests, prompts, warnings, problems, summary}) {
|
|
1982
2345
|
const store = stateFor(context.ports.env,root), now = context.ports.now(), batch = batchId(now,context.ports.randomUUID);
|
|
1983
2346
|
try {
|
|
1984
2347
|
const record = {version:1,batch,root,created_at:new Date(now).toISOString(),intent:'lint-only',local_only:true,source_sha256:null,
|
|
@@ -1991,14 +2354,14 @@ function saveLocalLayout(context, {root, tests, prompts, warnings, problems, sum
|
|
|
1991
2354
|
// Exclusive creation keeps every previous batch intact even if the ordinary ID collides.
|
|
1992
2355
|
mkdirSync(folder,{mode:0o700});
|
|
1993
2356
|
store.write(join(folder,'batch.json'),record);
|
|
1994
|
-
store.
|
|
2357
|
+
await store.updateRepo(root, current => ({...current,last_batch:batch}));
|
|
1995
2358
|
store.write(join(folder,'summary.json'),result);
|
|
1996
2359
|
return result;
|
|
1997
2360
|
} catch (error) { throw new Stop(2,`Could not save local lint result in PDD_STATE_DIR: ${error.message}`); }
|
|
1998
2361
|
}
|
|
1999
2362
|
|
|
2000
2363
|
// Local omissions are evidence too; recording them needs no owner token or job.
|
|
2001
|
-
function saveLocalNativeResult(context, rows, intent, problems = []) {
|
|
2364
|
+
async function saveLocalNativeResult(context, rows, intent, problems = []) {
|
|
2002
2365
|
const startedAt = context.ports.now(), batch = batchId(startedAt, context.ports.randomUUID);
|
|
2003
2366
|
for (const row of rows) row.unsent = true;
|
|
2004
2367
|
context.sourceSelection = {tests:[],exclude_fixture_projects:context.excludeFixtureProjects === true};
|
|
@@ -2007,15 +2370,17 @@ function saveLocalNativeResult(context, rows, intent, problems = []) {
|
|
|
2007
2370
|
Object.assign(context,{localOnly:true,startedAt,batch,intent,capture,rows,identity:{login:null,userId:null},lint:{state:'not_run',request_ids:[],...(problems.length ? {problems} : {})}});
|
|
2008
2371
|
context.folder = context.store.folder('batches',batch);
|
|
2009
2372
|
saveBatch(context);
|
|
2010
|
-
context.store.
|
|
2373
|
+
await context.store.updateRepo(context.root, current => ({...current,last_batch:batch}));
|
|
2011
2374
|
}
|
|
2012
2375
|
|
|
2013
2376
|
function batchRecord(context) {
|
|
2014
2377
|
const { batch, origin, root, identity, capture, rows, lint, warnings } = context;
|
|
2015
2378
|
const maintenance = activeMaintenance(context);
|
|
2016
|
-
return { version: 1, batch, origin, root, ...(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,
|
|
2379
|
+
return { version: 1, batch, origin, root, ...(context.stepIds?.length ? {diagnostic:true,diagnostic_subset:true,selected_steps:rows.flatMap(row=>row.selected_steps ?? [])} : {}), ...(maintenance ? { maintenance, retry_after: maintenance.retry_after } : {}), check_plan: context.checkPlan ?? null, ...(context.checkSelection ? {check_selection:context.checkSelection,baseline_report:context.baselineReport} : {}), head: context.head, login: identity.login, user_id: identity.userId,
|
|
2380
|
+
...(context.liveLocal || context.liveLocalSaved ? {live_local:true} : {}),
|
|
2017
2381
|
source_sha256: capture.sha256, files: capture.files.map(file => file.path), bytes: capture.bytes, timeout_min: context.timeoutMin,
|
|
2018
2382
|
...(context.singleAttempt ? {single_attempt:true} : {}), ...(context.maxTotalCalls != null ? {max_total_calls:context.maxTotalCalls} : {}),
|
|
2383
|
+
...(context.checkOptions ? {check_options:context.checkOptions} : {}),
|
|
2019
2384
|
source_selection: context.sourceSelection ?? {tests:sentTests(rows),exclude_fixture_projects:context.excludeFixtureProjects === true},
|
|
2020
2385
|
native_source: context.nativeSource ?? null,
|
|
2021
2386
|
...(context.localOnly ? {local_only:true} : {}),
|
|
@@ -2025,6 +2390,9 @@ function batchRecord(context) {
|
|
|
2025
2390
|
contract_snapshots: capture.stories,
|
|
2026
2391
|
test_cache: context.testCache ? { tokens: [...context.testCache.tokens] } : context.savedTestCache,
|
|
2027
2392
|
rows: rows.map(row => ({ test: row.test, ...(row.app_maps?.length ? { app_maps: row.app_maps } : {}), native_only: row.native_only ?? [], story: row.story, story_path: row.story_path, title: row.title, request_ids: row.request_ids, recovery_state: row.state, ...resultOutcome(row),
|
|
2393
|
+
...(Object.hasOwn(row, 'field_agreement') ? {field_agreement:row.field_agreement} : {}),
|
|
2394
|
+
...(row.sample_divergence ? {sample_divergence:row.sample_divergence} : {}),
|
|
2395
|
+
...(row.diagnostic || row.diagnostic_subset === true ? { ...(row.diagnostic ? {diagnostic:true} : {}), diagnostic_subset:true, selected_steps:row.selected_steps ?? [] } : {}),
|
|
2028
2396
|
...(!row.request_ids.length && Object.hasOwn(row, 'calls') ? { calls: row.calls } : {}),
|
|
2029
2397
|
...(row.unsent ? { unsent: true } : {}), ...(row.not_checked?.length ? {not_checked:row.not_checked} : {}), progress: row.progress, ahead: row.ahead, phase: row.phase, post_verdict: row.post_verdict ?? null, binding_plan: row.binding_plan, compatibility: row.compatibility, client_advice: row.client_advice, report_url: row.report_url, refusals: row.refusals, note: row.note ?? null, why: row.why ?? null, next_step: row.next_step ?? null,
|
|
2030
2398
|
sent_at: row.sent_at ?? null, ended_at: row.ended_at ?? null, max_calls: row.max_calls, warnings: row.warnings, steps: row.steps, criteria_total: row.criteria_total,
|
|
@@ -2044,6 +2412,31 @@ function claimPath(context, row, attempt = 0) {
|
|
|
2044
2412
|
const key = createHash('sha256').update(row.test).digest('hex');
|
|
2045
2413
|
return join(context.folder, `${key}.${attempt}.dispatch.json`);
|
|
2046
2414
|
}
|
|
2415
|
+
function unsentReplacementClaim(context, path, claim) {
|
|
2416
|
+
const proof = context.store.read(`${path}.unsent.json`);
|
|
2417
|
+
return claim?.restart === true && proof?.not_sent === true && typeof proof.prior_restart_used === 'boolean'
|
|
2418
|
+
&& isDeepStrictEqual(proof.claim, claim) && !statOrNull(join(context.folder, `${claim.id}.posted`)) ? proof : null;
|
|
2419
|
+
}
|
|
2420
|
+
function preserveUnsentReplacement(context, row, path) {
|
|
2421
|
+
if (!row.prior_restart_snapshot) return false;
|
|
2422
|
+
const claim = context.store.read(path);
|
|
2423
|
+
if (!claim?.restart || !isDeepStrictEqual(context.preparingDispatches?.get(row), claim)
|
|
2424
|
+
|| statOrNull(join(context.folder, `${claim.id}.posted`))) return false;
|
|
2425
|
+
// Only the owner reaching a definitely-unsent boundary writes this positive
|
|
2426
|
+
// evidence. Missing receipts or markers never authorize this conclusion.
|
|
2427
|
+
const fd = openSync(`${path}.unsent.json`, 'wx', 0o600);
|
|
2428
|
+
try {
|
|
2429
|
+
writeSync(fd, JSON.stringify({ not_sent: true, claim, prior_restart_used: !!row.prior_restart_snapshot.restart_used }));
|
|
2430
|
+
fsyncSync(fd);
|
|
2431
|
+
} finally { closeSync(fd); }
|
|
2432
|
+
return true;
|
|
2433
|
+
}
|
|
2434
|
+
function restoreReplacement(row) {
|
|
2435
|
+
const snapshot = row.prior_restart_snapshot;
|
|
2436
|
+
if (!snapshot) return;
|
|
2437
|
+
for (const key of Object.keys(row)) delete row[key];
|
|
2438
|
+
Object.assign(row, snapshot);
|
|
2439
|
+
}
|
|
2047
2440
|
function adoptClaims(context, row) {
|
|
2048
2441
|
if (statOrNull(claimPath(context, row).replace(/\.0\.dispatch\.json$/, '.restart.json'))) row.restart_used = true;
|
|
2049
2442
|
for (let attempt = 0; ; attempt++) {
|
|
@@ -2058,6 +2451,15 @@ function adoptClaims(context, row) {
|
|
|
2058
2451
|
row.dispatchIncomplete = true;
|
|
2059
2452
|
break;
|
|
2060
2453
|
}
|
|
2454
|
+
// A live local sender still owns this exact prepared claim while native
|
|
2455
|
+
// registration waits. Only posted or no-longer-owned claims enter recovery.
|
|
2456
|
+
if (isDeepStrictEqual(context.preparingDispatches?.get(row), claim) && !statOrNull(join(context.folder, `${claim.id}.posted`))) continue;
|
|
2457
|
+
const unsent = unsentReplacementClaim(context, path, claim);
|
|
2458
|
+
if (unsent) {
|
|
2459
|
+
row.request_ids = row.request_ids.filter(id => id !== claim.id);
|
|
2460
|
+
row.restart_used = unsent.prior_restart_used;
|
|
2461
|
+
continue;
|
|
2462
|
+
}
|
|
2061
2463
|
if (claim.restart) row.restart_used = true;
|
|
2062
2464
|
if (Number.isSafeInteger(claim.max_calls) && claim.max_calls >= 1) (row.claim_max_calls ??= {})[claim.id] = claim.max_calls;
|
|
2063
2465
|
if (claim.reservation && !row.admitting) row.reservation = claim.reservation;
|
|
@@ -2184,13 +2586,15 @@ function budgetRowsForContext(context, excludePendingRow = null) {
|
|
|
2184
2586
|
}
|
|
2185
2587
|
function applyBudgetDecisionStop(context, row, decision) {
|
|
2186
2588
|
if (row.restart_pending || decision.retain_prior_uncertainty) {
|
|
2187
|
-
|
|
2589
|
+
const transient = row.transient_pending;
|
|
2590
|
+
restoreReplacement(row);
|
|
2188
2591
|
row.restart_pending = false;
|
|
2592
|
+
const label = transient ? 'simulated check retry' : 'restart replacement';
|
|
2189
2593
|
const msg = decision.reason_code === 'restart-replacement-disabled'
|
|
2190
|
-
?
|
|
2594
|
+
? `No ${label} was sent: restart replacement is disabled for this batch.`
|
|
2191
2595
|
: decision.reason_code === 'restart-limit-reached'
|
|
2192
|
-
?
|
|
2193
|
-
: `No
|
|
2596
|
+
? `No ${label} was sent: the 1-replacement limit per test was already used.`
|
|
2597
|
+
: `No ${label} was sent: --max-total-calls ${context.maxTotalCalls} has 0 remaining calls after prior usage and unresolved reservations.`;
|
|
2194
2598
|
row.note = { code: decision.reason_code, message: msg };
|
|
2195
2599
|
const warnKey = `${row.test}:${decision.reason_code}`;
|
|
2196
2600
|
context.budgetNotices ??= new Set();
|
|
@@ -2247,6 +2651,7 @@ async function postJob(context, path, command, request, row, timeoutMs, deadline
|
|
|
2247
2651
|
if (registered === false) { await finishReservation(context, target, { state: 'not_run' }); return { kind: 'not_sent' }; }
|
|
2248
2652
|
if (context.interrupted || context.stopped || context.sendError || context.ports.now() >= deadline) { await finishReservation(context, target, { state: 'not_run' }); return { kind: 'not_sent' }; }
|
|
2249
2653
|
context.store.posted(context.folder, id);
|
|
2654
|
+
if (row) delete row.prior_restart_snapshot; // Dispatch is now uncertain; never roll it back.
|
|
2250
2655
|
if (row) { if (!row.request_ids.includes(id)) row.request_ids.push(id); row.sent_at ??= context.ports.now(); row.state = 'sending'; row.phase = 'server'; row.calls = 'unknown'; row.post_verdict = 'uncertain'; }
|
|
2251
2656
|
saveBatch(context);
|
|
2252
2657
|
const reply = await context.runtime.post(path, request, context.capture.tar, Math.max(1, Math.min(timeoutMs, deadline - context.ports.now())));
|
|
@@ -2267,10 +2672,15 @@ async function postJob(context, path, command, request, row, timeoutMs, deadline
|
|
|
2267
2672
|
async function sendCheck(context, row) {
|
|
2268
2673
|
row.admitting = true;
|
|
2269
2674
|
try { await sendCheckAttempt(context, row); }
|
|
2270
|
-
finally {
|
|
2675
|
+
finally {
|
|
2676
|
+
context.preparingDispatches?.delete(row);
|
|
2677
|
+
if (!row.awaiting_budget || context.interrupted || context.ports.now() >= context.deadline) restoreReplacement(row);
|
|
2678
|
+
row.budget_in_flight = 0; row.admitting = false;
|
|
2679
|
+
}
|
|
2271
2680
|
}
|
|
2272
2681
|
async function sendCheckAttempt(context, row) {
|
|
2273
2682
|
if (context.interrupted || context.ports.now() >= context.deadline || !['ready', 'waiting'].includes(row.state)) return;
|
|
2683
|
+
if (context.checkOptions && context.checkOptions.samples > row.max_calls) throw new Stop(2, 'samples exceeds this test’s total max_calls allowance.');
|
|
2274
2684
|
// Recheck the saved raw cohort immediately before any capacity-driven new ID.
|
|
2275
2685
|
// The one structured restart replacement has its own durable fuse and remains allowed.
|
|
2276
2686
|
if (row.request_ids.length && (row.busy || row.capacity_uncertain) && !row.restart_pending && !capacityRetryAllowed(context, row)) {
|
|
@@ -2280,10 +2690,10 @@ async function sendCheckAttempt(context, row) {
|
|
|
2280
2690
|
if (row.busy && row.request_ids.length && !await capacityReady(context, context.deadline, row)) return;
|
|
2281
2691
|
const candidateForRow = () => ({
|
|
2282
2692
|
test: row.test,
|
|
2283
|
-
kind: row.restart_pending ? 'restart-replacement' : 'initial',
|
|
2693
|
+
kind: row.restart_pending && !row.transient_pending ? 'restart-replacement' : 'initial',
|
|
2284
2694
|
requested_max_calls: row.max_calls,
|
|
2285
2695
|
restart_used: !!row.restart_used,
|
|
2286
|
-
prior_reason_code: row.restart_pending ? 'service-restarted' : null
|
|
2696
|
+
prior_reason_code: row.restart_pending && !row.transient_pending ? 'service-restarted' : null
|
|
2287
2697
|
});
|
|
2288
2698
|
const preDecision = evaluateCheckBudget({
|
|
2289
2699
|
max_total_calls: context.maxTotalCalls ?? null,
|
|
@@ -2309,6 +2719,7 @@ async function sendCheckAttempt(context, row) {
|
|
|
2309
2719
|
return;
|
|
2310
2720
|
}
|
|
2311
2721
|
adoptClaims(context, row);
|
|
2722
|
+
if (row.request_ids.length !== attempt) delete row.prior_restart_snapshot;
|
|
2312
2723
|
if (row.request_ids.length !== attempt || !['ready', 'waiting'].includes(row.state) || context.interrupted || context.ports.now() >= context.deadline) {
|
|
2313
2724
|
await finishReservation(context, row, { state: 'not_run' });
|
|
2314
2725
|
if (context.interrupted && row.request_ids.length === attempt && ['ready', 'waiting'].includes(row.state)) Object.assign(row, { state: 'not_run', calls: previousCalls, phase: 'local', note: { code: null, message: 'Stopped before sending.' } });
|
|
@@ -2332,6 +2743,11 @@ async function sendCheckAttempt(context, row) {
|
|
|
2332
2743
|
return;
|
|
2333
2744
|
}
|
|
2334
2745
|
const effectiveMaxCalls = finalDecision.effective_max_calls;
|
|
2746
|
+
if (context.checkOptions && context.checkOptions.samples > effectiveMaxCalls) {
|
|
2747
|
+
await finishReservation(context, row, { state: 'not_run' });
|
|
2748
|
+
Object.assign(row, {state:'not_run',note:{code:'call-budget',message:'Remaining total call allowance is smaller than samples.'}});
|
|
2749
|
+
return;
|
|
2750
|
+
}
|
|
2335
2751
|
row.budget_in_flight = effectiveMaxCalls;
|
|
2336
2752
|
if (row.restart_pending) {
|
|
2337
2753
|
const restartPath = claimPath(context, row).replace(/\.0\.dispatch\.json$/, '.restart.json');
|
|
@@ -2340,11 +2756,15 @@ async function sendCheckAttempt(context, row) {
|
|
|
2340
2756
|
catch (error) {
|
|
2341
2757
|
await finishReservation(context, row, { state: 'not_run' });
|
|
2342
2758
|
if (error.code !== 'EEXIST') throw error;
|
|
2759
|
+
delete row.prior_restart_snapshot;
|
|
2343
2760
|
row.restart_pending = false; adoptClaims(context, row); row.state = 'unknown'; return;
|
|
2344
2761
|
}
|
|
2345
|
-
try { writeSync(claim, JSON.stringify({ used: true })); } finally { closeSync(claim); }
|
|
2762
|
+
try { writeSync(claim, JSON.stringify({ used: true, ...(row.transient_pending ? { transient: true } : {}) })); } finally { closeSync(claim); }
|
|
2346
2763
|
row.restart_used = true; row.restart_pending = false;
|
|
2347
|
-
line(context.ports.stderr,
|
|
2764
|
+
line(context.ports.stderr, row.transient_pending
|
|
2765
|
+
? 'The interpreter gave no verdict for this simulated check. pdd sends it again (1 of 1).'
|
|
2766
|
+
: 'The interpreter restarted during this check. pdd sends it again (1 of 1).');
|
|
2767
|
+
row.transient_pending = false;
|
|
2348
2768
|
}
|
|
2349
2769
|
// Claim the original row and attempt before allocating an ID. Never remove a claim:
|
|
2350
2770
|
// an interruption between claim and POST leaves dispatch uncertain, never replayable.
|
|
@@ -2353,6 +2773,7 @@ async function sendCheckAttempt(context, row) {
|
|
|
2353
2773
|
try { fd = openSync(path, 'wx', 0o600); }
|
|
2354
2774
|
catch (error) {
|
|
2355
2775
|
if (error.code !== 'EEXIST') throw error;
|
|
2776
|
+
delete row.prior_restart_snapshot;
|
|
2356
2777
|
await finishReservation(context, row, { state: 'not_run' });
|
|
2357
2778
|
adoptClaims(context, row);
|
|
2358
2779
|
if (row.dispatchIncomplete) Object.assign(row, { state: 'unknown', phase: 'server', calls: 'unknown', final: true,
|
|
@@ -2361,9 +2782,12 @@ async function sendCheckAttempt(context, row) {
|
|
|
2361
2782
|
}
|
|
2362
2783
|
const id = context.ports.randomUUID();
|
|
2363
2784
|
(row.claim_max_calls ??= {})[id] = effectiveMaxCalls;
|
|
2364
|
-
|
|
2785
|
+
const dispatchClaim = { id, reservation: row.reservation, restart: !!row.restart_used, max_calls: effectiveMaxCalls };
|
|
2786
|
+
try { writeSync(fd, JSON.stringify(dispatchClaim)); }
|
|
2365
2787
|
finally { closeSync(fd); }
|
|
2788
|
+
(context.preparingDispatches ??= new WeakMap()).set(row, dispatchClaim);
|
|
2366
2789
|
if (context.interrupted || context.ports.now() >= context.deadline) {
|
|
2790
|
+
preserveUnsentReplacement(context, row, path);
|
|
2367
2791
|
await finishReservation(context, row, { state: 'not_run' });
|
|
2368
2792
|
adoptClaims(context, row);
|
|
2369
2793
|
if (context.interrupted) row.note = { code: null, message: 'Stopped before sending.' };
|
|
@@ -2377,10 +2801,22 @@ async function sendCheckAttempt(context, row) {
|
|
|
2377
2801
|
row.busy_request_id = null; row.busy_observed_at = null; row.capacity_until = null; row.busy_display = null;
|
|
2378
2802
|
row.phase = 'server';
|
|
2379
2803
|
const request = { requestId: id, source_sha256: context.capture.sha256, scenario: row.test, max_calls: effectiveMaxCalls,
|
|
2804
|
+
...(context.freshChecks || context.checkOptions?.fresh ? { fresh: true } : {}),
|
|
2805
|
+
...(context.checkOptions ? { samples: context.checkOptions.samples,
|
|
2806
|
+
...(context.checkOptions.step_ids ? { step_ids: context.checkOptions.step_ids } : {}) } : {}),
|
|
2380
2807
|
...(context.serverFeatures?.includes('lazy-interfaces') ? { lazy_interfaces: true } : {}),
|
|
2381
2808
|
...sourceProvenance(context) };
|
|
2382
|
-
|
|
2809
|
+
let verdict;
|
|
2810
|
+
try { verdict = await context.postCheck(request, row, Math.max(1, Math.min(context.ports.postMs, context.deadline - context.ports.now()))); }
|
|
2811
|
+
catch (error) {
|
|
2812
|
+
// Registration may throw before postJob starts dispatch. Keep the original
|
|
2813
|
+
// receipt while this invocation can still prove its exact claim was unsent.
|
|
2814
|
+
if (!preserveUnsentReplacement(context, row, path)) throw error;
|
|
2815
|
+
await finishReservation(context, row, { state: 'not_run' });
|
|
2816
|
+
return;
|
|
2817
|
+
}
|
|
2383
2818
|
if (verdict.kind === 'not_sent') {
|
|
2819
|
+
preserveUnsentReplacement(context, row, path);
|
|
2384
2820
|
const note = { code: null, message: 'Stopped before sending.' };
|
|
2385
2821
|
// Live knowledge owns this attempt's wording only; claim adoption still owns uncertainty.
|
|
2386
2822
|
if (context.interrupted) (context.unsentInterruptions ??= new WeakMap()).set(row, { id, note });
|
|
@@ -2695,6 +3131,8 @@ async function checkBatch(context, rows, priorLint = null) {
|
|
|
2695
3131
|
}
|
|
2696
3132
|
|
|
2697
3133
|
async function runScheduledChecks(context, rows, toSend) {
|
|
3134
|
+
// Saved live-local observations may poll original IDs, but cannot admit work.
|
|
3135
|
+
if (context.liveLocalSaved) toSend = [];
|
|
2698
3136
|
const { ports } = context;
|
|
2699
3137
|
context.checkWindow ??= localLimit(context);
|
|
2700
3138
|
for (const row of toSend) row.attempts = 0;
|
|
@@ -2702,7 +3140,7 @@ async function runScheduledChecks(context, rows, toSend) {
|
|
|
2702
3140
|
// Refill on a POST's settlement even while the polling loop awaits GETs.
|
|
2703
3141
|
// Waiting rows stay outside admission and dispatch-claim allocation.
|
|
2704
3142
|
const pumpSends = () => {
|
|
2705
|
-
if (context.interrupted || context.readStop || context.stopped || context.sendError || ports.now() >= context.deadline) return;
|
|
3143
|
+
if (context.liveLocalSaved || context.interrupted || context.readStop || context.stopped || context.sendError || ports.now() >= context.deadline) return;
|
|
2706
3144
|
const active = rows.filter(occupiesSlot).length;
|
|
2707
3145
|
const available = Math.max(0, Math.min(uploads - pendingSends.size, context.checkWindow - active - pendingSends.size));
|
|
2708
3146
|
const eligible = toSend.filter(row => !pendingSends.has(row) && !row.awaiting_budget && ['ready', 'waiting'].includes(row.state)
|
|
@@ -2740,7 +3178,7 @@ async function runScheduledChecks(context, rows, toSend) {
|
|
|
2740
3178
|
}
|
|
2741
3179
|
if (context.sendError) throw context.sendError;
|
|
2742
3180
|
const earlyRestarts = await recoverRestarts(context);
|
|
2743
|
-
for (const row of rows.filter(row => row.state === 'ready' && (row.restart_used || row.restart_pending))) if (!toSend.includes(row)) toSend.push(row);
|
|
3181
|
+
if (!context.liveLocalSaved) for (const row of rows.filter(row => row.state === 'ready' && (row.restart_used || row.restart_pending))) if (!toSend.includes(row)) toSend.push(row);
|
|
2744
3182
|
if (earlyRestarts.length) { for (const item of toSend) item.awaiting_budget = false; pumpSends(); }
|
|
2745
3183
|
const pending = toSend.some(row => ['ready', 'waiting'].includes(row.state));
|
|
2746
3184
|
if (pending && active >= context.checkWindow && !rows.some(readable)) break;
|
|
@@ -2752,7 +3190,7 @@ async function runScheduledChecks(context, rows, toSend) {
|
|
|
2752
3190
|
await eachLimited(rows.filter(readable), MAX_READS, row => readRow(context, row));
|
|
2753
3191
|
for (const item of toSend) item.awaiting_budget = false;
|
|
2754
3192
|
await recoverRestarts(context);
|
|
2755
|
-
for (const row of rows.filter(row => row.state === 'ready' && (row.restart_used || row.restart_pending))) if (!toSend.includes(row)) toSend.push(row);
|
|
3193
|
+
if (!context.liveLocalSaved) for (const row of rows.filter(row => row.state === 'ready' && (row.restart_used || row.restart_pending))) if (!toSend.includes(row)) toSend.push(row);
|
|
2756
3194
|
saveBatch(context);
|
|
2757
3195
|
}
|
|
2758
3196
|
} catch (error) { context.sendError ??= error; throw error; }
|
|
@@ -2761,6 +3199,7 @@ async function runScheduledChecks(context, rows, toSend) {
|
|
|
2761
3199
|
const stoppedEarly = context.interrupted || !!context.readStop;
|
|
2762
3200
|
context.timedOut ||= !stoppedEarly && ports.now() >= context.deadline && rows.some(isOpen);
|
|
2763
3201
|
for (const row of toSend) {
|
|
3202
|
+
restoreReplacement(row); // A budget-held replacement may never have reached sendCheck.
|
|
2764
3203
|
if (['ready', 'waiting'].includes(row.state)) Object.assign(row, { state: 'not_run', calls: row.restart_used || row.restart_pending ? accumulatedCalls(context, row) : 0, busy: true, can_retry: true,
|
|
2765
3204
|
phase: row.request_ids.length ? 'server' : 'local', note: { code: 'check-busy', message: context.interrupted && row.busy && row.request_ids.length
|
|
2766
3205
|
? stoppedPause(context, row, 'check') : row.request_ids.length
|
|
@@ -2890,34 +3329,58 @@ function runFiles(cwd, words, options, ports) {
|
|
|
2890
3329
|
async function runLintOnly(context, cwd, words, options, setRelease) {
|
|
2891
3330
|
const { ports } = context, origin = runtimeOrigin(ports.env), { root, found, normalized } = localSetup(cwd, words, ports);
|
|
2892
3331
|
context.excludeFixtureProjects = words.length === 0;
|
|
2893
|
-
const
|
|
3332
|
+
const promptArgs = words.length > 0 && normalized.every(word => word.endsWith('.prompt.md') && found.visible.has(word));
|
|
3333
|
+
const paths = promptArgs ? normalized : (words.length ? undefined : [...found.discoveryVisible].filter(path => path.endsWith('.prompt.md')));
|
|
2894
3334
|
let findings = paths ? interfaceFindings({root,paths}).filter(localInterfaceProblem) : [];
|
|
2895
3335
|
const advice = paths ? formatAdvice(root, found.visible, paths, found.workspace) : [];
|
|
3336
|
+
const { selectorLintForPrompts } = await import('./try-doors.mjs');
|
|
3337
|
+
let selectorInfo = paths ? selectorLintForPrompts({ root, visible: found.visible, paths, workspace: found.workspace }) : { warnings: [], tableLines: [] };
|
|
3338
|
+
advice.push(...selectorInfo.warnings);
|
|
2896
3339
|
found.warnings.push(...advice);
|
|
3340
|
+
context.selectorTableLines = selectorInfo.tableLines;
|
|
2897
3341
|
if (findings.some(item => item.code === 'interface-missing') && !found.tests.length) {
|
|
2898
3342
|
if (await probeLazyInterfaces(context, origin, context.store)) findings = findings.filter(item => item.code !== 'interface-missing');
|
|
2899
3343
|
}
|
|
2900
|
-
if (findings.length && !found.tests.length) {
|
|
3344
|
+
if (findings.length && (!found.tests.length || promptArgs)) {
|
|
2901
3345
|
const summary = 'Lint refused Runtime interfaces. 0 AI calls. No files were sent.';
|
|
2902
|
-
if (context.json) line(ports.stdout,JSON.stringify({repo:root,exit_code:4,lint_state:'refused',problems:findings,rows:[],summary_line:summary}));
|
|
2903
|
-
else for (const text of [...findings.map(item => `${item.code}: ${item.message}`),summary]) line(ports.stdout,text);
|
|
3346
|
+
if (context.json) line(ports.stdout,JSON.stringify({repo:root,exit_code:4,lint_state:'refused',problems:findings,rows:[],warnings:[...new Set(found.warnings)],summary_line:summary}));
|
|
3347
|
+
else for (const text of [...findings.map(item => `${item.code}: ${item.message}`), ...selectorInfo.warnings, summary]) line(ports.stdout,text);
|
|
2904
3348
|
return 4;
|
|
2905
3349
|
}
|
|
3350
|
+
if (promptArgs) {
|
|
3351
|
+
const hygiene = lintLocalHygiene({ root, files: [...found.visible], promptPaths: paths, tests: [], workspace: found.workspace }, ports);
|
|
3352
|
+
const warnings = [...new Set([...found.warnings, ...hygiene])];
|
|
3353
|
+
const summary = `Lint: checked ${paths.length} prompt ${paths.length === 1 ? 'file' : 'files'}. 0 AI calls. No checks were sent.`;
|
|
3354
|
+
if (context.json) {
|
|
3355
|
+
line(ports.stdout, JSON.stringify({ repo: root, exit_code: 0, lint_state: 'passed', problems: [], rows: [], warnings, summary_line: summary }));
|
|
3356
|
+
} else {
|
|
3357
|
+
for (const text of [...selectorInfo.tableLines, ...warnings, summary]) line(ports.stdout, text);
|
|
3358
|
+
}
|
|
3359
|
+
return 0;
|
|
3360
|
+
}
|
|
2906
3361
|
let selected;
|
|
2907
3362
|
try { selected = select(found, normalized, root, ports); }
|
|
2908
3363
|
catch (error) {
|
|
2909
3364
|
if (error instanceof Stop) {
|
|
2910
|
-
const noTestsAdvice = [...new Set([...advice, ...(paths ? lintLocalHygiene({ root, files: [...found.visible], promptPaths: paths, tests: [], workspace: found.workspace }, ports) : [])])];
|
|
3365
|
+
const noTestsAdvice = [...new Set([...advice, ...selectorInfo.tableLines, ...(paths ? lintLocalHygiene({ root, files: [...found.visible], promptPaths: paths, tests: [], workspace: found.workspace }, ports) : [])])];
|
|
2911
3366
|
if (noTestsAdvice.length) error.message = [error.message, ...noTestsAdvice].join('\n');
|
|
2912
3367
|
}
|
|
2913
3368
|
throw error;
|
|
2914
3369
|
}
|
|
2915
|
-
if (!paths) {
|
|
2916
|
-
|
|
3370
|
+
if (!paths) {
|
|
3371
|
+
advice.push(...formatAdvice(root, found.visible, entryPaths(selected), found.workspace));
|
|
3372
|
+
selectorInfo = selectorLintForPrompts({ root, visible: found.visible, paths: entryPaths(selected), workspace: found.workspace });
|
|
3373
|
+
advice.push(...selectorInfo.warnings);
|
|
3374
|
+
found.warnings.push(...advice);
|
|
3375
|
+
context.selectorTableLines = selectorInfo.tableLines;
|
|
3376
|
+
}
|
|
3377
|
+
const derivations = new Map(derivationProblems(root, found, selected).map(problem => [problem.path, problem]));
|
|
3378
|
+
const runnable = selected.filter(test => !derivations.has(test.path));
|
|
3379
|
+
for (const warning of missingCliImplementationWarnings({ root, found, selected:runnable })) {
|
|
2917
3380
|
if (!advice.includes(warning)) advice.push(warning);
|
|
2918
3381
|
if (!found.warnings.includes(warning)) found.warnings.push(warning);
|
|
2919
3382
|
}
|
|
2920
|
-
const hasMissing = findings.some(item => item.code === 'interface-missing') || hasMissingPromptInterface(root, found, entryPaths(
|
|
3383
|
+
const hasMissing = runnable.length > 0 && (findings.some(item => item.code === 'interface-missing') || hasMissingPromptInterface(root, found, entryPaths(runnable)));
|
|
2921
3384
|
const allowMissingInterfaces = hasMissing ? await probeLazyInterfaces(context, origin, context.store) : false;
|
|
2922
3385
|
if (allowMissingInterfaces) findings = findings.filter(item => item.code !== 'interface-missing');
|
|
2923
3386
|
const activeLocalProblem = problem => localInterfaceProblem(problem) && !(allowMissingInterfaces && problem.code === 'interface-missing');
|
|
@@ -2927,9 +3390,9 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
|
|
|
2927
3390
|
refusals: [], request_ids: [], warnings: [], steps: Array.isArray(test.doc?.steps) ? test.doc.steps.filter(isObject) : [],
|
|
2928
3391
|
app_maps: declaredMaps(test.doc),
|
|
2929
3392
|
criterion_texts: Object.fromEntries((Array.isArray(test.doc?.criteria) ? test.doc.criteria : []).filter(isObject).map(item => [item.id, item.text])),
|
|
2930
|
-
...(discoveryRefusal(test) ? { state: 'refused', phase: 'local', unsent:true, refusals: [discoveryRefusal(test)], steps: [], app_maps: [] } : {}) }));
|
|
3393
|
+
...(discoveryRefusal(test) || derivations.has(test.path) ? { state: 'refused', phase: 'local', unsent:true, refusals: [discoveryRefusal(test) ?? {...derivations.get(test.path),hint:'Fix the named derivation or expected value, then run the selection again.'}], steps: [], app_maps: [] } : {}) }));
|
|
2931
3394
|
context.rows = rows;
|
|
2932
|
-
const nativeRows = new Map(preflight({root,found,selected,allowMissingInterfaces}).rows.filter(row => row.native_only?.length).map(row => [row.test,row]));
|
|
3395
|
+
const nativeRows = new Map(preflight({root,found,selected:runnable,allowMissingInterfaces}).rows.filter(row => row.native_only?.length).map(row => [row.test,row]));
|
|
2933
3396
|
for (const row of rows) {
|
|
2934
3397
|
const native = nativeRows.get(row.test);
|
|
2935
3398
|
if (native) Object.assign(row,{state:native.refusals.length ? 'refused' : 'not_run',refusals:native.refusals,phase:'local',native_only:native.native_only,unsent:true,note:{code:'native-only',message:native.native_only.map(item => `${item.path}: ${item.reason}`).join('; ')}});
|
|
@@ -2937,7 +3400,7 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
|
|
|
2937
3400
|
if (!findings.length && rows.every(row => row.native_only?.length)) {
|
|
2938
3401
|
const hygiene = lintLocalHygiene({ root, files: [...found.visible], promptPaths: words.length ? entryPaths(selected) : undefined, tests: selected, workspace: found.workspace }, ports);
|
|
2939
3402
|
context.warnings = [...new Set([...found.warnings, ...hygiene])];
|
|
2940
|
-
saveLocalNativeResult(context, rows, 'lint-only');
|
|
3403
|
+
await saveLocalNativeResult(context, rows, 'lint-only');
|
|
2941
3404
|
return printLintResult(context, rows, [], [...new Set([...advice, ...hygiene])]);
|
|
2942
3405
|
}
|
|
2943
3406
|
const local = row => row.phase === 'local';
|
|
@@ -2958,7 +3421,7 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
|
|
|
2958
3421
|
});
|
|
2959
3422
|
const limited = findings.length > 0 || limitRows.some(row => !local(row) && row.refusals.length);
|
|
2960
3423
|
if (!limited && rows.every(local)) {
|
|
2961
|
-
if (rows.some(row => row.native_only?.length)) saveLocalNativeResult(context,rows,'lint-only');
|
|
3424
|
+
if (rows.some(row => row.native_only?.length)) await saveLocalNativeResult(context,rows,'lint-only');
|
|
2962
3425
|
return printLintResult(context,rows,[],found.warnings);
|
|
2963
3426
|
}
|
|
2964
3427
|
if (limited) {
|
|
@@ -2970,7 +3433,7 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
|
|
|
2970
3433
|
}
|
|
2971
3434
|
if (refusedRows.some(row => row.native_only?.length)) {
|
|
2972
3435
|
context.warnings = found.warnings;
|
|
2973
|
-
saveLocalNativeResult(context, refusedRows, 'lint-only', problems);
|
|
3436
|
+
await saveLocalNativeResult(context, refusedRows, 'lint-only', problems);
|
|
2974
3437
|
return printLintResult(context, refusedRows, problems);
|
|
2975
3438
|
}
|
|
2976
3439
|
const broken = refusedRows.filter(row=>row.unsent).length;
|
|
@@ -3034,8 +3497,7 @@ async function runLintOnly(context, cwd, words, options, setRelease) {
|
|
|
3034
3497
|
setRelease(interruptible(context));
|
|
3035
3498
|
await ownBatch(context, batch);
|
|
3036
3499
|
saveBatch(context);
|
|
3037
|
-
|
|
3038
|
-
context.store.saveRepo(root, { ...repoState, last_batch: batch });
|
|
3500
|
+
await context.store.updateRepo(root, current => ({ ...current, last_batch: batch }));
|
|
3039
3501
|
context.auth = authSession({ identity, store: context.store, ports, secrets: context.secrets, onRefresh: next => { context.identity = next; saveBatch(context); } });
|
|
3040
3502
|
context.runtime = new Runtime({ origin, token: identity.token, ports, signal: context.signal, auth: context.auth });
|
|
3041
3503
|
let lint;
|
|
@@ -3175,7 +3637,7 @@ function printLintResult(context, rows, problems, warnings = [], answer = null)
|
|
|
3175
3637
|
context: result.call_preflight_context, sourceSha256: context.capture?.sha256, requestedCap: result.call_preflight_requested_cap }).text);
|
|
3176
3638
|
if (typeof capabilityCoverage === 'boolean') out.push(`Capability inventory complete: ${capabilityCoverage}.`);
|
|
3177
3639
|
if (reportUrl) out.push(`Report: ${reportUrl}`);
|
|
3178
|
-
out.push(summary, coverageText(context.coverage), ...warnings);
|
|
3640
|
+
out.push(...(context.selectorTableLines ?? []), summary, coverageText(context.coverage), ...warnings);
|
|
3179
3641
|
ports.stdout.write(`${out.join('\n')}\n`);
|
|
3180
3642
|
return exitCode;
|
|
3181
3643
|
}
|
|
@@ -3276,6 +3738,8 @@ function validSavedCheck(row) {
|
|
|
3276
3738
|
}
|
|
3277
3739
|
|
|
3278
3740
|
async function continueHeld(context, candidates, saved) {
|
|
3741
|
+
if (context.liveLocalSaved) return;
|
|
3742
|
+
if (diagnosticBatch(saved) && !saved.check_options) { context.continuationNotice = 'Diagnostic subsets need a fresh pdd test with --step to send new checks.'; return; }
|
|
3279
3743
|
if (!candidates.length || context.interrupted || context.ports.now() >= context.deadline) return;
|
|
3280
3744
|
if (saved.intent === 'lint-only') return;
|
|
3281
3745
|
candidates = candidates.filter(row => runtimeLintRow(row) && !row.request_ids.length && !row.dispatchIncomplete);
|
|
@@ -3334,7 +3798,7 @@ function isLocalSavedBatchRead(context, saved) {
|
|
|
3334
3798
|
return true;
|
|
3335
3799
|
}
|
|
3336
3800
|
|
|
3337
|
-
async function runRead(context, batchWord, quiet = false, options = {}) {
|
|
3801
|
+
async function runRead(context, batchWord, quiet = false, options = {}, retry = false) {
|
|
3338
3802
|
context.cacheReadInvocation = true;
|
|
3339
3803
|
const { store, ports, root } = context;
|
|
3340
3804
|
const progress = context.checkProgress ??= { startedAt: ports.now(), shownAt: ports.now() };
|
|
@@ -3355,24 +3819,32 @@ async function runRead(context, batchWord, quiet = false, options = {}) {
|
|
|
3355
3819
|
await ownBatch(context, name);
|
|
3356
3820
|
const saved = store.read(join(context.folder, 'batch.json'));
|
|
3357
3821
|
if (!saved) throw new Stop(2, `No saved batch ${name}.`);
|
|
3822
|
+
if (saved.root !== root) throw new Stop(2, 'This saved batch belongs to a different repository.');
|
|
3823
|
+
if (retry && saved.live_local === true) throw new Stop(2, 'Saved live-local runs are observational. Start a fresh explicit --live-local run after reviewing the original outcome.');
|
|
3358
3824
|
for (const row of [...saved.rows, ...(saved.lint ? [saved.lint] : [])]) {
|
|
3359
3825
|
if (row.recovery_state !== undefined) { row.state = row.recovery_state; delete row.reason; }
|
|
3360
3826
|
}
|
|
3361
|
-
if (saved
|
|
3827
|
+
if (diagnosticBatch(saved)) {
|
|
3828
|
+
if (quiet) throw new Stop(2, 'Diagnostic subsets cannot be retried. Start a fresh pdd test with --step.');
|
|
3829
|
+
context.cacheEnabled = false; context.stepIds = saved.selected_steps ?? saved.rows.flatMap(row=>row.selected_steps ?? []);
|
|
3830
|
+
for (const row of saved.rows) Object.assign(row,{diagnostic:true,diagnostic_subset:true,selected_steps:row.selected_steps ?? context.stepIds});
|
|
3831
|
+
}
|
|
3832
|
+
context.checkOptions = saved.check_options ?? null;
|
|
3833
|
+
if (context.checkOptions) context.cacheEnabled = false;
|
|
3362
3834
|
context.checkPlan = saved.check_plan ?? null;
|
|
3363
3835
|
context.checkSelection = saved.check_selection; context.baselineReport = saved.baseline_report;
|
|
3364
3836
|
if (saved.local_only === true && saved.rows.length && saved.rows.every(row => row.unsent && ['refused','not_run'].includes(row.state) && !row.request_ids?.length)) {
|
|
3365
|
-
Object.assign(context,{localOnly:true,singleAttempt:context.singleAttempt || saved.single_attempt === true,maxTotalCalls:Number.isSafeInteger(saved.max_total_calls)&&saved.max_total_calls>=1?saved.max_total_calls:null,batch:name,intent:saved.intent,coverage:saved.coverage,rows:saved.rows,warnings:saved.warnings ?? [],
|
|
3837
|
+
Object.assign(context,{localOnly:true,liveLocalSaved:saved.live_local===true,singleAttempt:context.singleAttempt || saved.single_attempt === true,maxTotalCalls:Number.isSafeInteger(saved.max_total_calls)&&saved.max_total_calls>=1?saved.max_total_calls:null,batch:name,intent:saved.intent,coverage:saved.coverage,rows:saved.rows,warnings:saved.warnings ?? [],
|
|
3366
3838
|
capture:{sha256:saved.source_sha256},startedAt:Date.parse(saved.created_at),lint:saved.lint});
|
|
3367
3839
|
if (quiet) return saved.rows;
|
|
3368
3840
|
return saved.intent === 'lint-only' ? printLintResult(context,saved.rows,saved.lint?.problems ?? []) : printResult(context,saved.rows);
|
|
3369
3841
|
}
|
|
3370
|
-
if(loadRuntimeWorkspace({root}).configured)ports.captureSource(root,{tests:saved.rows.filter(row=>!row.unsent).map(row=>row.test),appMap:null,excludeFixtureProjects:saved.exclude_fixture_projects === true,...(saved.lazy_interfaces === true ? {allowMissingInterfaces:true} : {})});
|
|
3842
|
+
if(loadRuntimeWorkspace({root}).configured)ports.captureSource(root,{...(context.stepIds?.length ? {stepIds:context.stepIds} : {}),tests:saved.rows.filter(row=>!row.unsent).map(row=>row.test),appMap:null,excludeFixtureProjects:saved.exclude_fixture_projects === true,...(saved.lazy_interfaces === true ? {allowMissingInterfaces:true} : {})});
|
|
3371
3843
|
const identity = signIn(ports.gh, context.store, ports, {
|
|
3372
3844
|
allowSavedLocalReadFallback: !quiet && isLocalSavedBatchRead(context, saved),
|
|
3373
3845
|
});
|
|
3374
3846
|
if (identity.login !== saved.login) throw new Stop(5, `These runs belong to ${saved.login}. Run: gh auth switch -u ${saved.login}`);
|
|
3375
|
-
Object.assign(context, { singleAttempt: context.singleAttempt || saved.single_attempt === true, allowMissingInterfaces: saved.lazy_interfaces === true, maxTotalCalls: Number.isSafeInteger(saved.max_total_calls) && saved.max_total_calls >= 1 ? saved.max_total_calls : null, excludeFixtureProjects: saved.exclude_fixture_projects === true, batch: name, origin: saved.origin, sourceSelection:saved.source_selection, nativeSource:saved.native_source, coverage: saved.coverage, maintenance: saved.maintenance ?? null, identity, intent: saved.intent, secrets: [identity.token], warnings: saved.warnings ?? [],
|
|
3847
|
+
Object.assign(context, { liveLocalSaved:saved.live_local===true,singleAttempt: context.singleAttempt || saved.single_attempt === true, allowMissingInterfaces: saved.lazy_interfaces === true, maxTotalCalls: Number.isSafeInteger(saved.max_total_calls) && saved.max_total_calls >= 1 ? saved.max_total_calls : null, excludeFixtureProjects: saved.exclude_fixture_projects === true, batch: name, origin: saved.origin, sourceSelection:saved.source_selection, nativeSource:saved.native_source, coverage: saved.coverage, maintenance: saved.maintenance ?? null, identity, intent: saved.intent, secrets: [identity.token], warnings: saved.warnings ?? [],
|
|
3376
3848
|
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) });
|
|
3377
3849
|
runtimeOrigin({ PDD_RUNTIME_URL: saved.origin });
|
|
3378
3850
|
context.auth = authSession({
|
|
@@ -3497,11 +3969,14 @@ async function runRead(context, batchWord, quiet = false, options = {}) {
|
|
|
3497
3969
|
}
|
|
3498
3970
|
|
|
3499
3971
|
async function recoverRestarts(context) {
|
|
3972
|
+
if (context.liveLocalSaved) return [];
|
|
3973
|
+
if (context.reading && context.stepIds?.length) return [];
|
|
3500
3974
|
if (context.intent !== undefined && context.intent !== 'check') return [];
|
|
3501
3975
|
const eligible = context.rows.filter(row => {
|
|
3502
3976
|
adoptClaims(context, row);
|
|
3503
3977
|
const id = row.request_ids.at(-1), answer = id && context.store.read(join(context.folder, `${id}.json`));
|
|
3504
|
-
return !row.restart_used && !
|
|
3978
|
+
return !row.restart_used && !statOrNull(claimPath(context, row).replace(/\.0\.dispatch\.json$/, '.restart.json'))
|
|
3979
|
+
&& !row.restart_pending && !row.admitting && !context.restartDecisions?.has(id) && sameJob(answer, id, 'check') && (restarted(answer) || transientDrop(answer));
|
|
3505
3980
|
});
|
|
3506
3981
|
if (!eligible.length || context.interrupted || context.ports.now() >= context.deadline) return [];
|
|
3507
3982
|
if (context.singleAttempt) {
|
|
@@ -3512,7 +3987,10 @@ async function recoverRestarts(context) {
|
|
|
3512
3987
|
context.budgetNotices ??= new Set();
|
|
3513
3988
|
if (!context.budgetNotices.has(warnKey)) {
|
|
3514
3989
|
context.budgetNotices.add(warnKey);
|
|
3515
|
-
|
|
3990
|
+
const answer = context.store.read(join(context.folder, `${row.request_ids.at(-1)}.json`));
|
|
3991
|
+
line(context.ports.stderr, restarted(answer)
|
|
3992
|
+
? `The interpreter restarted ${row.test}; restart replacement is disabled, so pdd kept the original unknown result.`
|
|
3993
|
+
: `${row.test} gave no verdict; replacement is disabled, so pdd kept the original result.`);
|
|
3516
3994
|
}
|
|
3517
3995
|
}
|
|
3518
3996
|
return [];
|
|
@@ -3522,12 +4000,37 @@ async function recoverRestarts(context) {
|
|
|
3522
4000
|
context.continuationNotice = 'The saved source changed or cannot be verified; no restarted check was sent again.';
|
|
3523
4001
|
return [];
|
|
3524
4002
|
}
|
|
3525
|
-
const
|
|
3526
|
-
|
|
3527
|
-
|
|
4003
|
+
const matchingLint = sameJob(lint, lintId, 'lint');
|
|
4004
|
+
let heldRestarts = 0, heldTransient = false;
|
|
4005
|
+
const admitted = eligible.filter(row => {
|
|
4006
|
+
const answer = context.store.read(join(context.folder, `${row.request_ids.at(-1)}.json`));
|
|
4007
|
+
const hasLintPass = matchingLint && lintAdmits(lint, row, context.capture);
|
|
4008
|
+
if (restarted(answer)) {
|
|
4009
|
+
if (!hasLintPass) heldRestarts++;
|
|
4010
|
+
return hasLintPass;
|
|
4011
|
+
}
|
|
4012
|
+
if (hasLintPass && deterministicStory(context, row) && transientHistory(context, row)) return true;
|
|
4013
|
+
heldTransient = true;
|
|
4014
|
+
return false;
|
|
4015
|
+
});
|
|
4016
|
+
const notices = [];
|
|
4017
|
+
if (heldRestarts) notices.push(`The interpreter restarted ${heldRestarts === 1 ? 'a check' : `${heldRestarts} checks`}, `
|
|
4018
|
+
+ 'but the saved lint gives no pass of its own to that test, so pdd did not send it again. Start a fresh pdd test.');
|
|
4019
|
+
if (heldTransient) notices.push('The saved lint or deterministic simulation evidence does not authorize retrying every check; pdd kept those original results. Start a fresh pdd test.');
|
|
4020
|
+
if (notices.length) context.continuationNotice = notices.join('\n');
|
|
3528
4021
|
if (!admitted.length) return [];
|
|
3529
4022
|
context.restartDecisions ??= new Set();
|
|
3530
|
-
const
|
|
4023
|
+
const drops = admitted.filter(row => transientDrop(context.store.read(join(context.folder, `${row.request_ids.at(-1)}.json`))));
|
|
4024
|
+
// Backoff precedes the source recapture, so edits during the wait cannot
|
|
4025
|
+
// authorize a replacement of the original selected source.
|
|
4026
|
+
if (drops.length && !await waitBudget(context, 1000)) return [];
|
|
4027
|
+
let capture;
|
|
4028
|
+
try { capture = (!drops.length && context.recoveredSourceCapture) || context.ports.captureSource(context.root, { tests: sentTests(context.rows), appMap: null, excludeFixtureProjects: context.excludeFixtureProjects, ...(context.allowMissingInterfaces ? { allowMissingInterfaces: true } : {}) }); }
|
|
4029
|
+
catch (error) {
|
|
4030
|
+
if (!(error instanceof PreflightError)) throw error;
|
|
4031
|
+
context.continuationNotice = 'The saved source changed or cannot be verified; no replacement check was sent.';
|
|
4032
|
+
return [];
|
|
4033
|
+
}
|
|
3531
4034
|
if (capture.sha256 !== context.capture.sha256) { context.continuationNotice = 'The saved source changed; no restarted check was sent again.'; return []; }
|
|
3532
4035
|
capture.stories = context.capture.stories;
|
|
3533
4036
|
context.capture = capture;
|
|
@@ -3535,19 +4038,25 @@ async function recoverRestarts(context) {
|
|
|
3535
4038
|
const selected = [];
|
|
3536
4039
|
for (const row of admitted) {
|
|
3537
4040
|
if (context.interrupted || context.ports.now() >= context.deadline || !validSavedCheck(row)) continue;
|
|
4041
|
+
const transient = drops.includes(row);
|
|
3538
4042
|
const decision = evaluateCheckBudget({
|
|
3539
4043
|
max_total_calls: context.maxTotalCalls ?? null,
|
|
3540
4044
|
single_attempt: !!context.singleAttempt,
|
|
3541
4045
|
unresolved_prior_reservations: { count: 0, reserved_calls: 0 },
|
|
3542
4046
|
rows: budgetRowsForContext(context, row),
|
|
3543
|
-
candidate: { test: row.test, kind: 'restart-replacement', requested_max_calls: row.max_calls, restart_used: !!row.restart_used, prior_reason_code: 'service-restarted' }
|
|
4047
|
+
candidate: { test: row.test, kind: transient ? 'initial' : 'restart-replacement', requested_max_calls: row.max_calls, restart_used: !!row.restart_used, prior_reason_code: transient ? null : 'service-restarted' }
|
|
3544
4048
|
}).decision;
|
|
3545
4049
|
if (decision.action === 'wait') continue;
|
|
3546
4050
|
context.restartDecisions.add(row.request_ids.at(-1));
|
|
4051
|
+
if (transient && decision.action !== 'send') {
|
|
4052
|
+
line(context.ports.stderr, `${row.test}: No simulated check retry was sent: the remaining invocation call budget does not authorize another attempt.`);
|
|
4053
|
+
continue;
|
|
4054
|
+
}
|
|
3547
4055
|
if (decision.action !== 'send') { applyBudgetDecisionStop(context, row, decision); continue; }
|
|
3548
|
-
|
|
3549
|
-
|
|
3550
|
-
Object.assign(row, { state: 'ready', lost: false, final: false, eligible: true, retry_at: null, restart_pending: true
|
|
4056
|
+
if (transient) await finishReservation(context, row, { state: 'not_run' });
|
|
4057
|
+
row.prior_restart_snapshot = { ...row, request_ids: [...row.request_ids], ...(row.claim_max_calls ? { claim_max_calls: { ...row.claim_max_calls } } : {}) };
|
|
4058
|
+
Object.assign(row, { state: 'ready', lost: false, final: false, eligible: true, retry_at: null, restart_pending: true, transient_pending: transient,
|
|
4059
|
+
...(transient ? { capacity_uncertain: false } : {}) });
|
|
3551
4060
|
selected.push(row);
|
|
3552
4061
|
}
|
|
3553
4062
|
if (selected.length) context.reading = false;
|
|
@@ -3558,7 +4067,7 @@ async function runRetry(context, name, options) {
|
|
|
3558
4067
|
const { ports } = context;
|
|
3559
4068
|
const timeout = options['--timeout'] === undefined ? AGENT_WAIT_MIN : Number(options['--timeout']);
|
|
3560
4069
|
context.deadline = ports.now() + timeout * 60_000;
|
|
3561
|
-
const rows = await runRead(context, name, true, options);
|
|
4070
|
+
const rows = await runRead(context, name, true, options, true);
|
|
3562
4071
|
if (context.localLayout) {
|
|
3563
4072
|
line(ports.stderr,'For new evidence, run a fresh pdd lint --local.');
|
|
3564
4073
|
return () => printLocalLayout(context,context.localLayout);
|
|
@@ -3598,9 +4107,10 @@ async function runRequest(context, id, cwd) {
|
|
|
3598
4107
|
context.auth = authSession({ identity, store: context.store, ports, secrets: context.secrets });
|
|
3599
4108
|
const runtime = new Runtime({ origin, token: identity.token, ports, signal: context.signal, auth: context.auth });
|
|
3600
4109
|
const row = { test: '-', story: '-', title: '-', phase: 'server', request_ids: [id], state: 'unknown', refusals: [], warnings: [] };
|
|
4110
|
+
const owner = owningCheckBatch(context, identity, origin, id);
|
|
4111
|
+
if (owner?.diagnostic_subset === true) Object.assign(row,{...(owner?.diagnostic ? {diagnostic:true} : {}),diagnostic_subset:true,selected_steps:owner.selected_steps ?? []});
|
|
3601
4112
|
const read = judgeGet(await runtime.get(id), id, 'check');
|
|
3602
4113
|
if (read.kind === 'state') {
|
|
3603
|
-
const owner=owningCheckBatch(context,identity,origin,id);
|
|
3604
4114
|
if(owner?.not_checked?.length) Object.assign(row,{not_checked:owner.not_checked,criteria_total:owner.criteria_total,criterion_texts:owner.criterion_texts,steps:owner.steps});
|
|
3605
4115
|
applyAnswer(row, read.answer, context);
|
|
3606
4116
|
}
|
|
@@ -3618,9 +4128,15 @@ function owningCheckBatch({root,store},identity,origin,id) {
|
|
|
3618
4128
|
try {names=readdirSync(batches);}catch{return null;}
|
|
3619
4129
|
for(const name of names.filter(name=>BATCH.test(name)).sort().reverse()) {
|
|
3620
4130
|
const saved=store.read(join(batches,name,'batch.json'));
|
|
3621
|
-
if(saved?.batch!==name || saved.root!==root || saved.origin!==origin || saved.login!==identity.login || String(saved.user_id)!==String(identity.userId) || !Array.isArray(saved.rows))continue;
|
|
4131
|
+
if(saved?.batch!==name || (saved.intent!=='check' && !(saved.version===1 && saved.intent===undefined)) || saved.root!==root || saved.origin!==origin || saved.login!==identity.login || String(saved.user_id)!==String(identity.userId) || !Array.isArray(saved.rows))continue;
|
|
3622
4132
|
const row=saved.rows.find(row=>Array.isArray(row?.request_ids)&&row.request_ids.includes(id));
|
|
3623
|
-
if(row)
|
|
4133
|
+
if(row) {
|
|
4134
|
+
if(saved.intent!=='check') {
|
|
4135
|
+
const {diagnostic_subset,selected_steps,...coverage}=row;
|
|
4136
|
+
return coverage;
|
|
4137
|
+
}
|
|
4138
|
+
return diagnosticBatch(saved) ? {...row,...(saved.diagnostic || row.diagnostic ? {diagnostic:true} : {}),diagnostic_subset:true,selected_steps:row.selected_steps ?? saved.selected_steps ?? []} : row;
|
|
4139
|
+
}
|
|
3624
4140
|
}
|
|
3625
4141
|
return null;
|
|
3626
4142
|
}
|
|
@@ -3637,12 +4153,12 @@ async function refreshCheckBatches(context, identity, origin, id, answer) {
|
|
|
3637
4153
|
|| String(saved.user_id) !== String(identity.userId)) continue;
|
|
3638
4154
|
const matchingRow = saved.rows?.find(row => row.request_ids?.includes(id));
|
|
3639
4155
|
if (!matchingRow) continue;
|
|
3640
|
-
owner ??= { batch: name, folder, row: matchingRow };
|
|
4156
|
+
if (saved.intent === 'check') owner ??= { batch: name, folder, row: diagnosticBatch(saved) ? {...matchingRow,...(saved.diagnostic || matchingRow.diagnostic ? {diagnostic:true} : {}),diagnostic_subset:true,selected_steps:matchingRow.selected_steps ?? saved.selected_steps ?? []} : matchingRow };
|
|
3641
4157
|
const cached = store.read(join(folder, `${id}.json`));
|
|
3642
4158
|
if (sameJob(cached, id, 'check') && ['passed', 'failed', 'refused'].includes(cached.state)
|
|
3643
4159
|
&& !['passed', 'failed', 'refused'].includes(answer.state)) continue;
|
|
3644
4160
|
saveAnswerAt(store, folder, id, answer);
|
|
3645
|
-
if (context.cacheEnabled && saved.version === 1 && saved.intent === 'check'
|
|
4161
|
+
if (!diagnosticBatch(saved) && context.cacheEnabled && !saved.check_options && saved.version === 1 && saved.intent === 'check'
|
|
3646
4162
|
&& Array.isArray(saved.test_cache?.tokens) && saved.rows.some(row => row.request_ids?.at(-1) === id)) {
|
|
3647
4163
|
const capture = context.ports.captureSource(root, { tests: sentTests(saved.rows), appMap: null, excludeFixtureProjects: saved.exclude_fixture_projects === true });
|
|
3648
4164
|
if (capture.sha256 !== saved.source_sha256) continue;
|
|
@@ -3667,7 +4183,8 @@ async function refreshCheckBatches(context, identity, origin, id, answer) {
|
|
|
3667
4183
|
// A read is observation only; it does not replay the call or settle backend accounting.
|
|
3668
4184
|
async function runCallRead(context, id) {
|
|
3669
4185
|
const { ports, store } = context;
|
|
3670
|
-
const saved = store.read(join(store.dir, 'calls', `${id}.meta.json`))
|
|
4186
|
+
const saved = store.read(join(store.dir, 'calls', `${id}.meta.json`))
|
|
4187
|
+
?? store.read(join(store.dir, 'tries', `${id}.meta.json`));
|
|
3671
4188
|
const identity = signIn(ports.gh, store, ports);
|
|
3672
4189
|
if (saved && identity.login !== saved.login) throw new Stop(5, `These runs belong to ${saved.login}. Run: gh auth switch -u ${saved.login}`);
|
|
3673
4190
|
const origin = runtimeOrigin(saved ? { PDD_RUNTIME_URL: saved.origin } : ports.env);
|
|
@@ -3681,16 +4198,20 @@ async function runCallRead(context, id) {
|
|
|
3681
4198
|
ownerMismatchError: owner => new Stop(5, `These runs belong to ${owner}. Run: gh auth switch -u ${owner}`),
|
|
3682
4199
|
});
|
|
3683
4200
|
const runtime = new Runtime({ origin, token: identity.token, ports, signal: context.signal, auth });
|
|
4201
|
+
const localOwner = owningCheckBatch(context, identity, origin, id);
|
|
3684
4202
|
const reply = await runtime.get(id), blocked = blockingAnswer(reply);
|
|
3685
4203
|
if (blocked) throw new Stop(5, blocked);
|
|
3686
|
-
const command = ['call', 'check'].includes(reply.json?.command) ? reply.json.command : null;
|
|
4204
|
+
const command = ['call', 'try', 'check'].includes(reply.json?.command) ? reply.json.command : null;
|
|
3687
4205
|
const verified = [200, 202].includes(reply.status) && command && sameJob(reply.json, id, command)
|
|
4206
|
+
&& (!saved || (saved.command ?? 'call') === command)
|
|
4207
|
+
&& (command !== 'try' || (sameTryReceipt(reply.json, id) && (saved?.command === 'try' || isObject(reply.json.result?.session))))
|
|
3688
4208
|
&& !(saved?.session_id && reply.json.session_id && saved.session_id !== reply.json.session_id);
|
|
3689
4209
|
const answer = verified && !(command === 'call' && reply.json.state === 'passed' && !isObject(reply.json.result?.program_result)) ? reply.json : null;
|
|
3690
4210
|
if (answer?.command === 'check') {
|
|
3691
4211
|
Object.assign(context, { origin, secrets });
|
|
3692
4212
|
const row = { test: '-', story: '-', title: '-', phase: 'server', request_ids: [id], state: 'unknown', refusals: [], warnings: [] };
|
|
3693
4213
|
const owner = await refreshCheckBatches(context, identity, origin, id, answer);
|
|
4214
|
+
if (localOwner?.diagnostic_subset === true || owner?.row.diagnostic) Object.assign(row,{...(owner?.row.diagnostic ? {diagnostic:true} : {}), diagnostic_subset:true,selected_steps:localOwner?.selected_steps ?? owner?.row.selected_steps ?? []});
|
|
3694
4215
|
if (owner?.row.not_checked?.length) Object.assign(row, {not_checked:owner.row.not_checked,criteria_total:owner.row.criteria_total,
|
|
3695
4216
|
criterion_texts:owner.row.criterion_texts,steps:owner.row.steps});
|
|
3696
4217
|
// Use the owning batch only to build the direct row's aggregate projection.
|
|
@@ -3701,16 +4222,21 @@ async function runCallRead(context, id) {
|
|
|
3701
4222
|
const state = answer?.state ?? 'unknown', exitCode = ports.exitCodeFor([{ state }]);
|
|
3702
4223
|
const sanitize = value => typeof value === 'string' ? secrets.reduce((text, secret) => secret ? text.split(secret).join('[secret]') : text, value).replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '').replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, '').replace(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{12,})\b/g, '[secret]')
|
|
3703
4224
|
: Array.isArray(value) ? value.map(sanitize) : isObject(value) ? Object.fromEntries(Object.entries(value).map(([k, v]) => [sanitize(k), sanitize(v)])) : value;
|
|
3704
|
-
const out = sanitize({ request_id: id, command: 'call', state, exit_code: exitCode,
|
|
4225
|
+
const out = sanitize({ request_id: id, command: answer?.command ?? saved?.command ?? 'call', state, exit_code: exitCode,
|
|
4226
|
+
...(localOwner?.diagnostic_subset === true ? { diagnostic_subset: true, selected_steps: localOwner.selected_steps ?? [],
|
|
4227
|
+
summary_line: `diagnostic subset, not a full Story pass · selected steps: ${(localOwner.selected_steps ?? []).join(', ')}` } : {}),
|
|
3705
4228
|
calls: answer?.usage?.calls ?? 'unknown', usage: answer?.usage ?? null,
|
|
3706
4229
|
program_result: answer?.result?.program_result ?? null, result: answer?.result ?? null,
|
|
3707
4230
|
report_url: answer?.report_url ? validLink(answer.report_url, origin, 'report') : null,
|
|
3708
|
-
why: answer ? answer.why ?? null : reply.status === 401 ? AUTH_TEXT : reply.status === 410 ? 'The result expired.'
|
|
3709
|
-
|
|
4231
|
+
why: answer ? answer.why ?? null : reply.status === 401 ? AUTH_TEXT : reply.status === 410 ? 'The result expired.'
|
|
4232
|
+
: saved?.command === 'try' ? 'The Try receipt could not be verified.' : 'The call receipt could not be verified.' });
|
|
4233
|
+
if (answer) store.write(join(store.folder(command === 'try' ? 'tries' : 'calls'), `${id}.json`), answer);
|
|
3710
4234
|
if (!answer && reply.status === 401) line(ports.stderr, AUTH_TEXT);
|
|
3711
4235
|
if (context.json) line(ports.stdout, JSON.stringify(out));
|
|
3712
4236
|
else {
|
|
3713
|
-
line(ports.stdout,
|
|
4237
|
+
line(ports.stdout, `${out.command === 'try' ? 'Try' : 'Call'} ${id}: ${state} · ${out.calls} AI calls`);
|
|
4238
|
+
if (out.diagnostic_subset === true) line(ports.stdout, out.summary_line);
|
|
4239
|
+
if (out.command === 'try' && out.result !== null) line(ports.stdout, JSON.stringify(out.result, null, 2));
|
|
3714
4240
|
if (out.program_result !== null) {
|
|
3715
4241
|
const { stdout, stderr, ...fields } = out.program_result;
|
|
3716
4242
|
if (typeof stdout === 'string') { line(ports.stdout, 'stdout:'); ports.stdout.write(stdout); if (!stdout.endsWith('\n')) line(ports.stdout, ''); }
|
|
@@ -3725,11 +4251,106 @@ async function runCallRead(context, id) {
|
|
|
3725
4251
|
return exitCode;
|
|
3726
4252
|
}
|
|
3727
4253
|
|
|
4254
|
+
|
|
4255
|
+
function liveLocalOptions(options,kind) {
|
|
4256
|
+
const enabled=options['--live-local'];
|
|
4257
|
+
if(enabled===undefined||enabled===false) {
|
|
4258
|
+
if(options['--command-manifest']!==undefined||options['--allow-live-writes']!==undefined)throw new Stop(2,'--command-manifest and --allow-live-writes require --live-local.');
|
|
4259
|
+
return false;
|
|
4260
|
+
}
|
|
4261
|
+
if(enabled!==true||typeof options['--command-manifest']!=='string'||!options['--command-manifest'].trim()||options['--allow-live-writes']!==undefined&&typeof options['--allow-live-writes']!=='boolean')throw new Stop(2,'--live-local requires an explicit --command-manifest path and Boolean write flag.');
|
|
4262
|
+
const forbidden=['--target','--read','--retry','--files','--explain-bindings','--affected','--journeys','--product','--stop','--save-last','--lint','--local','--request','--lf','--cache-clear'];
|
|
4263
|
+
if(kind==='try')forbidden.push('--no-wait','--agent');
|
|
4264
|
+
// Refusal checks inspect supplied fields; they do not introduce accepted CLI options.
|
|
4265
|
+
if(Object.entries(options).some(([key,value])=>forbidden.includes(key)&&value!==undefined))throw new Stop(2,'This option combination is unavailable with --live-local. Live simulations must stay in the foreground.');
|
|
4266
|
+
return true;
|
|
4267
|
+
}
|
|
4268
|
+
async function prepareLiveManifest(context,options,root) {
|
|
4269
|
+
if(!context.liveLocal||context.localManifest)return;
|
|
4270
|
+
const host=context.ports.liveLocal;
|
|
4271
|
+
for(const name of ['readManifest','manifestInSource','execute','confirm','randomUUID','sleep','redact','resolveExecutable','environment'])if(typeof host?.[name]!=='function')throw unboundPortError(`Live-local port ${name} is not bound.`);
|
|
4272
|
+
if(typeof host.journal?.read!=='function'||typeof host.journal?.write!=='function'||typeof host.terminal!=='boolean')throw unboundPortError('Live-local private journal and actual terminal ports are not bound.');
|
|
4273
|
+
try {
|
|
4274
|
+
const raw=await host.readManifest({path:options['--command-manifest'],root});
|
|
4275
|
+
context.rawLocalManifest=raw?.schema_version==='pdd.live-local-manifest.v1'?null:JSON.parse(JSON.stringify(raw));
|
|
4276
|
+
context.localManifest=JSON.parse(JSON.stringify(compileLocalManifest(raw)));
|
|
4277
|
+
} catch { throw new Stop(2,'live-local-manifest-invalid'); }
|
|
4278
|
+
context.localManifestPath=options['--command-manifest'];
|
|
4279
|
+
context.allowLiveWrites=options['--allow-live-writes']===true;
|
|
4280
|
+
}
|
|
4281
|
+
async function ensureLocalSource(context,capture) {
|
|
4282
|
+
if(!context.liveLocal)return;
|
|
4283
|
+
if(await context.ports.liveLocal.manifestInSource({path:context.localManifestPath,root:context.root,files:capture.files.map(file=>file.path)}))throw new Stop(2,'live-local-manifest-in-source');
|
|
4284
|
+
if(context.rawLocalManifest) {
|
|
4285
|
+
const simulatedResources=[];
|
|
4286
|
+
for(const file of capture.sources??[]) {
|
|
4287
|
+
if(file?.path?.endsWith('.prompt.md')) {
|
|
4288
|
+
try {
|
|
4289
|
+
const text=Buffer.isBuffer(file.bytes)?file.bytes.toString('utf8'):String(file.bytes??'');
|
|
4290
|
+
for(const block of interfaceBlocks(text)) {
|
|
4291
|
+
const parsed=JSON.parse(block[1]);
|
|
4292
|
+
for(const res of parsed?.resources??[])if(typeof res?.name==='string'&&res.name)simulatedResources.push(res.name);
|
|
4293
|
+
}
|
|
4294
|
+
} catch {}
|
|
4295
|
+
} else if(file?.path?.endsWith('.json')) {
|
|
4296
|
+
try {
|
|
4297
|
+
const text=Buffer.isBuffer(file.bytes)?file.bytes.toString('utf8'):String(file.bytes??'');
|
|
4298
|
+
const doc=JSON.parse(text);
|
|
4299
|
+
const scanSim=val=>{
|
|
4300
|
+
if(Array.isArray(val)){for(const row of val)if(typeof row?.operation==='string'&&row.operation.includes('.'))simulatedResources.push(row.operation.split('.',1)[0]);}
|
|
4301
|
+
else if(isObject(val)){for(const key of Object.keys(val))if(key.includes('.'))simulatedResources.push(key.split('.',1)[0]);}
|
|
4302
|
+
};
|
|
4303
|
+
scanSim(doc?.simulation);
|
|
4304
|
+
for(const step of Array.isArray(doc?.steps)?doc.steps:[])if(isObject(step)){scanSim(step.simulation_overrides);scanSim(step.simulation_override);}
|
|
4305
|
+
} catch {}
|
|
4306
|
+
}
|
|
4307
|
+
}
|
|
4308
|
+
try { context.localManifest=JSON.parse(JSON.stringify(compileLocalManifest(context.rawLocalManifest,{simulatedResources}))); }
|
|
4309
|
+
catch { throw new Stop(2,'live-local-manifest-invalid'); }
|
|
4310
|
+
}
|
|
4311
|
+
}
|
|
4312
|
+
async function newLocalBridge(context,kind,requestId) {
|
|
4313
|
+
await ensureLocalSource(context,context.capture);
|
|
4314
|
+
const originalOwner=context.localOwner??context.identity.login;
|
|
4315
|
+
context.auth.expectedOwnerLogin=originalOwner;
|
|
4316
|
+
context.auth.ownerMismatchError=()=>new Stop(5,'live-local-owner-changed');
|
|
4317
|
+
if(context.identity.login!==originalOwner)throw new Stop(5,'live-local-owner-changed');
|
|
4318
|
+
const required=[`owner-local-${kind}-v1`,'private-live-reports-v1'];
|
|
4319
|
+
const capacity=await context.runtime.send('/v1/capacity',{method:'GET'},GET_MS);
|
|
4320
|
+
if(capacity.status!==200||!required.every(value=>capacity.json?.features?.includes(value)))throw new Stop(5,'This interpreter lacks owner-local execution or private live-report support. Nothing was dispatched.');
|
|
4321
|
+
const waitMs=capacity.json?.features?.includes('owner-local-longpoll-v1')?3000:0;
|
|
4322
|
+
try {
|
|
4323
|
+
const finalRuntime=new Runtime({origin:context.origin,token:context.identity.token,ports:context.ports,auth:context.auth});
|
|
4324
|
+
const bridge=await createLocalCommandBridge({manifest:context.localManifest,root:context.root,origin:context.origin,identity:context.identity,requestId,kind,allow_writes:context.allowLiveWrites,source_sha256:context.capture.sha256,...(waitMs>0?{wait_ms:waitMs}:{})},{liveLocal:context.ports.liveLocal,owner:()=>context.identity.login,onReceipt:receipt=>{line(context.ports.stderr,`Local command receipt: ${cleanText(receipt.request_id,context.secrets)} / ${cleanText(receipt.call_id,context.secrets)} (${receipt.status}).`);},request:({method,path,body,signal})=>finalRuntime.send(path,{method,...(signal?{signal}:{}),...(method==='DELETE'?{headers:{'X-Request-Id':context.ports.randomUUID()}}:{}),...(body===undefined?{}:{headers:{'Content-Type':'application/json'},body:JSON.stringify(body)})},waitMs>0&&path.includes('/pending?')?waitMs+5000:5000)});
|
|
4325
|
+
(context.localBridges??=new Map()).set(requestId,bridge);return bridge;
|
|
4326
|
+
} catch(error) { if(error?.unboundPort)throw error;throw new Stop(5,error.code??'live-local-bridge-refused'); }
|
|
4327
|
+
}
|
|
4328
|
+
async function startLocalBridge(context,bridge,id) {
|
|
4329
|
+
try {
|
|
4330
|
+
await bridge.connect(id);
|
|
4331
|
+
const service=bridge.service(context.signal);
|
|
4332
|
+
(context.localServices??=new Map()).set(id,service);
|
|
4333
|
+
service.catch(error=>{context.localBridgeError=error;context.stopped={code:error.code??'live-local-bridge-refused',message:'Owner-local command service stopped. Read the original result; do not replay commands.'};});
|
|
4334
|
+
} catch(error) { throw new Stop(3,error.code??'live-local-bridge-refused'); }
|
|
4335
|
+
}
|
|
4336
|
+
async function closeLocalBridges(context) {
|
|
4337
|
+
await Promise.all([...(context.localBridges?.values()??[])].map(bridge=>bridge.close()));
|
|
4338
|
+
}
|
|
4339
|
+
|
|
3728
4340
|
// All check POSTs use this one run-owned boundary, including sends after a read.
|
|
3729
4341
|
// Its lifetime covers scheduler waits, recovery and every phase of a retry.
|
|
3730
4342
|
async function withCheckRun(context, run) {
|
|
3731
4343
|
let ownership;
|
|
3732
4344
|
context.postCheck = async (request, row, timeoutMs) => {
|
|
4345
|
+
if(context.liveLocal) {
|
|
4346
|
+
const bridge=await newLocalBridge(context,'check',request.requestId);
|
|
4347
|
+
request={...request,resource_mode:'live',resource_setup:bridge.resource_setup};
|
|
4348
|
+
const verdict=await postJob(context,'/v1/check','check',request,row,timeoutMs,context.deadline);
|
|
4349
|
+
if(verdict.kind==='accepted'&&!ENDED.has(verdict.answer?.state))await startLocalBridge(context,bridge,request.requestId);
|
|
4350
|
+
return verdict;
|
|
4351
|
+
}
|
|
4352
|
+
// Probes and diagnostic subsets own no ordinary pass generation or cache identity evidence.
|
|
4353
|
+
if (context.stepIds?.length || context.checkOptions) return postJob(context, '/v1/check', 'check', request, row, timeoutMs, context.deadline);
|
|
3733
4354
|
ownership ??= (async () => {
|
|
3734
4355
|
if (!context.testCache) {
|
|
3735
4356
|
const cache = context.testCache = await openTestCache(context, context.root, false);
|
|
@@ -3756,9 +4377,19 @@ async function withCheckRun(context, run) {
|
|
|
3756
4377
|
// pdd test. Returns the exit code.
|
|
3757
4378
|
export async function runCheck({ words = [], options = {}, cwd = process.cwd(), cache = false, client, workflow } = {}, givenPorts = {}) {
|
|
3758
4379
|
const ports = withDefaults(givenPorts);
|
|
3759
|
-
const context = { ports, clientVersion: client?.version ?? ports.clientVersion ?? null, workflow, singleAttempt: ports.env.PDD_CHECK_SINGLE_ATTEMPT === '1', cacheEnabled: cache || !!options['--lf'] || !!options['--cache-clear'], json: options['--json'] === true, details: Boolean(options['--details'] || options.details), explicitTimeout: options['--timeout'] !== undefined, interrupted: false, warnings: [] };
|
|
4380
|
+
const context = { ports, clientVersion: client?.version ?? ports.clientVersion ?? null, workflow, singleAttempt: ports.env.PDD_CHECK_SINGLE_ATTEMPT === '1', cacheEnabled: cache || !!options['--lf'] || !!options['--cache-clear'], freshChecks: !!options['--cache-clear'], json: options['--json'] === true, details: Boolean(options['--details'] || options.details), explicitTimeout: options['--timeout'] !== undefined, interrupted: false, warnings: [] };
|
|
3760
4381
|
let release = () => {};
|
|
3761
4382
|
try {
|
|
4383
|
+
context.liveLocal=liveLocalOptions(options,'check');
|
|
4384
|
+
if(context.liveLocal){context.singleAttempt=true;context.cacheEnabled=false;}
|
|
4385
|
+
context.checkOptions = sampleOptions(options);
|
|
4386
|
+
if (context.checkOptions) context.cacheEnabled = false;
|
|
4387
|
+
if (!context.checkOptions && options['--step'] !== undefined) {
|
|
4388
|
+
const values = Array.isArray(options['--step']) ? options['--step'] : [options['--step']];
|
|
4389
|
+
if (!values.length || values.some(value=>typeof value !== 'string' || !value.trim())) throw new Stop(2, '--step needs one or more nonblank step IDs.');
|
|
4390
|
+
if (['--read','--retry','--request','--files','--explain-bindings','--lint','--local','--affected','--full','--journeys','--journey','--parts','--screen','--drawing','--look'].some(key=>options[key] !== undefined)) throw new Stop(2, '--step accepts an ordinary new test selection; start a fresh selected pdd test.');
|
|
4391
|
+
context.stepIds = [...new Set(values)]; context.cacheEnabled = false;
|
|
4392
|
+
}
|
|
3762
4393
|
if (options['--affected'] !== undefined && (options['--affected'] !== true || words.length || Object.keys(options).some(key => !['--affected','--json','--details','--timeout','--max-calls','--max-total-calls','--no-restart-replacement','--cache-clear'].includes(key))))
|
|
3763
4394
|
throw new Stop(2, '--affected accepts no Stories and only --cache-clear, --json, --details, --timeout, --max-calls, --max-total-calls and --no-restart-replacement.');
|
|
3764
4395
|
if(options['--journeys']!==undefined){
|
|
@@ -3844,19 +4475,70 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
|
|
|
3844
4475
|
if (typeof ports.lintSvgLayouts !== 'function') throw unboundPortError('SVG layout port (lintSvgLayouts) is not bound.');
|
|
3845
4476
|
try {
|
|
3846
4477
|
const root = repoRoot(cwd), workspace=loadRuntimeWorkspace({root}), files = gitFiles(root).filter(path=>allowsRuntimePath(workspace,path));
|
|
3847
|
-
let promptPaths, selectedTests, tests = [];
|
|
4478
|
+
let promptPaths, selectedTests, derivations = [], tests = [], selectedProblems = [], preflightWarnings = [];
|
|
3848
4479
|
if (words.length) {
|
|
3849
|
-
const { found, normalized } = localSetup(cwd, words, ports)
|
|
3850
|
-
|
|
3851
|
-
|
|
3852
|
-
|
|
4480
|
+
const { found, normalized } = localSetup(cwd, words, ports);
|
|
4481
|
+
if (normalized.every(word => word.endsWith('.prompt.md') && found.visible.has(word))) {
|
|
4482
|
+
promptPaths = [...new Set(normalized)].sort();
|
|
4483
|
+
selectedTests = [];
|
|
4484
|
+
selectedProblems = interfaceFindings({ root, paths: promptPaths }).filter(problem => localInterfaceProblem(problem) && problem.code !== 'interface-missing');
|
|
4485
|
+
} else {
|
|
4486
|
+
const selected = select(found, normalized, root, ports);
|
|
4487
|
+
selectedTests = selected;
|
|
4488
|
+
const checked = preflight({root,found,selected,workspace,allowMissingInterfaces:true,localLint:true});
|
|
4489
|
+
preflightWarnings = checked.warnings;
|
|
4490
|
+
selectedProblems = checked.rows.flatMap(row => row.refusals.map(problem => ({code:problem.code,path:problem.path ?? row.test,
|
|
4491
|
+
section:problem.section ?? 'scenario',message:`${row.test}: ${problem.message}${problem.hint ? ` ${problem.hint}` : ''}`})));
|
|
4492
|
+
tests = selected.filter(test => !test.error).map(test => test.path);
|
|
4493
|
+
const admittedTests = checked.rows.filter(row => !row.refusals.length).map(row => row.test);
|
|
4494
|
+
const inspected = new Set(), inspect = tests => {
|
|
4495
|
+
const captured = ports.captureSource(root,{tests,appMap:null,allowMissingInterfaces:true});
|
|
4496
|
+
for (const file of captured.files) if (file.path.endsWith('.prompt.md')) inspected.add(file.path);
|
|
4497
|
+
};
|
|
4498
|
+
// Completed preflight refusals survive a sibling's dependency failure.
|
|
4499
|
+
// Capture-only and aggregate failures retain their existing handling.
|
|
4500
|
+
if (admittedTests.length) try { inspect(admittedTests); }
|
|
4501
|
+
catch (error) {
|
|
4502
|
+
if (!selectedProblems.length || !sourceUnavailable(error)) throw error;
|
|
4503
|
+
let broken = false;
|
|
4504
|
+
for (const test of admittedTests) try { inspect([test]); }
|
|
4505
|
+
catch (own) {
|
|
4506
|
+
if (!sourceUnavailable(own)) throw own;
|
|
4507
|
+
broken = true;
|
|
4508
|
+
selectedProblems.push({code:own.code ?? 'source-unavailable',path:test,section:own.section ?? 'source',
|
|
4509
|
+
message:`${test}: ${own.message} ${own.hint ?? 'Restore the named dependency, make it readable, or correct its declared path.'}`});
|
|
4510
|
+
}
|
|
4511
|
+
if (!broken) throw error;
|
|
4512
|
+
}
|
|
4513
|
+
const seen = new Set(), visit = path => {
|
|
4514
|
+
if (typeof path !== 'string' || seen.has(path) || !found.visible.has(path) || !files.includes(path) || !path.endsWith('.prompt.md')) return;
|
|
4515
|
+
seen.add(path);
|
|
4516
|
+
let prompt;
|
|
4517
|
+
try { prompt = readPrompt(root,found.visible,path,workspace); }
|
|
4518
|
+
catch (error) { if (error instanceof PreflightError && error.exitCode === 4) return; throw error; }
|
|
4519
|
+
if (typeof prompt.text !== 'string') return;
|
|
4520
|
+
inspected.add(path);
|
|
4521
|
+
for (const call of Array.isArray(prompt.interface?.calls) ? prompt.interface.calls : []) visit(call?.target);
|
|
4522
|
+
if (prompt.error === 'interface-missing' || prompt.frontmatter) for (const target of promptMarkdownTargets(prompt.text,path,found.visible)) visit(target);
|
|
4523
|
+
};
|
|
4524
|
+
for (const path of entryPaths(selected)) visit(path);
|
|
4525
|
+
promptPaths = [...inspected].sort();
|
|
4526
|
+
}
|
|
3853
4527
|
}
|
|
3854
|
-
|
|
3855
|
-
|
|
3856
|
-
|
|
4528
|
+
if (!words.length) {
|
|
4529
|
+
const {found} = localSetup(cwd, [], ports);
|
|
4530
|
+
derivations = derivationProblems(root, found, found.tests);
|
|
4531
|
+
}
|
|
4532
|
+
// Story selections share offline preflight; repository scans retain their declaration checks.
|
|
4533
|
+
const problems = words.length ? selectedProblems : [...interfaceFindings({root,paths:promptPaths}).filter(problem => localInterfaceProblem(problem) && problem.code !== 'interface-missing'), ...derivations];
|
|
4534
|
+
const inspectedPrompts = promptPaths ?? files.filter(path => path.endsWith('.prompt.md'));
|
|
4535
|
+
const advice = formatAdvice(root, new Set(gitFiles(root)), inspectedPrompts, workspace);
|
|
4536
|
+
const { selectorLintForPrompts } = await import('./try-doors.mjs');
|
|
4537
|
+
const selectorInfo = selectorLintForPrompts({ root, visible: new Set(gitFiles(root)), paths: inspectedPrompts, workspace });
|
|
4538
|
+
context.selectorTableLines = selectorInfo.tableLines;
|
|
3857
4539
|
const hygiene = lintLocalHygiene({ root, files, promptPaths, tests: selectedTests, workspace }, ports);
|
|
3858
|
-
const warnings = [...new Set([...advice, ...ports.lintSvgLayouts({ root, files, promptPaths }), ...hygiene])], summary = `partial: checked SVG layout only; prompts not checked (local-only). ${warnings.length} warnings. 0 AI calls. No checks were sent.`;
|
|
3859
|
-
const result = saveLocalLayout(context,{root,tests,prompts:promptPaths ?? files.filter(path => path.endsWith('.prompt.md')),warnings,problems,summary});
|
|
4540
|
+
const warnings = [...new Set([...advice, ...selectorInfo.warnings, ...preflightWarnings, ...ports.lintSvgLayouts({ root, files, promptPaths }), ...hygiene])], summary = `partial: checked SVG layout only; prompts not checked (local-only). ${warnings.length} warnings. 0 AI calls. No checks were sent.`;
|
|
4541
|
+
const result = await saveLocalLayout(context,{root,tests,prompts:promptPaths ?? files.filter(path => path.endsWith('.prompt.md')),warnings,problems,summary});
|
|
3860
4542
|
return printLocalLayout(context,result);
|
|
3861
4543
|
} catch (error) { if (error?.unboundPort) throw error; throw new Stop(2, error.message); }
|
|
3862
4544
|
}
|
|
@@ -3869,6 +4551,7 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
|
|
|
3869
4551
|
if (modes[0] === '--explain-bindings') return runExplainBindings(cwd, words, options, ports);
|
|
3870
4552
|
if (modes[0] === '--files') return runFiles(cwd, words, options, ports);
|
|
3871
4553
|
context.root = root; context.store = stateFor(ports.env, root);
|
|
4554
|
+
await prepareLiveManifest(context,options,root);
|
|
3872
4555
|
return await withCheckRun(context, async () => {
|
|
3873
4556
|
if (modes[0] === '--retry') { release = interruptible(context); return await runRetry(context, options['--retry'], options); }
|
|
3874
4557
|
if (modes[0] === '--read') { release = interruptible(context); return UUID.test(words[0] ?? '') ? await runCallRead(context, words[0]) : await runRead(context, words[0], false, options); }
|
|
@@ -3898,6 +4581,7 @@ export async function runCheck({ words = [], options = {}, cwd = process.cwd(),
|
|
|
3898
4581
|
}
|
|
3899
4582
|
throw error;
|
|
3900
4583
|
} finally {
|
|
4584
|
+
await closeLocalBridges(context);
|
|
3901
4585
|
try { context.releaseBatch?.(); }
|
|
3902
4586
|
catch (error) {
|
|
3903
4587
|
try { line(ports.stderr, `Warning: could not release batch ${context.lockedBatch ?? context.batch ?? 'ownership'} (${cleanText(error.code ?? 'state error')}).`); } catch { /* preserve the command outcome */ }
|
|
@@ -4463,8 +5147,14 @@ async function runBatch(context, cwd, words, options, setRelease) {
|
|
|
4463
5147
|
context.agentLimit = false;
|
|
4464
5148
|
context.timeoutMin = options['--timeout'] !== undefined ? Number(options['--timeout']) : null;
|
|
4465
5149
|
let selected = select(found, normalized, root, ports);
|
|
5150
|
+
const diagnostic = context.stepIds?.length > 0;
|
|
5151
|
+
const preliminary = diagnostic ? preflight({root,found,selected,allowMissingInterfaces:true,stepIds:context.stepIds}) : null;
|
|
5152
|
+
if (preliminary && preliminary.rows.every(row=>row.refusals.length)) { context.rows = localRows(preliminary.rows); return printResult(context,context.rows); }
|
|
5153
|
+
if (diagnostic) selected = selected.map(test=>({...test,doc:{...test.doc,steps:preliminary.rows.find(row=>row.test===test.path)?.steps ?? []}}));
|
|
5154
|
+
validateSampleSelection(selected, context.checkOptions, root, found);
|
|
4466
5155
|
const inventory = selected;
|
|
4467
|
-
const
|
|
5156
|
+
const invalidDerivations = new Set(derivationProblems(root, found, inventory).map(problem => problem.path));
|
|
5157
|
+
const allowMissingInterfaces = hasMissingPromptInterface(root, found, entryPaths(inventory.filter(test => !invalidDerivations.has(test.path))))
|
|
4468
5158
|
? await probeLazyInterfaces(context, origin, context.store) : false;
|
|
4469
5159
|
const affected = options['--affected'] === true;
|
|
4470
5160
|
const resolveWorkflowBase = () => {
|
|
@@ -4556,12 +5246,12 @@ async function runBatch(context, cwd, words, options, setRelease) {
|
|
|
4556
5246
|
const failures = selected.filter(test => cache.failed[test.storyPath] === true);
|
|
4557
5247
|
if (failures.length) selected = failures;
|
|
4558
5248
|
}
|
|
4559
|
-
if (options['--cache-clear']) {
|
|
5249
|
+
if (options['--cache-clear'] && !diagnostic) {
|
|
4560
5250
|
const count = new Set(selected.map(test => test.storyPath ?? test.path)).size;
|
|
4561
|
-
line(ports.stderr, `pdd: test cache ${cache && !cache.disabled ? 'cleared' : 'unavailable'}. Running ${count} selected ${count === 1 ? 'Story' : 'Stories'};
|
|
5251
|
+
line(ports.stderr, `pdd: test cache ${cache && !cache.disabled ? 'cleared' : 'unavailable'}. Running ${count} selected ${count === 1 ? 'Story' : 'Stories'}; requesting fresh interpreter checks.`);
|
|
4562
5252
|
}
|
|
4563
|
-
context.coverage = bindingCoverage({ root, found, selected, includeRuntime:true, allowMissingInterfaces });
|
|
4564
|
-
const checked = preflight({ root, found, selected, allowMissingInterfaces });
|
|
5253
|
+
context.coverage = diagnostic ? {available:false,bound:null,total:null,modules:[],reason:'diagnostic subset'} : bindingCoverage({ root, found, selected, includeRuntime:true, allowMissingInterfaces });
|
|
5254
|
+
const checked = preflight({ root, found, selected, allowMissingInterfaces, ...(diagnostic ? {stepIds:context.stepIds} : {}) });
|
|
4565
5255
|
const rows = localRows(checked.rows);
|
|
4566
5256
|
context.rows = rows;
|
|
4567
5257
|
for (const row of rows) {
|
|
@@ -4574,8 +5264,12 @@ async function runBatch(context, cwd, words, options, setRelease) {
|
|
|
4574
5264
|
...(row.not_checked??[]).map(item=>[item.criterion_id,item.text])]);
|
|
4575
5265
|
}
|
|
4576
5266
|
if (options['--max-calls'] !== undefined) for (const row of rows) row.max_calls = Number(options['--max-calls']);
|
|
5267
|
+
if (context.checkOptions) for (const row of rows) {
|
|
5268
|
+
if (context.checkOptions.samples > row.max_calls) throw new Stop(2, 'samples exceeds this test’s total max_calls allowance.');
|
|
5269
|
+
if (context.checkOptions.step_ids && context.checkOptions.step_ids.length < row.steps.length) Object.assign(row,{sample_subset:true,diagnostic_subset:true,selected_steps:[...context.checkOptions.step_ids]});
|
|
5270
|
+
}
|
|
4577
5271
|
base ??= resolveWorkflowBase();
|
|
4578
|
-
context.checkPlan = affected ? planFor(rows) : buildCheckPlan({root,found,selected,rows,full:words.length === 0,base,allowMissingInterfaces,...planPolicyOptions},planningPorts);
|
|
5272
|
+
context.checkPlan = diagnostic ? null : affected ? planFor(rows) : buildCheckPlan({root,found,selected,rows,full:words.length === 0,base,allowMissingInterfaces,...planPolicyOptions},planningPorts);
|
|
4579
5273
|
if (affected) {
|
|
4580
5274
|
const finalSelection = selectCheckTests(context.checkPlan,{affected:true});
|
|
4581
5275
|
if (discoveryChanged || !isDeepStrictEqual(finalSelection.tests,context.checkSelection.tests)) return restartConservatively();
|
|
@@ -4583,15 +5277,15 @@ async function runBatch(context, cwd, words, options, setRelease) {
|
|
|
4583
5277
|
discover();
|
|
4584
5278
|
if (discoveryChanged) return restartConservatively();
|
|
4585
5279
|
}
|
|
4586
|
-
for (const value of checkPlanLines(context.checkPlan)) line(ports.stderr, value);
|
|
4587
|
-
if (!words.length && context.checkPlan
|
|
5280
|
+
for (const value of context.checkPlan ? checkPlanLines(context.checkPlan) : []) line(ports.stderr, value);
|
|
5281
|
+
if (!words.length && context.checkPlan?.prerequisites.length) {
|
|
4588
5282
|
const note = {code:'check-plan-prerequisite',message:checkPlanResults(context.checkPlan,rows).guidance};
|
|
4589
5283
|
for (const row of rows) {
|
|
4590
5284
|
if (row.state === 'ready') Object.assign(row,{state:'not_run',calls:0,phase:'local'});
|
|
4591
5285
|
if (row.state !== 'passed') row.note = note;
|
|
4592
5286
|
}
|
|
4593
5287
|
context.warnings.push('Full check blocked by a check-plan prerequisite. 0 AI calls. No checks were sent.');
|
|
4594
|
-
saveLocalNativeResult(context,rows,'check');
|
|
5288
|
+
await saveLocalNativeResult(context,rows,'check');
|
|
4595
5289
|
printResult(context,rows);
|
|
4596
5290
|
return 4;
|
|
4597
5291
|
}
|
|
@@ -4600,10 +5294,10 @@ async function runBatch(context, cwd, words, options, setRelease) {
|
|
|
4600
5294
|
context.warnings.push(...found.warnings, ...checked.warnings, ...sharedSourceFiles(root, found.discoveryVisible ?? found.visible, { ...(scopedOwnership ? { tests: selected } : {}), workspace: found.workspace }, ports));
|
|
4601
5295
|
context.unmatched = unmatchedLines(found);
|
|
4602
5296
|
if (cache) await beginTestAttempts(cache, rows.filter(row => row.state !== 'ready'), null, options, origin);
|
|
4603
|
-
if (!rows.some(row => row.state === 'ready')) { if (rows.some(row => row.native_only?.length)) saveLocalNativeResult(context, rows, 'check'); return printResult(context, rows); }
|
|
5297
|
+
if (!rows.some(row => row.state === 'ready')) { if (rows.some(row => row.native_only?.length)) await saveLocalNativeResult(context, rows, 'check'); return printResult(context, rows); }
|
|
4604
5298
|
context.nativeSource = nativeSourceIdentity(context, rows);
|
|
4605
5299
|
let capture;
|
|
4606
|
-
try { capture = captureIndependent(root, rows, ports, {appMap:null,excludeFixtureProjects:words.length === 0,...(allowMissingInterfaces ? {allowMissingInterfaces:true} : {})}); }
|
|
5300
|
+
try { capture = captureIndependent(root, rows, ports, {appMap:null,excludeFixtureProjects:words.length === 0,...(diagnostic ? {stepIds:context.stepIds} : {}),...(allowMissingInterfaces ? {allowMissingInterfaces:true} : {})}); }
|
|
4607
5301
|
catch (error) { if (cache) await beginTestAttempts(cache, rows, null, options, origin); throw error; }
|
|
4608
5302
|
if (!capture || !rows.some(row=>row.state==='ready')) {
|
|
4609
5303
|
if (cache) await beginTestAttempts(cache,rows,null,options,origin);
|
|
@@ -4643,6 +5337,7 @@ async function runBatch(context, cwd, words, options, setRelease) {
|
|
|
4643
5337
|
const validated = selectCheckTests(planFor([]),{affected:true});
|
|
4644
5338
|
if (discoveryChanged || !isDeepStrictEqual(validated.tests,context.checkSelection.tests)) return restartConservatively();
|
|
4645
5339
|
}
|
|
5340
|
+
if(context.liveLocal)context.localOwner??=identity.login;
|
|
4646
5341
|
const startedAt = ports.now(), batch = batchId(startedAt, ports.randomUUID);
|
|
4647
5342
|
const head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
|
|
4648
5343
|
Object.assign(context, { capture, identity, batch, startedAt, deadline: Infinity, rows,
|
|
@@ -4651,10 +5346,11 @@ async function runBatch(context, cwd, words, options, setRelease) {
|
|
|
4651
5346
|
setRelease(interruptible(context));
|
|
4652
5347
|
await ownBatch(context, batch);
|
|
4653
5348
|
saveBatch(context);
|
|
4654
|
-
|
|
4655
|
-
context.store.saveRepo(root, { ...repoState, last_batch: batch });
|
|
5349
|
+
await context.store.updateRepo(root, current => ({ ...current, last_batch: batch }));
|
|
4656
5350
|
context.auth = authSession({ identity, store: context.store, ports, secrets: context.secrets, onRefresh: next => { context.identity = next; saveBatch(context); } });
|
|
4657
5351
|
context.runtime = new Runtime({ origin, token: identity.token, ports, signal: context.signal, auth: context.auth });
|
|
5352
|
+
if(context.liveLocal){context.auth.expectedOwnerLogin=context.localOwner;context.auth.ownerMismatchError=()=>new Stop(5,'live-local-owner-changed');}
|
|
5353
|
+
await ensureLocalSource(context,capture);
|
|
4658
5354
|
await checkBatch(context, fresh);
|
|
4659
5355
|
if (cache) {
|
|
4660
5356
|
const observed = context.observedTestIdentities ?? [];
|
|
@@ -4816,12 +5512,13 @@ function simulationSelection(root, found, words, appMap, options, ports) {
|
|
|
4816
5512
|
return { test: seed, selected, tab, typed: typed && tab === 'call' && options['--serve'] === undefined };
|
|
4817
5513
|
}
|
|
4818
5514
|
|
|
4819
|
-
async function readUntil(context, id, command, isDone, ms, label) {
|
|
5515
|
+
async function readUntil(context, id, command, isDone, ms, label, acceptAnswer = null) {
|
|
4820
5516
|
const end = Math.min(context.deadline ?? Infinity, context.ports.now() + ms), tick = progressTicker(context.ports.stderr, context.ports.now);
|
|
4821
5517
|
let last = null;
|
|
4822
5518
|
for (;;) {
|
|
4823
5519
|
if (context.interrupted || context.ports.now() >= end) return { answer: last, open: true };
|
|
4824
5520
|
const read = judgeGet(await context.runtime.get(id, Math.max(1, Math.min(GET_MS, end - context.ports.now()))), id, command);
|
|
5521
|
+
if (read.kind === 'state' && acceptAnswer && !acceptAnswer(read.answer)) return { unknownWhy: 'The receipt could not be verified.' };
|
|
4825
5522
|
if (read.kind === 'state') { last = read.answer; queueProgress(context, last); context.store.write(join(context.store.folder('tries'), `${id}.json`), last); if (isDone(last)) return { answer: last }; }
|
|
4826
5523
|
else if (read.kind === 'unknown') return { unknownWhy: read.why };
|
|
4827
5524
|
else if (read.kind === 'auth') throw new Stop(5, AUTH_TEXT);
|
|
@@ -4931,32 +5628,838 @@ function tryPromptProblem(root, found, test, record, capture, ports) {
|
|
|
4931
5628
|
}
|
|
4932
5629
|
|
|
4933
5630
|
|
|
5631
|
+
// Git's common exclude file also protects linked worktrees without changing
|
|
5632
|
+
// authored files. Require the directory itself to be excluded so temporary
|
|
5633
|
+
// worlds are protected too. Recheck before every save; higher-priority negation
|
|
5634
|
+
// or tracked data must fail closed rather than publish a private world into Git.
|
|
5635
|
+
function protectProgramData(root, data) {
|
|
5636
|
+
try {
|
|
5637
|
+
const fs = nativeCacheFiles, exclude = fs.exclude(root);
|
|
5638
|
+
safeCachePath(fs, dirname(exclude), { directory: true, create: true });
|
|
5639
|
+
safeCachePath(fs, exclude);
|
|
5640
|
+
const stat = cacheStat(fs, exclude);
|
|
5641
|
+
if (stat && (stat.size > CACHE_LIMIT || stat.nlink !== 1)) throw new Error('unsafe Git exclude');
|
|
5642
|
+
const text = stat ? fs.read(exclude, 'utf8') : '';
|
|
5643
|
+
if (!text.split(/\r?\n/).includes('/.pdd/run/')) {
|
|
5644
|
+
const fd = openSync(exclude, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
|
|
5645
|
+
try {
|
|
5646
|
+
const current = fstatSync(fd);
|
|
5647
|
+
if (!current.isFile() || current.nlink !== 1) throw new Error('unsafe Git exclude');
|
|
5648
|
+
writeFileSync(fd, `${text.endsWith('\n') || !text ? '' : '\n'}/.pdd/run/\n`); fsyncSync(fd);
|
|
5649
|
+
} finally { closeSync(fd); }
|
|
5650
|
+
}
|
|
5651
|
+
for (const path of [relative(root, dirname(data)) + '/', relative(root, data)]) {
|
|
5652
|
+
const checked = spawnSync('git', ['check-ignore', '-q', '--', path], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
5653
|
+
if (checked.status !== 0) throw new Error('program data is not ignored');
|
|
5654
|
+
}
|
|
5655
|
+
} catch { throw new Stop(2, 'Private program data must be Git-ignored before use. Check the Git exclude file and any tracked data or ignore overrides.'); }
|
|
5656
|
+
}
|
|
5657
|
+
|
|
5658
|
+
// Program worlds are repository-local data. Session identities and pending request IDs
|
|
5659
|
+
// remain in the private store, separate from Story records and authored scenarios.
|
|
5660
|
+
// Keep ordinary exact Numbers usable by callers. Unsafe integer literals and
|
|
5661
|
+
// inexact numbers retain their source tokens through JSON transport and custody.
|
|
5662
|
+
// Numeric identity belongs only to comparison, never to serialized world data.
|
|
5663
|
+
function programJsonNumber(value, source) {
|
|
5664
|
+
const identity = jsonNumberIdentity(parseJsonValue(source));
|
|
5665
|
+
if (/^-?\d+$/.test(source) && !Number.isSafeInteger(value)) return JSON.rawJSON(source);
|
|
5666
|
+
return Number.isFinite(value) && jsonNumberIdentity(value) === identity ? (value === 0 ? 0 : value) : JSON.rawJSON(source);
|
|
5667
|
+
}
|
|
5668
|
+
function parseProgramJson(text) {
|
|
5669
|
+
return JSON.parse(text, (_key, value, context) => typeof value === 'number' ? programJsonNumber(value, context.source) : value);
|
|
5670
|
+
}
|
|
5671
|
+
function sameProgramWorld(left, right) {
|
|
5672
|
+
const identity = value => {
|
|
5673
|
+
if (typeof value === 'number' || JSON.isRawJSON(value)) return JSON.rawJSON(jsonNumberIdentity(typeof value === 'number' ? value : parseJsonValue(value.rawJSON)));
|
|
5674
|
+
if (Array.isArray(value)) return value.map(identity);
|
|
5675
|
+
if (isObject(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, identity(item)]));
|
|
5676
|
+
return value;
|
|
5677
|
+
};
|
|
5678
|
+
// Native raw JSON has a null prototype, distinct from authored rawJSON objects.
|
|
5679
|
+
return isDeepStrictEqual(identity(left), identity(right));
|
|
5680
|
+
}
|
|
5681
|
+
const programObject = value => isObject(value) && !JSON.isRawJSON(value);
|
|
5682
|
+
function programFiles(root, entry, store) {
|
|
5683
|
+
if (typeof entry !== 'string' || !entry.endsWith('.prompt.md') || entry !== relative(root, resolve(root, entry)).split(sep).join('/') || entry.startsWith('../')) throw new Stop(2, 'The program entry must be a canonical repository-relative prompt path.');
|
|
5684
|
+
protectProgramData(root, join(root, '.pdd', 'run', encodeURIComponent(entry), 'data.json'));
|
|
5685
|
+
let directory = root;
|
|
5686
|
+
for (const name of ['.pdd', 'run', encodeURIComponent(entry)]) {
|
|
5687
|
+
directory = join(directory, name);
|
|
5688
|
+
try { mkdirSync(directory, { mode: 0o700 }); } catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
5689
|
+
const stat = lstatSync(directory);
|
|
5690
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Stop(2, 'Refusing an unsafe program state folder.');
|
|
5691
|
+
}
|
|
5692
|
+
const data = join(directory, 'data.json'), meta = join(store.folder('programs'), `${sha256(root + '\0' + entry)}.json`);
|
|
5693
|
+
const stateFolder = lstatSync(directory);
|
|
5694
|
+
const safeDirectory = () => {
|
|
5695
|
+
let path = root;
|
|
5696
|
+
for (const part of ['.pdd', 'run', encodeURIComponent(entry)]) {
|
|
5697
|
+
path = join(path, part); const stat = lstatSync(path);
|
|
5698
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Stop(2, 'Refusing an unsafe program state folder.');
|
|
5699
|
+
}
|
|
5700
|
+
const current = lstatSync(directory);
|
|
5701
|
+
if (current.dev !== stateFolder.dev || current.ino !== stateFolder.ino) throw new Stop(2, 'The program state folder changed. Reopen the program.');
|
|
5702
|
+
};
|
|
5703
|
+
const regular = path => {
|
|
5704
|
+
const stat = statOrNull(path);
|
|
5705
|
+
if (stat && (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1)) throw new Stop(2, 'Refusing an unsafe program state file.');
|
|
5706
|
+
return stat;
|
|
5707
|
+
};
|
|
5708
|
+
regular(data);
|
|
5709
|
+
const read = () => {
|
|
5710
|
+
safeDirectory();
|
|
5711
|
+
if (!regular(data)) return {};
|
|
5712
|
+
const fd = openSync(data, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
5713
|
+
try {
|
|
5714
|
+
const stat = fstatSync(fd); if (!stat.isFile() || stat.nlink !== 1) throw new Stop(2, 'Refusing an unsafe program state file.');
|
|
5715
|
+
const world = parseProgramJson(readFileSync(fd, 'utf8')); if (!programObject(world)) throw new Stop(2, 'Saved program data must be a JSON object.'); return world;
|
|
5716
|
+
} finally { closeSync(fd); }
|
|
5717
|
+
};
|
|
5718
|
+
const save = world => {
|
|
5719
|
+
if (!programObject(world)) throw new Stop(3, 'The interpreter did not confirm an exact program world. The last saved data is kept.');
|
|
5720
|
+
safeDirectory(); regular(data); protectProgramData(root, data);
|
|
5721
|
+
const temp = join(directory, `.data-${randomUUID()}.tmp`), fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
5722
|
+
try { writeFileSync(fd, JSON.stringify(world) + '\n'); fsyncSync(fd); } finally { closeSync(fd); }
|
|
5723
|
+
try { safeDirectory(); regular(data); renameSync(temp, data); const dir = openSync(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); try { fsyncSync(dir); } finally { closeSync(dir); } }
|
|
5724
|
+
finally { try { unlinkSync(temp); } catch {} }
|
|
5725
|
+
};
|
|
5726
|
+
const lock = () => {
|
|
5727
|
+
safeDirectory();
|
|
5728
|
+
const path = join(directory, '.lock'); let fd;
|
|
5729
|
+
try { fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); }
|
|
5730
|
+
catch { throw new Stop(3, 'This program is busy or its state lock needs inspection. No new action was sent.'); }
|
|
5731
|
+
const held = fstatSync(fd);
|
|
5732
|
+
return () => { closeSync(fd); const current = statOrNull(path); if (current?.dev === held.dev && current.ino === held.ino) unlinkSync(path); };
|
|
5733
|
+
};
|
|
5734
|
+
return { read, save, lock, get: () => {
|
|
5735
|
+
safeDirectory(); if (!regular(meta)) return null;
|
|
5736
|
+
let value; try { value = parseProgramJson(readFileSync(meta, 'utf8')); } catch { throw new Stop(3, 'The saved program session record is unreadable. No replacement was sent.'); }
|
|
5737
|
+
if (value !== null && (!isObject(value) || !UUID.test(value.id ?? '') || value.entry !== entry)) throw new Stop(3, 'The saved program session record is invalid. No replacement was sent.');
|
|
5738
|
+
return value;
|
|
5739
|
+
}, set: value => { safeDirectory(); store.write(meta, value); } };
|
|
5740
|
+
}
|
|
5741
|
+
const programVersion = value => typeof value === 'string' && /^[0-9a-f]{32}:[1-9][0-9]*$/.test(value) ? value.split(':') : null;
|
|
5742
|
+
function releaseRefusedProgramAction(files, kind, id) {
|
|
5743
|
+
const current = files.get();
|
|
5744
|
+
if (current?.pending?.kind === kind && current.pending.id === id) {
|
|
5745
|
+
const { pending, ...released } = current; files.set(released);
|
|
5746
|
+
}
|
|
5747
|
+
}
|
|
5748
|
+
async function syncProgramWorld(runtime, files, record) {
|
|
5749
|
+
let reply = await runtime.send(`/v1/try/${record.id}/world?after=${encodeURIComponent(record.world_version ?? '0')}`, { method: 'GET' }, GET_MS);
|
|
5750
|
+
if (reply.status === 409 && reply.json?.error?.code === 'world-cursor-reset') {
|
|
5751
|
+
reply = await runtime.send(`/v1/try/${record.id}/world?after=0`, { method: 'GET' }, GET_MS);
|
|
5752
|
+
record = { ...record, world_version: null };
|
|
5753
|
+
}
|
|
5754
|
+
if (reply.status === 204 && programVersion(record.world_version)) return record;
|
|
5755
|
+
const version = programVersion(reply.json?.version), prior = programVersion(record.world_version);
|
|
5756
|
+
if (reply.status !== 200 || !version || !programObject(reply.json?.world)) throw new Stop(3, 'The current exact program world is not confirmed. The last saved data is kept; read this session again.');
|
|
5757
|
+
if (prior && prior[0] === version[0] && BigInt(version[1]) < BigInt(prior[1])) throw new Stop(3, 'An older program world was refused. The last saved data is kept.');
|
|
5758
|
+
if (record.world_version === reply.json.version && !sameProgramWorld(files.read(), reply.json.world)) throw new Stop(3, 'The same program version returned different data. The last saved data is kept.');
|
|
5759
|
+
if (prior && prior[0] !== version[0] && record.world_version) throw new Stop(3, 'The program world epoch changed without a reset response. Read this session again.');
|
|
5760
|
+
files.save(reply.json.world);
|
|
5761
|
+
const next = { ...record, world_version: reply.json.version }; files.set(next); return next;
|
|
5762
|
+
}
|
|
5763
|
+
async function commitProgramAction(runtime, files, record, terminal, beforeWorld) {
|
|
5764
|
+
// Keep the terminal evidence even when the committed-world read is unavailable.
|
|
5765
|
+
// Its original dispatch cursor survives a successful snapshot save and a retry.
|
|
5766
|
+
const pending = { ...record.pending, terminal };
|
|
5767
|
+
record = { ...record, pending }; files.set(record);
|
|
5768
|
+
if (beforeWorld) await beforeWorld();
|
|
5769
|
+
const next = await syncProgramWorld(runtime, files, record);
|
|
5770
|
+
const previousVersion = pending.world_version ?? record.world_version;
|
|
5771
|
+
if (next.world_version === previousVersion && pending.kind === 'call' && !sameProgramWorld(files.read(), terminal.world)) {
|
|
5772
|
+
throw new Stop(125, 'The exact call world is not yet committed. The original request ID and last saved data are kept.');
|
|
5773
|
+
}
|
|
5774
|
+
delete next.pending; files.set(next); return next;
|
|
5775
|
+
}
|
|
5776
|
+
async function recoverProgramAction(runtime, files, record) {
|
|
5777
|
+
if (!record.pending) return syncProgramWorld(runtime, files, record);
|
|
5778
|
+
const pending = record.pending;
|
|
5779
|
+
if (pending.terminal) return commitProgramAction(runtime, files, record, pending.terminal);
|
|
5780
|
+
const reply = pending.kind === 'call' ? await runtime.get(pending.id)
|
|
5781
|
+
: await runtime.send(`/v1/try/${record.id}/screen/api/action?id=${encodeURIComponent(pending.id)}`, { method: 'GET' }, GET_MS);
|
|
5782
|
+
const confirmed = pending.kind === 'call' ? reply.status === 200 && sameJob(reply.json, pending.id, 'call') && (!reply.json.session_id || reply.json.session_id === record.id) && ['passed', 'failed', 'refused', 'not_run'].includes(reply.json?.state) && isObject(reply.json?.result?.world)
|
|
5783
|
+
: reply.status === 200 && reply.json?.action?.action_id === pending.id && ['passed', 'failed', 'refused'].includes(reply.json?.action?.verdict);
|
|
5784
|
+
if (!confirmed) throw new Stop(3, `Program action ${pending.id} is not confirmed. Its original ID is kept; no action was repeated.`);
|
|
5785
|
+
const terminal = pending.kind === 'call' ? { state: reply.json.state, world: reply.json.result.world, replayed: reply.json.result.report?.replayed === true } : reply.json.action;
|
|
5786
|
+
return commitProgramAction(runtime, files, record, terminal);
|
|
5787
|
+
}
|
|
5788
|
+
function programSelection(cwd, word, ports, givenMap) {
|
|
5789
|
+
const root = realpathSync(repoRoot(cwd)), visible = new Set(gitFiles(root)), workspace = loadRuntimeWorkspace({ root });
|
|
5790
|
+
const canonical = raw => {
|
|
5791
|
+
const path = relative(root, resolve(cwd, raw)).split(sep).join('/');
|
|
5792
|
+
if (!path || path.startsWith('../') || !visible.has(path)) throw new Stop(2, 'Select a Git-visible prompt or app-map.json inside this repository.');
|
|
5793
|
+
requireRuntimePath(workspace, { path, from: 'Program selection' }); return path;
|
|
5794
|
+
};
|
|
5795
|
+
const selected = canonical(word), isMap = basename(selected) === 'app-map.json';
|
|
5796
|
+
const mapEntry = (path, explicit = false) => {
|
|
5797
|
+
requireRuntimePath(workspace, { path, from: 'Program app map' });
|
|
5798
|
+
let map;
|
|
5799
|
+
try { map = JSON.parse(sourceFilePort(root, visible).read({ path }).content); }
|
|
5800
|
+
catch (error) { if (error instanceof RuntimeWorkspaceError) throw error; throw new Stop(2, 'Select a readable app map containing valid JSON.'); }
|
|
5801
|
+
if (!isObject(map) || map.schema_version !== 'prompt-runtime.app-map.v1' || !Array.isArray(map.screens)) throw new Stop(2, 'Select a valid app map with executable screens.');
|
|
5802
|
+
if (explicit && (typeof map.name !== 'string' || !map.name)) throw new Stop(2, 'The selected app map has no name. See RUNBOOK.md §13.');
|
|
5803
|
+
const initial = map.screens.find(screen => screen.id === map.initial_screen), first = initial?.source === 'operation' ? initial : map.screens.find(screen => screen.source === 'operation');
|
|
5804
|
+
if (!first || typeof first.prompt_path !== 'string' || !first.prompt_path.endsWith('.prompt.md') || !visible.has(first.prompt_path)) throw new Stop(2, 'This app map has no executable prompt.');
|
|
5805
|
+
return first.prompt_path;
|
|
5806
|
+
};
|
|
5807
|
+
const entry = isMap ? mapEntry(selected) : selected;
|
|
5808
|
+
let appMap = isMap ? selected : null;
|
|
5809
|
+
if (givenMap !== undefined) {
|
|
5810
|
+
if (typeof givenMap !== 'string' || !givenMap) throw new Stop(2, '--app-map needs a Git-visible map path. See RUNBOOK.md §13.');
|
|
5811
|
+
const path = canonical(givenMap);
|
|
5812
|
+
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.');
|
|
5813
|
+
appMap = path;
|
|
5814
|
+
}
|
|
5815
|
+
if (!appMap) for (const path of ['app-map.json', 'app/app-map.json']) {
|
|
5816
|
+
if (!visible.has(path) || !allowsRuntimePath(workspace, path)) continue;
|
|
5817
|
+
try { if (mapEntry(path) === entry) { appMap = path; break; } } catch { /* An unrelated map cannot enlarge this program. */ }
|
|
5818
|
+
}
|
|
5819
|
+
const validatePinnedMap = path => {
|
|
5820
|
+
if (!visible.has(path) || mapEntry(path) !== entry) throw new Stop(4, 'The pinned program source or map changed. Use --new after reconciling this session.');
|
|
5821
|
+
return path;
|
|
5822
|
+
};
|
|
5823
|
+
return { root, visible, entry, appMap, validatePinnedMap, screen: isMap };
|
|
5824
|
+
}
|
|
5825
|
+
async function runProgramTry({ cwd, word, options, context, requestedBudget }) {
|
|
5826
|
+
const { ports } = context, selected = programSelection(cwd, word, ports, options['--app-map']), { root, entry } = selected;
|
|
5827
|
+
if (options['--data'] !== undefined && options['--fresh'] !== undefined) throw new Stop(2, 'Choose --data FILE or --fresh, not both.');
|
|
5828
|
+
if (options['--fresh'] !== undefined && options['--fresh'] !== true) throw new Stop(2, '--fresh takes no value.');
|
|
5829
|
+
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.');
|
|
5830
|
+
const store = stateFor(ports.env, root), files = programFiles(root, entry, store); let seeded = null;
|
|
5831
|
+
if (options['--data'] !== undefined) {
|
|
5832
|
+
if (typeof options['--data'] !== 'string') throw new Stop(2, '--data needs a JSON file.');
|
|
5833
|
+
try { seeded = parseProgramJson(readFileSync(resolve(cwd, options['--data']), 'utf8')); } catch { throw new Stop(2, '--data must contain valid JSON with an initial_world object.'); }
|
|
5834
|
+
if (!programObject(seeded) || !programObject(seeded.initial_world) || Object.hasOwn(seeded, 'simulation') && !programObject(seeded.simulation)) throw new Stop(2, '--data needs an initial_world object and optional simulation object.');
|
|
5835
|
+
}
|
|
5836
|
+
files.read(); const unlock = files.lock(); let released = false, releaseInterrupt = () => {};
|
|
5837
|
+
try {
|
|
5838
|
+
let record = files.get();
|
|
5839
|
+
if (record && options['--app-map'] !== undefined && !options['--new'] && selected.appMap !== record.app_map)
|
|
5840
|
+
throw new Stop(2, 'The live program keeps its pinned app map. Use --new to select a different app map.');
|
|
5841
|
+
const appMap = !selected.screen && !options['--new'] && record?.app_map
|
|
5842
|
+
? selected.validatePinnedMap(record.app_map) : selected.appMap;
|
|
5843
|
+
const capture = ports.captureSource(root, { tests: [entry], appMap });
|
|
5844
|
+
const origin = runtimeOrigin(ports.env), identity = signIn(ports.gh, store, ports);
|
|
5845
|
+
if (record && (record.login !== identity.login || record.origin !== origin)) throw new Stop(5, 'This program session belongs to another owner or interpreter. Use its original owner and address.');
|
|
5846
|
+
Object.assign(context, { root, cwd, origin, identity, store, capture, visible: selected.visible, appMap, programEntry: entry,
|
|
5847
|
+
programTarget: relative(root, resolve(cwd, word)).split(sep).join('/'), programFiles: files,
|
|
5848
|
+
secrets: [identity.token], startedAt: ports.now(), deadline: ports.now() + TRY_MS, lint: { request_ids: [], state: null }, rows: [], timeoutMin: 5, folder: store.folder('tries'), doorMode: options['--serve'] !== undefined || !selected.screen });
|
|
5849
|
+
releaseInterrupt = interruptible(context);
|
|
5850
|
+
context.auth = authSession({ identity, store, ports, secrets: context.secrets, expectedOwnerLogin: () => record?.login ?? identity.login, ownerMismatchError: () => new Stop(5, 'This program belongs to another owner.') });
|
|
5851
|
+
context.runtime = new Runtime({ origin, token: identity.token, ports, signal: context.signal, auth: context.auth, programJson: true });
|
|
5852
|
+
let answer = null;
|
|
5853
|
+
if (record) {
|
|
5854
|
+
const read = judgeGet(await context.runtime.get(record.id), record.id, 'try');
|
|
5855
|
+
if (read.kind !== 'state') throw new Stop(3, `Program setup ${record.id} is not confirmed. Its original ID is kept; no replacement was sent.`);
|
|
5856
|
+
answer = read.answer;
|
|
5857
|
+
const state = answer.result?.session?.state;
|
|
5858
|
+
if (answer.state === 'passed' && LIVE_SESSION.has(state)) {
|
|
5859
|
+
const current = Object.fromEntries(capture.sources.filter(file => file.path.endsWith('.prompt.md')).map(file => [file.path, sha256(file.bytes)]));
|
|
5860
|
+
const mapHash = appMap ? sha256(capture.sources.find(file => file.path === appMap).bytes) : null;
|
|
5861
|
+
if (!options['--new'] && (record.source_sha256 !== capture.sha256 || !isDeepStrictEqual(record.prompt_hashes, capture.raw_prompt_hashes) || !isDeepStrictEqual(record.effective_prompt_hashes, current) || record.app_map_hash !== mapHash)) throw new Stop(4, 'The pinned program source or map changed. Use --new after reconciling this session.');
|
|
5862
|
+
if (state === 'paused') answer = await reopenTry(context, record, { path: entry, story: entry });
|
|
5863
|
+
record = await recoverProgramAction(context.runtime, files, record);
|
|
5864
|
+
if (requestedBudget !== null && requestedBudget !== answer.result?.session?.max_calls && !options['--new']) throw new Stop(3, 'The live program keeps its original call budget. Use --new to request a different budget.');
|
|
5865
|
+
if (options['--new'] || seeded || options['--fresh']) { await stopTry(context, record); record = null; }
|
|
5866
|
+
} else if (['failed', 'refused', 'not_run'].includes(answer.state) || answer.state === 'passed' && state === 'stopped') {
|
|
5867
|
+
if (record.pending) throw new Stop(3, `Program action ${record.pending.id} remains unconfirmed. The saved session is kept.`);
|
|
5868
|
+
record = null;
|
|
5869
|
+
} else throw new Stop(3, `Program setup ${record.id} is not confirmed. Its original ID is kept; no replacement was sent.`);
|
|
5870
|
+
}
|
|
5871
|
+
if (!record) {
|
|
5872
|
+
const lint = await runLint(context);
|
|
5873
|
+
if (lint.kind !== 'answer' || lint.answer?.state !== 'passed') {
|
|
5874
|
+
const refusals = lint.answer?.result?.refusals ?? (lint.refusal ? [lint.refusal] : []);
|
|
5875
|
+
throw new Stop(4, refusals.map(item => item.fix ? `${item.message ?? item.code}. ${item.fix}` : item.message ?? item.code).join('; ') || 'Program lint did not confirm admission. No Try was created.');
|
|
5876
|
+
}
|
|
5877
|
+
const setup = { request_ids: [], reservation: null };
|
|
5878
|
+
for (;;) {
|
|
5879
|
+
if (!await admission(context, 'try', setup)) throw new Stop(5, 'The program setup wait ended before sending.');
|
|
5880
|
+
const request = { requestId: ports.randomUUID(), source_sha256: capture.sha256, entry,
|
|
5881
|
+
initial_world: seeded?.initial_world ?? (options['--fresh'] ? {} : files.read()), ...(seeded?.simulation ? { simulation: seeded.simulation } : {}),
|
|
5882
|
+
...(appMap ? { app_map: appMap } : {}), tab: selected.screen ? 'screen' : 'call', max_calls: requestedBudget ?? 300, ...sourceProvenance(context, capture) };
|
|
5883
|
+
setup.request_ids.push(request.requestId);
|
|
5884
|
+
if (await recordRuntimeRequest(setup.reservation, request.requestId, slotPorts(context)) === false || context.interrupted) throw new Stop(3, 'Stopped before sending the program.');
|
|
5885
|
+
record = { id: request.requestId, entry, origin, login: identity.login, source_sha256: capture.sha256, max_calls: request.max_calls, ...setup,
|
|
5886
|
+
prompt_hashes: capture.raw_prompt_hashes, effective_prompt_hashes: Object.fromEntries(capture.sources.filter(file => file.path.endsWith('.prompt.md')).map(file => [file.path, sha256(file.bytes)])),
|
|
5887
|
+
app_map: appMap, app_map_hash: appMap ? sha256(capture.sources.find(file => file.path === appMap).bytes) : null };
|
|
5888
|
+
files.set(record); store.posted(context.folder, record.id);
|
|
5889
|
+
let reply;
|
|
5890
|
+
try { reply = await context.runtime.post('/v1/try', request, capture.tar, ports.postMs); }
|
|
5891
|
+
catch (error) {
|
|
5892
|
+
if (unadmittedTryErrors.has(error)) {
|
|
5893
|
+
await finishReservation(context, setup, { state: 'not_run' });
|
|
5894
|
+
if (files.get()?.id === request.requestId) files.set(null);
|
|
5895
|
+
}
|
|
5896
|
+
throw error;
|
|
5897
|
+
}
|
|
5898
|
+
const verdict = judgePost(reply, record.id, 'try', context.secrets);
|
|
5899
|
+
if (verdict.answer) await finishReservation(context, setup, verdict.answer);
|
|
5900
|
+
if (verdict.kind === 'busy') { await finishReservation(context, setup, { state: 'not_run' }); files.set(null); if (await waitBudget(context, verdict.wait)) continue; throw new Stop(5, 'The interpreter stayed busy. No program was started.'); }
|
|
5901
|
+
if (verdict.kind !== 'accepted') {
|
|
5902
|
+
const refusedBeforeAdmission = verdict.kind === 'refused' || verdict.blocked || reply.status === 401 || gateText(reply)
|
|
5903
|
+
|| verdict.kind === 'not_run' && reply.status === 503;
|
|
5904
|
+
if (refusedBeforeAdmission) {
|
|
5905
|
+
await finishReservation(context, setup, { state: 'not_run' });
|
|
5906
|
+
if (files.get()?.id === request.requestId) files.set(null);
|
|
5907
|
+
throw new Stop(3, verdict.refusal?.message || verdict.note?.message || 'Program setup was refused before admission. No program was started.');
|
|
5908
|
+
}
|
|
5909
|
+
throw new Stop(3, `Program setup ${record.id} is not confirmed. Its original ID is kept; no replacement was sent.`);
|
|
5910
|
+
}
|
|
5911
|
+
const done = ENDED.has(verdict.answer.state) ? { answer: verdict.answer } : await readUntil(context, record.id, 'try', value => ENDED.has(value.state), TRY_MS, 'Starting your program');
|
|
5912
|
+
answer = done.answer; if (answer) await finishReservation(context, setup, answer);
|
|
5913
|
+
if (!tryLink(answer, origin)) throw new Stop(3, `Program setup ${record.id} is not confirmed running. Its original ID is kept.`);
|
|
5914
|
+
const cap = answer.result?.session?.max_calls;
|
|
5915
|
+
if (cap !== request.max_calls) throw new Stop(3, 'The program call budget was not confirmed. Its session is kept.');
|
|
5916
|
+
files.save(files.read()); record = await syncProgramWorld(context.runtime, files, record); break;
|
|
5917
|
+
}
|
|
5918
|
+
}
|
|
5919
|
+
const link = tryLink(answer, origin); if (!link) throw new Stop(3, refusedLink(answer, origin));
|
|
5920
|
+
context.programRecord = record;
|
|
5921
|
+
const restoreSession = async (current, active = context) => {
|
|
5922
|
+
if (current?.id !== record.id || current.entry !== record.entry || current.origin !== record.origin || current.login !== record.login)
|
|
5923
|
+
throw new Stop(3, 'The program session changed. Reopen this view.');
|
|
5924
|
+
const session = judgeGet(await active.runtime.get(current.id), current.id, 'try');
|
|
5925
|
+
if (session.kind !== 'state' || session.answer.state !== 'passed' || session.answer.result?.session?.id !== current.id
|
|
5926
|
+
|| !LIVE_SESSION.has(session.answer.result?.session?.state))
|
|
5927
|
+
throw new Stop(3, 'The original program session is not confirmed running or paused. Its saved state is kept; no action was sent.');
|
|
5928
|
+
if (session.answer.result.session.state === 'paused')
|
|
5929
|
+
await reopenTry({ ...active, deadline: ports.now() + TRY_MS }, current, { path: entry, story: entry });
|
|
5930
|
+
};
|
|
5931
|
+
// Screen confirmation and persistence share the same cross-process lock as typed calls.
|
|
5932
|
+
context.programScreen = async (resource, init) => {
|
|
5933
|
+
const done = files.lock();
|
|
5934
|
+
try {
|
|
5935
|
+
let current = files.get(), dispatchedId;
|
|
5936
|
+
await restoreSession(current);
|
|
5937
|
+
const actionRead = init.method === 'GET' && resource.startsWith('api/action?');
|
|
5938
|
+
const pendingRead = actionRead && current.pending?.kind === 'screen'
|
|
5939
|
+
&& new URLSearchParams(resource.slice(resource.indexOf('?'))).get('id') === current.pending.id;
|
|
5940
|
+
const savedTerminal = pendingRead ? current.pending.terminal : null;
|
|
5941
|
+
// Forward the original action's pending lookup without releasing custody.
|
|
5942
|
+
// Saved terminal evidence must still reconcile its world before any reply.
|
|
5943
|
+
if (current.pending && (!pendingRead || current.pending.terminal)) current = await recoverProgramAction(context.runtime, files, current);
|
|
5944
|
+
// Recovery releases custody; retain the matching receipt for this poll.
|
|
5945
|
+
if (savedTerminal) return { status: 200, json: { action: savedTerminal } };
|
|
5946
|
+
if (init.method === 'POST') {
|
|
5947
|
+
const capture = ports.captureSource(root, { tests: [entry], appMap: current.app_map });
|
|
5948
|
+
const effective = Object.fromEntries(capture.sources.filter(file => file.path.endsWith('.prompt.md')).map(file => [file.path, sha256(file.bytes)]));
|
|
5949
|
+
if (current.source_sha256 !== capture.sha256 || !isDeepStrictEqual(current.prompt_hashes, capture.raw_prompt_hashes) || !isDeepStrictEqual(current.effective_prompt_hashes, effective)
|
|
5950
|
+
|| current.app_map_hash !== (current.app_map ? sha256(capture.sources.find(file => file.path === current.app_map).bytes) : null)) throw new Stop(4, 'The pinned program source or map changed. Use --new after reconciling this session.');
|
|
5951
|
+
let body; try { body = JSON.parse(init.body); } catch { throw new Stop(2, 'Screen actions need a JSON object.'); }
|
|
5952
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(body?.action_id ?? '')) throw new Stop(2, 'A Screen action needs its original action_id.');
|
|
5953
|
+
dispatchedId = body.action_id;
|
|
5954
|
+
current = { ...current, pending: { kind: 'screen', id: body.action_id, world_version: current.world_version } }; files.set(current);
|
|
5955
|
+
}
|
|
5956
|
+
let reply;
|
|
5957
|
+
try { reply = await context.runtime.send(`/v1/try/${record.id}/screen/${resource}`, init, 90_000); }
|
|
5958
|
+
catch (error) {
|
|
5959
|
+
if (init.method === 'POST' && unadmittedScreenErrors.has(error)) releaseRefusedProgramAction(files, 'screen', dispatchedId);
|
|
5960
|
+
throw error;
|
|
5961
|
+
}
|
|
5962
|
+
if (init.method === 'POST' && isPreExecutionRefusal(reply)) releaseRefusedProgramAction(files, 'screen', dispatchedId);
|
|
5963
|
+
if ((init.method === 'POST' || actionRead) && [200, 202].includes(reply.status) && ['passed', 'failed', 'refused'].includes(reply.json?.action?.verdict)) {
|
|
5964
|
+
current = files.get();
|
|
5965
|
+
if (current.pending?.kind === 'screen') {
|
|
5966
|
+
if (current.pending.id !== reply.json.action.action_id) throw new Stop(3, `Program action ${current.pending.id} is not confirmed. Its original ID is kept; no action was repeated.`);
|
|
5967
|
+
await commitProgramAction(context.runtime, files, current, reply.json.action, () => restoreSession(current));
|
|
5968
|
+
} else await recoverProgramAction(context.runtime, files, current);
|
|
5969
|
+
}
|
|
5970
|
+
return reply;
|
|
5971
|
+
} finally { done(); }
|
|
5972
|
+
};
|
|
5973
|
+
unlock(); released = true;
|
|
5974
|
+
if (options['--serve'] !== undefined || !selected.screen) return await (await import('./try-http.mjs')).openServe(context, { path: entry, programEntry: entry, title: entry }, record.id, { ...options, '--serve': options['--serve'] === true ? 8080 : options['--serve'] ?? 8080 });
|
|
5975
|
+
line(ports.stdout, `Program ready: ${link}`);
|
|
5976
|
+
if (!options['--no-open']) await ports.openUrl(link);
|
|
5977
|
+
try {
|
|
5978
|
+
do {
|
|
5979
|
+
const done = files.lock();
|
|
5980
|
+
try {
|
|
5981
|
+
const current = files.get(); await restoreSession(current);
|
|
5982
|
+
await recoverProgramAction(context.runtime, files, current);
|
|
5983
|
+
} finally { done(); }
|
|
5984
|
+
if (options['--no-wait'] || !ports.interactive || context.interrupted) break;
|
|
5985
|
+
await ports.sleep(ports.watchMs, context.signal);
|
|
5986
|
+
} while (!context.interrupted);
|
|
5987
|
+
} catch (error) {
|
|
5988
|
+
if (!context.interrupted || !(error instanceof Stop || error.name === 'AbortError')) throw error;
|
|
5989
|
+
}
|
|
5990
|
+
if (context.interrupted) {
|
|
5991
|
+
// The watch signal is already aborted. Reconcile with the same owner under
|
|
5992
|
+
// the program lock using independently bounded reads before leaving the view.
|
|
5993
|
+
const finalRuntime = new Runtime({ origin, token: identity.token, ports, auth: context.auth, programJson: true });
|
|
5994
|
+
const finalContext = { ...context, runtime: finalRuntime, signal: undefined, interrupted: false };
|
|
5995
|
+
const done = files.lock();
|
|
5996
|
+
try {
|
|
5997
|
+
const current = files.get(); await restoreSession(current, finalContext);
|
|
5998
|
+
await recoverProgramAction(finalRuntime, files, current);
|
|
5999
|
+
} finally { done(); }
|
|
6000
|
+
}
|
|
6001
|
+
return 0;
|
|
6002
|
+
} finally { if (!released) unlock(); releaseInterrupt(); }
|
|
6003
|
+
}
|
|
6004
|
+
|
|
4934
6005
|
// pdd simulate. Returns the exit code.
|
|
6006
|
+
// Direct programs use the ordinary Try wire protocol; their Story exists only in the upload.
|
|
6007
|
+
function directPrivate(path, value) {
|
|
6008
|
+
const stat = statOrNull(path);
|
|
6009
|
+
if (stat && (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1)) throw new Stop(125, 'Program state must be a private regular file.');
|
|
6010
|
+
if (value === undefined) return stat ? JSON.parse(readFileSync(path, 'utf8')) : undefined;
|
|
6011
|
+
const temp = `${path}.${randomUUID()}.tmp`;
|
|
6012
|
+
const fd = openSync(temp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
|
6013
|
+
try { writeFileSync(fd, JSON.stringify(value, null, 2) + '\n'); } finally { closeSync(fd); }
|
|
6014
|
+
try { renameSync(temp, path); } catch (error) { try { unlinkSync(temp); } catch {} throw error; }
|
|
6015
|
+
return value;
|
|
6016
|
+
}
|
|
6017
|
+
function directFolder(root, name, prompt) {
|
|
6018
|
+
let folder = root;
|
|
6019
|
+
for (const part of ['.pdd', 'run']) {
|
|
6020
|
+
folder = join(folder, part);
|
|
6021
|
+
try { mkdirSync(folder, {mode:0o700}); } catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
6022
|
+
const stat = lstatSync(folder);
|
|
6023
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Stop(125, 'Program state folders must not be links.');
|
|
6024
|
+
}
|
|
6025
|
+
// A heading is editable; the root and entry retain ownership of saved state.
|
|
6026
|
+
const matches = [];
|
|
6027
|
+
for (const entry of readdirSync(folder, {withFileTypes:true})) {
|
|
6028
|
+
if (entry.name === name && entry.isSymbolicLink()) throw new Stop(125, 'Program state folders must not be links.');
|
|
6029
|
+
if (!entry.isDirectory() || !/^[A-Za-z][A-Za-z0-9._-]{0,63}$/.test(entry.name) || ['pdd','node','gh','git'].includes(entry.name.toLowerCase())) continue;
|
|
6030
|
+
let binding;
|
|
6031
|
+
try { binding = directPrivate(join(folder,entry.name,'identity.json')); }
|
|
6032
|
+
catch (error) { if (entry.name === name) throw error; continue; }
|
|
6033
|
+
if (binding && (binding.root !== root || binding.prompt !== prompt)) {
|
|
6034
|
+
let savedName;
|
|
6035
|
+
try { savedName = directPrivate(join(folder,entry.name,'session.json'))?.name; } catch {}
|
|
6036
|
+
if (entry.name === name || savedName === name)
|
|
6037
|
+
throw new Stop(125,'Another entry prompt already uses this program name. Give each entry its own program name.');
|
|
6038
|
+
}
|
|
6039
|
+
if (binding?.root === root && binding.prompt === prompt) matches.push(entry.name);
|
|
6040
|
+
}
|
|
6041
|
+
if (matches.length > 1) throw new Stop(125, 'More than one program state folder belongs to this entry. Reconcile its saved state before running another command.');
|
|
6042
|
+
folder = join(folder,matches[0] ?? name);
|
|
6043
|
+
try { mkdirSync(folder, {mode:0o700}); } catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
6044
|
+
const folderStat = lstatSync(folder);
|
|
6045
|
+
if (!folderStat.isDirectory() || folderStat.isSymbolicLink()) throw new Stop(125, 'Program state folders must not be links.');
|
|
6046
|
+
const git = spawnSync('git', ['rev-parse', '--git-path', 'info/exclude'], {cwd:root,encoding:'utf8',stdio:['ignore','pipe','pipe']});
|
|
6047
|
+
if (git.status !== 0) throw new Stop(125, 'Could not locate the local Git exclude file.');
|
|
6048
|
+
const exclude = resolve(root, git.stdout.trim());
|
|
6049
|
+
mkdirSync(dirname(exclude), {recursive:true});
|
|
6050
|
+
if (realpathSync(dirname(exclude)) !== dirname(exclude)) throw new Stop(125, 'The Git exclude folder must not be a link.');
|
|
6051
|
+
const stat = statOrNull(exclude);
|
|
6052
|
+
if (stat && (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1)) throw new Stop(125, 'The Git exclude file must not be linked.');
|
|
6053
|
+
const text = stat ? readFileSync(exclude,'utf8') : '';
|
|
6054
|
+
if (!text.split('\n').includes('/.pdd/run/')) writeFileSync(exclude, `${text}${text && !text.endsWith('\n') ? '\n' : ''}/.pdd/run/\n`);
|
|
6055
|
+
return folder;
|
|
6056
|
+
}
|
|
6057
|
+
function directCapture(root, promptPath, ports, allowMissingInterfaces = false) {
|
|
6058
|
+
// Select only the prompt closure, without unrelated Story discovery or global includes.
|
|
6059
|
+
const directPorts = {...ports,isStoryPath:()=>false,hasAcceptance:()=>false,matchTests:()=>({tests:[]}),orphanSummary:()=>null};
|
|
6060
|
+
const selection = {tests:[promptPath],appMap:null,validateCriteria:false,sourceIncludes:false,...(allowMissingInterfaces?{allowMissingInterfaces:true}:{})};
|
|
6061
|
+
const capture = ports.captureSource.isDefaultCapture ? captureSource(root,selection,directPorts) : ports.captureSource(root,selection);
|
|
6062
|
+
const sources = capture.sources.filter(file=>!file.path.startsWith('.pdd/run/'));
|
|
6063
|
+
const tar = tarFiles(sources);
|
|
6064
|
+
return {...capture,sources,tar,sha256:sha256(tar),files:sources.map(file=>({path:file.path,size:file.bytes.length})),bytes:sources.reduce((n,file)=>n+file.bytes.length,0)};
|
|
6065
|
+
}
|
|
6066
|
+
async function runDirectProgram({words,options,cwd}, ports) {
|
|
6067
|
+
const quiet = options['-q'] === true || options['--quiet'] === true;
|
|
6068
|
+
const started = ports.now(), context = {ports,interrupted:false,doorMode:true,warnings:[]};
|
|
6069
|
+
let release = ()=>{}, unlock = ()=>{}, folder, descriptor, secrets = [], setupCalls = 0;
|
|
6070
|
+
const diagnostic = error => {
|
|
6071
|
+
line(ports.stderr,`pdd: ${cleanText(error.message || 'The program could not run.',secrets)}`);
|
|
6072
|
+
line(ports.stderr,`Fix: ${cleanText(error.fix || 'Check the prompt, data and interpreter connection, then run the command again.',secrets)}`);
|
|
6073
|
+
if (!quiet) line(ports.stderr,`pdd: unknown AI calls · ${Math.max(0,ports.now()-started)/1000}s${context.draft?' · DRAFT':''}`);
|
|
6074
|
+
return context.interrupted ? 130 : error.exitCode === 2 ? 2 : 125;
|
|
6075
|
+
};
|
|
6076
|
+
try {
|
|
6077
|
+
for (const [key,value] of Object.entries(options)) {
|
|
6078
|
+
if (key === '--data' ? typeof value !== 'string' || !value.trim() : !['--fresh','--show-data','-q','--quiet'].includes(key) || typeof value !== 'boolean')
|
|
6079
|
+
throw new Stop(2,`Invalid direct program option: ${key}. Use --data FILE, --fresh, --show-data or --quiet.`);
|
|
6080
|
+
}
|
|
6081
|
+
const root = realpathSync(repoRoot(cwd)), promptPath = relative(root,resolve(cwd,words[0])).split(sep).join('/');
|
|
6082
|
+
if (promptPath.startsWith('../') || promptPath === '..') throw new Stop(125,'The program prompt must be inside this repository.');
|
|
6083
|
+
const visible = new Set(gitFiles(root)), workspace = loadRuntimeWorkspace({root});
|
|
6084
|
+
requireRuntimePath(workspace,{path:promptPath,from:'Direct program'});
|
|
6085
|
+
const doors = await import('./try-doors.mjs');
|
|
6086
|
+
const storyPath='user_stories/pdd-direct-program.md',criterionText='Generated CLI setup; not behavioral evidence.';
|
|
6087
|
+
const criterion={id:'ac-sha256-'+sha256(storyPath+'\0'+criterionText).slice(0,48),text:criterionText};
|
|
6088
|
+
const test = {directProgram:true,path:'test/pdd-direct-program.json',storyPath,story:'pdd-direct-program',title:'Direct program',
|
|
6089
|
+
doc:{schema_version:TEST_SCHEMA,story_path:storyPath,criteria:[criterion],initial_world:{},steps:[]}};
|
|
6090
|
+
// openCli's selection boundary also validates the program name and CLI conventions.
|
|
6091
|
+
let selected = await doors.openCli({root,visible,ports,directProgram:{prepareOnly:true,prompt:promptPath,allowMissingInterfaces:true}},test,null,{});
|
|
6092
|
+
folder = directFolder(root,selected.name,promptPath);
|
|
6093
|
+
const descriptorPath = join(folder,'session.json'), lastPath = join(folder,'last.json'), dataPath = join(folder,'data.json');
|
|
6094
|
+
const bindingPath=join(folder,'identity.json'),binding=directPrivate(bindingPath);
|
|
6095
|
+
if(binding&&(binding.root!==root||binding.prompt!==promptPath))throw new Stop(125,'Another entry prompt already uses this program name. Give each entry its own program name.');
|
|
6096
|
+
if(!binding)directPrivate(bindingPath,{root,prompt:promptPath});
|
|
6097
|
+
descriptor = directPrivate(descriptorPath);
|
|
6098
|
+
if (descriptor && (descriptor.root !== root || descriptor.prompt !== promptPath)) throw new Stop(125,'Another entry prompt already uses this program name. Give each entry its own program name.');
|
|
6099
|
+
const selectData=()=>{
|
|
6100
|
+
let data;
|
|
6101
|
+
if (options['--data'] !== undefined) {
|
|
6102
|
+
const path = resolve(cwd,options['--data']);
|
|
6103
|
+
if (realpathSync(dirname(path)) !== dirname(path)) throw new Stop(125,'The explicit data path must not contain links.');
|
|
6104
|
+
data = directPrivate(path);
|
|
6105
|
+
if (data === undefined) throw new Stop(125,'The explicit data file is unavailable.');
|
|
6106
|
+
} else {data = descriptor?.shellBootstrap&&Object.hasOwn(descriptor,'pendingData')?descriptor.pendingData:directPrivate(dataPath);if(data===undefined)data={};}
|
|
6107
|
+
if (!isObject(data)) throw new Stop(125,'Program data must be a JSON object.');
|
|
6108
|
+
return data;
|
|
6109
|
+
};
|
|
6110
|
+
if (options['--show-data']) { line(ports.stdout,JSON.stringify(selectData())); return 0; }
|
|
6111
|
+
let releaseLock;
|
|
6112
|
+
try { releaseLock=await ports.acquireBatchLock(folder); } catch(error){if(error.code==='BATCH_LOCK_BUSY')throw new Stop(125,'Another program invocation is pending. Recover its request before running another command.');throw error;}
|
|
6113
|
+
unlock=()=>{releaseLock();unlock=()=>{};};
|
|
6114
|
+
let last = directPrivate(lastPath), pendingCall = last?.state === 'unknown' && last.id;
|
|
6115
|
+
if(!pendingCall&&!descriptor?.setupPending)directPrivate(lastPath,{state:'unknown',id:null,input:{argv:words.slice(1)}});
|
|
6116
|
+
const capture = directCapture(root,promptPath,ports,selected.unadmitted), sourceHash = capture.sha256;
|
|
6117
|
+
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')));
|
|
6118
|
+
const store = stateFor(ports.env,root), origin = runtimeOrigin(ports.env), identity = signIn(ports.gh,store,ports,{exitCode:125});
|
|
6119
|
+
secrets = [identity.token];
|
|
6120
|
+
if (descriptor && descriptor.login !== identity.login) throw new Stop(125,`This program belongs to ${descriptor.login}. Run: gh auth switch -u ${descriptor.login}`);
|
|
6121
|
+
if (descriptor && descriptor.origin !== origin) throw new Stop(125,'This program belongs to another interpreter address. Restore its original PDD_RUNTIME_URL.');
|
|
6122
|
+
Object.assign(context,{ports:{...ports,stderr:{write(){return true;}}},root,store,origin,identity,secrets,visible,appMap:null,capture,startedAt:started,deadline:ports.now()+TRY_MS,lint:{request_ids:[],state:null},batch:null,timeoutMin:TRY_MS/60_000,agentLimit:false,head:null});
|
|
6123
|
+
release = interruptible(context);
|
|
6124
|
+
context.folder=store.folder('tries');
|
|
6125
|
+
context.auth = authSession({identity,store,ports,secrets,signInExitCode:125,expectedOwnerLogin:identity.login});
|
|
6126
|
+
context.runtime = new Runtime({origin,token:identity.token,ports,signal:context.signal,auth:context.auth});
|
|
6127
|
+
// A read-result command stores an authenticated receipt independently of this program record.
|
|
6128
|
+
if (pendingCall) {
|
|
6129
|
+
const meta=store.read(join(store.dir,'calls',`${pendingCall}.meta.json`));
|
|
6130
|
+
const answer=store.read(join(store.dir,'calls',`${pendingCall}.json`));
|
|
6131
|
+
if (meta?.root===root && meta.login===identity.login && meta.origin===origin && meta.session_id===descriptor?.sessionId
|
|
6132
|
+
&& sameJob(answer,pendingCall,'call') && (!answer.session_id || answer.session_id===descriptor.sessionId)) {
|
|
6133
|
+
const result=answer.result?.program_result, report=isObject(answer.result?.report)?answer.result.report:{};
|
|
6134
|
+
if (answer.state==='passed'
|
|
6135
|
+
&& typeof result?.stdout==='string' && typeof result?.stderr==='string'
|
|
6136
|
+
&& Number.isInteger(result.exit_code) && result.exit_code>=0 && result.exit_code<=255 && result.exit_code!==125
|
|
6137
|
+
&& (report.world===undefined || isObject(report.world))) {
|
|
6138
|
+
const observation=await doorWorldObservation(context.runtime,descriptor.sessionId,report,report.action_id);
|
|
6139
|
+
if(context.interrupted)throw new Stop(130,`Stopped while recovering the command. Read pdd test --read ${pendingCall}.`);
|
|
6140
|
+
if(observation.world!==undefined&&!isObject(observation.world))throw new Stop(125,'The interpreter returned invalid program data.');
|
|
6141
|
+
if(observation.world!==undefined)directPrivate(dataPath,observation.world);
|
|
6142
|
+
last={state:'confirmed',id:pendingCall,input:last.input,result,inputWorld:observation.input_world,world:observation.world};
|
|
6143
|
+
directPrivate(lastPath,last);pendingCall=false;
|
|
6144
|
+
} else if (['failed','refused','not_run'].includes(answer.state)) {
|
|
6145
|
+
last={state:'refused',id:pendingCall,input:last.input};directPrivate(lastPath,last);pendingCall=false;
|
|
6146
|
+
}
|
|
6147
|
+
}
|
|
6148
|
+
}
|
|
6149
|
+
const data=selectData();
|
|
6150
|
+
if (pendingCall && (options['--fresh'] || options['--data'] !== undefined || sourceHash !== descriptor?.sourceHash || !isDeepStrictEqual(last.input?.argv,words.slice(1))))
|
|
6151
|
+
throw Object.assign(new Stop(125,`The preceding command outcome is unknown. Read it with pdd test --read ${last.id}.`),{fix:`Recover pdd test --read ${last.id} before changing the program or its input.`});
|
|
6152
|
+
if(words.length===1&&!ports.directInvoke){
|
|
6153
|
+
if(descriptor?.setupPending)throw Object.assign(new Stop(125,`The preceding setup must be recovered with pdd test --read ${descriptor.sessionId}.`),{fix:`Read pdd test --read ${descriptor.sessionId} before opening this shell.`});
|
|
6154
|
+
descriptor={...descriptor,version:1,directProgram:true,shellBootstrap:true,root,prompt:promptPath,operation:selected.entry.operation,login:identity.login,origin,
|
|
6155
|
+
sessionId:descriptor?.sessionId??null,sourceHash:descriptor?.sourceHash??null,name:selected.name,inputSchema:selected.entry.input_schema,stateDir:store.dir,programDir:folder,draft:context.draft,
|
|
6156
|
+
replaceOnNextCall:descriptor?.replaceOnNextCall||options['--fresh']||options['--data']!==undefined,
|
|
6157
|
+
...(options['--data']!==undefined||Object.hasOwn(descriptor??{},'pendingData')?{pendingData:data}:{})};
|
|
6158
|
+
directPrivate(descriptorPath,descriptor);
|
|
6159
|
+
unlock();
|
|
6160
|
+
return await doors.openCli({root,visible,ports:{...ports,signal:context.signal},store,identity,origin,runtime:context.runtime,
|
|
6161
|
+
directProgram:{descriptor,descriptorPath,argv:[],quiet,startedAt:started,selected}},test,descriptor.sessionId,{});
|
|
6162
|
+
}
|
|
6163
|
+
const noteAdmittedDrafts=answer=>{
|
|
6164
|
+
const records=answer?.result?.report?.program?.prompts;
|
|
6165
|
+
if(answer?.state==='passed'&&Array.isArray(records)&&records.some(record=>
|
|
6166
|
+
capture.sources.some(file=>file.path===record.path)&&(record.admission_state==='draft'||record.state==='draft')))context.draft=true;
|
|
6167
|
+
};
|
|
6168
|
+
const admittedSelection=async()=>{
|
|
6169
|
+
const lint=await runLint(context),answer=lint.answer;
|
|
6170
|
+
const problem=lint.refusal??answer?.result?.refusals?.[0]??answer?.result?.report?.refusal;
|
|
6171
|
+
if(lint.kind!=='answer'||answer?.state!=='passed')throw Object.assign(new Stop(125,problem?.message||lint.note?.message||'The program interface admission is unconfirmed.'),{fix:problem?.fix});
|
|
6172
|
+
noteAdmittedDrafts(answer);
|
|
6173
|
+
const records=answer.result?.report?.program?.prompts;
|
|
6174
|
+
const record=Array.isArray(records)?records.find(record=>record.path===promptPath):null;
|
|
6175
|
+
if(!record?.interface)return null;
|
|
6176
|
+
if(!['approved','draft'].includes(record.admission_state??record.state))throw new Stop(125,'The entry prompt has no admitted CLI interface.');
|
|
6177
|
+
return doors.openCli({root,visible,ports,directProgram:{prepareOnly:true,prompt:promptPath,selected:null,interface:record.interface}},test,null,{});
|
|
6178
|
+
};
|
|
6179
|
+
let coldInterface=false;
|
|
6180
|
+
if(selected.unadmitted){
|
|
6181
|
+
if(!await probeLazyInterfaces(context,origin,store))throw Object.assign(new Stop(125,'The entry prompt has no Runtime interface block, and the PDD interpreter does not advertise lazy-interfaces.'),{fix:'Use a PDD interpreter that supports lazy-interfaces for plain Markdown prompts.'});
|
|
6182
|
+
const admitted=await admittedSelection();
|
|
6183
|
+
if(admitted)selected=admitted;
|
|
6184
|
+
else{
|
|
6185
|
+
if(!selected.entry.operation||!/\bcli\b/i.test(selected.prompt.text))throw new Stop(125,'The cold CLI prompt must explicitly declare one operation before lazy setup can be prepared.');
|
|
6186
|
+
coldInterface=true;
|
|
6187
|
+
}
|
|
6188
|
+
}
|
|
6189
|
+
let input=pendingCall?last.input:coldInterface?{argv:words.slice(1),...(selected.entry.input_schema.required?.includes('stdin')?{stdin:''}:{})}:(await doors.openCli({root,visible,ports:{...ports,signal:context.signal},
|
|
6190
|
+
directProgram:{prepareOnly:true,prepareInput:true,prompt:promptPath,argv:words.slice(1),selected}},test,null,{})).input;
|
|
6191
|
+
if(!pendingCall&&!descriptor?.setupPending)directPrivate(lastPath,{state:'unknown',id:null,input});
|
|
6192
|
+
const replace = !descriptor?.sessionId || descriptor.replaceOnNextCall || descriptor.setupFailed || options['--fresh'] || options['--data'] !== undefined || descriptor.sourceHash !== sourceHash;
|
|
6193
|
+
if (descriptor?.setupPending || replace && descriptor?.sessionId) {
|
|
6194
|
+
const meta = descriptor.setupPending && store.read(join(store.dir,'tries',`${descriptor.sessionId}.meta.json`));
|
|
6195
|
+
const cached = meta?.root === root && meta.login === identity.login && meta.origin === origin && meta.command === 'try'
|
|
6196
|
+
? store.read(join(store.dir,'tries',`${descriptor.sessionId}.json`)) : null;
|
|
6197
|
+
const reply = sameJob(cached,descriptor.sessionId,'try') && ENDED.has(cached.state) && cached.state !== 'unknown'
|
|
6198
|
+
? {status:200,json:cached} : await context.runtime.get(descriptor.sessionId), answer = reply.json;
|
|
6199
|
+
if (![200,202].includes(reply.status) || !sameTryReceipt(answer,descriptor.sessionId) || !ENDED.has(answer.state) || answer.state === 'unknown')
|
|
6200
|
+
throw Object.assign(new Stop(125,`The program setup outcome is unknown. Read pdd test --read ${descriptor.sessionId}.`),{fix:`Recover pdd test --read ${descriptor.sessionId} first.`});
|
|
6201
|
+
if (descriptor.setupPending) {
|
|
6202
|
+
if (answer.state !== 'passed' || !LIVE_SESSION.has(answer.result?.session?.state)) {directPrivate(descriptorPath,{...descriptor,setupPending:false,setupFailed:true});throw new Stop(125,'The program setup did not open a session.');}
|
|
6203
|
+
descriptor = {...descriptor,setupPending:false};directPrivate(descriptorPath,descriptor);
|
|
6204
|
+
}
|
|
6205
|
+
if (replace && LIVE_SESSION.has(answer.result?.session?.state)) await stopTry(context,{id:descriptor.sessionId});
|
|
6206
|
+
}
|
|
6207
|
+
if (replace) {
|
|
6208
|
+
const operation = selected.entry.operation;
|
|
6209
|
+
test.doc.initial_world = data;
|
|
6210
|
+
test.doc.steps = [{step_id:'direct-program',entry_path:promptPath,operation,input,checks:[{criterion_id:criterion.id,target:'result',path:'/exit_code',op:'equals',value:0}]}];
|
|
6211
|
+
const generated = [{path:test.storyPath,bytes:Buffer.from(`# Direct program setup\n\n## Acceptance criteria\n\n1. ${criterion.text}\n`)},{path:test.path,bytes:Buffer.from(JSON.stringify(test.doc))}];
|
|
6212
|
+
const sources = [...capture.sources,...generated].sort((a,b)=>a.path.localeCompare(b.path)),tar=tarFiles(sources);
|
|
6213
|
+
if(tar.length>LIMITS.bytes||sources.length>LIMITS.files)throw new Stop(125,'The direct program setup exceeds the source upload limit. Reduce its reached source.');
|
|
6214
|
+
if(new Set(sources.map(file=>file.path)).size!==sources.length)throw new Stop(125,'A reached file conflicts with generated program setup metadata. Rename that dependency.');
|
|
6215
|
+
context.capture = {...capture,sources,tar,sha256:sha256(tar),files:sources.map(file=>({path:file.path,size:file.bytes.length})),bytes:sources.reduce((n,file)=>n+file.bytes.length,0)};
|
|
6216
|
+
context.rows = localRows([{test:test.path,story:test.story,title:test.title,refusals:[],steps:test.doc.steps,criteria:test.doc.criteria,criteria_total:1}]);
|
|
6217
|
+
// Setup diagnostics are reserved for failure; one-shot stdout belongs entirely to the program.
|
|
6218
|
+
noteAdmittedDrafts(await checkLint(context,context.rows));
|
|
6219
|
+
const row = context.rows[0];
|
|
6220
|
+
if (row.state !== 'ready') throw Object.assign(new Stop(125,row.refusals?.map(item=>item.message||item.code).join('; ')||'The interpreter refused this program.'),{fix:row.raw_refusals?.find(item=>item.fix)?.fix});
|
|
6221
|
+
const setup = {request_ids:[],reservation:null};
|
|
6222
|
+
if (!await admission(context,'try',setup)) throw new Stop(125,'The interpreter could not admit this program.');
|
|
6223
|
+
const lazyInterfaces=context.serverFeatures?.includes('lazy-interfaces')===true;
|
|
6224
|
+
const id=ports.randomUUID(), request={requestId:id,source_sha256:context.capture.sha256,seed:test.path,max_calls:400,tab:'terminal',...(lazyInterfaces?{lazy_interfaces:true}:{})};
|
|
6225
|
+
await recordRuntimeRequest(setup.reservation,id,slotPorts(context));
|
|
6226
|
+
descriptor={version:1,directProgram:true,root,prompt:promptPath,operation,login:identity.login,origin,sessionId:id,sourceHash,setupPending:true,
|
|
6227
|
+
name:selected.name,inputSchema:selected.entry.input_schema,stateDir:store.dir,programDir:folder,
|
|
6228
|
+
draft:context.draft,lazyInterfaces};
|
|
6229
|
+
directPrivate(descriptorPath,descriptor);
|
|
6230
|
+
directPrivate(lastPath,{state:'unknown',id:null,setupId:id,input});
|
|
6231
|
+
store.write(join(store.folder('tries'),`${id}.meta.json`),{id,command:'try',origin,root,login:identity.login,user_id:identity.userId});
|
|
6232
|
+
store.posted(store.folder('tries'),id);
|
|
6233
|
+
const reply=await context.runtime.post('/v1/try',request,context.capture.tar,ports.postMs), verdict=judgePost(reply,id,'try',secrets);
|
|
6234
|
+
let answer=sameTryReceipt(verdict.answer,id)?verdict.answer:null;
|
|
6235
|
+
if (answer && !ENDED.has(answer.state)) answer=(await readUntil(context,id,'try',item=>ENDED.has(item.state),TRY_MS,'Starting program',item=>sameTryReceipt(item,id))).answer;
|
|
6236
|
+
if (answer) {store.write(join(store.folder('tries'),`${id}.json`),answer);await finishReservation(context,setup,answer);}
|
|
6237
|
+
if (answer&&sameJob(answer,id,'try')&&['failed','refused','not_run'].includes(answer.state))directPrivate(descriptorPath,{...descriptor,setupPending:false,setupFailed:true});
|
|
6238
|
+
if (!answer || !sameJob(answer,id,'try') || answer.state !== 'passed' || !LIVE_SESSION.has(answer.result?.session?.state))
|
|
6239
|
+
throw Object.assign(new Stop(125,verdict.refusal?.message||reply.json?.error?.message||`The program setup is unconfirmed. Read pdd test --read ${id}.`),{fix:verdict.refusal?.fix||reply.json?.error?.fix||`Read pdd test --read ${id}; do not start another setup.`});
|
|
6240
|
+
setupCalls=tryUsage(answer).calls;
|
|
6241
|
+
descriptor={...descriptor,setupPending:false};directPrivate(descriptorPath,descriptor);
|
|
6242
|
+
}
|
|
6243
|
+
if(coldInterface){
|
|
6244
|
+
const admitted=await admittedSelection();
|
|
6245
|
+
if(!admitted)throw Object.assign(new Stop(125,'admitted-interface-unavailable: The interpreter has not supplied the CLI contract after setup.'),{fix:'Read the saved setup result, then run the command after the interpreter supplies its admitted interface; no program call was sent.'});
|
|
6246
|
+
if(admitted.entry.operation!==selected.entry.operation)throw new Stop(125,'The admitted CLI operation differs from the generated setup declaration. No program call was sent.');
|
|
6247
|
+
selected=admitted;
|
|
6248
|
+
if(!pendingCall)input=(await doors.openCli({root,visible,ports:{...ports,signal:context.signal},
|
|
6249
|
+
directProgram:{prepareOnly:true,prepareInput:true,prompt:promptPath,argv:words.slice(1),selected}},test,null,{})).input;
|
|
6250
|
+
}
|
|
6251
|
+
const inputProblems=checkInput(input,selected.entry.input_schema,0).refusals;
|
|
6252
|
+
if(inputProblems.length)throw new Stop(125,inputProblems.map(problem=>problem.message).join('; '));
|
|
6253
|
+
descriptor={...descriptor,operation:selected.entry.operation,inputSchema:selected.entry.input_schema,draft:context.draft,
|
|
6254
|
+
lazyInterfaces:context.serverFeatures?context.serverFeatures.includes('lazy-interfaces'):descriptor.lazyInterfaces===true};
|
|
6255
|
+
directPrivate(descriptorPath,descriptor);
|
|
6256
|
+
if (context.interrupted) throw new Stop(130,'Stopped before the command was sent.');
|
|
6257
|
+
return await doors.openCli({root,visible,ports:{...ports,signal:context.signal},store,identity,origin,runtime:context.runtime,
|
|
6258
|
+
directProgram:{descriptor,descriptorPath,argv:words.slice(1),input,quiet,startedAt:started,setupCalls,recoverRequestId:pendingCall||null,invoke:true,selected}},test,descriptor.sessionId,{});
|
|
6259
|
+
} catch (error) { if(error?.unboundPort)throw error; return diagnostic(error); }
|
|
6260
|
+
finally {
|
|
6261
|
+
release();unlock();
|
|
6262
|
+
await Promise.all([...(context.reservations??[])].map(reservation=>releaseRuntimeSlot(reservation,{ended:false},slotPorts(context))));
|
|
6263
|
+
}
|
|
6264
|
+
}
|
|
6265
|
+
|
|
6266
|
+
function shouldUseDirectProgram(words, options, cwd) {
|
|
6267
|
+
if (typeof words[0] !== 'string' || !words[0].endsWith('.prompt.md')) return false;
|
|
6268
|
+
if (words.length > 1 || ['--show-data', '-q', '--quiet'].some(key => options[key] !== undefined)) return true;
|
|
6269
|
+
if (['--serve', '--page', '--tab', '--cli', '--shell', '--no-open', '--new', '--stop', '--app-map', '--max-calls'].some(key => options[key] !== undefined)) return false;
|
|
6270
|
+
try {
|
|
6271
|
+
const text = readFileSync(resolve(cwd, words[0]), 'utf8');
|
|
6272
|
+
return /\b(?:cli|argv|stdin|stdout|exit_code|command-line)\b/i.test(text);
|
|
6273
|
+
} catch {
|
|
6274
|
+
return true;
|
|
6275
|
+
}
|
|
6276
|
+
}
|
|
6277
|
+
|
|
6278
|
+
function shouldUseTypedTry(words, options, cwd) {
|
|
6279
|
+
if (typeof words[0] !== 'string' || !words[0].endsWith('.prompt.md')) return false;
|
|
6280
|
+
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;
|
|
6281
|
+
try {
|
|
6282
|
+
const text = readFileSync(resolve(cwd, words[0]), 'utf8');
|
|
6283
|
+
const blocks = interfaceBlocks(text);
|
|
6284
|
+
if (blocks.length !== 1) return words.slice(1).some(word => word === '--input' || word === '--help' || word.startsWith('--')) && !/\b(?:cli|argv|stdin|stdout|exit_code|command-line)\b/i.test(text);
|
|
6285
|
+
const iface = JSON.parse(blocks[0][1]);
|
|
6286
|
+
if (iface?.kind === 'http') return false;
|
|
6287
|
+
const entries = Array.isArray(iface?.entries) ? iface.entries : [];
|
|
6288
|
+
return entries.length > 0 && !entries.some(entry => entry?.conventions?.includes('cli')
|
|
6289
|
+
|| Object.hasOwn(entry?.input_schema?.properties ?? {}, 'argv')
|
|
6290
|
+
|| Object.hasOwn(entry?.output_schema?.properties ?? {}, 'exit_code')
|
|
6291
|
+
|| entry?.route || entry?.http || entry?.screen);
|
|
6292
|
+
} catch {
|
|
6293
|
+
return words.slice(1).some(word => word === '--input' || word === '--help');
|
|
6294
|
+
}
|
|
6295
|
+
}
|
|
6296
|
+
|
|
6297
|
+
// Direct invocations keep their transport receipts outside the saved Story map.
|
|
6298
|
+
async function runTypedTry(words, cwd, ports) {
|
|
6299
|
+
const {prepareTypedInvocation,formatTypedOutcome}=await import('./try-doors.mjs');
|
|
6300
|
+
const originalPorts=ports, secrets=[];
|
|
6301
|
+
const remember=(...values)=>{
|
|
6302
|
+
for(const value of values) if(typeof value==='string' && value && !secrets.includes(value)) secrets.push(value);
|
|
6303
|
+
// A replacement credential can contain an earlier credential in full.
|
|
6304
|
+
secrets.sort((a,b)=>b.length-a.length);
|
|
6305
|
+
recordSecret(originalPorts,...values);
|
|
6306
|
+
};
|
|
6307
|
+
typedInvocationSecrets.set(remember,secrets);
|
|
6308
|
+
ports={...ports,redaction:{...ports.redaction,remember},rememberSecrets:remember};
|
|
6309
|
+
const emit=answer=>{ports.stdout.write(answer.stdout);ports.stderr.write(answer.stderr);return answer.exit_code;};
|
|
6310
|
+
let release=()=>{}, context;
|
|
6311
|
+
try {
|
|
6312
|
+
const root=repoRoot(cwd), path=relative(root,resolve(cwd,words[0])).split(sep).join('/');
|
|
6313
|
+
const visible=new Set(gitFiles(root));
|
|
6314
|
+
const prompt=readPrompt(root,visible,path), argv=words.slice(1);
|
|
6315
|
+
const local={prompt_path:words[0],argv,interface_json:JSON.stringify(prompt.interface ?? {})};
|
|
6316
|
+
// Help and operation/flag errors do not read stdin or any input file.
|
|
6317
|
+
let prepared=prepareTypedInvocation(local);
|
|
6318
|
+
if (prepared.kind==='help') return emit(prepared);
|
|
6319
|
+
const hasFlags=argv.some(word=>word.startsWith('-'));
|
|
6320
|
+
const inputIndex=argv.indexOf('--input');
|
|
6321
|
+
if (inputIndex>=0 && argv[inputIndex+1]?.startsWith('@') && argv.filter(word=>word==='--input').length===1
|
|
6322
|
+
&& !argv.some(word=>word.startsWith('--') && word!=='--input')) {
|
|
6323
|
+
try {
|
|
6324
|
+
const inputFile=resolve(cwd,argv[inputIndex+1].slice(1)), workspace=loadRuntimeWorkspace({root});
|
|
6325
|
+
// Reuse the source reader's authored and complete link-chain checks when
|
|
6326
|
+
// the workspace ceiling is enabled. Opt-out keeps ordinary local reads.
|
|
6327
|
+
local.input_file_json=workspace.configured
|
|
6328
|
+
? sourceFilePort(root,visible,workspace).read({path:relative(root,inputFile).split(sep).join('/')}).content
|
|
6329
|
+
: readFileSync(inputFile,'utf8');
|
|
6330
|
+
}
|
|
6331
|
+
catch (error) { if(error instanceof RuntimeWorkspaceError || error instanceof PreflightError && error.code?.startsWith('workspace-'))throw error;return emit({...prepared,kind:'usage',operation:null,input_json:null,stdout:'',stderr:'Cannot read the input JSON file.\n'+prepared.stderr,exit_code:2}); }
|
|
6332
|
+
prepared=prepareTypedInvocation(local);
|
|
6333
|
+
} else if (!hasFlags && (typeof ports.stdin==='string' || ports.stdin && !ports.stdin.isTTY)) {
|
|
6334
|
+
// Select the operation before consuming a pipe; a local selector error is final.
|
|
6335
|
+
const names=prompt.interface?.entries ?? [];
|
|
6336
|
+
if (argv.length ? names.filter(entry=>entry.operation===argv[0]).length===1 : names.length===1) {
|
|
6337
|
+
try {
|
|
6338
|
+
const chunks=[];let size=0;
|
|
6339
|
+
const inputChunks=typeof ports.stdin==='string'?[ports.stdin]:ports.stdin;
|
|
6340
|
+
for await (const chunk of inputChunks) { const bytes=Buffer.from(chunk);size+=bytes.length;if(size>1024*1024) throw Error('Input JSON exceeds 1 MiB.');chunks.push(bytes); }
|
|
6341
|
+
local.stdin_json=new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks));
|
|
6342
|
+
} catch {return emit({...prepared,kind:'usage',operation:null,input_json:null,stdout:'',stderr:'Cannot read UTF-8 JSON input (limit 1 MiB).\n'+prepareTypedInvocation({...local,argv:[...argv,'--help']}).stderr,exit_code:2});}
|
|
6343
|
+
prepared=prepareTypedInvocation(local);
|
|
6344
|
+
}
|
|
6345
|
+
}
|
|
6346
|
+
if (prepared.kind!=='call') return emit(prepared);
|
|
6347
|
+
const input=JSON.parse(prepared.input_json), nonce=ports.randomUUID();
|
|
6348
|
+
const parent=dirname(path)==='.'?'':dirname(path)+'/';
|
|
6349
|
+
const name=`pdd-direct-${nonce}`, testPath=`${parent}test/${name}.json`, storyPath=`${parent}user_stories/${name}.md`;
|
|
6350
|
+
const criterionText='The direct operation returns its result.';
|
|
6351
|
+
const criterion={id:'ac-sha256-'+sha256(Buffer.from(storyPath+'\0'+criterionText,'utf8')).slice(0,48),text:criterionText};
|
|
6352
|
+
const doc={schema_version:TEST_SCHEMA,story_path:storyPath,criteria:[criterion],initial_world:{},simulation:{},context:[],steps:[{step_id:'direct',entry_path:path,operation:prepared.operation,input,checks:[{criterion_id:criterion.id,target:'result',path:'',op:'not_equals',value:null}]}]};
|
|
6353
|
+
const capture=ports.captureSource(root,{tests:[testPath],appMap:null,prepareSource(snapshot){
|
|
6354
|
+
for(const candidate of [testPath,storyPath]) if(snapshot.statFile(candidate,{presenceOnly:true}).exists) throw Error('The direct setup name is already in use.');
|
|
6355
|
+
// Scenario integer literals are exact integers; retain admitted Numbers
|
|
6356
|
+
// outside the safe integer range with their exact exponent spelling.
|
|
6357
|
+
const seed=JSON.stringify(doc,(_key,value)=>typeof value==='number'&&Number.isInteger(value)&&!Number.isSafeInteger(value)
|
|
6358
|
+
? JSON.rawJSON(exactNumberSpelling(value)) : value);
|
|
6359
|
+
return [{path:storyPath,bytes:`# Direct prompt invocation\n\n## Acceptance criteria\n\n1. ${criterion.text}\n`},{path:testPath,bytes:seed}];
|
|
6360
|
+
}});
|
|
6361
|
+
const capturedPrompt=capture.sources.find(file=>file.path===path);
|
|
6362
|
+
if(!capturedPrompt || executableInterfaceText(prompt.text)!==Buffer.from(capturedPrompt.bytes).toString('utf8')) throw Error('The selected prompt changed before invocation. Run the command again.');
|
|
6363
|
+
const declaredErrors=new Set(), visited=new Set(), pending=[path];
|
|
6364
|
+
while(pending.length) {
|
|
6365
|
+
const target=pending.shift();if(visited.has(target))continue;visited.add(target);
|
|
6366
|
+
const source=capture.sources.find(source=>source.path===target);
|
|
6367
|
+
if(!source)throw Error('A called prompt is unavailable in the captured source.');
|
|
6368
|
+
const blocks=interfaceBlocks(Buffer.from(source.bytes).toString('utf8'));
|
|
6369
|
+
if(blocks.length!==1)throw Error('A called prompt has no admitted local interface.');
|
|
6370
|
+
const iface=JSON.parse(blocks[0][1]);
|
|
6371
|
+
for(const entry of iface.entries ?? []) for(const error of entry.errors ?? []) {
|
|
6372
|
+
const code=typeof error==='string'?error:error?.code;if(typeof code==='string')declaredErrors.add(code);
|
|
6373
|
+
}
|
|
6374
|
+
for(const call of iface.calls ?? []) if(typeof call?.target==='string')pending.push(call.target);
|
|
6375
|
+
}
|
|
6376
|
+
const store=stateFor(ports.env,root), origin=runtimeOrigin(ports.env), identity=signIn(ports.gh,store,ports,{exitCode:125});
|
|
6377
|
+
const rows=localRows([{test:testPath,story:name,storyPath,title:'Direct prompt invocation',steps:doc.steps,refusals:[]}]);
|
|
6378
|
+
context={ports,root,store,origin,identity,secrets,capture,visible,rows,appMap:null,doorMode:true,interrupted:false,warnings:[],startedAt:ports.now(),deadline:ports.now()+TRY_MS,lint:{request_ids:[],state:null},batch:null,timeoutMin:TRY_MS/60000,agentLimit:false,head:null,folder:store.folder('tries')};
|
|
6379
|
+
release=interruptible(context);
|
|
6380
|
+
context.auth=authSession({identity,store,ports,secrets:context.secrets,signInExitCode:125,expectedOwnerLogin:identity.login});
|
|
6381
|
+
context.runtime=new Runtime({origin,token:identity.token,ports,signal:context.signal,auth:context.auth});
|
|
6382
|
+
await checkLint(context,rows);
|
|
6383
|
+
if(rows.some(row=>row.state!=='ready')) throw Error(rows[0].refusals?.map(row=>row.message || row.code).join('; ') || 'The interpreter refused lint.');
|
|
6384
|
+
const setup={request_ids:[],reservation:null};
|
|
6385
|
+
if(!await admission(context,'try',setup)) throw Error('The interpreter could not start the direct invocation.');
|
|
6386
|
+
const request={requestId:ports.randomUUID(),source_sha256:capture.sha256,seed:testPath,max_calls:400,tab:'call',...sourceProvenance(context)};
|
|
6387
|
+
setup.request_ids.push(request.requestId);
|
|
6388
|
+
if(await recordRuntimeRequest(setup.reservation,request.requestId,slotPorts(context))===false || context.interrupted) throw Error('Stopped before the direct invocation was sent.');
|
|
6389
|
+
const receiptPath=join(context.folder,`${request.requestId}.direct.json`);
|
|
6390
|
+
const receipt={id:request.requestId,root,origin,login:identity.login,prompt:path,operation:prepared.operation,source_sha256:capture.sha256,prompt_hashes:capture.raw_prompt_hashes};
|
|
6391
|
+
store.write(receiptPath,receipt);store.posted(context.folder,request.requestId);
|
|
6392
|
+
const reply=await context.runtime.post('/v1/try',request,capture.tar,ports.postMs);
|
|
6393
|
+
const verdict=judgePost(reply,request.requestId,'try',context.secrets);
|
|
6394
|
+
if(verdict.kind!=='accepted' && verdict.kind!=='unknown') throw Error(verdict.note?.message || verdict.refusal?.message || 'The interpreter refused direct setup.');
|
|
6395
|
+
const done=verdict.answer && ENDED.has(verdict.answer.state)?{answer:verdict.answer}:await readUntil(context,request.requestId,'try',answer=>ENDED.has(answer.state),TRY_MS,'Still starting the direct invocation');
|
|
6396
|
+
if(done.answer) {store.write(join(context.folder,`${request.requestId}.json`),done.answer);await finishReservation(context,setup,done.answer);}
|
|
6397
|
+
if(done.answer?.state!=='passed' || !LIVE_SESSION.has(done.answer.result?.session?.state)) throw Error(done.answer?.result?.refusals?.[0]?.message || 'The direct setup result is unavailable.');
|
|
6398
|
+
const fresh=ports.captureSource(root,{tests:[path],appMap:null});
|
|
6399
|
+
if(Object.entries(capture.raw_file_hashes ?? {}).some(([name,digest])=>fresh.raw_file_hashes?.[name]!==digest)
|
|
6400
|
+
|| capture.sources.filter(source=>source.path.endsWith('.prompt.md')).some(source=>!fresh.sources.some(current=>current.path===source.path && Buffer.from(current.bytes).equals(Buffer.from(source.bytes))))) throw Error('The source changed during setup. No operation was sent.');
|
|
6401
|
+
const answer=await runDoorCall({root,origin,login:identity.login,sessionId:request.requestId,prompt:path,operation:prepared.operation,declaredErrors:[...declaredErrors],directTyped:true},input,{...ports,signal:context.signal});
|
|
6402
|
+
store.write(receiptPath,{...receipt,call_id:answer.id,outcome:answer.error?'program_error':'result'});
|
|
6403
|
+
try {await stopTry(context,{id:request.requestId});store.write(receiptPath,{...receipt,call_id:answer.id,outcome:answer.error?'program_error':'result',stopped:true});}
|
|
6404
|
+
catch {line(ports.stderr,'pdd: The command completed, but its private Try could not be confirmed stopped.');}
|
|
6405
|
+
// Redact JSON strings before serialization so escaping and scalar types survive.
|
|
6406
|
+
const redactString=value=>secrets.reduce((text,secret)=>text.split(secret).join('[secret]'),value);
|
|
6407
|
+
const redactValue=value=>{
|
|
6408
|
+
if(typeof value==='string')return redactString(value);
|
|
6409
|
+
if(Array.isArray(value))return value.map(redactValue);
|
|
6410
|
+
if(!isObject(value))return value;
|
|
6411
|
+
const entries=Object.entries(value),used=new Set(entries.filter(([key])=>redactString(key)===key).map(([key])=>key));
|
|
6412
|
+
return Object.fromEntries(entries.map(([key,item])=>{
|
|
6413
|
+
const masked=redactString(key);let name=masked;
|
|
6414
|
+
// Keep ordinary keys and all values when credential-bearing keys collide.
|
|
6415
|
+
if(masked!==key)for(let suffix=2;used.has(name);suffix++)name=`${masked} (${suffix})`;
|
|
6416
|
+
used.add(name);return [name,redactValue(item)];
|
|
6417
|
+
}));
|
|
6418
|
+
};
|
|
6419
|
+
// Runtime diagnostics remain lossless apart from known credentials.
|
|
6420
|
+
const safeError=answer.error?JSON.parse(JSON.stringify(answer.error,(key,value)=>typeof value==='string'?context.secrets.reduce((text,secret)=>secret?text.split(secret).join('[secret]'):text,value):value)):null;
|
|
6421
|
+
return emit(formatTypedOutcome(safeError?{outcome:'program_error',error_json:JSON.stringify(safeError)}:{outcome:'result',result_json:JSON.stringify(redactValue(answer.result))}));
|
|
6422
|
+
} catch(error) {return emit(formatTypedOutcome({outcome:'interpreter_error',error_json:JSON.stringify({message:cleanText(error.message,secrets)})}));}
|
|
6423
|
+
finally {release();await Promise.all([...(context?.reservations ?? [])].map(reservation=>releaseRuntimeSlot(reservation,{ended:false},slotPorts(context))));}
|
|
6424
|
+
}
|
|
6425
|
+
|
|
6426
|
+
// pdd simulate and direct prompt commands return the command exit code.
|
|
4935
6427
|
export async function runTry({ words = [], options = {}, cwd = process.cwd() } = {}, givenPorts = {}) {
|
|
6428
|
+
if (shouldUseTypedTry(words, options, cwd)) return runTypedTry(words, cwd, withDefaults(givenPorts));
|
|
6429
|
+
if (shouldUseDirectProgram(words, options, cwd)) return runDirectProgram({words,options,cwd},withDefaults(givenPorts));
|
|
4936
6430
|
options = { ...options };
|
|
4937
6431
|
const ports = withDefaults(givenPorts), context = { ports, interrupted: false, doorMode: false, warnings: [] };
|
|
4938
6432
|
let release = () => {};
|
|
4939
6433
|
try {
|
|
6434
|
+
context.liveLocal=liveLocalOptions(options,'try');
|
|
4940
6435
|
const productMode=options['--product']===true;
|
|
4941
6436
|
if(options['--product']!==undefined&&!productMode || !productMode&&['--parts','--journey'].some(key=>options[key]!==undefined))throw new Stop(2,'--parts and --journey require --product.');
|
|
4942
6437
|
if(productMode&&options['--app-map']!==undefined)throw new Stop(2,'--product builds its map; omit --app-map.');
|
|
4943
6438
|
const requestedBudget = requestedCalls(options['--max-calls']);
|
|
6439
|
+
if (words.length === 1 && (words[0].endsWith('.prompt.md') || basename(words[0]) === 'app-map.json')) return await runProgramTry({ cwd, word: words[0], options, context, requestedBudget });
|
|
4944
6440
|
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.');
|
|
4945
6441
|
const doorModes = [options['--cli'] || options['--shell'], options['--serve'] !== undefined, options['--page'] || options['--tab'] !== undefined || options['--agent'] !== undefined, options['--save-last']].filter(Boolean);
|
|
4946
6442
|
if (doorModes.length > 1 || (doorModes.length && options['--stop'])
|
|
4947
|
-
|| (options['--save-last'] && (words.length || Object.keys(options).length !== 1))) throw new Stop(2, 'Choose one of --cli (with optional --shell), --shell, --serve, --page, --save-last or --stop.');
|
|
6443
|
+
|| (options['--save-last'] && (words.length > 1 || Object.keys(options).length !== 1))) throw new Stop(2, 'Choose one of --cli (with optional --shell), --shell, --serve, --page, --save-last or --stop.');
|
|
4948
6444
|
if (options['--save-last']) {
|
|
4949
6445
|
const root = repoRoot(cwd), store = stateFor(ports.env, root);
|
|
4950
|
-
const
|
|
4951
|
-
|
|
6446
|
+
const test = words.length ? (() => { const {found,normalized} = localSetup(cwd,words,ports); return oneTest(found,normalized,root,ports); })() : null;
|
|
6447
|
+
const repo = store.repo(root), pointer = test ? null : repo.last_door;
|
|
6448
|
+
const descriptor = test ? repo.last_run?.descriptor : pointer?.descriptor ? store.read(pointer.descriptor) : null;
|
|
6449
|
+
const policy = loadRuntimeWorkspace({root});
|
|
6450
|
+
const targetPath = test?.path ?? descriptor?.originalPath, storyPath = test?.doc?.story_path ?? descriptor?.storyPath;
|
|
6451
|
+
for (const [path,role] of [[targetPath,'original test'],[storyPath,'original Story'], ...[...new Set([descriptor?.prompt,...Object.keys(descriptor?.promptHashes??{}),...Object.keys(descriptor?.effectivePromptHashes??{})].filter(Boolean))].map(path=>[path,'recorded prompt'])]) if(path) requireRuntimePath(policy,{path,role});
|
|
6452
|
+
if (targetPath) ports.captureSource(root,{tests:[targetPath]});
|
|
6453
|
+
if (descriptor?.prompt) ports.captureSource(root,{tests:[descriptor.prompt]});
|
|
4952
6454
|
const identity = signIn(ports.gh, store, ports);
|
|
4953
|
-
return await (await import('./try-doors.mjs')).saveLast({ root, store, identity, ports });
|
|
6455
|
+
return await (await import('./try-doors.mjs')).saveLast({ root, store, identity, ports, test });
|
|
4954
6456
|
}
|
|
4955
6457
|
if (options['--stop'] && (options['--tab'] || options['--new'] || options['--no-open'] || options['--no-wait'] || options['--app-map'] !== undefined || productMode || requestedBudget !== null)) throw new Stop(2, 'pdd simulate --stop takes only a STORY. Run pdd simulate --help.');
|
|
4956
6458
|
if (words.length > 1) throw new Stop(2, 'pdd simulate takes one STORY.');
|
|
4957
6459
|
const origin = runtimeOrigin(ports.env);
|
|
4958
6460
|
if (options['--stop']) return await stopByName(context, cwd, words, origin);
|
|
4959
6461
|
const { root, found, normalized } = localSetup(cwd, words, ports), store = stateFor(ports.env, root);
|
|
6462
|
+
await prepareLiveManifest(context,options,root);
|
|
4960
6463
|
const repoState = store.repo(root);
|
|
4961
6464
|
if (!productMode && normalized.length && !options['--new']) {
|
|
4962
6465
|
const prior = repoState.tries?.[oneTest(found, normalized, root, ports).path];
|
|
@@ -4999,7 +6502,7 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
|
|
|
4999
6502
|
context.product_setup = productSetup;
|
|
5000
6503
|
context.typedForm = typed;
|
|
5001
6504
|
context.doorMode = !!(options['--cli'] || options['--serve'] !== undefined);
|
|
5002
|
-
context.agentConnection = !options['--no-wait'] && !context.doorMode && ports.agentBridge !== false
|
|
6505
|
+
context.agentConnection = !context.liveLocal && !options['--no-wait'] && !context.doorMode && ports.agentBridge !== false
|
|
5003
6506
|
&& (ports.stdout.isTTY === true || options['--agent'] !== undefined);
|
|
5004
6507
|
if (context.agentConnection) {
|
|
5005
6508
|
const loadDefinitions = ports.loadAgentDefinitions ?? ports.agents?.loadDefinitions;
|
|
@@ -5028,6 +6531,7 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
|
|
|
5028
6531
|
}
|
|
5029
6532
|
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.');
|
|
5030
6533
|
const identity = context.probedIdentity ?? signIn(ports.gh, context.store, ports, { exitCode: context.doorMode ? 125 : 5 });
|
|
6534
|
+
if(context.liveLocal)context.localOwner??=identity.login;
|
|
5031
6535
|
Object.assign(context, { capture, identity, secrets: [identity.token], startedAt: ports.now(), deadline: ports.now() + TRY_MS, lint: { request_ids: [], state: null },
|
|
5032
6536
|
batch: null, rows, timeoutMin: TRY_MS / 60_000, agentLimit: false, head: null });
|
|
5033
6537
|
context.folder = store.folder('tries');
|
|
@@ -5041,15 +6545,16 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
|
|
|
5041
6545
|
signInExitCode: context.doorMode ? 125 : 5,
|
|
5042
6546
|
expectedOwnerLogin: () => activeOwner,
|
|
5043
6547
|
ownerMismatchError: owner => new Stop(context.doorMode ? 125 : 5, `This Try belongs to ${owner}. Run: gh auth switch -u ${owner}`),
|
|
5044
|
-
onRefresh: next => {
|
|
6548
|
+
onRefresh: async next => {
|
|
5045
6549
|
context.identity = next;
|
|
5046
|
-
|
|
5047
|
-
|
|
5048
|
-
|
|
5049
|
-
}
|
|
6550
|
+
await store.updateRepo(root, latest => {
|
|
6551
|
+
const current = latest.tries?.[test.path];
|
|
6552
|
+
if (current && (!record || options['--new'] || current.id !== record.id)) return { ...latest, tries: { ...latest.tries, [test.path]: { ...current, login: next.login } } };
|
|
6553
|
+
});
|
|
5050
6554
|
},
|
|
5051
6555
|
});
|
|
5052
6556
|
context.runtime = new Runtime({ origin, token: identity.token, ports, signal: context.signal, auth: context.auth });
|
|
6557
|
+
if(context.liveLocal&&record&&!options['--new'])throw new Stop(2,'A live-local simulation needs --new. Saved sessions remain observational without --live-local.');
|
|
5053
6558
|
if (record) {
|
|
5054
6559
|
const needsOwner = context.doorMode || requestedBudget !== null || context.agentConnection;
|
|
5055
6560
|
if (needsOwner && record.login && record.login !== identity.login) throw new Stop(context.doorMode ? 125 : 5, `This Try belongs to ${record.login}. Run: gh auth switch -u ${record.login}`);
|
|
@@ -5091,8 +6596,7 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
|
|
|
5091
6596
|
throw new Stop(3, `The last Try for "${test.title}" is not ready or its state is unknown. Run pdd simulate ${test.story} again later, or pdd simulate ${test.story} --new to stop it and make a new one.`);
|
|
5092
6597
|
}
|
|
5093
6598
|
if (!ended) { line(ports.stderr, 'Stopping the old Try…'); await stopTry(context, record); }
|
|
5094
|
-
delete
|
|
5095
|
-
store.saveRepo(root, repoState);
|
|
6599
|
+
await store.updateRepo(root, current => { if (current.tries?.[recordPath]?.id === record.id) delete current.tries[recordPath]; return current; });
|
|
5096
6600
|
activeOwner = null;
|
|
5097
6601
|
}
|
|
5098
6602
|
if(prepared){
|
|
@@ -5106,6 +6610,8 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
|
|
|
5106
6610
|
line(ports.stderr,`Product parts: ${prepared.composition.parts.join(', ')}. One tap: up to ${prepared.maxTapCalls} AI calls.`);
|
|
5107
6611
|
line(ports.stderr,`Product screens: ${prepared.composition.labels.map(label=>label.title).join(', ')}. Up to ${prepared.composition.tapOperations} handler/background operations per tap, before drawing.`);
|
|
5108
6612
|
}
|
|
6613
|
+
if(context.liveLocal){context.auth.expectedOwnerLogin=context.localOwner;context.auth.ownerMismatchError=()=>new Stop(5,'live-local-owner-changed');}
|
|
6614
|
+
await ensureLocalSource(context,capture);
|
|
5109
6615
|
await checkLint(context, rows);
|
|
5110
6616
|
const failedRow = rows.find(item => item.state !== 'ready');
|
|
5111
6617
|
if (failedRow && failedRow !== row) {
|
|
@@ -5129,14 +6635,16 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
|
|
|
5129
6635
|
...(context.serverFeatures?.includes('lazy-interfaces') ? { lazy_interfaces: true } : {}),
|
|
5130
6636
|
...sourceProvenance(context, capture),
|
|
5131
6637
|
tab };
|
|
6638
|
+
let localBridge;
|
|
6639
|
+
if(context.liveLocal){localBridge=await newLocalBridge(context,'try',request.requestId);request.resource_setup=localBridge.resource_setup;}
|
|
5132
6640
|
setup.request_ids.push(request.requestId);
|
|
5133
6641
|
const registered = await recordRuntimeRequest(setup.reservation, request.requestId, slotPorts(context));
|
|
5134
6642
|
if (registered === false) { await finishReservation(context, setup, { state: 'not_run' }); throw new Stop(3, context.interrupted ? 'Stopped before sending.' : 'Stopped before the Try was sent.'); }
|
|
5135
6643
|
if (context.interrupted || ports.now() >= context.deadline) { await finishReservation(context, setup, { state: 'not_run' }); throw new Stop(3, context.interrupted ? 'Stopped before sending.' : 'Stopped before the Try was sent.'); }
|
|
5136
6644
|
const uploadedSeed=capture.sources.find(file=>file.path===test.path);
|
|
5137
|
-
const tryRecord = { id: request.requestId, ...setup, story: test.story, storyPath: test.storyPath, title: test.title, origin, login: identity.login, source_sha256: capture.sha256, max_calls: request.max_calls, ...(!productSetup && !words.length ? { simulation_scope: { tests: selected.map(item => item.path), appMap, appMapHash: appMap ? sha256(capture.sources.find(file => file.path === appMap).bytes) : null } } : {}), seed_scenario: uploadedSeed ?
|
|
6645
|
+
const tryRecord = { ...(context.liveLocal?{live_local:true,resource_setup:localBridge.resource_setup}:{}),id: request.requestId, ...setup, story: test.story, storyPath: test.storyPath, title: test.title, origin, login: identity.login, source_sha256: capture.sha256, max_calls: request.max_calls, ...(!productSetup && !words.length ? { simulation_scope: { tests: selected.map(item => item.path), appMap, appMapHash: appMap ? sha256(capture.sources.find(file => file.path === appMap).bytes) : null } } : {}), seed_scenario: uploadedSeed ? parseProgramJson(uploadedSeed.bytes.toString('utf8')) : test.doc, story_sha256: createHash('sha256').update(readFileSync(join(root, test.storyPath))).digest('hex'), prompt_hashes: capture.raw_prompt_hashes,
|
|
5138
6646
|
effective_prompt_hashes:Object.fromEntries(capture.sources.filter(file=>file.path.endsWith('.prompt.md')).map(file=>[file.path,sha256(file.bytes)])),contract_references:capture.references, ...(productSetup?{product_setup:productSetup,product_parts:prepared.composition.product_parts}:{}) };
|
|
5139
|
-
store.
|
|
6647
|
+
await store.updateRepo(root, current => ({ ...current, tries: { ...current.tries, [test.path]: tryRecord } }));
|
|
5140
6648
|
store.posted(context.folder, request.requestId);
|
|
5141
6649
|
line(ports.stderr, `Starting your Try: sending ${capture.files.length} files, ${formatSize(capture.bytes)}${note ? ` ${note}` : ''}…`);
|
|
5142
6650
|
reply = await context.runtime.post('/v1/try', request, capture.tar, Math.max(1, Math.min(ports.postMs, context.deadline - ports.now())));
|
|
@@ -5148,17 +6656,18 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
|
|
|
5148
6656
|
await finishReservation(context, setup, { state: 'not_run' });
|
|
5149
6657
|
if (!verdict.maintenance) line(ports.stderr, 'The interpreter is busy. Waiting to start your Try…');
|
|
5150
6658
|
if (await waitBudget(context, verdict.wait)) continue;
|
|
5151
|
-
delete
|
|
6659
|
+
await store.updateRepo(root, current => { if (current.tries?.[test.path]?.id === request.requestId) delete current.tries[test.path]; return current; });
|
|
5152
6660
|
throw new Stop(context.interrupted ? 3 : 5, context.interrupted ? stoppedPause(context, setup, 'Try setup') : 'The interpreter stayed busy until the Try setup wait ended.');
|
|
5153
6661
|
}
|
|
5154
6662
|
if (verdict.kind !== 'accepted') {
|
|
5155
|
-
if (verdict.kind !== 'unknown') { await finishReservation(context, setup, { state: 'not_run' }); delete
|
|
6663
|
+
if (verdict.kind !== 'unknown') { await finishReservation(context, setup, { state: 'not_run' }); await store.updateRepo(root, current => { if (current.tries?.[test.path]?.id === request.requestId) delete current.tries[test.path]; return current; }); }
|
|
5156
6664
|
if (reply.status === 429) throw new Stop(5, cleanText(reply.json?.error?.message, context.secrets) || 'Too many Try links are open. Stop one with pdd simulate --stop');
|
|
5157
6665
|
if (verdict.kind === 'refused') return trySetupRefused(context, test, appMap, [{ ...reply.json.error, ...verdict.refusal }], null);
|
|
5158
6666
|
if (verdict.blocked) throw new Stop(5, verdict.note.message);
|
|
5159
6667
|
if (verdict.kind === 'not_run' || verdict.kind === 'stop') throw new Stop(5, `${verdict.note.message}${verdict.note.code ? ` (${verdict.note.code})` : ''}`);
|
|
5160
6668
|
throw new Stop(3, `The Try setup result is unknown. Run pdd simulate ${test.story} again later: it reads this Try first and sends nothing new while it runs.`);
|
|
5161
6669
|
}
|
|
6670
|
+
if(context.liveLocal)await startLocalBridge(context,localBridge,request.requestId);
|
|
5162
6671
|
done = ENDED.has(verdict.answer.state) ? { answer: verdict.answer }
|
|
5163
6672
|
: await readUntil(context, request.requestId, 'try', answer => ENDED.has(answer.state), TRY_MS, 'Still starting your Try');
|
|
5164
6673
|
if (done.answer) await finishReservation(context, setup, done.answer);
|
|
@@ -5171,11 +6680,7 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
|
|
|
5171
6680
|
if (requestedBudget !== null && !Number.isSafeInteger(cap)) throw new Stop(3, 'The interpreter did not confirm the requested Try budget. The same Try is kept; read it again without changing its budget.');
|
|
5172
6681
|
const confirmedEngine = validEngineHex(done.answer?.engine_sha);
|
|
5173
6682
|
if (confirmedEngine) {
|
|
5174
|
-
|
|
5175
|
-
if (currentRepo.tries?.[test.path]?.id === request.requestId) {
|
|
5176
|
-
currentRepo.tries[test.path].engine_sha = confirmedEngine;
|
|
5177
|
-
store.saveRepo(root, currentRepo);
|
|
5178
|
-
}
|
|
6683
|
+
await store.updateRepo(root, current => { if (current.tries?.[test.path]?.id === request.requestId) current.tries[test.path].engine_sha = confirmedEngine; return current; });
|
|
5179
6684
|
}
|
|
5180
6685
|
return await showTry(context, test, link, options, request.requestId, false, done.answer?.result?.session, done.answer, store.repo(root).tries?.[test.path]);
|
|
5181
6686
|
}
|
|
@@ -5188,8 +6693,7 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
|
|
|
5188
6693
|
// A ready Try with a bad link stays recorded, so pdd simulate --stop can still end it; pdd never prints that link.
|
|
5189
6694
|
if (done.answer.state === 'passed' && LIVE_SESSION.has(done.answer.result?.session?.state)) throw new Stop(3, refusedLink(done.answer, origin));
|
|
5190
6695
|
applyAnswer(row, done.answer, context);
|
|
5191
|
-
delete
|
|
5192
|
-
store.saveRepo(root, repoState);
|
|
6696
|
+
await store.updateRepo(root, current => { if (current.tries?.[test.path]?.id === request.requestId) delete current.tries[test.path]; return current; });
|
|
5193
6697
|
if (row.state === 'refused') {
|
|
5194
6698
|
const report = isObject(done.answer.result?.report?.refusal) ? done.answer.result.report.refusal : null, given = done.answer.result?.refusals;
|
|
5195
6699
|
const refusals = (Array.isArray(given) && given.length ? given : report ? [report] : []).filter(isObject)
|
|
@@ -5211,7 +6715,7 @@ export async function runTry({ words = [], options = {}, cwd = process.cwd() } =
|
|
|
5211
6715
|
return error.exitCode;
|
|
5212
6716
|
}
|
|
5213
6717
|
throw error;
|
|
5214
|
-
} finally { release();for(const lease of context.caseWriteLeases?.values()??[])lease.release(); await Promise.all([...(context.reservations ?? [])].map(reservation => releaseRuntimeSlot(reservation, { ended: false }, slotPorts(context)))); }
|
|
6718
|
+
} finally { await closeLocalBridges(context);release();for(const lease of context.caseWriteLeases?.values()??[])lease.release(); await Promise.all([...(context.reservations ?? [])].map(reservation => releaseRuntimeSlot(reservation, { ended: false }, slotPorts(context)))); }
|
|
5215
6719
|
}
|
|
5216
6720
|
|
|
5217
6721
|
// pdd simulate --stop [STORY]: find the Try by its exact Try ID or story/test selector in the state record, so it works on any branch (real-user issue 14).
|
|
@@ -5249,8 +6753,7 @@ async function stopByName(context, cwd, words, origin) {
|
|
|
5249
6753
|
context.runtime = new Runtime({ origin: record.origin ?? origin, token: identity.token, ports, auth: context.auth });
|
|
5250
6754
|
line(ports.stderr, `Stopping the Try for "${title}"…`);
|
|
5251
6755
|
await stopTry(context, record);
|
|
5252
|
-
delete
|
|
5253
|
-
store.saveRepo(root, repoState);
|
|
6756
|
+
await store.updateRepo(root, current => { if (current.tries?.[path]?.id === record.id) delete current.tries[path]; return current; });
|
|
5254
6757
|
line(ports.stdout, `The Try link for "${title}" is stopped.`);
|
|
5255
6758
|
return 0;
|
|
5256
6759
|
}
|
|
@@ -5262,10 +6765,10 @@ async function checkLint(context, rows) {
|
|
|
5262
6765
|
if (lint.kind === 'refused') { Object.assign(rows[0], { state: 'refused', phase: 'lint', refusals: [lint.refusal], raw_refusals: [lint.refusal] }); return; }
|
|
5263
6766
|
if (context.doorMode && lint.kind === 'answer' && lint.answer?.state === 'refused' && !isObject(lint.answer.result?.report?.program)) {
|
|
5264
6767
|
const refusal = lint.answer.result?.refusals?.[0] ?? lint.answer.result?.report?.refusal;
|
|
5265
|
-
throw new Stop(125, refusal?.reason || refusal?.message || refusal?.code || 'The interpreter refused lint.');
|
|
6768
|
+
throw Object.assign(new Stop(125, refusal?.reason || refusal?.message || refusal?.code || 'The interpreter refused lint.'),{fix:refusal?.fix});
|
|
5266
6769
|
}
|
|
5267
6770
|
// A Try uses AI calls, so it passes the same lint gate as a check.
|
|
5268
|
-
if (rows.every(row => lintAdmits(lint.answer, row, context.capture, context.appMap))) { for (const text of lintDiagnostics(context, lint.answer, rows)) line(context.ports.stderr, text); return; }
|
|
6771
|
+
if (rows.every(row => lintAdmits(lint.answer, row, context.capture, context.appMap))) { for (const text of lintDiagnostics(context, lint.answer, rows)) line(context.ports.stderr, text); return lint.answer; }
|
|
5269
6772
|
const verdicts = judgeLint(lint.answer, rows, context.root, context.visible, context.secrets, context.capture, context.appMap);
|
|
5270
6773
|
const report = isObject(lint.answer?.result?.report?.refusal) ? lint.answer.result.report.refusal : null;
|
|
5271
6774
|
const reportUrl = validLink(cleanText(lint.answer?.report_url, context.secrets), context.origin, 'report');
|
|
@@ -5290,6 +6793,7 @@ async function checkLint(context, rows) {
|
|
|
5290
6793
|
}
|
|
5291
6794
|
throw new Stop(5, `No lint pass for this test (${ended.reason ?? ended.message}), so pdd made no Try link.`);
|
|
5292
6795
|
}
|
|
6796
|
+
return lint.answer;
|
|
5293
6797
|
}
|
|
5294
6798
|
|
|
5295
6799
|
// A refused Try setup is not a check (runtime team, Oct 27): two plain lines with what was refused, why and the fix; no table.
|
|
@@ -5402,12 +6906,34 @@ async function showTry(context, test, link, options, tryId, reused = false, sess
|
|
|
5402
6906
|
line(ports.stdout, `${options['--no-open'] ? '' : 'pdd could not open a browser. Open the link yourself. '}Anyone with the link can use it. ${ends}`);
|
|
5403
6907
|
if (bridge) line(ports.stdout, `Owner agent chat link (private; do not share): ${bridge.url}`);
|
|
5404
6908
|
}
|
|
6909
|
+
if(context.liveLocal){
|
|
6910
|
+
line(ports.stderr,'Owner-local command service is active. Keep this process running; interrupting revokes local authority.');
|
|
6911
|
+
await context.localServices.get(tryId);
|
|
6912
|
+
if(context.localBridgeError)throw new Stop(3,'Owner-local command service stopped. The original session is kept for observation.');
|
|
6913
|
+
return context.interrupted?3:0;
|
|
6914
|
+
}
|
|
5405
6915
|
if (!bridge) { await watchSavedTests(context, tryId, !options['--no-wait'] && ports.interactive, test.story); return 0; }
|
|
5406
6916
|
answers = ports.interactive ? ports.lineReader(ports.stdin) : null;
|
|
5407
6917
|
context.onAgentChatClose = () => answers?.close();
|
|
5408
|
-
return await bridge.run(async
|
|
5409
|
-
|
|
5410
|
-
|
|
6918
|
+
return await bridge.run(async hints => {
|
|
6919
|
+
if (!hints) { // Preserve direct/custom bridge callers.
|
|
6920
|
+
const tests = await collectSavedTests(context, tryId), approvals = await collectApprovals(context, tryId, test.story, answers);
|
|
6921
|
+
return tests !== 'ended' && approvals !== 'ended';
|
|
6922
|
+
}
|
|
6923
|
+
context.caseHandoffs ??= new Map(); context.caseWriteLeases ??= new Map();
|
|
6924
|
+
const collection = { ...context, signal: hints.signal, runtime: { send: (path, init, ms) => context.runtime.send(path, init?.method === 'GET' ? { ...init, signal: hints.signal } : init, ms) } };
|
|
6925
|
+
const categories = {};
|
|
6926
|
+
for (const category of hints.read) {
|
|
6927
|
+
if (hints.signal.aborted) break;
|
|
6928
|
+
categories[category] = category === 'tests' ? await collectSavedTests(collection, tryId, true)
|
|
6929
|
+
: await collectApprovals(collection, tryId, test.story, answers, true);
|
|
6930
|
+
if (categories[category].outcome === 'ended') break;
|
|
6931
|
+
}
|
|
6932
|
+
if (Object.values(categories).some(result => result.outcome === 'ended')) return { categories };
|
|
6933
|
+
const delivery = !hints.signal.aborted && (hints.postApprovals || hints.read.includes('approvals'))
|
|
6934
|
+
? await deliverApprovalAnswers(collection, tryId) : null;
|
|
6935
|
+
if (delivery?.ended) return false;
|
|
6936
|
+
return { categories, ...(delivery ? { delivery: {pending:delivery.pending,retryMs:delivery.retryMs} } : {}) };
|
|
5411
6937
|
});
|
|
5412
6938
|
} finally { answers?.close(); await bridge?.close(); }
|
|
5413
6939
|
}
|
|
@@ -5510,7 +7036,7 @@ function caseArea(root,p,{create=true}={}){
|
|
|
5510
7036
|
return area;
|
|
5511
7037
|
}
|
|
5512
7038
|
const caseResult=(record,state,reason,extra={})=>({state,path:record.target??null,pendingId:record.pendingId,reason,recoveryPath:record.recoveryPath,...extra});
|
|
5513
|
-
function caseMessage(result){return result.state==='committed'?`${result.duplicate?'already saved to':'added to'} ${result.path}${result.steps?.length?' as step '+result.steps.join(', '):''}`:`not added: ${result.reason}. Case retained at ${result.recoveryPath} (pending ${result.pendingId}).`;}
|
|
7039
|
+
function caseMessage(result){return result.state==='committed'?`${result.duplicate?'already saved to':'added to'} ${result.path}${!result.duplicate&&result.steps?.length?' as step '+result.steps.join(', '):''}`:`not added: ${result.reason}. Case retained at ${result.recoveryPath} (pending ${result.pendingId}).`;}
|
|
5514
7040
|
const caseOutcome=result=>({kind:'case',result,message:caseMessage(result)});
|
|
5515
7041
|
function retainCase(root,saved,options,p){
|
|
5516
7042
|
const original=options.seedTest??{path:saved?.original_path,storyPath:saved?.story_path??saved?.test?.story_path};
|
|
@@ -5612,7 +7138,7 @@ function caseImportState(root,record,p,{inspect=false,reconcile=false,reason='re
|
|
|
5612
7138
|
const journal=record.recoveryPath.replace('.received.json','.transaction.json');
|
|
5613
7139
|
if(!caseStat(p,journal))return{};
|
|
5614
7140
|
const transaction=JSON.parse(caseRead(p,journal));
|
|
5615
|
-
if(transaction.state==='committed')return{result:caseResult(record,'committed','already applied',{path:transaction.path,duplicate:true})};
|
|
7141
|
+
if(transaction.state==='committed')return{result:caseResult(record,'committed','already applied',{path:transaction.path,duplicate:true,...(transaction.steps?.length?{steps:transaction.steps}:{})})};
|
|
5616
7142
|
// Only a conflict recorded before publication retains the observed baseline
|
|
5617
7143
|
// in its history. Older conflicts lost their phase, so absence is uncertain.
|
|
5618
7144
|
if(transaction.state==='conflict'&&!transaction.observed?.includes(transaction.before))
|
|
@@ -5679,7 +7205,7 @@ export const saveDoorCaseResult=(root,saved,options={})=>{
|
|
|
5679
7205
|
const p=casePorts(options.ports??{env:options.env});let record;
|
|
5680
7206
|
try{root=p.files.realpath(root);record=retainCase(root,saved,options,p);
|
|
5681
7207
|
const known=caseImportState(root,record,p);if(known.result)return caseOutcome(known.result);
|
|
5682
|
-
if(options.writeOwnership)return caseOutcome(applyPendingCaseSync({root,pendingId:record.pendingId,writeOwnership:options.writeOwnership,signal:options.signal},options.ports??{env:options.env}));
|
|
7208
|
+
if(options.writeOwnership)return caseOutcome(applyPendingCaseSync({root,pendingId:record.pendingId,writeOwnership:options.writeOwnership,signal:options.signal},options.ports??{env:options.env},options.publicationGuard));
|
|
5683
7209
|
let reason;try{prepareCase(root,record,p);}catch(error){if(error?.unboundPort)throw error;reason=error.message;}
|
|
5684
7210
|
const result=caseResult(record,'pending',options.signal?.aborted?'case save cancelled':reason??'close the editor for the named original test and apply the retained case with supported ownership');return caseOutcome(result);}
|
|
5685
7211
|
catch(error){if(error?.unboundPort)throw error;return{kind:'failure',message:`not added: durable case receipt failed (${cleanText(error.message??error)}).${record?' Recovery: '+record.recoveryPath:''}`};}
|
|
@@ -5692,7 +7218,7 @@ function retainedCaseAuthority(root,record,p){
|
|
|
5692
7218
|
const directory=caseStateDirectory(p.env,root,p),meta=JSON.parse(caseRead(p,join(directory,'calls',action+'.meta.json')));
|
|
5693
7219
|
if(meta.id!==action||meta.root!==root||typeof meta.session_id!=='string'||!UUID.test(meta.session_id)
|
|
5694
7220
|
||record.identity.session!=null&&record.identity.session!==meta.session_id)throw Error('original local call authority does not match this receipt');
|
|
5695
|
-
const repo=
|
|
7221
|
+
const repo=parseProgramJson(caseRead(p,join(directory,'repos',sha256(Buffer.from(root)).slice(0,16)+'.json')));
|
|
5696
7222
|
if(repo.root!==root||!isObject(repo.tries))throw Error('original local Try authority is unavailable');
|
|
5697
7223
|
const matches=Object.entries(repo.tries).filter(([,value])=>value?.id===meta.session_id);
|
|
5698
7224
|
if(matches.length!==1)throw Error('original local Try authority is missing or ambiguous');
|
|
@@ -5779,42 +7305,63 @@ async function caseHandoff(context,testPath){
|
|
|
5779
7305
|
if(context.ports.caseHandoff)return context.ports.caseHandoff({root:context.root,testPath,signal:context.signal});
|
|
5780
7306
|
if(!context.ports.interactive||context.signal?.aborted)return null;
|
|
5781
7307
|
line(context.ports.stdout,`Close the editor for ${testPath}. Hand over this closed file for the pending case apply? y/N`);
|
|
5782
|
-
const answers=context.ports.lineReader(context.ports.stdin)
|
|
7308
|
+
const answers=context.ports.lineReader(context.ports.stdin),close=()=>answers.close();
|
|
7309
|
+
context.signal?.addEventListener('abort',close,{once:true});
|
|
7310
|
+
try{if(context.signal?.aborted)return null;const answer=await answers.ask();return !context.signal?.aborted&&/^y(?:es)?$/i.test(answer.trim())?{kind:'closed-editor',testPath}:null;}finally{context.signal?.removeEventListener('abort',close);answers.close();}
|
|
7311
|
+
}
|
|
7312
|
+
|
|
7313
|
+
// Shared Try read/delivery delay. A present invalid header wins over the envelope.
|
|
7314
|
+
export function tryRetryDelay(reply) {
|
|
7315
|
+
if (reply.headers?.has?.('retry-after') || reply.headers?.get?.('retry-after') != null) return retryAfter(reply.headers);
|
|
7316
|
+
const seconds = reply.json?.error?.details?.retry_after;
|
|
7317
|
+
return typeof seconds === 'number' && Number.isFinite(seconds) && seconds > 0 ? Math.ceil(Math.min(300, Math.max(1, seconds)) * 1000) : 5000;
|
|
7318
|
+
}
|
|
7319
|
+
function savedListOutcome(reply, key) {
|
|
7320
|
+
if ([401,403,410].includes(reply.status)) return {outcome:'ended',retryMs:0};
|
|
7321
|
+
if (reply.status === 404) return {outcome:'missing',retryMs:0};
|
|
7322
|
+
if (reply.status !== 200 || !Array.isArray(reply.json?.[key]) || !reply.json[key].every(record => {
|
|
7323
|
+
if (!isObject(record) || typeof record.id !== 'string' || !record.id) return false;
|
|
7324
|
+
if (key === 'tests') return isObject(record.test);
|
|
7325
|
+
return /^[A-Za-z0-9_-]{1,128}$/.test(record.id) && ['pending','done','declined'].includes(record.state)
|
|
7326
|
+
&& typeof record.prompt_path === 'string' && typeof record.prose_sha256 === 'string';
|
|
7327
|
+
})) return {outcome:'retry',retryMs:tryRetryDelay(reply)};
|
|
7328
|
+
return null;
|
|
5783
7329
|
}
|
|
7330
|
+
const legacyCollectionOutcome = result => result.outcome === 'success' || result.outcome === 'retry' ? 'ok' : result.outcome;
|
|
5784
7331
|
|
|
5785
7332
|
// Saved cases: add each new one once. Returns 'ok', 'missing' (no endpoint yet) or 'ended'.
|
|
5786
|
-
async function collectSavedTests(context, tryId) {
|
|
7333
|
+
async function collectSavedTests(context, tryId, detailed = false) {
|
|
5787
7334
|
const { ports, store, root } = context, path = join(store.folder('tries'), `${tryId}.tests.json`);
|
|
5788
7335
|
const reply = await context.runtime.send(`/v1/try/${tryId}/tests`, { method: 'GET' }, GET_MS);
|
|
5789
|
-
|
|
5790
|
-
if (
|
|
7336
|
+
const refusal = savedListOutcome(reply, 'tests');
|
|
7337
|
+
if (refusal) return detailed ? refusal : legacyCollectionOutcome(refusal);
|
|
5791
7338
|
const done = store.read(path) ?? {},writeLeases=context.caseWriteLeases??=new Map();
|
|
5792
7339
|
for (const [receivedIndex,saved] of reply.json.tests.entries()) {
|
|
5793
7340
|
const key = typeof saved?.id === 'string' ? saved.id : null;
|
|
5794
7341
|
if (!key) continue;
|
|
5795
7342
|
const caseSelectionPorts={env:ports.env,findTests:ports.findTests,captureSource:ports.captureSource,isStoryPath:ports.isStoryPath,hasAcceptance:ports.hasAcceptance,matchTests:ports.matchTests,orphanSummary:ports.orphanSummary};
|
|
5796
|
-
const p=casePorts(caseSelectionPorts),record=retainCase(root,saved,{seedTest:context.seedTest,sessionId:tryId,rawBytes:receivedCaseBytes(reply.text,receivedIndex)},p);
|
|
7343
|
+
const p=casePorts(caseSelectionPorts),record=withRepositoryRunLock(root,store,()=>retainCase(root,saved,{seedTest:context.seedTest,sessionId:tryId,rawBytes:receivedCaseBytes(reply.text,receivedIndex)},p));
|
|
5797
7344
|
let result=caseResult(record,'pending','close the editor for the named original test and explicitly hand over the file');
|
|
5798
7345
|
let valid=true;try{prepareCase(root,record,p);}catch(error){if(error?.unboundPort)throw error;valid=false;result=caseResult(record,'pending',error.message);}
|
|
5799
7346
|
const handoff=valid&&!writeLeases.has(record.target)?await caseHandoff(context,record.target):null;
|
|
5800
|
-
if(handoff||writeLeases.has(record.target)){try{let lease=writeLeases.get(record.target);if(!lease){lease=await acquireCaseWriteOwnership({root,testPath:record.target,handoff,signal:context.signal},caseSelectionPorts);writeLeases.set(record.target,lease);}result=
|
|
7347
|
+
if(handoff||writeLeases.has(record.target)){try{let lease=writeLeases.get(record.target);if(!lease){lease=await acquireCaseWriteOwnership({root,testPath:record.target,handoff,signal:context.signal},caseSelectionPorts);writeLeases.set(record.target,lease);}result=withRepositoryRunLock(root,store,()=>applyPendingCaseSync({root,pendingId:record.pendingId,writeOwnership:lease,signal:context.signal},caseSelectionPorts));}catch(error){if(error?.unboundPort)throw error;result=caseResult(record,'pending',error.message);}}
|
|
5801
7348
|
const said=caseMessage(result);
|
|
5802
7349
|
if(result.duplicate&&done[key])continue;
|
|
5803
7350
|
if(done[key]?.result===said)continue;
|
|
5804
7351
|
done[key] = { at: new Date(ports.now()).toISOString(), result: said };
|
|
5805
|
-
store.write(path,
|
|
7352
|
+
withRepositoryRunLock(root,store,()=>store.write(path,{...(store.read(path)??{}),[key]:done[key]}));
|
|
5806
7353
|
try { context.onAgentCaseSaved?.({ id: key, name: saved.name, story_path: saved.story_path ?? saved.test?.story_path, result: said }); } catch {}
|
|
5807
7354
|
line(ports.stdout, said);
|
|
5808
7355
|
}
|
|
5809
|
-
return 'ok';
|
|
7356
|
+
return detailed ? {outcome:'success',retryMs:0} : 'ok';
|
|
5810
7357
|
}
|
|
5811
7358
|
|
|
5812
7359
|
// Approval requests from the Try page (#9): only a person's y in this terminal approves; the page gets done or declined.
|
|
5813
|
-
async function collectApprovals(context, tryId, story, answers) {
|
|
7360
|
+
async function collectApprovals(context, tryId, story, answers, detailed = false) {
|
|
5814
7361
|
const { ports, store, root } = context, path = join(store.folder('tries'), `${tryId}.approvals.json`);
|
|
5815
7362
|
const reply = await context.runtime.send(`/v1/try/${tryId}/approvals`, { method: 'GET' }, GET_MS);
|
|
5816
|
-
|
|
5817
|
-
if (
|
|
7363
|
+
const refusal = savedListOutcome(reply, 'approvals');
|
|
7364
|
+
if (refusal) return detailed ? refusal : legacyCollectionOutcome(refusal);
|
|
5818
7365
|
const handled = store.read(path) ?? {};
|
|
5819
7366
|
for (const request of reply.json.approvals) {
|
|
5820
7367
|
const id = typeof request?.id === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(request.id) ? request.id : null;
|
|
@@ -5836,11 +7383,28 @@ async function collectApprovals(context, tryId, story, answers) {
|
|
|
5836
7383
|
handled[id] = { state: result.state, at: new Date(ports.now()).toISOString() };
|
|
5837
7384
|
store.write(path, handled);
|
|
5838
7385
|
}
|
|
7386
|
+
}
|
|
7387
|
+
if (!detailed) { const delivery = await deliverApprovalAnswers(context, tryId); if (delivery.ended) return 'ended'; }
|
|
7388
|
+
return detailed ? {outcome:'success',retryMs:0} : 'ok';
|
|
7389
|
+
}
|
|
7390
|
+
|
|
7391
|
+
// A journalled decision is an obligation independent of category revisions.
|
|
7392
|
+
async function deliverApprovalAnswers(context, tryId) {
|
|
7393
|
+
const {store} = context, path = join(store.folder('tries'), `${tryId}.approvals.json`), handled = store.read(path) ?? {};
|
|
7394
|
+
let pending = false, retryMs = 0;
|
|
7395
|
+
const defer = delay => { pending = true; retryMs = retryMs ? Math.min(retryMs, delay) : delay; };
|
|
7396
|
+
for (const [id, record] of Object.entries(handled)) {
|
|
7397
|
+
if (context.signal?.aborted) break;
|
|
7398
|
+
if (!/^[A-Za-z0-9_-]{1,128}$/.test(id) || !['done','declined'].includes(record.state) || record.posted) continue;
|
|
7399
|
+
if (Number.isSafeInteger(record.retryAt) && record.retryAt > context.ports.now()) { defer(record.retryAt - context.ports.now()); continue; }
|
|
5839
7400
|
const answer = await context.runtime.send(`/v1/try/${tryId}/approvals/${id}`,
|
|
5840
|
-
{ method:
|
|
5841
|
-
if (
|
|
7401
|
+
{ method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({state:record.state}) }, GET_MS);
|
|
7402
|
+
if ([401,403,410].includes(answer.status)) return {pending:true,retryMs:0,ended:true};
|
|
7403
|
+
if (answer.status === 409) throw Error(`Approval answer conflicts with the server decision: ${cleanText(answer.json?.error?.message ?? 'already decided')}`);
|
|
7404
|
+
if (answer.status >= 200 && answer.status < 300) { record.posted = true; delete record.retryAt; store.write(path, handled); }
|
|
7405
|
+
else { const delay = tryRetryDelay(answer); record.retryAt = Math.min(Number.MAX_SAFE_INTEGER, context.ports.now() + delay); store.write(path, handled); defer(delay); }
|
|
5842
7406
|
}
|
|
5843
|
-
return
|
|
7407
|
+
return {pending,retryMs};
|
|
5844
7408
|
}
|
|
5845
7409
|
|
|
5846
7410
|
// Read saved cases and approval requests once; with `wait` (a person's terminal), keep reading until Ctrl-C or the Try ends.
|
|
@@ -5897,13 +7461,72 @@ function normalizeObservationBody(json) {
|
|
|
5897
7461
|
};
|
|
5898
7462
|
}
|
|
5899
7463
|
|
|
7464
|
+
async function doorWorldObservation(runtime,sessionId,report,actionId) {
|
|
7465
|
+
let observation=report??{};
|
|
7466
|
+
try {
|
|
7467
|
+
const state=await runtime.send(`/v1/try/${sessionId}/state`,{method:'GET'},GET_MS);
|
|
7468
|
+
const matched=typeof actionId==='string'&&state.status===200&&Array.isArray(state.json?.actions)
|
|
7469
|
+
?state.json.actions.find(action=>action.action_id===actionId):null;
|
|
7470
|
+
if(matched)observation={...observation,
|
|
7471
|
+
...(Object.hasOwn(matched,'input_world')?{input_world:matched.input_world}:{}),
|
|
7472
|
+
...(Object.hasOwn(matched,'world')?{world:matched.world}:{})};
|
|
7473
|
+
} catch { /* Observation is optional; the confirmed result remains confirmed. */ }
|
|
7474
|
+
return observation;
|
|
7475
|
+
}
|
|
7476
|
+
|
|
5900
7477
|
// The doors use the same gh identity, private store, one-shot dispatch and owner-scoped ledger as Try.
|
|
5901
7478
|
export async function runDoorCall(descriptor, input, givenPorts = {}) {
|
|
7479
|
+
if (!descriptor.programEntry) return executeDoorCall(descriptor, input, givenPorts);
|
|
7480
|
+
const ports = withDefaults(givenPorts), { root, programEntry: entry, sessionId, origin, login } = descriptor;
|
|
7481
|
+
const store = stateFor(ports.env, root), files = programFiles(root, entry, store), unlock = files.lock();
|
|
7482
|
+
try {
|
|
7483
|
+
let record = files.get();
|
|
7484
|
+
if (record?.id !== sessionId || record.entry !== entry || record.origin !== origin || record.login !== login) throw new Stop(125, 'The program descriptor does not match its saved session.');
|
|
7485
|
+
const capture = ports.captureSource(root, { tests: [entry], appMap: record.app_map });
|
|
7486
|
+
const effective = Object.fromEntries(capture.sources.filter(file => file.path.endsWith('.prompt.md')).map(file => [file.path, sha256(file.bytes)]));
|
|
7487
|
+
if (record.source_sha256 !== capture.sha256 || !isDeepStrictEqual(record.prompt_hashes, capture.raw_prompt_hashes) || !isDeepStrictEqual(record.effective_prompt_hashes, effective)
|
|
7488
|
+
|| record.app_map_hash !== (record.app_map ? sha256(capture.sources.find(file => file.path === record.app_map).bytes) : null)) throw new Stop(125, 'The pinned program source changed. Open the program with --new.');
|
|
7489
|
+
if (!Object.hasOwn(record.prompt_hashes, descriptor.prompt)) throw new Stop(125, 'This prompt is outside the selected program.');
|
|
7490
|
+
const identity = signIn(ports.gh, store, ports, { exitCode: 125 });
|
|
7491
|
+
if (identity.login !== login) throw new Stop(125, `This program belongs to ${login}. Run: gh auth switch -u ${login}`);
|
|
7492
|
+
const secrets = [identity.token], auth = authSession({ identity, store, ports, secrets, expectedOwnerLogin: login, ownerMismatchError: () => new Stop(125, 'This program belongs to another owner.') });
|
|
7493
|
+
const runtime = new Runtime({ origin, token: identity.token, ports, signal: ports.signal, auth, programJson: true });
|
|
7494
|
+
const session = judgeGet(await runtime.get(sessionId), sessionId, 'try');
|
|
7495
|
+
if (session.kind !== 'state' || session.answer.state !== 'passed' || session.answer.result?.session?.id !== sessionId
|
|
7496
|
+
|| !LIVE_SESSION.has(session.answer.result?.session?.state)) throw new Stop(125, 'The original program session is not confirmed running or paused. Its saved state is kept; no action was sent.');
|
|
7497
|
+
if (session.answer.result.session.state === 'paused') await reopenTry({ ports, runtime, origin, store, secrets,
|
|
7498
|
+
signal: ports.signal, interrupted: ports.signal?.aborted === true }, record, { path: entry, story: entry });
|
|
7499
|
+
record = await recoverProgramAction(runtime, files, record);
|
|
7500
|
+
let answer, dispatchedId;
|
|
7501
|
+
const execution = {};
|
|
7502
|
+
try {
|
|
7503
|
+
answer = await executeDoorCall({ ...descriptor, beforeProgramDispatch: id => {
|
|
7504
|
+
dispatchedId = id;
|
|
7505
|
+
record = { ...record, pending: { kind: 'call', id, world_version: record.world_version } }; files.set(record);
|
|
7506
|
+
} }, input, givenPorts, execution);
|
|
7507
|
+
} catch (error) {
|
|
7508
|
+
// A known terminal failure may have changed the world. Only a refusal
|
|
7509
|
+
// before execution proves that this pending ID has no receipt to recover.
|
|
7510
|
+
if (execution.preExecutionRefusal === true) releaseRefusedProgramAction(files, 'call', dispatchedId);
|
|
7511
|
+
throw error;
|
|
7512
|
+
}
|
|
7513
|
+
if (!isObject(answer.world)) throw new Stop(125, 'The exact call world is not confirmed. The original request ID and last saved data are kept.');
|
|
7514
|
+
await commitProgramAction(runtime, files, files.get(), answer);
|
|
7515
|
+
return answer;
|
|
7516
|
+
} finally { unlock(); }
|
|
7517
|
+
}
|
|
7518
|
+
|
|
7519
|
+
async function executeDoorCall(descriptor, input, givenPorts = {}, execution = {}) {
|
|
5902
7520
|
const ports = withDefaults(givenPorts), { root, origin, sessionId, login, prompt, operation } = descriptor;
|
|
7521
|
+
if (descriptor.maxCalls !== undefined && (!Number.isInteger(descriptor.maxCalls) || descriptor.maxCalls < 1 || descriptor.maxCalls > 1000)) throw new Stop(2, 'maxCalls must be an integer from 1 to 1000.');
|
|
7522
|
+
if (descriptor.fresh !== undefined && typeof descriptor.fresh !== 'boolean') throw new Stop(2, 'fresh must be Boolean.');
|
|
5903
7523
|
const existingOnly = descriptor.existingOnly === true;
|
|
5904
7524
|
const declaredErrors = Array.isArray(descriptor.declaredErrors) ? descriptor.declaredErrors : [];
|
|
5905
|
-
if(loadRuntimeWorkspace({root}).configured)ports.captureSource(root,{tests:descriptor.originalPath?[descriptor.originalPath]:[descriptor.prompt].filter(Boolean)});
|
|
5906
|
-
const store = stateFor(ports.env, root),
|
|
7525
|
+
if(loadRuntimeWorkspace({root}).configured){if(descriptor.directProgram||descriptor.freeProgram)directCapture(root,descriptor.prompt,ports,descriptor.lazyInterfaces===true);else ports.captureSource(root,{tests:descriptor.originalPath?[descriptor.originalPath]:[descriptor.prompt].filter(Boolean)});}
|
|
7526
|
+
const store = stateFor(ports.env, root), runId = !descriptor.originalPath && !descriptor.directProgram && !descriptor.directTyped && !descriptor.freeProgram ? ports.randomUUID() : null;
|
|
7527
|
+
if (runId) await store.updateLastRun(root, () => ({state:'unknown',id:runId}));
|
|
7528
|
+
const runSource = runId ? (ports.captureSource.isDefaultCapture && typeof ports.isStoryPath !== 'function' ? directCapture(root, prompt, ports) : ports.captureSource(root,{tests:[prompt]})) : null;
|
|
7529
|
+
const identity = signIn(ports.gh, store, ports, { exitCode: 125 });
|
|
5907
7530
|
if (identity.login !== login) throw new Stop(125, `This Try belongs to ${login}. Run: gh auth switch -u ${login}`);
|
|
5908
7531
|
if (runtimeOrigin({ PDD_RUNTIME_URL: origin }) !== origin) throw new Stop(2, 'The saved interpreter address is invalid.');
|
|
5909
7532
|
const repo=store.read(join(store.dir,'repos',`${store.repoKey(root)}.json`));
|
|
@@ -5913,16 +7536,33 @@ export async function runDoorCall(descriptor, input, givenPorts = {}) {
|
|
|
5913
7536
|
const problem=tryPromptProblem(root,found,test,saved[1],undefined,ports);
|
|
5914
7537
|
if (problem) throw new Stop(125,`${problem} Run pdd simulate STORY --new.`);
|
|
5915
7538
|
}
|
|
7539
|
+
// An existing session executes its original source, even when local files change.
|
|
7540
|
+
// Current capture may validate original pins, but cannot create their authority.
|
|
7541
|
+
const originalRaw = saved ? saved[1].prompt_hashes : descriptor.promptHashes;
|
|
7542
|
+
const originalEffective = saved ? saved[1].effective_prompt_hashes : descriptor.effectivePromptHashes;
|
|
7543
|
+
const reached = Object.keys(runSource?.raw_prompt_hashes ?? {});
|
|
7544
|
+
const effective = Object.fromEntries((runSource?.sources ?? []).filter(file => file.path.endsWith('.prompt.md')).map(file => [file.path, sha256(file.bytes)]));
|
|
7545
|
+
const sourcePins = reached.length && isObject(originalRaw) && isObject(originalEffective)
|
|
7546
|
+
&& reached.every(path => validSha256Hex(originalRaw[path]) && validSha256Hex(originalEffective[path])
|
|
7547
|
+
&& originalRaw[path] === runSource.raw_prompt_hashes[path] && originalEffective[path] === effective[path])
|
|
7548
|
+
? { promptHashes: Object.fromEntries(reached.map(path => [path, originalRaw[path]])),
|
|
7549
|
+
effectivePromptHashes: Object.fromEntries(reached.map(path => [path, originalEffective[path]])) } : null;
|
|
5916
7550
|
const secrets = [identity.token];
|
|
5917
7551
|
if (ports.signal?.aborted) throw new Stop(125, 'The local server stopped before the command was sent.');
|
|
5918
|
-
const id =
|
|
7552
|
+
const id = descriptor.directProgram && descriptor.recoverRequestId ? descriptor.recoverRequestId : (descriptor.runId ?? runId ?? ports.randomUUID());
|
|
7553
|
+
if ((descriptor.directProgram || descriptor.runId) && !UUID.test(id)) throw new Stop(descriptor.runId ? 2 : 125, descriptor.runId ? 'The program run ID is invalid.' : 'The saved command request ID is invalid.');
|
|
7554
|
+
const request = { requestId: id, prompt, operation, input,
|
|
7555
|
+
...(descriptor.maxCalls !== undefined ? { max_calls: descriptor.maxCalls } : {}),
|
|
7556
|
+
...(descriptor.fresh !== undefined ? { fresh: descriptor.fresh } : {}) };
|
|
7557
|
+
ports.onDoorRequest?.(id);
|
|
7558
|
+
const runBody = JSON.stringify(request), recordedInput = JSON.parse(runBody).input;
|
|
5919
7559
|
const recovery = ` Read the result with: pdd test --read ${id}`;
|
|
5920
7560
|
store.write(join(store.folder('calls'), `${id}.meta.json`), {
|
|
5921
7561
|
id, origin, root, login, user_id: identity.userId, session_id: sessionId,
|
|
5922
7562
|
...(typeof descriptor.originalPath === 'string' ? { test_path: descriptor.originalPath } : {}),
|
|
5923
7563
|
});
|
|
5924
|
-
store.posted(store.folder('tries'), id);
|
|
5925
|
-
let knownOutcome = false, dispatched = false;
|
|
7564
|
+
if (!(descriptor.directProgram && descriptor.recoverRequestId)) store.posted(store.folder('tries'), id);
|
|
7565
|
+
let knownOutcome = false, dispatched = false, preExecutionRefusal = false;
|
|
5926
7566
|
const auth = authSession({
|
|
5927
7567
|
identity,
|
|
5928
7568
|
store,
|
|
@@ -5931,27 +7571,37 @@ export async function runDoorCall(descriptor, input, givenPorts = {}) {
|
|
|
5931
7571
|
signInExitCode: 125,
|
|
5932
7572
|
expectedOwnerLogin: login,
|
|
5933
7573
|
ownerMismatchError: owner => {
|
|
5934
|
-
if (!dispatched) knownOutcome = true;
|
|
7574
|
+
if (!dispatched) { knownOutcome = true; preExecutionRefusal = true; }
|
|
5935
7575
|
return new Stop(125, `This Try belongs to ${owner}. Run: gh auth switch -u ${owner}`);
|
|
5936
7576
|
},
|
|
5937
7577
|
onRefresh: next => {
|
|
5938
7578
|
if (next.login === login) store.write(join(store.folder('calls'), `${id}.meta.json`), { id, origin, root, login, user_id: next.userId, session_id: sessionId, ...(typeof descriptor.originalPath === 'string' ? { test_path: descriptor.originalPath } : {}) });
|
|
5939
7579
|
},
|
|
5940
7580
|
});
|
|
5941
|
-
const runtime = new Runtime({ origin, token: identity.token, ports, signal: ports.signal, auth });
|
|
7581
|
+
const runtime = new Runtime({ origin, token: identity.token, ports, signal: ports.signal, auth, programJson: Boolean(descriptor.programEntry) });
|
|
5942
7582
|
try {
|
|
5943
|
-
|
|
5944
|
-
|
|
7583
|
+
descriptor.beforeProgramDispatch?.(id);
|
|
7584
|
+
const reply = descriptor.directProgram && descriptor.recoverRequestId ? { status: 202 } : await runtime.send(`/v1/try/${sessionId}/call`, { method: 'POST',
|
|
7585
|
+
headers: { 'Content-Type': 'application/json' }, body: runBody }, ports.postMs);
|
|
5945
7586
|
if (reply.status && ![200, 202].includes(reply.status)) {
|
|
5946
|
-
knownOutcome = reply
|
|
5947
|
-
|
|
7587
|
+
knownOutcome = isPreExecutionRefusal(reply);
|
|
7588
|
+
preExecutionRefusal = knownOutcome;
|
|
7589
|
+
throw Object.assign(new Stop(125, cleanText(reply.json?.error?.message || (reply.status === 401 ? AUTH_TEXT : reply.json?.error?.code) || `The interpreter refused the command (HTTP ${reply.status}).`, secrets) + recovery), { fix: reply.json?.error?.fix });
|
|
5948
7590
|
}
|
|
5949
7591
|
dispatched = true;
|
|
7592
|
+
// Existing-session calls settle through their authenticated observation.
|
|
7593
|
+
// A nonterminal acknowledgment may omit requestId, but cannot conflict.
|
|
7594
|
+
const pendingExistingCall = existingOnly && reply.status === 202 && ['queued', 'running'].includes(reply.json?.state)
|
|
7595
|
+
&& reply.json.id === id && reply.json.command === 'call'
|
|
7596
|
+
&& (!Object.hasOwn(reply.json, 'requestId') || reply.json.requestId === id)
|
|
7597
|
+
&& (!Object.hasOwn(reply.json, 'session_id') || reply.json.session_id === sessionId)
|
|
7598
|
+
&& (!Object.hasOwn(reply.json.result?.session ?? {}, 'id') || reply.json.result.session.id === sessionId);
|
|
7599
|
+
if ([200, 202].includes(reply.status) && reply.json && !pendingExistingCall && !programReceiptMatches(reply.json, id, 'call', sessionId)) throw new Stop(125, 'The interpreter returned a different command.' + recovery);
|
|
5950
7600
|
const end = ports.now() + 900_000;
|
|
5951
7601
|
let answer = null;
|
|
5952
7602
|
for (;;) {
|
|
5953
7603
|
if (ports.signal?.aborted) throw new Stop(125, 'The local server stopped; this command result is unknown. Do not repeat it automatically.' + recovery);
|
|
5954
|
-
if (answer &&
|
|
7604
|
+
if (answer && !programReceiptMatches(answer, id, 'call', sessionId)) throw new Stop(125, 'The interpreter returned a different command.' + recovery);
|
|
5955
7605
|
if (answer && ENDED.has(answer.state)) {
|
|
5956
7606
|
store.write(join(store.folder('tries'), `${id}.json`), answer);
|
|
5957
7607
|
const rawReport = isObject(answer.result?.report) ? answer.result.report : null;
|
|
@@ -5963,7 +7613,7 @@ export async function runDoorCall(descriptor, input, givenPorts = {}) {
|
|
|
5963
7613
|
request_id: id,
|
|
5964
7614
|
declared_errors: declaredErrors,
|
|
5965
7615
|
state: answer.state === 'not_run' ? 'refused' : answer.state,
|
|
5966
|
-
has_program_result: isObject(answer.result
|
|
7616
|
+
has_program_result: isObject(answer.result) && Object.hasOwn(answer.result, 'program_result'),
|
|
5967
7617
|
usage_calls: Number.isSafeInteger(usage?.calls) ? usage.calls : null,
|
|
5968
7618
|
report: rawReport ? {
|
|
5969
7619
|
action_id: typeof rawReport.action_id === 'string' ? rawReport.action_id : null,
|
|
@@ -5978,29 +7628,26 @@ export async function runDoorCall(descriptor, input, givenPorts = {}) {
|
|
|
5978
7628
|
const limit = stepTimeLimit(answer, { steps: [{ step_id: operation }], secrets: secrets });
|
|
5979
7629
|
const why = answer.result?.refusals?.[0];
|
|
5980
7630
|
if (limit) throw Object.assign(new Stop(125, `${limit.message} ${limit.fix}${recovery}`), { tryUsage: usage });
|
|
5981
|
-
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 });
|
|
5982
|
-
}
|
|
5983
|
-
let observation = rawReport ?? {};
|
|
5984
|
-
if (typeof projected.action_id === 'string') {
|
|
5985
|
-
try {
|
|
5986
|
-
const state = await runtime.send(`/v1/try/${sessionId}/state`, { method: 'GET' }, GET_MS);
|
|
5987
|
-
const matched = state.status === 200 && Array.isArray(state.json?.actions)
|
|
5988
|
-
? state.json.actions.find(action => action.action_id === projected.action_id) : null;
|
|
5989
|
-
if (matched) observation = { ...observation,
|
|
5990
|
-
...(Object.hasOwn(matched, 'input_world') ? { input_world: matched.input_world } : {}),
|
|
5991
|
-
...(Object.hasOwn(matched, 'world') ? { world: matched.world } : {}) };
|
|
5992
|
-
} catch { /* Observation is optional; the confirmed result remains confirmed. */ }
|
|
7631
|
+
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 });
|
|
5993
7632
|
}
|
|
5994
|
-
|
|
7633
|
+
knownOutcome = true;
|
|
7634
|
+
const observation = typeof projected.action_id === 'string' || descriptor.directProgram
|
|
7635
|
+
? await doorWorldObservation(runtime,sessionId,rawReport,projected.action_id) : rawReport ?? {};
|
|
7636
|
+
const confirmed = {
|
|
5995
7637
|
id,
|
|
5996
7638
|
actionId: projected.action_id,
|
|
5997
7639
|
replayed: projected.replayed,
|
|
5998
7640
|
result: projected.outcome === 'result' ? answer.result.program_result : null,
|
|
5999
7641
|
error: projected.outcome === 'program_error' ? reportError : null,
|
|
6000
7642
|
usage,
|
|
7643
|
+
callChain: rawReport?.call_chain,
|
|
6001
7644
|
inputWorld: observation.input_world,
|
|
6002
|
-
world: observation.world,
|
|
7645
|
+
world: Object.hasOwn(answer.result ?? {}, 'world') ? answer.result.world : observation.world,
|
|
6003
7646
|
};
|
|
7647
|
+
if (sourcePins && projected.outcome === 'result') await store.updateLastRun(root, current => current?.id !== id ? undefined : ({state:'confirmed',
|
|
7648
|
+
descriptor:{root,sessionId,origin,login,prompt,operation,...sourcePins},
|
|
7649
|
+
input:recordedInput,...confirmed}));
|
|
7650
|
+
return confirmed;
|
|
6004
7651
|
}
|
|
6005
7652
|
if (ports.now() >= end) throw new Stop(125, 'The command result is unknown. Do not repeat it automatically.' + recovery);
|
|
6006
7653
|
if (existingOnly) {
|
|
@@ -6031,7 +7678,18 @@ export async function runDoorCall(descriptor, input, givenPorts = {}) {
|
|
|
6031
7678
|
answer = [200, 202].includes(read.status) ? read.json : null;
|
|
6032
7679
|
}
|
|
6033
7680
|
} catch (error) {
|
|
7681
|
+
if (!dispatched && unadmittedCallErrors.has(runtime) && unadmittedCallErrors.get(runtime) === error) {
|
|
7682
|
+
knownOutcome = true;
|
|
7683
|
+
preExecutionRefusal = true;
|
|
7684
|
+
}
|
|
7685
|
+
// Custody evidence belongs to this invocation, never to a reusable port error.
|
|
7686
|
+
execution.preExecutionRefusal = preExecutionRefusal;
|
|
7687
|
+
// A port may reuse an Error across calls with different outcomes.
|
|
7688
|
+
if (!(error instanceof Stop)) error = Object.assign(new Error(error?.message ?? String(error)), error,
|
|
7689
|
+
{ name: error?.name ?? 'Error', cause: error });
|
|
6034
7690
|
if (!knownOutcome) error.unknownOutcome = true;
|
|
7691
|
+
else delete error.unknownOutcome;
|
|
7692
|
+
error.requestId = id;
|
|
6035
7693
|
throw error;
|
|
6036
7694
|
}
|
|
6037
7695
|
}
|
|
@@ -6242,7 +7900,7 @@ export async function readTryOwner({ cwd = process.cwd(), story, tryId } = {}, g
|
|
|
6242
7900
|
// Local migration ports use the same private custody/publication boundary.
|
|
6243
7901
|
export function runtimeWorkspaceMigrationStore({root,projectionRoot,env=process.env},given={}){
|
|
6244
7902
|
const p=casePorts({...given,env}),directory=caseStateDirectory(env,root,p),oldKey=p.hash(Buffer.from(projectionRoot)).slice(0,16);
|
|
6245
|
-
const readJson=path=>
|
|
7903
|
+
const readJson=path=>parseProgramJson(caseRead(p,path));
|
|
6246
7904
|
const list=path=>{try{caseSafe(p,path,{directory:true});return p.files.list(path);}catch(e){if(e.code==='ENOENT'||!caseStat(p,path))return[];throw e;}};
|
|
6247
7905
|
const destinationRepo=join(directory,'repos',p.hash(Buffer.from(root)).slice(0,16)+'.json');
|
|
6248
7906
|
function migrateDoor(pointer,record) {
|
|
@@ -6287,26 +7945,34 @@ export function runtimeWorkspaceMigrationStore({root,projectionRoot,env=process.
|
|
|
6287
7945
|
return {...records[0],items};
|
|
6288
7946
|
},
|
|
6289
7947
|
publishMapping(id,record){
|
|
6290
|
-
const
|
|
6291
|
-
|
|
6292
|
-
|
|
6293
|
-
|
|
6294
|
-
const
|
|
6295
|
-
|
|
6296
|
-
|
|
6297
|
-
|
|
6298
|
-
|
|
6299
|
-
|
|
6300
|
-
|
|
6301
|
-
|
|
6302
|
-
|
|
6303
|
-
|
|
6304
|
-
|
|
6305
|
-
|
|
6306
|
-
|
|
6307
|
-
|
|
6308
|
-
|
|
6309
|
-
|
|
7948
|
+
const lockFolder=destinationRepo.replace(/\.json$/,'.last-run');
|
|
7949
|
+
caseSafe(p,lockFolder,{directory:true,create:true});
|
|
7950
|
+
const release=acquireNativeBatchLock(lockFolder);
|
|
7951
|
+
try {
|
|
7952
|
+
const itemId=record.activeItem,item=record.items[itemId],folder=join(directory,'workspace-migrations',id),path=join(folder,p.hash(Buffer.from(itemId))+'.json');
|
|
7953
|
+
// Each item has its own atomic record; another item's update cannot be lost.
|
|
7954
|
+
if(item.state==='applied'&&item.kind==='repo'){
|
|
7955
|
+
const old=item.record,mapping=new Map(record.mappings.map(m=>[m.from,m.to])),target=join(directory,'repos',p.hash(Buffer.from(root)).slice(0,16)+'.json');
|
|
7956
|
+
const current=caseStat(p,target)?readJson(target):{root,tries:{}};const tries={...current.tries};
|
|
7957
|
+
for(const [from,value] of Object.entries(old.tries??{})){const to=mapping.get(from);if(!to)throw Error('original Try has no exact destination mapping');if(tries[to]&&tries[to].id!==value.id)throw Error('authored repository already has another Try at this test');tries[to]={...value,original_root:projectionRoot};}
|
|
7958
|
+
const migratedDoor=old.last_door?migrateDoor(old.last_door,{...record,readCommand:item.readCommand}):undefined;
|
|
7959
|
+
const last_door=current.last_door??migratedDoor;
|
|
7960
|
+
const next={...old,...current,root,original_root:projectionRoot,tries,last_batch:current.last_batch??old.last_batch??null,...(last_door?{last_door}:{})};
|
|
7961
|
+
if(!Object.hasOwn(current,'last_run'))delete next.last_run;
|
|
7962
|
+
// Destination publication is separately prepared and recoverable. Original
|
|
7963
|
+
// receipts/state remain untouched and the selected lease guards this item.
|
|
7964
|
+
caseWrite(p,target,JSON.stringify(next));
|
|
7965
|
+
}
|
|
7966
|
+
if(item.state==='applied'&&item.kind==='try'&&itemId.endsWith('.door.json')) {
|
|
7967
|
+
const old=readJson(join(directory,'repos',oldKey+'.json'));
|
|
7968
|
+
if(old.last_door?.descriptor!==itemId)throw Error('door has no owned original last-result pointer; preserve its original recovery command');
|
|
7969
|
+
const last_door=migrateDoor(old.last_door,{...record,readCommand:item.readCommand});
|
|
7970
|
+
if(!caseStat(p,destinationRepo))throw Error('authored repository pointer is unavailable');
|
|
7971
|
+
const current=readJson(destinationRepo);
|
|
7972
|
+
if(!current.last_door)caseWrite(p,destinationRepo,JSON.stringify({...current,last_door}));
|
|
7973
|
+
}
|
|
7974
|
+
caseWrite(p,path,JSON.stringify({...record,items:{[itemId]:item}}));return path;
|
|
7975
|
+
} finally { release(); }
|
|
6310
7976
|
},
|
|
6311
7977
|
transferCase(item,target){const old=item.record;
|
|
6312
7978
|
// Transfer every conflicting variant before any one variant can be applied.
|
|
@@ -6321,3 +7987,128 @@ export function runtimeWorkspaceMigrationStore({root,projectionRoot,env=process.
|
|
|
6321
7987
|
}
|
|
6322
7988
|
};
|
|
6323
7989
|
}
|
|
7990
|
+
|
|
7991
|
+
// The free-run adapter shares authentication, admission and receipts with Try.
|
|
7992
|
+
function programReceiptMatches(answer, requestId, command, sessionId) {
|
|
7993
|
+
return sameJob(answer, requestId, command)
|
|
7994
|
+
&& (!Object.hasOwn(answer, 'session_id') || answer.session_id === sessionId)
|
|
7995
|
+
&& (!Object.hasOwn(answer.result?.session ?? {}, 'id') || answer.result.session.id === sessionId);
|
|
7996
|
+
}
|
|
7997
|
+
|
|
7998
|
+
export function createProgramContext({ cwd = process.cwd(), options = {} } = {}, givenPorts = {}) {
|
|
7999
|
+
const ports = withDefaults(givenPorts), root = repoRoot(cwd), store = stateFor(ports.env, root);
|
|
8000
|
+
const origin = runtimeOrigin(ports.env), identity = signIn(ports.gh, store, ports, { exitCode: 125 });
|
|
8001
|
+
const context = { root, cwd: realpathSync(cwd), options, ports, store, origin, identity, signal: ports.signal,
|
|
8002
|
+
startedAt: ports.now(), deadline: ports.now() + TRY_MS, folder: store.folder('tries'),
|
|
8003
|
+
lint: { request_ids: [], state: null }, rows: [], secrets: [identity.token], batch: null };
|
|
8004
|
+
Object.defineProperty(context, 'interrupted', { get: () => !!ports.signal?.aborted });
|
|
8005
|
+
context.auth = authSession({ identity, store, ports, secrets: context.secrets, signInExitCode: 125,
|
|
8006
|
+
expectedOwnerLogin: identity.login, ownerMismatchError: owner => new Stop(125, `This Try belongs to ${owner}. Run: gh auth switch -u ${owner}`),
|
|
8007
|
+
onRefresh: next => { context.identity = next; } });
|
|
8008
|
+
context.runtime = new Runtime({ origin, token: identity.token, ports, signal: context.signal, auth: context.auth });
|
|
8009
|
+
context.stopSession = async (sessionId, requestId) => {
|
|
8010
|
+
if (!UUID.test(sessionId) || !UUID.test(requestId)) throw new Stop(2, 'The program stop identity is invalid.');
|
|
8011
|
+
store.posted(store.folder('tries'), requestId);
|
|
8012
|
+
const reply = await context.runtime.stop(sessionId, requestId);
|
|
8013
|
+
if ([404,410].includes(reply.status)) return {stopped:true,readOnly:true};
|
|
8014
|
+
const verdict = judgePost(reply,requestId,'stop',context.secrets);
|
|
8015
|
+
let answer = verdict.answer;
|
|
8016
|
+
if (answer) store.write(join(context.folder, `${requestId}.json`), answer);
|
|
8017
|
+
const matches = row => programReceiptMatches(row, requestId, 'stop', sessionId);
|
|
8018
|
+
const uncertain = () => Object.assign(new Stop(125, `The stop outcome is unknown. Read the result with: pdd run --read ${requestId}`), { unknownOutcome: true, runId: requestId });
|
|
8019
|
+
if (answer && !matches(answer)) throw uncertain();
|
|
8020
|
+
if (['accepted','unknown'].includes(verdict.kind) && (!answer || !ENDED.has(answer.state))) {
|
|
8021
|
+
try { answer = (await readUntil(context,requestId,'stop',row=>!matches(row)||ENDED.has(row.state),TRY_MS,null)).answer; }
|
|
8022
|
+
catch (error) { throw Object.assign(new Stop(125, `${error.message} Read the result with: pdd run --read ${requestId}`), { unknownOutcome: true, runId: requestId }); }
|
|
8023
|
+
}
|
|
8024
|
+
if (answer && !matches(answer)) throw uncertain();
|
|
8025
|
+
if (answer?.state === 'passed') {
|
|
8026
|
+
if (answer.result?.session?.id !== sessionId || answer.result.session.state !== 'stopped') throw uncertain();
|
|
8027
|
+
return {stopped:true,readOnly:false};
|
|
8028
|
+
}
|
|
8029
|
+
const unknown = ['accepted','unknown'].includes(verdict.kind) && (!answer || !['failed','refused','not_run'].includes(answer.state));
|
|
8030
|
+
throw Object.assign(new Stop(125,unknown ? `The stop outcome is unknown. Read the result with: pdd run --read ${requestId}` : 'The interpreter did not confirm that the old program stopped.'),{unknownOutcome:unknown,runId:requestId});
|
|
8031
|
+
};
|
|
8032
|
+
context.readState = sessionId => new Runtime({ origin, token: context.identity.token, ports, auth: context.auth }).send(`/v1/try/${encodeURIComponent(sessionId)}/state`, {method:'GET'}, GET_MS);
|
|
8033
|
+
context.dispose = async () => {
|
|
8034
|
+
await Promise.all([...(context.reservations ?? [])].map(reservation => releaseRuntimeSlot(reservation, { ended: false }, slotPorts(context))));
|
|
8035
|
+
};
|
|
8036
|
+
return context;
|
|
8037
|
+
}
|
|
8038
|
+
|
|
8039
|
+
async function readProgramReceipt(context, id, command, verdict, target, matches = () => true) {
|
|
8040
|
+
let answer = verdict.answer;
|
|
8041
|
+
if (!answer || matches(answer) && !ENDED.has(answer.state)) answer = (await readUntil(context, id, command, item => !matches(item) || ENDED.has(item.state), TRY_MS, null)).answer;
|
|
8042
|
+
if (answer) {
|
|
8043
|
+
context.store.write(join(context.folder, `${id}.json`), answer);
|
|
8044
|
+
if (matches(answer)) await finishReservation(context, target, answer);
|
|
8045
|
+
}
|
|
8046
|
+
return answer;
|
|
8047
|
+
}
|
|
8048
|
+
|
|
8049
|
+
export async function inspectProgram(context, capture, { appMap } = {}) {
|
|
8050
|
+
if (context.programLintCapture === capture.sha256 && context.programLintAnswer) return context.programLintAnswer;
|
|
8051
|
+
const { ports } = context;
|
|
8052
|
+
context.capture = capture; context.appMap = appMap ?? null;
|
|
8053
|
+
const paths = capture.sources.filter(file => file.path.endsWith('.prompt.md')).map(file => file.path).sort();
|
|
8054
|
+
const problem = message => Object.assign(new Stop(125,message),{unknownOutcome:false});
|
|
8055
|
+
for (;;) {
|
|
8056
|
+
if (!await admission(context, 'lint', context.lint)) throw problem('The interpreter stayed busy before program lint. No program was sent.');
|
|
8057
|
+
if (context.allowMissingInterfaces && !context.serverFeatures?.includes('lazy-interfaces')) throw problem('This PDD interpreter needs an upgrade to support plain prompt programs (lazy-interfaces). No program was sent.');
|
|
8058
|
+
const id = ports.randomUUID(), request = { requestId: id, source_sha256: capture.sha256, paths, complete: true, tests: [], app_maps: appMap ? [appMap] : [], ...sourceProvenance(context, capture),
|
|
8059
|
+
...(context.serverFeatures?.includes('lazy-interfaces') ? { lazy_interfaces: true } : {}) };
|
|
8060
|
+
context.lint.request_ids.push(id);
|
|
8061
|
+
const verdict = await postJob(context, '/v1/lint', 'lint', request, null, ports.postMs);
|
|
8062
|
+
if (verdict.kind === 'busy' && await waitBudget(context, verdict.wait)) continue;
|
|
8063
|
+
if (!['accepted','unknown'].includes(verdict.kind)) throw problem(verdict.refusal?.message ?? verdict.note?.message ?? 'Program lint was refused. Fix the prompt and run again.');
|
|
8064
|
+
const answer = await readProgramReceipt(context,id,'lint',verdict,context.lint);
|
|
8065
|
+
if (answer?.state !== 'passed' || answer.result?.report?.lint?.complete !== true && answer.result?.problems_complete !== true
|
|
8066
|
+
|| answer.result?.report?.program?.refused_prompts?.length || answer.result?.refusals?.length) {
|
|
8067
|
+
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.');
|
|
8068
|
+
}
|
|
8069
|
+
const admittedPrompts = answer.result?.report?.program?.prompts;
|
|
8070
|
+
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.');
|
|
8071
|
+
context.programLintCapture = capture.sha256; context.programLintAnswer = answer;
|
|
8072
|
+
return answer;
|
|
8073
|
+
}
|
|
8074
|
+
}
|
|
8075
|
+
|
|
8076
|
+
export async function admitProgram(context, capture, { entry, appMap, initial_world = {}, simulation = {}, max_calls = 400, tab = 'call', requestId } = {}) {
|
|
8077
|
+
const { ports, store } = context;
|
|
8078
|
+
await inspectProgram(context,capture,{appMap});
|
|
8079
|
+
const problem = (message, unknownOutcome = false, id = requestId) => Object.assign(new Stop(125,
|
|
8080
|
+
`${message}${unknownOutcome && id ? ` Read the result with: pdd run ${entry} --read ${id}` : ''}`), { unknownOutcome, runId: id });
|
|
8081
|
+
const setup = { request_ids: [], reservation: null };
|
|
8082
|
+
let id = requestId;
|
|
8083
|
+
for (;;) {
|
|
8084
|
+
if (!await admission(context, 'try', setup)) throw problem('The interpreter stayed busy before program setup. No program was sent.');
|
|
8085
|
+
id ??= ports.randomUUID();
|
|
8086
|
+
if (!UUID.test(id)) throw new Stop(2, 'The program session ID is invalid.');
|
|
8087
|
+
const request = { requestId: id, source_sha256: capture.sha256, entry, initial_world, simulation, max_calls, tab,
|
|
8088
|
+
...(appMap ? { app_map: appMap } : {}), ...sourceProvenance(context, capture),
|
|
8089
|
+
...(context.serverFeatures?.includes('lazy-interfaces') ? { lazy_interfaces: true } : {}) };
|
|
8090
|
+
setup.request_ids.push(id);
|
|
8091
|
+
const registered = await recordRuntimeRequest(setup.reservation, id, slotPorts(context));
|
|
8092
|
+
if (registered === false || context.interrupted) { await finishReservation(context, setup, { state: 'not_run' }); throw problem('Stopped before program setup was sent.'); }
|
|
8093
|
+
store.posted(context.folder, id);
|
|
8094
|
+
const reply = await context.runtime.post('/v1/try', request, capture.tar, ports.postMs);
|
|
8095
|
+
const verdict = judgePost(reply, id, 'try', context.secrets);
|
|
8096
|
+
if (verdict.answer) store.write(join(context.folder, `${id}.json`), verdict.answer);
|
|
8097
|
+
if (verdict.kind === 'busy') {
|
|
8098
|
+
await finishReservation(context, setup, { state: 'not_run' });
|
|
8099
|
+
// A caller-owned ID is durable; no second POST may use that ID.
|
|
8100
|
+
if (requestId) throw problem('Program setup did not start because capacity is busy. Run again later.');
|
|
8101
|
+
if (await waitBudget(context, verdict.wait)) { id = null; continue; }
|
|
8102
|
+
}
|
|
8103
|
+
if (!['accepted','unknown'].includes(verdict.kind)) { await finishReservation(context, setup, {state:'not_run'}); throw problem(verdict.refusal?.message ?? verdict.note?.message ?? 'The interpreter refused program setup.'); }
|
|
8104
|
+
let answer;
|
|
8105
|
+
try { answer = await readProgramReceipt(context,id,'try',verdict,setup, row => programReceiptMatches(row,id,'try',id)); }
|
|
8106
|
+
catch (error) { throw problem(error.message, true, id); }
|
|
8107
|
+
if (!programReceiptMatches(answer,id,'try',id) || !ENDED.has(answer.state) || answer.state === 'unknown'
|
|
8108
|
+
|| answer.state === 'passed' && (answer.result?.session?.id !== id || answer.result.session.state !== 'running')) throw problem('The program session outcome is unknown. Do not send it again automatically.', true, id);
|
|
8109
|
+
if (answer.state !== 'passed') throw problem(answer.result?.refusals?.[0]?.message ?? 'The interpreter did not open the program session.');
|
|
8110
|
+
const url = validLink(answer.result?.url, context.origin, 'try');
|
|
8111
|
+
if (!url) throw problem(refusedLink(answer, context.origin), true, id);
|
|
8112
|
+
return { id, url, session: answer.result.session, answer };
|
|
8113
|
+
}
|
|
8114
|
+
}
|