@codemem/opencode-plugin 0.47.5 → 0.48.1

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.
@@ -1,7 +1,10 @@
1
+ import { isUtf8 } from "node:buffer";
1
2
  import { createHash, randomUUID } from "node:crypto";
3
+ import { constants } from "node:fs";
2
4
  import {
3
5
  chmod,
4
6
  link,
7
+ lstat,
5
8
  mkdir,
6
9
  open,
7
10
  readdir,
@@ -15,6 +18,10 @@ import { isDeepStrictEqual } from "node:util";
15
18
 
16
19
  const DEFAULT_DRAIN_LIMIT = 20;
17
20
  const DEFAULT_MAX_ENTRIES = 2000;
21
+ const MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES = 16 * 1024 * 1024;
22
+ const INSPECTION_READ_CHUNK_BYTES = 64 * 1024;
23
+ const REJECTED_LOCK_RECORD_MAX_BYTES = 1024;
24
+ const REJECTED_LOCK_PURPOSE = "rejected-raw-event-v1";
18
25
  const RAW_EVENT_SPOOL_FULL_CODE = "raw_event_spool_full";
19
26
  const RAW_EVENT_SPOOL_CONFLICT_CODE = "raw_event_spool_conflict";
20
27
  const SPOOL_DIRECTORY_NAME = "opencode-raw-event-spool";
@@ -28,6 +35,73 @@ const spoolFilename = (eventId) => {
28
35
  return `${digest}.json`;
29
36
  };
30
37
 
38
+ const rejectedReasons = new Map([[400, "invalid_payload"], [413, "payload_too_large"]]);
39
+ const rejectedFilename = (eventId, status, reason) =>
40
+ `rejected-${spoolFilename(eventId).slice(0, -5)}-${status}-${reason}.json`;
41
+
42
+ const parseRejectedFilename = (name) => {
43
+ const match = /^rejected-([a-f0-9]{64})-(400|413)-(invalid_payload|payload_too_large)\.json$/.exec(name);
44
+ if (!match) return null;
45
+ const status = Number(match[2]);
46
+ if (rejectedReasons.get(status) !== match[3]) return null;
47
+ return { digest: match[1], status, reason: match[3] };
48
+ };
49
+
50
+ const requirePrivateSpoolDirectory = async (directory) => {
51
+ for (const path of [dirname(directory), directory]) {
52
+ const details = await lstat(path);
53
+ if (!details.isDirectory() || details.isSymbolicLink()) {
54
+ throw new Error("raw event spool requires a real directory");
55
+ }
56
+ }
57
+ };
58
+
59
+ // Open without following links, then inspect the opened inode before reading it.
60
+ const readRegularSpoolFile = async (path, { makePrivate = false } = {}) => {
61
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
62
+ try {
63
+ const details = await handle.stat();
64
+ if (!details.isFile()) throw new Error("raw event spool requires a regular file");
65
+ const bytes = await handle.readFile();
66
+ if (!isUtf8(bytes)) throw new Error("raw event spool requires UTF-8 JSON");
67
+ const serialized = bytes.toString("utf8");
68
+ if (makePrivate) {
69
+ await handle.chmod(0o600);
70
+ await handle.sync();
71
+ }
72
+ return { serialized, details };
73
+ } finally {
74
+ await handle.close();
75
+ }
76
+ };
77
+
78
+ const requireMatchingIdentity = (serialized, filename) => {
79
+ let envelope;
80
+ try {
81
+ envelope = JSON.parse(serialized);
82
+ } catch (error) {
83
+ error.spoolConflict = { branch: "rejected_identity", reason: "invalid_json" };
84
+ throw error;
85
+ }
86
+ let eventId;
87
+ try {
88
+ eventId = requireEventId(envelope);
89
+ } catch (error) {
90
+ error.spoolConflict = { branch: "rejected_identity", reason: "invalid_shape" };
91
+ throw error;
92
+ }
93
+ if (spoolFilename(eventId) !== filename) {
94
+ throw conflictingEntry({ branch: "rejected_identity", reason: "identity_mismatch" });
95
+ }
96
+ };
97
+
98
+ const rejectedMetadata = (name, entry, bytes) => ({
99
+ receipt: name,
100
+ bytes,
101
+ status: entry.status,
102
+ reason: entry.reason,
103
+ });
104
+
31
105
  const requireEventId = (envelope) => {
32
106
  const eventId = typeof envelope?.event_id === "string"
33
107
  ? envelope.event_id.trim()
@@ -38,25 +112,71 @@ const requireEventId = (envelope) => {
38
112
  return eventId;
39
113
  };
40
114
 
115
+ // Only literal paths from this schema may enter diagnostics. Payload values and
116
+ // unknown property names remain private even when retained JSON is malformed.
117
+ const CONFLICT_FIELDS = {
118
+ started_at: true,
119
+ host_generation: true,
120
+ capture_context: true,
121
+ session_stream_id: true,
122
+ session_id: true,
123
+ stream_id: true,
124
+ opencode_session_id: true,
125
+ cwd: true,
126
+ project: true,
127
+ source: true,
128
+ event_type: true,
129
+ payload: { timestamp: true, _adapter: { ts: true }, _raw_spooled: true, args: true },
130
+ };
131
+
132
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
133
+
134
+ const changedConflictFields = (existing, incoming, schema = CONFLICT_FIELDS, prefix = "") => {
135
+ const fields = [];
136
+ let other = false;
137
+ const left = { ...existing };
138
+ const right = { ...incoming };
139
+ for (const [key, child] of Object.entries(schema)) {
140
+ const path = `${prefix}${key}`;
141
+ const differs = Object.hasOwn(left, key) !== Object.hasOwn(right, key)
142
+ || !isDeepStrictEqual(left[key], right[key]);
143
+ if (differs && child === true) fields.push(path);
144
+ else if (differs && isRecord(left[key]) && isRecord(right[key])) {
145
+ const nested = changedConflictFields(left[key], right[key], child, `${path}.`);
146
+ fields.push(...nested.fields);
147
+ other ||= nested.other;
148
+ } else if (differs) {
149
+ fields.push(path);
150
+ other = true;
151
+ }
152
+ delete left[key];
153
+ delete right[key];
154
+ }
155
+ return { fields, other: other || !isDeepStrictEqual(left, right) };
156
+ };
157
+
41
158
  /** Delivery timestamps can change when the same host event is captured again. */
42
- const sameEventApartFromDeliveryTime = (existingBytes, incomingBytes) => {
43
- if (existingBytes === incomingBytes) return true;
159
+ const compareEventApartFromDeliveryTime = (existingBytes, incomingBytes) => {
160
+ if (existingBytes === incomingBytes) return null;
44
161
  try {
45
162
  const existing = JSON.parse(existingBytes);
46
163
  const incoming = JSON.parse(incomingBytes);
47
- if (!existing || typeof existing !== "object" || Array.isArray(existing)) return false;
48
- if (!incoming || typeof incoming !== "object" || Array.isArray(incoming)) return false;
164
+ if (!isRecord(existing) || !isRecord(incoming)) return { reason: "invalid_shape" };
49
165
  const withoutDeliveryTime = ({ ts_wall_ms: _wall, ts_mono_ms: _mono, ...event }) => event;
50
- return isDeepStrictEqual(withoutDeliveryTime(existing), withoutDeliveryTime(incoming));
166
+ const left = withoutDeliveryTime(existing);
167
+ const right = withoutDeliveryTime(incoming);
168
+ if (isDeepStrictEqual(left, right)) return null;
169
+ return { reason: "field_mismatch", ...changedConflictFields(left, right) };
51
170
  } catch {
52
171
  // Malformed retained data is not proof that the new event is already durable.
53
- return false;
172
+ return { reason: "invalid_json" };
54
173
  }
55
174
  };
56
175
 
57
- const conflictingEntry = () => {
176
+ const conflictingEntry = (diagnostic) => {
58
177
  const error = new Error("raw event spool entry conflicts with existing event_id");
59
178
  error.code = RAW_EVENT_SPOOL_CONFLICT_CODE;
179
+ if (diagnostic) error.spoolConflict = diagnostic;
60
180
  return error;
61
181
  };
62
182
 
@@ -112,7 +232,8 @@ const readExistingEntry = async (directory, destination, bytes, eventId) => {
112
232
  try {
113
233
  return await atSpoolStage("existing_entry", async () => {
114
234
  const existing = await readFile(destination, "utf8");
115
- if (!sameEventApartFromDeliveryTime(existing, bytes)) throw conflictingEntry();
235
+ const mismatch = compareEventApartFromDeliveryTime(existing, bytes);
236
+ if (mismatch) throw conflictingEntry({ branch: "active_comparison", ...mismatch });
116
237
  await chmod(destination, 0o600);
117
238
  await syncDirectory(directory);
118
239
  return { eventId, serialized: existing };
@@ -123,6 +244,30 @@ const readExistingEntry = async (directory, destination, bytes, eventId) => {
123
244
  }
124
245
  };
125
246
 
247
+ const readRejectedEntry = async (directory, name, eventId) => {
248
+ try {
249
+ const entry = await readRegularSpoolFile(join(directory, name), { makePrivate: true });
250
+ requireMatchingIdentity(entry.serialized, spoolFilename(eventId));
251
+ return entry;
252
+ } catch (error) {
253
+ if (error?.code === "ENOENT") return null;
254
+ throw error;
255
+ }
256
+ };
257
+
258
+ const readMatchingRejectedEntry = async (directory, eventId, bytes) => {
259
+ let existing = null;
260
+ for (const [status, reason] of rejectedReasons) {
261
+ const entry = await readRejectedEntry(directory, rejectedFilename(eventId, status, reason), eventId);
262
+ if (!entry) continue;
263
+ const mismatch = compareEventApartFromDeliveryTime(entry.serialized, bytes);
264
+ if (mismatch) throw conflictingEntry({ branch: "rejected_comparison", ...mismatch });
265
+ existing = { eventId, serialized: entry.serialized };
266
+ }
267
+ if (existing) await syncDirectory(directory);
268
+ return existing;
269
+ };
270
+
126
271
  const requireSpoolCapacity = async (directory, maxEntries) =>
127
272
  atSpoolStage("capacity", async () => {
128
273
  const directoryEntries = await readdir(directory, { withFileTypes: true });
@@ -144,7 +289,8 @@ const publishSpoolEntry = async (temporary, destination, bytes) => {
144
289
  } catch (error) {
145
290
  if (error?.code !== "EEXIST") throw error;
146
291
  const existing = await readFile(destination, "utf8");
147
- if (!sameEventApartFromDeliveryTime(existing, bytes)) throw conflictingEntry();
292
+ const mismatch = compareEventApartFromDeliveryTime(existing, bytes);
293
+ if (mismatch) throw conflictingEntry({ branch: "publish_comparison", ...mismatch });
148
294
  await chmod(destination, 0o600);
149
295
  }
150
296
  await chmod(destination, 0o600);
@@ -174,7 +320,9 @@ const writeRawEventSpoolEntryUnlocked = async ({
174
320
 
175
321
  await atSpoolStage("directory", () => ensurePrivateDirectory(directory));
176
322
  const existing = await readExistingEntry(directory, destination, bytes, eventId);
177
- if (existing) return existing;
323
+ const rejected = await atSpoolStage("existing_entry", () =>
324
+ readMatchingRejectedEntry(directory, eventId, bytes));
325
+ if (rejected || existing) return rejected || existing;
178
326
  await requireSpoolCapacity(directory, normalizedMaxEntries);
179
327
  await publishSpoolEntry(temporary, destination, bytes);
180
328
  await atSpoolStage("directory_sync", () => syncDirectory(directory));
@@ -182,11 +330,10 @@ const writeRawEventSpoolEntryUnlocked = async ({
182
330
  return { eventId, serialized: bytes };
183
331
  };
184
332
 
185
- const writeRawEventSpoolEntry = async (options) => {
186
- const directory = resolveSpoolDirectory(options?.homeDir);
333
+ const serializeSpoolMutation = (directory, action) => {
187
334
  const previousWrite = spoolWritesInFlight.get(directory);
188
335
  const writePromise = (previousWrite ? previousWrite.catch(() => {}) : Promise.resolve())
189
- .then(() => writeRawEventSpoolEntryUnlocked(options));
336
+ .then(action);
190
337
  const trackedWrite = writePromise.finally(() => {
191
338
  if (spoolWritesInFlight.get(directory) === trackedWrite) {
192
339
  spoolWritesInFlight.delete(directory);
@@ -196,31 +343,466 @@ const writeRawEventSpoolEntry = async (options) => {
196
343
  return trackedWrite;
197
344
  };
198
345
 
199
- const removeRawEventSpoolEntry = async ({ eventId, homeDir = homedir() }) => {
200
- const normalizedEventId = requireEventId({ event_id: eventId });
201
- await rm(
202
- join(resolveSpoolDirectory(homeDir), spoolFilename(normalizedEventId)),
203
- { force: true },
204
- );
346
+ const writeRawEventSpoolEntry = async (options) =>
347
+ serializeSpoolMutation(resolveSpoolDirectory(options?.homeDir), () =>
348
+ writeRawEventSpoolEntryUnlocked(options));
349
+
350
+ const requireSameInode = async (path, expected) => {
351
+ const actual = await lstat(path);
352
+ if (!actual.isFile() || actual.dev !== expected.dev || actual.ino !== expected.ino) {
353
+ throw conflictingEntry();
354
+ }
205
355
  };
206
356
 
207
- const loadRawEventSpoolEntries = async ({
208
- homeDir = homedir(),
209
- limit = DEFAULT_DRAIN_LIMIT,
210
- } = {}) => {
357
+ const publishRejectedEntry = async (directory, source, destination, active) => {
358
+ await requireSameInode(source, active.details);
359
+ try {
360
+ await link(source, destination);
361
+ } catch (error) {
362
+ if (error?.code !== "EEXIST") throw error;
363
+ }
364
+ const retained = await readRegularSpoolFile(destination, { makePrivate: true });
365
+ if (retained.serialized !== active.serialized) {
366
+ throw conflictingEntry();
367
+ }
368
+ // Both names must survive a crash before removing the active name.
369
+ await atSpoolStage("rejected_directory_sync", () => syncDirectory(directory));
370
+ await requireSameInode(destination, retained.details);
371
+ await requireSameInode(source, active.details);
372
+ await atSpoolStage("rejected_unlink", () => rm(source));
373
+ await atSpoolStage("rejected_final_sync", () => syncDirectory(directory));
374
+ return retained;
375
+ };
376
+
377
+ const retainRejectedRawEventSpoolEntryUnlocked = async ({ eventId, status, reason, homeDir }) => {
378
+ const normalizedEventId = requireEventId({ event_id: eventId });
379
+ if (!rejectedReasons.has(status) || rejectedReasons.get(status) !== reason) {
380
+ throw new Error("unsupported raw event rejection");
381
+ }
211
382
  const directory = resolveSpoolDirectory(homeDir);
212
- let directoryEntries;
383
+ await requirePrivateSpoolDirectory(directory);
384
+ await chmod(directory, 0o700);
385
+ const name = rejectedFilename(normalizedEventId, status, reason);
386
+ const source = join(directory, spoolFilename(normalizedEventId));
387
+ let active;
213
388
  try {
214
- directoryEntries = await readdir(directory, { withFileTypes: true });
389
+ active = await readRegularSpoolFile(source, { makePrivate: true });
390
+ } catch (error) {
391
+ if (error?.code !== "ENOENT") throw error;
392
+ const retained = await readRejectedEntry(directory, name, normalizedEventId);
393
+ if (!retained) throw error;
394
+ await syncDirectory(directory);
395
+ return rejectedMetadata(name, { status, reason }, retained.details.size);
396
+ }
397
+ requireMatchingIdentity(active.serialized, spoolFilename(normalizedEventId));
398
+ for (const [otherStatus, otherReason] of rejectedReasons) {
399
+ if (otherStatus === status) continue;
400
+ const other = await readRejectedEntry(directory,
401
+ rejectedFilename(normalizedEventId, otherStatus, otherReason), normalizedEventId);
402
+ if (other) throw conflictingEntry();
403
+ }
404
+ const retained = await publishRejectedEntry(directory, source, join(directory, name), active);
405
+ return rejectedMetadata(name, { status, reason }, retained.details.size);
406
+ };
407
+
408
+ const retainRejectedRawEventSpoolEntry = async (options) =>
409
+ serializeSpoolMutation(resolveSpoolDirectory(options?.homeDir), async () => {
410
+ const digest = spoolFilename(requireEventId({ event_id: options.eventId })).slice(0, -5);
411
+ const lock = await acquireRejectedSpoolLock(resolveSpoolDirectory(options.homeDir), digest);
412
+ let outcome;
413
+ try {
414
+ outcome = { retained: await retainRejectedRawEventSpoolEntryUnlocked(options) };
415
+ } catch (error) {
416
+ outcome = { error };
417
+ }
418
+ try {
419
+ await releaseRejectedSpoolLock(lock);
420
+ } catch {
421
+ if ("retained" in outcome) return { ...outcome.retained, lock: "release_failed" };
422
+ try {
423
+ Object.defineProperty(outcome.error, "lock", {
424
+ value: "release_failed", enumerable: true, configurable: true, writable: true,
425
+ });
426
+ } catch {
427
+ // Preserve the primary failure even when it is frozen or is a thrown primitive.
428
+ }
429
+ }
430
+ if ("error" in outcome) throw outcome.error;
431
+ return outcome.retained;
432
+ });
433
+
434
+ class RawEventSpoolInspectionError extends Error {
435
+ constructor(code, message) {
436
+ super(message);
437
+ this.name = "RawEventSpoolInspectionError";
438
+ this.code = code;
439
+ }
440
+ }
441
+
442
+ const inspectionFailure = () => new RawEventSpoolInspectionError(
443
+ "inspection_failed", "Could not inspect retained events. Files were left untouched.",
444
+ );
445
+
446
+ const requireInspectionRegularFile = (details) => {
447
+ if (!details.isFile() || details.isSymbolicLink()) {
448
+ throw new RawEventSpoolInspectionError("unsafe_entry", "Receipt must name a regular file.");
449
+ }
450
+ };
451
+
452
+ const openRejectedEntryForInspection = async (path) => {
453
+ const expected = await lstat(path);
454
+ requireInspectionRegularFile(expected);
455
+ const flags = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
456
+ const handle = await open(path, flags);
457
+ try {
458
+ // lstat also rejects links where O_NOFOLLOW is unavailable. Check both the
459
+ // opened file and its current name before reading any private bytes.
460
+ for (const actual of [await handle.stat(), await lstat(path)]) {
461
+ requireInspectionRegularFile(actual);
462
+ if (actual.dev !== expected.dev || actual.ino !== expected.ino) {
463
+ throw new RawEventSpoolInspectionError("unsafe_entry", "Receipt changed while opening. Retry inspection.");
464
+ }
465
+ }
466
+ return handle;
215
467
  } catch (error) {
468
+ await handle.close().catch(() => {});
469
+ throw error;
470
+ }
471
+ };
472
+
473
+ const readWithinInspectionLimit = async (handle, maxBytes, { position = null } = {}) => {
474
+ const chunks = [];
475
+ let total = 0;
476
+ while (total <= maxBytes) {
477
+ const buffer = Buffer.alloc(Math.min(INSPECTION_READ_CHUNK_BYTES, maxBytes + 1 - total));
478
+ const offset = position === null ? null : position + total;
479
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset);
480
+ if (bytesRead === 0) return Buffer.concat(chunks, total);
481
+ total += bytesRead;
482
+ if (total > maxBytes) return null;
483
+ chunks.push(buffer.subarray(0, bytesRead));
484
+ }
485
+ return null;
486
+ };
487
+
488
+ const inspectOpenedRejectedEntry = async (handle, receipt, entry, maxBytes) => {
489
+ const before = await handle.stat();
490
+ requireInspectionRegularFile(before);
491
+ const metadata = rejectedMetadata(receipt, entry, before.size);
492
+ if (before.size > maxBytes) return { ...metadata, validation: "read_limit_exceeded" };
493
+ const bytes = await readWithinInspectionLimit(handle, maxBytes);
494
+ const after = await handle.stat();
495
+ if (!bytes || after.size > maxBytes) {
496
+ return { ...metadata, bytes: after.size, validation: "read_limit_exceeded" };
497
+ }
498
+ if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) {
499
+ return { ...metadata, validation: "changed_during_read" };
500
+ }
501
+ try {
502
+ if (!isUtf8(bytes)) return { ...metadata, validation: "invalid" };
503
+ const serialized = bytes.toString("utf8");
504
+ requireMatchingIdentity(serialized, `${entry.digest}.json`);
505
+ return { ...metadata, validation: "valid", serialized };
506
+ } catch {
507
+ return { ...metadata, validation: "invalid" };
508
+ }
509
+ };
510
+
511
+ const inspectRejectedRawEventSpoolEntry = async ({
512
+ receipt, homeDir = homedir(), maxBytes = MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES,
513
+ }) => {
514
+ const entry = typeof receipt === "string" ? parseRejectedFilename(receipt) : null;
515
+ if (!entry) {
516
+ throw new RawEventSpoolInspectionError("invalid_receipt", "Use a receipt from capture list-rejected.");
517
+ }
518
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES) {
519
+ throw new RawEventSpoolInspectionError("invalid_limit", "Inspection limit must be between 1 byte and 16 MiB.");
520
+ }
521
+ let handle;
522
+ try {
523
+ const directory = resolveSpoolDirectory(homeDir);
524
+ await requirePrivateSpoolDirectory(directory);
525
+ handle = await openRejectedEntryForInspection(join(directory, receipt));
526
+ return await inspectOpenedRejectedEntry(handle, receipt, entry, maxBytes);
527
+ } catch (error) {
528
+ if (error instanceof RawEventSpoolInspectionError) throw error;
216
529
  if (error?.code === "ENOENT") {
217
- return { entries: [], corruptCount: 0 };
530
+ throw new RawEventSpoolInspectionError("receipt_not_found", "Retained receipt was not found. Run capture list-rejected again.");
531
+ }
532
+ throw inspectionFailure();
533
+ } finally {
534
+ await handle?.close().catch(() => {});
535
+ }
536
+ };
537
+
538
+ const sameFileSnapshot = (actual, expected) => actual.isFile()
539
+ && !actual.isSymbolicLink()
540
+ && actual.dev === expected.dev && actual.ino === expected.ino
541
+ && actual.size === expected.size
542
+ && actual.mtimeMs === expected.mtimeMs && actual.ctimeMs === expected.ctimeMs;
543
+
544
+ const rejectedLockError = (code) => new RawEventSpoolInspectionError(
545
+ code, "Retained event lock is unavailable. Stop capture before repairing its lock.",
546
+ );
547
+
548
+ const classifyExistingRejectedLock = async (path, digest) => {
549
+ let handle;
550
+ try {
551
+ handle = await openRejectedEntryForInspection(path);
552
+ const before = await handle.stat();
553
+ if (before.size > REJECTED_LOCK_RECORD_MAX_BYTES) throw rejectedLockError("lock_repair_required");
554
+ const bytes = await readWithinInspectionLimit(handle, REJECTED_LOCK_RECORD_MAX_BYTES);
555
+ if (!bytes || !isUtf8(bytes) || !sameFileSnapshot(await handle.stat(), before)
556
+ || !sameFileSnapshot(await lstat(path), before)) throw rejectedLockError("lock_repair_required");
557
+ const record = JSON.parse(bytes.toString("utf8"));
558
+ if (!record || Object.keys(record).sort().join() !== "digest,pid,purpose,token,version"
559
+ || record.purpose !== REJECTED_LOCK_PURPOSE || record.version !== 1 || record.digest !== digest
560
+ || !Number.isSafeInteger(record.pid) || record.pid <= 0
561
+ || typeof record.token !== "string"
562
+ || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(record.token)) {
563
+ throw rejectedLockError("lock_repair_required");
564
+ }
565
+ try {
566
+ process.kill(record.pid, 0);
567
+ } catch (error) {
568
+ if (error?.code === "ESRCH") return "lock_repair_required";
218
569
  }
570
+ return "lock_busy";
571
+ } catch {
572
+ return "lock_repair_required";
573
+ } finally {
574
+ await handle?.close().catch(() => {});
575
+ }
576
+ };
577
+
578
+ const acquireRejectedSpoolLock = async (directory, digest) => {
579
+ await requirePrivateSpoolDirectory(directory);
580
+ const path = join(directory, `.rejected-${digest}.lock`);
581
+ let handle;
582
+ try {
583
+ handle = await open(path, "wx+", 0o600);
584
+ } catch (error) {
585
+ if (error?.code === "EEXIST") throw rejectedLockError(await classifyExistingRejectedLock(path, digest));
586
+ throw rejectedLockError("lock_failed");
587
+ }
588
+ try {
589
+ const serialized = JSON.stringify({
590
+ purpose: REJECTED_LOCK_PURPOSE, version: 1, digest, pid: process.pid, token: randomUUID(),
591
+ });
592
+ await handle.writeFile(serialized, { encoding: "utf8" });
593
+ await handle.sync();
594
+ const details = await handle.stat();
595
+ requireInspectionRegularFile(details);
596
+ await requirePrivateSpoolDirectory(directory);
597
+ if (!sameFileSnapshot(await lstat(path), details)) throw rejectedLockError("lock_repair_required");
598
+ return { directory, path, handle, serialized, details };
599
+ } catch {
600
+ // An incomplete or unverifiable named lock needs manual repair, never age-based removal.
601
+ await handle.close().catch(() => {});
602
+ throw rejectedLockError("lock_repair_required");
603
+ }
604
+ };
605
+
606
+ const assertRejectedSpoolLock = async (lock) => {
607
+ await requirePrivateSpoolDirectory(lock.directory);
608
+ const bytes = await readWithinInspectionLimit(lock.handle, REJECTED_LOCK_RECORD_MAX_BYTES, { position: 0 });
609
+ if (!bytes || bytes.toString("utf8") !== lock.serialized
610
+ || !sameFileSnapshot(await lock.handle.stat(), lock.details)
611
+ || !sameFileSnapshot(await lstat(lock.path), lock.details)) {
612
+ throw rejectedLockError("lock_release_failed");
613
+ }
614
+ };
615
+
616
+ const releaseRejectedSpoolLock = async (lock) => {
617
+ try {
618
+ await assertRejectedSpoolLock(lock);
619
+ await rm(lock.path);
620
+ await syncDirectory(lock.directory);
621
+ } catch {
622
+ throw rejectedLockError("lock_release_failed");
623
+ } finally {
624
+ await lock.handle.close().catch(() => {});
625
+ }
626
+ };
627
+
628
+ const deliveryAcknowledgement = async (deliver, serialized) => {
629
+ let result;
630
+ try {
631
+ result = await deliver({ serialized });
632
+ } catch {
633
+ return { delivery: "unacknowledged", cleanup: "not_attempted", reason: "delivery_failed" };
634
+ }
635
+ try {
636
+ const isRecord = result && typeof result === "object" && !Array.isArray(result);
637
+ const keys = isRecord ? Reflect.ownKeys(result).sort().join() : "";
638
+ const acknowledged = isRecord ? Object.getOwnPropertyDescriptor(result, "acknowledged")?.value : undefined;
639
+ const acknowledgement = isRecord ? Object.getOwnPropertyDescriptor(result, "acknowledgement")?.value : undefined;
640
+ if (result === false || (keys === "acknowledged" && acknowledged === false)) {
641
+ return { delivery: "unacknowledged", cleanup: "not_attempted", reason: "delivery_rejected" };
642
+ }
643
+ if (keys === "acknowledged,acknowledgement" && acknowledged === true
644
+ && ["queued", "ingested"].includes(acknowledgement)) {
645
+ return { delivery: "accepted", acknowledgement };
646
+ }
647
+ } catch {
648
+ // An exception while inspecting the result does not confirm delivery.
649
+ }
650
+ return { delivery: "unacknowledged", cleanup: "not_attempted", reason: "invalid_acknowledgement" };
651
+ };
652
+
653
+ const removeRecoveredSnapshot = async (snapshot, lock) => {
654
+ let current;
655
+ try {
656
+ await requirePrivateSpoolDirectory(snapshot.directory);
657
+ current = await openRejectedEntryForInspection(snapshot.path);
658
+ if (!sameFileSnapshot(await snapshot.handle.stat(), snapshot.details)
659
+ || !sameFileSnapshot(await current.stat(), snapshot.details)) return "changed";
660
+ const bytes = await readWithinInspectionLimit(current, MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES);
661
+ if (!bytes?.equals(Buffer.from(snapshot.serialized, "utf8"))
662
+ || createHash("sha256").update(bytes).digest("hex") !== snapshot.digest
663
+ || !sameFileSnapshot(await current.stat(), snapshot.details)
664
+ || !sameFileSnapshot(await lstat(snapshot.path), snapshot.details)) return "changed";
665
+ } catch (error) {
666
+ if (error instanceof RawEventSpoolInspectionError || ["ENOENT", "ELOOP"].includes(error?.code)) return "changed";
667
+ return "failed";
668
+ } finally {
669
+ await current?.close().catch(() => {});
670
+ }
671
+ try {
672
+ await assertRejectedSpoolLock(lock);
673
+ if (!sameFileSnapshot(await lstat(snapshot.path), snapshot.details)) return "changed";
674
+ await rm(snapshot.path);
675
+ } catch {
676
+ return "failed";
677
+ }
678
+ try {
679
+ await syncDirectory(snapshot.directory);
680
+ return "removed";
681
+ } catch {
682
+ return "uncertain";
683
+ }
684
+ };
685
+
686
+ const deliverRejectedSnapshot = async ({ directory, receipt, entry, deliver }, lock) => {
687
+ let handle;
688
+ try {
689
+ const path = join(directory, receipt);
690
+ handle = await openRejectedEntryForInspection(path);
691
+ const details = await handle.stat();
692
+ const inspection = await inspectOpenedRejectedEntry(handle, receipt, entry, MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES);
693
+ if (inspection.validation !== "valid") {
694
+ return { delivery: "not_attempted", cleanup: "not_attempted", reason: inspection.validation };
695
+ }
696
+ if (!sameFileSnapshot(await handle.stat(), details) || !sameFileSnapshot(await lstat(path), details)) {
697
+ return { delivery: "not_attempted", cleanup: "not_attempted", reason: "changed_during_read" };
698
+ }
699
+ const snapshot = { directory, path, handle, details, serialized: inspection.serialized,
700
+ digest: createHash("sha256").update(inspection.serialized, "utf8").digest("hex") };
701
+ const delivery = await deliveryAcknowledgement(deliver, snapshot.serialized);
702
+ if (delivery.delivery !== "accepted") return delivery;
703
+ return { ...delivery, cleanup: await removeRecoveredSnapshot(snapshot, lock) };
704
+ } finally {
705
+ await handle?.close().catch(() => {});
706
+ }
707
+ };
708
+
709
+ const recoveryFailure = (error) => {
710
+ const safeCodes = ["lock_busy", "lock_repair_required", "lock_failed", "unsafe_entry"];
711
+ let reason = "inspection_failed";
712
+ if (error instanceof RawEventSpoolInspectionError && safeCodes.includes(error.code)) reason = error.code;
713
+ if (error?.code === "ENOENT") reason = "receipt_not_found";
714
+ return { delivery: "not_attempted", cleanup: "not_attempted", reason };
715
+ };
716
+
717
+ const recoverRejectedEntryUnlocked = async (options) => {
718
+ let lock;
719
+ let result;
720
+ try {
721
+ lock = await acquireRejectedSpoolLock(options.directory, options.entry.digest);
722
+ result = await deliverRejectedSnapshot(options, lock);
723
+ } catch (error) {
724
+ result = recoveryFailure(error);
725
+ }
726
+ if (!lock) return { ...result, lock: "not_acquired" };
727
+ try {
728
+ await releaseRejectedSpoolLock(lock);
729
+ return { ...result, lock: "released" };
730
+ } catch {
731
+ return { ...result, lock: "release_failed" };
732
+ }
733
+ };
734
+
735
+ const recoverRejectedRawEventSpoolEntry = async ({ receipt, homeDir = homedir(), deliver } = {}) => {
736
+ const entry = typeof receipt === "string" ? parseRejectedFilename(receipt) : null;
737
+ if (!entry || typeof deliver !== "function") {
738
+ return { delivery: "not_attempted", cleanup: "not_attempted", lock: "not_acquired",
739
+ reason: entry ? "invalid_delivery" : "invalid_receipt" };
740
+ }
741
+ try {
742
+ const directory = resolveSpoolDirectory(homeDir);
743
+ return await serializeSpoolMutation(directory, () =>
744
+ recoverRejectedEntryUnlocked({ directory, receipt, entry, deliver }));
745
+ } catch (error) {
746
+ return { ...recoveryFailure(error), lock: "not_acquired" };
747
+ }
748
+ };
749
+
750
+ const listRejectedEntries = async ({ homeDir, validation }) => {
751
+ const directory = resolveSpoolDirectory(homeDir);
752
+ let names;
753
+ try {
754
+ await requirePrivateSpoolDirectory(directory);
755
+ names = await readdir(directory, { withFileTypes: true });
756
+ } catch (error) {
757
+ if (error?.code === "ENOENT") return [];
219
758
  throw error;
220
759
  }
760
+ const entries = [];
761
+ for (const candidate of names) {
762
+ const entry = parseRejectedFilename(candidate.name);
763
+ if (!candidate.isFile() || !entry) continue;
764
+ try {
765
+ if (validation === "metadata") {
766
+ const details = await lstat(join(directory, candidate.name));
767
+ if (details.isFile()) {
768
+ entries.push({ ...rejectedMetadata(candidate.name, entry, details.size), validation: "not_checked" });
769
+ }
770
+ continue;
771
+ }
772
+ const retained = await readRegularSpoolFile(join(directory, candidate.name));
773
+ requireMatchingIdentity(retained.serialized, `${entry.digest}.json`);
774
+ entries.push(rejectedMetadata(candidate.name, entry, retained.details.size));
775
+ } catch {
776
+ // Invalid or concurrently removed files expose no payload or filesystem details.
777
+ }
778
+ }
779
+ return entries.sort((left, right) => left.receipt.localeCompare(right.receipt));
780
+ };
781
+
782
+ const listRejectedRawEventSpoolEntries = async ({ homeDir = homedir(), validation = "payload" } = {}) => {
783
+ if (!["metadata", "payload"].includes(validation)) {
784
+ throw new RawEventSpoolInspectionError("invalid_validation", "Unsupported inspection mode.");
785
+ }
786
+ try {
787
+ return await listRejectedEntries({ homeDir, validation });
788
+ } catch (error) {
789
+ if (validation === "payload") throw error;
790
+ throw inspectionFailure();
791
+ }
792
+ };
221
793
 
794
+ const removeRawEventSpoolEntry = async ({ eventId, homeDir = homedir() }) => {
795
+ const normalizedEventId = requireEventId({ event_id: eventId });
796
+ await rm(
797
+ join(resolveSpoolDirectory(homeDir), spoolFilename(normalizedEventId)),
798
+ { force: true },
799
+ );
800
+ };
801
+
802
+ const findActiveSpoolCandidates = async (directory, directoryEntries) => {
222
803
  const candidates = [];
223
804
  for (const directoryEntry of directoryEntries) {
805
+ if (parseRejectedFilename(directoryEntry.name)) continue;
224
806
  if (!directoryEntry.isFile() || !directoryEntry.name.endsWith(".json")) {
225
807
  continue;
226
808
  }
@@ -235,6 +817,25 @@ const loadRawEventSpoolEntries = async ({
235
817
  candidates.sort(
236
818
  (left, right) => left.mtimeMs - right.mtimeMs || left.name.localeCompare(right.name),
237
819
  );
820
+ return candidates;
821
+ };
822
+
823
+ const loadRawEventSpoolEntries = async ({
824
+ homeDir = homedir(),
825
+ limit = DEFAULT_DRAIN_LIMIT,
826
+ } = {}) => {
827
+ const directory = resolveSpoolDirectory(homeDir);
828
+ let directoryEntries;
829
+ try {
830
+ directoryEntries = await readdir(directory, { withFileTypes: true });
831
+ } catch (error) {
832
+ if (error?.code === "ENOENT") {
833
+ return { entries: [], corruptCount: 0 };
834
+ }
835
+ throw error;
836
+ }
837
+
838
+ const candidates = await findActiveSpoolCandidates(directory, directoryEntries);
238
839
 
239
840
  const entries = [];
240
841
  let corruptCount = 0;
@@ -265,10 +866,16 @@ const loadRawEventSpoolEntries = async ({
265
866
  export {
266
867
  DEFAULT_DRAIN_LIMIT,
267
868
  DEFAULT_MAX_ENTRIES,
869
+ inspectRejectedRawEventSpoolEntry,
870
+ listRejectedRawEventSpoolEntries,
268
871
  loadRawEventSpoolEntries,
872
+ MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES,
269
873
  RAW_EVENT_SPOOL_CONFLICT_CODE,
270
874
  RAW_EVENT_SPOOL_FULL_CODE,
875
+ RawEventSpoolInspectionError,
876
+ recoverRejectedRawEventSpoolEntry,
271
877
  removeRawEventSpoolEntry,
272
878
  resolveSpoolDirectory,
879
+ retainRejectedRawEventSpoolEntry,
273
880
  writeRawEventSpoolEntry,
274
881
  };