@nexart/ai-execution 0.2.0 → 0.4.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 (91) hide show
  1. package/README.md +100 -330
  2. package/dist/index.cjs +607 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +56 -0
  5. package/dist/index.d.ts +55 -11
  6. package/dist/index.mjs +550 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/dist/providers/anthropic.cjs +258 -0
  9. package/dist/providers/anthropic.cjs.map +1 -0
  10. package/dist/providers/anthropic.d.cts +24 -0
  11. package/dist/providers/anthropic.d.ts +7 -5
  12. package/dist/providers/anthropic.mjs +221 -0
  13. package/dist/providers/anthropic.mjs.map +1 -0
  14. package/dist/providers/openai.cjs +259 -0
  15. package/dist/providers/openai.cjs.map +1 -0
  16. package/dist/providers/openai.d.cts +24 -0
  17. package/dist/providers/openai.d.ts +7 -5
  18. package/dist/providers/openai.mjs +222 -0
  19. package/dist/providers/openai.mjs.map +1 -0
  20. package/dist/providers/wrap.cjs +221 -0
  21. package/dist/providers/wrap.cjs.map +1 -0
  22. package/dist/providers/wrap.d.cts +9 -0
  23. package/dist/providers/wrap.d.ts +5 -3
  24. package/dist/providers/wrap.mjs +186 -0
  25. package/dist/providers/wrap.mjs.map +1 -0
  26. package/dist/{types.d.ts → types-DF29BsH5.d.cts} +18 -16
  27. package/dist/types-DF29BsH5.d.ts +155 -0
  28. package/package.json +18 -9
  29. package/dist/__tests__/fixtures.test.d.ts +0 -2
  30. package/dist/__tests__/fixtures.test.d.ts.map +0 -1
  31. package/dist/__tests__/fixtures.test.js +0 -37
  32. package/dist/__tests__/fixtures.test.js.map +0 -1
  33. package/dist/__tests__/v020.test.d.ts +0 -2
  34. package/dist/__tests__/v020.test.d.ts.map +0 -1
  35. package/dist/__tests__/v020.test.js +0 -408
  36. package/dist/__tests__/v020.test.js.map +0 -1
  37. package/dist/__tests__/vectors.test.d.ts +0 -2
  38. package/dist/__tests__/vectors.test.d.ts.map +0 -1
  39. package/dist/__tests__/vectors.test.js +0 -261
  40. package/dist/__tests__/vectors.test.js.map +0 -1
  41. package/dist/archive.d.ts +0 -4
  42. package/dist/archive.d.ts.map +0 -1
  43. package/dist/archive.js +0 -28
  44. package/dist/archive.js.map +0 -1
  45. package/dist/attest.d.ts +0 -3
  46. package/dist/attest.d.ts.map +0 -1
  47. package/dist/attest.js +0 -42
  48. package/dist/attest.js.map +0 -1
  49. package/dist/canonicalJson.d.ts +0 -2
  50. package/dist/canonicalJson.d.ts.map +0 -1
  51. package/dist/canonicalJson.js +0 -38
  52. package/dist/canonicalJson.js.map +0 -1
  53. package/dist/cer.d.ts +0 -7
  54. package/dist/cer.d.ts.map +0 -1
  55. package/dist/cer.js +0 -61
  56. package/dist/cer.js.map +0 -1
  57. package/dist/certify.d.ts +0 -3
  58. package/dist/certify.d.ts.map +0 -1
  59. package/dist/certify.js +0 -27
  60. package/dist/certify.js.map +0 -1
  61. package/dist/errors.d.ts +0 -10
  62. package/dist/errors.d.ts.map +0 -1
  63. package/dist/errors.js +0 -19
  64. package/dist/errors.js.map +0 -1
  65. package/dist/hash.d.ts +0 -6
  66. package/dist/hash.d.ts.map +0 -1
  67. package/dist/hash.js +0 -32
  68. package/dist/hash.js.map +0 -1
  69. package/dist/index.d.ts.map +0 -1
  70. package/dist/index.js +0 -11
  71. package/dist/index.js.map +0 -1
  72. package/dist/providers/anthropic.d.ts.map +0 -1
  73. package/dist/providers/anthropic.js +0 -61
  74. package/dist/providers/anthropic.js.map +0 -1
  75. package/dist/providers/openai.d.ts.map +0 -1
  76. package/dist/providers/openai.js +0 -62
  77. package/dist/providers/openai.js.map +0 -1
  78. package/dist/providers/wrap.d.ts.map +0 -1
  79. package/dist/providers/wrap.js +0 -28
  80. package/dist/providers/wrap.js.map +0 -1
  81. package/dist/run.d.ts +0 -14
  82. package/dist/run.d.ts.map +0 -1
  83. package/dist/run.js +0 -62
  84. package/dist/run.js.map +0 -1
  85. package/dist/snapshot.d.ts +0 -4
  86. package/dist/snapshot.d.ts.map +0 -1
  87. package/dist/snapshot.js +0 -113
  88. package/dist/snapshot.js.map +0 -1
  89. package/dist/types.d.ts.map +0 -1
  90. package/dist/types.js +0 -2
  91. package/dist/types.js.map +0 -1
package/README.md CHANGED
@@ -1,7 +1,11 @@
1
- # @nexart/ai-execution v0.2.0
1
+ # @nexart/ai-execution v0.4.0
2
2
 
3
3
  Tamper-evident records and Certified Execution Records (CER) for AI operations.
4
4
 
5
+ ## Why Not Just Store Logs?
6
+
7
+ Logs tell you what happened. CERs prove it. A log entry can be edited, truncated, or fabricated after the fact with no way to detect it. A CER bundle is cryptographically sealed: any modification — to the input, output, parameters, or ordering — invalidates the certificate hash. If you need to demonstrate to an auditor, regulator, or downstream system that a specific AI model produced a specific output for a specific input with specific parameters, logs are insufficient. CERs provide the tamper-evident chain of custody that logs cannot.
8
+
5
9
  ## What This Does
6
10
 
7
11
  This package creates integrity records for AI executions. Every time you call an AI model, it captures:
@@ -11,16 +15,16 @@ This package creates integrity records for AI executions. Every time you call an
11
15
  - The exact parameters used (temperature, model, etc.)
12
16
  - SHA-256 hashes of everything for tamper detection
13
17
 
14
- These records can be verified later to prove the execution happened as recorded.
18
+ These records can be verified offline to prove the execution happened as recorded.
15
19
 
16
20
  **Important:** This does NOT promise that an AI model will produce the same output twice. LLMs are not deterministic. This package provides **integrity and auditability** — proof that a specific input produced a specific output at a specific time with specific parameters.
17
21
 
18
22
  ## Compatibility Guarantees
19
23
 
20
- - **v0.1.0 bundles verify forever.** Any CER bundle produced by v0.1.0 will pass `verifyCer()` in v0.2.0 and all future versions.
24
+ - **v0.1.0, v0.2.0, and v0.3.0 bundles verify forever.** Any CER bundle produced by any prior version will pass `verify()` in v0.4.0 and all future versions.
21
25
  - **Hashing rules are frozen for `cer.ai.execution.v1`.** The canonicalization, SHA-256 computation, and certificate hash inputs (bundleType, version, createdAt, snapshot) are unchanged.
22
26
  - **New optional snapshot fields** (runId, stepId, stepIndex, etc.) default to undefined and are excluded from legacy snapshots. They participate in the certificate hash only when present.
23
- - **If stricter canonicalization is needed in the future**, it will ship as a new bundle type (e.g. `cer.ai.execution.v2`), not as a change to v1.
27
+ - **Canonicalization is frozen for v1.** Number-to-string conversion uses `JSON.stringify()`, which is consistent across JavaScript engines but does not implement RFC 8785 (JCS) for edge cases like `-0`. If stricter canonicalization is required, it will ship as a new bundle type (`cer.ai.execution.v2`), never as a modification to v1.
24
28
 
25
29
  ## Installation
26
30
 
@@ -46,30 +50,24 @@ const cer = certifyDecision({
46
50
  console.log(cer.certificateHash); // "sha256:..."
47
51
  ```
48
52
 
49
- ### Manual Snapshot + Seal (v0.1.0 style, still supported)
53
+ ### Manual Snapshot + Seal
50
54
 
51
55
  ```typescript
52
- import { createSnapshot, verifySnapshot, sealCer, verifyCer } from '@nexart/ai-execution';
56
+ import { createSnapshot, sealCer, verify } from '@nexart/ai-execution';
53
57
 
54
58
  const snapshot = createSnapshot({
55
59
  executionId: 'exec-001',
56
60
  provider: 'openai',
57
61
  model: 'gpt-4o',
58
- modelVersion: '2026-01-01',
59
62
  prompt: 'You are a helpful assistant.',
60
63
  input: 'What is 2+2?',
61
64
  parameters: { temperature: 0.7, maxTokens: 1024, topP: null, seed: null },
62
65
  output: 'The answer is 4.',
63
66
  });
64
67
 
65
- const result = verifySnapshot(snapshot);
66
- console.log(result.ok); // true
67
-
68
68
  const bundle = sealCer(snapshot);
69
- console.log(bundle.certificateHash); // "sha256:..."
70
-
71
- const cerResult = verifyCer(bundle);
72
- console.log(cerResult.ok); // true
69
+ const result = verify(bundle);
70
+ console.log(result.ok); // true
73
71
  ```
74
72
 
75
73
  ### Agentic Multi-Step Workflow
@@ -79,28 +77,24 @@ import { RunBuilder } from '@nexart/ai-execution';
79
77
 
80
78
  const run = new RunBuilder({ runId: 'analysis-run', workflowId: 'data-pipeline' });
81
79
 
82
- const step0 = run.step({
83
- provider: 'openai',
84
- model: 'gpt-4o',
80
+ run.step({
81
+ provider: 'openai', model: 'gpt-4o',
85
82
  prompt: 'Plan the analysis.',
86
83
  input: 'Analyze Q1 sales data.',
87
84
  output: 'I will: 1) load data, 2) compute totals, 3) summarize.',
88
85
  parameters: { temperature: 0.3, maxTokens: 512, topP: null, seed: null },
89
86
  });
90
- // step0.snapshot.stepIndex === 0, prevStepHash === null
91
87
 
92
- const step1 = run.step({
93
- provider: 'openai',
94
- model: 'gpt-4o',
88
+ run.step({
89
+ provider: 'openai', model: 'gpt-4o',
95
90
  prompt: 'Execute step 1.',
96
91
  input: 'Load and total Q1 data.',
97
92
  output: 'Total revenue: $1.2M.',
98
93
  parameters: { temperature: 0.3, maxTokens: 512, topP: null, seed: null },
99
94
  });
100
- // step1.snapshot.stepIndex === 1, prevStepHash === step0.certificateHash
101
95
 
102
96
  const summary = run.finalize();
103
- // { runId, stepCount: 2, steps: [...], finalStepHash: step1.certificateHash }
97
+ // { runId, stepCount: 2, steps: [...], finalStepHash: "sha256:..." }
104
98
  ```
105
99
 
106
100
  ### Attest to Canonical Node
@@ -113,110 +107,20 @@ const proof = await attest(cer, {
113
107
  nodeUrl: 'https://node.nexart.io',
114
108
  apiKey: process.env.NEXART_API_KEY!,
115
109
  });
116
- console.log(proof.attestationId); // ledger proof reference
117
- ```
118
-
119
- ### Archive (Export / Import)
120
-
121
- ```typescript
122
- import { exportCer, importCer, sealCer, createSnapshot } from '@nexart/ai-execution';
123
-
124
- const bundle = sealCer(createSnapshot({ /* ... */ }));
125
-
126
- // Export as canonical JSON string (deterministic, archive-safe)
127
- const json = exportCer(bundle);
128
- await fs.writeFile('audit/cer-001.json', json);
129
-
130
- // Import and verify in one step (throws CerVerificationError if invalid)
131
- const restored = importCer(await fs.readFile('audit/cer-001.json', 'utf-8'));
132
- ```
133
-
134
- ### With JSON Input/Output
135
-
136
- ```typescript
137
- const snapshot = createSnapshot({
138
- executionId: 'exec-002',
139
- provider: 'openai',
140
- model: 'gpt-4o',
141
- prompt: 'Extract entities',
142
- input: { text: 'John lives in Paris', lang: 'en' },
143
- parameters: { temperature: 0, maxTokens: 512, topP: null, seed: 42 },
144
- output: { entities: ['John', 'Paris'], count: 2 },
145
- });
110
+ console.log(proof.attestationId);
146
111
  ```
147
112
 
148
- ### OpenAI Provider (Optional)
149
-
150
- Convenience adapter only; the core value of this package is the snapshot + hashing format.
151
- The OpenAI adapter wraps a single `chat/completions` call and returns a sealed CER bundle.
152
- **Provider determinism is not guaranteed** — identical inputs may produce different outputs across calls.
153
-
154
- ```typescript
155
- import { runOpenAIChatExecution } from '@nexart/ai-execution/providers/openai';
113
+ Attestation verifies internal integrity only. It does not re-run the model. The node confirms the bundle's hashes are consistent and records it in the proof ledger.
156
114
 
157
- const result = await runOpenAIChatExecution({
158
- prompt: 'You are a helpful assistant.',
159
- input: 'What is the capital of France?',
160
- model: 'gpt-4o',
161
- parameters: { temperature: 0.7, maxTokens: 256 },
162
- });
163
-
164
- console.log(result.output); // "The capital of France is Paris."
165
- console.log(result.snapshot.inputHash); // "sha256:..."
166
- console.log(result.bundle.certificateHash); // "sha256:..."
167
- ```
168
-
169
- Requires `OPENAI_API_KEY` environment variable or `apiKey` parameter.
170
-
171
- ### Anthropic Provider (Optional)
115
+ ### Archive (Export / Import)
172
116
 
173
117
  ```typescript
174
- import { runAnthropicExecution } from '@nexart/ai-execution/providers/anthropic';
118
+ import { exportCer, importCer } from '@nexart/ai-execution';
175
119
 
176
- const result = await runAnthropicExecution({
177
- prompt: 'You are a helpful assistant.',
178
- input: 'Explain quantum computing briefly.',
179
- model: 'claude-sonnet-4-20250514',
180
- parameters: { temperature: 0.5, maxTokens: 512 },
181
- });
120
+ const json = exportCer(bundle); // canonical JSON string
121
+ const restored = importCer(json); // parse + verify (throws on tamper)
182
122
  ```
183
123
 
184
- Requires `ANTHROPIC_API_KEY` environment variable or `apiKey` parameter.
185
-
186
- ### Generic Provider Wrapper
187
-
188
- ```typescript
189
- import { wrapProvider } from '@nexart/ai-execution/providers/wrap';
190
-
191
- const myProvider = wrapProvider({
192
- provider: 'my-llm',
193
- callFn: async (input) => await myLlmClient.chat(input),
194
- extractOutput: (raw) => raw.message,
195
- extractModelVersion: (raw) => raw.modelVersion,
196
- });
197
-
198
- const result = await myProvider.execute({
199
- providerInput: { messages: [{ role: 'user', content: 'Hello' }] },
200
- prompt: 'System prompt',
201
- input: 'Hello',
202
- model: 'my-model-v2',
203
- parameters: { temperature: 0.7, maxTokens: 1024, topP: null, seed: null },
204
- });
205
- ```
206
-
207
- ## v0.2.0 Additions
208
-
209
- | Feature | Description |
210
- |---|---|
211
- | `certifyDecision()` | One-call convenience: createSnapshot + sealCer combined |
212
- | `RunBuilder` | Agentic workflow support with step chaining and prevStepHash |
213
- | `attest()` | Post CER bundle to canonical node for ledger attestation |
214
- | `exportCer()` / `importCer()` | Archive-safe canonical JSON serialization with verification |
215
- | `wrapProvider()` | Generic provider wrapper factory |
216
- | Anthropic adapter | `@nexart/ai-execution/providers/anthropic` |
217
- | Typed errors | `CerVerificationError`, `CerAttestationError` |
218
- | Workflow fields | `runId`, `stepId`, `stepIndex`, `workflowId`, `conversationId`, `prevStepHash` |
219
-
220
124
  ## Snapshot Format (ai.execution.v1)
221
125
 
222
126
  ### Required vs Optional Fields
@@ -235,24 +139,16 @@ const result = await myProvider.execute({
235
139
  | `modelVersion` | Optional | `string \| null` | Defaults to `null` |
236
140
  | `parameters.topP` | Optional | `number \| null` | Defaults to `null` |
237
141
  | `parameters.seed` | Optional | `number \| null` | Defaults to `null` |
238
- | `sdkVersion` | Optional | `string \| null` | Defaults to package version (`"0.2.0"`) |
142
+ | `sdkVersion` | Optional | `string \| null` | Defaults to `"0.4.0"` |
239
143
  | `appId` | Optional | `string \| null` | Defaults to `null` |
240
- | `runId` | Optional | `string \| null` | Workflow run ID (v0.2.0+) |
241
- | `stepId` | Optional | `string \| null` | Step identifier within a run (v0.2.0+) |
242
- | `stepIndex` | Optional | `number \| null` | 0-based step position (v0.2.0+) |
243
- | `workflowId` | Optional | `string \| null` | Workflow template ID (v0.2.0+) |
244
- | `conversationId` | Optional | `string \| null` | Conversation/session ID (v0.2.0+) |
245
- | `prevStepHash` | Optional | `string \| null` | certificateHash of previous step (v0.2.0+) |
144
+ | `runId` | Optional | `string \| null` | Workflow run ID |
145
+ | `stepId` | Optional | `string \| null` | Step identifier within a run |
146
+ | `stepIndex` | Optional | `number \| null` | 0-based step position |
147
+ | `workflowId` | Optional | `string \| null` | Workflow template ID |
148
+ | `conversationId` | Optional | `string \| null` | Conversation/session ID |
149
+ | `prevStepHash` | Optional | `string \| null` | certificateHash of previous step |
246
150
 
247
- The following fields are **auto-generated** by `createSnapshot` and must not be set manually:
248
-
249
- | Field | Value |
250
- |---|---|
251
- | `type` | `"ai.execution.v1"` |
252
- | `protocolVersion` | `"1.2.0"` |
253
- | `executionSurface` | `"ai"` |
254
- | `inputHash` | SHA-256 of input |
255
- | `outputHash` | SHA-256 of output |
151
+ Auto-generated fields (set by `createSnapshot`, do not set manually): `type`, `protocolVersion`, `executionSurface`, `inputHash`, `outputHash`.
256
152
 
257
153
  ## CER Bundle Format
258
154
 
@@ -263,249 +159,123 @@ The following fields are **auto-generated** by `createSnapshot` and must not be
263
159
  "createdAt": "2026-02-12T00:00:00.000Z",
264
160
  "version": "0.1",
265
161
  "snapshot": { ... },
266
- "meta": {
267
- "source": "my-app",
268
- "tags": ["production"]
269
- }
162
+ "meta": { "source": "my-app", "tags": ["production"] }
270
163
  }
271
164
  ```
272
165
 
273
166
  ### Certificate Hash Computation
274
167
 
275
- The `certificateHash` is SHA-256 of the UTF-8 bytes of the canonical JSON of **exactly these four fields**:
276
-
277
- ```
278
- { bundleType, version, createdAt, snapshot }
279
- ```
280
-
281
- - `meta` is **excluded** from the certificate hash. It is an informational envelope field that does not affect integrity verification.
282
- - Key-ordering rules apply **recursively** — every nested object within `snapshot` is also sorted lexicographically by key.
283
- - The bytes being hashed are the UTF-8 encoding of the canonical JSON string (no BOM, no trailing newline).
284
- - **This computation is identical in v0.1.0 and v0.2.0.** New optional snapshot fields (runId, stepIndex, etc.) participate in the hash only when present in the snapshot object.
285
-
286
- ## Hashing Rules
287
-
288
- - **String values**: SHA-256 of UTF-8 bytes of the raw string
289
- - **Object/Array values**: SHA-256 of UTF-8 bytes of canonical JSON (sorted keys, no whitespace, stable array order)
290
- - All hashes use the format `sha256:<hex>` (lowercase hex, 64 characters)
291
-
292
- ## Canonical JSON Constraints
293
-
294
- Canonical JSON is a deterministic subset of JSON. The following rules apply:
295
-
296
- 1. **Object keys** are sorted lexicographically (Unicode codepoint order) at every nesting level.
297
- 2. **No whitespace** — no spaces, tabs, or newlines between tokens.
298
- 3. **Array order is preserved** — arrays are never re-sorted.
299
- 4. **`null`** is valid and serialized as `null`.
300
- 5. **Numbers** must be finite. `NaN`, `Infinity`, and `-Infinity` are **rejected** (throw).
301
- 6. **`undefined`** values in object properties are **omitted** (the key is dropped).
302
- 7. **`BigInt`**, **functions**, and **`Symbol`** are **not valid** JSON types and are **rejected** (throw).
303
- 8. Strings are JSON-escaped (e.g. `"` → `\"`).
304
-
305
- These constraints ensure that the same logical value always produces the same byte sequence, which is essential for hash stability across implementations and languages.
306
-
307
- **Note on number formatting:** v1 bundles use `JSON.stringify()` for number-to-string conversion, which is consistent across JavaScript engines but does not implement RFC 8785 (JCS) number formatting for edge cases like `-0`. If stricter canonicalization is required in the future, it will be introduced via a new bundle type (`cer.ai.execution.v2`), not by modifying v1 behavior.
308
-
309
- ## RunBuilder: Agentic Workflow Chaining
310
-
311
- The `RunBuilder` class enables multi-step AI workflows with cryptographic chaining:
312
-
313
- - **Auto-incrementing `stepIndex`**: starts at 0, increments with each `.step()` call.
314
- - **`prevStepHash` chaining**: each step's `prevStepHash` is set to the `certificateHash` of the previous step (null for step 0).
315
- - **`executionId` generation**: automatically set to `{runId}-step-{stepIndex}`.
316
- - Each step produces a full, independently verifiable CER bundle.
317
- - Call `.finalize()` to get a `RunSummary` with all step hashes and chain metadata.
168
+ The `certificateHash` is SHA-256 of the UTF-8 bytes of the canonical JSON of exactly: `{ bundleType, version, createdAt, snapshot }`. `meta` is excluded. Key-ordering is recursive. This computation is identical across all SDK versions.
318
169
 
319
170
  ## Attestation
320
171
 
321
- The `attest()` function posts a sealed CER bundle to a NexArt canonical node:
322
-
323
- ```typescript
324
- const proof = await attest(bundle, {
325
- nodeUrl: 'https://node.nexart.io',
326
- apiKey: 'your-api-key',
327
- });
328
- ```
172
+ Endpoint: `POST {nodeUrl}/api/attest`
329
173
 
330
- - Endpoint: `POST {nodeUrl}/api/attest`
331
174
  - Authorization: `Bearer {apiKey}`
332
- - Body: the full CER bundle as JSON
175
+ - Body: the full CER bundle as JSON (auto-sanitized via `sanitizeForAttestation` in v0.4.0+)
333
176
  - Returns: `AttestationResult` with `attestationId`, `nodeRuntimeHash`, `certificateHash`, `protocolVersion`
334
- - Throws: `CerAttestationError` on network or HTTP errors
335
-
336
- ## Error Types
337
-
338
- | Error | When thrown |
339
- |---|---|
340
- | `CerVerificationError` | `importCer()` receives invalid or tampered JSON |
341
- | `CerAttestationError` | `attest()` fails (network error, HTTP error, invalid response) |
342
-
343
- Both extend `Error` and include structured data:
344
- - `CerVerificationError.errors`: `string[]` of specific verification failures
345
- - `CerAttestationError.statusCode`: HTTP status code (if available)
346
- - `CerAttestationError.responseBody`: raw response body (if available)
347
-
348
- ## Interoperability (Test Vectors)
349
-
350
- Cross-language implementations **must** match the test vectors exactly. Vectors are committed as JSON fixtures at:
351
-
352
- ```
353
- packages/ai-execution/fixtures/vectors/
354
- ```
355
-
356
- ### Vector 001 (single decision)
357
-
358
- See `vector-001.snapshot.json` and `vector-001.expected.json` for a single text-in/text-out CER with committed hash values.
359
-
360
- ### Vector 002 (3-step agentic chain)
361
-
362
- See `vector-002.chain.json` for a 3-step workflow chain with:
363
- - Step 0: `prevStepHash: null`, `stepIndex: 0`
364
- - Step 1: `prevStepHash: step0.certificateHash`, `stepIndex: 1`
365
- - Step 2: `prevStepHash: step1.certificateHash`, `stepIndex: 2`
366
-
367
- Each entry includes `snapshot`, `expectedCertificateHash`, and `cerCreatedAt` for deterministic verification.
368
-
369
- ### Golden Fixtures (backward compatibility)
370
-
371
- 5 CER bundles produced with v0.1.0 semantics are committed at:
372
-
373
- ```
374
- packages/ai-execution/fixtures/golden/
375
- ```
177
+ - Default timeout: 10 seconds (configurable via `timeoutMs`)
178
+ - Validates: response `certificateHash` matches submitted bundle; all hashes in `sha256:<64hex>` format
179
+ - Throws: `CerAttestationError` on mismatch, network error, timeout, or HTTP error
376
180
 
377
- These bundles must verify with every future version of the library.
181
+ Attestation verifies internal integrity only. It does not re-run the model or validate the correctness of the AI output.
378
182
 
379
- ## Threat Model
183
+ ### Sanitization and Redaction
380
184
 
381
- This package provides **integrity and auditability** for AI execution records.
185
+ `sanitizeForAttestation(bundle)` returns a JSON-safe deep clone:
186
+ - Removes keys with `undefined` values at all nesting levels
187
+ - Rejects `BigInt`, functions, and symbols (throws)
188
+ - Safe to serialize with `JSON.stringify` or canonical JSON
382
189
 
383
- ### What it prevents
190
+ **Recommended redaction pattern:** delete keys or set them to `null` — never set to `undefined`, which is not valid JSON. Call `sanitizeForAttestation` before archiving or attesting if your bundle may contain `undefined` values.
384
191
 
385
- - **Output tampering** any modification to the recorded output invalidates the `outputHash` and `certificateHash`.
386
- - **Parameter laundering** — changing temperature, model, seed, or other parameters after the fact is detectable.
387
- - **Silent record edits** — any modification to a sealed CER bundle is detectable via `verifyCer()`.
388
- - **Chain forgery** — in multi-step workflows, `prevStepHash` links each step to the previous, making it impossible to insert, remove, or reorder steps without detection.
192
+ **Skip re-attestation:** use `hasAttestation(bundle)` to check if a bundle already includes attestation fields before calling `attest()` again.
389
193
 
390
- ### What it does NOT prevent
391
-
392
- - **Provider lying** — if the AI provider returns fabricated output, this package faithfully records it.
393
- - **Model drift** — models change over time. `modelVersion` helps track this but cannot prevent it.
394
- - **Correctness of the answer** — this package records what was said, not whether it was right.
395
-
396
- ## Verification Best Practice
397
-
398
- **Recommended flow:**
399
-
400
- 1. Call `certifyDecision(...)` (or `createSnapshot` + `sealCer`).
401
- 2. Call `verifyCer(bundle)` **before** storing — catches any in-memory corruption.
402
- 3. Store the full bundle as an immutable audit artifact.
403
- 4. Optionally call `attest(bundle, ...)` to register on the canonical node ledger.
404
- 5. On retrieval, call `verifyCer(bundle)` again to confirm integrity.
405
-
406
- ```typescript
407
- const bundle = certifyDecision({ ... });
408
-
409
- const check = verifyCer(bundle);
410
- if (!check.ok) {
411
- throw new Error(`CER integrity failure: ${check.errors.join('; ')}`);
412
- }
413
-
414
- await store(bundle);
194
+ ## Canonical JSON Constraints
415
195
 
416
- // Optional: attest to canonical node
417
- const proof = await attest(bundle, { nodeUrl, apiKey });
418
- ```
196
+ 1. Object keys sorted lexicographically (Unicode codepoint order) at every nesting level.
197
+ 2. No whitespace between tokens.
198
+ 3. Array order preserved.
199
+ 4. `null` serialized as `null`.
200
+ 5. Numbers must be finite. `NaN`, `Infinity`, `-Infinity` rejected (throw).
201
+ 6. `undefined` values in object properties omitted (key dropped).
202
+ 7. `BigInt`, functions, `Symbol` rejected (throw).
203
+ 8. Strings JSON-escaped.
419
204
 
420
- ## Privacy & Data Handling
205
+ **Canonicalization is frozen for v1.** Number formatting uses `JSON.stringify()` (V8-consistent). This does not normalize `-0` to `0` and does not implement RFC 8785 exponential notation rules. These are documented known behaviors, not bugs. Any future stricter canonicalization will ship under a new bundle type.
421
206
 
422
- Snapshots include **raw prompt, input, and output by default**. This means:
207
+ ## Error Types
423
208
 
424
- - If the input contains PII, medical data, or other sensitive information, the snapshot will contain it verbatim.
425
- - If the output contains sensitive content, it will be stored in full.
209
+ | Error | When thrown | Structured data |
210
+ |---|---|---|
211
+ | `CerVerificationError` | `importCer()` on invalid/tampered data | `.errors: string[]` |
212
+ | `CerAttestationError` | `attest()` on failure | `.statusCode`, `.responseBody`, `.details: string[]` |
426
213
 
427
- **Recommendations:**
214
+ ## Interoperability (Test Vectors)
428
215
 
429
- - For sensitive workloads, consider redacting input/output before calling `createSnapshot()`, then verify the redacted versions.
430
- - A dedicated redacted bundle type (`cer.ai.execution.redacted.v1`) is planned for a future release.
431
- - Treat CER bundles with the same access controls as the underlying data they contain.
216
+ Fixtures at `fixtures/vectors/` and `fixtures/golden/`. Cross-language implementations must match committed hash values exactly. Golden fixtures (v0.1.0 semantics) must verify with every future version.
432
217
 
433
218
  ## API Reference
434
219
 
435
220
  ### Core
436
221
 
437
222
  | Function | Description |
438
- |----------|-------------|
439
- | `createSnapshot(params)` | Create an AI execution snapshot with computed hashes |
223
+ |---|---|
224
+ | `createSnapshot(params)` | Create snapshot with computed hashes |
440
225
  | `verifySnapshot(snapshot)` | Verify snapshot hashes and structure |
441
- | `sealCer(snapshot, options?)` | Seal a snapshot into a CER bundle |
442
- | `verifyCer(bundle)` | Verify a CER bundle (snapshot + certificate hash) |
443
- | `certifyDecision(params)` | One-call: createSnapshot + sealCer combined **(v0.2.0)** |
226
+ | `sealCer(snapshot, options?)` | Seal snapshot into CER bundle |
227
+ | `verify(bundle)` / `verifyCer(bundle)` | Verify CER bundle |
228
+ | `certifyDecision(params)` | One-call: createSnapshot + sealCer |
444
229
 
445
230
  ### Workflow
446
231
 
447
- | Function/Class | Description |
448
- |----------|-------------|
449
- | `RunBuilder` | Multi-step workflow builder with step chaining **(v0.2.0)** |
450
- | `RunBuilder.step(params)` | Add a step, returns sealed CER bundle |
451
- | `RunBuilder.finalize()` | Returns RunSummary with all step hashes |
452
-
453
- ### Attestation
454
-
455
- | Function | Description |
456
- |----------|-------------|
457
- | `attest(bundle, options)` | Post CER bundle to canonical node **(v0.2.0)** |
458
-
459
- ### Archive
460
-
461
- | Function | Description |
462
- |----------|-------------|
463
- | `exportCer(bundle)` | Serialize bundle to canonical JSON string **(v0.2.0)** |
464
- | `importCer(json)` | Parse + verify bundle from JSON string **(v0.2.0)** |
465
-
466
- ### Hashing
467
-
468
- | Function | Description |
469
- |----------|-------------|
470
- | `computeInputHash(input)` | Compute hash for input (string or object) |
471
- | `computeOutputHash(output)` | Compute hash for output (string or object) |
472
- | `toCanonicalJson(value)` | Deterministic JSON serialization |
473
- | `sha256Hex(data)` | Raw SHA-256 hex digest |
474
- | `hashUtf8(value)` | Hash a UTF-8 string |
475
- | `hashCanonicalJson(value)` | Hash canonical JSON of a value |
232
+ | Export | Description |
233
+ |---|---|
234
+ | `RunBuilder` | Multi-step workflow builder with prevStepHash chaining |
476
235
 
477
- ### Providers
236
+ ### Attestation & Archive
478
237
 
479
238
  | Function | Description |
480
- |----------|-------------|
481
- | `runOpenAIChatExecution(params)` | OpenAI chat wrapper (sub-export) |
482
- | `runAnthropicExecution(params)` | Anthropic Messages wrapper **(v0.2.0)** |
483
- | `wrapProvider(config)` | Generic provider wrapper factory **(v0.2.0)** |
239
+ |---|---|
240
+ | `attest(bundle, options)` | Post CER to canonical node (auto-sanitizes) |
241
+ | `sanitizeForAttestation(bundle)` | Remove `undefined` keys, reject BigInt/functions/symbols |
242
+ | `hasAttestation(bundle)` | Check if bundle already has attestation fields |
243
+ | `exportCer(bundle)` | Serialize to canonical JSON string |
244
+ | `importCer(json)` | Parse + verify from JSON string |
484
245
 
485
- ### Errors
246
+ ### Providers (sub-exports)
486
247
 
487
- | Class | Description |
488
- |----------|-------------|
489
- | `CerVerificationError` | Thrown by `importCer()` on invalid/tampered data **(v0.2.0)** |
490
- | `CerAttestationError` | Thrown by `attest()` on failure **(v0.2.0)** |
248
+ | Function | Export path |
249
+ |---|---|
250
+ | `runOpenAIChatExecution` | `@nexart/ai-execution/providers/openai` |
251
+ | `runAnthropicExecution` | `@nexart/ai-execution/providers/anthropic` |
252
+ | `wrapProvider` | `@nexart/ai-execution/providers/wrap` |
491
253
 
492
- ## Version Plan
254
+ ## Version History
493
255
 
494
- | Version | Status | Description |
495
- |---------|--------|-------------|
496
- | v0.1.0 | Released | Core snapshot + CER + verify + OpenAI adapter |
497
- | **v0.2.0** | **Current** | certifyDecision, RunBuilder, attest, archive, Anthropic, wrapProvider, typed errors, workflow fields |
498
- | v1.0.0 | Planned | API stabilization. Rename `sealCer`→`seal`, `verifyCer`→`verify` (old names kept as deprecated aliases). Freeze public API surface. |
256
+ | Version | Description |
257
+ |---|---|
258
+ | v0.1.0 | Core snapshot + CER + verify + OpenAI adapter |
259
+ | v0.2.0 | certifyDecision, RunBuilder, attest, archive, Anthropic, wrapProvider, typed errors, workflow fields |
260
+ | v0.3.0 | Attestation hardening (hash validation, timeout), `verify` alias, `CerAttestationError.details`, release hygiene |
261
+ | **v0.4.0** | Dual ESM/CJS build, `sanitizeForAttestation`, `hasAttestation`, auto-sanitize in `attest()`, fixed `ERR_PACKAGE_PATH_NOT_EXPORTED` |
262
+ | v1.0.0 | Planned: API stabilization, freeze public API surface |
499
263
 
500
- ## How to Publish
264
+ ## Releasing
501
265
 
502
266
  ```bash
503
267
  cd packages/ai-execution
504
268
  npm run build
505
- npm run test
269
+ npm test
506
270
  npm publish --access public
507
271
  ```
508
272
 
273
+ The `release` script automates build, test, version bump, and publish:
274
+
275
+ ```bash
276
+ npm run release
277
+ ```
278
+
509
279
  ## License
510
280
 
511
281
  MIT