@tpsdev-ai/agent 0.6.0 → 0.8.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.
@@ -0,0 +1,325 @@
1
+ /**
2
+ * mail-promote-guard.test.ts — cli#380 F1 (the packages/agent maildir→model path).
3
+ *
4
+ * `packages/agent/src/io/mail.ts` is a FOURTH consumer that reaches a
5
+ * tool-holding EventLoop (AgentRuntime's EventLoop), alongside the three
6
+ * runtimes moved onto the shared promote() lifecycle. It promoted `new/`→`cur/`
7
+ * with verification OPTIONAL, two ways:
8
+ *
9
+ * 1. `checkNewMail()` guarded verification behind `if (this.flairClient)`, so
10
+ * a runtime built without Flair config promoted unverified mail;
11
+ * 2. `verifyMailBody()` swallowed a verifier THROW and returned `pass: true`,
12
+ * so a Flair outage promoted unverified mail.
13
+ *
14
+ * These drills pin the fail-CLOSED contract: no verifier → no promotion;
15
+ * a throw → no promotion; a deterministic reject → dlq/ with the shared
16
+ * `.reason` sidecar. Both defects are RED at 545e23cd and GREEN after.
17
+ */
18
+
19
+ import { describe, test, expect, beforeEach, afterEach } from "bun:test";
20
+ import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync, readdirSync, mkdirSync } from "node:fs";
21
+ import { join } from "node:path";
22
+ import { tmpdir } from "node:os";
23
+ import { randomUUID } from "node:crypto";
24
+ import * as ed from "@noble/ed25519";
25
+ import { signEnvelope, type Envelope, type ChainEntry, type FlairClient } from "../src/lib/signEnvelope.js";
26
+ import { FlairContextProvider } from "../src/io/flair.js";
27
+ import { MailClient } from "../src/io/mail.js";
28
+
29
+ const AGENT = "mailbox";
30
+
31
+ function seed(b: number): Buffer {
32
+ return Buffer.alloc(32, b);
33
+ }
34
+ function pub(seedBytes: Buffer): Buffer {
35
+ return Buffer.from(ed.getPublicKey(new Uint8Array(seedBytes)));
36
+ }
37
+
38
+ /** FlairClient stub resolving the named agents to their public keys. */
39
+ function flairClient(agents: Record<string, Buffer>): FlairClient {
40
+ return {
41
+ async getAgent(name: string) {
42
+ const pk = agents[name];
43
+ return pk ? { publicKey: pk } : null;
44
+ },
45
+ };
46
+ }
47
+
48
+ /** A verifier that cannot run (Flair unreachable). */
49
+ const throwingFlair: FlairClient = {
50
+ async getAgent() {
51
+ throw new Error("Flair unreachable: ECONNREFUSED");
52
+ },
53
+ };
54
+
55
+ /**
56
+ * The FlairClient adapter AgentRuntime builds for envelope verification
57
+ * (a thin wrapper over the provider). Mirrored here so the outage drill
58
+ * exercises the REAL provider, not a stub.
59
+ */
60
+ function providerVerifier(provider: FlairContextProvider): FlairClient {
61
+ return {
62
+ async getAgent(name: string) {
63
+ const a = await provider.getAgent(name);
64
+ if (!a) return null;
65
+ return { publicKey: Buffer.from(a.publicKey, "hex") };
66
+ },
67
+ };
68
+ }
69
+
70
+ function signedEnvelope(
71
+ from: string,
72
+ to: string,
73
+ body: string,
74
+ seeds: Record<string, Buffer>,
75
+ overrides: Partial<Envelope> = {},
76
+ ): Envelope {
77
+ const now = new Date().toISOString();
78
+ const chain: ChainEntry[] = [
79
+ { agent: "system", kind: "human", timestamp: now, rationale: "originates", signature: null },
80
+ { agent: from, kind: "agent", timestamp: now, rationale: "sends", signature: null },
81
+ ];
82
+ const envelope: Envelope = {
83
+ v: 1,
84
+ from,
85
+ to,
86
+ body,
87
+ messageId: randomUUID(),
88
+ timestamp: now,
89
+ delegationChain: chain,
90
+ ...overrides,
91
+ };
92
+ return signEnvelope(envelope, { [from]: seeds[from]! });
93
+ }
94
+
95
+ describe("agent MailClient promotion is fail-closed (cli#380 F1)", () => {
96
+ let tmpDir: string;
97
+ const FLINT = seed(0x01);
98
+ const KERN = seed(0x02);
99
+
100
+ beforeEach(() => {
101
+ tmpDir = mkdtempSync(join(tmpdir(), "tps-agent-mail-guard-"));
102
+ });
103
+ afterEach(() => {
104
+ rmSync(tmpDir, { recursive: true, force: true });
105
+ });
106
+
107
+ const inbox = (d: "new" | "cur" | "dlq") => join(tmpDir, AGENT, d);
108
+ const files = (d: "new" | "cur" | "dlq") =>
109
+ existsSync(inbox(d)) ? readdirSync(inbox(d)).filter((f) => f.endsWith(".json")) : [];
110
+ const wrapper = (from: string, env: Envelope) => ({ from, to: AGENT, body: JSON.stringify(env) });
111
+ const plant = (wrapperObj: unknown, name = "m1.json") => {
112
+ mkdirSync(inbox("new"), { recursive: true });
113
+ writeFileSync(join(inbox("new"), name), JSON.stringify(wrapperObj), "utf-8");
114
+ };
115
+
116
+ // ── F1 defect 1: verification was optional (no client ⇒ unverified promote) ─
117
+ test("NO verifier: refuses to promote — the record stays in new/", async () => {
118
+ const env = signedEnvelope("flint", AGENT, "hello", { flint: FLINT });
119
+ plant(wrapper("flint", env));
120
+
121
+ const client = new MailClient(tmpDir, undefined, AGENT); // no flairClient
122
+ const msgs = await client.checkNewMail();
123
+
124
+ expect(msgs.length).toBe(0);
125
+ expect(files("new")).toContain("m1.json"); // untouched
126
+ expect(files("cur").length).toBe(0); // never promoted
127
+ });
128
+
129
+ // ── F1 defect 2: the verifier throw was swallowed and treated as a pass ────
130
+ test("THROWING verifier: refuses to promote — a throw must not mean pass", async () => {
131
+ const env = signedEnvelope("flint", AGENT, "hello", { flint: FLINT });
132
+ plant(wrapper("flint", env));
133
+
134
+ const client = new MailClient(tmpDir, undefined, AGENT, throwingFlair);
135
+ const msgs = await client.checkNewMail();
136
+
137
+ expect(msgs.length).toBe(0);
138
+ expect(files("new")).toContain("m1.json");
139
+ expect(files("cur").length).toBe(0);
140
+ });
141
+
142
+ // ── Deterministic rejection → dlq with the SHARED `.reason` sidecar ────────
143
+ test("a signature rejection dead-letters to dlq with a `.reason` sidecar (class: invalid)", async () => {
144
+ const env = signedEnvelope("flint", AGENT, "tampered", { flint: FLINT });
145
+ // Resolve flint to the WRONG key → signature verification fails.
146
+ const wrongKey = flairClient({ flint: pub(KERN) });
147
+ plant(wrapper("flint", env));
148
+
149
+ const client = new MailClient(tmpDir, undefined, AGENT, wrongKey);
150
+ const msgs = await client.checkNewMail();
151
+
152
+ expect(msgs.length).toBe(0);
153
+ expect(files("cur").length).toBe(0);
154
+ expect(files("dlq")).toContain("m1.json");
155
+
156
+ const sidecar = join(inbox("dlq"), "m1.json.reason");
157
+ expect(existsSync(sidecar)).toBe(true);
158
+ expect(readFileSync(sidecar, "utf-8")).toContain("class: invalid");
159
+ // Not the old `.reject` sidecar the shared re-drive cannot read.
160
+ expect(existsSync(join(inbox("dlq"), "m1.json.reject"))).toBe(false);
161
+ });
162
+
163
+ // ── Topology failure is labelled as such, not as forgery (mirrors #383) ────
164
+ test("an unresolvable principal dead-letters as `unresolvable-principal`, not `invalid`", async () => {
165
+ const ghost = seed(0x09);
166
+ const env = signedEnvelope("ghost", AGENT, "from nowhere", { ghost });
167
+ const reachableNoGhost = flairClient({ flint: pub(FLINT) }); // Flair up, ghost absent
168
+ plant(wrapper("ghost", env));
169
+
170
+ const client = new MailClient(tmpDir, undefined, AGENT, reachableNoGhost);
171
+ const msgs = await client.checkNewMail();
172
+
173
+ expect(msgs.length).toBe(0);
174
+ expect(files("dlq")).toContain("m1.json");
175
+ expect(readFileSync(join(inbox("dlq"), "m1.json.reason"), "utf-8")).toContain(
176
+ "class: unresolvable-principal",
177
+ );
178
+ });
179
+
180
+ // ── A non-envelope body is a terminal reject too ───────────────────────────
181
+ test("a plain (non-envelope) body is dead-lettered, never promoted", async () => {
182
+ plant({ from: "flint", to: AGENT, body: "plain text, no envelope" });
183
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
184
+ const msgs = await client.checkNewMail();
185
+
186
+ expect(msgs.length).toBe(0);
187
+ expect(files("cur").length).toBe(0);
188
+ expect(files("dlq")).toContain("m1.json");
189
+ });
190
+
191
+ // ── Positive control: a valid signed envelope IS promoted ──────────────────
192
+ test("a valid signed envelope with a working verifier is promoted to cur/", async () => {
193
+ const env = signedEnvelope("flint", AGENT, "do the thing", { flint: FLINT });
194
+ plant(wrapper("flint", env));
195
+
196
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
197
+ const msgs = await client.checkNewMail();
198
+
199
+ expect(msgs.length).toBe(1);
200
+ expect(msgs[0]!.from).toBe("flint");
201
+ // The agent MailClient presents the raw record body (unchanged); the
202
+ // verified content is the signed envelope inside it.
203
+ const raw = JSON.parse(msgs[0]!.body) as { from: string; body: string };
204
+ expect(raw.from).toBe("flint");
205
+ expect((JSON.parse(raw.body) as Envelope).body).toBe("do the thing");
206
+ expect(files("cur")).toContain("m1.json");
207
+ expect(files("new").length).toBe(0);
208
+ });
209
+
210
+ // ── 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 () => {
212
+ const env = signedEnvelope("flint", AGENT, "heal me", { flint: FLINT });
213
+ plant(wrapper("flint", env));
214
+
215
+ const noVerifier = new MailClient(tmpDir, undefined, AGENT);
216
+ expect((await noVerifier.checkNewMail()).length).toBe(0);
217
+ expect(files("new")).toContain("m1.json");
218
+
219
+ const withVerifier = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
220
+ const healed = await withVerifier.checkNewMail();
221
+ expect(healed.length).toBe(1);
222
+ expect(files("cur")).toContain("m1.json");
223
+ });
224
+
225
+ // ── Finding 1: an outage is RETRYABLE, not a terminal dead-letter ───────────
226
+
227
+ test("an UNREACHABLE Flair is a RETRYABLE refusal (stays in new/), not a terminal dead-letter", async () => {
228
+ const env = signedEnvelope("flint", AGENT, "during outage", { flint: FLINT });
229
+ plant(wrapper("flint", env));
230
+
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
+ });
237
+ const client = new MailClient(tmpDir, undefined, AGENT, providerVerifier(provider));
238
+ const msgs = await client.checkNewMail();
239
+
240
+ expect(msgs.length).toBe(0);
241
+ expect(files("dlq").length).toBe(0); // NOT dead-lettered
242
+ expect(files("new")).toContain("m1.json"); // left for a later check (retryable)
243
+ });
244
+
245
+ 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
+ const server = Bun.serve({
248
+ port: 0,
249
+ fetch(req) {
250
+ const p = new URL(req.url).pathname;
251
+ if (p === "/Health") return new Response("ok", { status: 200 });
252
+ return new Response("not found", { status: 404 });
253
+ },
254
+ });
255
+ try {
256
+ const env = signedEnvelope("flint", AGENT, "absent", { flint: FLINT });
257
+ plant(wrapper("flint", env));
258
+ const provider = new FlairContextProvider(AGENT, {
259
+ url: server.url.href,
260
+ keyPath: join(tmpDir, "no-key"),
261
+ });
262
+ const client = new MailClient(tmpDir, undefined, AGENT, providerVerifier(provider));
263
+ const msgs = await client.checkNewMail();
264
+
265
+ expect(msgs.length).toBe(0);
266
+ expect(files("dlq")).toContain("m1.json");
267
+ expect(readFileSync(join(inbox("dlq"), "m1.json.reason"), "utf-8")).toContain(
268
+ "class: unresolvable-principal",
269
+ );
270
+ } finally {
271
+ server.stop(true);
272
+ }
273
+ });
274
+
275
+ // ── Finding 2: the guard checks WHO FOR, and the wrapper binding ────────────
276
+
277
+ test("a correctly-signed envelope addressed to ANOTHER principal is not presented (wrong-recipient)", async () => {
278
+ const env = signedEnvelope("flint", "someone-else", "not for me", { flint: FLINT });
279
+ plant({ from: "flint", to: "someone-else", body: JSON.stringify(env) });
280
+
281
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
282
+ const msgs = await client.checkNewMail();
283
+
284
+ expect(msgs.length).toBe(0);
285
+ expect(files("cur").length).toBe(0);
286
+ expect(files("dlq")).toContain("m1.json");
287
+ expect(readFileSync(join(inbox("dlq"), "m1.json.reason"), "utf-8")).toContain("class: wrong-recipient");
288
+ });
289
+
290
+ test("a wrapper whose from disagrees with the envelope is rejected (invalid)", async () => {
291
+ const env = signedEnvelope("flint", AGENT, "spoofed wrapper", { flint: FLINT });
292
+ plant({ from: "nathan", to: AGENT, body: JSON.stringify(env) });
293
+
294
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
295
+ const msgs = await client.checkNewMail();
296
+
297
+ expect(msgs.length).toBe(0);
298
+ expect(files("dlq")).toContain("m1.json");
299
+ expect(readFileSync(join(inbox("dlq"), "m1.json.reason"), "utf-8")).toContain("class: invalid");
300
+ });
301
+
302
+ test("an envelope with a malformed messageId is rejected (invalid)", async () => {
303
+ const env = signedEnvelope("flint", AGENT, "bad id", { flint: FLINT }, { messageId: "" });
304
+ plant(wrapper("flint", env));
305
+
306
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
307
+ const msgs = await client.checkNewMail();
308
+
309
+ expect(msgs.length).toBe(0);
310
+ expect(files("dlq")).toContain("m1.json");
311
+ expect(readFileSync(join(inbox("dlq"), "m1.json.reason"), "utf-8")).toContain("class: invalid");
312
+ });
313
+
314
+ test("an envelope with a malformed timestamp is rejected (invalid)", async () => {
315
+ const env = signedEnvelope("flint", AGENT, "bad ts", { flint: FLINT }, { timestamp: "not-a-date" });
316
+ plant(wrapper("flint", env));
317
+
318
+ const client = new MailClient(tmpDir, undefined, AGENT, flairClient({ flint: pub(FLINT) }));
319
+ const msgs = await client.checkNewMail();
320
+
321
+ expect(msgs.length).toBe(0);
322
+ expect(files("dlq")).toContain("m1.json");
323
+ expect(readFileSync(join(inbox("dlq"), "m1.json.reason"), "utf-8")).toContain("class: invalid");
324
+ });
325
+ });