@promptdriven/runtime-client 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,13 @@
1
- // Generated from prompts/cli/try-doors.prompt.md (sha256: a7f657473a8a63a20e48ec6b5e52261695af9226d6bb3290a00c23f217975763).
2
- import { spawn } from 'node:child_process';
3
- import { createHash } from 'node:crypto';
1
+ // Generated from prompts/cli/try-doors.prompt.md (sha256: 5bd90da988b27996d32579172073ba42f9a320968d451592be1456dec50449cb).
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
4
  import { accessSync, chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
5
5
  import { basename, dirname, join, resolve } from 'node:path';
6
6
  import { fileURLToPath, pathToFileURL } from 'node:url';
7
- import { findTests, gitFiles, readPrompt, captureSource, executableInterfaceText } from './runtime-preflight.mjs';
8
- import { cleanText, tryUsage, tryUsageLine } from './runtime-output.mjs';
9
- import { runDoorCall, saveDoorCaseResult, acquireCaseWriteOwnership, defaultLineReader } from './runtime-client.mjs';
7
+ import { findTests, gitFiles, readPrompt, captureSource, executableInterfaceText, interfaceSchemaProblems, readAppMapScreens, analyzePromptSelectorWords } from './runtime-preflight.mjs';
8
+ import { loadRuntimeWorkspace, requireRuntimePath } from './runtime-workspace.mjs';
9
+ import { cleanText, causeText, tryUsage, tryUsageLine } from './runtime-output.mjs';
10
+ import { runDoorCall, saveDoorCaseResult, acquireCaseWriteOwnership, withRepositoryRunLockAsync, defaultLineReader } from './runtime-client.mjs';
10
11
 
11
12
  const WRAPPER_EXIT = 125;
12
13
  const hash = text => createHash('sha256').update(text).digest('hex');
@@ -47,6 +48,17 @@ function safeBin(root) {
47
48
  return path;
48
49
  }
49
50
 
51
+ function excludeLaunchers(root) {
52
+ const git = spawnSync('git', ['rev-parse', '--git-path', 'info/exclude'], { cwd: root, encoding: 'utf8' });
53
+ if (git.status !== 0) fail('Could not locate the repository’s local Git exclude file.');
54
+ const exclude = resolve(root, git.stdout.trim());
55
+ if (existsSync(exclude)) regular(exclude);
56
+ mkdirSync(dirname(exclude), { recursive: true });
57
+ if (realpathSync(dirname(exclude)) !== dirname(exclude)) fail('Refusing a symbolic link in the Git exclude path.');
58
+ const ignored = existsSync(exclude) ? readFileSync(exclude, 'utf8') : '';
59
+ if (!ignored.split('\n').includes('/.pdd/try/')) writeFileSync(exclude, `${ignored}${ignored.endsWith('\n') || !ignored ? '' : '\n'}/.pdd/try/\n`);
60
+ }
61
+
50
62
  function cliEntries(context, test) {
51
63
  const entries = new Map();
52
64
  for (const step of Array.isArray(test.doc?.steps) ? test.doc.steps : []) {
@@ -79,7 +91,26 @@ function typedUnmappedStory(context, test) {
79
91
  }
80
92
 
81
93
  function cliEntry(context, test) {
82
- const entries = cliEntries(context, test);
94
+ let entries;
95
+ if (context.directProgram) {
96
+ if(context.directProgram.selected)return context.directProgram.selected;
97
+ const path=context.directProgram.prompt??context.directProgram.descriptor?.prompt;
98
+ const source=readPrompt(context.root,context.visible,path);
99
+ const prompt=context.directProgram.interface?{...source,interface:context.directProgram.interface,error:null}:source;
100
+ if(prompt.error==='interface-missing'&&context.directProgram.allowMissingInterfaces){
101
+ // A cold declaration prepares transport only. The client must obtain the admitted schema before calling.
102
+ const operations=[...new Set([...prompt.text.matchAll(/\b(?:export|operation)\s+`?([A-Za-z_$][\w$]*)`?/gi)].map(match=>match[1]))];
103
+ const stdin=/\bstdin\s*(\?)?\s*:\s*string\b/.exec(prompt.text);
104
+ const entry={operation:operations.length===1?operations[0]:null,input_schema:{type:'object',properties:{argv:{type:'array',items:{type:'string'}},...(stdin?{stdin:{type:'string'}}:{})},required:['argv',...(stdin&&!stdin[1]?['stdin']:[])],additionalProperties:false}};
105
+ entries=new Map([[path,{step:{entry_path:path,operation:entry.operation},prompt,entry,unadmitted:true}]]);
106
+ }else{
107
+ const candidates=Array.isArray(prompt.interface?.entries)?prompt.interface.entries:[];
108
+ const conventions=Array.isArray(prompt.interface?.conventions)?prompt.interface.conventions:[];
109
+ entries=new Map(candidates.flatMap((entry,index)=>['input_schema','result_schema'].every(key=>conventions.some(c=>c?.path===`/entries/${index}/${key}`&&c.convention==='cli'))
110
+ ? [[`${path}#${entry.operation}`,{step:{entry_path:path,operation:entry.operation},prompt,entry}]]:[]));
111
+ if(entries.size!==1)fail('The entry prompt must declare exactly one command-line program.');
112
+ }
113
+ } else entries = cliEntries(context, test);
83
114
  if (entries.size !== 1) {
84
115
  if (entries.size) fail('This Story uses more than one command-line program. Choose a Story with one command-line program.');
85
116
  const found = context.found ?? (context.ports?.findTests ? context.ports.findTests({ root: context.root, files: [...context.visible] }) : findTests({ root: context.root, files: [...context.visible] }, context.ports));
@@ -95,7 +126,87 @@ function cliEntry(context, test) {
95
126
  return { ...value, name: heading };
96
127
  }
97
128
 
129
+ async function directProgramInput(inputSchema,argv,ports){
130
+ const input={argv};
131
+ try{
132
+ if(inputSchema.properties?.stdin&&!ports.stdin.isTTY){
133
+ const chunks=[];let bytes=0;
134
+ const collect=async()=>{for await(const chunk of ports.stdin){const part=Buffer.from(chunk);bytes+=part.length;if(bytes>1024*1024)fail('Piped stdin exceeds 1 MiB.');chunks.push(part);}};
135
+ let abort;
136
+ try{
137
+ if(ports.signal?.aborted)fail('Stopped before the command was sent.');
138
+ const interrupted=ports.signal?new Promise((done,reject)=>{abort=()=>{ports.stdin.destroy?.();reject(new Error('Stopped while reading stdin; no command was sent.'));};ports.signal.addEventListener('abort',abort,{once:true});}):null;
139
+ if(interrupted)await Promise.race([collect(),interrupted]);else await collect();
140
+ }finally{if(abort)ports.signal.removeEventListener('abort',abort);}
141
+ input.stdin=new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks));
142
+ }else if(inputSchema.required?.includes('stdin'))input.stdin='';
143
+
144
+ return input;
145
+ }catch(error){
146
+ if(error instanceof TypeError&&/encoded data/.test(error.message))fail('Piped stdin must be UTF-8 text.');
147
+ throw error;
148
+ }
149
+ }
150
+
151
+ async function openDirectCli(context, test, selected) {
152
+ const direct=context.directProgram;
153
+ if (direct.prepareOnly) return direct.prepareInput?{...selected,input:await directProgramInput(selected.entry.input_schema,direct.argv,context.ports)}:selected;
154
+ const {descriptorPath,argv,quiet,recoverRequestId}=direct, d=direct.descriptor;
155
+ if (argv.length || recoverRequestId || direct.invoke) return runShim(descriptorPath,argv,{...context.ports,directPrepared:true,directInput:direct.input,directQuiet:quiet,directStartedAt:direct.startedAt,directSetupCalls:direct.setupCalls,directRecoveryId:recoverRequestId});
156
+ excludeLaunchers(context.root);
157
+ const bin=safeBin(context.root),shim=join(bin,d.name);
158
+ if(existsSync(shim)){regular(shim);if(!readFileSync(shim,'utf8').startsWith('#!/bin/sh\n# PDD Try launcher v1\n'))fail('Refusing to overwrite a non-PDD launcher.');}
159
+ const moduleUrl=context.ports.tryLauncherUrl??pathToFileURL(join(dirname(fileURLToPath(import.meta.url)),'try-doors.mjs')).href;
160
+ const script='import(process.argv[1]).then(async ({runShim})=>{process.exitCode=await runShim(process.argv[2],process.argv.slice(3));}).catch(()=>{process.stderr.write("pdd: The program adapter could not load.\\nFix: Reinstall PDD and open the program again.\\n");process.exitCode=125;});';
161
+ const fd=openSync(shim,constants.O_WRONLY|constants.O_CREAT|constants.O_TRUNC|constants.O_NOFOLLOW,0o700);
162
+ try{writeFileSync(fd,`#!/bin/sh\n# PDD Try launcher v1\nexec ${quote(process.execPath)} --input-type=commonjs -e ${quote(script)} -- ${quote(moduleUrl)} ${quote(descriptorPath)} "$@"\n`);}finally{closeSync(fd);}
163
+ chmodSync(shim,0o700);
164
+ context.ports.stdout.write(`Try is ready: ${d.name}\n${shim}\nexport PATH=${quote(bin)}:"$PATH"\n`);
165
+ if(typeof context.ports.shell!=='function')fail('The shell host capability is unavailable.');
166
+ const chosen=context.ports.env.SHELL||'/bin/sh',shell=['bash','zsh','sh'].includes(basename(chosen))?chosen:'/bin/sh';
167
+ return context.ports.shell(shell,{...context.ports.env,PATH:`${bin}:${context.ports.env.PATH||process.env.PATH||''}`},context.root);
168
+ }
169
+ function directSummary(d,usage,elapsed,replayed=false,setupCalls=0){
170
+ const ownerCalls=replayed?0:usage?.calls;
171
+ const total=Number.isSafeInteger(setupCalls)&&Number.isSafeInteger(ownerCalls)?setupCalls+ownerCalls:null;
172
+ const calls=Number.isSafeInteger(total)?total:'unknown';
173
+ return `pdd: ${calls} AI calls · ${Math.max(0,elapsed)/1000}s${d.draft?' · DRAFT':''}\n`;
174
+ }
175
+ async function runDirectShim(d,descriptorPath,argv,ports){
176
+ if(!ports.directPrepared)return (await import('./runtime-client.mjs')).runTry({cwd:d.root,words:[d.prompt,...argv],options:{}},{...ports,directInvoke:true});
177
+ const now=ports.now??Date.now,started=ports.directStartedAt??now(),last=join(d.programDir,'last.json'),data=join(d.programDir,'data.json');
178
+ let input=ports.directInput??{argv},requestId=ports.directRecoveryId??null,accounting,replayed=false;
179
+ const quiet=ports.directQuiet===true;
180
+ try{
181
+ if(ports.directRecoveryId){regular(last);Object.assign(input,read(last).input);}
182
+ else{
183
+ writePrivate(last,{state:'unknown',id:null,input});
184
+ if(!ports.directInput)input=await directProgramInput(d.inputSchema,argv,ports);
185
+ }
186
+ const answer=await runDoorCall({...d,recoverRequestId:ports.directRecoveryId},input,{...ports,env:{...ports.env,PDD_STATE_DIR:d.stateDir},
187
+ onDoorRequest:id=>{requestId=id;writePrivate(last,{state:'unknown',id,input});}});
188
+ accounting=answer.usage;replayed=answer.replayed;
189
+ const result=answer.result;
190
+ if(typeof result?.stdout!=='string'||typeof result?.stderr!=='string'||!Number.isInteger(result.exit_code)||result.exit_code<0||result.exit_code>255||result.exit_code===WRAPPER_EXIT)
191
+ fail('The prompt must return stdout, stderr and an exit_code from 0–255 except reserved code 125.');
192
+ if(answer.world!==undefined){if(answer.world===null||typeof answer.world!=='object'||Array.isArray(answer.world))fail('The interpreter returned invalid program data.');writePrivate(data,answer.world);}
193
+ writePrivate(last,{state:'confirmed',id:answer.id,input,result,inputWorld:answer.inputWorld,world:answer.world});
194
+ ports.stdout.write(result.stdout);ports.stderr.write(result.stderr);
195
+ if(!quiet)ports.stderr.write(`${result.stderr&&!result.stderr.endsWith('\n')?'\n':''}${directSummary(d,answer.usage,now()-started,answer.replayed,ports.directSetupCalls)}`);
196
+ if(ports.signal?.aborted){ports.stderr.write(`${quiet&&result.stderr&&!result.stderr.endsWith('\n')?'\n':''}pdd: Stopped. Read the result with: pdd test --read ${answer.id}\n`);return 130;}
197
+ return result.exit_code;
198
+ }catch(error){
199
+ if(error?.unboundPort)throw error;
200
+ try{writePrivate(last,{state:error.unknownOutcome?'unknown':'refused',id:requestId,input});}catch(persistenceError){error=persistenceError;}
201
+ const reason=error instanceof TypeError&&/encoded data/.test(error.message)?'Piped stdin must be UTF-8 text.':cleanText(error.message||'The command could not run.');
202
+ ports.stderr.write(`pdd: ${reason}\nFix: ${cleanText(error.fix|| (requestId&&error.unknownOutcome?`Read pdd test --read ${requestId}; do not repeat the command automatically.`:'Check the prompt, data and interpreter connection, then run the command again.'))}\n`);
203
+ if(!quiet)ports.stderr.write(directSummary(d,error.tryUsage??accounting,now()-started,replayed,ports.directSetupCalls));
204
+ return ports.signal?.aborted?130:WRAPPER_EXIT;
205
+ }
206
+ }
207
+
98
208
  export async function openCli(context, test, sessionId, options) {
209
+ if(context.directProgram)return openDirectCli(context,test,cliEntry(context,test));
99
210
  const { root, ports, store, identity, origin } = context;
100
211
  const { step, prompt, entry, name } = cliEntry(context, test);
101
212
  const record = store.repo(root).tries?.[test.path];
@@ -107,16 +218,7 @@ export async function openCli(context, test, sessionId, options) {
107
218
  regular(shim);
108
219
  if (!readFileSync(shim, 'utf8').startsWith(`#!/bin/sh\n# PDD Try launcher v1\n`)) fail(`Refusing to overwrite ${shim}; it is not a PDD Try launcher.`);
109
220
  } else { try { lstatSync(shim); fail('Refusing a symbolic link in Try files.'); } catch (e) { if (e.code !== 'ENOENT') throw e; } }
110
- // A local exclude is preferable to changing the project's tracked .gitignore.
111
- const { spawnSync } = await import('node:child_process');
112
- const git = spawnSync('git', ['rev-parse', '--git-path', 'info/exclude'], { cwd: root, encoding: 'utf8' });
113
- if (git.status !== 0) fail('Could not locate the repository’s local Git exclude file.');
114
- const exclude = git.stdout.trim().startsWith('/') ? git.stdout.trim() : join(root, git.stdout.trim());
115
- if (existsSync(exclude)) regular(exclude);
116
- mkdirSync(dirname(exclude), { recursive: true });
117
- if (realpathSync(dirname(exclude)) !== dirname(exclude)) fail('Refusing a symbolic link in the Git exclude path.');
118
- const ignored = existsSync(exclude) ? readFileSync(exclude, 'utf8') : '';
119
- if (!ignored.split('\n').includes('/.pdd/try/')) writeFileSync(exclude, `${ignored}${ignored.endsWith('\n') || !ignored ? '' : '\n'}/.pdd/try/\n`);
221
+ excludeLaunchers(root);
120
222
  const descriptorPath = join(store.folder('tries'), `${sessionId}.door.json`);
121
223
  if (existsSync(descriptorPath) && read(descriptorPath).promptHash !== hash(prompt.text)) fail('The CLI prompt changed since this Try. Run pdd simulate STORY --cli --new.');
122
224
  const ghPath = (ports.env.PATH || process.env.PATH || '').split(':').map(folder => join(folder, 'gh')).find(path => { try { accessSync(path, constants.X_OK); return (lstatSync(path).isFile() || lstatSync(path).isSymbolicLink()) && !readFileSync(path).subarray(0, 64).toString().includes('PDD Try launcher v1'); } catch { return false; } });
@@ -125,6 +227,7 @@ export async function openCli(context, test, sessionId, options) {
125
227
  const usage = tryUsage(metadata);
126
228
  ports.stderr.write(`${tryUsageLine(usage)}\n`);
127
229
  const descriptor = { callCap: usage.cap, version: 1, root, sessionId, origin, login: identity.login, prompt: step.entry_path, operation: step.operation,
230
+ ...(options?.['--fresh'] === true ? { fresh: true } : {}),
128
231
  ghPath: ghPath ? resolve(ghPath) : null, promptHashes: record.prompt_hashes, effectivePromptHashes:record.effective_prompt_hashes, name, inputSchema: entry.input_schema, originalPath: test.path, storyPath: test.doc.story_path, criteria: test.doc.criteria,
129
232
  criterion: step.checks[0]?.criterion_id, storyHash: hash(readFileSync(join(root, test.doc.story_path))),
130
233
  promptHash: hash(prompt.text), stateDir: store.dir, repoState: join(store.folder('repos'), `${store.repoKey(root)}.json`) };
@@ -142,18 +245,20 @@ export async function openCli(context, test, sessionId, options) {
142
245
  if (options['--shell']) {
143
246
  const chosen = ports.env.SHELL || '/bin/sh', shell = ['bash', 'zsh', 'sh'].includes(basename(chosen)) ? chosen : '/bin/sh';
144
247
  const env = { ...ports.env, PATH: `${bin}:${ports.env.PATH || process.env.PATH || ''}` };
145
- if (ports.shell) return ports.shell(shell, env);
248
+ if (ports.shell) return ports.shell(shell, env, root);
146
249
  return new Promise((done, reject) => { const child = spawn(shell, ['-i'], { cwd: root, env, stdio: 'inherit' }); child.on('error', reject); child.on('exit', (code, signal) => done(code ?? (signal ? 128 : 0))); });
147
250
  }
148
251
  return 0;
149
252
  }
150
253
 
151
- function invalidate(descriptor, path) {
152
- const last = join(dirname(path), `${descriptor.sessionId}.last.json`);
153
- writePrivate(last, { state: 'unknown' });
154
- regular(descriptor.repoState);
155
- writePrivate(descriptor.repoState, { ...read(descriptor.repoState), last_door: { descriptor: path, last } });
156
- return last;
254
+ async function invalidate(descriptor, path) {
255
+ const last = join(dirname(path), `${descriptor.sessionId}.last.json`), invocationId = randomUUID();
256
+ await withRepositoryRunLockAsync(descriptor.repoState, () => {
257
+ regular(descriptor.repoState);
258
+ writePrivate(last, {state:'unknown',invocationId});
259
+ writePrivate(descriptor.repoState, {...read(descriptor.repoState),last_door:{descriptor:path,last}});
260
+ });
261
+ return {last,invocationId};
157
262
  }
158
263
  export async function runShim(descriptorPath, argv, givenPorts = {}) {
159
264
  const ports = {
@@ -166,8 +271,12 @@ export async function runShim(descriptorPath, argv, givenPorts = {}) {
166
271
  try {
167
272
  regular(descriptorPath);
168
273
  const d = read(descriptorPath);
274
+ if(d.directProgram){
275
+ if(d.version!==1||(!d.sessionId&&!d.shellBootstrap)||!d.root||realpathSync(d.root)!==d.root||d.programDir!==dirname(descriptorPath))fail('The direct program record is invalid.');
276
+ return await runDirectShim(d,descriptorPath,argv,ports);
277
+ }
169
278
  if (d.version !== 1 || !d.sessionId || !d.root || realpathSync(d.root) !== d.root) fail('The Try session record is invalid. Run pdd simulate STORY --cli again.');
170
- const last = invalidate(d, descriptorPath), input = { argv };
279
+ const {last,invocationId} = await invalidate(d, descriptorPath), input = { argv: [...argv] };
171
280
  if (Object.entries(d.promptHashes ?? { [d.prompt]: d.promptHash }).some(([path, expected]) => hash(readFileSync(join(d.root, path))) !== expected)) fail('The CLI prompt changed since this Try. Run pdd simulate STORY --cli --new.');
172
281
  checkEffectivePrompts(d.root,d.promptHashes ?? {[d.prompt]:d.promptHash},d.effectivePromptHashes);
173
282
  if (d.inputSchema.properties?.stdin && !ports.stdin.isTTY) {
@@ -182,7 +291,10 @@ export async function runShim(descriptorPath, argv, givenPorts = {}) {
182
291
  try { answer = await runDoorCall(d, input, { ...ports, ghPath: d.ghPath, env: { ...ports.env, PDD_STATE_DIR: d.stateDir } }); } finally { clearTimeout(note); }
183
292
  const result = answer.result;
184
293
  if (typeof result.stdout !== 'string' || typeof result.stderr !== 'string' || !Number.isInteger(result.exit_code) || result.exit_code < 0 || result.exit_code > 255 || result.exit_code === WRAPPER_EXIT) fail('The prompt must return stdout, stderr and an exit_code from 0–255 except reserved code 125.');
185
- writePrivate(last, { state: 'confirmed', id: answer.id, input, result, inputWorld: answer.inputWorld, world: answer.world });
294
+ await withRepositoryRunLockAsync(d.repoState, () => {
295
+ regular(last);
296
+ if (read(last).invocationId === invocationId) writePrivate(last, {state:'confirmed',invocationId,id:answer.id,input,result,inputWorld:answer.inputWorld,world:answer.world});
297
+ });
186
298
  ports.stdout.write(result.stdout); ports.stderr.write(result.stderr);
187
299
  ports.stderr.write(`${result.stderr && !result.stderr.endsWith('\n') ? '\n' : ''}${tryUsageLine(answer.usage, { command: true })}\n`);
188
300
  return result.exit_code;
@@ -194,38 +306,293 @@ export async function runShim(descriptorPath, argv, givenPorts = {}) {
194
306
  }
195
307
  }
196
308
 
197
- export async function saveLast({ root, store, identity, ports }) {
198
- const pointer = store.repo(root).last_door;
199
- if (!pointer) fail('No last command is available. Run a command through the Try command first.');
200
- regular(pointer.descriptor); regular(pointer.last);
201
- const d = read(pointer.descriptor), last = read(pointer.last);
202
- if (d.root !== root || identity.login !== d.login) fail(`This Try belongs to ${d.login}. Run: gh auth switch -u ${d.login}`);
203
- if (last.state !== 'confirmed') fail('The last command result is unknown; there is no confirmed output to save.');
204
- if (last.saved) { ports.stdout.write('The last command is already saved.\n'); return 0; }
205
- if (hash(readFileSync(join(root, d.storyPath))) !== d.storyHash || Object.entries(d.promptHashes ?? { [d.prompt]: d.promptHash }).some(([path, expected]) => hash(readFileSync(join(root, path))) !== expected)) fail('The Story or prompt changed since this Try. Open a new Try and run the command again.');
206
- checkEffectivePrompts(root,d.promptHashes ?? {[d.prompt]:d.promptHash},d.effectivePromptHashes);
207
- const step = { step_id: `try-${last.id}`, entry_path: d.prompt, operation: d.operation, input: last.input,
208
- checks: [{ criterion_id: d.criterion, target: 'result', path: '', op: 'equals', value: last.result }] };
209
- (ports?.captureSource ?? ((r, o) => captureSource(r, o, ports)))(root,{tests:[d.originalPath]});
210
- const saved={ id: last.id, name: 'Recorded terminal command', story_path: d.storyPath, original_path: d.originalPath,
211
- test: { schema_version: 'prompt-runtime.program-scenario.v1', story_path: d.storyPath, criteria: d.criteria, ...(Object.hasOwn(last,'inputWorld')?{initial_world:last.inputWorld}:{}), steps: [step] } };
212
- const retained=saveDoorCaseResult(root,saved,{signal:ports.signal,env:ports.env,ports});
213
- if(retained.kind==='failure')fail(retained.message);
214
- const refuse=(outcome,error)=>{ports.stderr.write(`pdd: ${error?cleanText(error)+'. ':''}${outcome.message}\n`);return WRAPPER_EXIT;};
215
- let outcome=retained;
216
- if(retained.result.state==='pending'){
217
- let lease;
218
- try{
219
- if(ports.caseHandoff){const handoff=await ports.caseHandoff({root,testPath:d.originalPath,signal:ports.signal});if(handoff)lease=await acquireCaseWriteOwnership({root,testPath:d.originalPath,handoff,signal:ports.signal},{...ports,env:ports.env});}
220
- else if(ports.interactive){ports.stdout.write(`Close the editor for ${d.originalPath}. Hand over this closed file for the pending case apply? y/N\n`);const answers=(ports.lineReader??defaultLineReader)(ports.stdin);try{if(/^y(?:es)?$/i.test((await answers.ask()).trim()))lease=await acquireCaseWriteOwnership({root,testPath:d.originalPath,handoff:{kind:'closed-editor',testPath:d.originalPath},signal:ports.signal},{...ports,env:ports.env});}finally{answers.close();}}
221
- if(lease)outcome=saveDoorCaseResult(root,saved,{writeOwnership:lease,signal:ports.signal,env:ports.env,ports});
222
- }catch(error){if(error?.unboundPort)throw error;return refuse(retained,error.message??error);}
223
- finally{lease?.release();}
309
+ export async function saveLast({ root, store, identity, ports, test }) {
310
+ const repo = store.repo(root), pointer = test ? null : repo.last_door;
311
+ if (!test && !pointer) fail('No last command is available. Run a command through the Try command first.');
312
+ if (pointer) { regular(pointer.descriptor); regular(pointer.last); }
313
+ const last = test ? repo.last_run : read(pointer.last), d = test ? repo.last_run?.descriptor : read(pointer.descriptor);
314
+ if (last?.state !== 'confirmed') fail('The last command result is unknown; there is no confirmed output to save.');
315
+ if (!d || d.root !== root || identity.login !== d.login) fail(`This Try belongs to ${d?.login ?? 'another owner'}. Run: gh auth switch -u ${d?.login ?? 'OWNER'}`);
316
+ if (!test && (d.programEntry || !d.originalPath || !d.storyPath)) fail('This program run has no selected Story. Its observed result cannot be appended as a Story case.');
317
+ const originalPath = test?.path ?? d.originalPath, storyPath = test?.doc.story_path ?? d.storyPath;
318
+ if (test ? last.saved?.includes(originalPath) : last.saved) { ports.stdout.write('The last command is already saved.\n'); return 0; }
319
+ const capture = ports.captureSource ?? ((r,o)=>captureSource(r,o,ports));
320
+ const authority = () => {
321
+ const policy = loadRuntimeWorkspace({root});
322
+ requireRuntimePath(policy,{path:originalPath,role:'original test'});
323
+ requireRuntimePath(policy,{path:storyPath,role:'original Story'});
324
+ for (const path of new Set([d.prompt,...Object.keys(d.promptHashes??{}),...Object.keys(d.effectivePromptHashes??{})].filter(Boolean))) requireRuntimePath(policy,{path,role:'recorded prompt'});
325
+ };
326
+ authority();
327
+ const storyHash = test ? hash(readFileSync(join(root,storyPath))) : d.storyHash;
328
+ const checkFresh = () => {
329
+ authority();
330
+ capture(root,{tests:[d.prompt]});
331
+ if (hash(readFileSync(join(root,storyPath))) !== storyHash || Object.entries(d.promptHashes ?? {[d.prompt]:d.promptHash}).some(([path,expected])=>hash(readFileSync(join(root,path)))!==expected)) fail('The Story or prompt changed since this Try. Open a new Try and run the command again.');
332
+ checkEffectivePrompts(root,d.promptHashes??{[d.prompt]:d.promptHash},d.effectivePromptHashes);
333
+ if (read(join(root,originalPath)).story_path !== storyPath) fail('The original Story test identity changed. Add the input and the right expected value by hand.');
334
+ };
335
+ checkFresh();
336
+ const original = read(join(root,originalPath));
337
+ const tied = test ? [...new Set(original.steps.filter(step=>step.entry_path===d.prompt&&step.operation===d.operation).flatMap(step=>(step.checks??[]).map(check=>check.criterion_id)))] : [d.criterion];
338
+ if (tied.length !== 1 || !original.criteria.some(item=>item.id===tied[0])) fail('The Story must associate exactly one criterion with this run entry. Add the case and the right expected value by hand.');
339
+ if (!last.inputWorld || typeof last.inputWorld !== 'object' || Array.isArray(last.inputWorld)) fail('The interpreter did not provide confirmed data before this run. Add the input and the right expected value by hand.');
340
+ const manual = `Nothing added. To write the right expected value by hand, edit ${originalPath}: add the input to steps and the expected value to checks (target: "result", op: "equals", value: your correct answer).\n`;
341
+ ports.stdout.write(`Input:\n${JSON.stringify(last.input,null,2)}\nData before:\n${JSON.stringify(last.inputWorld,null,2)}\nOutput:\n${JSON.stringify(last.result,null,2)}\n`);
342
+ if (!ports.stdin?.isTTY || !ports.stdout?.isTTY) {
343
+ ports.stderr.write('A person must answer "Is this answer right? [y/N]" in a terminal. '+manual);
344
+ return WRAPPER_EXIT;
224
345
  }
225
- if(outcome.kind==='failure')fail(outcome.message);
226
- if(outcome.result.state!=='committed')return refuse(outcome);
227
- writePrivate(pointer.last, { ...last, saved: true });
228
- ports.stdout.write(`${outcome.message}\n`);
229
- if (last.inputWorld && Object.keys(last.inputWorld).length) ports.stdout.write('This records observed output. Review the saved-data setup before replaying this case.\n');
230
- return 0;
346
+ const checkCurrent = () => {
347
+ const current = store.repo(root);
348
+ if (test) {
349
+ if (current.last_run?.state !== 'confirmed' || current.last_run.id !== last.id) fail('The last command was superseded or is unknown. Run the command again before saving.');
350
+ return current;
351
+ }
352
+ if (current.last_door?.descriptor !== pointer.descriptor || current.last_door?.last !== pointer.last) fail('The last command was superseded. Run the command again before saving.');
353
+ regular(pointer.last);
354
+ const latest = read(pointer.last);
355
+ if (latest.state !== 'confirmed' || latest.id !== last.id || latest.invocationId !== last.invocationId) fail('The last command was superseded or is unknown. Run the command again before saving.');
356
+ return current;
357
+ };
358
+ const repoState = test ? join(store.folder('repos'), `${store.repoKey(root)}.json`) : d.repoState;
359
+ const locked = action => store.withRepoLock ? store.withRepoLock(root,action) : withRepositoryRunLockAsync(repoState,action);
360
+ const answers = (ports.lineReader ?? defaultLineReader)(ports.stdin);
361
+ try {
362
+ ports.stdout.write('Is this answer right? [y/N]\n');
363
+ if (!/^y$/i.test((await answers.ask()).trim())) { ports.stdout.write(manual); return 0; }
364
+ const step = {step_id:`try-${last.id}`,entry_path:d.prompt,operation:d.operation,input:last.input,
365
+ checks:[{criterion_id:tied[0],target:'result',path:'',op:'equals',value:last.result}]};
366
+ const saved = {id:last.id,name:'Recorded terminal command',story_path:storyPath,original_path:originalPath,
367
+ test:{schema_version:'prompt-runtime.program-scenario.v1',story_path:storyPath,criteria:original.criteria,
368
+ initial_world:last.inputWorld,...(Object.keys(original.simulation??{}).length?{simulation:original.simulation}:{}),...(original.context?.length?{context:original.context}:{}),steps:[step]}};
369
+ const publish = writeOwnership => locked(() => {
370
+ const current = checkCurrent(); checkFresh(); capture(root,{tests:[originalPath]});
371
+ const outcome = saveDoorCaseResult(root,saved,{writeOwnership,signal:ports.signal,env:ports.env,ports,publicationGuard:()=>{checkCurrent();checkFresh();}});
372
+ if (outcome.kind === 'case' && outcome.result.state === 'committed') {
373
+ if (test) store.write(repoState,{...current,last_run:{...current.last_run,saved:[...new Set([...(current.last_run.saved??[]),originalPath])]}});
374
+ else writePrivate(pointer.last,{...read(pointer.last),saved:true});
375
+ }
376
+ return outcome;
377
+ });
378
+ let outcome = await publish();
379
+ if (outcome.kind === 'failure') fail(outcome.message);
380
+ const refuse = (result,error) => { ports.stderr.write(`pdd: ${error?cleanText(error)+'. ':''}${result.message}\n`); return WRAPPER_EXIT; };
381
+ if (outcome.result.state === 'pending') {
382
+ let lease;
383
+ try {
384
+ if (ports.caseHandoff) {
385
+ const handoff = await ports.caseHandoff({root,testPath:originalPath,signal:ports.signal});
386
+ if (handoff) lease = await acquireCaseWriteOwnership({root,testPath:originalPath,handoff,signal:ports.signal},{...ports,env:ports.env});
387
+ } else {
388
+ ports.stdout.write(`Close the editor for ${originalPath}. Hand over this closed file for the pending case apply? y/N\n`);
389
+ if (/^y(?:es)?$/i.test((await answers.ask()).trim())) lease = await acquireCaseWriteOwnership({root,testPath:originalPath,handoff:{kind:'closed-editor',testPath:originalPath},signal:ports.signal},{...ports,env:ports.env});
390
+ }
391
+ if (lease) outcome = await publish(lease);
392
+ } catch (error) { if(error?.unboundPort)throw error; return refuse(outcome,error.message??error); }
393
+ finally { lease?.release(); }
394
+ }
395
+ if (outcome.kind === 'failure') fail(outcome.message);
396
+ if (outcome.result.state !== 'committed') return refuse(outcome);
397
+ const actualStep = outcome.result.steps?.[0] ?? step.step_id;
398
+ ports.stdout.write(`Added to ${originalPath} as step ${actualStep}. Review the data before this step, then run: pdd test ${test?.story ?? basename(storyPath,'.md')}\n`);
399
+ return 0;
400
+ } finally { answers.close(); }
401
+ }
402
+
403
+ // Direct typed commands share the executable schema subset, but never defer input
404
+ // validation to a model. In particular, unsupported schemas cannot skip checks.
405
+ const typedObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
406
+ function typedEqual(left,right) {
407
+ // Native numeric equality gives JSON's single zero value. Recurse without
408
+ // coercing scalar types, object members or array positions.
409
+ if(left===right)return true;
410
+ if(Array.isArray(left))return Array.isArray(right)&&left.length===right.length&&left.every((value,index)=>typedEqual(value,right[index]));
411
+ if(!typedObject(left)||!typedObject(right))return false;
412
+ const names=Object.keys(left);
413
+ return names.length===Object.keys(right).length&&names.every(name=>Object.hasOwn(right,name)&&typedEqual(left[name],right[name]));
414
+ }
415
+ const typedJson = text => JSON.parse(text,(key,value)=>{
416
+ if (typeof value==='number' && !Number.isFinite(value)) throw Error('JSON numbers must be finite.');
417
+ return value;
418
+ });
419
+ function typedMultipleOf(value, step) {
420
+ // Compare exact decimal Number spellings, including scientific notation.
421
+ const decimal = number => {
422
+ const [mantissa, exponent='0'] = String(number).split('e');
423
+ const [whole, fraction=''] = mantissa.split('.');
424
+ return {coefficient:BigInt(whole+fraction), exponent:Number(exponent)-fraction.length};
425
+ };
426
+ const valueParts=decimal(value), stepParts=decimal(step);
427
+ const difference=valueParts.exponent-stepParts.exponent;
428
+ return difference>=0
429
+ ? (valueParts.coefficient*10n**BigInt(difference))%stepParts.coefficient===0n
430
+ : valueParts.coefficient%(stepParts.coefficient*10n**BigInt(-difference))===0n;
431
+ }
432
+ class UnsupportedTypedPattern extends Error {
433
+ constructor() { super('Unsupported input pattern: local validation requires portable syntax and printable ASCII input.'); }
434
+ }
435
+ function typedPattern(source) {
436
+ // Keep membership evidence within the common JavaScript/Python domain.
437
+ // Outside printable ASCII, classes, dot and end anchors can disagree.
438
+ if (/[^\x20-\x7e]/u.test(source) || /\[\^?\]/u.test(source)
439
+ || /\\(?:[1-9bBAZzGkpPuU]|x|c)|\(\?/u.test(source)
440
+ // Python refuses overflowing repetition counts that JavaScript can compile.
441
+ || /\{(?:\d{10,}(?:,\d*)?|\d*,\d{10,})\}/u.test(source)) throw new UnsupportedTypedPattern();
442
+ try { return new RegExp(source,'u'); } catch { throw new UnsupportedTypedPattern(); }
443
+ }
444
+ function typedValidation(value, schema) {
445
+ const issues = interfaceSchemaProblems({entries:[{input_schema:schema}],limits:{max_steps:1,max_model_calls:1}});
446
+ if (issues.length) throw Error(`Unsupported input schema: ${issues[0].pointer} ${issues[0].rule}`);
447
+ // Unsupported pattern syntax refuses even on omitted or unused branches.
448
+ const patterns=new Map();
449
+ const compile=shape=>{
450
+ if(typeof shape.pattern==='string') patterns.set(shape,typedPattern(shape.pattern));
451
+ if(Array.isArray(shape.oneOf)) shape.oneOf.forEach(compile);
452
+ if(shape.type==='object') Object.values(shape.properties).forEach(compile);
453
+ if(shape.type==='array') compile(shape.items);
454
+ };
455
+ compile(schema);
456
+ const visit = (item, shape) => {
457
+ if (Array.isArray(shape.oneOf)) {
458
+ const matches = shape.oneOf.filter(part => {
459
+ try { visit(item,part); return true; }
460
+ catch (error) { if(error instanceof UnsupportedTypedPattern) throw error; return false; }
461
+ });
462
+ if (matches.length !== 1) throw Error('Input must match exactly one allowed shape.');
463
+ return;
464
+ }
465
+ const invalid = reason => {throw Error(`Input ${reason}`);};
466
+ const type=item===null?'null':Array.isArray(item)?'array':typeof item;
467
+ if(shape.type==='integer'? !Number.isInteger(item) : shape.type==='object'? !typedObject(item) : shape.type!==type) invalid(`must be ${shape.type}.`);
468
+ if (shape.enum && !shape.enum.some(choice=>typedEqual(item,choice))) invalid('is not an allowed enum value.');
469
+ if (Object.hasOwn(shape,'const') && !typedEqual(item,shape.const)) invalid('does not match its const value.');
470
+ if (typeof item==='number') {
471
+ if(!Number.isFinite(item)) invalid('numbers must be finite.');
472
+ if(shape.minimum!==undefined && item<shape.minimum || shape.maximum!==undefined && item>shape.maximum
473
+ || shape.exclusiveMinimum!==undefined && item<=shape.exclusiveMinimum || shape.exclusiveMaximum!==undefined && item>=shape.exclusiveMaximum) invalid('is outside its numeric bounds.');
474
+ if(shape.multipleOf!==undefined && !typedMultipleOf(item,shape.multipleOf)) invalid('must be a multiple of its declared step.');
475
+ }
476
+ if (typeof item==='string') {
477
+ const length=[...item].length;
478
+ if(shape.minLength!==undefined && length<shape.minLength || shape.maxLength!==undefined && length>shape.maxLength) invalid('is outside its string length bounds.');
479
+ if(patterns.has(shape)) {
480
+ if(/[^\x20-\x7e]/u.test(item)) throw new UnsupportedTypedPattern();
481
+ if(!patterns.get(shape).test(item)) invalid('does not match its pattern.');
482
+ }
483
+ }
484
+ if (Array.isArray(item)) {
485
+ if(shape.minItems!==undefined && item.length<shape.minItems || shape.maxItems!==undefined && item.length>shape.maxItems) invalid('is outside its array length bounds.');
486
+ if(shape.uniqueItems && item.some((child,index)=>item.slice(0,index).some(other=>typedEqual(child,other)))) invalid('requires unique array items.');
487
+ item.forEach(child=>visit(child,shape.items));
488
+ }
489
+ if (typedObject(item)) {
490
+ const count=Object.keys(item).length;
491
+ if(shape.minProperties!==undefined && count<shape.minProperties || shape.maxProperties!==undefined && count>shape.maxProperties) invalid('is outside its field count bounds.');
492
+ for(const name of shape.required) if(!Object.hasOwn(item,name)) invalid(`requires field ${name}.`);
493
+ for(const [name,child] of Object.entries(item)) {
494
+ if(!Object.hasOwn(shape.properties,name)) invalid(`has unknown field ${name}.`);
495
+ visit(child,shape.properties[name]);
496
+ }
497
+ }
498
+ };
499
+ visit(value,schema);
500
+ }
501
+
502
+ function typedInputJson(value) {
503
+ if (Array.isArray(value)) return '['+value.map(typedInputJson).join(',')+']';
504
+ if (typedObject(value)) return '{'+Object.keys(value).sort().map(name=>JSON.stringify(name)+':'+typedInputJson(value[name])).join(',')+'}';
505
+ return JSON.stringify(value);
506
+ }
507
+
508
+ export function prepareTypedInvocation({prompt_path,argv,interface_json,stdin_json,input_file_json}) {
509
+ let entries = [], selected;
510
+ const usage = () => {
511
+ const properties=typedObject(selected?.input_schema?.properties)?selected.input_schema.properties:{};
512
+ const required=Array.isArray(selected?.input_schema?.required)?selected.input_schema.required:[];
513
+ const fields=Object.entries(properties).filter(([,schema])=>typedObject(schema) && (typeof schema.type==='string' || Array.isArray(schema.oneOf)));
514
+ return `Usage: pdd ${prompt_path} [OPERATION] [--field value ... | --input JSON|@file]\nOperations: ${entries.map(entry=>entry.operation).join(', ')}\n`
515
+ + (selected ? 'Fields:\n'+fields.map(([name,schema])=>` --${name} <${typeof schema.type==='string'?schema.type:'oneOf'}> (${required.includes(name)?'required':'optional'})\n`).join('') : '');
516
+ };
517
+ const local = (kind,reason='') => ({kind,operation:null,input_json:null,stdout:'',stderr:(reason?reason+'\n':'')+usage(),exit_code:2});
518
+ try {
519
+ const iface=typedJson(interface_json);
520
+ if (!Array.isArray(iface?.entries) || !iface.entries.length || iface.entries.some(entry=>typeof entry?.operation!=='string')) throw Error('The typed interface is unavailable.');
521
+ entries=iface.entries;
522
+ const args=[...argv];
523
+ const word=args[0] && !args[0].startsWith('-') ? args.shift() : undefined;
524
+ const matches=word===undefined ? entries.length===1?entries:[] : entries.filter(entry=>entry.operation===word);
525
+ if (matches.length===1) selected=matches[0];
526
+ if (args.includes('--help')) return local('help');
527
+ if (!selected) throw Error(word===undefined?'Choose an operation.':'Unknown or ambiguous operation.');
528
+ const schema=selected.input_schema;
529
+ // Validate the schema even when all fields are optional.
530
+ const schemaIssues=interfaceSchemaProblems({entries:[{input_schema:schema}],limits:{max_steps:1,max_model_calls:1}});
531
+ if (schemaIssues.length) throw Error(`Unsupported input schema: ${schemaIssues[0].pointer} ${schemaIssues[0].rule}`);
532
+ let input={}, whole, fields=0, wholeCount=0;
533
+ const scalar=(token,shape)=>{
534
+ if (shape?.type==='string') return token;
535
+ if (shape?.type==='boolean' && ['true','false'].includes(token)) return token==='true';
536
+ if (['integer','number'].includes(shape?.type) && /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(token)) {
537
+ const value=Number(token);
538
+ if (Number.isFinite(value) && (shape.type!=='integer' || Number.isInteger(value))) return value;
539
+ }
540
+ throw Error('Invalid scalar value or unsupported flag shape. Use --input for objects and non-scalar arrays.');
541
+ };
542
+ for (let index=0;index<args.length;index++) {
543
+ const flag=args[index], token=args[++index];
544
+ if (!/^--[^=]+$/.test(flag) || token===undefined || token.startsWith('--')) throw Error('Each field flag needs a value.');
545
+ const name=flag.slice(2);
546
+ if (name==='input') { wholeCount++; whole=token; continue; }
547
+ if (schema.type!=='object') throw Error('Field flags require top-level schema properties. Use --input for this input shape.');
548
+ if (!Object.hasOwn(schema.properties,name)) throw Error(`Unknown field: ${flag}.`);
549
+ fields++;
550
+ const shape=schema.properties[name];
551
+ if (shape.type==='array') {
552
+ if (!Object.hasOwn(input,name)) Object.defineProperty(input,name,{value:[],enumerable:true,writable:true,configurable:true});
553
+ input[name].push(scalar(token,shape.items));
554
+ } else {
555
+ if (Object.hasOwn(input,name)) throw Error(`Repeated field: ${flag}.`);
556
+ Object.defineProperty(input,name,{value:scalar(token,shape),enumerable:true,writable:true,configurable:true});
557
+ }
558
+ }
559
+ if (wholeCount>1 || wholeCount && fields) throw Error('Use one --input or field flags.');
560
+ if (wholeCount) input=typedJson(whole.startsWith('@') ? input_file_json : whole);
561
+ else if (!fields && stdin_json!==undefined) input=typedJson(stdin_json);
562
+ if (!typedObject(input)) throw Error('Input must be a JSON object.');
563
+ typedValidation(input,schema);
564
+ return {kind:'call',operation:selected.operation,input_json:typedInputJson(input),stdout:'',stderr:'',exit_code:0};
565
+ } catch (error) { return local('usage',error instanceof SyntaxError?'Input must be valid JSON.':error.message); }
566
+ }
567
+
568
+ export function formatTypedOutcome({outcome,result_json,error_json}) {
569
+ try {
570
+ if (outcome==='result') return {stdout:JSON.stringify(typedJson(result_json))+'\n',stderr:'',exit_code:0};
571
+ const error=typedJson(error_json ?? '{}');
572
+ if (outcome==='program_error' && typeof error?.code==='string' && typeof error?.message==='string'
573
+ && (error.call_chain===undefined || Array.isArray(error.call_chain) && error.call_chain.every(row=>typeof row?.prompt==='string' && typeof row?.operation==='string'))) {
574
+ const chain=error.call_chain?.length ? 'Traceback (prompt calls):\n'+error.call_chain.map(row=>` ${row.prompt}: ${row.operation}\n`).join('') : '';
575
+ return {stdout:'',stderr:chain+`pdd: ${error.code}: ${error.message}\n`,exit_code:1};
576
+ }
577
+ return {stdout:'',stderr:`pdd: ${causeText(error?.message).replace(/https?:\/\/[^\s]+/gi,'<service>') || 'The PDD interpreter returned an incompatible outcome.'}\n`,exit_code:125};
578
+ } catch { return {stdout:'',stderr:'pdd: The PDD interpreter returned an incompatible outcome.\n',exit_code:125}; }
579
+ }
580
+
581
+ export { analyzePromptSelectorWords };
582
+
583
+ export function selectorLintForPrompts({ root, visible, paths, workspace }) {
584
+ const appMapScreens = readAppMapScreens(root, visible, workspace);
585
+ const warnings = [];
586
+ const tableLines = [];
587
+ const seen = new Set();
588
+ for (const path of paths ?? []) {
589
+ if (typeof path !== 'string' || seen.has(path)) continue;
590
+ seen.add(path);
591
+ let prompt;
592
+ try { prompt = readPrompt(root, visible, path, workspace); } catch { continue; }
593
+ const info = analyzePromptSelectorWords(prompt, { appMapScreens });
594
+ for (const warning of info.warnings) if (!warnings.includes(warning)) warnings.push(warning);
595
+ if (info.tableLines.length) tableLines.push(...info.tableLines);
596
+ }
597
+ return { warnings, tableLines };
231
598
  }