@tpsdev-ai/agent 0.8.0 → 0.9.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 (133) hide show
  1. package/bun.lock +27 -15
  2. package/dist/bin.js +4 -3
  3. package/dist/bin.js.map +1 -1
  4. package/dist/config.d.ts +8 -1
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/config.js +38 -3
  7. package/dist/config.js.map +1 -1
  8. package/dist/home.d.ts +3 -0
  9. package/dist/home.d.ts.map +1 -0
  10. package/dist/home.js +18 -0
  11. package/dist/home.js.map +1 -0
  12. package/dist/index.d.ts +16 -3
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +12 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/io/flair.d.ts +1 -10
  17. package/dist/io/flair.d.ts.map +1 -1
  18. package/dist/io/flair.js +29 -28
  19. package/dist/io/flair.js.map +1 -1
  20. package/dist/io/mail.d.ts +184 -30
  21. package/dist/io/mail.d.ts.map +1 -1
  22. package/dist/io/mail.js +944 -185
  23. package/dist/io/mail.js.map +1 -1
  24. package/dist/lib/agent-keys.d.ts +106 -0
  25. package/dist/lib/agent-keys.d.ts.map +1 -0
  26. package/dist/lib/agent-keys.js +298 -0
  27. package/dist/lib/agent-keys.js.map +1 -0
  28. package/dist/lib/bridge-identity.d.ts +10 -0
  29. package/dist/lib/bridge-identity.d.ts.map +1 -0
  30. package/dist/lib/bridge-identity.js +56 -0
  31. package/dist/lib/bridge-identity.js.map +1 -0
  32. package/dist/lib/mail-lock-namespace.d.ts +19 -0
  33. package/dist/lib/mail-lock-namespace.d.ts.map +1 -0
  34. package/dist/lib/mail-lock-namespace.js +58 -0
  35. package/dist/lib/mail-lock-namespace.js.map +1 -0
  36. package/dist/lib/mail-lock.d.ts +81 -0
  37. package/dist/lib/mail-lock.d.ts.map +1 -0
  38. package/dist/lib/mail-lock.js +319 -0
  39. package/dist/lib/mail-lock.js.map +1 -0
  40. package/dist/lib/mailbox-filename.d.ts +2 -0
  41. package/dist/lib/mailbox-filename.d.ts.map +1 -0
  42. package/dist/lib/mailbox-filename.js +4 -0
  43. package/dist/lib/mailbox-filename.js.map +1 -0
  44. package/dist/lib/mailbox-policy.d.ts +245 -0
  45. package/dist/lib/mailbox-policy.d.ts.map +1 -0
  46. package/dist/lib/mailbox-policy.js +949 -0
  47. package/dist/lib/mailbox-policy.js.map +1 -0
  48. package/dist/lib/public-key.d.ts +6 -0
  49. package/dist/lib/public-key.d.ts.map +1 -0
  50. package/dist/lib/public-key.js +45 -0
  51. package/dist/lib/public-key.js.map +1 -0
  52. package/dist/lib/registry-key.d.ts +2 -0
  53. package/dist/lib/registry-key.d.ts.map +1 -0
  54. package/dist/lib/registry-key.js +10 -0
  55. package/dist/lib/registry-key.js.map +1 -0
  56. package/dist/lib/relay-lock.d.ts +7 -0
  57. package/dist/lib/relay-lock.d.ts.map +1 -0
  58. package/dist/lib/relay-lock.js +19 -0
  59. package/dist/lib/relay-lock.js.map +1 -0
  60. package/dist/lib/signEnvelope.d.ts +2 -0
  61. package/dist/lib/signEnvelope.d.ts.map +1 -1
  62. package/dist/lib/signEnvelope.js.map +1 -1
  63. package/dist/lib/signing-key.d.ts +2 -0
  64. package/dist/lib/signing-key.d.ts.map +1 -0
  65. package/dist/lib/signing-key.js +9 -0
  66. package/dist/lib/signing-key.js.map +1 -0
  67. package/dist/lib/topic-recipient.d.ts +2 -0
  68. package/dist/lib/topic-recipient.d.ts.map +1 -0
  69. package/dist/lib/topic-recipient.js +2 -0
  70. package/dist/lib/topic-recipient.js.map +1 -0
  71. package/dist/llm/provider.d.ts.map +1 -1
  72. package/dist/llm/provider.js +9 -7
  73. package/dist/llm/provider.js.map +1 -1
  74. package/dist/runtime/agent.d.ts.map +1 -1
  75. package/dist/runtime/agent.js +32 -25
  76. package/dist/runtime/agent.js.map +1 -1
  77. package/dist/runtime/event-loop.d.ts +21 -2
  78. package/dist/runtime/event-loop.d.ts.map +1 -1
  79. package/dist/runtime/event-loop.js +199 -54
  80. package/dist/runtime/event-loop.js.map +1 -1
  81. package/dist/runtime/types.d.ts +11 -0
  82. package/dist/runtime/types.d.ts.map +1 -1
  83. package/dist/runtime/types.js +13 -1
  84. package/dist/runtime/types.js.map +1 -1
  85. package/package.json +2 -3
  86. package/src/bin.ts +4 -3
  87. package/src/config.ts +46 -3
  88. package/src/home.ts +18 -0
  89. package/src/index.ts +33 -2
  90. package/src/io/flair.ts +23 -28
  91. package/src/io/mail.ts +1007 -200
  92. package/src/lib/agent-keys.ts +308 -0
  93. package/src/lib/bridge-identity.ts +49 -0
  94. package/src/lib/mail-lock-namespace.ts +64 -0
  95. package/src/lib/mail-lock.ts +337 -0
  96. package/src/lib/mailbox-filename.ts +3 -0
  97. package/src/lib/mailbox-policy.ts +1085 -0
  98. package/src/lib/public-key.ts +49 -0
  99. package/src/lib/registry-key.ts +8 -0
  100. package/src/lib/relay-lock.ts +20 -0
  101. package/src/lib/signEnvelope.ts +2 -0
  102. package/src/lib/signing-key.ts +8 -0
  103. package/src/lib/topic-recipient.ts +1 -0
  104. package/src/llm/provider.ts +9 -7
  105. package/src/runtime/agent.ts +30 -27
  106. package/src/runtime/event-loop.ts +221 -68
  107. package/src/runtime/types.ts +14 -0
  108. package/test/config.test.ts +85 -2
  109. package/test/core-loop.test.ts +6 -4
  110. package/test/governance.test.ts +4 -1
  111. package/test/helpers/event-loop-child.mjs +50 -0
  112. package/test/helpers/mail-delivery-worker.mjs +16 -0
  113. package/test/helpers/mail-kill-child.mjs +104 -0
  114. package/test/helpers/signed-relay-record.ts +31 -0
  115. package/test/home-per-call.test.ts +72 -0
  116. package/test/io.test.ts +81 -14
  117. package/test/mail-client-lock-namespace.test.ts +155 -0
  118. package/test/mail-client-repoint-root.test.ts +368 -0
  119. package/test/mail-delivery-at-least-once.test.ts +1238 -0
  120. package/test/mail-event-loop-delivery.test.ts +769 -0
  121. package/test/mail-intent-phases.test.ts +304 -0
  122. package/test/mail-interrupted-recovery.test.ts +393 -0
  123. package/test/mail-lock-pid-state.test.ts +238 -0
  124. package/test/mail-lock.test.ts +96 -0
  125. package/test/mail-partial-flair.test.ts +102 -0
  126. package/test/mail-placement-replay.test.ts +116 -0
  127. package/test/mail-promote-guard.test.ts +305 -21
  128. package/test/mail-relay-reservation.test.ts +60 -0
  129. package/test/mailbox-filename.test.ts +16 -0
  130. package/test/public-key.test.ts +108 -0
  131. package/test/runtime-key-encoding.test.ts +105 -0
  132. package/test/runtime-pending-key.test.ts +117 -0
  133. package/test/security/mail-trust.test.ts +406 -109
@@ -16,15 +16,19 @@
16
16
  * `.reason` sidecar. Both defects are RED at 545e23cd and GREEN after.
17
17
  */
18
18
 
19
- import { describe, test, expect, beforeEach, afterEach } from "bun:test";
19
+ import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test";
20
+ import * as fs from "node:fs";
20
21
  import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync, readdirSync, mkdirSync } from "node:fs";
21
22
  import { join } from "node:path";
22
23
  import { tmpdir } from "node:os";
23
- import { randomUUID } from "node:crypto";
24
+ import { generateKeyPairSync, randomUUID } from "node:crypto";
24
25
  import * as ed from "@noble/ed25519";
25
26
  import { signEnvelope, type Envelope, type ChainEntry, type FlairClient } from "../src/lib/signEnvelope.js";
27
+ import { parseFlairPublicKey } from "../src/lib/public-key.js";
26
28
  import { FlairContextProvider } from "../src/io/flair.js";
27
29
  import { MailClient } from "../src/io/mail.js";
30
+ import { acquireMailLockSync } from "../src/lib/mail-lock.js";
31
+ import { mailboxReplayStore } from "../src/lib/mailbox-policy.js";
28
32
 
29
33
  const AGENT = "mailbox";
30
34
 
@@ -62,7 +66,7 @@ function providerVerifier(provider: FlairContextProvider): FlairClient {
62
66
  async getAgent(name: string) {
63
67
  const a = await provider.getAgent(name);
64
68
  if (!a) return null;
65
- return { publicKey: Buffer.from(a.publicKey, "hex") };
69
+ return { publicKey: parseFlairPublicKey(a.publicKey) };
66
70
  },
67
71
  };
68
72
  }
@@ -113,17 +117,84 @@ describe("agent MailClient promotion is fail-closed (cli#380 F1)", () => {
113
117
  writeFileSync(join(inbox("new"), name), JSON.stringify(wrapperObj), "utf-8");
114
118
  };
115
119
 
120
+ for (const method of ["checkNewMail", "deliverNext"] as const) {
121
+ test(`${method} leaves a dot-file beside a promoted message (cli#870)`, async () => {
122
+ const env = signedEnvelope("flint", AGENT, "hello", { flint: FLINT });
123
+ plant(wrapper("flint", env));
124
+ const scratch = join(inbox("new"), ".x.json");
125
+ writeFileSync(scratch, "{ not mail");
126
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
127
+
128
+ if (method === "checkNewMail") {
129
+ expect((await client.checkNewMail()).map((message) => message.filename)).toEqual(["m1.json"]);
130
+ } else {
131
+ const result = await client.deliverNext();
132
+ expect(result.status).toBe("delivered");
133
+ }
134
+
135
+ expect(readdirSync(inbox("new"))).toEqual([".x.json"]);
136
+ expect(readFileSync(scratch, "utf8")).toBe("{ not mail");
137
+ expect(files("cur")).toEqual(["m1.json"]);
138
+ expect(files("dlq")).toEqual([]);
139
+ });
140
+ }
141
+
116
142
  // ── F1 defect 1: verification was optional (no client ⇒ unverified promote) ─
117
- test("NO verifier: refuses to promote — the record stays in new/", async () => {
143
+ test("NO verifier: construction throws", () => {
144
+ expect(() => new MailClient(tmpDir, undefined, AGENT)).toThrow(/requires a Flair verifier/);
145
+ });
146
+
147
+ test("a pending placement with matching new/ and cur/ links is delivered", async () => {
148
+ const env = signedEnvelope("flint", AGENT, "hello", { flint: FLINT });
149
+ plant(wrapper("flint", env));
150
+ mkdirSync(inbox("cur"), { recursive: true });
151
+ const lock = acquireMailLockSync(join(tmpDir, AGENT));
152
+ if (!lock) throw new Error("lock unavailable");
153
+ try {
154
+ fs.linkSync(join(inbox("new"), "m1.json"), join(inbox("cur"), "m1.json"));
155
+ mailboxReplayStore(join(tmpDir, AGENT)).beginPlacement(env.messageId, "m1.json", join(inbox("cur"), "m1.json"));
156
+ } finally { lock.release(); }
157
+
158
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
159
+ const first = await client.checkNewMail();
160
+ const second = await client.checkNewMail();
161
+
162
+ expect(first.length + second.length).toBe(1);
163
+ expect(files("new")).toEqual([]);
164
+ });
165
+
166
+ test("a cur/ entry that is a different file with the same name is refused, not completed", async () => {
118
167
  const env = signedEnvelope("flint", AGENT, "hello", { flint: FLINT });
119
168
  plant(wrapper("flint", env));
169
+ mkdirSync(inbox("cur"), { recursive: true });
170
+ writeFileSync(join(inbox("cur"), "m1.json"), readFileSync(join(inbox("new"), "m1.json")));
120
171
 
121
- const client = new MailClient(tmpDir, undefined, AGENT); // no flairClient
172
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
122
173
  const msgs = await client.checkNewMail();
123
174
 
124
175
  expect(msgs.length).toBe(0);
125
- expect(files("new")).toContain("m1.json"); // untouched
126
- expect(files("cur").length).toBe(0); // never promoted
176
+ expect(files("cur")).toEqual(["m1.json"]);
177
+ expect(readFileSync(join(inbox("dlq"), "m1.json.reason"), "utf-8")).toContain("class: replay");
178
+ });
179
+
180
+ test("a pending linked placement is completed across two checks", async () => {
181
+ const env = signedEnvelope("flint", AGENT, "hello", { flint: FLINT });
182
+ plant(wrapper("flint", env));
183
+ mkdirSync(inbox("cur"), { recursive: true });
184
+ const lock = acquireMailLockSync(join(tmpDir, AGENT));
185
+ if (!lock) throw new Error("lock unavailable");
186
+ try {
187
+ fs.linkSync(join(inbox("new"), "m1.json"), join(inbox("cur"), "m1.json"));
188
+ mailboxReplayStore(join(tmpDir, AGENT)).beginPlacement(env.messageId, "m1.json", join(inbox("cur"), "m1.json"));
189
+ } finally { lock.release(); }
190
+
191
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
192
+ const first = await client.checkNewMail();
193
+ const second = await client.checkNewMail();
194
+
195
+ expect(first.length + second.length).toBe(1);
196
+ expect(files("new")).toEqual([]);
197
+ expect(files("cur")).toEqual(["m1.json"]);
127
198
  });
128
199
 
129
200
  // ── F1 defect 2: the verifier throw was swallowed and treated as a pass ────
@@ -208,12 +279,12 @@ describe("agent MailClient promotion is fail-closed (cli#380 F1)", () => {
208
279
  });
209
280
 
210
281
  // ── The refusal is non-destructive: a later verifier promotes the same file ─
211
- test("a record refused without a verifier is promoted once a verifier is present", async () => {
282
+ test("a record a verifier could not run on is promoted once verification can run", async () => {
212
283
  const env = signedEnvelope("flint", AGENT, "heal me", { flint: FLINT });
213
284
  plant(wrapper("flint", env));
214
285
 
215
- const noVerifier = new MailClient(tmpDir, undefined, AGENT);
216
- expect((await noVerifier.checkNewMail()).length).toBe(0);
286
+ const unreachable = new MailClient(tmpDir, undefined, AGENT, throwingFlair);
287
+ expect((await unreachable.checkNewMail()).length).toBe(0);
217
288
  expect(files("new")).toContain("m1.json");
218
289
 
219
290
  const withVerifier = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
@@ -228,12 +299,9 @@ describe("agent MailClient promotion is fail-closed (cli#380 F1)", () => {
228
299
  const env = signedEnvelope("flint", AGENT, "during outage", { flint: FLINT });
229
300
  plant(wrapper("flint", env));
230
301
 
231
- // Real provider against a dead endpoint. getAgent() swallows the connection
232
- // error to null; the verifier must probe /Health to tell "absent" from "down".
233
- const provider = new FlairContextProvider(AGENT, {
234
- url: "http://127.0.0.1:1",
235
- keyPath: join(tmpDir, "no-key"),
236
- });
302
+ const keyPath = join(tmpDir, "reader.key");
303
+ writeFileSync(keyPath, generateKeyPairSync("ed25519").privateKey.export({ type: "pkcs8", format: "pem" }));
304
+ const provider = new FlairContextProvider(AGENT, { url: "http://127.0.0.1:1", keyPath });
237
305
  const client = new MailClient(tmpDir, undefined, AGENT, providerVerifier(provider));
238
306
  const msgs = await client.checkNewMail();
239
307
 
@@ -243,7 +311,6 @@ describe("agent MailClient promotion is fail-closed (cli#380 F1)", () => {
243
311
  });
244
312
 
245
313
  test("a REACHABLE Flair that does not know the principal IS terminal (unresolvable-principal)", async () => {
246
- // Control for the disambiguation: the SAME null from getAgent, but /Health is up.
247
314
  const server = Bun.serve({
248
315
  port: 0,
249
316
  fetch(req) {
@@ -255,10 +322,9 @@ describe("agent MailClient promotion is fail-closed (cli#380 F1)", () => {
255
322
  try {
256
323
  const env = signedEnvelope("flint", AGENT, "absent", { flint: FLINT });
257
324
  plant(wrapper("flint", env));
258
- const provider = new FlairContextProvider(AGENT, {
259
- url: server.url.href,
260
- keyPath: join(tmpDir, "no-key"),
261
- });
325
+ const keyPath = join(tmpDir, "reader.key");
326
+ writeFileSync(keyPath, generateKeyPairSync("ed25519").privateKey.export({ type: "pkcs8", format: "pem" }));
327
+ const provider = new FlairContextProvider(AGENT, { url: server.url.href, keyPath });
262
328
  const client = new MailClient(tmpDir, undefined, AGENT, providerVerifier(provider));
263
329
  const msgs = await client.checkNewMail();
264
330
 
@@ -311,6 +377,206 @@ describe("agent MailClient promotion is fail-closed (cli#380 F1)", () => {
311
377
  expect(readFileSync(join(inbox("dlq"), "m1.json.reason"), "utf-8")).toContain("class: invalid");
312
378
  });
313
379
 
380
+ test("a messageId outside the shared id rule is rejected (invalid)", async () => {
381
+ const env = signedEnvelope("flint", AGENT, "bad id", { flint: FLINT }, { messageId: "has a space\n" });
382
+ plant(wrapper("flint", env));
383
+
384
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
385
+ expect((await client.checkNewMail()).length).toBe(0);
386
+ expect(files("cur").length).toBe(0);
387
+ expect(readFileSync(join(inbox("dlq"), "m1.json.reason"), "utf-8")).toContain("invalid messageId");
388
+ });
389
+
390
+ test("a replyToId outside the shared id rule is rejected (invalid)", async () => {
391
+ const env = signedEnvelope("flint", AGENT, "bad reply", { flint: FLINT }, { replyToId: "../../etc" });
392
+ plant(wrapper("flint", env));
393
+
394
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
395
+ expect((await client.checkNewMail()).length).toBe(0);
396
+ expect(files("cur").length).toBe(0);
397
+ expect(readFileSync(join(inbox("dlq"), "m1.json.reason"), "utf-8")).toContain("invalid replyToId");
398
+ });
399
+
400
+ test("a signed replay is refused after the first copy has left cur/ (replay)", async () => {
401
+ const env = signedEnvelope("flint", AGENT, "once only", { flint: FLINT });
402
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
403
+
404
+ plant(wrapper("flint", env), "first.json");
405
+ expect((await client.checkNewMail()).length).toBe(1);
406
+ rmSync(join(inbox("cur"), "first.json"));
407
+
408
+ plant(wrapper("flint", env), "again.json");
409
+ expect((await client.checkNewMail()).length).toBe(0);
410
+ expect(files("cur")).not.toContain("again.json");
411
+ expect(readFileSync(join(inbox("dlq"), "again.json.reason"), "utf-8")).toContain("class: replay");
412
+ });
413
+
414
+ test("a messageId in the mailbox's consumed ledger is refused (replay)", async () => {
415
+ const env = signedEnvelope("flint", AGENT, "consumed elsewhere", { flint: FLINT });
416
+ mkdirSync(join(tmpDir, AGENT), { recursive: true });
417
+ writeFileSync(
418
+ join(tmpDir, AGENT, "consumed.jsonl"),
419
+ `${JSON.stringify({ id: env.messageId, at: new Date().toISOString() })}\n`,
420
+ );
421
+ plant(wrapper("flint", env));
422
+
423
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
424
+ expect((await client.checkNewMail()).length).toBe(0);
425
+ expect(files("cur").length).toBe(0);
426
+ expect(readFileSync(join(inbox("dlq"), "m1.json.reason"), "utf-8")).toContain("class: replay");
427
+ });
428
+
429
+ // ── cli#482: a first-delivery filename collision must not replace ──────────
430
+ //
431
+ test("an unconsumed filename collision stays in new and keeps the cur record", async () => {
432
+ const first = signedEnvelope("flint", AGENT, "hello", { flint: FLINT }, { messageId: "guard482-id-1" });
433
+ plant(wrapper("flint", first), "collide.json");
434
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
435
+ expect((await client.checkNewMail()).length).toBe(1);
436
+ const before = readFileSync(join(inbox("cur"), "collide.json"), "utf-8");
437
+
438
+ const again = signedEnvelope("flint", AGENT, "hello", { flint: FLINT }, { messageId: "guard482-id-2" });
439
+ plant(wrapper("flint", again), "collide.json");
440
+ expect((await client.checkNewMail()).length).toBe(0);
441
+
442
+ expect(readFileSync(join(inbox("cur"), "collide.json"), "utf-8")).toBe(before);
443
+ expect(files("new")).toEqual(["collide.json"]);
444
+ expect(files("dlq")).toEqual([]);
445
+ });
446
+
447
+ for (const body of ["hello", "different"]) {
448
+ test(`a consumed ID with ${body} body returns replay and keeps the cur record`, async () => {
449
+ const first = signedEnvelope("flint", AGENT, "hello", { flint: FLINT }, { messageId: "guard482-consumed" });
450
+ plant(wrapper("flint", first), "consumed.json");
451
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
452
+ expect(await client.checkNewMail()).toHaveLength(1);
453
+ const cur = join(inbox("cur"), "consumed.json");
454
+ const before = readFileSync(cur);
455
+ const again = signedEnvelope("flint", AGENT, body, { flint: FLINT }, { messageId: first.messageId });
456
+ plant(wrapper("flint", again), "consumed.json");
457
+ expect(await client.checkNewMail()).toEqual([]);
458
+ expect(readFileSync(cur)).toEqual(before);
459
+ expect(readFileSync(join(inbox("dlq"), "consumed.json.reason"), "utf8")).toContain("class: replay");
460
+ });
461
+ }
462
+
463
+ for (const reuseId of [false, true]) {
464
+ test(`same filename, ${reuseId ? "consumed" : "unconsumed"} ID, different signed body keeps the cur record`, async () => {
465
+ const first = signedEnvelope("flint", AGENT, "original", { flint: FLINT }, { messageId: "guard482-id-3" });
466
+ plant(wrapper("flint", first), "clash.json");
467
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
468
+ expect((await client.checkNewMail()).length).toBe(1);
469
+ const before = readFileSync(join(inbox("cur"), "clash.json"), "utf-8");
470
+
471
+ const other = signedEnvelope("flint", AGENT, "different", { flint: FLINT }, { messageId: reuseId ? "guard482-id-3" : "guard482-id-4" });
472
+ plant(wrapper("flint", other), "clash.json");
473
+ expect((await client.checkNewMail()).length).toBe(0);
474
+
475
+ expect(readFileSync(join(inbox("cur"), "clash.json"), "utf-8")).toBe(before);
476
+ if (reuseId) {
477
+ expect(files("dlq")).toContain("clash.json");
478
+ expect(readFileSync(join(inbox("dlq"), "clash.json.reason"), "utf-8")).toContain("class: replay");
479
+ } else {
480
+ expect(files("new")).toEqual(["clash.json"]);
481
+ expect(files("dlq")).toEqual([]);
482
+ }
483
+ });
484
+ }
485
+
486
+ for (const code of ["EACCES", "EISDIR"]) {
487
+ test(`an unreadable ledger (${code}) with no cur/ copy withholds delivery`, async () => {
488
+ const env = signedEnvelope("flint", AGENT, "once only", { flint: FLINT });
489
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
490
+ plant(wrapper("flint", env), "first.json");
491
+ expect(await client.checkNewMail()).toHaveLength(1);
492
+ rmSync(join(inbox("cur"), "first.json"));
493
+ plant(wrapper("flint", env), "again.json");
494
+ const ledger = join(tmpDir, AGENT, "consumed.jsonl");
495
+ const read = fs.readFileSync;
496
+ const fault = spyOn(fs, "readFileSync").mockImplementation((...args: Parameters<typeof read>) => {
497
+ if (args[0] === ledger) throw Object.assign(new Error(code), { code });
498
+ return read(...args);
499
+ });
500
+ try {
501
+ expect(await client.checkNewMail()).toEqual([]);
502
+ expect(files("cur")).toEqual([]);
503
+ expect(files("new")).toContain("again.json");
504
+ } finally {
505
+ fault.mockRestore();
506
+ }
507
+ expect(await client.checkNewMail()).toEqual([]);
508
+ expect(readFileSync(join(inbox("dlq"), "again.json.reason"), "utf-8")).toContain("class: replay");
509
+ });
510
+ }
511
+
512
+ test("source unlink failure withholds delivery and retries", async () => {
513
+ const env = signedEnvelope("flint", AGENT, "once only", { flint: FLINT });
514
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
515
+ plant(wrapper("flint", env));
516
+ const source = join(inbox("new"), "m1.json");
517
+ const unlink = fs.unlinkSync;
518
+ const fault = spyOn(fs, "unlinkSync").mockImplementation((...args: Parameters<typeof unlink>) => {
519
+ if (args[0] === source) throw new Error("source cleanup fault");
520
+ return unlink(...args);
521
+ });
522
+ try {
523
+ expect(await client.checkNewMail()).toEqual([]);
524
+ expect(existsSync(source)).toBe(true);
525
+ expect(files("cur")).toEqual([]);
526
+ expect(existsSync(join(tmpDir, AGENT, "consumed.jsonl"))).toBe(false);
527
+ } finally {
528
+ fault.mockRestore();
529
+ }
530
+ const restarted = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
531
+ expect(await restarted.checkNewMail()).toHaveLength(1);
532
+ expect(await restarted.checkNewMail()).toEqual([]);
533
+ expect(files("new")).toEqual([]);
534
+ expect(files("cur")).toEqual(["m1.json"]);
535
+ });
536
+
537
+ test("failed consumed-ID append removes cur/ while retaining the source", async () => {
538
+ const env = signedEnvelope("flint", AGENT, "retry", { flint: FLINT });
539
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
540
+ plant(wrapper("flint", env));
541
+ const append = fs.appendFileSync;
542
+ const fault = spyOn(fs, "appendFileSync").mockImplementation((...args: Parameters<typeof append>) => {
543
+ if (args[0] === join(tmpDir, AGENT, "consumed.jsonl")) throw new Error("append fault");
544
+ return append(...args);
545
+ });
546
+ try {
547
+ expect(await client.checkNewMail()).toEqual([]);
548
+ expect(files("cur")).toEqual([]);
549
+ expect(files("new")).toEqual(["m1.json"]);
550
+ } finally {
551
+ fault.mockRestore();
552
+ }
553
+ expect(await client.checkNewMail()).toHaveLength(1);
554
+ });
555
+
556
+ test("a failed ledger append and rollback are both reported without delivery", async () => {
557
+ const env = signedEnvelope("flint", AGENT, "uncommitted", { flint: FLINT });
558
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
559
+ plant(wrapper("flint", env));
560
+ const append = fs.appendFileSync;
561
+ const rename = fs.renameSync;
562
+ const appendFault = spyOn(fs, "appendFileSync").mockImplementation((...args: Parameters<typeof append>) => {
563
+ if (args[0] === join(tmpDir, AGENT, "consumed.jsonl")) throw new Error("append fault");
564
+ return append(...args);
565
+ });
566
+ const rollbackFault = spyOn(fs, "renameSync").mockImplementation((...args: Parameters<typeof rename>) => {
567
+ if (args[0] === join(inbox("cur"), "m1.json")) throw new Error("rollback fault");
568
+ return rename(...args);
569
+ });
570
+ try {
571
+ await expect(client["commitToCur"](client["operationRoots"](), "m1.json", join(inbox("new"), "m1.json"),
572
+ readFileSync(join(inbox("new"), "m1.json"), "utf-8"), env)).rejects.toThrow(/append fault.*rollback fault/);
573
+ expect(readFileSync(join(tmpDir, AGENT, "consumed.jsonl"), "utf-8")).toBe("");
574
+ } finally {
575
+ appendFault.mockRestore();
576
+ rollbackFault.mockRestore();
577
+ }
578
+ });
579
+
314
580
  test("an envelope with a malformed timestamp is rejected (invalid)", async () => {
315
581
  const env = signedEnvelope("flint", AGENT, "bad ts", { flint: FLINT }, { timestamp: "not-a-date" });
316
582
  plant(wrapper("flint", env));
@@ -322,4 +588,22 @@ describe("agent MailClient promotion is fail-closed (cli#380 F1)", () => {
322
588
  expect(files("dlq")).toContain("m1.json");
323
589
  expect(readFileSync(join(inbox("dlq"), "m1.json.reason"), "utf-8")).toContain("class: invalid");
324
590
  });
591
+
592
+ test("MailClient retains new mail on trust-tier resolution errors", async () => {
593
+ const env = signedEnvelope("flint", AGENT, "tier", { flint: FLINT });
594
+ plant(wrapper("flint", env));
595
+ mkdirSync(join(tmpDir, ".bridge-principals"), { recursive: true });
596
+ writeFileSync(join(tmpDir, ".bridge-principals", "broken.json"), "not json", "utf-8");
597
+
598
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
599
+ expect(await client.checkNewMail()).toEqual([]);
600
+ expect(files("new")).toEqual(["m1.json"]);
601
+ expect(files("cur")).toEqual([]);
602
+ expect(files("dlq")).toEqual([]);
603
+
604
+ rmSync(join(tmpDir, ".bridge-principals"), { recursive: true, force: true });
605
+ expect((await client.checkNewMail()).length).toBe(1);
606
+ expect(files("new")).toEqual([]);
607
+ expect(files("cur")).toEqual(["m1.json"]);
608
+ });
325
609
  });
@@ -0,0 +1,60 @@
1
+ import { afterEach, beforeEach, expect, test } from "bun:test";
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { MailClient } from "../src/io/mail.js";
7
+ import { relayAcceptanceLockRoot } from "../src/lib/relay-lock.js";
8
+ import { senderKeyResolver, signedRelayRecord } from "./helpers/signed-relay-record.js";
9
+
10
+ let root: string;
11
+ let savedMailDir: string | undefined;
12
+ beforeEach(() => {
13
+ root = mkdtempSync(join(tmpdir(), "mail-relay-reservation-"));
14
+ savedMailDir = process.env.TPS_MAIL_DIR;
15
+ process.env.TPS_MAIL_DIR = root;
16
+ });
17
+ afterEach(() => {
18
+ if (savedMailDir === undefined) delete process.env.TPS_MAIL_DIR;
19
+ else process.env.TPS_MAIL_DIR = savedMailDir;
20
+ rmSync(root, { recursive: true, force: true });
21
+ });
22
+
23
+ // These reservation cases align TPS_MAIL_DIR with MailClient.mailDir.
24
+ for (const valid of [true, false]) {
25
+ test(`MailClient ${valid ? "promotion" : "dead-lettering"} leaves a same-id source in place while its stripe is reserved`, async () => {
26
+ const client = new MailClient(root, undefined, "mailbox", senderKeyResolver());
27
+ const source = join(root, "mailbox", "new", "m1.json");
28
+ const relayDelivery = { branchId: "remote", id: "reserved" };
29
+ const raw = valid
30
+ ? signedRelayRecord("mailbox", "reserved", relayDelivery)
31
+ : JSON.stringify({ from: "sender", body: "invalid", relayDelivery });
32
+ writeFileSync(source, raw);
33
+ const script = join(root, "holder.ts");
34
+ writeFileSync(script, `
35
+ const { acquireMailLockSync } = await import(${JSON.stringify(new URL("../src/lib/mail-lock.js", import.meta.url).href)});
36
+ const lock = acquireMailLockSync(${JSON.stringify(relayAcceptanceLockRoot("remote", "reserved"))});
37
+ if (!lock) throw new Error("holder could not acquire");
38
+ process.stdout.write("ready");
39
+ process.stdin.once("data", () => { lock.release(); process.exit(0); });
40
+ `);
41
+ const child = spawn("bun", [script], { env: { ...process.env }, stdio: ["pipe", "pipe", "inherit"] });
42
+ const exited = new Promise<number | null>((resolve) => child.once("exit", resolve));
43
+ await new Promise<void>((resolve, reject) => {
44
+ child.once("error", reject);
45
+ child.stdout.once("data", () => resolve());
46
+ child.once("exit", () => reject(new Error("holder exited before ready")));
47
+ });
48
+ try {
49
+ expect(await client.checkNewMail()).toEqual([]);
50
+ expect(readFileSync(source, "utf8")).toBe(raw);
51
+ expect(existsSync(join(root, "mailbox", "cur", "m1.json"))).toBe(false);
52
+ expect(existsSync(join(root, "mailbox", "dlq", "m1.json"))).toBe(false);
53
+ } finally {
54
+ child.stdin.end("release");
55
+ expect(await exited).toBe(0);
56
+ }
57
+ expect(await client.checkNewMail()).toHaveLength(valid ? 1 : 0);
58
+ expect(existsSync(join(root, "mailbox", valid ? "cur" : "dlq", "m1.json"))).toBe(true);
59
+ });
60
+ }
@@ -0,0 +1,16 @@
1
+ import { expect, test } from "bun:test";
2
+ import { isMailboxMessageFile } from "../src/lib/mailbox-filename.js";
3
+
4
+ for (const [name, expected] of [
5
+ [".x.json", false],
6
+ ["message.txt", false],
7
+ ["2026-11-08-message.json", true],
8
+ ["", false],
9
+ ["nested/message.json", false],
10
+ ["nested\\message.json", false],
11
+ ["message.JSON", false],
12
+ ] as const) {
13
+ test(`mailbox filename ${JSON.stringify(name)} is ${expected}`, () => {
14
+ expect(isMailboxMessageFile(name)).toBe(expected);
15
+ });
16
+ }
@@ -0,0 +1,108 @@
1
+ import { expect, test } from "bun:test";
2
+ import * as ed from "@noble/ed25519";
3
+ import { hashes } from "@noble/ed25519";
4
+ import { createHash } from "node:crypto";
5
+ import { PublicKeyFormatError, parseFlairPublicKey } from "../src/lib/public-key.js";
6
+
7
+ hashes.sha512 = (message: Uint8Array) => new Uint8Array(createHash("sha512").update(message).digest());
8
+
9
+ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
10
+
11
+ function pub(seed: Buffer): Buffer {
12
+ return Buffer.from(ed.getPublicKey(new Uint8Array(seed)));
13
+ }
14
+
15
+ /** A 32-byte seed whose public key's base64url carries a '-' or '_'. */
16
+ function seedWithUrlChar(): Buffer {
17
+ for (let i = 0; i < 256; i++) {
18
+ const candidate = Buffer.alloc(32, i);
19
+ const encoded = pub(candidate).toString("base64url");
20
+ if (encoded.includes("-") || encoded.includes("_")) return candidate;
21
+ }
22
+ throw new Error("no single-byte seed produced a base64url key with '-' or '_'");
23
+ }
24
+
25
+ const KEY = pub(Buffer.alloc(32, 0x11));
26
+
27
+ test("accepts an unpadded base64url key", () => {
28
+ expect(parseFlairPublicKey(KEY.toString("base64url"))).toEqual(KEY);
29
+ });
30
+
31
+ test("accepts a base64url key carrying '-' or '_'", () => {
32
+ const encoded = pub(seedWithUrlChar()).toString("base64url");
33
+ expect(encoded).toHaveLength(43);
34
+ expect(encoded).toMatch(/[-_]/);
35
+ expect(parseFlairPublicKey(encoded)).toEqual(pub(seedWithUrlChar()));
36
+ });
37
+
38
+ test("accepts a standard padded base64 key", () => {
39
+ expect(parseFlairPublicKey(KEY.toString("base64"))).toEqual(KEY);
40
+ });
41
+
42
+ test("accepts a standard unpadded base64 key", () => {
43
+ expect(parseFlairPublicKey(KEY.toString("base64").replace(/=+$/, ""))).toEqual(KEY);
44
+ });
45
+
46
+ test("refuses a 31-byte value", () => {
47
+ expect(() => parseFlairPublicKey(Buffer.alloc(31, 0x01).toString("base64url"))).toThrow(
48
+ PublicKeyFormatError,
49
+ );
50
+ });
51
+
52
+ test("refuses a 33-byte value", () => {
53
+ expect(() => parseFlairPublicKey(Buffer.alloc(33, 0x01).toString("base64url"))).toThrow(
54
+ PublicKeyFormatError,
55
+ );
56
+ });
57
+
58
+ test("refuses characters outside base64/base64url", () => {
59
+ expect(() => parseFlairPublicKey("not-a-key!!")).toThrow(PublicKeyFormatError);
60
+ });
61
+
62
+ test("refuses a non-string or empty value", () => {
63
+ expect(() => parseFlairPublicKey(undefined)).toThrow(PublicKeyFormatError);
64
+ expect(() => parseFlairPublicKey("")).toThrow(PublicKeyFormatError);
65
+ });
66
+
67
+ test("refuses a value that mixes the base64 and base64url alphabets", () => {
68
+ const mixed = Buffer.alloc(32, 0xfb).toString("base64").replace(/\+/, "-");
69
+ expect(mixed).toMatch(/\//);
70
+ expect(mixed).toMatch(/-/);
71
+ expect(() => parseFlairPublicKey(mixed)).toThrow(PublicKeyFormatError);
72
+ });
73
+
74
+ test("refuses a non-canonical encoding that decodes to the same 32 bytes", () => {
75
+ const canonical = KEY.toString("base64").replace(/=+$/, "");
76
+ const idx = ALPHABET.indexOf(canonical.at(-1)!);
77
+ // Flip the two padding bits of the final character: same bytes, different text.
78
+ const mutated = canonical.slice(0, -1) + ALPHABET[idx ^ 3];
79
+ expect(mutated).not.toBe(canonical);
80
+ expect(() => parseFlairPublicKey(mutated)).toThrow(PublicKeyFormatError);
81
+ });
82
+
83
+ for (const encoded of [KEY.toString("hex"), KEY.toString("hex").toUpperCase()]) {
84
+ test(`accepts uniform-case hex ${encoded}`, () => {
85
+ expect(parseFlairPublicKey(encoded)).toEqual(KEY);
86
+ });
87
+ }
88
+
89
+ test("accepts canonical padded base64url", () => {
90
+ expect(parseFlairPublicKey(KEY.toString("base64url") + "=")).toEqual(KEY);
91
+ });
92
+
93
+ for (const encoded of [
94
+ KEY.toString("base64") + "=",
95
+ KEY.toString("base64url") + "==",
96
+ KEY.toString("base64") + "junk",
97
+ KEY.toString("base64") + "\n",
98
+ KEY.toString("hex") + "junk",
99
+ KEY.toString("hex") + "\n",
100
+ "aA" + KEY.toString("hex").slice(2),
101
+ KEY.toString("hex").slice(2),
102
+ KEY.toString("hex") + "00",
103
+ Buffer.alloc(32, 0xab),
104
+ ]) {
105
+ test(`refuses malformed or mixed-case input ${JSON.stringify(encoded)}`, () => {
106
+ expect(() => parseFlairPublicKey(encoded)).toThrow(PublicKeyFormatError);
107
+ });
108
+ }