@clagentic/console 1.0.4 → 1.1.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.
package/lib/sessions.js CHANGED
@@ -13,6 +13,11 @@ function createSessionManager(opts) {
13
13
  var sendAndRecord = null; // set after init via setSendAndRecord
14
14
  var onSessionDone = opts.onSessionDone || function () {};
15
15
 
16
+ // --- LRU eviction limit: max sessions with in-memory history ---
17
+ var LRU_HISTORY_LIMIT = 50;
18
+ // Access order for loaded sessions: most-recently-accessed localId is last.
19
+ var lruOrder = [];
20
+
16
21
  // --- Multi-session state ---
17
22
  var nextLocalId = 1;
18
23
  var sessions = new Map(); // localId -> session object
@@ -67,26 +72,163 @@ function createSessionManager(opts) {
67
72
  var tmpPath = sfPath + ".tmp." + process.pid;
68
73
  fs.writeFileSync(tmpPath, lines.join("\n") + "\n");
69
74
  if (process.platform !== "win32") {
75
+ // chmod 0o600 once at file creation; appendToSessionFile skips it
76
+ // after _fileModeSet is true.
70
77
  try { fs.chmodSync(tmpPath, 0o600); } catch (chmodErr) {}
71
78
  }
72
79
  fs.renameSync(tmpPath, sfPath);
80
+ // Mark that the file mode has been set so appendToSessionFile skips chmod.
81
+ session._fileModeSet = true;
73
82
  } catch(e) {
74
83
  console.error("[session] Failed to save session file:", e.message);
75
84
  }
76
85
  }
77
86
 
87
+ // --- Write buffer state for async append (Finding 1) ---
88
+ // Per-session write buffer: localId -> { lines: string[], timer: Timeout|null }
89
+ var _writeBuffers = {};
90
+
91
+ // Flush all pending lines for a session synchronously. Called on session
92
+ // end and process exit — must be synchronous so no lines are lost.
93
+ function flushSessionBuffer(session) {
94
+ var buf = _writeBuffers[session.localId];
95
+ if (!buf || buf.lines.length === 0) return;
96
+ if (buf.timer) {
97
+ clearTimeout(buf.timer);
98
+ buf.timer = null;
99
+ }
100
+ if (!session.cliSessionId) {
101
+ buf.lines = [];
102
+ return;
103
+ }
104
+ try {
105
+ var afPath = sessionFilePath(session.cliSessionId);
106
+ fs.appendFileSync(afPath, buf.lines.join(""));
107
+ } catch(e) {
108
+ console.error("[session] Failed to flush session buffer:", e.message);
109
+ }
110
+ buf.lines = [];
111
+ }
112
+
113
+ // Flush asynchronously (non-blocking hot path).
114
+ function _flushBufferAsync(session) {
115
+ var buf = _writeBuffers[session.localId];
116
+ if (!buf || buf.lines.length === 0) return;
117
+ if (buf.timer) {
118
+ clearTimeout(buf.timer);
119
+ buf.timer = null;
120
+ }
121
+ if (!session.cliSessionId) {
122
+ buf.lines = [];
123
+ return;
124
+ }
125
+ var toWrite = buf.lines.join("");
126
+ buf.lines = [];
127
+ var afPath = sessionFilePath(session.cliSessionId);
128
+ fs.promises.appendFile(afPath, toWrite).catch(function(e) {
129
+ console.error("[session] Failed to async-flush session buffer:", e.message);
130
+ });
131
+ }
132
+
78
133
  function appendToSessionFile(session, obj) {
79
134
  if (!session.cliSessionId) return;
80
135
  session.lastActivity = Date.now();
81
- try {
82
- var afPath = sessionFilePath(session.cliSessionId);
83
- fs.appendFileSync(afPath, JSON.stringify(obj) + "\n");
84
- if (process.platform !== "win32") {
85
- try { fs.chmodSync(afPath, 0o600); } catch (chmodErr) {}
136
+
137
+ // Ensure a buffer entry exists for this session.
138
+ if (!_writeBuffers[session.localId]) {
139
+ _writeBuffers[session.localId] = { lines: [], timer: null };
140
+ }
141
+ var buf = _writeBuffers[session.localId];
142
+ buf.lines.push(JSON.stringify(obj) + "\n");
143
+
144
+ // Set file mode exactly once at first append if saveSessionFile hasn't
145
+ // done it yet (e.g. for sessions that receive appends before their first
146
+ // full save).
147
+ if (!session._fileModeSet && process.platform !== "win32") {
148
+ try { fs.chmodSync(sessionFilePath(session.cliSessionId), 0o600); } catch (chmodErr) {}
149
+ session._fileModeSet = true;
150
+ }
151
+
152
+ // Flush immediately if threshold reached; otherwise arm the 50ms timer.
153
+ if (buf.lines.length >= 20) {
154
+ _flushBufferAsync(session);
155
+ } else if (!buf.timer) {
156
+ buf.timer = setTimeout(function() {
157
+ buf.timer = null;
158
+ _flushBufferAsync(session);
159
+ }, 50);
160
+ }
161
+ }
162
+
163
+ // --- Lazy history load and LRU eviction (Findings 2 & 3) ---
164
+
165
+ // Remove a localId from lruOrder (helper used by eviction and delete).
166
+ function _lruRemove(localId) {
167
+ var idx = lruOrder.indexOf(localId);
168
+ if (idx !== -1) lruOrder.splice(idx, 1);
169
+ }
170
+
171
+ // Touch a session in the LRU order: move it to the most-recently-used end.
172
+ function _lruTouch(localId) {
173
+ _lruRemove(localId);
174
+ lruOrder.push(localId);
175
+ }
176
+
177
+ // Evict the least-recently-used loaded session if we are over the limit.
178
+ // Never evicts the active session or one that is currently processing.
179
+ function _lruEvictIfNeeded() {
180
+ if (lruOrder.length <= LRU_HISTORY_LIMIT) return;
181
+ for (var ei = 0; ei < lruOrder.length; ei++) {
182
+ var candidateId = lruOrder[ei];
183
+ if (candidateId === activeSessionId) continue;
184
+ var candidate = sessions.get(candidateId);
185
+ if (!candidate || candidate.isProcessing) continue;
186
+ // Unload history from memory; disk file is the source of truth.
187
+ candidate.history = [];
188
+ candidate._historyLoaded = false;
189
+ _lruRemove(candidateId);
190
+ return;
191
+ }
192
+ }
193
+
194
+ // Synchronously load a session's history from disk if it has not been loaded.
195
+ // Reconstructs messageUUIDs from the history lines.
196
+ function loadSessionHistory(session) {
197
+ if (session._historyLoaded) {
198
+ _lruTouch(session.localId);
199
+ return;
200
+ }
201
+ if (!session.cliSessionId) {
202
+ // Brand-new session with no file yet — history is already [] and that is correct.
203
+ session._historyLoaded = true;
204
+ return;
205
+ }
206
+
207
+ // Flush any buffered appends first so we read the full on-disk state.
208
+ flushSessionBuffer(session);
209
+
210
+ var filePath = sessionFilePath(session.cliSessionId);
211
+ var content;
212
+ try { content = fs.readFileSync(filePath, "utf8"); } catch { content = ""; }
213
+ var lines = content.trim().split("\n");
214
+ var history = [];
215
+ var messageUUIDs = [];
216
+ // Skip line 0 — it's the meta record, already loaded at startup.
217
+ for (var j = 1; j < lines.length; j++) {
218
+ if (!lines[j]) continue;
219
+ var entry;
220
+ try { entry = JSON.parse(lines[j]); } catch { continue; }
221
+ if (entry.type === "message_uuid") {
222
+ messageUUIDs.push({ uuid: entry.uuid, type: entry.messageType, historyIndex: history.length });
86
223
  }
87
- } catch(e) {
88
- console.error("[session] Failed to append to session file:", e.message);
224
+ history.push(entry);
89
225
  }
226
+ session.history = history;
227
+ session.messageUUIDs = messageUUIDs;
228
+ session._historyLoaded = true;
229
+
230
+ _lruTouch(session.localId);
231
+ _lruEvictIfNeeded();
90
232
  }
91
233
 
92
234
  function loadSessions() {
@@ -103,23 +245,27 @@ function createSessionManager(opts) {
103
245
  var loaded = [];
104
246
  for (var i = 0; i < files.length; i++) {
105
247
  if (!files[i].endsWith(".jsonl")) continue;
106
- var content;
107
- try { content = fs.readFileSync(path.join(sessionsDir, files[i]), "utf8"); } catch { continue; }
108
- var lines = content.trim().split("\n");
109
- if (lines.length === 0) continue;
248
+ // Read only the first line (meta record) — history is lazy-loaded on demand.
249
+ var fd;
250
+ var firstLine = "";
251
+ try {
252
+ fd = fs.openSync(path.join(sessionsDir, files[i]), "r");
253
+ var buf = Buffer.alloc(4096);
254
+ var bytesRead = fs.readSync(fd, buf, 0, 4096, 0);
255
+ var chunk = buf.toString("utf8", 0, bytesRead);
256
+ var nl = chunk.indexOf("\n");
257
+ firstLine = nl !== -1 ? chunk.substring(0, nl) : chunk;
258
+ } catch { continue; } finally {
259
+ if (fd !== undefined) try { fs.closeSync(fd); } catch (e) {}
260
+ }
110
261
 
111
262
  var meta;
112
- try { meta = JSON.parse(lines[0]); } catch { continue; }
263
+ try { meta = JSON.parse(firstLine); } catch { continue; }
113
264
  if (meta.type !== "meta" || !meta.cliSessionId) continue;
114
265
 
115
- var history = [];
116
- for (var j = 1; j < lines.length; j++) {
117
- try { history.push(JSON.parse(lines[j])); } catch {}
118
- }
119
-
120
266
  var fileMtime = 0;
121
267
  try { fileMtime = fs.statSync(path.join(sessionsDir, files[i])).mtimeMs; } catch {}
122
- loaded.push({ meta: meta, history: history, mtime: fileMtime });
268
+ loaded.push({ meta: meta, mtime: fileMtime });
123
269
  }
124
270
 
125
271
  loaded.sort(function(a, b) { return a.meta.createdAt - b.meta.createdAt; });
@@ -127,13 +273,6 @@ function createSessionManager(opts) {
127
273
  for (var i = 0; i < loaded.length; i++) {
128
274
  var m = loaded[i].meta;
129
275
  var localId = nextLocalId++;
130
- // Reconstruct messageUUIDs from history
131
- var messageUUIDs = [];
132
- for (var k = 0; k < loaded[i].history.length; k++) {
133
- if (loaded[i].history[k].type === "message_uuid") {
134
- messageUUIDs.push({ uuid: loaded[i].history[k].uuid, type: loaded[i].history[k].messageType, historyIndex: k });
135
- }
136
- }
137
276
  var session = {
138
277
  localId: localId,
139
278
  queryInstance: null,
@@ -147,9 +286,13 @@ function createSessionManager(opts) {
147
286
  title: m.title || "",
148
287
  createdAt: m.createdAt || Date.now(),
149
288
  lastActivity: loaded[i].mtime || m.createdAt || Date.now(),
150
- history: loaded[i].history,
151
- messageUUIDs: messageUUIDs,
289
+ // History is not loaded yet; populated lazily by loadSessionHistory().
290
+ history: [],
291
+ _historyLoaded: false,
292
+ messageUUIDs: [],
152
293
  lastRewindUuid: m.lastRewindUuid || null,
294
+ // File mode already correct on disk — skip chmod on first append.
295
+ _fileModeSet: true,
153
296
  };
154
297
  if (m.vendor) session.vendor = m.vendor;
155
298
  if (m.agentName) session.agentName = m.agentName;
@@ -165,6 +308,14 @@ function createSessionManager(opts) {
165
308
  // Load persisted sessions from disk
166
309
  loadSessions();
167
310
 
311
+ // Drain all write buffers synchronously on process exit to prevent trailing
312
+ // event loss when the daemon shuts down cleanly.
313
+ process.on("exit", function() {
314
+ sessions.forEach(function(session) {
315
+ flushSessionBuffer(session);
316
+ });
317
+ });
318
+
168
319
  function getActiveSession() {
169
320
  return sessions.get(activeSessionId) || null;
170
321
  }
@@ -257,6 +408,7 @@ function createSessionManager(opts) {
257
408
  createdAt: Date.now(),
258
409
  lastActivity: Date.now(),
259
410
  history: [],
411
+ _historyLoaded: true, // new in-memory session — nothing to load from disk
260
412
  messageUUIDs: [],
261
413
  ownerId: (sessionOpts && sessionOpts.ownerId) || null,
262
414
  sessionVisibility: (sessionOpts && sessionOpts.sessionVisibility) || "shared",
@@ -290,6 +442,7 @@ function createSessionManager(opts) {
290
442
  createdAt: Date.now(),
291
443
  lastActivity: Date.now(),
292
444
  history: [],
445
+ _historyLoaded: true, // new in-memory session — nothing to load from disk
293
446
  messageUUIDs: [],
294
447
  ownerId: (sessionOpts && sessionOpts.ownerId) || null,
295
448
  sessionVisibility: (sessionOpts && sessionOpts.sessionVisibility) || "shared",
@@ -315,6 +468,9 @@ function createSessionManager(opts) {
315
468
  }
316
469
 
317
470
  function replayHistory(session, fromIndex, targetWs, transform) {
471
+ // Ensure history is in memory before replaying.
472
+ loadSessionHistory(session);
473
+
318
474
  var _send = (targetWs && sendTo) ? function (obj) { sendTo(targetWs, obj); } : send;
319
475
  var total = session.history.length;
320
476
  if (typeof fromIndex !== "number") {
@@ -357,8 +513,45 @@ function createSessionManager(opts) {
357
513
  }
358
514
 
359
515
  function switchSession(localId, targetWs, transform) {
516
+ if (!sessions.has(localId)) {
517
+ // Only send structured error when a client ws is the initiator. Internal
518
+ // callers (createSession, deleteSession, resumeSession, project-loop) pass
519
+ // targetWs=null and are always trusted.
520
+ if (targetWs && sendTo) {
521
+ sendTo(targetWs, { type: "error", error: "Session not found" });
522
+ }
523
+ return;
524
+ }
360
525
  var session = sessions.get(localId);
361
- if (!session) return;
526
+
527
+ // Access check for client-initiated switches. In single-user mode, sessions
528
+ // with an ownerId are user-scoped and should not be visible without auth;
529
+ // in multi-user mode defer to users.canAccessSession (same rules as
530
+ // getVisibleSessions / server-palette). Internal callers (targetWs=null)
531
+ // bypass this gate — they operate on already-validated session references.
532
+ if (targetWs) {
533
+ var multiUser = users.isMultiUser();
534
+ if (multiUser) {
535
+ var requestingUser = targetWs._clayUser || null;
536
+ if (!requestingUser) {
537
+ if (sendTo) sendTo(targetWs, { type: "error", error: "Access denied" });
538
+ return;
539
+ }
540
+ // Use { visibility: "public" } so canAccessProject passes and the
541
+ // session-level ownership/visibility rules do the real work.
542
+ if (!users.canAccessSession(requestingUser.id, session, { visibility: "public" })) {
543
+ if (sendTo) sendTo(targetWs, { type: "error", error: "Access denied" });
544
+ return;
545
+ }
546
+ } else {
547
+ // Single-user mode: sessions with an ownerId were created in a multi-user
548
+ // context; block access to prevent cross-context leakage.
549
+ if (session.ownerId) {
550
+ if (sendTo) sendTo(targetWs, { type: "error", error: "Access denied" });
551
+ return;
552
+ }
553
+ }
554
+ }
362
555
 
363
556
  activeSessionId = localId;
364
557
  if (targetWs) {
@@ -374,13 +567,16 @@ function createSessionManager(opts) {
374
567
  // Clear unread for single-user mode
375
568
  singleUserUnread[localId] = 0;
376
569
 
570
+ // Update LRU when a session is switched to (history will be loaded in replayHistory).
571
+ _lruTouch(localId);
572
+
377
573
  // In multi-user mode with a specific client, only send to that client
378
574
  var _send = (targetWs && sendTo) ? function (obj) { sendTo(targetWs, obj); } : send;
379
575
 
380
576
  var _capsByVendor = capabilitiesByVendor || {};
381
577
  var _sessionVendor = session.vendor || defaultVendor || "claude";
382
578
  var _vendorCaps = _capsByVendor[_sessionVendor] || {};
383
- _send({ type: "session_switched", id: localId, cliSessionId: session.cliSessionId || null, loop: session.loop || null, vendor: session.vendor || null, hasHistory: (session.history && session.history.length > 0), capabilities: _vendorCaps, isProcessing: !!session.isProcessing, agentName: session.agentName || null });
579
+ _send({ type: "session_switched", id: localId, cliSessionId: session.cliSessionId || null, loop: session.loop || null, vendor: session.vendor || null, hasHistory: (session._historyLoaded ? session.history.length > 0 : !!session.cliSessionId), capabilities: _vendorCaps, isProcessing: !!session.isProcessing, agentName: session.agentName || null });
384
580
  // Send vendor-specific slash commands
385
581
  var _vendorCmds = slashCommandsByVendor[_sessionVendor] || slashCommands || [];
386
582
  _send({ type: "slash_commands", commands: _vendorCmds, vendor: _sessionVendor });
@@ -425,6 +621,11 @@ function createSessionManager(opts) {
425
621
  var session = sessions.get(localId);
426
622
  if (!session) return;
427
623
 
624
+ // Drain any pending write buffer before removing the session.
625
+ flushSessionBuffer(session);
626
+ delete _writeBuffers[localId];
627
+ _lruRemove(localId);
628
+
428
629
  // Clean up unread tracking
429
630
  delete singleUserUnread[localId];
430
631
 
@@ -467,6 +668,12 @@ function createSessionManager(opts) {
467
668
  function deleteSessionQuiet(localId) {
468
669
  var session = sessions.get(localId);
469
670
  if (!session) return;
671
+
672
+ // Drain any pending write buffer before removing the session.
673
+ flushSessionBuffer(session);
674
+ delete _writeBuffers[localId];
675
+ _lruRemove(localId);
676
+
470
677
  delete singleUserUnread[localId];
471
678
  cleanupMentionSessions(session);
472
679
  if (session.abortController) {
@@ -539,7 +746,12 @@ function createSessionManager(opts) {
539
746
  function doSendAndRecord(session, obj) {
540
747
  // Stamp every recorded message so history replay preserves original times
541
748
  if (!obj._ts) obj._ts = Date.now();
542
- session.history.push(obj);
749
+ // If history has not been loaded from disk yet, do not trigger a load just
750
+ // to append — the append path writes directly to the file buffer. History
751
+ // will be loaded lazily on the next switchSession/replayHistory call.
752
+ if (session._historyLoaded) {
753
+ session.history.push(obj);
754
+ }
543
755
  appendToSessionFile(session, obj);
544
756
  if (sendEach) {
545
757
  // Multi-user: send to clients whose active session matches this one
@@ -617,6 +829,7 @@ function createSessionManager(opts) {
617
829
  createdAt: Date.now(),
618
830
  lastActivity: Date.now(),
619
831
  history: cliHistory,
832
+ _historyLoaded: true, // caller provided history directly
620
833
  messageUUIDs: [],
621
834
  bookmarked: false,
622
835
  favoriteOrder: null,
@@ -651,12 +864,19 @@ function createSessionManager(opts) {
651
864
  sessions.forEach(function (session) {
652
865
  var titleMatch = (session.title || "New Session").toLowerCase().indexOf(q) !== -1;
653
866
  var contentMatch = false;
654
- for (var i = 0; i < session.history.length; i++) {
655
- var entry = session.history[i];
656
- if ((entry.type === "delta" || entry.type === "user_message" || entry.type === "mention_user" || entry.type === "mention_response") && entry.text) {
657
- if (entry.text.toLowerCase().indexOf(q) !== -1) {
658
- contentMatch = true;
659
- break;
867
+ if (titleMatch) {
868
+ // Skip content search when title already matches — avoids loading history
869
+ // for sessions that are guaranteed to appear in results anyway.
870
+ } else {
871
+ // Lazy-load history to enable content search.
872
+ loadSessionHistory(session);
873
+ for (var i = 0; i < session.history.length; i++) {
874
+ var entry = session.history[i];
875
+ if ((entry.type === "delta" || entry.type === "user_message" || entry.type === "mention_user" || entry.type === "mention_response") && entry.text) {
876
+ if (entry.text.toLowerCase().indexOf(q) !== -1) {
877
+ contentMatch = true;
878
+ break;
879
+ }
660
880
  }
661
881
  }
662
882
  }
@@ -679,6 +899,10 @@ function createSessionManager(opts) {
679
899
  if (!query) return { hits: [], total: 0 };
680
900
  var session = sessions.get(localId);
681
901
  if (!session) return { hits: [], total: 0 };
902
+
903
+ // Lazy-load history for the target session before searching.
904
+ loadSessionHistory(session);
905
+
682
906
  var q = query.toLowerCase();
683
907
  var qLen = query.length;
684
908
  var history = session.history;
@@ -703,7 +927,7 @@ function createSessionManager(opts) {
703
927
  if (idx === -1) break;
704
928
  var s = Math.max(0, idx - 15);
705
929
  var e = Math.min(text.length, idx + qLen + 15);
706
- var snippet = (s > 0 ? "\u2026" : "") + text.substring(s, e) + (e < text.length ? "\u2026" : "");
930
+ var snippet = (s > 0 ? "…" : "") + text.substring(s, e) + (e < text.length ? "…" : "");
707
931
  hits.push({ historyIndex: historyIndex, snippet: snippet, role: role, ts: ts });
708
932
  from = idx + qLen;
709
933
  }
@@ -728,7 +952,7 @@ function createSessionManager(opts) {
728
952
  var seg = turnSegments[segCursor];
729
953
  var s = Math.max(0, idx - 15);
730
954
  var e = Math.min(turnBuffer.length, idx + qLen + 15);
731
- var snippet = (s > 0 ? "\u2026" : "") + turnBuffer.substring(s, e) + (e < turnBuffer.length ? "\u2026" : "");
955
+ var snippet = (s > 0 ? "…" : "") + turnBuffer.substring(s, e) + (e < turnBuffer.length ? "…" : "");
732
956
  hits.push({ historyIndex: seg.historyIndex, snippet: snippet, role: "assistant", ts: seg.ts });
733
957
  from = idx + qLen;
734
958
  }
@@ -858,6 +1082,8 @@ function createSessionManager(opts) {
858
1082
  },
859
1083
  saveSessionFile: saveSessionFile,
860
1084
  appendToSessionFile: appendToSessionFile,
1085
+ loadSessionHistory: loadSessionHistory,
1086
+ flushSessionBuffer: flushSessionBuffer,
861
1087
  sendAndRecord: doSendAndRecord,
862
1088
  sendToSession: doSendToSession,
863
1089
  findTurnBoundary: findTurnBoundary,
package/lib/store.js ADDED
@@ -0,0 +1,137 @@
1
+ /**
2
+ * store.js — async JSON persistence with per-file write serialization.
3
+ *
4
+ * Provides two call patterns:
5
+ * readJson(name, defaultValue) — name is bare filename, resolved against CONFIG_DIR
6
+ * writeJson(name, value, opts) — same resolution; writes are queued per name
7
+ *
8
+ * readJsonAt(fullPath, defaultValue) — full path variant for per-project state
9
+ * writeJsonAt(fullPath, value, opts) — same; queued per resolved path
10
+ *
11
+ * Writes are atomic: data goes to {path}.tmp.{pid}, then renamed to {path}.
12
+ * After rename, chmod is applied (default 0o600).
13
+ * Concurrent writes to the same name/path are serialized in call order.
14
+ * Concurrent writes to different names/paths are independent.
15
+ */
16
+
17
+ "use strict";
18
+
19
+ var fs = require("fs");
20
+ var path = require("path");
21
+ var { CONFIG_DIR } = require("./config");
22
+
23
+ // --- Per-path write queues ---
24
+ // Key: resolved absolute path. Value: Promise (tail of the chain).
25
+ var _queues = new Map();
26
+
27
+ function _enqueue(resolvedPath, fn) {
28
+ var tail = _queues.get(resolvedPath) || Promise.resolve();
29
+ var next = tail.then(fn, fn); // always advance the chain even if fn rejects
30
+ _queues.set(resolvedPath, next);
31
+ // Clean up the map entry once the chain reaches this point so the Map
32
+ // doesn't grow unboundedly for one-shot paths.
33
+ next.then(function () {
34
+ if (_queues.get(resolvedPath) === next) _queues.delete(resolvedPath);
35
+ }, function () {
36
+ if (_queues.get(resolvedPath) === next) _queues.delete(resolvedPath);
37
+ });
38
+ return next;
39
+ }
40
+
41
+ // --- Core I/O ---
42
+
43
+ function _read(resolvedPath, defaultValue) {
44
+ return fs.promises.readFile(resolvedPath, "utf8").then(function (raw) {
45
+ try {
46
+ return JSON.parse(raw);
47
+ } catch (e) {
48
+ process.stderr.write("[store] Warning: corrupt JSON at " + resolvedPath + " — returning default\n");
49
+ return defaultValue;
50
+ }
51
+ }, function (err) {
52
+ if (err.code === "ENOENT") return defaultValue;
53
+ throw err;
54
+ });
55
+ }
56
+
57
+ function _write(resolvedPath, value, mode) {
58
+ var tmpPath = resolvedPath + ".tmp." + process.pid;
59
+ var json;
60
+ try {
61
+ json = JSON.stringify(value, null, 2);
62
+ } catch (e) {
63
+ return Promise.reject(new Error("[store] Cannot serialize value for " + resolvedPath + ": " + e.message));
64
+ }
65
+ return fs.promises.mkdir(path.dirname(resolvedPath), { recursive: true })
66
+ .then(function () {
67
+ return fs.promises.writeFile(tmpPath, json, { encoding: "utf8" });
68
+ })
69
+ .then(function () {
70
+ return fs.promises.rename(tmpPath, resolvedPath);
71
+ })
72
+ .then(function () {
73
+ if (process.platform === "win32") return;
74
+ return fs.promises.chmod(resolvedPath, mode).catch(function () {});
75
+ })
76
+ .catch(function (err) {
77
+ // Best-effort cleanup of tmp file on failure
78
+ fs.promises.unlink(tmpPath).catch(function () {});
79
+ throw err;
80
+ });
81
+ }
82
+
83
+ // --- Public API ---
84
+
85
+ /**
86
+ * Read a named JSON store from CONFIG_DIR.
87
+ * @param {string} name - Bare filename, e.g. "users.json"
88
+ * @param {*} defaultValue - Returned when file is missing or contains corrupt JSON
89
+ */
90
+ function readJson(name, defaultValue) {
91
+ if (defaultValue === undefined) defaultValue = {};
92
+ var resolvedPath = path.join(CONFIG_DIR, name);
93
+ return _read(resolvedPath, defaultValue);
94
+ }
95
+
96
+ /**
97
+ * Write a named JSON store to CONFIG_DIR atomically.
98
+ * Serializes concurrent writes to the same name in call order.
99
+ * @param {string} name - Bare filename, e.g. "users.json"
100
+ * @param {*} value - JSON-serializable value
101
+ * @param {object} [opts]
102
+ * @param {number} [opts.mode=0o600] - File permission mode after write
103
+ */
104
+ function writeJson(name, value, opts) {
105
+ var mode = (opts && opts.mode !== undefined) ? opts.mode : 0o600;
106
+ var resolvedPath = path.join(CONFIG_DIR, name);
107
+ return _enqueue(resolvedPath, function () {
108
+ return _write(resolvedPath, value, mode);
109
+ });
110
+ }
111
+
112
+ /**
113
+ * Read JSON from an arbitrary full path (for per-project state files).
114
+ * @param {string} fullPath - Absolute path to the JSON file
115
+ * @param {*} defaultValue - Returned when file is missing or contains corrupt JSON
116
+ */
117
+ function readJsonAt(fullPath, defaultValue) {
118
+ if (defaultValue === undefined) defaultValue = {};
119
+ return _read(fullPath, defaultValue);
120
+ }
121
+
122
+ /**
123
+ * Write JSON to an arbitrary full path atomically.
124
+ * Serializes concurrent writes to the same path in call order.
125
+ * @param {string} fullPath - Absolute path to the JSON file
126
+ * @param {*} value - JSON-serializable value
127
+ * @param {object} [opts]
128
+ * @param {number} [opts.mode=0o600] - File permission mode after write
129
+ */
130
+ function writeJsonAt(fullPath, value, opts) {
131
+ var mode = (opts && opts.mode !== undefined) ? opts.mode : 0o600;
132
+ return _enqueue(fullPath, function () {
133
+ return _write(fullPath, value, mode);
134
+ });
135
+ }
136
+
137
+ module.exports = { readJson: readJson, writeJson: writeJson, readJsonAt: readJsonAt, writeJsonAt: writeJsonAt };