@codemem/opencode-plugin 0.48.0 → 0.49.0-beta.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.
@@ -9,11 +9,55 @@ import {
9
9
  RAW_EVENT_SPOOL_FULL_CODE,
10
10
  removeRawEventSpoolEntry,
11
11
  resolveSpoolDirectory,
12
+ retainRejectedRawEventSpoolEntry,
12
13
  writeRawEventSpoolEntry,
13
14
  } from "./raw-event-spool.js";
14
15
 
15
16
  const rawEventSpoolDrainsInFlight = new Map();
16
17
 
18
+ // Mirror the Viewer's explicit validation responses without importing server code.
19
+ const TERMINAL_VALIDATION_MESSAGES = new Set([
20
+ "source must be string",
21
+ "source is required",
22
+ "source must use 1-64 letters, digits, dots, underscores, or hyphens",
23
+ "session_stream_id must be string",
24
+ "session_id must be string",
25
+ "stream_id must be string",
26
+ "opencode_session_id must be string",
27
+ "conflicting session id fields",
28
+ "invalid session id",
29
+ "event source conflicts with request source",
30
+ "session id required",
31
+ "event_type must be string",
32
+ "event_type required",
33
+ "event_type has invalid syntax",
34
+ "event_id must be string",
35
+ "event_id required",
36
+ "event_id has invalid syntax",
37
+ "event_seq must be int",
38
+ "ts_wall_ms must be number",
39
+ "ts_mono_ms must be number",
40
+ "payload must be an object",
41
+ "cwd must be string",
42
+ "project must be string",
43
+ "started_at must be string",
44
+ "events must be a list",
45
+ "event must be an object",
46
+ ]);
47
+
48
+ export const classifyRawEventTerminalRejection = ({ status, responseBody, outgoingBytes }) => {
49
+ if (!responseBody || typeof responseBody !== "object" || Array.isArray(responseBody)) return null;
50
+ if (status === 400 && TERMINAL_VALIDATION_MESSAGES.has(responseBody.error)) {
51
+ return { status: 400, reason: "invalid_payload" };
52
+ }
53
+ if (status === 413 && responseBody.error === "payload too large"
54
+ && Number.isFinite(responseBody.max_bytes) && responseBody.max_bytes > 0
55
+ && Number.isFinite(outgoingBytes) && outgoingBytes > responseBody.max_bytes) {
56
+ return { status: 413, reason: "payload_too_large" };
57
+ }
58
+ return null;
59
+ };
60
+
17
61
  export const classifyRawEventTransportCause = (error) => {
18
62
  const diagnostic = [
19
63
  error?.name,
@@ -49,6 +93,7 @@ const createDeliveryState = (options) => ({
49
93
  latestViewerFailure: null,
50
94
  lastToastAtBySession: new Map(),
51
95
  options,
96
+ retainedPayloads: new WeakSet(),
52
97
  spoolDirectory: resolveSpoolDirectory(options.spoolHome),
53
98
  spoolCorruptionNoted: false,
54
99
  spoolLoadFailureNoted: false,
@@ -100,6 +145,33 @@ const warnSpoolPersistenceFailure = async (state, sessionID, reason) => {
100
145
 
101
146
  const SPOOL_STAGES = new Set(["directory", "existing_entry", "capacity", "temporary_write", "publish", "directory_sync"]);
102
147
  const SPOOL_ERRNOS = new Set(["EACCES", "EPERM", "ENOSPC", "EROFS", "ENOTDIR", "EEXIST", "EIO", "EINVAL", "EMFILE", "ENFILE"]);
148
+ const SPOOL_CONFLICT_BRANCHES = ["active_comparison", "rejected_comparison", "rejected_identity", "publish_comparison"];
149
+ const SPOOL_CONFLICT_REASONS = ["invalid_json", "invalid_shape", "field_mismatch", "identity_mismatch"];
150
+ const SPOOL_CONFLICT_FIELDS = [
151
+ "started_at", "host_generation", "capture_context", "session_stream_id", "session_id",
152
+ "stream_id", "opencode_session_id", "cwd", "project", "source", "event_type",
153
+ "payload", "payload.timestamp", "payload._adapter", "payload._adapter.ts", "payload._raw_spooled", "payload.args",
154
+ ];
155
+
156
+ const spoolConflictDiagnostic = (error) => {
157
+ try {
158
+ const diagnostic = error?.spoolConflict;
159
+ // Rebuild from literals at the logging boundary, including for foreign errors.
160
+ const branch = SPOOL_CONFLICT_BRANCHES.find((value) => value === diagnostic?.branch);
161
+ const reason = SPOOL_CONFLICT_REASONS.find((value) => value === diagnostic?.reason);
162
+ if (!branch || !reason) return "";
163
+ const fields = diagnostic.fields;
164
+ const changed = Array.isArray(fields)
165
+ ? SPOOL_CONFLICT_FIELDS.filter((field) => fields.includes(field))
166
+ : [];
167
+ let suffix = ` branch=${branch} reason=${reason}`;
168
+ if (changed.length) suffix += ` fields=${changed.join(",")}`;
169
+ if (diagnostic.other === true) suffix += " other=true";
170
+ return suffix;
171
+ } catch {
172
+ return "";
173
+ }
174
+ };
103
175
 
104
176
  const spoolFailureDiagnostic = (error) => {
105
177
  const stage = SPOOL_STAGES.has(error?.spoolStage) ? error.spoolStage : "unknown";
@@ -107,7 +179,8 @@ const spoolFailureDiagnostic = (error) => {
107
179
  if (error?.code === RAW_EVENT_SPOOL_CONFLICT_CODE) code = "conflict";
108
180
  else if (error?.code === RAW_EVENT_SPOOL_FULL_CODE) code = "full";
109
181
  else if (SPOOL_ERRNOS.has(error?.code)) code = error.code;
110
- return `raw_events.spool.failure stage=${stage} code=${code} category=persistence`;
182
+ return `raw_events.spool.failure stage=${stage} code=${code} category=persistence`
183
+ + spoolConflictDiagnostic(error);
111
184
  };
112
185
 
113
186
  const persistSafeSpoolDiagnostic = async (state, line) => {
@@ -118,12 +191,16 @@ const persistSafeSpoolDiagnostic = async (state, line) => {
118
191
 
119
192
  const persistForRetry = async (state, { body, serialized, payload, sessionID }) => {
120
193
  try {
121
- await writeRawEventSpoolEntry({
194
+ const stored = await writeRawEventSpoolEntry({
122
195
  envelope: body,
123
196
  serialized,
124
197
  homeDir: state.options.spoolHome,
125
198
  maxEntries: state.options.spoolMaxEntries,
126
199
  });
200
+ if (typeof stored?.serialized === "string" && stored.serialized !== serialized
201
+ && payload && typeof payload === "object") {
202
+ state.envelopes.set(payload, { body: JSON.parse(stored.serialized), serialized: stored.serialized });
203
+ }
127
204
  state.spoolPersistenceFailureNoted = null;
128
205
  if (payload && typeof payload === "object") payload._raw_spooled = true;
129
206
  return true;
@@ -267,6 +344,48 @@ const armViewerBackoff = (state, error, timing) => {
267
344
  return viewerFailure;
268
345
  };
269
346
 
347
+ const warnRejectedEntry = async (state, { rejection, outcome, sessionID }) => {
348
+ const messages = {
349
+ retained: "codemem retained a rejected raw event; inspect it with codemem diagnostics capture list-rejected",
350
+ retain_failed: "codemem could not retain a rejected raw event outside retries; inspect saved events before retrying",
351
+ lock_release_failed: "codemem could not release a rejected-event lock; stop capture and inspect saved events before repairing the lock",
352
+ };
353
+ const message = messages[outcome];
354
+ await state.options.logLine(
355
+ `raw_events.spool.${outcome} status=${rejection.status} reason=${rejection.reason}`
356
+ );
357
+ await bestEffortHostLog(state, {
358
+ service: "codemem",
359
+ level: outcome === "retained" ? "warn" : "error",
360
+ message,
361
+ extra: { category: "rejection", status: rejection.status, reason: rejection.reason, outcome },
362
+ });
363
+ if (!state.options.hostNotify || !shouldToast(state, sessionID, `rejection:${outcome}`)) return;
364
+ await bestEffortNotify(state, { message, variant: outcome === "retained" ? "warning" : "error" });
365
+ };
366
+
367
+ const retainRejectedEntry = async (state, { eventId, rejection, sessionID, payload }) => {
368
+ let retained;
369
+ try {
370
+ retained = await retainRejectedRawEventSpoolEntry({
371
+ eventId,
372
+ ...rejection,
373
+ homeDir: state.options.spoolHome,
374
+ });
375
+ } catch (error) {
376
+ await warnRejectedEntry(state, { rejection, sessionID, outcome: "retain_failed" });
377
+ if (error?.lock === "release_failed") {
378
+ await warnRejectedEntry(state, { rejection, sessionID, outcome: "lock_release_failed" });
379
+ }
380
+ return;
381
+ }
382
+ if (payload && typeof payload === "object") state.retainedPayloads.add(payload);
383
+ await warnRejectedEntry(state, { rejection, sessionID, outcome: "retained" });
384
+ if (retained.lock === "release_failed") {
385
+ await warnRejectedEntry(state, { rejection, sessionID, outcome: "lock_release_failed" });
386
+ }
387
+ };
388
+
270
389
  const drainLoadedEntries = async (state, loaded) => {
271
390
  if (loaded.corruptCount > 0) {
272
391
  await state.options.logLine(`raw_events.spool.corrupt_retained count=${loaded.corruptCount}`);
@@ -280,6 +399,10 @@ const drainLoadedEntries = async (state, loaded) => {
280
399
  await postToViewer(state, entry.envelope);
281
400
  await removeFromSpool(state, { eventId: entry.eventId });
282
401
  } catch (error) {
402
+ if (error?.rawEventTerminalRejection) {
403
+ await retainRejectedEntry(state, { eventId: entry.eventId, rejection: error.rawEventTerminalRejection });
404
+ continue;
405
+ }
283
406
  await state.options.logLine("raw_events.spool.drain_deferred category=fallback");
284
407
  const status = error?.rawEventFailure?.status;
285
408
  if (!Number.isInteger(status) || status >= 500 || status === 409) {
@@ -381,6 +504,7 @@ const checkViewerAvailability = async (state, now) => {
381
504
 
382
505
  const postToViewer = async (state, body) => {
383
506
  const options = state.options;
507
+ const outgoing = JSON.stringify({ ...body, db_path: options.promptPackDbPath, identity_target: options.identityTarget });
384
508
  const response = await fetch(options.rawEventsUrl, {
385
509
  method: "POST",
386
510
  headers: { "Content-Type": "application/json" },
@@ -388,7 +512,7 @@ const postToViewer = async (state, body) => {
388
512
  state.abortController.signal,
389
513
  AbortSignal.timeout(options.rawEventsStatusTimeoutMs),
390
514
  ]),
391
- body: JSON.stringify({ ...body, db_path: options.promptPackDbPath, identity_target: options.identityTarget }),
515
+ body: outgoing,
392
516
  });
393
517
  if (response.ok) return response;
394
518
  let responseBody = null;
@@ -398,6 +522,11 @@ const postToViewer = async (state, body) => {
398
522
  // Generic connection guidance remains the safe fallback.
399
523
  }
400
524
  const error = new Error(`raw-events post failed (${response.status})`);
525
+ error.rawEventTerminalRejection = classifyRawEventTerminalRejection({
526
+ status: response.status,
527
+ responseBody,
528
+ outgoingBytes: Buffer.byteLength(outgoing, "utf8"),
529
+ });
401
530
  error.rawEventFailureCategory = options.classifyViewerFailure(responseBody);
402
531
  error.rawEventFailure = {
403
532
  stage: "post",
@@ -408,6 +537,23 @@ const postToViewer = async (state, body) => {
408
537
  };
409
538
 
410
539
  const handleViewerFailure = async (state, input, error, timing) => {
540
+ if (error?.rawEventTerminalRejection) {
541
+ const durable = await persistForRetry(state, input);
542
+ if (durable) {
543
+ const canonical = input.payload && typeof input.payload === "object"
544
+ ? state.envelopes.get(input.payload) : null;
545
+ // A size rejection proves only the posted copy was too large. Retry changed saved bytes first.
546
+ if (error.rawEventTerminalRejection.status === 413
547
+ && canonical && canonical.serialized !== input.serialized) return durable;
548
+ await retainRejectedEntry(state, {
549
+ eventId: input.body.event_id,
550
+ rejection: error.rawEventTerminalRejection,
551
+ sessionID: input.sessionID,
552
+ payload: input.payload,
553
+ });
554
+ }
555
+ return durable;
556
+ }
411
557
  if (!state.options.isActive()) return persistForRetry(state, input);
412
558
  const category = error?.rawEventFailureCategory || "connection";
413
559
  const viewerFailure = armViewerBackoff(state, error, timing);
@@ -433,6 +579,7 @@ const deliver = async (state, { sessionID, type, payload }) => {
433
579
  if (!state.options.enabled) return true;
434
580
  if (!sessionID || !type) return false;
435
581
  if (payload?._raw_enqueued) return true;
582
+ if (payload && typeof payload === "object" && state.retainedPayloads.has(payload)) return true;
436
583
  const now = Date.now();
437
584
  const envelope = cachedEnvelope(state, sessionID, type, payload, now);
438
585
  const input = { ...envelope, payload, sessionID };
@@ -0,0 +1,105 @@
1
+ export const DEFAULT_DRAIN_LIMIT: number;
2
+ export const DEFAULT_MAX_ENTRIES: number;
3
+ export const MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES: number;
4
+ export const RAW_EVENT_SPOOL_CONFLICT_CODE: "raw_event_spool_conflict";
5
+ export const RAW_EVENT_SPOOL_FULL_CODE: "raw_event_spool_full";
6
+
7
+ export interface RejectedRawEventMetadata {
8
+ receipt: string;
9
+ bytes: number;
10
+ status: 400 | 413;
11
+ reason: "invalid_payload" | "payload_too_large";
12
+ }
13
+
14
+ export type RejectedRawEventInspection =
15
+ | (RejectedRawEventMetadata & { validation: "valid"; serialized: string })
16
+ | (RejectedRawEventMetadata & {
17
+ validation: "invalid" | "read_limit_exceeded" | "changed_during_read";
18
+ });
19
+
20
+ export class RawEventSpoolInspectionError extends Error {
21
+ code: string;
22
+ constructor(code: string, message: string);
23
+ }
24
+
25
+ export function resolveSpoolDirectory(homeDir?: string): string;
26
+ export function listRejectedRawEventSpoolEntries(options: {
27
+ homeDir?: string;
28
+ validation: "metadata";
29
+ }): Promise<(RejectedRawEventMetadata & { validation: "not_checked" })[]>;
30
+ export function listRejectedRawEventSpoolEntries(options?: {
31
+ homeDir?: string;
32
+ validation?: "payload";
33
+ }): Promise<RejectedRawEventMetadata[]>;
34
+ export function inspectRejectedRawEventSpoolEntry(options: {
35
+ receipt: string;
36
+ homeDir?: string;
37
+ maxBytes?: number;
38
+ }): Promise<RejectedRawEventInspection>;
39
+ export type RejectedRawEventAcknowledgement = {
40
+ acknowledged: true;
41
+ acknowledgement: "queued" | "ingested";
42
+ };
43
+ export type RejectedRawEventDeliveryResult =
44
+ | RejectedRawEventAcknowledgement
45
+ | { acknowledged: false }
46
+ | false;
47
+ export type RejectedRawEventRecoveryResult = {
48
+ lock: "not_acquired" | "released" | "release_failed";
49
+ } & (
50
+ | {
51
+ delivery: "not_attempted";
52
+ cleanup: "not_attempted";
53
+ reason:
54
+ | "invalid_receipt"
55
+ | "invalid_delivery"
56
+ | "receipt_not_found"
57
+ | "inspection_failed"
58
+ | "unsafe_entry"
59
+ | "invalid"
60
+ | "read_limit_exceeded"
61
+ | "changed_during_read"
62
+ | "lock_busy"
63
+ | "lock_repair_required"
64
+ | "lock_failed";
65
+ }
66
+ | {
67
+ delivery: "unacknowledged";
68
+ cleanup: "not_attempted";
69
+ reason: "delivery_failed" | "delivery_rejected" | "invalid_acknowledgement";
70
+ }
71
+ | {
72
+ delivery: "accepted";
73
+ acknowledgement: "queued" | "ingested";
74
+ cleanup: "changed" | "failed" | "removed" | "kept" | "uncertain";
75
+ }
76
+ );
77
+ export function recoverRejectedRawEventSpoolEntry(options: {
78
+ receipt: string;
79
+ homeDir?: string;
80
+ keepReceipt?: boolean;
81
+ /** Runs under the directory serializer. Must not await another mutation in the same spool. */
82
+ deliver: (entry: {
83
+ serialized: string;
84
+ }) => RejectedRawEventDeliveryResult | Promise<RejectedRawEventDeliveryResult>;
85
+ }): Promise<RejectedRawEventRecoveryResult>;
86
+ export function writeRawEventSpoolEntry(options: {
87
+ envelope: Record<string, unknown>;
88
+ serialized?: string;
89
+ homeDir?: string;
90
+ maxEntries?: number;
91
+ }): Promise<{ eventId: string; serialized: string }>;
92
+ export function retainRejectedRawEventSpoolEntry(options: {
93
+ eventId: string;
94
+ status: 400 | 413;
95
+ reason: "invalid_payload" | "payload_too_large";
96
+ homeDir?: string;
97
+ }): Promise<RejectedRawEventMetadata & { lock?: "release_failed" }>;
98
+ export function removeRawEventSpoolEntry(options: {
99
+ eventId: string;
100
+ homeDir?: string;
101
+ }): Promise<void>;
102
+ export function loadRawEventSpoolEntries(options?: { homeDir?: string; limit?: number }): Promise<{
103
+ entries: { eventId: string; envelope: Record<string, unknown>; serialized: string }[];
104
+ corruptCount: number;
105
+ }>;
@@ -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,80 @@ const requireEventId = (envelope) => {
38
112
  return eventId;
39
113
  };
40
114
 
41
- /** Delivery timestamps can change when the same host event is captured again. */
42
- const sameEventApartFromDeliveryTime = (existingBytes, incomingBytes) => {
43
- if (existingBytes === incomingBytes) return true;
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
+
158
+ const RUNTIME_CONTEXT_FIELDS = ["cwd", "project", "started_at"];
159
+ const hasRuntimeContext = (event) => RUNTIME_CONTEXT_FIELDS.every((key) =>
160
+ Object.hasOwn(event, key) && (event[key] === null || typeof event[key] === "string"));
161
+ const withoutRuntimeContext = ({ cwd: _cwd, project: _project, started_at: _started, ...event }) => event;
162
+ const differsOnlyInRuntimeContext = (left, right) =>
163
+ hasRuntimeContext(left) && hasRuntimeContext(right)
164
+ && isDeepStrictEqual(withoutRuntimeContext(left), withoutRuntimeContext(right));
165
+
166
+ /** Content-derived IDs can be shared by runtimes with different directory context. Keep the first saved context. */
167
+ const compareEventApartFromDeliveryTime = (existingBytes, incomingBytes) => {
168
+ if (existingBytes === incomingBytes) return null;
44
169
  try {
45
170
  const existing = JSON.parse(existingBytes);
46
171
  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;
172
+ if (!isRecord(existing) || !isRecord(incoming)) return { reason: "invalid_shape" };
49
173
  const withoutDeliveryTime = ({ ts_wall_ms: _wall, ts_mono_ms: _mono, ...event }) => event;
50
- return isDeepStrictEqual(withoutDeliveryTime(existing), withoutDeliveryTime(incoming));
174
+ const left = withoutDeliveryTime(existing);
175
+ const right = withoutDeliveryTime(incoming);
176
+ if (isDeepStrictEqual(left, right)) return null;
177
+ if (differsOnlyInRuntimeContext(left, right)) return null;
178
+ return { reason: "field_mismatch", ...changedConflictFields(left, right) };
51
179
  } catch {
52
180
  // Malformed retained data is not proof that the new event is already durable.
53
- return false;
181
+ return { reason: "invalid_json" };
54
182
  }
55
183
  };
56
184
 
57
- const conflictingEntry = () => {
185
+ const conflictingEntry = (diagnostic) => {
58
186
  const error = new Error("raw event spool entry conflicts with existing event_id");
59
187
  error.code = RAW_EVENT_SPOOL_CONFLICT_CODE;
188
+ if (diagnostic) error.spoolConflict = diagnostic;
60
189
  return error;
61
190
  };
62
191
 
@@ -112,7 +241,8 @@ const readExistingEntry = async (directory, destination, bytes, eventId) => {
112
241
  try {
113
242
  return await atSpoolStage("existing_entry", async () => {
114
243
  const existing = await readFile(destination, "utf8");
115
- if (!sameEventApartFromDeliveryTime(existing, bytes)) throw conflictingEntry();
244
+ const mismatch = compareEventApartFromDeliveryTime(existing, bytes);
245
+ if (mismatch) throw conflictingEntry({ branch: "active_comparison", ...mismatch });
116
246
  await chmod(destination, 0o600);
117
247
  await syncDirectory(directory);
118
248
  return { eventId, serialized: existing };
@@ -123,6 +253,30 @@ const readExistingEntry = async (directory, destination, bytes, eventId) => {
123
253
  }
124
254
  };
125
255
 
256
+ const readRejectedEntry = async (directory, name, eventId) => {
257
+ try {
258
+ const entry = await readRegularSpoolFile(join(directory, name), { makePrivate: true });
259
+ requireMatchingIdentity(entry.serialized, spoolFilename(eventId));
260
+ return entry;
261
+ } catch (error) {
262
+ if (error?.code === "ENOENT") return null;
263
+ throw error;
264
+ }
265
+ };
266
+
267
+ const readMatchingRejectedEntry = async (directory, eventId, bytes) => {
268
+ let existing = null;
269
+ for (const [status, reason] of rejectedReasons) {
270
+ const entry = await readRejectedEntry(directory, rejectedFilename(eventId, status, reason), eventId);
271
+ if (!entry) continue;
272
+ const mismatch = compareEventApartFromDeliveryTime(entry.serialized, bytes);
273
+ if (mismatch) throw conflictingEntry({ branch: "rejected_comparison", ...mismatch });
274
+ existing = { eventId, serialized: entry.serialized };
275
+ }
276
+ if (existing) await syncDirectory(directory);
277
+ return existing;
278
+ };
279
+
126
280
  const requireSpoolCapacity = async (directory, maxEntries) =>
127
281
  atSpoolStage("capacity", async () => {
128
282
  const directoryEntries = await readdir(directory, { withFileTypes: true });
@@ -136,6 +290,7 @@ const requireSpoolCapacity = async (directory, maxEntries) =>
136
290
  });
137
291
 
138
292
  const publishSpoolEntry = async (temporary, destination, bytes) => {
293
+ let published = bytes;
139
294
  try {
140
295
  await atSpoolStage("temporary_write", () => writeDurableFile(temporary, bytes));
141
296
  await atSpoolStage("publish", async () => {
@@ -144,7 +299,9 @@ const publishSpoolEntry = async (temporary, destination, bytes) => {
144
299
  } catch (error) {
145
300
  if (error?.code !== "EEXIST") throw error;
146
301
  const existing = await readFile(destination, "utf8");
147
- if (!sameEventApartFromDeliveryTime(existing, bytes)) throw conflictingEntry();
302
+ const mismatch = compareEventApartFromDeliveryTime(existing, bytes);
303
+ if (mismatch) throw conflictingEntry({ branch: "publish_comparison", ...mismatch });
304
+ published = existing;
148
305
  await chmod(destination, 0o600);
149
306
  }
150
307
  await chmod(destination, 0o600);
@@ -152,6 +309,7 @@ const publishSpoolEntry = async (temporary, destination, bytes) => {
152
309
  } finally {
153
310
  await rm(temporary, { force: true }).catch(() => {});
154
311
  }
312
+ return published;
155
313
  };
156
314
 
157
315
  const writeRawEventSpoolEntryUnlocked = async ({
@@ -174,19 +332,20 @@ const writeRawEventSpoolEntryUnlocked = async ({
174
332
 
175
333
  await atSpoolStage("directory", () => ensurePrivateDirectory(directory));
176
334
  const existing = await readExistingEntry(directory, destination, bytes, eventId);
177
- if (existing) return existing;
335
+ const rejected = await atSpoolStage("existing_entry", () =>
336
+ readMatchingRejectedEntry(directory, eventId, bytes));
337
+ if (rejected || existing) return rejected || existing;
178
338
  await requireSpoolCapacity(directory, normalizedMaxEntries);
179
- await publishSpoolEntry(temporary, destination, bytes);
339
+ const published = await publishSpoolEntry(temporary, destination, bytes);
180
340
  await atSpoolStage("directory_sync", () => syncDirectory(directory));
181
341
 
182
- return { eventId, serialized: bytes };
342
+ return { eventId, serialized: published };
183
343
  };
184
344
 
185
- const writeRawEventSpoolEntry = async (options) => {
186
- const directory = resolveSpoolDirectory(options?.homeDir);
345
+ const serializeSpoolMutation = (directory, action) => {
187
346
  const previousWrite = spoolWritesInFlight.get(directory);
188
347
  const writePromise = (previousWrite ? previousWrite.catch(() => {}) : Promise.resolve())
189
- .then(() => writeRawEventSpoolEntryUnlocked(options));
348
+ .then(action);
190
349
  const trackedWrite = writePromise.finally(() => {
191
350
  if (spoolWritesInFlight.get(directory) === trackedWrite) {
192
351
  spoolWritesInFlight.delete(directory);
@@ -196,31 +355,467 @@ const writeRawEventSpoolEntry = async (options) => {
196
355
  return trackedWrite;
197
356
  };
198
357
 
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
- );
358
+ const writeRawEventSpoolEntry = async (options) =>
359
+ serializeSpoolMutation(resolveSpoolDirectory(options?.homeDir), () =>
360
+ writeRawEventSpoolEntryUnlocked(options));
361
+
362
+ const requireSameInode = async (path, expected) => {
363
+ const actual = await lstat(path);
364
+ if (!actual.isFile() || actual.dev !== expected.dev || actual.ino !== expected.ino) {
365
+ throw conflictingEntry();
366
+ }
205
367
  };
206
368
 
207
- const loadRawEventSpoolEntries = async ({
208
- homeDir = homedir(),
209
- limit = DEFAULT_DRAIN_LIMIT,
210
- } = {}) => {
369
+ const publishRejectedEntry = async (directory, source, destination, active) => {
370
+ await requireSameInode(source, active.details);
371
+ try {
372
+ await link(source, destination);
373
+ } catch (error) {
374
+ if (error?.code !== "EEXIST") throw error;
375
+ }
376
+ const retained = await readRegularSpoolFile(destination, { makePrivate: true });
377
+ if (retained.serialized !== active.serialized) {
378
+ throw conflictingEntry();
379
+ }
380
+ // Both names must survive a crash before removing the active name.
381
+ await atSpoolStage("rejected_directory_sync", () => syncDirectory(directory));
382
+ await requireSameInode(destination, retained.details);
383
+ await requireSameInode(source, active.details);
384
+ await atSpoolStage("rejected_unlink", () => rm(source));
385
+ await atSpoolStage("rejected_final_sync", () => syncDirectory(directory));
386
+ return retained;
387
+ };
388
+
389
+ const retainRejectedRawEventSpoolEntryUnlocked = async ({ eventId, status, reason, homeDir }) => {
390
+ const normalizedEventId = requireEventId({ event_id: eventId });
391
+ if (!rejectedReasons.has(status) || rejectedReasons.get(status) !== reason) {
392
+ throw new Error("unsupported raw event rejection");
393
+ }
211
394
  const directory = resolveSpoolDirectory(homeDir);
212
- let directoryEntries;
395
+ await requirePrivateSpoolDirectory(directory);
396
+ await chmod(directory, 0o700);
397
+ const name = rejectedFilename(normalizedEventId, status, reason);
398
+ const source = join(directory, spoolFilename(normalizedEventId));
399
+ let active;
213
400
  try {
214
- directoryEntries = await readdir(directory, { withFileTypes: true });
401
+ active = await readRegularSpoolFile(source, { makePrivate: true });
215
402
  } catch (error) {
403
+ if (error?.code !== "ENOENT") throw error;
404
+ const retained = await readRejectedEntry(directory, name, normalizedEventId);
405
+ if (!retained) throw error;
406
+ await syncDirectory(directory);
407
+ return rejectedMetadata(name, { status, reason }, retained.details.size);
408
+ }
409
+ requireMatchingIdentity(active.serialized, spoolFilename(normalizedEventId));
410
+ for (const [otherStatus, otherReason] of rejectedReasons) {
411
+ if (otherStatus === status) continue;
412
+ const other = await readRejectedEntry(directory,
413
+ rejectedFilename(normalizedEventId, otherStatus, otherReason), normalizedEventId);
414
+ if (other) throw conflictingEntry();
415
+ }
416
+ const retained = await publishRejectedEntry(directory, source, join(directory, name), active);
417
+ return rejectedMetadata(name, { status, reason }, retained.details.size);
418
+ };
419
+
420
+ const retainRejectedRawEventSpoolEntry = async (options) =>
421
+ serializeSpoolMutation(resolveSpoolDirectory(options?.homeDir), async () => {
422
+ const digest = spoolFilename(requireEventId({ event_id: options.eventId })).slice(0, -5);
423
+ const lock = await acquireRejectedSpoolLock(resolveSpoolDirectory(options.homeDir), digest);
424
+ let outcome;
425
+ try {
426
+ outcome = { retained: await retainRejectedRawEventSpoolEntryUnlocked(options) };
427
+ } catch (error) {
428
+ outcome = { error };
429
+ }
430
+ try {
431
+ await releaseRejectedSpoolLock(lock);
432
+ } catch {
433
+ if ("retained" in outcome) return { ...outcome.retained, lock: "release_failed" };
434
+ try {
435
+ Object.defineProperty(outcome.error, "lock", {
436
+ value: "release_failed", enumerable: true, configurable: true, writable: true,
437
+ });
438
+ } catch {
439
+ // Preserve the primary failure even when it is frozen or is a thrown primitive.
440
+ }
441
+ }
442
+ if ("error" in outcome) throw outcome.error;
443
+ return outcome.retained;
444
+ });
445
+
446
+ class RawEventSpoolInspectionError extends Error {
447
+ constructor(code, message) {
448
+ super(message);
449
+ this.name = "RawEventSpoolInspectionError";
450
+ this.code = code;
451
+ }
452
+ }
453
+
454
+ const inspectionFailure = () => new RawEventSpoolInspectionError(
455
+ "inspection_failed", "Could not inspect retained events. Files were left untouched.",
456
+ );
457
+
458
+ const requireInspectionRegularFile = (details) => {
459
+ if (!details.isFile() || details.isSymbolicLink()) {
460
+ throw new RawEventSpoolInspectionError("unsafe_entry", "Receipt must name a regular file.");
461
+ }
462
+ };
463
+
464
+ const openRejectedEntryForInspection = async (path) => {
465
+ const expected = await lstat(path);
466
+ requireInspectionRegularFile(expected);
467
+ const flags = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
468
+ const handle = await open(path, flags);
469
+ try {
470
+ // lstat also rejects links where O_NOFOLLOW is unavailable. Check both the
471
+ // opened file and its current name before reading any private bytes.
472
+ for (const actual of [await handle.stat(), await lstat(path)]) {
473
+ requireInspectionRegularFile(actual);
474
+ if (actual.dev !== expected.dev || actual.ino !== expected.ino) {
475
+ throw new RawEventSpoolInspectionError("unsafe_entry", "Receipt changed while opening. Retry inspection.");
476
+ }
477
+ }
478
+ return handle;
479
+ } catch (error) {
480
+ await handle.close().catch(() => {});
481
+ throw error;
482
+ }
483
+ };
484
+
485
+ const readWithinInspectionLimit = async (handle, maxBytes, { position = null } = {}) => {
486
+ const chunks = [];
487
+ let total = 0;
488
+ while (total <= maxBytes) {
489
+ const buffer = Buffer.alloc(Math.min(INSPECTION_READ_CHUNK_BYTES, maxBytes + 1 - total));
490
+ const offset = position === null ? null : position + total;
491
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset);
492
+ if (bytesRead === 0) return Buffer.concat(chunks, total);
493
+ total += bytesRead;
494
+ if (total > maxBytes) return null;
495
+ chunks.push(buffer.subarray(0, bytesRead));
496
+ }
497
+ return null;
498
+ };
499
+
500
+ const inspectOpenedRejectedEntry = async (handle, receipt, entry, maxBytes) => {
501
+ const before = await handle.stat();
502
+ requireInspectionRegularFile(before);
503
+ const metadata = rejectedMetadata(receipt, entry, before.size);
504
+ if (before.size > maxBytes) return { ...metadata, validation: "read_limit_exceeded" };
505
+ const bytes = await readWithinInspectionLimit(handle, maxBytes);
506
+ const after = await handle.stat();
507
+ if (!bytes || after.size > maxBytes) {
508
+ return { ...metadata, bytes: after.size, validation: "read_limit_exceeded" };
509
+ }
510
+ if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) {
511
+ return { ...metadata, validation: "changed_during_read" };
512
+ }
513
+ try {
514
+ if (!isUtf8(bytes)) return { ...metadata, validation: "invalid" };
515
+ const serialized = bytes.toString("utf8");
516
+ requireMatchingIdentity(serialized, `${entry.digest}.json`);
517
+ return { ...metadata, validation: "valid", serialized };
518
+ } catch {
519
+ return { ...metadata, validation: "invalid" };
520
+ }
521
+ };
522
+
523
+ const inspectRejectedRawEventSpoolEntry = async ({
524
+ receipt, homeDir = homedir(), maxBytes = MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES,
525
+ }) => {
526
+ const entry = typeof receipt === "string" ? parseRejectedFilename(receipt) : null;
527
+ if (!entry) {
528
+ throw new RawEventSpoolInspectionError("invalid_receipt", "Use a receipt from capture list-rejected.");
529
+ }
530
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES) {
531
+ throw new RawEventSpoolInspectionError("invalid_limit", "Inspection limit must be between 1 byte and 16 MiB.");
532
+ }
533
+ let handle;
534
+ try {
535
+ const directory = resolveSpoolDirectory(homeDir);
536
+ await requirePrivateSpoolDirectory(directory);
537
+ handle = await openRejectedEntryForInspection(join(directory, receipt));
538
+ return await inspectOpenedRejectedEntry(handle, receipt, entry, maxBytes);
539
+ } catch (error) {
540
+ if (error instanceof RawEventSpoolInspectionError) throw error;
216
541
  if (error?.code === "ENOENT") {
217
- return { entries: [], corruptCount: 0 };
542
+ throw new RawEventSpoolInspectionError("receipt_not_found", "Retained receipt was not found. Run capture list-rejected again.");
218
543
  }
544
+ throw inspectionFailure();
545
+ } finally {
546
+ await handle?.close().catch(() => {});
547
+ }
548
+ };
549
+
550
+ const sameFileSnapshot = (actual, expected) => actual.isFile()
551
+ && !actual.isSymbolicLink()
552
+ && actual.dev === expected.dev && actual.ino === expected.ino
553
+ && actual.size === expected.size
554
+ && actual.mtimeMs === expected.mtimeMs && actual.ctimeMs === expected.ctimeMs;
555
+
556
+ const rejectedLockError = (code) => new RawEventSpoolInspectionError(
557
+ code, "Retained event lock is unavailable. Stop capture before repairing its lock.",
558
+ );
559
+
560
+ const classifyExistingRejectedLock = async (path, digest) => {
561
+ let handle;
562
+ try {
563
+ handle = await openRejectedEntryForInspection(path);
564
+ const before = await handle.stat();
565
+ if (before.size > REJECTED_LOCK_RECORD_MAX_BYTES) throw rejectedLockError("lock_repair_required");
566
+ const bytes = await readWithinInspectionLimit(handle, REJECTED_LOCK_RECORD_MAX_BYTES);
567
+ if (!bytes || !isUtf8(bytes) || !sameFileSnapshot(await handle.stat(), before)
568
+ || !sameFileSnapshot(await lstat(path), before)) throw rejectedLockError("lock_repair_required");
569
+ const record = JSON.parse(bytes.toString("utf8"));
570
+ if (!record || Object.keys(record).sort().join() !== "digest,pid,purpose,token,version"
571
+ || record.purpose !== REJECTED_LOCK_PURPOSE || record.version !== 1 || record.digest !== digest
572
+ || !Number.isSafeInteger(record.pid) || record.pid <= 0
573
+ || typeof record.token !== "string"
574
+ || !/^[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)) {
575
+ throw rejectedLockError("lock_repair_required");
576
+ }
577
+ try {
578
+ process.kill(record.pid, 0);
579
+ } catch (error) {
580
+ if (error?.code === "ESRCH") return "lock_repair_required";
581
+ }
582
+ return "lock_busy";
583
+ } catch {
584
+ return "lock_repair_required";
585
+ } finally {
586
+ await handle?.close().catch(() => {});
587
+ }
588
+ };
589
+
590
+ const acquireRejectedSpoolLock = async (directory, digest) => {
591
+ await requirePrivateSpoolDirectory(directory);
592
+ const path = join(directory, `.rejected-${digest}.lock`);
593
+ let handle;
594
+ try {
595
+ handle = await open(path, "wx+", 0o600);
596
+ } catch (error) {
597
+ if (error?.code === "EEXIST") throw rejectedLockError(await classifyExistingRejectedLock(path, digest));
598
+ throw rejectedLockError("lock_failed");
599
+ }
600
+ try {
601
+ const serialized = JSON.stringify({
602
+ purpose: REJECTED_LOCK_PURPOSE, version: 1, digest, pid: process.pid, token: randomUUID(),
603
+ });
604
+ await handle.writeFile(serialized, { encoding: "utf8" });
605
+ await handle.sync();
606
+ const details = await handle.stat();
607
+ requireInspectionRegularFile(details);
608
+ await requirePrivateSpoolDirectory(directory);
609
+ if (!sameFileSnapshot(await lstat(path), details)) throw rejectedLockError("lock_repair_required");
610
+ return { directory, path, handle, serialized, details };
611
+ } catch {
612
+ // An incomplete or unverifiable named lock needs manual repair, never age-based removal.
613
+ await handle.close().catch(() => {});
614
+ throw rejectedLockError("lock_repair_required");
615
+ }
616
+ };
617
+
618
+ const assertRejectedSpoolLock = async (lock) => {
619
+ await requirePrivateSpoolDirectory(lock.directory);
620
+ const bytes = await readWithinInspectionLimit(lock.handle, REJECTED_LOCK_RECORD_MAX_BYTES, { position: 0 });
621
+ if (!bytes || bytes.toString("utf8") !== lock.serialized
622
+ || !sameFileSnapshot(await lock.handle.stat(), lock.details)
623
+ || !sameFileSnapshot(await lstat(lock.path), lock.details)) {
624
+ throw rejectedLockError("lock_release_failed");
625
+ }
626
+ };
627
+
628
+ const releaseRejectedSpoolLock = async (lock) => {
629
+ try {
630
+ await assertRejectedSpoolLock(lock);
631
+ await rm(lock.path);
632
+ await syncDirectory(lock.directory);
633
+ } catch {
634
+ throw rejectedLockError("lock_release_failed");
635
+ } finally {
636
+ await lock.handle.close().catch(() => {});
637
+ }
638
+ };
639
+
640
+ const deliveryAcknowledgement = async (deliver, serialized) => {
641
+ let result;
642
+ try {
643
+ result = await deliver({ serialized });
644
+ } catch {
645
+ return { delivery: "unacknowledged", cleanup: "not_attempted", reason: "delivery_failed" };
646
+ }
647
+ try {
648
+ const isRecord = result && typeof result === "object" && !Array.isArray(result);
649
+ const keys = isRecord ? Reflect.ownKeys(result).sort().join() : "";
650
+ const acknowledged = isRecord ? Object.getOwnPropertyDescriptor(result, "acknowledged")?.value : undefined;
651
+ const acknowledgement = isRecord ? Object.getOwnPropertyDescriptor(result, "acknowledgement")?.value : undefined;
652
+ if (result === false || (keys === "acknowledged" && acknowledged === false)) {
653
+ return { delivery: "unacknowledged", cleanup: "not_attempted", reason: "delivery_rejected" };
654
+ }
655
+ if (keys === "acknowledged,acknowledgement" && acknowledged === true
656
+ && ["queued", "ingested"].includes(acknowledgement)) {
657
+ return { delivery: "accepted", acknowledgement };
658
+ }
659
+ } catch {
660
+ // An exception while inspecting the result does not confirm delivery.
661
+ }
662
+ return { delivery: "unacknowledged", cleanup: "not_attempted", reason: "invalid_acknowledgement" };
663
+ };
664
+
665
+ const finishRecoveredSnapshot = async (snapshot, lock, { keepReceipt }) => {
666
+ let current;
667
+ try {
668
+ await requirePrivateSpoolDirectory(snapshot.directory);
669
+ current = await openRejectedEntryForInspection(snapshot.path);
670
+ if (!sameFileSnapshot(await snapshot.handle.stat(), snapshot.details)
671
+ || !sameFileSnapshot(await current.stat(), snapshot.details)) return "changed";
672
+ const bytes = await readWithinInspectionLimit(current, MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES);
673
+ if (!bytes?.equals(Buffer.from(snapshot.serialized, "utf8"))
674
+ || createHash("sha256").update(bytes).digest("hex") !== snapshot.digest
675
+ || !sameFileSnapshot(await current.stat(), snapshot.details)
676
+ || !sameFileSnapshot(await lstat(snapshot.path), snapshot.details)) return "changed";
677
+ } catch (error) {
678
+ if (error instanceof RawEventSpoolInspectionError || ["ENOENT", "ELOOP"].includes(error?.code)) return "changed";
679
+ return "failed";
680
+ } finally {
681
+ await current?.close().catch(() => {});
682
+ }
683
+ try {
684
+ await assertRejectedSpoolLock(lock);
685
+ if (!sameFileSnapshot(await lstat(snapshot.path), snapshot.details)) return "changed";
686
+ if (keepReceipt === true) return "kept";
687
+ await rm(snapshot.path);
688
+ } catch {
689
+ return "failed";
690
+ }
691
+ try {
692
+ await syncDirectory(snapshot.directory);
693
+ return "removed";
694
+ } catch {
695
+ return "uncertain";
696
+ }
697
+ };
698
+
699
+ const deliverRejectedSnapshot = async ({ directory, receipt, entry, deliver, keepReceipt }, lock) => {
700
+ let handle;
701
+ try {
702
+ const path = join(directory, receipt);
703
+ handle = await openRejectedEntryForInspection(path);
704
+ const details = await handle.stat();
705
+ const inspection = await inspectOpenedRejectedEntry(handle, receipt, entry, MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES);
706
+ if (inspection.validation !== "valid") {
707
+ return { delivery: "not_attempted", cleanup: "not_attempted", reason: inspection.validation };
708
+ }
709
+ if (!sameFileSnapshot(await handle.stat(), details) || !sameFileSnapshot(await lstat(path), details)) {
710
+ return { delivery: "not_attempted", cleanup: "not_attempted", reason: "changed_during_read" };
711
+ }
712
+ const snapshot = { directory, path, handle, details, serialized: inspection.serialized,
713
+ digest: createHash("sha256").update(inspection.serialized, "utf8").digest("hex") };
714
+ const delivery = await deliveryAcknowledgement(deliver, snapshot.serialized);
715
+ if (delivery.delivery !== "accepted") return delivery;
716
+ return { ...delivery, cleanup: await finishRecoveredSnapshot(snapshot, lock, { keepReceipt }) };
717
+ } finally {
718
+ await handle?.close().catch(() => {});
719
+ }
720
+ };
721
+
722
+ const recoveryFailure = (error) => {
723
+ const safeCodes = ["lock_busy", "lock_repair_required", "lock_failed", "unsafe_entry"];
724
+ let reason = "inspection_failed";
725
+ if (error instanceof RawEventSpoolInspectionError && safeCodes.includes(error.code)) reason = error.code;
726
+ if (error?.code === "ENOENT") reason = "receipt_not_found";
727
+ return { delivery: "not_attempted", cleanup: "not_attempted", reason };
728
+ };
729
+
730
+ const recoverRejectedEntryUnlocked = async (options) => {
731
+ let lock;
732
+ let result;
733
+ try {
734
+ lock = await acquireRejectedSpoolLock(options.directory, options.entry.digest);
735
+ result = await deliverRejectedSnapshot(options, lock);
736
+ } catch (error) {
737
+ result = recoveryFailure(error);
738
+ }
739
+ if (!lock) return { ...result, lock: "not_acquired" };
740
+ try {
741
+ await releaseRejectedSpoolLock(lock);
742
+ return { ...result, lock: "released" };
743
+ } catch {
744
+ return { ...result, lock: "release_failed" };
745
+ }
746
+ };
747
+
748
+ const recoverRejectedRawEventSpoolEntry = async ({ receipt, homeDir = homedir(), deliver, keepReceipt } = {}) => {
749
+ const entry = typeof receipt === "string" ? parseRejectedFilename(receipt) : null;
750
+ if (!entry || typeof deliver !== "function") {
751
+ return { delivery: "not_attempted", cleanup: "not_attempted", lock: "not_acquired",
752
+ reason: entry ? "invalid_delivery" : "invalid_receipt" };
753
+ }
754
+ try {
755
+ const directory = resolveSpoolDirectory(homeDir);
756
+ return await serializeSpoolMutation(directory, () =>
757
+ recoverRejectedEntryUnlocked({ directory, receipt, entry, deliver, keepReceipt }));
758
+ } catch (error) {
759
+ return { ...recoveryFailure(error), lock: "not_acquired" };
760
+ }
761
+ };
762
+
763
+ const listRejectedEntries = async ({ homeDir, validation }) => {
764
+ const directory = resolveSpoolDirectory(homeDir);
765
+ let names;
766
+ try {
767
+ await requirePrivateSpoolDirectory(directory);
768
+ names = await readdir(directory, { withFileTypes: true });
769
+ } catch (error) {
770
+ if (error?.code === "ENOENT") return [];
219
771
  throw error;
220
772
  }
773
+ const entries = [];
774
+ for (const candidate of names) {
775
+ const entry = parseRejectedFilename(candidate.name);
776
+ if (!candidate.isFile() || !entry) continue;
777
+ try {
778
+ if (validation === "metadata") {
779
+ const details = await lstat(join(directory, candidate.name));
780
+ if (details.isFile()) {
781
+ entries.push({ ...rejectedMetadata(candidate.name, entry, details.size), validation: "not_checked" });
782
+ }
783
+ continue;
784
+ }
785
+ const retained = await readRegularSpoolFile(join(directory, candidate.name));
786
+ requireMatchingIdentity(retained.serialized, `${entry.digest}.json`);
787
+ entries.push(rejectedMetadata(candidate.name, entry, retained.details.size));
788
+ } catch {
789
+ // Invalid or concurrently removed files expose no payload or filesystem details.
790
+ }
791
+ }
792
+ return entries.sort((left, right) => left.receipt.localeCompare(right.receipt));
793
+ };
794
+
795
+ const listRejectedRawEventSpoolEntries = async ({ homeDir = homedir(), validation = "payload" } = {}) => {
796
+ if (!["metadata", "payload"].includes(validation)) {
797
+ throw new RawEventSpoolInspectionError("invalid_validation", "Unsupported inspection mode.");
798
+ }
799
+ try {
800
+ return await listRejectedEntries({ homeDir, validation });
801
+ } catch (error) {
802
+ if (validation === "payload") throw error;
803
+ throw inspectionFailure();
804
+ }
805
+ };
221
806
 
807
+ const removeRawEventSpoolEntry = async ({ eventId, homeDir = homedir() }) => {
808
+ const normalizedEventId = requireEventId({ event_id: eventId });
809
+ await rm(
810
+ join(resolveSpoolDirectory(homeDir), spoolFilename(normalizedEventId)),
811
+ { force: true },
812
+ );
813
+ };
814
+
815
+ const findActiveSpoolCandidates = async (directory, directoryEntries) => {
222
816
  const candidates = [];
223
817
  for (const directoryEntry of directoryEntries) {
818
+ if (parseRejectedFilename(directoryEntry.name)) continue;
224
819
  if (!directoryEntry.isFile() || !directoryEntry.name.endsWith(".json")) {
225
820
  continue;
226
821
  }
@@ -235,6 +830,25 @@ const loadRawEventSpoolEntries = async ({
235
830
  candidates.sort(
236
831
  (left, right) => left.mtimeMs - right.mtimeMs || left.name.localeCompare(right.name),
237
832
  );
833
+ return candidates;
834
+ };
835
+
836
+ const loadRawEventSpoolEntries = async ({
837
+ homeDir = homedir(),
838
+ limit = DEFAULT_DRAIN_LIMIT,
839
+ } = {}) => {
840
+ const directory = resolveSpoolDirectory(homeDir);
841
+ let directoryEntries;
842
+ try {
843
+ directoryEntries = await readdir(directory, { withFileTypes: true });
844
+ } catch (error) {
845
+ if (error?.code === "ENOENT") {
846
+ return { entries: [], corruptCount: 0 };
847
+ }
848
+ throw error;
849
+ }
850
+
851
+ const candidates = await findActiveSpoolCandidates(directory, directoryEntries);
238
852
 
239
853
  const entries = [];
240
854
  let corruptCount = 0;
@@ -265,10 +879,16 @@ const loadRawEventSpoolEntries = async ({
265
879
  export {
266
880
  DEFAULT_DRAIN_LIMIT,
267
881
  DEFAULT_MAX_ENTRIES,
882
+ inspectRejectedRawEventSpoolEntry,
883
+ listRejectedRawEventSpoolEntries,
268
884
  loadRawEventSpoolEntries,
885
+ MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES,
269
886
  RAW_EVENT_SPOOL_CONFLICT_CODE,
270
887
  RAW_EVENT_SPOOL_FULL_CODE,
888
+ RawEventSpoolInspectionError,
889
+ recoverRejectedRawEventSpoolEntry,
271
890
  removeRawEventSpoolEntry,
272
891
  resolveSpoolDirectory,
892
+ retainRejectedRawEventSpoolEntry,
273
893
  writeRawEventSpoolEntry,
274
894
  };
@@ -38,7 +38,7 @@ import {
38
38
 
39
39
  const TRUTHY_VALUES = ["1", "true", "yes"];
40
40
  const DISABLED_VALUES = ["0", "false", "off"];
41
- const PINNED_BACKEND_VERSION = "0.48.0";
41
+ const PINNED_BACKEND_VERSION = "0.49.0-beta.1";
42
42
  const COMPAT_CHECK_DELAY_MS = 1500;
43
43
  const COMPAT_CHECK_CACHE_TTL_MS = 5 * 60 * 1000;
44
44
  const MAX_UPDATE_STATUS_BYTES = 16 * 1024;
@@ -311,8 +311,9 @@ const hashPromptPackQuery = (query) =>
311
311
 
312
312
  const redactPackCommand = (runner, runnerArgs, packArgs) => {
313
313
  const safePackArgs = [...packArgs];
314
- if (safePackArgs[0] === "pack" && safePackArgs.length > 1) {
315
- safePackArgs[1] = "[query-redacted]";
314
+ const queryIndex = safePackArgs[0] === "memory" ? 2 : 1;
315
+ if (safePackArgs[queryIndex - 1] === "pack" && safePackArgs.length > queryIndex) {
316
+ safePackArgs[queryIndex] = "[query-redacted]";
316
317
  }
317
318
  for (let index = 0; index < safePackArgs.length - 1; index += 1) {
318
319
  if (safePackArgs[index] === "--working-set-file") {
@@ -722,7 +723,7 @@ const buildPackArgs = ({ query, filesModified, injectLimit, injectTokenBudget, i
722
723
  .slice(-8)
723
724
  .map((value) => String(value || "").trim())
724
725
  .filter(Boolean);
725
- const args = ["pack", query, "--json"];
726
+ const args = ["memory", "pack", query, "--json"];
726
727
  if (internalLedger) {
727
728
  args.push("--internal-ledger");
728
729
  }
@@ -2303,8 +2304,8 @@ const createCliStatusTools = ({ runCli, viewerUrlHost, viewerPort, logPath }) =>
2303
2304
  description: "Show codemem stats and recent entries",
2304
2305
  args: {},
2305
2306
  async execute() {
2306
- const stats = await runCli(["stats"]);
2307
- const recent = await runCli(["recent", "--limit", "5"]);
2307
+ const stats = await runCli(["memory", "stats"]);
2308
+ const recent = await runCli(["memory", "list", "--limit", "5"]);
2308
2309
  const lines = [
2309
2310
  `viewer: http://${viewerUrlHost}:${viewerPort}`,
2310
2311
  `log: ${logPath || "disabled"}`,
@@ -2328,7 +2329,7 @@ const createCliStatusTools = ({ runCli, viewerUrlHost, viewerPort, logPath }) =>
2328
2329
  // Number.isFinite accepts floats and negatives; coerce to a positive
2329
2330
  // integer (default 5) before forwarding to the CLI.
2330
2331
  const safeLimit = String(parsePositiveInt(limit, 5));
2331
- const recent = await runCli(["recent", "--limit", safeLimit]);
2332
+ const recent = await runCli(["memory", "list", "--limit", safeLimit]);
2332
2333
  if (recent.exitCode === 0) {
2333
2334
  return recent.stdout.trim() || "No recent memories.";
2334
2335
  }
@@ -2340,7 +2341,7 @@ const createCliStatusTools = ({ runCli, viewerUrlHost, viewerPort, logPath }) =>
2340
2341
  description: "Show codemem stats",
2341
2342
  args: {},
2342
2343
  async execute() {
2343
- const stats = await runCli(["stats"]);
2344
+ const stats = await runCli(["memory", "stats"]);
2344
2345
  if (stats.exitCode === 0) {
2345
2346
  return stats.stdout.trim() || "No stats yet.";
2346
2347
  }
@@ -3191,7 +3192,7 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
3191
3192
  return;
3192
3193
  }
3193
3194
 
3194
- const versionResult = await runCli(["version"]);
3195
+ const versionResult = await runCli(["--version"]);
3195
3196
  if (versionResult?.exitCode !== 0) {
3196
3197
  await logLine(
3197
3198
  `compat.version_check_failed exit=${versionResult?.exitCode ?? "unknown"} stderr=${
@@ -3280,7 +3281,7 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
3280
3281
  )}`
3281
3282
  );
3282
3283
 
3283
- const refreshedResult = await runCli(["version"]);
3284
+ const refreshedResult = await runCli(["--version"]);
3284
3285
  const refreshedVersion = (refreshedResult?.stdout || "").trim();
3285
3286
  if (
3286
3287
  refreshedResult?.exitCode === 0
@@ -3353,7 +3354,7 @@ export const createCodememRuntime = async ({ location, host, hostGeneration = nu
3353
3354
  await logLine(`release.auto_update_start cmd=${autoPlan.commandText}`);
3354
3355
  const installation = await installCliUpdate(autoPlan.command);
3355
3356
  if (installation?.exitCode === 0) {
3356
- const verification = await runCli(["version"]);
3357
+ const verification = await runCli(["--version"]);
3357
3358
  const installedVersion = (verification?.stdout || "").trim();
3358
3359
  if (verification?.exitCode !== 0 || installedVersion !== notification.latestVersion) {
3359
3360
  await logLine(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codemem/opencode-plugin",
3
- "version": "0.48.0",
3
+ "version": "0.49.0-beta.1",
4
4
  "description": "CodeMem plugin for OpenCode",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -39,9 +39,10 @@
39
39
  "@opencode/plugin": "2.0.24"
40
40
  },
41
41
  "devDependencies": {
42
- "codemem": "^0.48.0",
42
+ "@babel/parser": "8.1.0",
43
43
  "@opencode/cli": "2.0.24",
44
44
  "@types/node": "^24.12.4",
45
+ "codemem": "^0.49.0-beta.1",
45
46
  "vitest": "^4.1.11"
46
47
  },
47
48
  "repository": {