toolsplice 0.0.0-stage → 0.0.2

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 (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +104 -2
  3. package/dist/abortable.d.ts +6 -0
  4. package/dist/abortable.js +50 -0
  5. package/dist/adaptive-read.d.ts +50 -0
  6. package/dist/adaptive-read.js +780 -0
  7. package/dist/answer-wait.d.ts +7 -0
  8. package/dist/answer-wait.js +45 -0
  9. package/dist/cache-reads.d.ts +18 -0
  10. package/dist/cache-reads.js +89 -0
  11. package/dist/calibration-ledger.d.ts +37 -0
  12. package/dist/calibration-ledger.js +148 -0
  13. package/dist/calibration-marker.d.ts +4 -0
  14. package/dist/calibration-marker.js +77 -0
  15. package/dist/catalog-setup.d.ts +33 -0
  16. package/dist/catalog-setup.js +89 -0
  17. package/dist/catalog.d.ts +10 -0
  18. package/dist/catalog.js +42 -0
  19. package/dist/checkpoint-files.d.ts +15 -0
  20. package/dist/checkpoint-files.js +99 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +1454 -0
  23. package/dist/coalesce-reads.d.ts +6 -0
  24. package/dist/coalesce-reads.js +33 -0
  25. package/dist/codegen.d.ts +44 -0
  26. package/dist/codegen.js +479 -0
  27. package/dist/contract-caller.d.ts +23 -0
  28. package/dist/contract-caller.js +326 -0
  29. package/dist/contract-corrections.d.ts +35 -0
  30. package/dist/contract-corrections.js +159 -0
  31. package/dist/contract-schema.d.ts +7 -0
  32. package/dist/contract-schema.js +156 -0
  33. package/dist/contracts.d.ts +72 -0
  34. package/dist/contracts.js +370 -0
  35. package/dist/core.d.ts +44 -0
  36. package/dist/core.js +43 -0
  37. package/dist/db-final-answer.d.ts +9 -0
  38. package/dist/db-final-answer.js +62 -0
  39. package/dist/define.d.ts +78 -0
  40. package/dist/define.js +14 -0
  41. package/dist/doctor.d.ts +22 -0
  42. package/dist/doctor.js +91 -0
  43. package/dist/drift.d.ts +23 -0
  44. package/dist/drift.js +111 -0
  45. package/dist/execution.d.ts +38 -0
  46. package/dist/execution.js +66 -0
  47. package/dist/extract.d.ts +34 -0
  48. package/dist/extract.js +73 -0
  49. package/dist/final-answer-stores.d.ts +71 -0
  50. package/dist/final-answer-stores.js +72 -0
  51. package/dist/final-answer.d.ts +32 -0
  52. package/dist/final-answer.js +104 -0
  53. package/dist/impact.d.ts +48 -0
  54. package/dist/impact.js +71 -0
  55. package/dist/index.d.ts +51 -0
  56. package/dist/index.js +47 -0
  57. package/dist/local-tool.d.ts +18 -0
  58. package/dist/local-tool.js +32 -0
  59. package/dist/mcp-apps.d.ts +53 -0
  60. package/dist/mcp-apps.js +32 -0
  61. package/dist/mcp-event-delivery.d.ts +98 -0
  62. package/dist/mcp-event-delivery.js +211 -0
  63. package/dist/mcp-extensions.d.ts +46 -0
  64. package/dist/mcp-extensions.js +200 -0
  65. package/dist/mcp-peer.d.ts +45 -0
  66. package/dist/mcp-peer.js +207 -0
  67. package/dist/mcp-server-card.d.ts +21 -0
  68. package/dist/mcp-server-card.js +54 -0
  69. package/dist/ordered-transport.d.ts +12 -0
  70. package/dist/ordered-transport.js +106 -0
  71. package/dist/page-checkpoint.d.ts +71 -0
  72. package/dist/page-checkpoint.js +286 -0
  73. package/dist/page-read-gate.d.ts +15 -0
  74. package/dist/page-read-gate.js +48 -0
  75. package/dist/pattern.d.ts +3 -0
  76. package/dist/pattern.js +54 -0
  77. package/dist/postgres.d.ts +41 -0
  78. package/dist/postgres.js +264 -0
  79. package/dist/probe.d.ts +29 -0
  80. package/dist/probe.js +121 -0
  81. package/dist/proxy.d.ts +40 -0
  82. package/dist/proxy.js +436 -0
  83. package/dist/read-pages.d.ts +25 -0
  84. package/dist/read-pages.js +85 -0
  85. package/dist/read-policy.d.ts +6 -0
  86. package/dist/read-policy.js +16 -0
  87. package/dist/read-steps.d.ts +12 -0
  88. package/dist/read-steps.js +36 -0
  89. package/dist/result-session.d.ts +109 -0
  90. package/dist/result-session.js +620 -0
  91. package/dist/route-checkpoint.d.ts +3 -0
  92. package/dist/route-checkpoint.js +80 -0
  93. package/dist/route-driver-cli.d.ts +3 -0
  94. package/dist/route-driver-cli.js +43 -0
  95. package/dist/route-evaluation.d.ts +141 -0
  96. package/dist/route-evaluation.js +329 -0
  97. package/dist/row-groups.d.ts +17 -0
  98. package/dist/row-groups.js +79 -0
  99. package/dist/row-query.d.ts +62 -0
  100. package/dist/row-query.js +172 -0
  101. package/dist/rules.d.ts +30 -0
  102. package/dist/rules.js +72 -0
  103. package/dist/run-diagnostics.d.ts +75 -0
  104. package/dist/run-diagnostics.js +212 -0
  105. package/dist/runtime.d.ts +6 -0
  106. package/dist/runtime.js +26 -0
  107. package/dist/schema.d.ts +17 -0
  108. package/dist/schema.js +299 -0
  109. package/dist/search-fetch.d.ts +50 -0
  110. package/dist/search-fetch.js +264 -0
  111. package/dist/shape.d.ts +91 -0
  112. package/dist/shape.js +499 -0
  113. package/dist/skill-files.d.ts +9 -0
  114. package/dist/skill-files.js +49 -0
  115. package/dist/splice-diagnostics.d.ts +44 -0
  116. package/dist/splice-diagnostics.js +88 -0
  117. package/dist/splice-measure.d.ts +33 -0
  118. package/dist/splice-measure.js +55 -0
  119. package/dist/splice-project.d.ts +125 -0
  120. package/dist/splice-project.js +348 -0
  121. package/dist/splice-recording.d.ts +132 -0
  122. package/dist/splice-recording.js +481 -0
  123. package/dist/splice.d.ts +181 -0
  124. package/dist/splice.js +1263 -0
  125. package/dist/sqlite-checkpoint-store.d.ts +5 -0
  126. package/dist/sqlite-checkpoint-store.js +91 -0
  127. package/dist/sqlite-checkpoint-worker.d.ts +1 -0
  128. package/dist/sqlite-checkpoint-worker.js +115 -0
  129. package/dist/storage.d.ts +17 -0
  130. package/dist/storage.js +1 -0
  131. package/dist/store.d.ts +151 -0
  132. package/dist/store.js +735 -0
  133. package/dist/test-difference.d.ts +13 -0
  134. package/dist/test-difference.js +42 -0
  135. package/dist/testing.d.ts +122 -0
  136. package/dist/testing.js +261 -0
  137. package/dist/text-pages.d.ts +24 -0
  138. package/dist/text-pages.js +36 -0
  139. package/dist/tool-discovery.d.ts +59 -0
  140. package/dist/tool-discovery.js +136 -0
  141. package/dist/unevaluated.d.ts +7 -0
  142. package/dist/unevaluated.js +156 -0
  143. package/dist/v2.d.ts +49 -0
  144. package/dist/v2.js +413 -0
  145. package/dist/validate-output.d.ts +3 -0
  146. package/dist/validate-output.js +73 -0
  147. package/dist/version.d.ts +1 -0
  148. package/dist/version.js +1 -0
  149. package/dist/workflow-json.d.ts +8 -0
  150. package/dist/workflow-json.js +74 -0
  151. package/docs/AGENT-FRAMEWORKS.md +431 -0
  152. package/docs/BENCHMARKS.md +43 -0
  153. package/docs/INTEGRATION-QUICKSTART.md +859 -0
  154. package/docs/LEARNING-AND-STORAGE.md +393 -0
  155. package/docs/MCP.md +204 -0
  156. package/docs/PROJECTS-AND-UPGRADES.md +173 -0
  157. package/docs/PYTHON-REFERENCE.md +348 -0
  158. package/docs/PYTHON.md +120 -0
  159. package/docs/RECORDING-AND-CORRECTIONS.md +205 -0
  160. package/docs/TESTING.md +259 -0
  161. package/examples/mcp-app/build.mjs +11 -0
  162. package/examples/mcp-app/view.mjs +22 -0
  163. package/examples/quickstart.mjs +43 -0
  164. package/examples/route-driver.mjs +67 -0
  165. package/integrations/ai.d.mts +36 -0
  166. package/integrations/ai.mjs +178 -0
  167. package/integrations/call-options.mjs +9 -0
  168. package/integrations/langchain.d.mts +31 -0
  169. package/integrations/langchain.mjs +114 -0
  170. package/integrations/managed.mjs +154 -0
  171. package/integrations/types.d.mts +13 -0
  172. package/package.json +139 -4
@@ -0,0 +1,132 @@
1
+ import { type ReadPolicy } from "./read-policy.js";
2
+ import type { ToolCaller } from "./execution.js";
3
+ import type { ToolResultLike } from "./extract.js";
4
+ import { type ContractSnapshot } from "./contracts.js";
5
+ import { SpliceError, type SpliceSpec, type SpliceRunOptions, type SpliceReadOptions } from "./splice.js";
6
+ interface RecordedCall {
7
+ side: "source" | "target";
8
+ name: string;
9
+ outcome: "returned" | "threw";
10
+ durationMs: number;
11
+ arguments?: Record<string, unknown>;
12
+ result?: ToolResultLike;
13
+ }
14
+ type RecordedOutcome = {
15
+ status: "succeeded";
16
+ resultFingerprint?: string;
17
+ } | {
18
+ status: "failed";
19
+ stage: SpliceError["stage"] | "unknown";
20
+ completedTargets: number;
21
+ issues: {
22
+ code: string;
23
+ path: string;
24
+ }[];
25
+ };
26
+ export interface SpliceRecording {
27
+ format: "toolsplice-recording";
28
+ formatVersion: 1;
29
+ createdAt: string;
30
+ toolspliceVersion: string;
31
+ capture: "metadata" | "payloads";
32
+ complete: boolean;
33
+ planFingerprint: string;
34
+ plan?: SpliceSpec;
35
+ sourceContract?: ContractSnapshot;
36
+ targetContract?: ContractSnapshot;
37
+ input?: unknown;
38
+ context?: unknown;
39
+ allowReview: boolean;
40
+ readPolicy?: ReadPolicy;
41
+ cancellationObserved: boolean;
42
+ calls: RecordedCall[];
43
+ outcome: RecordedOutcome;
44
+ diagnostics: string[];
45
+ redactions: string[];
46
+ fingerprint: string;
47
+ }
48
+ export interface SpliceRecordingOptions {
49
+ /** Metadata is the default; payloads explicitly opt in to retaining inputs and results. */
50
+ capture?: "metadata" | "payloads";
51
+ /** Case-insensitive field names, in addition to common credential names. */
52
+ redactKeys?: string[];
53
+ /** Any string containing one of these values is wholly redacted. Values are never saved as policy. */
54
+ redactValues?: string[];
55
+ /** Serialized artifact cap, 1 KiB–5 MiB. Capture failures never retry or fail the workflow. */
56
+ maxBytes?: number;
57
+ }
58
+ export declare function createSpliceRecorder(plan: SpliceSpec, source: ContractSnapshot, target: ContractSnapshot, options?: SpliceRecordingOptions): {
59
+ report: import("./splice.js").SpliceReport;
60
+ run: (source: ToolCaller, target: ToolCaller, input: unknown, options?: SpliceRunOptions) => Promise<unknown[]>;
61
+ runReads: (source: ToolCaller, target: ToolCaller, input: unknown, options?: SpliceReadOptions) => Promise<unknown[]>;
62
+ snapshot: () => SpliceRecording;
63
+ };
64
+ export declare function parseSpliceRecording(input: unknown): SpliceRecording;
65
+ export interface SpliceReplayOptions {
66
+ restorations?: Record<string, unknown>;
67
+ /** Candidate contracts are checked against the saved calls; they never replace the recording. */
68
+ sourceContract?: ContractSnapshot;
69
+ targetContract?: ContractSnapshot;
70
+ /** Explicit policy override; otherwise the recorded review decision is retained. */
71
+ allowReview?: boolean;
72
+ }
73
+ /** Shared artifact loader for replay and explicit project scaffolding. No writes or connections. */
74
+ export declare function loadReplayFixture(input: SpliceRecording | string, options?: {
75
+ restorations?: Record<string, unknown>;
76
+ }): {
77
+ recording: SpliceRecording;
78
+ restored: boolean;
79
+ spec: SpliceSpec;
80
+ source: ContractSnapshot;
81
+ target: ContractSnapshot;
82
+ };
83
+ /** No live caller or connection can be supplied. Saved responses are consumed strictly in order. */
84
+ export declare function replaySpliceRecording(input: SpliceRecording | string, options?: SpliceReplayOptions): Promise<{
85
+ matched: boolean;
86
+ recordedOutcome: RecordedOutcome;
87
+ upgrade?: {
88
+ status: "failed" | "inconclusive" | "passed";
89
+ source: import("./contracts.js").ContractComparison;
90
+ target: import("./contracts.js").ContractComparison;
91
+ fingerprints: {
92
+ recordedSource: string;
93
+ candidateSource: string;
94
+ recordedTarget: string;
95
+ candidateTarget: string;
96
+ };
97
+ note: string;
98
+ } | undefined;
99
+ mode: "restored-fixture" | "saved-fixture";
100
+ networkCalls: 0;
101
+ consumedCalls: number;
102
+ recordedCalls: number;
103
+ outcome: RecordedOutcome;
104
+ result?: unknown[] | undefined;
105
+ explanation?: import("./splice-diagnostics.js").SpliceExplanation | undefined;
106
+ caveats: string[];
107
+ }>;
108
+ export declare function replayLoadedFixture(fixture: ReturnType<typeof loadReplayFixture>, options: SpliceReplayOptions): Promise<{
109
+ matched: boolean;
110
+ recordedOutcome: RecordedOutcome;
111
+ upgrade?: {
112
+ status: "failed" | "inconclusive" | "passed";
113
+ source: import("./contracts.js").ContractComparison;
114
+ target: import("./contracts.js").ContractComparison;
115
+ fingerprints: {
116
+ recordedSource: string;
117
+ candidateSource: string;
118
+ recordedTarget: string;
119
+ candidateTarget: string;
120
+ };
121
+ note: string;
122
+ } | undefined;
123
+ mode: "restored-fixture" | "saved-fixture";
124
+ networkCalls: 0;
125
+ consumedCalls: number;
126
+ recordedCalls: number;
127
+ outcome: RecordedOutcome;
128
+ result?: unknown[] | undefined;
129
+ explanation?: import("./splice-diagnostics.js").SpliceExplanation | undefined;
130
+ caveats: string[];
131
+ }>;
132
+ export {};
@@ -0,0 +1,481 @@
1
+ // Explicit one-run capture and network-free replay. This is not a durable job journal.
2
+ import { parseReadPolicy } from "./read-policy.js";
3
+ import { VERSION } from "./version.js";
4
+ import { parseContractSnapshot, selectContractTools, compareContractSnapshots, } from "./contracts.js";
5
+ import { prepareSplice, parseSpliceSpec, SpliceError, } from "./splice.js";
6
+ import { explainSpliceError } from "./splice-diagnostics.js";
7
+ import { copyJson, jsonFingerprint, jsonObject, JSON_LIMIT, parseWorkflowJson, escapePointer, pointerParts, replaceOwnPointer, } from "./workflow-json.js";
8
+ const CREDENTIAL_KEYS = [
9
+ "password",
10
+ "authorization",
11
+ "apikey",
12
+ "api_key",
13
+ "access_token",
14
+ "refresh_token",
15
+ "token",
16
+ "secret",
17
+ "client_secret",
18
+ ];
19
+ const MARKER = "__TOOLSPLICE_REDACTED__";
20
+ const hashRecording = (recording) => {
21
+ const { fingerprint: _fingerprint, ...body } = recording;
22
+ return jsonFingerprint(body);
23
+ };
24
+ export function createSpliceRecorder(plan, source, target, options = {}) {
25
+ const spec = parseSpliceSpec(plan), s = selectContractTools(source, [spec.source.tool]), t = selectContractTools(target, [spec.target.tool]);
26
+ const prepared = prepareSplice(spec, s, t), capture = options.capture ?? "metadata", maxBytes = options.maxBytes ?? JSON_LIMIT;
27
+ if (!["metadata", "payloads"].includes(capture) ||
28
+ !Number.isSafeInteger(maxBytes) ||
29
+ maxBytes < 1024 ||
30
+ maxBytes > JSON_LIMIT)
31
+ throw new Error("Invalid recording capture policy or byte limit.");
32
+ for (const values of [options.redactKeys, options.redactValues])
33
+ if (values !== undefined &&
34
+ (!Array.isArray(values) ||
35
+ values.length > 64 ||
36
+ values.some((v) => typeof v !== "string" || !v || v.length > 2048)))
37
+ throw new Error("Redaction policies require at most 64 bounded nonempty strings.");
38
+ const keys = new Set([
39
+ ...CREDENTIAL_KEYS,
40
+ ...(options.redactKeys ?? []).map((k) => k.toLowerCase()),
41
+ ]);
42
+ const secrets = [...(options.redactValues ?? [])];
43
+ let state = "new";
44
+ let capturedBytes = 0;
45
+ const recording = {
46
+ format: "toolsplice-recording",
47
+ formatVersion: 1,
48
+ createdAt: new Date().toISOString(),
49
+ toolspliceVersion: VERSION,
50
+ capture,
51
+ complete: true,
52
+ planFingerprint: jsonFingerprint(spec),
53
+ allowReview: false,
54
+ cancellationObserved: false,
55
+ calls: [],
56
+ outcome: {
57
+ status: "failed",
58
+ stage: "unknown",
59
+ completedTargets: 0,
60
+ issues: [],
61
+ },
62
+ diagnostics: [],
63
+ redactions: [],
64
+ fingerprint: "",
65
+ };
66
+ const captureValue = (value) => {
67
+ try {
68
+ const copy = copyJson(value, maxBytes);
69
+ capturedBytes += Buffer.byteLength(JSON.stringify(copy));
70
+ if (capturedBytes > maxBytes)
71
+ throw new Error("Capture budget exceeded.");
72
+ return copy;
73
+ }
74
+ catch {
75
+ recording.complete = false;
76
+ if (!recording.diagnostics.includes("payload-not-recorded"))
77
+ recording.diagnostics.push("payload-not-recorded");
78
+ return undefined;
79
+ }
80
+ };
81
+ const wrap = (side, caller) => async (request, callOptions) => {
82
+ const entry = {
83
+ side,
84
+ name: request.name,
85
+ outcome: "threw",
86
+ durationMs: 0,
87
+ };
88
+ if (capture === "payloads")
89
+ entry.arguments = captureValue(request.arguments);
90
+ recording.calls.push(entry);
91
+ const started = Date.now();
92
+ try {
93
+ const result = await caller(request, callOptions);
94
+ entry.outcome = "returned";
95
+ if (capture === "payloads")
96
+ entry.result = captureValue(result);
97
+ return result;
98
+ }
99
+ finally {
100
+ entry.durationMs = Math.max(0, Date.now() - started);
101
+ }
102
+ };
103
+ const captureRun = async (sourceCaller, targetCaller, input, runOptions, policy) => {
104
+ if (state !== "new")
105
+ throw new Error("A recorder captures one run; create another recorder for concurrent or subsequent runs.");
106
+ state = "running";
107
+ if (policy)
108
+ recording.readPolicy = policy;
109
+ recording.allowReview = runOptions.allowReview === true;
110
+ if (capture === "payloads") {
111
+ recording.plan = captureValue(spec);
112
+ recording.sourceContract = captureValue(s);
113
+ recording.targetContract = captureValue(t);
114
+ const saved = captureValue(input);
115
+ if (saved !== undefined)
116
+ recording.input = saved;
117
+ if (runOptions.context !== undefined) {
118
+ const context = captureValue(runOptions.context);
119
+ if (context !== undefined)
120
+ recording.context = context;
121
+ }
122
+ }
123
+ try {
124
+ const execute = policy ? prepared.runReads : prepared.run;
125
+ const result = await execute(wrap("source", sourceCaller), wrap("target", targetCaller), input, { ...runOptions, ...policy });
126
+ let resultFingerprint;
127
+ try {
128
+ resultFingerprint = jsonFingerprint(result);
129
+ }
130
+ catch {
131
+ recording.complete = false;
132
+ recording.diagnostics.push("payload-not-recorded");
133
+ }
134
+ recording.outcome = {
135
+ status: "succeeded",
136
+ ...(resultFingerprint === undefined ? {} : { resultFingerprint }),
137
+ };
138
+ return result;
139
+ }
140
+ catch (error) {
141
+ recording.outcome =
142
+ error instanceof SpliceError
143
+ ? {
144
+ status: "failed",
145
+ stage: error.stage,
146
+ completedTargets: error.completedTargets,
147
+ issues: error.issues.map((i) => ({ code: i.code, path: i.path })),
148
+ }
149
+ : {
150
+ status: "failed",
151
+ stage: "unknown",
152
+ completedTargets: 0,
153
+ issues: [],
154
+ };
155
+ throw error;
156
+ }
157
+ finally {
158
+ recording.cancellationObserved = runOptions.signal?.aborted ?? false;
159
+ state = "finished";
160
+ }
161
+ };
162
+ const snapshot = () => {
163
+ if (state !== "finished")
164
+ throw new Error("Recording is available only after the run settles.");
165
+ // Undefined capture fields are omitted; the raw caller result itself is never modified.
166
+ const detached = JSON.parse(JSON.stringify(recording));
167
+ const redactions = [];
168
+ const redact = (value, path) => {
169
+ if (typeof value === "string" &&
170
+ secrets.some((secret) => value.includes(secret))) {
171
+ redactions.push(path);
172
+ return MARKER;
173
+ }
174
+ if (Array.isArray(value))
175
+ return value.map((v, i) => redact(v, `${path}/${i}`));
176
+ if (!jsonObject(value))
177
+ return value;
178
+ if (Object.keys(value).some((key) => secrets.some((secret) => key.includes(secret)))) {
179
+ redactions.push(path);
180
+ return MARKER;
181
+ }
182
+ return Object.fromEntries(Object.entries(value).map(([key, v]) => {
183
+ const next = `${path}/${escapePointer(key)}`;
184
+ if (keys.has(key.toLowerCase())) {
185
+ redactions.push(next);
186
+ return [key, MARKER];
187
+ }
188
+ return [key, redact(v, next)];
189
+ }));
190
+ };
191
+ // Artifact structure is fixed; redact application-owned data, not envelope keys/diagnostic metadata.
192
+ for (const key of [
193
+ "plan",
194
+ "sourceContract",
195
+ "targetContract",
196
+ "input",
197
+ "context",
198
+ ])
199
+ if (Object.hasOwn(detached, key))
200
+ detached[key] = redact(detached[key], `/${key}`);
201
+ for (const [i, call] of detached.calls.entries())
202
+ for (const key of ["arguments", "result"])
203
+ if (Object.hasOwn(call, key))
204
+ call[key] = redact(call[key], `/calls/${i}/${key}`);
205
+ detached.redactions = redactions;
206
+ try {
207
+ copyJson(detached, maxBytes);
208
+ }
209
+ catch {
210
+ detached.complete = false;
211
+ detached.diagnostics.push("recording-byte-limit");
212
+ delete detached.plan;
213
+ delete detached.sourceContract;
214
+ delete detached.targetContract;
215
+ delete detached.input;
216
+ delete detached.context;
217
+ for (const call of detached.calls) {
218
+ delete call.arguments;
219
+ delete call.result;
220
+ }
221
+ detached.redactions = [];
222
+ }
223
+ detached.fingerprint = hashRecording(detached);
224
+ return copyJson(detached, maxBytes);
225
+ };
226
+ const run = (source, target, input, options = {}) => captureRun(source, target, input, options);
227
+ const runReads = async (source, target, input, options = {}) => {
228
+ const policy = parseReadPolicy({ concurrency: options.concurrency ?? 4, assumeReadOnly: options.assumeReadOnly ?? false });
229
+ return captureRun(source, target, input, options, policy);
230
+ };
231
+ return { report: prepared.report, run, runReads, snapshot };
232
+ }
233
+ export function parseSpliceRecording(input) {
234
+ const r = parseWorkflowJson(input);
235
+ const bad = () => {
236
+ throw new Error("Invalid or unsupported splice recording.");
237
+ };
238
+ if (!jsonObject(r) ||
239
+ r.format !== "toolsplice-recording" ||
240
+ r.formatVersion !== 1 ||
241
+ typeof r.createdAt !== "string" ||
242
+ !Number.isFinite(Date.parse(r.createdAt)) ||
243
+ typeof r.toolspliceVersion !== "string" ||
244
+ !r.toolspliceVersion ||
245
+ !["metadata", "payloads"].includes(String(r.capture)) ||
246
+ typeof r.complete !== "boolean" ||
247
+ typeof r.allowReview !== "boolean" ||
248
+ typeof r.cancellationObserved !== "boolean" ||
249
+ typeof r.planFingerprint !== "string" ||
250
+ !/^[a-f0-9]{64}$/.test(r.planFingerprint) ||
251
+ !Array.isArray(r.calls) ||
252
+ r.calls.length > 1001 ||
253
+ !Array.isArray(r.redactions) ||
254
+ r.redactions.some((p) => typeof p !== "string") ||
255
+ !Array.isArray(r.diagnostics) ||
256
+ r.diagnostics.some((d) => !["payload-not-recorded", "recording-byte-limit"].includes(String(d))) ||
257
+ !jsonObject(r.outcome) ||
258
+ !["succeeded", "failed"].includes(String(r.outcome.status)) ||
259
+ typeof r.fingerprint !== "string")
260
+ return bad();
261
+ if (r.readPolicy !== undefined)
262
+ parseReadPolicy(r.readPolicy);
263
+ for (const c of r.calls) {
264
+ if (!jsonObject(c) ||
265
+ !["source", "target"].includes(String(c.side)) ||
266
+ typeof c.name !== "string" ||
267
+ !["returned", "threw"].includes(String(c.outcome)) ||
268
+ typeof c.durationMs !== "number" ||
269
+ c.durationMs < 0)
270
+ return bad();
271
+ }
272
+ if (r.outcome.status === "failed" &&
273
+ (![
274
+ "preflight",
275
+ "context",
276
+ "source",
277
+ "mapping",
278
+ "target",
279
+ "unknown",
280
+ ].includes(String(r.outcome.stage)) ||
281
+ !Number.isSafeInteger(r.outcome.completedTargets) ||
282
+ Number(r.outcome.completedTargets) < 0 ||
283
+ !Array.isArray(r.outcome.issues) ||
284
+ r.outcome.issues.some((i) => !jsonObject(i) ||
285
+ typeof i.code !== "string" ||
286
+ typeof i.path !== "string")))
287
+ return bad();
288
+ if (r.outcome.status === "succeeded" &&
289
+ r.outcome.resultFingerprint !== undefined &&
290
+ (typeof r.outcome.resultFingerprint !== "string" ||
291
+ !/^[a-f0-9]{64}$/.test(r.outcome.resultFingerprint)))
292
+ return bad();
293
+ const redactions = r.redactions;
294
+ if (new Set(redactions).size !== redactions.length)
295
+ return bad();
296
+ for (const path of redactions) {
297
+ const parts = pointerParts(path);
298
+ if (![
299
+ "plan",
300
+ "sourceContract",
301
+ "targetContract",
302
+ "input",
303
+ "context",
304
+ ].includes(parts[0]) &&
305
+ !(parts[0] === "calls" &&
306
+ /^(0|[1-9]\d*)$/.test(parts[1]) &&
307
+ ["arguments", "result"].includes(parts[2])))
308
+ return bad();
309
+ let value = r;
310
+ for (const key of parts) {
311
+ if (!value || typeof value !== "object" || !Object.hasOwn(value, key))
312
+ return bad();
313
+ value = value[key];
314
+ }
315
+ if (value !== MARKER)
316
+ return bad();
317
+ }
318
+ const result = r;
319
+ if (hashRecording(result) !== result.fingerprint)
320
+ throw new Error("Recording fingerprint does not match its contents.");
321
+ return result;
322
+ }
323
+ /** Shared artifact loader for replay and explicit project scaffolding. No writes or connections. */
324
+ export function loadReplayFixture(input, options = {}) {
325
+ const recording = parseSpliceRecording(input), restored = recording.redactions.length > 0;
326
+ if (recording.capture !== "payloads" || !recording.complete)
327
+ throw new Error("Replay needs a complete payload recording; metadata or dropped payloads cannot be replayed.");
328
+ const replacements = options.restorations ?? {};
329
+ if (!jsonObject(replacements) ||
330
+ Object.keys(replacements).length !== recording.redactions.length ||
331
+ recording.redactions.some((p) => !Object.hasOwn(replacements, p)))
332
+ throw new Error("Every redacted path requires an explicit private restoration; no other paths can be replaced.");
333
+ for (const path of recording.redactions)
334
+ replaceOwnPointer(recording, path, copyJson(replacements[path]));
335
+ const spec = parseSpliceSpec(recording.plan), s = parseContractSnapshot(recording.sourceContract), t = parseContractSnapshot(recording.targetContract);
336
+ if (jsonFingerprint(spec) !== recording.planFingerprint)
337
+ throw new Error("Restored plan does not match its recorded fingerprint.");
338
+ if (!Object.hasOwn(recording, "input"))
339
+ throw new Error("Recording has no captured workflow input.");
340
+ return { recording, restored, spec, source: s, target: t };
341
+ }
342
+ /** No live caller or connection can be supplied. Saved responses are consumed strictly in order. */
343
+ export async function replaySpliceRecording(input, options = {}) {
344
+ return replayLoadedFixture(loadReplayFixture(input, options), options);
345
+ }
346
+ export async function replayLoadedFixture(fixture, options) {
347
+ const { recording, restored, spec, source: originalSource, target: originalTarget, } = fixture;
348
+ const candidate = (value, original, tool) => {
349
+ if (value === undefined)
350
+ return original;
351
+ const parsed = parseContractSnapshot(value);
352
+ if (parsed.server.name !== original.server.name)
353
+ throw new Error("Candidate contract must use the recorded server identity.");
354
+ return selectContractTools(parsed, parsed.tools.some((t) => t.name === tool) ? [tool] : []);
355
+ };
356
+ const s = candidate(options.sourceContract, originalSource, spec.source.tool), t = candidate(options.targetContract, originalTarget, spec.target.tool), checkingUpgrade = options.sourceContract !== undefined ||
357
+ options.targetContract !== undefined;
358
+ const missing = !s.tools.some((tool) => tool.name === spec.source.tool)
359
+ ? "source"
360
+ : !t.tools.some((tool) => tool.name === spec.target.tool)
361
+ ? "target"
362
+ : undefined;
363
+ let consumed = 0, mismatch = false;
364
+ const caller = (side) => async (request) => {
365
+ const saved = recording.calls[consumed];
366
+ if (!saved ||
367
+ saved.side !== side ||
368
+ saved.name !== request.name ||
369
+ !saved.arguments ||
370
+ jsonFingerprint(saved.arguments) !== jsonFingerprint(request.arguments)) {
371
+ mismatch = true;
372
+ throw new Error("Recorded call sequence or arguments differ from replay.");
373
+ }
374
+ consumed++;
375
+ if (saved.outcome === "threw")
376
+ throw new Error("Simulated recorded transport failure; original exception was not retained.");
377
+ if (!Object.hasOwn(saved, "result")) {
378
+ mismatch = true;
379
+ throw new Error("Recorded response is absent.");
380
+ }
381
+ return copyJson(saved.result);
382
+ };
383
+ let outcome, result, explanation;
384
+ try {
385
+ if (missing)
386
+ throw new SpliceError("preflight", 0, undefined, [
387
+ {
388
+ severity: "error",
389
+ code: "candidate-tool-missing",
390
+ path: `/${missing}`,
391
+ message: "The candidate catalog no longer contains the selected tool.",
392
+ },
393
+ ]);
394
+ const prepared = prepareSplice(spec, s, t);
395
+ const execute = recording.readPolicy ? prepared.runReads : prepared.run;
396
+ result = await execute(caller("source"), caller("target"), recording.input, {
397
+ ...recording.readPolicy,
398
+ allowReview: options.allowReview ?? recording.allowReview,
399
+ ...(Object.hasOwn(recording, "context")
400
+ ? { context: recording.context }
401
+ : {}),
402
+ });
403
+ outcome = {
404
+ status: "succeeded",
405
+ resultFingerprint: jsonFingerprint(result),
406
+ };
407
+ }
408
+ catch (error) {
409
+ outcome =
410
+ error instanceof SpliceError
411
+ ? {
412
+ status: "failed",
413
+ stage: error.stage,
414
+ completedTargets: error.completedTargets,
415
+ issues: error.issues.map((i) => ({ code: i.code, path: i.path })),
416
+ }
417
+ : {
418
+ status: "failed",
419
+ stage: "unknown",
420
+ completedTargets: 0,
421
+ issues: [],
422
+ };
423
+ if (error instanceof SpliceError)
424
+ explanation = explainSpliceError(spec, error);
425
+ }
426
+ const matched = !mismatch &&
427
+ consumed === recording.calls.length &&
428
+ jsonFingerprint(outcome) === jsonFingerprint(recording.outcome);
429
+ const upgradeStatus = recording.outcome.status !== "succeeded" ||
430
+ recording.cancellationObserved ||
431
+ recording.calls.some((call) => call.outcome === "threw")
432
+ ? "inconclusive"
433
+ : matched
434
+ ? "passed"
435
+ : "failed";
436
+ return {
437
+ matched,
438
+ recordedOutcome: copyJson(recording.outcome),
439
+ ...(checkingUpgrade
440
+ ? {
441
+ upgrade: {
442
+ status: upgradeStatus,
443
+ source: compareContractSnapshots(originalSource, s),
444
+ target: compareContractSnapshots(originalTarget, t),
445
+ fingerprints: {
446
+ recordedSource: originalSource.fingerprint,
447
+ candidateSource: s.fingerprint,
448
+ recordedTarget: originalTarget.fingerprint,
449
+ candidateTarget: t.fingerprint,
450
+ },
451
+ note: "This checks the captured case only. A previously failed or cancelled run cannot establish successful upgrade compatibility.",
452
+ },
453
+ }
454
+ : {}),
455
+ mode: restored ? "restored-fixture" : "saved-fixture",
456
+ networkCalls: 0,
457
+ consumedCalls: consumed,
458
+ recordedCalls: recording.calls.length,
459
+ outcome,
460
+ ...(result === undefined ? {} : { result }),
461
+ ...(explanation ? { explanation } : {}),
462
+ caveats: [
463
+ "Replay tests saved data and current guards; it does not establish live provider behavior or committed side effects.",
464
+ ...(recording.cancellationObserved
465
+ ? [
466
+ "Cancellation timing is not reproduced; a saved response may replay differently.",
467
+ ]
468
+ : []),
469
+ ...(recording.calls.some((c) => c.outcome === "threw")
470
+ ? [
471
+ "Transport exceptions are simulated without their original messages or causes.",
472
+ ]
473
+ : []),
474
+ ...(restored
475
+ ? [
476
+ "Restoration values are supplied by the application; their authenticity is not certified.",
477
+ ]
478
+ : []),
479
+ ],
480
+ };
481
+ }