@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,519 @@
1
+ // Generated from prompts/cli/contract-refs.prompt.md (sha256: d8eb48d704e6ab8441b09867fc7fe96c9c4c3559cfa9d704112733ef2907462b).
2
+ // Numbers remain tokens until serialization, including values outside binary64.
3
+ class JsonNumber { constructor(text) { this.text = text; Object.freeze(this); } }
4
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof JsonNumber);
5
+ const LIMIT = 10_485_760;
6
+ const layouts = new WeakMap();
7
+ const put = (value, key, item) => Object.defineProperty(value, key, { value: item, enumerable: true, configurable: true, writable: true });
8
+ const keysOf = value => {
9
+ const layout=layouts.get(value);
10
+ if (!layout) return Object.keys(value);
11
+ const written=new Set(layout.keys);
12
+ return [...layout.keys.filter(key=>Object.hasOwn(value,key)),...Object.keys(value).filter(key=>!written.has(key))];
13
+ };
14
+ // Strings are scanned by hand: the simple regex forms for a string body either backtrack
15
+ // exponentially or overflow the regex stack at the source size limit.
16
+ function lex(text) {
17
+ const tokens = [], scalar = /-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null|[{}\[\]:,"]/g;
18
+ for (let match; (match = scalar.exec(text));) {
19
+ if (match[0] !== '"') { tokens.push(match); continue; }
20
+ let end = match.index + 1;
21
+ while (end < text.length && text[end] !== '"') end += text[end] === '\\' ? 2 : 1;
22
+ tokens.push(Object.assign([text.slice(match.index, end + 1)], {index:match.index}));
23
+ scalar.lastIndex = end + 1;
24
+ }
25
+ return tokens;
26
+ }
27
+ // JSON.parse remains the value decoder. This lexical index records the source
28
+ // spans and written member order which JavaScript's object enumeration loses.
29
+ function parse(text) {
30
+ const value = JSON.parse(text, (_key, item, context) => typeof item === 'number' ? new JsonNumber(context.source) : item);
31
+ const tokens = lex(text);
32
+ let index = 0;
33
+ function locate(item) {
34
+ const first = tokens[index++], start = first.index;
35
+ const array = first[0] === '[';
36
+ if (!array && first[0] !== '{') return {start,end:start+first[0].length,value:item};
37
+ const entries = [], keys = [];
38
+ while (tokens[index][0] !== (array ? ']' : '}')) {
39
+ let key, keyStart, keyEnd;
40
+ if (array) key = String(entries.length);
41
+ else { const token = tokens[index++]; keyStart = token.index; keyEnd = token.index+token[0].length; key = JSON.parse(token[0]); index++; }
42
+ const child = locate((object(item) || Array.isArray(item)) && Object.hasOwn(item,key) ? item[key] : undefined);
43
+ entries.push({...child,key,keyStart,keyEnd}); keys.push(key);
44
+ if (tokens[index][0] === ',') index++; else break;
45
+ }
46
+ const end = tokens[index++].index + 1;
47
+ if ((array && Array.isArray(item)) || (!array && object(item))) {
48
+ const last = new Map(entries.map((entry,i)=>[entry.key,i]));
49
+ entries.forEach((entry,i)=>{entry.active=last.get(entry.key)===i;});
50
+ layouts.set(item,{text,start,end,entries,keys:[...new Set(keys)]});
51
+ }
52
+ return {start,end,value:item};
53
+ }
54
+ locate(value);
55
+ return value;
56
+ }
57
+ function shallow(value) {
58
+ const result = Array.isArray(value) ? [] : {};
59
+ for (const key of keysOf(value)) put(result,key,value[key]);
60
+ if (layouts.has(value)) layouts.set(result,layouts.get(value));
61
+ return result;
62
+ }
63
+ function clone(value) {
64
+ if (!object(value) && !Array.isArray(value)) return value;
65
+ const result = shallow(value);
66
+ for (const key of keysOf(value)) put(result,key,clone(value[key]));
67
+ return result;
68
+ }
69
+ function writeJson(value, {canonical = false, collect = true, tooBig = () => { throw new Error('JSON value is too big'); }} = {}) {
70
+ let size = 0; const parts = [], measured = new WeakMap();
71
+ const append = text => { size += Buffer.byteLength(text); if (size > LIMIT) tooBig(); if (collect) parts.push(text); };
72
+ function visit(item) {
73
+ if (item instanceof JsonNumber) { append(item.text); return; }
74
+ if (!object(item) && !Array.isArray(item)) { append(JSON.stringify(item)); return; }
75
+ if (!collect && measured.has(item)) { size += measured.get(item); if (size>LIMIT) tooBig(); return; }
76
+ const initialSize = size;
77
+ const layout = !canonical && layouts.get(item), keys = canonical && !Array.isArray(item) ? Object.keys(item).sort() : keysOf(item);
78
+ if (layout && layout.keys.every(key => Object.hasOwn(item,key)) && keys.length >= layout.keys.length) {
79
+ let offset = layout.start;
80
+ for (const entry of layout.entries) {
81
+ append(layout.text.slice(offset,entry.start));
82
+ if (!entry.active || item[entry.key] === entry.value) append(layout.text.slice(entry.start,entry.end)); else visit(item[entry.key]);
83
+ offset = entry.end;
84
+ }
85
+ const written=new Set(layout.keys), added = keys.filter(key => !written.has(key));
86
+ if (added.length) {
87
+ if (!layout.entries.length) { append(layout.text.slice(offset,layout.start+1)); offset = layout.start+1; }
88
+ const first = layout.entries[0], last = layout.entries.at(-1);
89
+ const prefix = first ? layout.text.slice(layout.start+1,first.keyStart) : '';
90
+ const colon = first ? layout.text.slice(first.keyEnd,first.start) : ':';
91
+ const separator = layout.entries.length > 1 ? layout.text.slice(layout.entries[0].end,layout.entries[1].keyStart) : `,${prefix}`;
92
+ for (const key of added) { append(last || key !== added[0] ? separator : ''); append(JSON.stringify(key)); append(colon); visit(item[key]); }
93
+ }
94
+ append(layout.text.slice(offset,layout.end)); if (!collect) measured.set(item,size-initialSize); return;
95
+ }
96
+ const array = Array.isArray(item);
97
+ append(array ? '[' : '{');
98
+ keys.forEach((key,i) => { if (i) append(','); if (!array) { append(JSON.stringify(key)); append(':'); } visit(item[key]); });
99
+ append(array ? ']' : '}');
100
+ if (!collect) measured.set(item,size-initialSize);
101
+ }
102
+ visit(value);
103
+ return collect ? parts.join('') : size;
104
+ }
105
+ const encode = value => writeJson(value,{canonical:true});
106
+ const render = (value,tooBig) => writeJson(value,{tooBig});
107
+ const escape = key => key.replace(/~/g, '~0').replace(/\//g, '~1');
108
+ const fragment = title => title.toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s+/g, '-');
109
+ const INTERFACE = /<details\b[^>]*>\s*<summary\b[^>]*>\s*(?:<strong\b[^>]*>\s*)?Runtime\s+interface(?:\s*:\s*[^<]+?)?\s*(?:<\/strong\s*>\s*)?(?:\s*:\s*[^<]+?)?\s*<\/summary\s*>\s*```json\b\s*([\s\S]*?)\s*```\s*<\/details\s*>/gid;
110
+
111
+ function fail(code, consumer, target, detail, chain = []) {
112
+ const message = `${consumer}: ${target}: ${detail}${chain.length ? ` (${chain.join(' -> ')})` : ''}`;
113
+ throw Object.assign(new Error(message.slice(0, 4000)), { code });
114
+ }
115
+ function pointerTokens(pointer, invalid) {
116
+ if (pointer === '') return [];
117
+ if (typeof pointer !== 'string' || !pointer.startsWith('/') || /~(?:[^01]|$)/.test(pointer)) invalid();
118
+ return pointer.slice(1).split('/').map(key => key.replace(/~1/g, '/').replace(/~0/g, '~'));
119
+ }
120
+ function member(value, key) {
121
+ return (object(value) || Array.isArray(value)) && Object.hasOwn(value, key)
122
+ && (!Array.isArray(value) || /^(?:0|[1-9][0-9]*)$/.test(key));
123
+ }
124
+
125
+ // Headings and fences are recognized together: headings inside a fence are data.
126
+ function sections(text) {
127
+ const result = []; let section = null, fence = null;
128
+ for (const line of text.split(/\r?\n/)) {
129
+ const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
130
+ if (fence) {
131
+ if (marker && marker[1][0] === fence.char && marker[1].length >= fence.length && !marker[2].trim()) {
132
+ if (fence.json && section) section.blocks.push(fence.lines.join('\n'));
133
+ fence = null;
134
+ } else if (fence.json) fence.lines.push(line);
135
+ continue;
136
+ }
137
+ if (marker) { fence = { char: marker[1][0], length: marker[1].length, json: marker[2].trim() === 'json', lines: [] }; continue; }
138
+ const heading = /^ {0,3}(#{1,3})[ \t]+(.+?)[ \t]*$/.exec(line);
139
+ if (heading) heading[2] = heading[2].replace(/[ \t]+#+[ \t]*$/, '');
140
+ if (heading) {
141
+ section = heading[1].length === 3 ? { title: heading[2], blocks: [] } : null;
142
+ if (section) result.push(section);
143
+ }
144
+ }
145
+ return result;
146
+ }
147
+
148
+ function schemaSlots(document, visit) {
149
+ if (!object(document)) return;
150
+ const entries = Array.isArray(document.entries) ? document.entries : [];
151
+ entries.forEach((entry, i) => { if (object(entry)) for (const key of ['input_schema','result_schema']) if (Object.hasOwn(entry, key)) put(entry, key, visit(entry[key], `/entries/${i}/${key}`)); });
152
+ const resources = Array.isArray(document.resources) ? document.resources : [];
153
+ resources.forEach((resource, i) => {
154
+ (Array.isArray(resource?.operations) ? resource.operations : []).forEach((operation, j) => {
155
+ if (object(operation)) for (const key of ['arguments_schema','result_schema']) if (Object.hasOwn(operation, key)) put(operation, key, visit(operation[key], `/resources/${i}/operations/${j}/${key}`));
156
+ });
157
+ });
158
+ }
159
+ function schemaChildren(value, pointer, visit) {
160
+ if (!object(value)) return value;
161
+ if (object(value.properties)) for (const key of Object.keys(value.properties)) put(value.properties, key, visit(value.properties[key], `${pointer}/properties/${escape(key)}`));
162
+ if (Object.hasOwn(value, 'items')) put(value, 'items', visit(value.items, `${pointer}/items`));
163
+ if (Array.isArray(value.oneOf)) {
164
+ const variants=shallow(value.oneOf);
165
+ value.oneOf.forEach((child,i)=>put(variants,String(i),visit(child,`${pointer}/oneOf/${i}`)));
166
+ put(value,'oneOf',variants);
167
+ }
168
+ return value;
169
+ }
170
+
171
+ export function expandSource(input, files) {
172
+ return expand(input, files, new Map());
173
+ }
174
+ function expand({ path: consumer, text, format }, files, documents) {
175
+ const references = new Map(), expandedTargets = new Map(), collectors = [];
176
+ const error = (code, target, detail, chain) => fail(code, consumer, target, detail, chain);
177
+ const tooBig = (target,chain = []) => error('contract-invalid',target,'expanded source is too big (limit 10485760 bytes)',chain);
178
+ const bounded = (value,target,chain = []) => writeJson(value,{collect:false,tooBig:()=>tooBig(target,chain)});
179
+ function load(path, requested, chain) {
180
+ if (documents.has(path)) return documents.get(path);
181
+ let stat, content;
182
+ try {
183
+ stat = files.stat({ path });
184
+ if (!stat?.exists) error('contract-missing', requested, `missing file ${path}`, chain);
185
+ if (stat.is_symlink) error('contract-unsafe', requested, 'symbolic link', chain);
186
+ if (stat.size > LIMIT) tooBig(requested,chain);
187
+ content = files.read({ path }).content;
188
+ if (typeof content !== 'string') throw new Error('Invalid content');
189
+ } catch (cause) {
190
+ if(cause?.code==='workspace-path-outside')error('workspace-path-outside',requested,cause.message,chain);
191
+ if (typeof cause?.code==='string' && cause.code.startsWith('contract-')) throw cause;
192
+ error('contract-unsafe', requested, `cannot safely read ${path}`, chain);
193
+ }
194
+ const document = {content};
195
+ documents.set(path, document);
196
+ return document;
197
+ }
198
+ function target(requested, kind, chain) {
199
+ if (typeof requested !== 'string') error(kind === 'seed' ? 'seed-invalid' : 'contract-invalid', String(requested), 'reference must be a string', chain);
200
+ const hash = requested.indexOf('#'), path = hash < 0 ? requested : requested.slice(0, hash), selection = hash < 0 ? '' : requested.slice(hash + 1);
201
+ if (!path || /^[~/]|^[a-z][a-z0-9+.-]*:/i.test(path) || /[\\\x00-\x1f\x7f]/.test(path) || path.split('/').some(part => !part || part === '.' || part === '..')) error('contract-unsafe', requested, 'use a safe repository-root path', chain);
202
+ if (kind === 'seed' && (hash >= 0 || !path.endsWith('.json'))) error('seed-invalid', requested, 'seed must name a JSON file without a fragment', chain);
203
+ const loaded = load(path, requested, chain), {content} = loaded;
204
+ let value, canonical;
205
+ if (path.endsWith('.md') && kind !== 'seed') {
206
+ const matches = sections(content).filter(section => section.title === selection || fragment(section.title) === selection);
207
+ if (!matches.length) error('contract-missing', requested, `no ### ${selection}`, chain);
208
+ if (matches.length !== 1) error('contract-ambiguous', requested, `ambiguous heading ${selection}`, chain);
209
+ if (!matches[0].blocks.length) error('contract-missing', requested, `no JSON record under ### ${selection}`, chain);
210
+ if (matches[0].blocks.length !== 1) error('contract-invalid', requested, 'record needs exactly one JSON block', chain);
211
+ try { value = parse(matches[0].blocks[0]); } catch { error('contract-invalid', requested, 'record contains invalid JSON', chain); }
212
+ canonical = `${path}#${matches[0].title}`;
213
+ } else if (path.endsWith('.json')) {
214
+ if (!loaded.parsed) { loaded.parsed = true; try { loaded.value = parse(content); } catch { loaded.invalid = true; } }
215
+ if (loaded.invalid) error('contract-invalid', requested, 'file contains invalid JSON', chain);
216
+ value = loaded.value;
217
+ const tokens = pointerTokens(selection, () => error('contract-invalid', requested, 'invalid JSON Pointer', chain));
218
+ for (const key of tokens) {
219
+ if (!member(value, key)) error('contract-missing', requested, `missing JSON Pointer ${selection}`, chain);
220
+ value = value[key];
221
+ }
222
+ canonical = `${path}#${tokens.length ? `/${tokens.map(escape).join('/')}` : ''}`;
223
+ } else error('contract-invalid', requested, 'target must be Markdown or JSON', chain);
224
+ if (!object(value)) error(kind === 'seed' ? 'seed-invalid' : 'contract-invalid', requested, 'selected value must be an object', chain);
225
+ if (chain.includes(canonical)) error('contract-cycle', requested, 'reference cycle', [...chain, canonical]);
226
+ return { value, canonical };
227
+ }
228
+ function record(pointer, canonical, kind, value) {
229
+ for (const collector of collectors) collector.set(`${kind}:${canonical}`,{canonical,kind,value});
230
+ if (references.has(JSON.stringify([consumer,pointer,canonical,kind]))) return;
231
+ const ref = { consumer, source_pointer: pointer, target: canonical, kind, value_json: writeJson(value,{canonical:true,tooBig:()=>tooBig(canonical)}) };
232
+ references.set(JSON.stringify([consumer,pointer,canonical,kind]), ref);
233
+ }
234
+ function schema(value, pointer, chain = [], originating = null) {
235
+ if (!object(value)) return value;
236
+ if (Object.hasOwn(value, '$contract')) {
237
+ if (typeof value.$contract !== 'string' || Object.keys(value).some(key => !['$contract','title','description'].includes(key)) || ['title','description'].some(key => Object.hasOwn(value,key) && typeof value[key] !== 'string')) error('contract-invalid', String(value.$contract), 'only string title and description may accompany $contract', chain);
238
+ const origin = originating ?? pointer, { value: selected, canonical } = target(value.$contract, 'contract', chain);
239
+ let cached = expandedTargets.get(canonical);
240
+ if (!cached) {
241
+ const dependencies = new Map(); collectors.push(dependencies);
242
+ let expanded;
243
+ try { expanded = schema(selected, origin, [...chain, canonical], origin); } finally { collectors.pop(); }
244
+ bounded(expanded,canonical,chain);
245
+ cached = {expanded, dependencies:[...dependencies.values()]};
246
+ expandedTargets.set(canonical,cached);
247
+ } else for (const ref of cached.dependencies) record(origin,ref.canonical,ref.kind,ref.value);
248
+ record(origin, canonical, 'contract', cached.expanded);
249
+ const result = shallow(cached.expanded);
250
+ for (const key of keysOf(value)) if (['title','description'].includes(key)) put(result,key,value[key]);
251
+ bounded(result,canonical,chain);
252
+ return result;
253
+ }
254
+ const result = shallow(value);
255
+ if (object(value.properties)) put(result,'properties',shallow(value.properties));
256
+ schemaChildren(result, pointer, (child, childPointer) => schema(child, childPointer, chain, originating));
257
+ return result;
258
+ }
259
+ function seed(value, pointer, chain = []) {
260
+ if (!object(value) || !Object.hasOwn(value, '$seed')) return value;
261
+ if (typeof value.$seed !== 'string' || Object.keys(value).some(key => !['$seed','set'].includes(key)) || (Object.hasOwn(value,'set') && !object(value.set))) error('seed-invalid', String(value.$seed), 'invalid shared world or overrides', chain);
262
+ const { value: selected, canonical } = target(value.$seed, 'seed', chain);
263
+ let world = seed(selected, pointer, [...chain, canonical]);
264
+ record(pointer, canonical, 'seed', world);
265
+ bounded(world,canonical,chain);
266
+ world = clone(world);
267
+ for (const raw of keysOf(value.set ?? {})) {
268
+ const replacement = value.set[raw];
269
+ const invalid = () => error('seed-invalid', value.$seed, `invalid override pointer ${raw}`, chain);
270
+ const tokens = pointerTokens(raw, invalid);
271
+ if (!tokens.length) { if (!object(replacement)) invalid(); world = clone(replacement); continue; }
272
+ let parent = world;
273
+ for (const key of tokens.slice(0,-1)) { if (!member(parent,key)) invalid(); parent = parent[key]; }
274
+ const key = tokens.at(-1);
275
+ if (!object(parent) && !Array.isArray(parent)) invalid();
276
+ if (Array.isArray(parent) && !member(parent,key)) invalid();
277
+ put(parent, key, clone(replacement));
278
+ bounded(world,canonical,chain);
279
+ }
280
+ return world;
281
+ }
282
+ function simulation(requested, pointer, chain = []) {
283
+ const { value, canonical } = target(requested, 'simulation', chain);
284
+ let result;
285
+ if (Object.hasOwn(value, '$simulation')) {
286
+ if (Object.keys(value).some(key => !['$simulation','simulation'].includes(key)) ||
287
+ (Object.hasOwn(value, 'simulation') && !object(value.simulation)))
288
+ error('contract-invalid', String(requested), `${pointer}: invalid simulation wrapper`, chain);
289
+ result = simulation(value.$simulation, pointer, [...chain, canonical]);
290
+ result = shallow(result);
291
+ for (const key of keysOf(value.simulation ?? {})) put(result, key, value.simulation[key]);
292
+ } else result = clone(value);
293
+ bounded(result, canonical, chain);
294
+ record(pointer, canonical, 'simulation', result);
295
+ return result;
296
+ }
297
+ let document, block;
298
+ if (format === 'prompt') {
299
+ const blocks = [...text.matchAll(INTERFACE)];
300
+ if (blocks.length !== 1) return { text, references: [] };
301
+ block = blocks[0];
302
+ try { document = clone(parse(block[1])); } catch { return { text, references: [] }; }
303
+ schemaSlots(document, (value,pointer) => schema(value,pointer));
304
+ } else {
305
+ try { document = clone(parse(text)); } catch { return { text, references: [] }; }
306
+ if (format === 'json-schema') document = schema(document, '');
307
+ else if (format === 'scenario' && object(document)) {
308
+ if (Object.hasOwn(document, '$simulation')) {
309
+ const pointer = '/$simulation';
310
+ let merged;
311
+ try {
312
+ if (Object.hasOwn(document, 'simulation') && !object(document.simulation))
313
+ error('contract-invalid', String(document.$simulation), `${pointer}: simulation must be an object`);
314
+ merged = simulation(document.$simulation, pointer);
315
+ merged = shallow(merged);
316
+ for (const key of keysOf(document.simulation ?? {})) put(merged, key, document.simulation[key]);
317
+ bounded(merged, String(document.$simulation));
318
+ } catch (cause) {
319
+ if (cause instanceof Error && !cause.message.includes(pointer)) cause.message = `${consumer}: ${pointer}: ${cause.message}`.slice(0,4000);
320
+ throw cause;
321
+ }
322
+ // Re-index the enclosing layout after removing or renaming the reference member.
323
+ const layout = layouts.get(document), entries = layout.entries;
324
+ const keep = Object.hasOwn(document, 'simulation') ? null : entries.find(item => item.key === '$simulation' && item.active);
325
+ const edits = [];
326
+ if (keep) edits.push({start:keep.keyStart,end:keep.keyEnd,text:'"simulation"'});
327
+ for (let i = 0; i < entries.length;) {
328
+ if (entries[i].key !== '$simulation' || entries[i] === keep) { i++; continue; }
329
+ const first = i;
330
+ while (i + 1 < entries.length && entries[i + 1].key === '$simulation' && entries[i + 1] !== keep) i++;
331
+ if (i + 1 < entries.length) edits.push({start:entries[first].keyStart,end:entries[i + 1].keyStart,text:''});
332
+ else edits.push({start:entries[first - 1].end,end:entries[i].end,text:''});
333
+ i++;
334
+ }
335
+ let revised = text;
336
+ for (const edit of edits.sort((a,b)=>b.start-a.start)) revised = revised.slice(0,edit.start) + edit.text + revised.slice(edit.end);
337
+ document = clone(parse(revised));
338
+ put(document, 'simulation', merged);
339
+ }
340
+ if (Object.hasOwn(document, 'initial_world')) put(document,'initial_world',seed(document.initial_world, '/initial_world'));
341
+ }
342
+ }
343
+ if (!references.size) return { text, references: [] };
344
+ const result = render(document,()=>tooBig([...references.values()].at(-1).target));
345
+ const outsideSize = block ? Buffer.byteLength(text.slice(0,block.indices[1][0])) + Buffer.byteLength(text.slice(block.indices[1][1])) : Buffer.byteLength(text) - Buffer.byteLength(text.trim());
346
+ if (outsideSize + Buffer.byteLength(result) > LIMIT) tooBig([...references.values()].at(-1).target);
347
+ const effective = block ? `${text.slice(0,block.indices[1][0])}${result}${text.slice(block.indices[1][1])}` : `${text.slice(0,text.search(/\S/))}${result}${text.slice(text.trimEnd().length)}`;
348
+ if (Buffer.byteLength(effective) > LIMIT) tooBig([...references.values()].at(-1).target);
349
+ return { text: effective, references: [...references.values()].sort((a,b) => {
350
+ for (const key of ['consumer','source_pointer','target','kind']) { if (a[key] !== b[key]) return a[key] < b[key] ? -1 : 1; }
351
+ return 0;
352
+ }) };
353
+ }
354
+
355
+ export function catalogRecords(sources, targets = []) {
356
+ const map = new Map(sources.map(source => [source.path, source.text])), records = [], warnings = [], documents = new Map();
357
+ const files = { stat: ({path}) => ({ exists: map.has(path), is_symlink: false, size: Buffer.byteLength(map.get(path) ?? '') }), read: ({path}) => ({ content: map.get(path) }) };
358
+ const candidates = new Set(targets);
359
+ for (const {path,text} of sources) {
360
+ if (path.endsWith('.md')) for (const section of sections(text)) if (section.blocks.length) candidates.add(`${path}#${section.title}`);
361
+ if (path.endsWith('.json')) {
362
+ try {
363
+ const root = parse(text);
364
+ documents.set(path,{content:text,value:root,parsed:true});
365
+ if (object(root)) candidates.add(`${path}#`);
366
+ const walk = (value, pointer) => {
367
+ if (object(value) && object(value.properties)) candidates.add(`${path}#${pointer}`);
368
+ if (object(value) || Array.isArray(value)) for (const [key,child] of Object.entries(value)) walk(child, `${pointer}/${escape(key)}`);
369
+ };
370
+ walk(root,'');
371
+ } catch { documents.set(path,{content:text,parsed:true,invalid:true}); warnings.push(`${path}: invalid JSON contract`); }
372
+ }
373
+ }
374
+ for (const target of [...candidates].sort()) {
375
+ try {
376
+ const path = target.split('#')[0];
377
+ if (target === `${path}#` && path.endsWith('.json') && object(documents.get(path)?.value) && Object.hasOwn(documents.get(path).value, '$seed')) {
378
+ const expanded = expand({ path, text: JSON.stringify({ initial_world: { $seed:path } }), format:'scenario' }, files, documents);
379
+ records.push({path,target,value_json:encode(parse(expanded.text).initial_world)});
380
+ continue;
381
+ }
382
+ const expanded = expand({ path: target.split('#')[0], text: JSON.stringify({$contract:target}), format: 'json-schema' }, files, documents);
383
+ const own = expanded.references.find(ref => ref.target === target) ?? expanded.references.find(ref => ref.source_pointer === '' && ref.kind === 'contract');
384
+ if (own && !records.some(record => record.target === own.target)) records.push({ path: own.target.split('#')[0], target: own.target, value_json: own.value_json });
385
+ } catch (error) { warnings.push(error.message); }
386
+ }
387
+ return { records: records.sort((a,b) => a.target < b.target ? -1 : a.target > b.target ? 1 : 0), warnings };
388
+ }
389
+
390
+ function numericIdentity(text) {
391
+ const [,sign,whole,fraction = '',exponent = '0'] = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(text);
392
+ let digits = `${whole}${fraction}`.replace(/^0+/, '');
393
+ if (!digits) return '0';
394
+ const trailing = /0*$/.exec(digits)[0].length;
395
+ digits = digits.slice(0, digits.length - trailing);
396
+ return `${sign}${digits}e${BigInt(exponent) - BigInt(fraction.length) + BigInt(trailing)}`;
397
+ }
398
+ function identity(value) {
399
+ if (value instanceof JsonNumber) return `n:${numericIdentity(value.text)}`;
400
+ if (Array.isArray(value)) return `[${value.map(identity).join(',')}]`;
401
+ if (object(value)) return `{${Object.keys(value).sort().map(key=>`${JSON.stringify(key)}:${identity(value[key])}`).join(',')}}`;
402
+ return JSON.stringify(value);
403
+ }
404
+ function differences(a,b,pointer = '', root = true, schema = true, unordered = false) {
405
+ if (a instanceof JsonNumber && b instanceof JsonNumber) return numericIdentity(a.text) === numericIdentity(b.text) ? [] : [`${pointer}: ${a.text} -> ${b.text}`];
406
+ if (object(a) && object(b)) return [...new Set([...Object.keys(a),...Object.keys(b)])].sort().flatMap(key => {
407
+ if (root && ['title','description'].includes(key)) return [];
408
+ const path = `${pointer}/${escape(key)}`;
409
+ if (!Object.hasOwn(a,key)) return [`${path}: missing in copy`];
410
+ if (!Object.hasOwn(b,key)) return [`${path}: extra in copy`];
411
+ if (schema && key === 'properties' && object(a[key]) && object(b[key])) {
412
+ return [...new Set([...Object.keys(a[key]),...Object.keys(b[key])])].sort().flatMap(name => {
413
+ const nested = `${path}/${escape(name)}`;
414
+ if (!Object.hasOwn(a[key],name)) return [`${nested}: missing in copy`];
415
+ if (!Object.hasOwn(b[key],name)) return [`${nested}: extra in copy`];
416
+ return differences(a[key][name],b[key][name],nested,false,true);
417
+ });
418
+ }
419
+ return differences(a[key],b[key],path,false,schema && ['items','oneOf'].includes(key),schema && ['required','enum'].includes(key));
420
+ });
421
+ if (Array.isArray(a) && Array.isArray(b)) {
422
+ if (unordered) return a.map(identity).sort().join('\n') === b.map(identity).sort().join('\n') ? [] : [`${pointer}: ${encode(a)} -> ${encode(b)}`];
423
+ return a.length !== b.length ? [`${pointer}: ${encode(a)} -> ${encode(b)}`] : a.flatMap((child,i) => differences(child,b[i],`${pointer}/${i}`,false,schema));
424
+ }
425
+ return encode(a) === encode(b) ? [] : [`${pointer}: ${encode(a)} -> ${encode(b)}`];
426
+ }
427
+ export function compareCopies(sources, records) {
428
+ const matches = [], warnings = [], candidates = [], nested = new Map();
429
+ const collectSchema = (value, top = false) => {
430
+ if (!object(value) || Object.hasOwn(value, '$contract') || Object.hasOwn(value, '$seed')) return;
431
+ if (value.type === 'object' && object(value.properties)) {
432
+ if (!top && Object.keys(value.properties).length >= 3) {
433
+ const signature = JSON.stringify(Object.keys(value.properties).sort());
434
+ nested.set(signature, [...(nested.get(signature) ?? []), value]);
435
+ }
436
+ for (const key of Object.keys(value.properties)) collectSchema(value.properties[key]);
437
+ }
438
+ if (value.type === 'array' && object(value.items)) collectSchema(value.items);
439
+ if (Array.isArray(value.oneOf)) for (const variant of value.oneOf) collectSchema(variant);
440
+ };
441
+ for (const record of records) {
442
+ let value;
443
+ try { value = parse(record.value_json); } catch { continue; }
444
+ if (!object(value) || Object.hasOwn(value, '$seed')) continue;
445
+ if (value.type === 'object' && object(value.properties)) candidates.push({ ...record, value });
446
+ collectSchema(value, true);
447
+ if (Array.isArray(value.entries) || Array.isArray(value.resources)) schemaSlots(value, slot => { collectSchema(slot); return slot; });
448
+ }
449
+ for (const {path,text} of sources) {
450
+ const blocks = [...text.matchAll(INTERFACE)];
451
+ if (blocks.length !== 1) continue;
452
+ let document; try { document = parse(blocks[0][1]); } catch { continue; }
453
+ const visit = (value,pointer) => {
454
+ if (!object(value) || Object.hasOwn(value,'$contract')) return value;
455
+ if (value.type==='object' && object(value.properties) && Object.keys(value.properties).length >= 3) {
456
+ const keys = new Set(Object.keys(value.properties));
457
+ const options = candidates.filter(record => {
458
+ const other = new Set(Object.keys(record.value.properties));
459
+ return [...keys].filter(key => !other.has(key)).length + [...other].filter(key => !keys.has(key)).length <= 1;
460
+ }).map(record => ({ record, differences: differences(value,record.value) })).filter(option => !option.differences.length || Object.keys(option.record.value.properties).length >= 4);
461
+ const exact = options.filter(option => !option.differences.length);
462
+ if (exact.length === 1) { matches.push({ path, source_pointer:pointer, target:exact[0].record.target, kind:'exact', differences:[] }); return value; }
463
+ if (exact.length > 1) { warnings.push(`${path} ${pointer}: ambiguous contract copies (${exact.map(option => option.record.target).join(', ')})`); return value; }
464
+ if ((nested.get(JSON.stringify([...keys].sort())) ?? []).some(schema => !differences(value,schema).length)) return value;
465
+ if (options.length === 1) matches.push({ path, source_pointer:pointer, target:options[0].record.target, kind:'near', differences:options[0].differences });
466
+ else if (options.length > 1) warnings.push(`${path} ${pointer}: ambiguous contract copies (${options.map(option => option.record.target).join(', ')})`);
467
+ }
468
+ return schemaChildren(value,pointer,visit);
469
+ };
470
+ schemaSlots(document,visit);
471
+ }
472
+ return { matches, warnings };
473
+ }
474
+ export function planSync(sources, matches) {
475
+ const edits = [], warnings = [];
476
+ for (const {path,text} of sources) {
477
+ const selected = matches.filter(match => match.path === path).sort((a,b) => a.source_pointer.length - b.source_pointer.length);
478
+ if (!selected.length) continue;
479
+ const blocks = [...text.matchAll(INTERFACE)]; if (blocks.length !== 1) continue;
480
+ const block = blocks[0]; let document;
481
+ try { document = clone(parse(block[1])); } catch { continue; }
482
+ const replaced = [];
483
+ for (const match of selected) {
484
+ if (replaced.some(parent => match.source_pointer.startsWith(`${parent}/`))) continue;
485
+ const tokens = pointerTokens(match.source_pointer, () => fail('contract-invalid',path,match.target,'invalid schema location'));
486
+ let parent = document;
487
+ for (const key of tokens.slice(0,-1)) { if (!member(parent,key)) { parent = null; break; } parent = parent[key]; }
488
+ const key = tokens.at(-1), value = parent?.[key];
489
+ if (!object(value) || Object.hasOwn(value,'$contract')) continue;
490
+ const reference = { $contract: match.target };
491
+ for (const annotation of keysOf(value).filter(key=>['title','description'].includes(key))) put(reference,annotation,clone(value[annotation]));
492
+ const layout = layouts.get(value);
493
+ if (layout) {
494
+ const entries = layout.entries, first = entries[0];
495
+ const prefix = first ? layout.text.slice(layout.start+1,first.keyStart) : '';
496
+ const colon = first ? layout.text.slice(first.keyEnd,first.start) : ':';
497
+ const separator = entries.length>1 ? layout.text.slice(entries[0].end,entries[1].keyStart) : `,${prefix}`;
498
+ const suffix = entries.length ? layout.text.slice(entries.at(-1).end,layout.end-1) : '';
499
+ const rendered = `{${prefix}${keysOf(reference).map(key=>`${JSON.stringify(key)}${colon}${render(reference[key])}`).join(separator)}${suffix}}`;
500
+ put(parent,key,parse(rendered));
501
+ } else put(parent,key,reference); replaced.push(match.source_pointer);
502
+ }
503
+ if (!replaced.length) continue;
504
+ if (document.status === 'approved') document.status = 'draft';
505
+ const after = `${text.slice(0,block.indices[1][0])}${render(document)}${text.slice(block.indices[1][1])}`;
506
+ if (after !== text) edits.push({path,before:text,after});
507
+ }
508
+ return { edits, warnings };
509
+ }
510
+
511
+ // Public codec shares the exact token representation and bounded serializer above.
512
+ export const parseJsonValue = text => parse(text);
513
+ export const stringifyJsonValue = value => encode(value);
514
+ export const isJsonNumber = value => value instanceof JsonNumber;
515
+ export function jsonNumberIdentity(value) {
516
+ if (value instanceof JsonNumber) return numericIdentity(value.text);
517
+ if (typeof value !== 'number' || !Number.isFinite(value)) throw new TypeError('Expected a finite JSON number.');
518
+ return numericIdentity(JSON.stringify(value));
519
+ }