@promptdriven/runtime-client 0.0.0-stage → 1.0.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.
Files changed (35) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +42 -2
  3. package/package.json +28 -4
  4. package/src/index.mjs +1 -0
  5. package/src/runtime/agent-ask.mjs +187 -0
  6. package/src/runtime/agent-chat.mjs +105 -0
  7. package/src/runtime/agent-coverage.mjs +97 -0
  8. package/src/runtime/agent-guide.mjs +152 -0
  9. package/src/runtime/agent-judge.mjs +71 -0
  10. package/src/runtime/agent-packet.mjs +62 -0
  11. package/src/runtime/agent-project.mjs +93 -0
  12. package/src/runtime/contract-refs.mjs +519 -0
  13. package/src/runtime/contracts.mjs +138 -0
  14. package/src/runtime/index.mjs +943 -0
  15. package/src/runtime/lint-call-preflight.mjs +19 -0
  16. package/src/runtime/lint-compatibility-display.mjs +62 -0
  17. package/src/runtime/product-composition.mjs +384 -0
  18. package/src/runtime/runtime-binding-plan.mjs +145 -0
  19. package/src/runtime/runtime-bindings.mjs +71 -0
  20. package/src/runtime/runtime-check-plan.mjs +411 -0
  21. package/src/runtime/runtime-client.mjs +6323 -0
  22. package/src/runtime/runtime-lint-receipt.mjs +25 -0
  23. package/src/runtime/runtime-markdown.mjs +215 -0
  24. package/src/runtime/runtime-outcome.mjs +407 -0
  25. package/src/runtime/runtime-output.mjs +714 -0
  26. package/src/runtime/runtime-preflight.mjs +3118 -0
  27. package/src/runtime/runtime-slots.mjs +391 -0
  28. package/src/runtime/runtime-workspace-migration.mjs +70 -0
  29. package/src/runtime/runtime-workspace.mjs +52 -0
  30. package/src/runtime/scenario-json.mjs +91 -0
  31. package/src/runtime/secret-redaction.mjs +53 -0
  32. package/src/runtime/try-doors.mjs +231 -0
  33. package/src/runtime/try-http.mjs +259 -0
  34. package/src/runtime/try-mcp.mjs +223 -0
  35. package/src/runtime/try-session.mjs +95 -0
@@ -0,0 +1,138 @@
1
+ import {loadRuntimeWorkspace,allowsRuntimePath} from './runtime-workspace.mjs';
2
+ // Generated from prompts/cli/contracts.prompt.md (sha256: cf5871b996696fe6a67c650e008cc651c150441ecd6d21c15645302f8a1d4954).
3
+ import { randomUUID } from 'node:crypto';
4
+ import { spawnSync } from 'node:child_process';
5
+ import { closeSync, constants, fchmodSync, fstatSync, lstatSync, openSync, renameSync, unlinkSync, writeSync } from 'node:fs';
6
+ import { dirname, join } from 'node:path';
7
+ import { isDeepStrictEqual } from 'node:util';
8
+ import { catalogRecords, compareCopies, expandSource, planSync } from './contract-refs.mjs';
9
+ import { createStrictSourceAccess, gitFiles, LIMITS } from './runtime-preflight.mjs';
10
+ import { readContractHistory } from './runtime-client.mjs';
11
+
12
+ const line = (stream,text) => stream.write(`${text}\n`);
13
+ const finite = error => String(error.message ?? error).replace(/[\r\n\x00-\x1f\x7f]/g,' ').slice(0,4000);
14
+ const snapshotMap = references => new Map(references.map(ref=>[`${ref.kind}:${ref.target}`,ref.value_json]));
15
+
16
+ export function runContracts({words = [],options = {},cwd = process.cwd()} = {}, ports = {}) {
17
+ const {env = process.env,stdout = process.stdout,stderr = process.stderr} = ports;
18
+ if (words.length>1 || words.length===1 && words[0]!=='sync' || Object.keys(options).some(key=>key!=='--write') || options['--write']!==undefined && (words[0]!=='sync' || options['--write']!==true)) {
19
+ line(stderr,'Use pdd contracts or pdd contracts sync [--write].'); return 2;
20
+ }
21
+ const git=spawnSync('git',['rev-parse','--show-toplevel'],{cwd,encoding:'utf8'});
22
+ if (git.status!==0 || !git.stdout.trim()) { line(stderr,'pdd contracts works in a Git repository.'); return 2; }
23
+ const root=git.stdout.trim();
24
+ try {
25
+ const access=createStrictSourceAccess(root,undefined,ports);
26
+ const workspace=loadRuntimeWorkspace({root}), visible=new Set(gitFiles(root).filter(path=>allowsRuntimePath(workspace,path))), files=access.sourceFilePort(visible);
27
+ const warnings = [];
28
+ const readDiscovered = path => {
29
+ if (files.stat({path}).size > LIMITS.bytes) { warnings.push(`${path}: discovery/catalog unavailable (too big; limit 10 MB).`); return []; }
30
+ return [{path,text:files.read({path}).content}];
31
+ };
32
+ const sources=[...visible].sort().filter(path=>path.startsWith('contracts/') && /\.(?:md|json)$/.test(path)).flatMap(readDiscovered);
33
+ const promptPaths=[...visible].sort().filter(path=>path.endsWith('.prompt.md'));
34
+ const prompts=promptPaths.flatMap(readDiscovered);
35
+ const found=access.findTests({files:[...visible]});
36
+ warnings.push(...found.warnings.map(warning=>warning.replace(/^Warning: /,'')));
37
+ const prepared=[];
38
+ for (const source of prompts) {
39
+ try { prepared.push({...source,...expandSource({...source,format:'prompt'},files)}); }
40
+ catch (error) { warnings.push(`${source.path}: current uses unavailable: ${finite(error)}`); }
41
+ }
42
+ // Listing has no selected runtime program. Isolate unavailable consumers so
43
+ // one unfinished sibling cannot hide every independent record and Story.
44
+ const stories=new Map(), selectedReferences=[];
45
+ for (const test of found.tests) {
46
+ if (stories.has(test.doc?.story_path) && !stories.get(test.doc.story_path).selectedUnavailable) continue;
47
+ try {
48
+ const captured=access.captureSource({tests:[test.path]});
49
+ selectedReferences.push(...captured.references);
50
+ for (const story of captured.stories) stories.set(story.story_path,story);
51
+ } catch (error) {
52
+ if (error?.unboundPort) throw error;
53
+ const cause=finite(error); warnings.push(`${test.path}: footprint unavailable: ${cause}`);
54
+ if (typeof test.doc?.story_path==='string') stories.set(test.doc.story_path,{story_path:test.doc.story_path,tests:[test.path],selectedUnavailable:true,unavailable:[{path:test.path,cause}]});
55
+ }
56
+ }
57
+ const capture={stories:[...stories.values()]};
58
+ const references=[...prepared.flatMap(source=>source.references),...selectedReferences,...capture.stories.flatMap(story=>story.references ?? [])];
59
+ for (const warning of warnings) line(stderr,`Warning: ${warning}`);
60
+ const catalog=catalogRecords(sources,references.map(ref=>ref.target));
61
+ for (const warning of catalog.warnings) line(stderr,`Warning: ${warning}`);
62
+ if (words[0]==='sync') {
63
+ const compared=compareCopies(prompts,catalog.records), plan=planSync(prompts,compared.matches);
64
+ for (const warning of [...compared.warnings,...plan.warnings]) line(stderr,`Warning: ${warning}`);
65
+ for (const match of compared.matches) line(stdout,`${match.path} ${match.source_pointer} -> ${match.target}${match.differences.length ? `; adopts ${match.differences.join('; ')}` : '; exact copy'}`);
66
+ if (options['--write']!==true) { line(stdout,`Preview: ${plan.edits.length} files. Use --write to apply.`); return 0; }
67
+ let failures=0,changed=0;
68
+ for (const edit of plan.edits) {
69
+ let fd, temporary, owned;
70
+ try {
71
+ const path=join(root,edit.path), before=lstatSync(path,{bigint:true});
72
+ const ancestors = () => {
73
+ const parts = edit.path.split('/'), result = [];
74
+ for (let i=1;i<parts.length;i++) {
75
+ const parent = lstatSync(join(root,...parts.slice(0,i)),{bigint:true});
76
+ if (!parent.isDirectory() || parent.isSymbolicLink()) throw new Error('destination ancestor changed since preview');
77
+ result.push([parent.dev,parent.ino]);
78
+ }
79
+ return result;
80
+ };
81
+ const parents = ancestors();
82
+ const current=access.sourceFilePort(new Set(gitFiles(root)));
83
+ if (current.read({path:edit.path}).content!==edit.before) throw new Error('source changed since preview');
84
+ const sameIdentity = stat => stat.isFile() && stat.dev===before.dev && stat.ino===before.ino && stat.size===before.size && stat.mtimeNs===before.mtimeNs && stat.ctimeNs===before.ctimeNs;
85
+ // Exclusive preparation leaves the complete destination visible until
86
+ // the final rename; no destination descriptor is ever truncated.
87
+ for (let attempt=0;attempt<100;attempt++) {
88
+ const candidate=join(dirname(path),`.pdd-sync-${randomUUID()}.tmp`);
89
+ try { fd=openSync(candidate,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,Number(before.mode & 0o777n)); temporary=candidate; break; }
90
+ catch (error) { if (error.code!=='EEXIST') throw error; }
91
+ }
92
+ if (fd===undefined) throw new Error('cannot prepare exclusive temporary file');
93
+ owned=fstatSync(fd,{bigint:true});
94
+ fchmodSync(fd,Number(before.mode & 0o777n));
95
+ const bytes=Buffer.from(edit.after,'utf8');
96
+ let offset=0;
97
+ while (offset<bytes.length) { const written=writeSync(fd,bytes,offset,bytes.length-offset,offset); if (!written) throw new Error('temporary write made no progress'); offset+=written; }
98
+ const prepared=fstatSync(fd,{bigint:true});
99
+ if (!prepared.isFile() || prepared.size!==BigInt(bytes.length) || prepared.dev!==owned.dev || prepared.ino!==owned.ino) throw new Error('temporary file changed');
100
+ closeSync(fd); fd=undefined;
101
+ if (!sameIdentity(lstatSync(path,{bigint:true})) || !isDeepStrictEqual(parents,ancestors())) throw new Error('destination changed since preview');
102
+ if (access.sourceFilePort(new Set(gitFiles(root))).read({path:edit.path}).content!==edit.before) throw new Error('source changed since preview');
103
+ const tempNow=lstatSync(temporary,{bigint:true});
104
+ if (tempNow.isSymbolicLink() || tempNow.dev!==owned.dev || tempNow.ino!==owned.ino || !sameIdentity(lstatSync(path,{bigint:true})) || !isDeepStrictEqual(parents,ancestors())) throw new Error('destination or temporary file changed since preview');
105
+ renameSync(temporary,path); temporary=undefined;
106
+ changed++; line(stdout,`Updated ${edit.path}`);
107
+ } catch (error) { failures++; line(stderr,`Refused ${edit.path}: ${finite(error)}`); }
108
+ finally { if (fd!==undefined) closeSync(fd); if (temporary!==undefined) { try { const remaining=lstatSync(temporary,{bigint:true}); if (owned && remaining.dev===owned.dev && remaining.ino===owned.ino) unlinkSync(temporary); } catch {} } }
109
+ }
110
+ line(stdout,`Sync: ${changed} files updated, ${failures} refused.`);
111
+ return failures ? 4 : 0;
112
+ }
113
+ const history=readContractHistory({root,env},ports);
114
+ for (const warning of history.warnings) line(stderr,`Warning: ${warning}`);
115
+ const unknownStories=capture.stories.some(story=>story.unavailable?.length);
116
+ const unknownUses=prepared.length<promptPaths.length || unknownStories;
117
+ for (const record of catalog.records) {
118
+ const users=[...new Set(references.filter(ref=>ref.target===record.target).map(ref=>ref.consumer))].sort();
119
+ const stories=capture.stories.filter(story=>story.references?.some(ref=>ref.target===record.target)).map(story=>story.story_path).sort();
120
+ const userEvidence=users.length ? `${users.join(', ')}${unknownUses?' (incomplete)':''}` : unknownUses?'unavailable':'none';
121
+ line(stdout,`${record.target} owner: ${record.path} users: ${userEvidence} Stories: ${stories.join(', ')||(unknownStories?'unavailable':'none')}`);
122
+ }
123
+ for (const story of capture.stories) {
124
+ if (story.unavailable?.length) { line(stdout,`${story.story_path}: footprint unavailable (${story.unavailable.map(item=>item.cause).join('; ')})`); continue; }
125
+ const baseline=history.stories.find(row=>row.story_path===story.story_path);
126
+ if (history.warnings.length) { line(stdout,`${story.story_path}: baseline unavailable`); continue; }
127
+ if (!baseline || baseline.baseline==='not-checked') { line(stdout,`${story.story_path}: not checked`); continue; }
128
+ if (baseline.baseline==='unavailable' || history.warnings.length) { line(stdout,`${story.story_path}: baseline unavailable`); continue; }
129
+ const before=snapshotMap(baseline.references), current=snapshotMap(story.references);
130
+ const changed=[...new Set([...before.keys(),...current.keys()])].filter(key=>before.get(key)!==current.get(key));
131
+ for (const identity of changed) line(stdout,`${identity.slice(identity.indexOf(':')+1)}: changed since the last check (${story.story_path})`);
132
+ const stale=changed.length || !isDeepStrictEqual(baseline.files,story.files);
133
+ line(stdout,`${story.story_path}: ${stale?'stale: needs a new check':'current'} (last check ${baseline.result_state}, ${baseline.checked_at})`);
134
+ }
135
+ if (!catalog.records.length) line(stdout,'No shared contract records found.');
136
+ return 0;
137
+ } catch (error) { if (error?.unboundPort) throw error; line(stderr,finite(error)); return error.exitCode ?? (error.code?.startsWith('contract-') || error.code==='seed-invalid' ? 4 : 5); }
138
+ }