@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
@@ -0,0 +1,949 @@
1
+ /**
2
+ * Shared mailbox policy and consumed-id replay store for both first-delivery
3
+ * paths: the CLI's `promote()` and this package's `MailClient`.
4
+ */
5
+ import { appendFileSync, closeSync, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { homedir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { verifyEnvelope } from "./signEnvelope.js";
10
+ // ─── Envelope id shape (cli#429) ─────────────────────────────────────────────
11
+ //
12
+ // signOutboundBody validates replyToId before signing. The mailbox policy
13
+ // validates messageId and any replyToId on receipt; signEnvelope itself does not.
14
+ /** 1-128 chars of `[A-Za-z0-9._-]`. Anchored; no flags. */
15
+ export const ENVELOPE_ID_SHAPE = /^[A-Za-z0-9._-]{1,128}$/;
16
+ /** A human-readable statement of ENVELOPE_ID_SHAPE, for error messages. */
17
+ export const ENVELOPE_ID_SHAPE_TEXT = "letters, digits, dot, underscore or hyphen, 1-128 chars";
18
+ /** True only for a string that satisfies ENVELOPE_ID_SHAPE. */
19
+ export function isValidEnvelopeId(id) {
20
+ return typeof id === "string" && ENVELOPE_ID_SHAPE.test(id);
21
+ }
22
+ /** Describe a rejected id without echoing it: its type, and its length for a string. */
23
+ function describeIdValue(value) {
24
+ if (typeof value === "string")
25
+ return value.length === 0 ? "an empty string" : `a ${value.length}-char string outside the rule`;
26
+ return value === null ? "null" : typeof value;
27
+ }
28
+ // ─── Envelope parsing ────────────────────────────────────────────────────────
29
+ /**
30
+ * Try to parse a message body as an envelope-shaped record.
31
+ *
32
+ * Returns the envelope object, or the string "json-parse-error" (not JSON) or
33
+ * "missing-fields" (JSON but not envelope-shaped).
34
+ */
35
+ export function tryParseEnvelope(body) {
36
+ let parsed;
37
+ try {
38
+ parsed = JSON.parse(body);
39
+ }
40
+ catch {
41
+ return "json-parse-error";
42
+ }
43
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
44
+ return "missing-fields";
45
+ }
46
+ const obj = parsed;
47
+ if (typeof obj.v !== "number" ||
48
+ !Array.isArray(obj.delegationChain) ||
49
+ typeof obj.signature !== "string") {
50
+ return "missing-fields";
51
+ }
52
+ return obj;
53
+ }
54
+ /** Parse an envelope-shaped record with a string body. */
55
+ export function parseSignedEnvelope(body) {
56
+ const parsed = tryParseEnvelope(body);
57
+ if (parsed === "json-parse-error") {
58
+ return { ok: false, class: "invalid", reason: "body is not JSON (signed envelope required)" };
59
+ }
60
+ if (parsed === "missing-fields") {
61
+ return { ok: false, class: "invalid", reason: "body is not envelope-shaped" };
62
+ }
63
+ if (typeof parsed.body !== "string") {
64
+ return { ok: false, class: "invalid", reason: "envelope body is not a string" };
65
+ }
66
+ if (typeof parsed.from !== "string" || !parsed.delegationChain.every((hop) => {
67
+ if (!hop || typeof hop !== "object")
68
+ return false;
69
+ const entry = hop;
70
+ return typeof entry.agent === "string" && (entry.kind === "agent" || entry.kind === "human")
71
+ && (entry.signature === null || typeof entry.signature === "string");
72
+ })) {
73
+ return { ok: false, class: "invalid", reason: "invalid envelope sender or delegation chain" };
74
+ }
75
+ return { ok: true, envelope: parsed };
76
+ }
77
+ export function isTopicRecipient(address, agentId, from) {
78
+ if (typeof address !== "string" || !address.startsWith("topic:"))
79
+ return false;
80
+ const topic = address.slice("topic:".length);
81
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(topic) || topic.length > 64)
82
+ return false;
83
+ try {
84
+ const root = process.env.TPS_HOME || join(process.env.HOME || homedir(), ".tps");
85
+ const meta = JSON.parse(readFileSync(join(root, "topics", topic, "meta.json"), "utf8"));
86
+ return Array.isArray(meta.subscribers) && meta.subscribers.includes(agentId)
87
+ && (meta.allowedPublishers === undefined || (Array.isArray(meta.allowedPublishers)
88
+ && (meta.allowedPublishers.length === 0 || meta.allowedPublishers.includes(from))));
89
+ }
90
+ catch {
91
+ return false;
92
+ }
93
+ }
94
+ /**
95
+ * The stable reason string `verifyEnvelope` returns when an agent-kind chain
96
+ * entry or `envelope.from` cannot be resolved from the LOCAL Flair. It is a
97
+ * presence failure, not a signature failure: the principal is simply not
98
+ * registered here.
99
+ */
100
+ const UNRESOLVABLE_PRINCIPAL_REASON_RE = /^agent (.+) not found in Flair$/;
101
+ /**
102
+ * The ONE mailbox decision for an enveloped record.
103
+ *
104
+ * The checks, in order:
105
+ * 1. signature, through the caller's Flair client;
106
+ * 2. wrapper/envelope `from` binding;
107
+ * 3. recipient binding;
108
+ * 4. `messageId` shape, and `replyToId` shape when present;
109
+ * 5. `timestamp` shape.
110
+ *
111
+ * The replay gate (first delivery only) is the ReplayStore below.
112
+ */
113
+ export async function decideEnvelopeForMailbox(agent, envelope, wrapperFrom, client) {
114
+ // 1. Signature.
115
+ const verified = await verifyEnvelope(envelope, client);
116
+ if (!verified.ok) {
117
+ // Unresolved-principal presence failure.
118
+ // CLI promotion attempts verify-unavailable dead-lettering on verifier throws;
119
+ // MailClient leaves the record in new/ for retry.
120
+ const missing = UNRESOLVABLE_PRINCIPAL_REASON_RE.exec(verified.reason);
121
+ if (missing) {
122
+ const entry = missing[1];
123
+ const reason = `unresolvable-principal: ${entry} is not registered in the local Flair ` +
124
+ `(agent-kind delegation-chain entry or sender this mailbox cannot resolve). ` +
125
+ `Possible spoke-topology cause: a spoke holds only its own principal and hub ` +
126
+ `principals are not distributed downward (see cli#383). Not a signature or ` +
127
+ `forgery verdict. Terminal — delivery refused.`;
128
+ return { ok: false, class: "unresolvable-principal", reason };
129
+ }
130
+ return { ok: false, class: "invalid", reason: `signature verification failed: ${verified.reason}` };
131
+ }
132
+ // 2. The wrapper `from` is what consumers route by, and it is unverified; a
133
+ // wrapper/envelope mismatch is itself a reject.
134
+ if (typeof wrapperFrom !== "string" || wrapperFrom !== envelope.from) {
135
+ return {
136
+ ok: false,
137
+ class: "invalid",
138
+ reason: `wrapper/envelope from mismatch (wrapper.from=${String(wrapperFrom)}, envelope.from=${envelope.from})`,
139
+ };
140
+ }
141
+ if (envelope.to !== agent && !isTopicRecipient(envelope.to, agent, envelope.from)) {
142
+ return {
143
+ ok: false,
144
+ class: "wrong-recipient",
145
+ reason: `wrong-recipient (envelope.to=${envelope.to}, mailbox=${agent})`,
146
+ };
147
+ }
148
+ // 4. `messageId` shape — the replay gate keys on it, a reply threads on it,
149
+ // and verifyEnvelope does not enforce it. A malformed id is a terminal
150
+ // reject, not an undefined key that silently never matches. The reason
151
+ // never echoes the value (it may carry control characters); it names only
152
+ // the type/length.
153
+ if (!isValidEnvelopeId(envelope.messageId)) {
154
+ return {
155
+ ok: false,
156
+ class: "invalid",
157
+ reason: `invalid messageId (must be ${ENVELOPE_ID_SHAPE_TEXT}; got ${describeIdValue(envelope.messageId)})`,
158
+ };
159
+ }
160
+ // 4b. `replyToId` shape (cli#429): optional, but when the envelope carries
161
+ // the field it must satisfy the same rule — a signed value outside it is
162
+ // never presented, whoever signed it.
163
+ if (envelope.replyToId !== undefined && !isValidEnvelopeId(envelope.replyToId)) {
164
+ return {
165
+ ok: false,
166
+ class: "invalid",
167
+ reason: `invalid replyToId (must be ${ENVELOPE_ID_SHAPE_TEXT}; got ${describeIdValue(envelope.replyToId)})`,
168
+ };
169
+ }
170
+ // 5. `timestamp` shape — a malformed/absent timestamp is rejected, never
171
+ // silently replaced by the wrapper's unsigned value (that fallback would
172
+ // let an unsigned field stand in for a signed one).
173
+ if (typeof envelope.timestamp !== "string" || Number.isNaN(Date.parse(envelope.timestamp))) {
174
+ const shown = typeof envelope.timestamp === "string" ? JSON.stringify(envelope.timestamp) : String(envelope.timestamp);
175
+ return {
176
+ ok: false,
177
+ class: "invalid",
178
+ reason: `invalid timestamp (must be a parseable timestamp, got ${shown})`,
179
+ };
180
+ }
181
+ return { ok: true, envelope };
182
+ }
183
+ // ─── Durable consumed-id ledger (replay gate that survives maildir GC) ───────
184
+ const CONSUMED_LEDGER_FILE = "consumed.jsonl";
185
+ const CONSUMED_LEDGER_RETENTION_MS = 180 * 24 * 60 * 60 * 1000;
186
+ /** Bounds checked on later deliverNext() calls for unclaimed in_progress work; the deadline precedes re-verification. */
187
+ export const MAX_DELIVERY_PRESENTATIONS = 5;
188
+ export const DELIVERY_PRESENTATION_TTL_MS = 24 * 60 * 60 * 1000;
189
+ /** The durable ReplayStore for the mailbox rooted at `root` (`<mailDir>/<agent>`). */
190
+ export function mailboxReplayStore(root) {
191
+ return {
192
+ isConsumed: (messageId, pendingFile) => isConsumedMessageId(root, messageId, pendingFile),
193
+ beginPlacement: (messageId, file, sourcePath) => writePlacementIntent(root, messageId, file, sourcePath),
194
+ ownsPendingPlacement: (messageId, file) => {
195
+ const intent = readPlacementIntent(root, file);
196
+ if (intent?.messageId !== messageId || !intent.identity)
197
+ return false;
198
+ try {
199
+ const stat = lstatSync(join(root, "cur", file), { bigint: true });
200
+ return stat.isFile() && matchesFileIdentity(stat, intent.identity, readFileSync(join(root, "cur", file)));
201
+ }
202
+ catch (err) {
203
+ if (isMissing(err))
204
+ return false;
205
+ throw err;
206
+ }
207
+ },
208
+ hasPendingFile: (file) => existsSync(`${placementIntentPath(root, file)}.quarantined`) || isLivePlacement(readPlacementIntent(root, file)),
209
+ hasPendingPlacement: (messageId, file) => {
210
+ const intent = readPlacementIntent(root, file);
211
+ return intent?.messageId === messageId && isLivePlacement(intent);
212
+ },
213
+ placementPhase: (file) => readPlacementIntent(root, file)?.phase ?? null,
214
+ finishPlacement: (messageId, file) => {
215
+ const intent = readPlacementIntent(root, file);
216
+ if (intent?.messageId !== messageId || intent.phase !== "placing")
217
+ return;
218
+ unlinkSync(placementIntentPath(root, file));
219
+ syncDirectory(root);
220
+ },
221
+ recordConsumed: (messageId) => recordConsumedMessageId(root, messageId),
222
+ placementState: (file) => {
223
+ const intent = readPlacementIntent(root, file);
224
+ if (!intent)
225
+ return null;
226
+ return {
227
+ messageId: intent.messageId, phase: intent.phase,
228
+ ...(intent.presentations === undefined ? {} : { presentations: intent.presentations }),
229
+ ...(intent.firstPresentedAt === undefined ? {} : { firstPresentedAt: intent.firstPresentedAt }),
230
+ ...(intent.claim === undefined ? {} : { claim: { ...intent.claim } }),
231
+ };
232
+ },
233
+ advancePresentation: (messageId, file, nowIso, claim) => advancePlacementPresentation(root, messageId, file, nowIso, claim),
234
+ expireOverdue: (messageId, file, nowIso) => expireOverduePlacement(root, messageId, file, nowIso),
235
+ completePlacement: (messageId, file, token) => completeInProgressPlacement(root, messageId, file, token),
236
+ releasePlacement: (messageId, file, token) => releaseInProgressPlacement(root, messageId, file, token),
237
+ };
238
+ }
239
+ /**
240
+ * List well-formed pending intents with their phase; quarantine malformed ones
241
+ * and omit them. An intent whose phase resolves to `failed` is not pending and
242
+ * is omitted.
243
+ * Call under the mailbox lock and re-read each intent before acting on it.
244
+ */
245
+ export function pendingPlacementEntries(root) {
246
+ const entries = [];
247
+ let names;
248
+ try {
249
+ names = readdirSync(root);
250
+ }
251
+ catch (err) {
252
+ if (isMissing(err))
253
+ return entries;
254
+ throw err;
255
+ }
256
+ for (const name of names) {
257
+ if (!/^\.placement-[a-f0-9]{64}\.json$/.test(name))
258
+ continue;
259
+ const path = join(root, name);
260
+ let raw;
261
+ try {
262
+ raw = readFileSync(path, "utf8");
263
+ }
264
+ catch (err) {
265
+ if (isMissing(err))
266
+ continue; // removed after the listing
267
+ throw err;
268
+ }
269
+ const intent = parsePlacement(raw, path);
270
+ if (!intent) {
271
+ quarantinePlacement(path);
272
+ continue;
273
+ }
274
+ if (!isLivePlacement(intent))
275
+ continue;
276
+ entries.push({ messageId: intent.messageId, file: intent.file, phase: intent.phase });
277
+ }
278
+ return entries;
279
+ }
280
+ function placementIntentPath(root, file) {
281
+ return join(root, `.placement-${createHash("sha256").update(file).digest("hex")}.json`);
282
+ }
283
+ function malformedPlacement(path) {
284
+ const err = new Error(`malformed placement intent at ${path}`);
285
+ err.name = "MalformedPlacementIntentError";
286
+ return err;
287
+ }
288
+ function quarantinePlacement(path) {
289
+ const err = malformedPlacement(path);
290
+ writeFileSync(`${path}.quarantined.reason`, `${err.name}: ${err.message}\n`, { mode: 0o600 });
291
+ renameSync(path, `${path}.quarantined`);
292
+ syncDirectory(join(path, ".."));
293
+ console.warn(`${err.name}: ${err.message}`);
294
+ }
295
+ /** The placement intent schema version this reader understands; an intent without one is this version. */
296
+ const PLACEMENT_INTENT_VERSION = 1;
297
+ // Link changes preserve this identity. The same device, inode and bytes are accepted as the same message.
298
+ export function fileIdentity(stat, bytes) {
299
+ return { dev: stat.dev.toString(), ino: stat.ino.toString(), size: stat.size.toString(), sha256: createHash("sha256").update(bytes).digest("hex") };
300
+ }
301
+ export function matchesFileIdentity(stat, identity, bytes) {
302
+ const current = fileIdentity(stat, bytes);
303
+ return stat.isFile() && current.dev === identity.dev && current.ino === identity.ino
304
+ && current.size === identity.size && current.sha256 === identity.sha256;
305
+ }
306
+ /** A plain basename: non-empty, not `.` or `..`, with no path separator or NUL. */
307
+ function isPlainBasename(file) {
308
+ return file !== "" && file !== "." && file !== ".." && !/[/\\\0]/.test(file);
309
+ }
310
+ const CLAIM_TOKEN_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
311
+ /** A presentation claim has UUID token/module nonces, a positive pid and a start token string or null. */
312
+ function isPresentationClaim(value) {
313
+ if (value === null || typeof value !== "object" || Array.isArray(value))
314
+ return false;
315
+ const claim = value;
316
+ return typeof claim.token === "string" && CLAIM_TOKEN_SHAPE.test(claim.token)
317
+ && typeof claim.moduleNonce === "string" && CLAIM_TOKEN_SHAPE.test(claim.moduleNonce)
318
+ && Number.isSafeInteger(claim.pid) && claim.pid > 0
319
+ && (claim.start === null || (typeof claim.start === "string" && claim.start.length > 0 && claim.start.length <= 256));
320
+ }
321
+ /**
322
+ * Resolve the phase of a parsed intent. `version`, `presentations` and
323
+ * `firstPresentedAt` are checked first, and an unsupported value in any of them
324
+ * resolves to `unknown` whatever `phase` says. Then `phase` resolves: absent or
325
+ * `placing`, `in_progress`, `failed`, and anything else is `unknown`. `unknown`
326
+ * is not malformed, and other extra fields are ignored. A malformed identity or
327
+ * basename is still malformed (parsePlacement).
328
+ */
329
+ function phaseOf(intent) {
330
+ if (intent.version !== undefined && intent.version !== PLACEMENT_INTENT_VERSION)
331
+ return "unknown";
332
+ const presentations = intent.presentations;
333
+ if (presentations !== undefined && !(Number.isSafeInteger(presentations) && presentations >= 0))
334
+ return "unknown";
335
+ const firstPresentedAt = intent.firstPresentedAt;
336
+ if (firstPresentedAt !== undefined && (typeof firstPresentedAt !== "string" || Number.isNaN(Date.parse(firstPresentedAt)))) {
337
+ return "unknown";
338
+ }
339
+ const claim = intent.claim;
340
+ if (claim !== undefined && !isPresentationClaim(claim))
341
+ return "unknown";
342
+ const phase = intent.phase;
343
+ let resolved;
344
+ if (phase === undefined || phase === "placing")
345
+ resolved = "placing";
346
+ else if (phase === "in_progress" || phase === "failed")
347
+ resolved = phase;
348
+ else
349
+ return "unknown";
350
+ // A claim is valid only on an in_progress intent.
351
+ if (claim !== undefined && resolved !== "in_progress")
352
+ return "unknown";
353
+ return resolved;
354
+ }
355
+ /** A pending intent: any resolved phase but `failed`. */
356
+ function isLivePlacement(intent) {
357
+ return intent !== null && intent.phase !== "failed";
358
+ }
359
+ /**
360
+ * Parse an intent, or null when it is malformed: the name, messageId and
361
+ * identity must hold; an in_progress claim requires firstPresentedAt.
362
+ * An unsupported value in `phase`, `version` or a liveness field alone never
363
+ * makes an intent malformed (see phaseOf).
364
+ */
365
+ function parsePlacement(raw, path) {
366
+ try {
367
+ const intent = JSON.parse(raw);
368
+ if (typeof intent?.file === "string" && isPlainBasename(intent.file)
369
+ && placementIntentPath(join(path, ".."), intent.file) === path
370
+ && isValidEnvelopeId(intent?.messageId)
371
+ && (intent.identity === undefined || (typeof intent.identity?.dev === "string"
372
+ && typeof intent.identity?.ino === "string" && /^(0|[1-9][0-9]*)$/.test(intent.identity.dev)
373
+ && /^[1-9][0-9]*$/.test(intent.identity.ino)
374
+ && (intent.identity.sha256 === undefined || (typeof intent.identity.sha256 === "string" && /^[a-f0-9]{64}$/.test(intent.identity.sha256)))
375
+ && (intent.identity.size === undefined || (typeof intent.identity.size === "string" && /^(0|[1-9][0-9]*)$/.test(intent.identity.size)))))) {
376
+ if (intent.phase === "in_progress" && intent.claim !== undefined && intent.firstPresentedAt === undefined)
377
+ return null;
378
+ const phase = phaseOf(intent);
379
+ return {
380
+ messageId: intent.messageId, file: intent.file, identity: intent.identity, phase,
381
+ ...(phase === "unknown" ? {} : {
382
+ presentations: intent.presentations,
383
+ firstPresentedAt: intent.firstPresentedAt,
384
+ ...(intent.claim === undefined ? {} : { claim: { token: intent.claim.token, pid: intent.claim.pid, start: intent.claim.start, moduleNonce: intent.claim.moduleNonce } }),
385
+ }),
386
+ };
387
+ }
388
+ }
389
+ catch { }
390
+ return null;
391
+ }
392
+ function readPlacementIntent(root, file) {
393
+ const path = placementIntentPath(root, file);
394
+ if (existsSync(`${path}.quarantined`))
395
+ throw malformedPlacement(path);
396
+ let raw;
397
+ try {
398
+ raw = readFileSync(path, "utf8");
399
+ }
400
+ catch (err) {
401
+ if (isMissing(err))
402
+ return null;
403
+ throw err;
404
+ }
405
+ const intent = parsePlacement(raw, path);
406
+ if (!intent) {
407
+ quarantinePlacement(path);
408
+ throw malformedPlacement(path);
409
+ }
410
+ return intent;
411
+ }
412
+ /**
413
+ * Where a retired `failed` marker for `file` is kept (cli#617):
414
+ * `.placement-<sha256(file)>.failed-<messageId>.json`. A tombstone leaves the
415
+ * per-file (filename) gate open and is never listed for recovery. It keeps its
416
+ * message ID retained in the consumed ledger (pendingPlacementIds), so the
417
+ * consumed-ID (replay) gate still refuses that message. It stays until an
418
+ * operator removes it.
419
+ */
420
+ function failedTombstonePath(root, file, messageId) {
421
+ return `${placementIntentPath(root, file).slice(0, -".json".length)}.failed-${messageId}.json`;
422
+ }
423
+ const FAILED_TOMBSTONE_NAME = /^\.placement-[a-f0-9]{64}\.failed-(.+)\.json$/;
424
+ /**
425
+ * Move a `failed` marker to its tombstone without ever replacing one: the link
426
+ * fails if the tombstone name is taken. A tombstone that is the marker's own
427
+ * inode is treated as an interrupted earlier move, which this finishes. Any
428
+ * other occupant is refused by name, and the marker and the tombstone are both
429
+ * kept.
430
+ */
431
+ function retireFailedMarker(root, path, file, messageId) {
432
+ const tombstone = failedTombstonePath(root, file, messageId);
433
+ try {
434
+ linkSync(path, tombstone);
435
+ }
436
+ catch (err) {
437
+ if (err.code !== "EEXIST")
438
+ throw err;
439
+ const marker = lstatSync(path, { bigint: true });
440
+ const kept = lstatSync(tombstone, { bigint: true });
441
+ if (!marker.isFile() || !kept.isFile() || !matchesFileIdentity(marker, fileIdentity(kept, readFileSync(tombstone)), readFileSync(path))) {
442
+ const refusal = new Error(`failed tombstone occupied for ${file} (message ${messageId}); marker and tombstone kept`);
443
+ refusal.name = "FailedTombstoneOccupiedError";
444
+ throw refusal;
445
+ }
446
+ }
447
+ unlinkSync(path);
448
+ syncDirectory(root);
449
+ }
450
+ function isAbsent(path) {
451
+ try {
452
+ lstatSync(path);
453
+ return false;
454
+ }
455
+ catch (err) {
456
+ if (isMissing(err))
457
+ return true;
458
+ throw err;
459
+ }
460
+ }
461
+ function syncDirectory(root) {
462
+ const fd = openSync(root, "r");
463
+ try {
464
+ fsyncSync(fd);
465
+ }
466
+ finally {
467
+ closeSync(fd);
468
+ }
469
+ }
470
+ function writePlacementIntent(root, messageId, file, sourcePath) {
471
+ if (!isValidEnvelopeId(messageId))
472
+ throw new Error("invalid placement messageId");
473
+ if (!isPlainBasename(file))
474
+ throw new Error("placement file is not a plain basename");
475
+ const path = placementIntentPath(root, file);
476
+ const existing = readPlacementIntent(root, file);
477
+ if (existing && existing.messageId !== messageId) {
478
+ // cli#617: once its payload has left cur/, a `failed` marker yields its
479
+ // basename to a different message. It moves to its tombstone, keeping the
480
+ // operator's record and the old consumed ID, and this placement proceeds.
481
+ // The exception is an occupied tombstone, which refuses by name
482
+ // (retireFailedMarker).
483
+ if (existing.phase !== "failed" || !isAbsent(join(root, "cur", file))) {
484
+ throw new Error(`placement intent for ${file} names another message`);
485
+ }
486
+ retireFailedMarker(root, path, file, existing.messageId);
487
+ }
488
+ else if (existing && existing.phase !== "placing") {
489
+ // cli#617: only a `placing` intent is rewritten; any other phase is kept.
490
+ throw new Error(`placement intent for ${file} is ${existing.phase}; not replaced`);
491
+ }
492
+ let identity;
493
+ if (sourcePath !== undefined) {
494
+ const stat = typeof sourcePath === "number" ? fstatSync(sourcePath, { bigint: true }) : lstatSync(sourcePath, { bigint: true });
495
+ if (!stat.isFile())
496
+ throw new Error("placement source is not a regular file");
497
+ identity = fileIdentity(stat, readFileSync(sourcePath));
498
+ }
499
+ const tmp = `${path}.${randomUUID()}.tmp`;
500
+ const fd = openSync(tmp, "wx", 0o600);
501
+ try {
502
+ try {
503
+ writeFileSync(fd, JSON.stringify({ messageId, file, identity }));
504
+ fsyncSync(fd);
505
+ }
506
+ finally {
507
+ closeSync(fd);
508
+ }
509
+ renameSync(tmp, path);
510
+ syncDirectory(root);
511
+ }
512
+ finally {
513
+ rmSync(tmp, { force: true });
514
+ }
515
+ }
516
+ /**
517
+ * cli#617 slice (b): rewrite the live intent for `file` in place, keeping its
518
+ * messageId and recorded identity. Refuses (returns false) unless a `placing`
519
+ * or `in_progress` intent for this message is present; a `failed` or `unknown`
520
+ * intent, or another message's intent, is never replaced. The write is the
521
+ * temp-file, fsync, rename, directory-fsync sequence. A
522
+ * `.phase.tmp` suffix marks the phase transition for the crash-boundary
523
+ * fixture (mail-kill-child).
524
+ */
525
+ function writePlacementPhase(root, messageId, file, fields) {
526
+ const path = placementIntentPath(root, file);
527
+ const existing = readPlacementIntent(root, file);
528
+ if (!existing || existing.messageId !== messageId)
529
+ return false;
530
+ if (existing.phase !== "placing" && existing.phase !== "in_progress")
531
+ return false;
532
+ const next = {
533
+ messageId,
534
+ file,
535
+ ...(existing.identity ? { identity: existing.identity } : {}),
536
+ ...fields,
537
+ };
538
+ const tmp = `${path}.${randomUUID()}.phase.tmp`;
539
+ const fd = openSync(tmp, "wx", 0o600);
540
+ try {
541
+ try {
542
+ writeFileSync(fd, JSON.stringify(next));
543
+ fsyncSync(fd);
544
+ }
545
+ finally {
546
+ closeSync(fd);
547
+ }
548
+ renameSync(tmp, path);
549
+ syncDirectory(root);
550
+ }
551
+ finally {
552
+ rmSync(tmp, { force: true });
553
+ }
554
+ return true;
555
+ }
556
+ /** Is an `in_progress` intent past the deadline at `nowIso`? An intent without a first presentation never is. */
557
+ function pastDeliveryDeadline(intent, nowIso) {
558
+ if (intent.firstPresentedAt === undefined)
559
+ return false;
560
+ return Date.parse(nowIso) - Date.parse(intent.firstPresentedAt) > DELIVERY_PRESENTATION_TTL_MS;
561
+ }
562
+ /** Write the terminal `failed` phase over a live intent, dropping its claim. */
563
+ function failPlacement(root, messageId, file, presentations, firstPresentedAt) {
564
+ return writePlacementPhase(root, messageId, file, {
565
+ version: PLACEMENT_INTENT_VERSION, phase: "failed", presentations, firstPresentedAt,
566
+ });
567
+ }
568
+ /**
569
+ * cli#617 slice (b): advance a live intent to its next presentation, or to the
570
+ * terminal `failed` phase before a sixth presentation or when the deadline is
571
+ * exceeded. The count check permits the fifth. A `placing`
572
+ * intent becomes `in_progress` at presentation 1 (the first hand-over, counted
573
+ * before it); an `in_progress` intent's count increments. Either way the new
574
+ * presentation's claim replaces any earlier one, so an earlier presentation can
575
+ * no longer complete it. `failed` and `unknown` are not live, so they advance
576
+ * to `absent`.
577
+ */
578
+ function advancePlacementPresentation(root, messageId, file, nowIso, claim) {
579
+ if (!isPresentationClaim(claim))
580
+ throw new Error("invalid presentation claim");
581
+ const intent = readPlacementIntent(root, file);
582
+ if (!intent || intent.messageId !== messageId)
583
+ return { status: "absent" };
584
+ if (intent.phase === "placing") {
585
+ const written = writePlacementPhase(root, messageId, file, {
586
+ version: PLACEMENT_INTENT_VERSION, phase: "in_progress", presentations: 1, firstPresentedAt: nowIso, claim,
587
+ });
588
+ return written ? { status: "presented", presentations: 1 } : { status: "absent" };
589
+ }
590
+ if (intent.phase !== "in_progress")
591
+ return { status: "absent" };
592
+ const previous = intent.presentations ?? 0;
593
+ const firstPresentedAt = intent.firstPresentedAt ?? nowIso;
594
+ const next = previous + 1;
595
+ if (next > MAX_DELIVERY_PRESENTATIONS || pastDeliveryDeadline(intent, nowIso)) {
596
+ return failPlacement(root, messageId, file, previous, firstPresentedAt)
597
+ ? { status: "failed", presentations: previous }
598
+ : { status: "absent" };
599
+ }
600
+ const written = writePlacementPhase(root, messageId, file, {
601
+ version: PLACEMENT_INTENT_VERSION, phase: "in_progress", presentations: next, firstPresentedAt, claim,
602
+ });
603
+ return written ? { status: "presented", presentations: next } : { status: "absent" };
604
+ }
605
+ /** cli#617 slice (b): the deadline alone, never a presentation (see ReplayStore.expireOverdue). */
606
+ function expireOverduePlacement(root, messageId, file, nowIso) {
607
+ const intent = readPlacementIntent(root, file);
608
+ if (!intent || intent.messageId !== messageId || intent.phase !== "in_progress")
609
+ return { status: "absent" };
610
+ if (!pastDeliveryDeadline(intent, nowIso))
611
+ return { status: "live" };
612
+ const presentations = intent.presentations ?? 0;
613
+ return failPlacement(root, messageId, file, presentations, intent.firstPresentedAt)
614
+ ? { status: "failed", presentations }
615
+ : { status: "absent" };
616
+ }
617
+ function releaseInProgressPlacement(root, messageId, file, token) {
618
+ const intent = readPlacementIntent(root, file);
619
+ if (!intent || intent.messageId !== messageId || intent.phase !== "in_progress" || intent.claim?.token !== token)
620
+ return false;
621
+ return writePlacementPhase(root, messageId, file, {
622
+ version: PLACEMENT_INTENT_VERSION,
623
+ phase: "in_progress",
624
+ presentations: intent.presentations,
625
+ firstPresentedAt: intent.firstPresentedAt,
626
+ });
627
+ }
628
+ export class PlacementDurabilityError extends Error {
629
+ }
630
+ /**
631
+ * cli#617 slice (b): completion-only finalize, bound to one presentation: the
632
+ * intent must be `in_progress` for this message, carry `token` in its claim,
633
+ * and still name the cur/ file at its recorded identity.
634
+ */
635
+ function completeInProgressPlacement(root, messageId, file, token) {
636
+ const intent = readPlacementIntent(root, file);
637
+ if (!intent || intent.messageId !== messageId)
638
+ return "absent";
639
+ if (intent.phase !== "in_progress" || intent.claim?.token !== token)
640
+ return "stale";
641
+ if (!intent.identity)
642
+ return "identity";
643
+ let stat;
644
+ try {
645
+ stat = lstatSync(join(root, "cur", file), { bigint: true });
646
+ if (!stat.isFile() || !matchesFileIdentity(stat, intent.identity, readFileSync(join(root, "cur", file))))
647
+ return "identity";
648
+ }
649
+ catch (err) {
650
+ if (isMissing(err))
651
+ return "identity";
652
+ throw err;
653
+ }
654
+ unlinkSync(placementIntentPath(root, file));
655
+ try {
656
+ syncDirectory(root);
657
+ }
658
+ catch (cause) {
659
+ throw new PlacementDurabilityError("intent unlinked; directory sync failed, durability uncertain", { cause });
660
+ }
661
+ return "completed";
662
+ }
663
+ function pendingPlacementIds(root, quarantine = false) {
664
+ const ids = new Set();
665
+ const blocked = new Set();
666
+ let retainAll = false;
667
+ for (const name of readdirSync(root)) {
668
+ // A retired `failed` marker keeps its message ID retained, by its name alone.
669
+ const tombstone = FAILED_TOMBSTONE_NAME.exec(name);
670
+ if (tombstone) {
671
+ if (isValidEnvelopeId(tombstone[1]))
672
+ ids.add(tombstone[1]);
673
+ continue;
674
+ }
675
+ if (!/^\.placement-[a-f0-9]{64}\.json(?:\.quarantined)?$/.test(name))
676
+ continue;
677
+ const path = join(root, name.replace(/\.quarantined$/, ""));
678
+ const raw = readFileSync(join(root, name), "utf8");
679
+ const intent = name.endsWith(".quarantined") ? null : parsePlacement(raw, path);
680
+ if (intent) {
681
+ ids.add(intent.messageId);
682
+ continue;
683
+ }
684
+ const matches = [...raw.matchAll(/"messageId"\s*:\s*("(?:[^"\\]|\\.)*")/g)];
685
+ if (matches.length === 0 || matches.length !== [...raw.matchAll(/"messageId"\s*:/g)].length)
686
+ retainAll = true;
687
+ for (const match of matches) {
688
+ try {
689
+ const id = JSON.parse(match[1]);
690
+ if (isValidEnvelopeId(id)) {
691
+ ids.add(id);
692
+ blocked.add(id);
693
+ }
694
+ else
695
+ retainAll = true;
696
+ }
697
+ catch {
698
+ retainAll = true;
699
+ }
700
+ }
701
+ if (quarantine && !name.endsWith(".quarantined"))
702
+ quarantinePlacement(path);
703
+ }
704
+ return { ids, blocked, retainAll };
705
+ }
706
+ function consumedLedgerPath(root) {
707
+ return join(root, CONSUMED_LEDGER_FILE);
708
+ }
709
+ /**
710
+ * Append after writing cur/. A successful append commits the promotion.
711
+ */
712
+ function recordConsumedMessageId(root, messageId) {
713
+ mkdirSync(root, { recursive: true });
714
+ const path = consumedLedgerPath(root);
715
+ const raw = readLedgerText(root);
716
+ if (raw === null)
717
+ writeFileSync(path, "", { flag: "wx" });
718
+ try {
719
+ writeFileSync(join(root, ".consumed-initialized"), "", { flag: "wx" });
720
+ }
721
+ catch (err) {
722
+ if (err.code !== "EEXIST")
723
+ throw err;
724
+ }
725
+ appendFileSync(path, `${raw !== null && raw !== "" && !raw.endsWith("\n") ? "\n" : ""}${JSON.stringify({ id: messageId, at: new Date().toISOString() })}\n`, "utf-8");
726
+ }
727
+ function parseConsumedLedger(raw, cutoff, pendingIds, retainAll = false) {
728
+ const ids = new Set();
729
+ const kept = [];
730
+ let pruned = 0;
731
+ for (const line of raw.split("\n")) {
732
+ if (!line)
733
+ continue;
734
+ let entry;
735
+ try {
736
+ entry = JSON.parse(line);
737
+ }
738
+ catch {
739
+ // Retain intact IDs; a line without one blocks delivery.
740
+ const matches = [...line.matchAll(/"id"\s*:\s*("(?:[^"\\]|\\.)*")/g)];
741
+ if (matches.length === 0 || matches.length !== [...line.matchAll(/"id"\s*:/g)].length) {
742
+ throw new Error("consumed history has an unrecoverable ID");
743
+ }
744
+ for (const match of matches) {
745
+ const id = JSON.parse(match[1]);
746
+ if (!isValidEnvelopeId(id))
747
+ throw new Error("consumed history has an invalid ID");
748
+ ids.add(id);
749
+ }
750
+ kept.push(line);
751
+ continue;
752
+ }
753
+ const id = entry?.id;
754
+ if (!isValidEnvelopeId(id))
755
+ throw new Error("consumed history has an invalid ID");
756
+ const at = typeof entry.at === "string" ? Date.parse(entry.at) : Number.NaN;
757
+ if (Number.isNaN(at)) {
758
+ ids.add(id);
759
+ kept.push(line);
760
+ continue;
761
+ }
762
+ if (at < cutoff && !retainAll && !pendingIds.has(id)) {
763
+ pruned++;
764
+ continue;
765
+ }
766
+ ids.add(id);
767
+ kept.push(line);
768
+ }
769
+ return { ids, kept, pruned };
770
+ }
771
+ /**
772
+ * The replace drops any line appended between the read and the rename, so call
773
+ * this only while holding the mailbox lock. A reader that does not hold the
774
+ * lock uses peekConsumedLedger.
775
+ */
776
+ function readConsumedLedger(root) {
777
+ const path = consumedLedgerPath(root);
778
+ const raw = readLedgerText(root);
779
+ const pending = pendingPlacementIds(root, true);
780
+ if (raw === null)
781
+ return pending.blocked;
782
+ const { ids, kept, pruned } = parseConsumedLedger(raw, Date.now() - CONSUMED_LEDGER_RETENTION_MS, pending.ids, pending.retainAll);
783
+ if (pruned > 0) {
784
+ try {
785
+ const tmp = `${path}.tmp`;
786
+ writeFileSync(tmp, kept.length > 0 ? `${kept.join("\n")}\n` : "", "utf-8");
787
+ renameSync(tmp, path);
788
+ }
789
+ catch {
790
+ // Pruning is housekeeping — non-fatal, retried on the next read.
791
+ }
792
+ }
793
+ for (const id of pending.blocked)
794
+ ids.add(id);
795
+ return ids;
796
+ }
797
+ /** A read error on consumed history, naming the path that could not be read. */
798
+ function unreadableHistory(path, err) {
799
+ const code = err?.code;
800
+ const detail = code ?? (err instanceof Error ? err.message : String(err));
801
+ return new Error(`consumed history at ${path} is unreadable (${detail})`);
802
+ }
803
+ function isMissing(err) {
804
+ return err?.code === "ENOENT";
805
+ }
806
+ /**
807
+ * Read the ledger without changing it: the live id set readConsumedLedger would
808
+ * return, or null for an uninitialized missing ledger. It never writes,
809
+ * renames or prunes.
810
+ */
811
+ function peekConsumedLedger(root) {
812
+ const raw = readLedgerText(root);
813
+ if (raw === null)
814
+ return null;
815
+ const pending = pendingPlacementIds(root);
816
+ return parseConsumedLedger(raw, Date.now() - CONSUMED_LEDGER_RETENTION_MS, pending.ids, pending.retainAll).ids;
817
+ }
818
+ /**
819
+ * Does this maildir record carry the envelope messageId? Counts both the
820
+ * persisted `envelopeId` and, for legacy records, a body that is itself a
821
+ * signed envelope.
822
+ */
823
+ function recordCarriesMessageId(msg, messageId) {
824
+ if (msg.envelopeId !== undefined) {
825
+ if (!isValidEnvelopeId(msg.envelopeId))
826
+ throw new Error("consumed record has an invalid envelope ID");
827
+ return msg.envelopeId === messageId;
828
+ }
829
+ if (typeof msg.body !== "string")
830
+ throw new Error("consumed record has no envelope ID");
831
+ const parsed = tryParseEnvelope(msg.body);
832
+ if (parsed === "json-parse-error" || parsed === "missing-fields" || !isValidEnvelopeId(parsed.messageId)) {
833
+ throw new Error("consumed record has no recoverable envelope ID");
834
+ }
835
+ return parsed.messageId === messageId;
836
+ }
837
+ /**
838
+ * Has this envelope messageId already been consumed?
839
+ *
840
+ * The durable ledger is the authority (it survives maildir GC). The maildir
841
+ * scan (cur/ + archive/, recursively) is kept as a MIGRATION fallback for
842
+ * records consumed before this ledger existed — or by an older build — so an
843
+ * upgrade does not open a window for records already on disk. Counts both the
844
+ * persisted `envelopeId` and, for legacy records, a body that is itself a
845
+ * signed envelope. This is the gate on replay of consumed history.
846
+ *
847
+ * It reads the ledger through readConsumedLedger, which may rewrite the ledger:
848
+ * call it only while holding the mailbox lock.
849
+ */
850
+ function isConsumedMessageId(root, messageId, pendingFile) {
851
+ if (readConsumedLedger(root).has(messageId))
852
+ return true;
853
+ return maildirHistoryHasMessageId(root, messageId, pendingFile === undefined ? undefined : join(root, "cur", pendingFile));
854
+ }
855
+ function maildirHistoryHasMessageId(root, messageId, pendingPath) {
856
+ const stack = [join(root, "cur"), join(root, "archive")];
857
+ for (let dir = stack.pop(); dir !== undefined; dir = stack.pop()) {
858
+ let entries;
859
+ try {
860
+ entries = readdirSync(dir, { withFileTypes: true });
861
+ }
862
+ catch (err) {
863
+ if (isMissing(err))
864
+ continue;
865
+ throw unreadableHistory(dir, err);
866
+ }
867
+ for (const entry of entries) {
868
+ const full = join(dir, entry.name);
869
+ if (full === pendingPath)
870
+ continue;
871
+ if (entry.isDirectory()) {
872
+ stack.push(full);
873
+ continue;
874
+ }
875
+ if (!entry.name.endsWith(".json"))
876
+ continue;
877
+ let raw;
878
+ try {
879
+ raw = readFileSync(full, "utf-8");
880
+ }
881
+ catch (err) {
882
+ if (isMissing(err))
883
+ continue; // removed after the listing
884
+ throw unreadableHistory(full, err);
885
+ }
886
+ let record;
887
+ try {
888
+ record = JSON.parse(raw);
889
+ }
890
+ catch {
891
+ throw new Error(`consumed history at ${full} is corrupt`);
892
+ }
893
+ if (record == null || typeof record !== "object")
894
+ throw new Error(`consumed history at ${full} is corrupt`);
895
+ if (recordCarriesMessageId(record, messageId))
896
+ return true;
897
+ }
898
+ }
899
+ return false;
900
+ }
901
+ /**
902
+ * Replay lookup for a reader that does not hold the mailbox lock: true when
903
+ * this envelope messageId is in the consumed ledger or, failing that, in the
904
+ * maildir fallback — the history isConsumedMessageId consults. It writes,
905
+ * renames, prunes and creates nothing. Unavailable history throws; the caller
906
+ * must withhold the record.
907
+ */
908
+ export function peekConsumedForMailboxRoot(root, messageId) {
909
+ if (peekConsumedLedger(root)?.has(messageId))
910
+ return true;
911
+ return maildirHistoryHasMessageId(root, messageId);
912
+ }
913
+ function readLedgerText(root) {
914
+ const path = consumedLedgerPath(root);
915
+ try {
916
+ return readFileSync(path, "utf-8");
917
+ }
918
+ catch (err) {
919
+ if (!isMissing(err))
920
+ throw unreadableHistory(path, err);
921
+ try {
922
+ readFileSync(join(root, ".consumed-initialized"));
923
+ }
924
+ catch (markerErr) {
925
+ if (isMissing(markerErr))
926
+ return null;
927
+ throw unreadableHistory(path, markerErr);
928
+ }
929
+ throw new Error(`consumed history at ${path} is missing after initialization`);
930
+ }
931
+ }
932
+ export function hasCommittedMessageId(root, messageId) {
933
+ const ids = peekConsumedLedger(root);
934
+ if (ids === null)
935
+ return false;
936
+ return ids.has(messageId);
937
+ }
938
+ export function placeCurRecord(sourcePath, curPath) {
939
+ try {
940
+ linkSync(sourcePath, curPath);
941
+ return { status: "placed" };
942
+ }
943
+ catch (err) {
944
+ if (err.code !== "EEXIST")
945
+ throw err;
946
+ return { status: "exists" };
947
+ }
948
+ }
949
+ //# sourceMappingURL=mailbox-policy.js.map