@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.
- package/bun.lock +27 -15
- package/dist/bin.js +4 -3
- package/dist/bin.js.map +1 -1
- package/dist/config.d.ts +8 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +38 -3
- package/dist/config.js.map +1 -1
- package/dist/home.d.ts +3 -0
- package/dist/home.d.ts.map +1 -0
- package/dist/home.js +18 -0
- package/dist/home.js.map +1 -0
- package/dist/index.d.ts +16 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -1
- package/dist/index.js.map +1 -1
- package/dist/io/flair.d.ts +1 -10
- package/dist/io/flair.d.ts.map +1 -1
- package/dist/io/flair.js +29 -28
- package/dist/io/flair.js.map +1 -1
- package/dist/io/mail.d.ts +184 -30
- package/dist/io/mail.d.ts.map +1 -1
- package/dist/io/mail.js +944 -185
- package/dist/io/mail.js.map +1 -1
- package/dist/lib/agent-keys.d.ts +106 -0
- package/dist/lib/agent-keys.d.ts.map +1 -0
- package/dist/lib/agent-keys.js +298 -0
- package/dist/lib/agent-keys.js.map +1 -0
- package/dist/lib/bridge-identity.d.ts +10 -0
- package/dist/lib/bridge-identity.d.ts.map +1 -0
- package/dist/lib/bridge-identity.js +56 -0
- package/dist/lib/bridge-identity.js.map +1 -0
- package/dist/lib/mail-lock-namespace.d.ts +19 -0
- package/dist/lib/mail-lock-namespace.d.ts.map +1 -0
- package/dist/lib/mail-lock-namespace.js +58 -0
- package/dist/lib/mail-lock-namespace.js.map +1 -0
- package/dist/lib/mail-lock.d.ts +81 -0
- package/dist/lib/mail-lock.d.ts.map +1 -0
- package/dist/lib/mail-lock.js +319 -0
- package/dist/lib/mail-lock.js.map +1 -0
- package/dist/lib/mailbox-filename.d.ts +2 -0
- package/dist/lib/mailbox-filename.d.ts.map +1 -0
- package/dist/lib/mailbox-filename.js +4 -0
- package/dist/lib/mailbox-filename.js.map +1 -0
- package/dist/lib/mailbox-policy.d.ts +245 -0
- package/dist/lib/mailbox-policy.d.ts.map +1 -0
- package/dist/lib/mailbox-policy.js +949 -0
- package/dist/lib/mailbox-policy.js.map +1 -0
- package/dist/lib/public-key.d.ts +6 -0
- package/dist/lib/public-key.d.ts.map +1 -0
- package/dist/lib/public-key.js +45 -0
- package/dist/lib/public-key.js.map +1 -0
- package/dist/lib/registry-key.d.ts +2 -0
- package/dist/lib/registry-key.d.ts.map +1 -0
- package/dist/lib/registry-key.js +10 -0
- package/dist/lib/registry-key.js.map +1 -0
- package/dist/lib/relay-lock.d.ts +7 -0
- package/dist/lib/relay-lock.d.ts.map +1 -0
- package/dist/lib/relay-lock.js +19 -0
- package/dist/lib/relay-lock.js.map +1 -0
- package/dist/lib/signEnvelope.d.ts +2 -0
- package/dist/lib/signEnvelope.d.ts.map +1 -1
- package/dist/lib/signEnvelope.js.map +1 -1
- package/dist/lib/signing-key.d.ts +2 -0
- package/dist/lib/signing-key.d.ts.map +1 -0
- package/dist/lib/signing-key.js +9 -0
- package/dist/lib/signing-key.js.map +1 -0
- package/dist/lib/topic-recipient.d.ts +2 -0
- package/dist/lib/topic-recipient.d.ts.map +1 -0
- package/dist/lib/topic-recipient.js +2 -0
- package/dist/lib/topic-recipient.js.map +1 -0
- package/dist/llm/provider.d.ts.map +1 -1
- package/dist/llm/provider.js +9 -7
- package/dist/llm/provider.js.map +1 -1
- package/dist/runtime/agent.d.ts.map +1 -1
- package/dist/runtime/agent.js +32 -25
- package/dist/runtime/agent.js.map +1 -1
- package/dist/runtime/event-loop.d.ts +21 -2
- package/dist/runtime/event-loop.d.ts.map +1 -1
- package/dist/runtime/event-loop.js +199 -54
- package/dist/runtime/event-loop.js.map +1 -1
- package/dist/runtime/types.d.ts +11 -0
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/runtime/types.js +13 -1
- package/dist/runtime/types.js.map +1 -1
- package/package.json +2 -3
- package/src/bin.ts +4 -3
- package/src/config.ts +46 -3
- package/src/home.ts +18 -0
- package/src/index.ts +33 -2
- package/src/io/flair.ts +23 -28
- package/src/io/mail.ts +1007 -200
- package/src/lib/agent-keys.ts +308 -0
- package/src/lib/bridge-identity.ts +49 -0
- package/src/lib/mail-lock-namespace.ts +64 -0
- package/src/lib/mail-lock.ts +337 -0
- package/src/lib/mailbox-filename.ts +3 -0
- package/src/lib/mailbox-policy.ts +1085 -0
- package/src/lib/public-key.ts +49 -0
- package/src/lib/registry-key.ts +8 -0
- package/src/lib/relay-lock.ts +20 -0
- package/src/lib/signEnvelope.ts +2 -0
- package/src/lib/signing-key.ts +8 -0
- package/src/lib/topic-recipient.ts +1 -0
- package/src/llm/provider.ts +9 -7
- package/src/runtime/agent.ts +30 -27
- package/src/runtime/event-loop.ts +221 -68
- package/src/runtime/types.ts +14 -0
- package/test/config.test.ts +85 -2
- package/test/core-loop.test.ts +6 -4
- package/test/governance.test.ts +4 -1
- package/test/helpers/event-loop-child.mjs +50 -0
- package/test/helpers/mail-delivery-worker.mjs +16 -0
- package/test/helpers/mail-kill-child.mjs +104 -0
- package/test/helpers/signed-relay-record.ts +31 -0
- package/test/home-per-call.test.ts +72 -0
- package/test/io.test.ts +81 -14
- package/test/mail-client-lock-namespace.test.ts +155 -0
- package/test/mail-client-repoint-root.test.ts +368 -0
- package/test/mail-delivery-at-least-once.test.ts +1238 -0
- package/test/mail-event-loop-delivery.test.ts +769 -0
- package/test/mail-intent-phases.test.ts +304 -0
- package/test/mail-interrupted-recovery.test.ts +393 -0
- package/test/mail-lock-pid-state.test.ts +238 -0
- package/test/mail-lock.test.ts +96 -0
- package/test/mail-partial-flair.test.ts +102 -0
- package/test/mail-placement-replay.test.ts +116 -0
- package/test/mail-promote-guard.test.ts +305 -21
- package/test/mail-relay-reservation.test.ts +60 -0
- package/test/mailbox-filename.test.ts +16 -0
- package/test/public-key.test.ts +108 -0
- package/test/runtime-key-encoding.test.ts +105 -0
- package/test/runtime-pending-key.test.ts +117 -0
- package/test/security/mail-trust.test.ts +406 -109
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { afterEach, beforeEach, expect, spyOn, test } from "bun:test";
|
|
2
|
+
import { type ChildProcess, spawn } from "node:child_process";
|
|
3
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
import { acquireMailLockSync, mailLockPath, processStartToken } from "../src/lib/mail-lock.js";
|
|
8
|
+
|
|
9
|
+
let root: string;
|
|
10
|
+
beforeEach(() => {
|
|
11
|
+
root = mkdtempSync(join(tmpdir(), "mail-lock-wait-"));
|
|
12
|
+
});
|
|
13
|
+
afterEach(() => {
|
|
14
|
+
rmSync(root, { recursive: true, force: true });
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
function plantContendedLock(): void {
|
|
18
|
+
const dir = mailLockPath(root);
|
|
19
|
+
mkdirSync(dir);
|
|
20
|
+
writeFileSync(join(dir, "owner.json"), JSON.stringify({ pid: process.pid, startToken: processStartToken(process.pid) }));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const HOLDER_MODULE = fileURLToPath(new URL("../src/lib/mail-lock.ts", import.meta.url));
|
|
24
|
+
|
|
25
|
+
/** Spawn a real second process that acquires `root`'s lock and holds it. */
|
|
26
|
+
function spawnLockHolder(): { child: ChildProcess; ready: Promise<void>; exited: Promise<number | null> } {
|
|
27
|
+
const child = spawn("bun", ["--eval", `
|
|
28
|
+
import { acquireMailLock } from ${JSON.stringify(HOLDER_MODULE)};
|
|
29
|
+
const lock = await acquireMailLock(${JSON.stringify(root)});
|
|
30
|
+
if (!lock) { process.stdout.write("unavailable"); process.exit(2); }
|
|
31
|
+
process.stdout.write("ready");
|
|
32
|
+
process.stdin.resume();
|
|
33
|
+
process.stdin.once("end", () => { lock.release(); process.exit(0); });
|
|
34
|
+
`], { stdio: ["pipe", "pipe", "pipe"] });
|
|
35
|
+
const exited = new Promise<number | null>((resolve) => {
|
|
36
|
+
child.once("exit", resolve);
|
|
37
|
+
child.once("error", () => resolve(null));
|
|
38
|
+
});
|
|
39
|
+
const ready = new Promise<void>((resolve, reject) => {
|
|
40
|
+
const timer = setTimeout(() => reject(new Error("lock holder did not become ready in time")), 10000);
|
|
41
|
+
child.once("error", (err) => { clearTimeout(timer); reject(err); });
|
|
42
|
+
child.once("exit", (code) => { clearTimeout(timer); reject(new Error(`lock holder exited before readiness (code ${code})`)); });
|
|
43
|
+
child.stdout?.once("data", (chunk) => {
|
|
44
|
+
clearTimeout(timer);
|
|
45
|
+
const line = chunk.toString();
|
|
46
|
+
if (line === "ready") resolve();
|
|
47
|
+
else reject(new Error(`lock holder signalled ${JSON.stringify(line)}`));
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
return { child, ready, exited };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
test("a contended synchronous acquisition returns null after waiting about timeoutMs", async () => {
|
|
54
|
+
const timeoutMs = 400;
|
|
55
|
+
// The holder is a real second process, so the wait below is genuine
|
|
56
|
+
// inter-process contention. The lower bound rejects an acquirer whose measured
|
|
57
|
+
// wait is below 0.9 * timeoutMs, targeting the one-retry and small-cap regressions.
|
|
58
|
+
const { child, ready, exited } = spawnLockHolder();
|
|
59
|
+
try {
|
|
60
|
+
await ready;
|
|
61
|
+
const started = performance.now();
|
|
62
|
+
expect(acquireMailLockSync(root, { timeoutMs })).toBeNull();
|
|
63
|
+
const elapsed = performance.now() - started;
|
|
64
|
+
expect(elapsed).toBeGreaterThanOrEqual(0.9 * timeoutMs);
|
|
65
|
+
expect(elapsed).toBeLessThan(timeoutMs + 3000);
|
|
66
|
+
} finally {
|
|
67
|
+
child.stdin?.end("release");
|
|
68
|
+
child.kill("SIGKILL");
|
|
69
|
+
await exited;
|
|
70
|
+
}
|
|
71
|
+
}, 15000);
|
|
72
|
+
|
|
73
|
+
for (const [name, opts, expectedMs] of [
|
|
74
|
+
["a contended synchronous acquisition uses the default retry interval of 2 ms", {}, 2],
|
|
75
|
+
["pollMs overrides the default retry interval", { pollMs: 7 }, 7],
|
|
76
|
+
] as const) {
|
|
77
|
+
test(name, () => {
|
|
78
|
+
plantContendedLock();
|
|
79
|
+
const waits: number[] = [];
|
|
80
|
+
const realWait = Atomics.wait;
|
|
81
|
+
const spy = spyOn(Atomics, "wait").mockImplementation(((array: Int32Array, index: number, value: number, timeout?: number) => {
|
|
82
|
+
expect(value).toBe(array[index]);
|
|
83
|
+
const result = realWait(array, index, value, timeout);
|
|
84
|
+
expect(result).toBe("timed-out");
|
|
85
|
+
waits.push(timeout ?? 0);
|
|
86
|
+
return result;
|
|
87
|
+
}) as typeof Atomics.wait);
|
|
88
|
+
try {
|
|
89
|
+
expect(acquireMailLockSync(root, { timeoutMs: 100, ...opts })).toBeNull();
|
|
90
|
+
} finally {
|
|
91
|
+
spy.mockRestore();
|
|
92
|
+
}
|
|
93
|
+
expect(waits.length).toBeGreaterThan(0);
|
|
94
|
+
expect(waits.every((ms) => ms === expectedMs)).toBe(true);
|
|
95
|
+
});
|
|
96
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { afterEach, expect, spyOn, test } from "bun:test";
|
|
2
|
+
import { generateKeyPairSync } from "node:crypto";
|
|
3
|
+
import * as fs from "node:fs";
|
|
4
|
+
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readdirSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import * as ed from "@noble/ed25519";
|
|
8
|
+
import { FlairContextProvider } from "../src/io/flair.js";
|
|
9
|
+
import { AgentRuntime } from "../src/runtime/agent.js";
|
|
10
|
+
import { MailClient } from "../src/io/mail.js";
|
|
11
|
+
import { signEnvelope } from "../src/lib/signEnvelope.js";
|
|
12
|
+
|
|
13
|
+
let root: string;
|
|
14
|
+
let fault: ReturnType<typeof spyOn>;
|
|
15
|
+
afterEach(() => { fault?.mockRestore(); if (root) rmSync(root, { recursive: true, force: true }); });
|
|
16
|
+
|
|
17
|
+
for (const response of [401, 403, 500, null, {}]) {
|
|
18
|
+
test(`healthy Health with indeterminate Agent response ${JSON.stringify(response)} stays retryable`, async () => {
|
|
19
|
+
root = mkdtempSync(join(tmpdir(), "partial-flair-"));
|
|
20
|
+
const keyPath = join(root, "reader.key");
|
|
21
|
+
writeFileSync(keyPath, generateKeyPairSync("ed25519").privateKey.export({ type: "pkcs8", format: "pem" }));
|
|
22
|
+
const seed = Buffer.alloc(32, 3);
|
|
23
|
+
let recovered = false;
|
|
24
|
+
fault = spyOn(globalThis, "fetch").mockImplementation(async (input) => {
|
|
25
|
+
if (new URL(String(input)).pathname === "/Health") return new Response("ok");
|
|
26
|
+
if (recovered) return Response.json({ id: "flint", publicKey: Buffer.from(ed.getPublicKey(seed)).toString("base64") });
|
|
27
|
+
return typeof response === "number" ? new Response("failure", { status: response }) : Response.json(response);
|
|
28
|
+
});
|
|
29
|
+
expect((await fetch("http://flair.test/Health")).ok).toBe(true);
|
|
30
|
+
const provider = new FlairContextProvider("kern", { url: "http://flair.test", keyPath });
|
|
31
|
+
await expect(provider.getAgent("flint")).rejects.toThrow();
|
|
32
|
+
const runtime = new AgentRuntime({ agentId: "kern", name: "kern", workspace: root,
|
|
33
|
+
mailDir: root, memoryPath: join(root, "memory.jsonl"),
|
|
34
|
+
llm: { provider: "anthropic", model: "test", apiKey: "test" },
|
|
35
|
+
flair: { url: "http://flair.test", keyPath } });
|
|
36
|
+
const client = (runtime as unknown as { mail: MailClient }).mail;
|
|
37
|
+
const timestamp = new Date().toISOString();
|
|
38
|
+
const envelope = signEnvelope({ v: 1, from: "flint", to: "kern", body: "retry", messageId: "partial-outage", timestamp,
|
|
39
|
+
delegationChain: [{ agent: "flint", kind: "agent", rationale: "sends", timestamp, signature: null }] }, { flint: seed });
|
|
40
|
+
const fresh = join(root, "kern", "new");
|
|
41
|
+
mkdirSync(fresh, { recursive: true });
|
|
42
|
+
writeFileSync(join(fresh, "mail.json"), JSON.stringify({ from: "flint", body: JSON.stringify(envelope) }));
|
|
43
|
+
expect(await client.checkNewMail()).toEqual([]);
|
|
44
|
+
expect(readdirSync(fresh)).toEqual(["mail.json"]);
|
|
45
|
+
expect(readdirSync(join(root, "kern", "dlq"))).toEqual([]);
|
|
46
|
+
recovered = true;
|
|
47
|
+
expect(await client.checkNewMail()).toHaveLength(1);
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
test("AgentRuntime authenticates registry reads with an agent-create raw private seed", async () => {
|
|
52
|
+
root = mkdtempSync(join(tmpdir(), "raw-seed-runtime-"));
|
|
53
|
+
const keyPath = join(root, "reader.key");
|
|
54
|
+
const reader = Buffer.alloc(32, 2);
|
|
55
|
+
const sender = Buffer.alloc(32, 3);
|
|
56
|
+
writeFileSync(keyPath, reader);
|
|
57
|
+
let authenticated = 0;
|
|
58
|
+
fault = spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
|
|
59
|
+
const path = new URL(String(input)).pathname;
|
|
60
|
+
if (path === "/Health") return new Response("ok");
|
|
61
|
+
const auth = new Headers(init?.headers).get("Authorization")!;
|
|
62
|
+
const [agent, timestamp, nonce, signature] = auth.slice("TPS-Ed25519 ".length).split(":");
|
|
63
|
+
const payload = Buffer.from(`${agent}:${timestamp}:${nonce}:GET:${path}`);
|
|
64
|
+
if (agent !== "kern" || !ed.verify(Buffer.from(signature!, "base64"), payload, ed.getPublicKey(reader))) {
|
|
65
|
+
return new Response("invalid credential", { status: 403 });
|
|
66
|
+
}
|
|
67
|
+
authenticated++;
|
|
68
|
+
return Response.json({ id: "flint", publicKey: Buffer.from(ed.getPublicKey(sender)).toString("hex") });
|
|
69
|
+
});
|
|
70
|
+
const runtime = new AgentRuntime({ agentId: "kern", name: "kern", workspace: root,
|
|
71
|
+
mailDir: root, memoryPath: join(root, "memory.jsonl"),
|
|
72
|
+
llm: { provider: "anthropic", model: "test", apiKey: "test" }, flair: { url: "http://flair.test", keyPath } });
|
|
73
|
+
const timestamp = new Date().toISOString();
|
|
74
|
+
const envelope = signEnvelope({ v: 1, from: "flint", to: "kern", body: "raw-seed", messageId: "raw-seed", timestamp,
|
|
75
|
+
delegationChain: [{ agent: "flint", kind: "agent", rationale: "sends", timestamp, signature: null }] }, { flint: sender });
|
|
76
|
+
writeFileSync(join(root, "kern", "new", "mail.json"), JSON.stringify({ from: "flint", body: JSON.stringify(envelope) }));
|
|
77
|
+
const mail = (runtime as unknown as { mail: MailClient }).mail;
|
|
78
|
+
expect(await mail.checkNewMail()).toHaveLength(1);
|
|
79
|
+
expect(authenticated).toBeGreaterThan(0);
|
|
80
|
+
for (const [index, invalid] of [{ ...envelope, v: 2 }, { ...envelope, signature: "bad" }, { ...envelope, delegationChain: [] }].entries()) {
|
|
81
|
+
writeFileSync(join(root, "kern", "new", `invalid-${index}.json`), JSON.stringify({ from: "flint", body: JSON.stringify(invalid) }));
|
|
82
|
+
expect(await mail.checkNewMail()).toEqual([]);
|
|
83
|
+
expect(fs.readFileSync(join(root, "kern", "dlq", `invalid-${index}.json.reason`), "utf8")).toContain("class: invalid");
|
|
84
|
+
}
|
|
85
|
+
const next = signEnvelope({ ...envelope, messageId: "after-key-fault", signature: undefined,
|
|
86
|
+
delegationChain: envelope.delegationChain.map(hop => ({ ...hop, signature: null })) }, { flint: sender });
|
|
87
|
+
writeFileSync(join(root, "kern", "new", "next.json"), JSON.stringify({ from: "flint", body: JSON.stringify(next) }));
|
|
88
|
+
const read = fs.readFileSync;
|
|
89
|
+
const unreadable = spyOn(fs, "readFileSync").mockImplementation((...args: Parameters<typeof read>) => {
|
|
90
|
+
if (args[0] === keyPath) throw Object.assign(new Error("EACCES"), { code: "EACCES" });
|
|
91
|
+
return read(...args);
|
|
92
|
+
});
|
|
93
|
+
try { expect(await mail.checkNewMail()).toEqual([]); }
|
|
94
|
+
finally { unreadable.mockRestore(); }
|
|
95
|
+
writeFileSync(keyPath, "torn private key");
|
|
96
|
+
expect(await mail.checkNewMail()).toEqual([]);
|
|
97
|
+
rmSync(keyPath);
|
|
98
|
+
expect(await mail.checkNewMail()).toEqual([]);
|
|
99
|
+
expect(readdirSync(join(root, "kern", "new"))).toEqual(["next.json"]);
|
|
100
|
+
writeFileSync(keyPath, reader);
|
|
101
|
+
expect(await mail.checkNewMail()).toHaveLength(1);
|
|
102
|
+
});
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { afterEach, beforeEach, expect, spyOn, test } from "bun:test";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import { linkSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import * as ed from "@noble/ed25519";
|
|
7
|
+
import { MailClient } from "../src/io/mail.js";
|
|
8
|
+
import { acquireMailLockSync } from "../src/lib/mail-lock.js";
|
|
9
|
+
import { mailboxReplayStore } from "../src/lib/mailbox-policy.js";
|
|
10
|
+
import { signEnvelope } from "../src/lib/signEnvelope.js";
|
|
11
|
+
|
|
12
|
+
let root: string;
|
|
13
|
+
let client: MailClient;
|
|
14
|
+
let messageId: string;
|
|
15
|
+
const seed = Buffer.alloc(32, 1);
|
|
16
|
+
const path = (dir: string) => join(root, "mailbox", dir, "m1.json");
|
|
17
|
+
beforeEach(() => {
|
|
18
|
+
root = mkdtempSync(join(tmpdir(), "placement-replay-"));
|
|
19
|
+
client = new MailClient(root, undefined, "mailbox", {
|
|
20
|
+
async getAgent() { return { publicKey: Buffer.from(ed.getPublicKey(seed)) }; },
|
|
21
|
+
});
|
|
22
|
+
const timestamp = new Date().toISOString();
|
|
23
|
+
messageId = "placement-replay";
|
|
24
|
+
const envelope = signEnvelope({
|
|
25
|
+
v: 1, from: "flint", to: "mailbox", body: "hello", messageId, timestamp,
|
|
26
|
+
delegationChain: [
|
|
27
|
+
{ agent: "system", kind: "human", timestamp, rationale: "originates", signature: null },
|
|
28
|
+
{ agent: "flint", kind: "agent", timestamp, rationale: "sends", signature: null },
|
|
29
|
+
],
|
|
30
|
+
}, { flint: seed });
|
|
31
|
+
writeFileSync(path("new"), JSON.stringify({ from: "flint", body: JSON.stringify(envelope) }));
|
|
32
|
+
});
|
|
33
|
+
afterEach(() => rmSync(root, { recursive: true, force: true }));
|
|
34
|
+
|
|
35
|
+
function pruneConsumedId(): void {
|
|
36
|
+
const mailbox = join(root, "mailbox");
|
|
37
|
+
const ledger = join(mailbox, "consumed.jsonl");
|
|
38
|
+
writeFileSync(ledger, JSON.stringify({ id: messageId, at: "2000-01-01T00:00:00.000Z" }) + "\n");
|
|
39
|
+
const lock = acquireMailLockSync(mailbox);
|
|
40
|
+
if (!lock) throw new Error("lock unavailable");
|
|
41
|
+
try { expect(mailboxReplayStore(mailbox).isConsumed("absent-id")).toBe(false); }
|
|
42
|
+
finally { lock.release(); }
|
|
43
|
+
expect(readFileSync(ledger, "utf8")).toBe("");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
test("a delivered file hard-linked back into new/ is removed without delivery", async () => {
|
|
47
|
+
expect(await client.checkNewMail()).toHaveLength(1);
|
|
48
|
+
linkSync(path("cur"), path("new"));
|
|
49
|
+
expect(await client.checkNewMail()).toEqual([]);
|
|
50
|
+
expect(() => readFileSync(path("new"))).toThrow();
|
|
51
|
+
expect(await client.checkNewMail()).toEqual([]);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("a delivered file relink is removed after its consumed ID is pruned", async () => {
|
|
55
|
+
expect(await client.checkNewMail()).toHaveLength(1);
|
|
56
|
+
pruneConsumedId();
|
|
57
|
+
linkSync(path("cur"), path("new"));
|
|
58
|
+
expect(await client.checkNewMail()).toEqual([]);
|
|
59
|
+
expect(() => readFileSync(path("new"))).toThrow();
|
|
60
|
+
expect(await client.checkNewMail()).toEqual([]);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
function pendingPlacement(id = messageId): void {
|
|
65
|
+
const mailbox = join(root, "mailbox");
|
|
66
|
+
const lock = acquireMailLockSync(mailbox);
|
|
67
|
+
if (!lock) throw new Error("lock unavailable");
|
|
68
|
+
linkSync(path("new"), path("cur"));
|
|
69
|
+
try { mailboxReplayStore(mailbox).beginPlacement(id, "m1.json", path("cur")); }
|
|
70
|
+
finally { lock.release(); }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
test("a placement interrupted after linking recovers the original message", async () => {
|
|
74
|
+
const link = fs.linkSync;
|
|
75
|
+
const fault = spyOn(fs, "linkSync").mockImplementation((...args: Parameters<typeof link>) => {
|
|
76
|
+
link(...args);
|
|
77
|
+
throw new Error("interrupted after link");
|
|
78
|
+
});
|
|
79
|
+
try { expect(await client.checkNewMail()).toEqual([]); }
|
|
80
|
+
finally { fault.mockRestore(); }
|
|
81
|
+
const replay = mailboxReplayStore(join(root, "mailbox"));
|
|
82
|
+
expect(replay.hasPendingPlacement(messageId, "m1.json")).toBe(true);
|
|
83
|
+
expect(replay.ownsPendingPlacement(messageId, "m1.json")).toBe(true);
|
|
84
|
+
const restarted = new MailClient(root, undefined, "mailbox", {
|
|
85
|
+
async getAgent() { return { publicKey: Buffer.from(ed.getPublicKey(seed)) }; },
|
|
86
|
+
});
|
|
87
|
+
const result = await restarted.deliverNext();
|
|
88
|
+
expect(result.status).toBe("delivered");
|
|
89
|
+
if (result.status !== "delivered") throw new Error(JSON.stringify(result));
|
|
90
|
+
expect(await restarted.completeDelivery(result.delivery)).toEqual({ status: "completed" });
|
|
91
|
+
expect(replay.hasPendingPlacement(messageId, "m1.json")).toBe(false);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("an intent for another ID does not authorize delivery", async () => {
|
|
95
|
+
pendingPlacement("other-id");
|
|
96
|
+
expect(await client.checkNewMail()).toEqual([]);
|
|
97
|
+
expect(readFileSync(path("new"))).toEqual(readFileSync(path("cur")));
|
|
98
|
+
expect(mailboxReplayStore(join(root, "mailbox")).hasPendingPlacement("other-id", "m1.json")).toBe(true);
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
for (const pending of [false, true]) {
|
|
102
|
+
test(`a linked record with corrupt history is withheld (pending=${pending})`, async () => {
|
|
103
|
+
if (pending) pendingPlacement();
|
|
104
|
+
else linkSync(path("new"), path("cur"));
|
|
105
|
+
writeFileSync(join(root, "mailbox", "consumed.jsonl"), "broken history\n");
|
|
106
|
+
expect(await client.checkNewMail()).toEqual([]);
|
|
107
|
+
expect(readFileSync(path("new"))).toEqual(readFileSync(path("cur")));
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
test("pending recovery validates other maildir history", async () => {
|
|
112
|
+
pendingPlacement();
|
|
113
|
+
writeFileSync(join(root, "mailbox", "cur", "corrupt.json"), "broken history");
|
|
114
|
+
expect(await client.checkNewMail()).toEqual([]);
|
|
115
|
+
expect(readFileSync(path("new"))).toEqual(readFileSync(path("cur")));
|
|
116
|
+
});
|