@mikeargento/bitgraph 1.1.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 (80) hide show
  1. package/LICENSE +9 -0
  2. package/NOTICE +14 -0
  3. package/README.md +175 -0
  4. package/dist/__tests__/canonical.test.d.ts +2 -0
  5. package/dist/__tests__/canonical.test.d.ts.map +1 -0
  6. package/dist/__tests__/canonical.test.js +162 -0
  7. package/dist/__tests__/canonical.test.js.map +1 -0
  8. package/dist/__tests__/commit-service.integration.test.d.ts +2 -0
  9. package/dist/__tests__/commit-service.integration.test.d.ts.map +1 -0
  10. package/dist/__tests__/commit-service.integration.test.js +95 -0
  11. package/dist/__tests__/commit-service.integration.test.js.map +1 -0
  12. package/dist/__tests__/constructor.test.d.ts +2 -0
  13. package/dist/__tests__/constructor.test.d.ts.map +1 -0
  14. package/dist/__tests__/constructor.test.js +267 -0
  15. package/dist/__tests__/constructor.test.js.map +1 -0
  16. package/dist/__tests__/hello-world.test.d.ts +2 -0
  17. package/dist/__tests__/hello-world.test.d.ts.map +1 -0
  18. package/dist/__tests__/hello-world.test.js +9 -0
  19. package/dist/__tests__/hello-world.test.js.map +1 -0
  20. package/dist/__tests__/policy-enforcement.test.d.ts +2 -0
  21. package/dist/__tests__/policy-enforcement.test.d.ts.map +1 -0
  22. package/dist/__tests__/policy-enforcement.test.js +188 -0
  23. package/dist/__tests__/policy-enforcement.test.js.map +1 -0
  24. package/dist/__tests__/proof-hash-regression.test.d.ts +2 -0
  25. package/dist/__tests__/proof-hash-regression.test.d.ts.map +1 -0
  26. package/dist/__tests__/proof-hash-regression.test.js +134 -0
  27. package/dist/__tests__/proof-hash-regression.test.js.map +1 -0
  28. package/dist/__tests__/proof-hash.test.d.ts +2 -0
  29. package/dist/__tests__/proof-hash.test.d.ts.map +1 -0
  30. package/dist/__tests__/proof-hash.test.js +134 -0
  31. package/dist/__tests__/proof-hash.test.js.map +1 -0
  32. package/dist/__tests__/verifier.test.d.ts +2 -0
  33. package/dist/__tests__/verifier.test.d.ts.map +1 -0
  34. package/dist/__tests__/verifier.test.js +457 -0
  35. package/dist/__tests__/verifier.test.js.map +1 -0
  36. package/dist/canonical.d.ts +54 -0
  37. package/dist/canonical.d.ts.map +1 -0
  38. package/dist/canonical.js +119 -0
  39. package/dist/canonical.js.map +1 -0
  40. package/dist/constructor.d.ts +66 -0
  41. package/dist/constructor.d.ts.map +1 -0
  42. package/dist/constructor.js +339 -0
  43. package/dist/constructor.js.map +1 -0
  44. package/dist/host.d.ts +138 -0
  45. package/dist/host.d.ts.map +1 -0
  46. package/dist/host.js +3 -0
  47. package/dist/host.js.map +1 -0
  48. package/dist/index.d.ts +20 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +9 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/policy.d.ts +68 -0
  53. package/dist/policy.d.ts.map +1 -0
  54. package/dist/policy.js +176 -0
  55. package/dist/policy.js.map +1 -0
  56. package/dist/proof-hash.d.ts +9 -0
  57. package/dist/proof-hash.d.ts.map +1 -0
  58. package/dist/proof-hash.js +75 -0
  59. package/dist/proof-hash.js.map +1 -0
  60. package/dist/types.d.ts +705 -0
  61. package/dist/types.d.ts.map +1 -0
  62. package/dist/types.js +3 -0
  63. package/dist/types.js.map +1 -0
  64. package/dist/verifier.d.ts +27 -0
  65. package/dist/verifier.d.ts.map +1 -0
  66. package/dist/verifier.js +844 -0
  67. package/dist/verifier.js.map +1 -0
  68. package/package.json +40 -0
  69. package/src/__tests__/canonical.test.ts +253 -0
  70. package/src/__tests__/commit-service.integration.test.ts +117 -0
  71. package/src/__tests__/constructor.test.ts +340 -0
  72. package/src/__tests__/hello-world.test.ts +10 -0
  73. package/src/__tests__/policy-enforcement.test.ts +226 -0
  74. package/src/__tests__/proof-hash-regression.test.ts +147 -0
  75. package/src/__tests__/proof-hash.test.ts +148 -0
  76. package/src/__tests__/verifier.test.ts +541 -0
  77. package/src/constructor.ts +435 -0
  78. package/src/host.ts +153 -0
  79. package/src/index.ts +51 -0
  80. package/src/policy.ts +239 -0
@@ -0,0 +1,340 @@
1
+ // Copyright (c) Mike Argento. All rights reserved. See LICENSE.
2
+
3
+ import { describe, test } from "node:test";
4
+ import * as assert from "node:assert/strict";
5
+ import { getPublicKeyAsync, signAsync } from "@noble/ed25519";
6
+ import { Constructor } from "../constructor.js";
7
+ import type { HostCapabilities } from "../host.js";
8
+
9
+ // ---------------------------------------------------------------------------
10
+ // Test helper: build a mock host backed by a real Ed25519 key pair
11
+ // ---------------------------------------------------------------------------
12
+
13
+ interface KeyMaterial {
14
+ privateKey: Uint8Array;
15
+ publicKeyBytes: Uint8Array;
16
+ publicKeyB64: string;
17
+ }
18
+
19
+ async function makeKeys(): Promise<KeyMaterial> {
20
+ const privateKey = crypto.getRandomValues(new Uint8Array(32));
21
+ const publicKeyBytes = await getPublicKeyAsync(privateKey);
22
+ const publicKeyB64 = Buffer.from(publicKeyBytes).toString("base64");
23
+ return { privateKey, publicKeyBytes, publicKeyB64 };
24
+ }
25
+
26
+ /** Minimal stub host — all required capabilities, no optional ones. */
27
+ function baseHost(km: KeyMaterial): HostCapabilities {
28
+ return {
29
+ enforcementTier: "stub" as const,
30
+ getMeasurement: async () => "test-measurement-cafebabe",
31
+ getFreshNonce: async () => crypto.getRandomValues(new Uint8Array(16)),
32
+ sign: async (data: Uint8Array) => signAsync(data, km.privateKey),
33
+ getPublicKey: async () => km.publicKeyBytes,
34
+ };
35
+ }
36
+
37
+ /** Stub host that also exposes a monotonic counter. */
38
+ function hostWithCounter(km: KeyMaterial): HostCapabilities {
39
+ let c = 0;
40
+ return {
41
+ enforcementTier: "stub" as const,
42
+ getMeasurement: async () => "test-measurement-cafebabe",
43
+ getFreshNonce: async () => crypto.getRandomValues(new Uint8Array(16)),
44
+ sign: async (data: Uint8Array) => signAsync(data, km.privateKey),
45
+ getPublicKey: async () => km.publicKeyBytes,
46
+ nextCounter: async () => String(++c),
47
+ };
48
+ }
49
+
50
+ /** Stub host that also exposes a secure clock. */
51
+ function hostWithTime(km: KeyMaterial, timeMs: number): HostCapabilities {
52
+ return {
53
+ enforcementTier: "stub" as const,
54
+ getMeasurement: async () => "test-measurement-cafebabe",
55
+ getFreshNonce: async () => crypto.getRandomValues(new Uint8Array(16)),
56
+ sign: async (data: Uint8Array) => signAsync(data, km.privateKey),
57
+ getPublicKey: async () => km.publicKeyBytes,
58
+ secureTime: async () => timeMs,
59
+ };
60
+ }
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Constructor.initialize
64
+ // ---------------------------------------------------------------------------
65
+
66
+ describe("Constructor.initialize", () => {
67
+ test("succeeds with a minimal host", async () => {
68
+ const km = await makeKeys();
69
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
70
+ assert.ok(ctor instanceof Constructor);
71
+ });
72
+
73
+ test("fails when getMeasurement() rejects", async () => {
74
+ const km = await makeKeys();
75
+ const host: HostCapabilities = {
76
+ ...baseHost(km),
77
+ getMeasurement: async () => { throw new Error("measurement unavailable"); },
78
+ };
79
+ await assert.rejects(
80
+ Constructor.initialize({ host }),
81
+ /preflight failed/,
82
+ );
83
+ });
84
+
85
+ test("fails when getPublicKey() rejects", async () => {
86
+ const km = await makeKeys();
87
+ const host: HostCapabilities = {
88
+ ...baseHost(km),
89
+ getPublicKey: async () => { throw new Error("key unavailable"); },
90
+ };
91
+ await assert.rejects(
92
+ Constructor.initialize({ host }),
93
+ /preflight failed/,
94
+ );
95
+ });
96
+
97
+ test("rejects requireCounter policy when host has no nextCounter", async () => {
98
+ const km = await makeKeys();
99
+ await assert.rejects(
100
+ Constructor.initialize({ host: baseHost(km), policy: { requireCounter: true } }),
101
+ /nextCounter/,
102
+ );
103
+ });
104
+
105
+ test("rejects requireTime policy when host has no secureTime", async () => {
106
+ const km = await makeKeys();
107
+ await assert.rejects(
108
+ Constructor.initialize({ host: baseHost(km), policy: { requireTime: true } }),
109
+ /secureTime/,
110
+ );
111
+ });
112
+
113
+ test("accepts requireCounter policy when host has nextCounter", async () => {
114
+ const km = await makeKeys();
115
+ const ctor = await Constructor.initialize({
116
+ host: hostWithCounter(km),
117
+ policy: { requireCounter: true },
118
+ });
119
+ assert.ok(ctor instanceof Constructor);
120
+ });
121
+
122
+ test("accepts requireTime policy when host has secureTime", async () => {
123
+ const km = await makeKeys();
124
+ const ctor = await Constructor.initialize({
125
+ host: hostWithTime(km, Date.now()),
126
+ policy: { requireTime: true },
127
+ });
128
+ assert.ok(ctor instanceof Constructor);
129
+ });
130
+ });
131
+
132
+ // ---------------------------------------------------------------------------
133
+ // Constructor.commit
134
+ // ---------------------------------------------------------------------------
135
+
136
+ describe("Constructor.commit", () => {
137
+ test("returns a structurally valid BitGraphProof", async () => {
138
+ const km = await makeKeys();
139
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
140
+ const bytes = new TextEncoder().encode("hello bitgraph");
141
+ const proof = await ctor.commit({ bytes });
142
+
143
+ assert.equal(proof.version, "bitgraph/1");
144
+ assert.equal(proof.artifact.hashAlg, "sha256");
145
+ assert.ok(typeof proof.artifact.digestB64 === "string" && proof.artifact.digestB64.length > 0);
146
+ assert.ok(typeof proof.commit.nonceB64 === "string" && proof.commit.nonceB64.length > 0);
147
+ assert.equal(proof.signer.publicKeyB64, km.publicKeyB64);
148
+ assert.ok(typeof proof.signer.signatureB64 === "string" && proof.signer.signatureB64.length > 0);
149
+ assert.equal(proof.environment.enforcement, "stub");
150
+ assert.equal(proof.environment.measurement, "test-measurement-cafebabe");
151
+ });
152
+
153
+ test("works with empty bytes", async () => {
154
+ const km = await makeKeys();
155
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
156
+ const proof = await ctor.commit({ bytes: new Uint8Array(0) });
157
+ assert.equal(proof.version, "bitgraph/1");
158
+ assert.ok(proof.artifact.digestB64.length > 0);
159
+ });
160
+
161
+ test("works with large bytes (100 KB)", async () => {
162
+ const km = await makeKeys();
163
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
164
+ // crypto.getRandomValues is limited to 65536 bytes; use fill instead
165
+ const bytes = new Uint8Array(100_000).fill(0xab);
166
+ const proof = await ctor.commit({ bytes });
167
+ assert.equal(proof.version, "bitgraph/1");
168
+ });
169
+
170
+ test("includes metadata when provided (outside signature)", async () => {
171
+ const km = await makeKeys();
172
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
173
+ const proof = await ctor.commit({
174
+ bytes: new Uint8Array([1, 2, 3]),
175
+ metadata: { source: "test-suite" },
176
+ });
177
+ assert.deepEqual(proof.metadata, { source: "test-suite" });
178
+ });
179
+
180
+ test("omits metadata field when not provided", async () => {
181
+ const km = await makeKeys();
182
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
183
+ const proof = await ctor.commit({ bytes: new Uint8Array([1]) });
184
+ assert.equal(proof.metadata, undefined);
185
+ });
186
+
187
+ test("includes counter when host provides nextCounter", async () => {
188
+ const km = await makeKeys();
189
+ const ctor = await Constructor.initialize({ host: hostWithCounter(km) });
190
+ const proof = await ctor.commit({ bytes: new Uint8Array([1]) });
191
+ assert.ok(typeof proof.commit.counter === "string");
192
+ assert.equal(proof.commit.counter, "1");
193
+ });
194
+
195
+ test("counter increments across commits", async () => {
196
+ const km = await makeKeys();
197
+ const ctor = await Constructor.initialize({ host: hostWithCounter(km) });
198
+ const p1 = await ctor.commit({ bytes: new Uint8Array([1]) });
199
+ const p2 = await ctor.commit({ bytes: new Uint8Array([2]) });
200
+ assert.equal(p1.commit.counter, "1");
201
+ assert.equal(p2.commit.counter, "2");
202
+ });
203
+
204
+ test("includes time when host provides secureTime", async () => {
205
+ const km = await makeKeys();
206
+ const fixedTime = 1_700_000_000_000;
207
+ const ctor = await Constructor.initialize({ host: hostWithTime(km, fixedTime) });
208
+ const proof = await ctor.commit({ bytes: new Uint8Array([1]) });
209
+ assert.equal(proof.commit.time, fixedTime);
210
+ });
211
+
212
+ test("includes prevB64 when provided", async () => {
213
+ const km = await makeKeys();
214
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
215
+ const prevHash = Buffer.alloc(32).toString("base64");
216
+ const proof = await ctor.commit({
217
+ bytes: new Uint8Array([1]),
218
+ prevProofHashB64: prevHash,
219
+ });
220
+ assert.equal(proof.commit.prevB64, prevHash);
221
+ });
222
+
223
+ test("includes epochId when Constructor was initialized with one", async () => {
224
+ const km = await makeKeys();
225
+ const epochId = "epoch-abc-123";
226
+ const ctor = await Constructor.initialize({ host: baseHost(km), epochId });
227
+ const proof = await ctor.commit({ bytes: new Uint8Array([1]) });
228
+ assert.equal(proof.commit.epochId, epochId);
229
+ });
230
+
231
+ test("omits epochId when not provided at initialization", async () => {
232
+ const km = await makeKeys();
233
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
234
+ const proof = await ctor.commit({ bytes: new Uint8Array([1]) });
235
+ assert.equal(proof.commit.epochId, undefined);
236
+ });
237
+
238
+ test("each commit has a unique nonce", async () => {
239
+ const km = await makeKeys();
240
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
241
+ const p1 = await ctor.commit({ bytes: new Uint8Array([1]) });
242
+ const p2 = await ctor.commit({ bytes: new Uint8Array([1]) });
243
+ assert.notEqual(p1.commit.nonceB64, p2.commit.nonceB64);
244
+ });
245
+
246
+ test("fail-closed: throws when sign() rejects (no partial proof)", async () => {
247
+ const km = await makeKeys();
248
+ const badSignHost: HostCapabilities = {
249
+ enforcementTier: "stub" as const,
250
+ getMeasurement: async () => "meas",
251
+ getFreshNonce: async () => crypto.getRandomValues(new Uint8Array(16)),
252
+ sign: async () => { throw new Error("HSM offline"); },
253
+ getPublicKey: async () => km.publicKeyBytes,
254
+ };
255
+ const ctor = await Constructor.initialize({ host: badSignHost });
256
+ await assert.rejects(
257
+ ctor.commit({ bytes: new Uint8Array([1]) }),
258
+ /host\.sign\(\) rejected/,
259
+ );
260
+ });
261
+
262
+ test("throws when nonce is too short", async () => {
263
+ const km = await makeKeys();
264
+ const shortNonceHost: HostCapabilities = {
265
+ ...baseHost(km),
266
+ getFreshNonce: async () => new Uint8Array(8), // < 16 bytes required
267
+ };
268
+ const ctor = await Constructor.initialize({ host: shortNonceHost });
269
+ await assert.rejects(
270
+ ctor.commit({ bytes: new Uint8Array([1]) }),
271
+ /insufficient length/,
272
+ );
273
+ });
274
+
275
+ test("two commits to same bytes produce different proofs (nonce)", async () => {
276
+ const km = await makeKeys();
277
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
278
+ const bytes = new Uint8Array([42, 43, 44]);
279
+ const p1 = await ctor.commit({ bytes });
280
+ const p2 = await ctor.commit({ bytes });
281
+ assert.equal(p1.artifact.digestB64, p2.artifact.digestB64); // same digest
282
+ assert.notEqual(p1.signer.signatureB64, p2.signer.signatureB64); // different signature
283
+ });
284
+ });
285
+
286
+ // ---------------------------------------------------------------------------
287
+ // Constructor.commitDigest
288
+ // ---------------------------------------------------------------------------
289
+
290
+ describe("Constructor.commitDigest", () => {
291
+ test("returns a valid proof given a correct 32-byte base64 digest", async () => {
292
+ const km = await makeKeys();
293
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
294
+ // SHA-256 of empty bytes
295
+ const digest = Buffer.alloc(32, 0xab).toString("base64");
296
+ const proof = await ctor.commitDigest({ digestB64: digest });
297
+ assert.equal(proof.version, "bitgraph/1");
298
+ assert.equal(proof.artifact.digestB64, digest);
299
+ });
300
+
301
+ test("throws for invalid base64", async () => {
302
+ const km = await makeKeys();
303
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
304
+ await assert.rejects(
305
+ ctor.commitDigest({ digestB64: "not-valid-base64!!!" }),
306
+ /base64/i,
307
+ );
308
+ });
309
+
310
+ test("throws when digest decodes to != 32 bytes", async () => {
311
+ const km = await makeKeys();
312
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
313
+ // 16 bytes, valid base64, but not 32 bytes
314
+ const shortDigest = Buffer.alloc(16).toString("base64");
315
+ await assert.rejects(
316
+ ctor.commitDigest({ digestB64: shortDigest }),
317
+ /32/,
318
+ );
319
+ });
320
+
321
+ test("throws for empty string digest", async () => {
322
+ const km = await makeKeys();
323
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
324
+ await assert.rejects(
325
+ ctor.commitDigest({ digestB64: "" }),
326
+ /non-empty|base64/i,
327
+ );
328
+ });
329
+
330
+ test("includes metadata when provided", async () => {
331
+ const km = await makeKeys();
332
+ const ctor = await Constructor.initialize({ host: baseHost(km) });
333
+ const digest = Buffer.alloc(32, 0x77).toString("base64");
334
+ const proof = await ctor.commitDigest({
335
+ digestB64: digest,
336
+ metadata: { mode: "digest-only" },
337
+ });
338
+ assert.deepEqual(proof.metadata, { mode: "digest-only" });
339
+ });
340
+ });
@@ -0,0 +1,10 @@
1
+ // Copyright (c) Mike Argento. All rights reserved. See LICENSE.
2
+
3
+ import { describe, test } from "node:test";
4
+ import * as assert from "node:assert/strict";
5
+
6
+ describe("hello world", () => {
7
+ test("passes", () => {
8
+ assert.strictEqual("hello world", "hello world");
9
+ });
10
+ });
@@ -0,0 +1,226 @@
1
+ // Copyright (c) Mike Argento. All rights reserved. See LICENSE.
2
+ // End-to-end test for the BitGraph policy enforcement pipeline.
3
+
4
+ import { test, describe } from "node:test";
5
+ import * as assert from "node:assert/strict";
6
+ import { tmpdir } from "node:os";
7
+ import { mkdirSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { Constructor } from "../constructor.js";
10
+ import { canonicalize } from "../index.js";
11
+ import { hashPolicy, createPolicyBinding } from "../policy.js";
12
+ import { sha256 } from "@noble/hashes/sha256";
13
+
14
+ // Inline stub host for test isolation — dynamic import avoids tsc dist conflicts
15
+ async function createTestHost(statePath: string) {
16
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
17
+ const mod = await import("bitgraph-stub" as string) as any;
18
+ const StubHost = mod.StubHost ?? mod.default?.StubHost;
19
+ return StubHost.createPersistent({
20
+ statePath,
21
+ measurement: "test",
22
+ enableTime: true,
23
+ enableCounter: true,
24
+ });
25
+ }
26
+
27
+ const TEST_POLICY = `# Policy: Test Policy
28
+ version: 2.0
29
+
30
+ ## Allowed Tools
31
+ - search
32
+ - read_file
33
+
34
+ ## Limits
35
+ - max_actions: 100
36
+ - rate_limit: 10/min
37
+ `;
38
+
39
+ const TEST_POLICY_REVOKED = `# Policy: Test Policy Revoked
40
+ version: 3.0
41
+
42
+ ## Allowed Tools
43
+ - search
44
+
45
+ ## Limits
46
+ - max_actions: 50
47
+ `;
48
+
49
+ describe("Policy Enforcement Pipeline", () => {
50
+ test("policy binding is created from markdown", () => {
51
+ const binding = createPolicyBinding(TEST_POLICY);
52
+ assert.ok(binding.digestB64, "should have digestB64");
53
+ assert.equal(binding.name, "Test Policy");
54
+ assert.equal(binding.version, "2.0");
55
+ });
56
+
57
+ test("policy committed as slot 0 with binding in proof", async () => {
58
+ const testDir = join(tmpdir(), `bitgraph-test-${Date.now()}`);
59
+ mkdirSync(testDir, { recursive: true });
60
+
61
+ const stub = await createTestHost(join(testDir, "state.json"));
62
+
63
+ const constructor = await Constructor.initialize({
64
+ host: stub.host,
65
+ policy: { requireCounter: true, requireTime: true },
66
+ });
67
+
68
+ const binding = createPolicyBinding(TEST_POLICY);
69
+ const policyDigest = hashPolicy(TEST_POLICY);
70
+
71
+ const policyProof = await constructor.commitDigest({
72
+ digestB64: policyDigest,
73
+ metadata: { kind: "policy-commitment", policyName: binding.name },
74
+ policy: binding,
75
+ });
76
+
77
+ assert.ok(policyProof, "should return a proof");
78
+ assert.equal(policyProof.commit.counter, "1");
79
+ assert.ok(policyProof.policy, "proof should have policy field");
80
+ assert.equal(policyProof.policy!.digestB64, policyDigest);
81
+ assert.equal(policyProof.policy!.name, "Test Policy");
82
+
83
+ const proofHash = Buffer.from(sha256(canonicalize(policyProof))).toString("base64");
84
+ binding.authorProofDigestB64 = proofHash;
85
+ assert.ok(binding.authorProofDigestB64);
86
+ });
87
+
88
+ test("action proofs carry the policy binding", async () => {
89
+ const testDir = join(tmpdir(), `bitgraph-test-${Date.now()}`);
90
+ mkdirSync(testDir, { recursive: true });
91
+
92
+ const stub = await createTestHost(join(testDir, "state.json"));
93
+
94
+ const constructor = await Constructor.initialize({
95
+ host: stub.host,
96
+ policy: { requireCounter: true, requireTime: true },
97
+ });
98
+
99
+ const binding = createPolicyBinding(TEST_POLICY);
100
+ const policyDigest = hashPolicy(TEST_POLICY);
101
+
102
+ const policyProof = await constructor.commitDigest({
103
+ digestB64: policyDigest,
104
+ metadata: { kind: "policy-commitment" },
105
+ policy: binding,
106
+ });
107
+
108
+ const proofHash = Buffer.from(sha256(canonicalize(policyProof))).toString("base64");
109
+ binding.authorProofDigestB64 = proofHash;
110
+
111
+ const actionDigest = Buffer.from(sha256(new TextEncoder().encode("search:query"))).toString("base64");
112
+ const actionProof = await constructor.commitDigest({
113
+ digestB64: actionDigest,
114
+ metadata: { kind: "tool-execution", tool: "search" },
115
+ prevProofHashB64: proofHash,
116
+ policy: binding,
117
+ });
118
+
119
+ assert.ok(actionProof.policy, "action proof should have policy");
120
+ assert.equal(actionProof.policy!.digestB64, policyDigest);
121
+ assert.equal(actionProof.policy!.authorProofDigestB64, proofHash);
122
+ assert.equal(actionProof.commit.counter, "2");
123
+ });
124
+
125
+ test("policy revocation updates binding", async () => {
126
+ const testDir = join(tmpdir(), `bitgraph-test-${Date.now()}`);
127
+ mkdirSync(testDir, { recursive: true });
128
+
129
+ const stub = await createTestHost(join(testDir, "state.json"));
130
+
131
+ const constructor = await Constructor.initialize({
132
+ host: stub.host,
133
+ policy: { requireCounter: true, requireTime: true },
134
+ });
135
+
136
+ // Slot 0: original policy
137
+ const originalBinding = createPolicyBinding(TEST_POLICY);
138
+ const originalDigest = hashPolicy(TEST_POLICY);
139
+
140
+ const slot0Proof = await constructor.commitDigest({
141
+ digestB64: originalDigest,
142
+ metadata: { kind: "policy-commitment" },
143
+ policy: originalBinding,
144
+ });
145
+ const slot0Hash = Buffer.from(sha256(canonicalize(slot0Proof))).toString("base64");
146
+ originalBinding.authorProofDigestB64 = slot0Hash;
147
+
148
+ // Action under original policy
149
+ const action1 = await constructor.commitDigest({
150
+ digestB64: Buffer.from(sha256(new TextEncoder().encode("action1"))).toString("base64"),
151
+ metadata: { kind: "tool-execution", tool: "read_file" },
152
+ prevProofHashB64: slot0Hash,
153
+ policy: originalBinding,
154
+ });
155
+ assert.equal(action1.policy!.digestB64, originalDigest);
156
+
157
+ // Revoke: commit new policy
158
+ const revokedBinding = createPolicyBinding(TEST_POLICY_REVOKED);
159
+ const revokedDigest = hashPolicy(TEST_POLICY_REVOKED);
160
+
161
+ const action1Hash = Buffer.from(sha256(canonicalize(action1))).toString("base64");
162
+ const revokeProof = await constructor.commitDigest({
163
+ digestB64: revokedDigest,
164
+ metadata: { kind: "policy-change", removed: ["read_file"] },
165
+ prevProofHashB64: action1Hash,
166
+ policy: revokedBinding,
167
+ });
168
+ const revokeHash = Buffer.from(sha256(canonicalize(revokeProof))).toString("base64");
169
+ revokedBinding.authorProofDigestB64 = revokeHash;
170
+
171
+ // Action under new (revoked) policy
172
+ const action2 = await constructor.commitDigest({
173
+ digestB64: Buffer.from(sha256(new TextEncoder().encode("action2"))).toString("base64"),
174
+ metadata: { kind: "tool-execution", tool: "search" },
175
+ prevProofHashB64: revokeHash,
176
+ policy: revokedBinding,
177
+ });
178
+
179
+ assert.equal(action2.policy!.digestB64, revokedDigest);
180
+ assert.equal(action2.policy!.authorProofDigestB64, revokeHash);
181
+ assert.notEqual(action2.policy!.digestB64, originalDigest);
182
+ });
183
+
184
+ test("causal ordering: policy counter < action counter", async () => {
185
+ const testDir = join(tmpdir(), `bitgraph-test-${Date.now()}`);
186
+ mkdirSync(testDir, { recursive: true });
187
+
188
+ const stub = await createTestHost(join(testDir, "state.json"));
189
+
190
+ const constructor = await Constructor.initialize({
191
+ host: stub.host,
192
+ policy: { requireCounter: true, requireTime: true },
193
+ });
194
+
195
+ const binding = createPolicyBinding(TEST_POLICY);
196
+
197
+ const policyProof = await constructor.commitDigest({
198
+ digestB64: hashPolicy(TEST_POLICY),
199
+ metadata: { kind: "policy-commitment" },
200
+ policy: binding,
201
+ });
202
+ const policyCounter = BigInt(policyProof.commit.counter ?? "0");
203
+
204
+ const proofHash = Buffer.from(sha256(canonicalize(policyProof))).toString("base64");
205
+ binding.authorProofDigestB64 = proofHash;
206
+
207
+ for (let i = 1; i <= 3; i++) {
208
+ const actionProof = await constructor.commitDigest({
209
+ digestB64: Buffer.from(sha256(new TextEncoder().encode(`action-${i}`))).toString("base64"),
210
+ metadata: { kind: "tool-execution", tool: "search" },
211
+ policy: binding,
212
+ });
213
+ const actionCounter = BigInt(actionProof.commit.counter ?? "0");
214
+ assert.ok(actionCounter > policyCounter, `action ${i} counter (${actionCounter}) > policy counter (${policyCounter})`);
215
+ }
216
+ });
217
+
218
+ test("hashPolicy produces consistent digest", () => {
219
+ const digest1 = hashPolicy(TEST_POLICY);
220
+ const digest2 = hashPolicy(TEST_POLICY);
221
+ assert.equal(digest1, digest2);
222
+
223
+ const digest3 = hashPolicy(TEST_POLICY_REVOKED);
224
+ assert.notEqual(digest1, digest3);
225
+ });
226
+ });