cc-viewer 1.9.21 → 1.9.22

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.
@@ -0,0 +1,249 @@
1
+ // Wire Format v2 — session-dir sharding (prompt-count auto-split).
2
+ //
3
+ // A single long-lived session can grow without bound (issue: a 653MB session
4
+ // dir made startup / cold load replay parse every journal + responses +
5
+ // conversation line into memory, stalling the event loop for seconds-to-
6
+ // minutes). Sharding caps the LIVE dir by PROMPT COUNT: once the session
7
+ // crosses SHARD_PROMPT_THRESHOLD main-conversation user prompts, the writer
8
+ // moves the CURRENT content aside into the session's own `parts/`
9
+ // subdir and continues writing into a fresh skeleton at the same dir.
10
+ //
11
+ // Layout contract: parts/ path helpers live in layout.js (the single owner of
12
+ // every v2 path) and are re-exported here for rotate-side consumers. A session
13
+ // dir keeps ALL of its history under ONE folder — copy/move/download/delete of
14
+ // the session dir carries every shard:
15
+ // <project>/sessions/<dirName>/ — active shard (live files at the root)
16
+ // <project>/sessions/<dirName>/parts/<N>/ — frozen shard N (N = 1,2,… oldest→newest)
17
+ // sessions/ enumerators only ever look ONE level down (listSessionIds yields
18
+ // session dirs; summarizeSession/readSession read the live files at the root),
19
+ // so the nested parts/ subtree is invisible to them. A frozen shard is a
20
+ // SELF-CONTAINED session dir (journal + responses + conversations + blobs as
21
+ // of the cut): the replay engine reconstructs it exactly like a complete
22
+ // session — its incremental snapshot replays to the state at the shard
23
+ // boundary, so no cross-shard baseline is needed. Journal seqs stay continuous
24
+ // across shards (the writer carries _seq over the cut).
25
+
26
+ import { mkdirSync, readdirSync, readFileSync, renameSync } from 'node:fs';
27
+ import { join, basename } from 'node:path';
28
+ import { ensureSessionDirSync, writeFileAtomicSync, shardPartsDir, shardPartDir, listShards } from './layout.js';
29
+ import { readJsonlTolerant } from './replay.js';
30
+ import { BlobStore } from './blob-store.js';
31
+ import { ConversationStore } from './conversation-store.js';
32
+ import { reportSwallowed } from '../../lib/error-report.js';
33
+
34
+ // Path ownership lives in layout.js; re-export so existing rotate-side and
35
+ // route-side consumers keep a single import site.
36
+ export { shardPartsDir, shardPartDir, listShards } from './layout.js';
37
+
38
+ /** Default prompt-count ceiling per shard: after this many main-conversation
39
+ * user-prompt turns, the NEXT new user prompt opens a fresh shard — so every
40
+ * part holds whole user-prompt→loop segments. Tests override via the writer's
41
+ * `shardPrompts` seam, not env. */
42
+ export const SHARD_PROMPT_THRESHOLD = 2000;
43
+
44
+ /**
45
+ * Read every frozen shard's cut seq, oldest first. Each shard's cut is its
46
+ * journal max seq; the persisted `cut.json` marker (written at the cut) is
47
+ * read FIRST, and only shards written before the marker existed fall back to a
48
+ * full journal scan. The journal is the smallest of the four files, but on a
49
+ * many-shard session the marker turns an O(total-history) scan into
50
+ * O(shard count) small reads.
51
+ * @param {string} sessionDir - absolute path of the ACTIVE session dir
52
+ * @returns {Array<{ partIndex: number, dir: string, cutSeq: number }>}
53
+ */
54
+ export function readShardCuts(sessionDir) {
55
+ const cuts = [];
56
+ for (const sh of listShards(sessionDir)) {
57
+ let maxSeq = 0;
58
+ let fromMarker = false;
59
+ try {
60
+ const marker = JSON.parse(readFileSync(join(sh.dir, 'cut.json'), 'utf-8'));
61
+ if (marker && typeof marker.cutSeq === 'number' && marker.cutSeq > 0) { maxSeq = marker.cutSeq; fromMarker = true; }
62
+ } catch { /* no marker (legacy shard) — fall through to the journal scan */ }
63
+ if (!fromMarker) {
64
+ try {
65
+ for (const line of readJsonlTolerant(join(sh.dir, 'journal.jsonl'))) {
66
+ if (typeof line.seq === 'number' && line.seq > maxSeq) maxSeq = line.seq;
67
+ }
68
+ } catch (err) { reportSwallowed('v2-shard.cut-read', err); }
69
+ }
70
+ cuts.push({ partIndex: sh.partIndex, dir: sh.dir, cutSeq: maxSeq });
71
+ }
72
+ return cuts;
73
+ }
74
+
75
+ /**
76
+ * Initial shard cursor for the "load earlier history" button on a cold load:
77
+ * the seq just past the newest frozen shard's cut (i.e. the first seq the
78
+ * ACTIVE dir owns), so the first shardBefore read lands on exactly that shard.
79
+ * Shared by the /events and /api/local-log routes — identical contract.
80
+ * Returns null when the session has no frozen shards (or its cut is unknown).
81
+ */
82
+ export function initialShardCursor(sourceDir) {
83
+ if (!sourceDir) return null;
84
+ const cuts = readShardCuts(sourceDir);
85
+ if (cuts.length === 0) return null;
86
+ const newest = cuts[cuts.length - 1];
87
+ if (!newest.cutSeq || newest.cutSeq <= 0) return null;
88
+ // The session UUID lets the follow-latest view (no ?sid in scope) still
89
+ // address the shardBefore read back to THIS session.
90
+ let sid = null;
91
+ try { sid = JSON.parse(readFileSync(join(sourceDir, 'meta.json'), 'utf-8')).sessionId || null; } catch {}
92
+ return { hasMore: true, oldestSeq: newest.cutSeq + 1, partIndex: newest.partIndex + 1, prepend: false, sid };
93
+ }
94
+
95
+ /** Highest shard index already archived for a session (0 when none). A
96
+ * transient readdir failure must NOT be read as "no shards" — that would pick
97
+ * N=1 and overwrite an existing frozen shard. Non-ENOENT errors throw so the
98
+ * rotation aborts instead of clobbering history. */
99
+ function _maxShardIndex(sessionDir) {
100
+ let max = 0;
101
+ let entries;
102
+ try {
103
+ entries = readdirSync(shardPartsDir(sessionDir), { withFileTypes: true });
104
+ } catch (err) {
105
+ if (err && err.code === 'ENOENT') return 0; // no parts/ yet
106
+ throw err; // EMFILE/EACCES/EIO — abort, never risk overwriting a shard
107
+ }
108
+ for (const e of entries) {
109
+ if (!e.isDirectory()) continue;
110
+ const n = Number(e.name);
111
+ if (Number.isInteger(n) && n > max) max = n;
112
+ }
113
+ return max;
114
+ }
115
+
116
+ /** Live files/dirs moved aside at a cut (everything EXCEPT the parts archive). */
117
+ const _SHARD_LIVE_ENTRIES = ['journal.jsonl', 'responses.jsonl', 'prompts.jsonl', 'conversations', 'blobs'];
118
+
119
+ /**
120
+ * Rotate the live session dir: move its live files into `parts/<N>/` and
121
+ * recreate the live skeleton, then rebind the session object. Callers MUST
122
+ * guarantee a quiescent point (no in-flight request bound to this session and
123
+ * the write queue idle) — see V2Writer._maybeRotate.
124
+ *
125
+ * The JOURNAL object is reused (only its _paths pointer flips) so `_seq`
126
+ * continues monotonically across the cut — the reader folds by seq and must
127
+ * never see a restart at 1. meta identity fields (sessionId/startTs/leader/
128
+ * cwd/userIdRaw/userIdEncoding/instance + writer metaExtra) are carried over
129
+ * from the pre-cut meta so the rebuilt live dir keeps the session's identity.
130
+ *
131
+ * @param {object} writer - V2Writer instance
132
+ * @param {object} s - session object {paths, blobs, journal, convs, resolver, project, _identityId, _instanceKey}
133
+ * @returns {boolean} true when a rotation happened
134
+ */
135
+ export function rotateSessionDir(writer, s) {
136
+ if (!s || !s.paths || !s.paths.dir) return false;
137
+ const sessionDir = s.paths.dir;
138
+ const n = _maxShardIndex(sessionDir) + 1;
139
+ const partDir = shardPartDir(sessionDir, n);
140
+
141
+ // Identity + carry-over fields come from the pre-cut meta (first-write-wins,
142
+ // never changes for the life of the session). Read BEFORE the move.
143
+ const frozenMeta = _readFrozenMeta(sessionDir);
144
+
145
+ try {
146
+ // Archive the live files into parts/<N>/. Each is a same-dir rename (atomic,
147
+ // O(1)); the parts/ tree then holds the frozen shard as a self-contained
148
+ // session dir. meta.json is COPIED (not moved) into the shard so the shard
149
+ // keeps the session's identity (sessionId/project/leader/userIdRaw…) — a
150
+ // shard without meta would replay with a wrong/degraded identity
151
+ // (`_seqEpoch` = the part number, no user_id, teammate tag lost).
152
+ // Claim the shard index EXCLUSIVELY: a non-recursive mkdir fails with EEXIST
153
+ // if parts/<N>/ already exists, so a collision never overwrites a frozen
154
+ // shard (the rename below would otherwise silently replace its journal).
155
+ mkdirSync(shardPartsDir(sessionDir), { recursive: true }); // ensure parts/ parent
156
+ mkdirSync(partDir); // EEXIST = collision → throw, abort the cut
157
+ if (frozenMeta) {
158
+ try { writeFileAtomicSync(join(partDir, 'meta.json'), JSON.stringify({ ...frozenMeta, pid: 0, frozen: true }, null, 2) + '\n'); }
159
+ catch (err) { reportSwallowed('v2-shard.rotate-meta', err); }
160
+ }
161
+ // Persist the cut seq so readers (initial cursor, shard selection, restart
162
+ // re-seeding) never re-parse the whole archived journal — one small file.
163
+ // Written BEFORE the moves so a crash mid-archive leaves a shard that reads
164
+ // as "cut at this seq"; the moves below are the source of truth for content.
165
+ try { writeFileAtomicSync(join(partDir, 'cut.json'), JSON.stringify({ cutSeq: s.journal._seq }) + '\n'); }
166
+ catch (err) { reportSwallowed('v2-shard.rotate-cut', err); }
167
+ for (const name of _SHARD_LIVE_ENTRIES) {
168
+ const src = join(sessionDir, name);
169
+ try { renameSync(src, join(partDir, name)); }
170
+ catch (err) {
171
+ // A file that never existed (e.g. prompts.jsonl before its first write)
172
+ // is fine to skip; anything else is reported and the move continues (the
173
+ // shard is still valid — replay tolerates a missing optional file).
174
+ if (err && err.code !== 'ENOENT') reportSwallowed('v2-shard.rotate-move', err, { name });
175
+ }
176
+ }
177
+ } catch (err) {
178
+ reportSwallowed('v2-shard.rotate-rename', err);
179
+ return false;
180
+ }
181
+
182
+ try {
183
+ const paths = ensureSessionDirSync(
184
+ writer._logDir,
185
+ s.project,
186
+ (frozenMeta && frozenMeta.sessionId) || s._identityId || basename(sessionDir).replace(/^\d{14}_/, ''),
187
+ {
188
+ // Carry every identity/role field the readers key off. pid is the only
189
+ // field that must be re-stamped to the current (live) process.
190
+ ...(frozenMeta || {}),
191
+ pid: process.pid,
192
+ startTs: (frozenMeta && frozenMeta.startTs) || new Date().toISOString(),
193
+ // The fresh shard starts its prompt count over; persist it so a
194
+ // restart re-seeds from meta (not the archived, PROMPTS-capped
195
+ // prompts.jsonl line count).
196
+ shardPromptsActive: 0,
197
+ ...(s._instanceKey && { instance: s._instanceKey }),
198
+ },
199
+ writer._sessionsDirName,
200
+ basename(sessionDir),
201
+ );
202
+ s.paths = paths;
203
+ // Persist the FROZEN shard's final prompt count into the live meta (the
204
+ // frozen copy keeps its own). This is the restart re-seed source: the
205
+ // archived prompts.jsonl is PROMPTS-capped and would under-count.
206
+ try {
207
+ const liveMeta = { ...(frozenMeta || {}), pid: process.pid, shardPromptsActive: s._partPrompts || 0, ...(s._instanceKey && { instance: s._instanceKey }) };
208
+ writeFileAtomicSync(join(sessionDir, 'meta.json'), JSON.stringify(liveMeta, null, 2) + '\n');
209
+ } catch (err) { reportSwallowed('v2-shard.rotate-livemeta', err); }
210
+ s.blobs = new BlobStore(paths);
211
+ // ConversationStore: REUSE the same object (only its _paths pointer flips to
212
+ // the fresh skeleton). Rebuilding it empty would make the next request write
213
+ // a `snapshot(first)` carrying the FULL pre-cut wire history — defeating the
214
+ // shard's whole point (the active dir would never shrink; disk would grow
215
+ // super-linearly with the shard count). Keeping count/fps/epoch lets the
216
+ // first post-cut request write only its INCREMENT, exactly like a restart
217
+ // continuation. The cut boundary still replays cleanly: the frozen shard's
218
+ // own snapshot is its self-contained baseline, and the fresh shard continues
219
+ // by appending deltas onto the (inherited) wire state.
220
+ s.convs._paths = paths;
221
+ // The reused store's per-conv dirEnsured flag pointed at the OLD (now
222
+ // archived) dirs — reset it so the first post-cut write re-creates the conv
223
+ // dir under the fresh skeleton (its content is carried by count/fps, so the
224
+ // write itself is still an increment, not a snapshot).
225
+ for (const st of s.convs._convs.values()) st.dirEnsured = false;
226
+ // Journal: reuse the SAME object so _seq survives the cut; only its target
227
+ // paths change. The reader folds by seq — a restart at 1 would collide with
228
+ // every frozen-shard line.
229
+ s.journal._paths = paths;
230
+ } catch (err) {
231
+ // The live files are archived under parts/<N>/ but the live skeleton could
232
+ // not be recreated. Report loudly; the next ingest retries this branch.
233
+ reportSwallowed('v2-shard.rotate-rebind', err);
234
+ return false;
235
+ }
236
+
237
+ // Best-effort observation event — lets the live feed re-attach without
238
+ // suppressing the fresh shard's history.
239
+ try { writer._onShardRotated && writer._onShardRotated(partDir, s); } catch {}
240
+ return true;
241
+ }
242
+
243
+ /** Read a session dir's meta.json (first-write-wins identity + role fields). */
244
+ function _readFrozenMeta(dir) {
245
+ try {
246
+ const meta = JSON.parse(readFileSync(join(dir, 'meta.json'), 'utf-8'));
247
+ return meta && typeof meta === 'object' ? meta : null;
248
+ } catch { return null; }
249
+ }
@@ -29,7 +29,9 @@ import { ConversationStore } from './conversation-store.js';
29
29
  import { parseUserId, classifyKind, ConvResolver } from './identity.js';
30
30
  import { parseAgentId, findHeader } from './agent-id.js';
31
31
  import { extractUserTexts, flattenPromptText, isSuggestionMode, readPromptsHead } from '../user-prompt-extract.js';
32
+ import { iterateJsonlLines } from './jsonl-read.js';
32
33
  import { consumePendingForWireByKey, writeSnapshotByKey, systemTextOfBody } from '../system-prompt-snapshots.js';
34
+ import { rotateSessionDir, SHARD_PROMPT_THRESHOLD } from './shard-manager.js';
33
35
 
34
36
  // Below this many free bytes on the log volume, v2 skips writing and reports
35
37
  // once — logging must not be the thing that fills the disk (plan risk #9).
@@ -94,6 +96,10 @@ export class V2Writer {
94
96
  // REASSIGNED away from body.messages, never mutated in place — safe).
95
97
  this._lateHandles = new Map(); // rid → handle for held requests whose completion arrives after the flush
96
98
  this._diskGuardTripped = false;
99
+ // Shard rotation seam (tests): prompt ceiling per shard. The production
100
+ // default is SHARD_PROMPT_THRESHOLD (2000); tests inject a tiny value so a
101
+ // few fixture prompts trigger the cut.
102
+ this._shardPrompts = typeof opts.shardPrompts === 'number' && opts.shardPrompts > 0 ? opts.shardPrompts : 0;
97
103
  this._continuedSeen = false; // P2: wire-level `claude -c` continuation marker
98
104
  // `-c` folder adoption (Claude 2.1.210 hands a fresh wire session_id on every
99
105
  // continue, so a new folder would otherwise be minted each time). Set from
@@ -139,6 +145,11 @@ export class V2Writer {
139
145
  * writer exists (module init order), so the nudge callback arrives here. */
140
146
  setOnActivity(fn) { this._onActivity = typeof fn === 'function' ? fn : null; }
141
147
  setOnSessionResolved(fn) { this._onSessionResolved = typeof fn === 'function' ? fn : null; }
148
+ // Shard rotation (2026-11): fired AFTER a rotation rebinds the session to a
149
+ // fresh skeleton. The live feed must re-attach the dir WITHOUT suppressing
150
+ // history — the fresh shard's first post-cut content is new, not cold-load
151
+ // history (the default shrink→rebuild path would suppress and swallow it).
152
+ setOnShardRotated(fn) { this._onShardRotated = typeof fn === 'function' ? fn : null; }
142
153
 
143
154
  /**
144
155
  * If this request should adopt the previous main session's folder — a `-c`
@@ -331,6 +342,13 @@ export class V2Writer {
331
342
  // dir keeps its ORIGINAL author's cwd — never relabeled by the adopting entry.
332
343
  // Normalized lexically (no realpath) to match the read side's targetCwd.
333
344
  ...(cwd && { cwd: normalizeSessionCwd(cwd) }),
345
+ // Sharding (2026-11): persist the ACTIVE shard's prompt counter so a
346
+ // restart re-seeds from meta instead of the prompts.jsonl line count —
347
+ // that file is archived with its shard (PROMPTS-capped) and would seed
348
+ // an under-count, letting a near-threshold shard grow unboundedly.
349
+ // First-write-wins: the counter is carried forward by the rotation's own
350
+ // meta carry-over, not rewritten here.
351
+ shardPromptsActive: 0,
334
352
  ...(this._metaExtra || {}),
335
353
  };
336
354
  const projectDir = join(this._logDir, sanitizePathComponent(project));
@@ -366,6 +384,24 @@ export class V2Writer {
366
384
  journal: new Journal(paths, this._queue),
367
385
  convs: new ConversationStore(paths, this._queue, { exactFps: this._exactConvFps }),
368
386
  resolver: new ConvResolver(),
387
+ // Identity UUID (wire sessionId / adopted folder's UUID) — shard rotation
388
+ // re-stamps it on the recreated active dir so the session's identity stays
389
+ // stable across the cut without re-reading the frozen meta.
390
+ _identityId: identityId,
391
+ // The instanceKey that stamped meta.json — shard rotation re-stamps it on
392
+ // the recreated active dir (shard-manager.js) so multi-instance routing
393
+ // survives the cut.
394
+ _instanceKey: instanceKey || null,
395
+ // In-flight request count + rotation state (shard-manager.js): the cut is
396
+ // deferred until no request is open and the write queue is idle.
397
+ _inflight: 0,
398
+ _shardArmed: false,
399
+ _rotating: false,
400
+ _shardRetryQueued: false,
401
+ // New-user-prompt count on the CURRENT shard (the rotation trigger).
402
+ // Seeded once from the live prompts.jsonl on first contact (restart).
403
+ _partPrompts: 0,
404
+ _promptsSeeded: false,
369
405
  // The project this session's dir lives under — needed by resetSessions(target)
370
406
  // to clear ONLY one project's sessions on a workspace switch, leaving a
371
407
  // concurrently-running background project's bindings (a cross-project /resume
@@ -521,6 +557,23 @@ export class V2Writer {
521
557
  (typeof entry._ccvInstance === 'string' && entry._ccvInstance) ? entry._ccvInstance : null,
522
558
  (typeof entry._resumeProjectCwd === 'string' && entry._resumeProjectCwd) ? entry._resumeProjectCwd : null);
523
559
 
560
+ // Shard rotation (shard-manager.js): the live content is archived into the
561
+ // session's own `parts/<N>/` and this session is rebound to a fresh
562
+ // skeleton. The trigger is PROMPT-COUNT based, not bytes: after
563
+ // SHARD_PROMPT_THRESHOLD user-prompt turns on the main conversation, the
564
+ // NEXT new user prompt starts a fresh shard — so every part holds whole
565
+ // user-prompt→loop segments, never a half-turn. Rotation is DEFERRED to a
566
+ // quiescent point (no in-flight request + an idle write queue, so a
567
+ // req/done never splits across shards and a chunked drain never tears a
568
+ // line across the cut). Cost below threshold: one O(1) counter check.
569
+ try { this._armShardRotation(s); } catch (err) { reportSwallowed('v2-write.shard-arm', err); }
570
+ // Run an already-armed cut at this quiescent point (no in-flight request
571
+ // on this session yet — the count is bumped by _ingestInto below). This
572
+ // is what lets the NEXT new-user-prompt after a threshold-crossing one
573
+ // land in a fresh shard. (_armShardRotation already runs _maybeRotate
574
+ // when it arms with nothing in flight; this covers cuts armed earlier.)
575
+ if (s._shardArmed && (s._inflight || 0) === 0) this._maybeRotate(s);
576
+
524
577
  // System-prompt snapshot, Bind A (wire): the FIRST main request of a session
525
578
  // carries the launch's rendered injection in body.system — match it against the
526
579
  // project's pending queue and key the snapshot to the wire sid (== transcript
@@ -562,15 +615,34 @@ export class V2Writer {
562
615
  const pseq = this._ingestInto(s, sid, p.entry, p.originalMessages);
563
616
  const prid = p.rid; // captured at hold time — the seam may have deleted entry.requestId by now
564
617
  if (pseq != null && prid) {
565
- this._lateHandles.set(prid, { s, sid, seq: pseq, rid: prid });
618
+ // Held requests count as in-flight too (they complete later via
619
+ // _lateHandles): a rotation must not fire while one is open.
620
+ const handle = { s, sid, seq: pseq, rid: prid, paths: s.paths, journal: s.journal, counted: false };
621
+ this._openHandle(handle);
622
+ this._lateHandles.set(prid, handle);
566
623
  if (this._lateHandles.size > 64) {
567
- this._lateHandles.delete(this._lateHandles.keys().next().value);
624
+ const evicted = this._lateHandles.keys().next().value;
625
+ const evictedHandle = this._lateHandles.get(evicted);
626
+ this._lateHandles.delete(evicted);
627
+ // Evicting a still-open handle must release its in-flight count,
628
+ // or the session would never rotate again (stuck at >0). The
629
+ // handle is unreachable afterwards, so close without re-arming
630
+ // the rotation latch (its completion can never arrive).
631
+ this._closeHandle(evictedHandle, { rotate: false });
568
632
  }
569
633
  }
570
634
  }
571
635
  }
572
636
 
573
637
  const seq = this._ingestInto(s, sid, entry, originalMessages);
638
+ const handle = seq == null ? null : { s, sid, seq, rid: entry.requestId || `${seq}`, paths: s.paths, journal: s.journal, counted: false };
639
+ if (handle) {
640
+ // In-flight guard for shard rotation: a completion must land its
641
+ // done/response in the SAME shard that holds its req line. Count the
642
+ // request as open until ingestCompletion closes it; rotation only runs
643
+ // once this reaches zero (and the queue is flushed).
644
+ this._openHandle(handle);
645
+ }
574
646
  if (seq != null && this._onActivity) {
575
647
  try { this._onActivity(s.paths.dir); } catch { /* nudge only — never disturb the write */ }
576
648
  }
@@ -578,8 +650,10 @@ export class V2Writer {
578
650
  // resetSessions() (workspace switch) clears the _sessions map, and a
579
651
  // completion arriving after the switch must still land its done/response
580
652
  // lines in the session the request belonged to (review P2: a map lookup
581
- // at completion time silently dropped them).
582
- return seq == null ? null : { s, sid, seq, rid: entry.requestId || `${seq}` };
653
+ // at completion time silently dropped them). It ALSO snapshots the
654
+ // request-time paths so a shard rotation between request and completion
655
+ // keeps the done/response in the shard that owns this seq.
656
+ return handle;
583
657
  } catch (err) {
584
658
  reportSwallowed('v2-write.ingestRequest', err);
585
659
  return null;
@@ -603,6 +677,19 @@ export class V2Writer {
603
677
  }
604
678
  if (kind === 'main') s._sawMain = true;
605
679
 
680
+ // Shard trigger (2026-11): a NEW main-conversation user prompt is the cut
681
+ // node. See _countShardPrompt for the counting rule. On crossing the prompt
682
+ // ceiling, rotate BEFORE this request's blob/conv/journal writes so the new
683
+ // prompt opens the fresh shard (this is the quiescent point: this request's
684
+ // in-flight count isn't bumped until after _ingestInto returns).
685
+ if (this._countShardPrompt(s, kind, msgs)) {
686
+ if ((s._partPrompts || 0) > this._shardThresholdPrompts() && (s._inflight || 0) === 0 && !s._rotating) {
687
+ s._shardArmed = true;
688
+ this._maybeRotate(s);
689
+ if (!s._rotating && !s._shardArmed) s._partPrompts = 1; // rotated: this prompt starts the new shard
690
+ }
691
+ }
692
+
606
693
  // 1. Blobs (sync + fsync — the durability barrier).
607
694
  const toolsRef = s.blobs.put(entry.body && entry.body.tools);
608
695
  const sysRef = s.blobs.put(entry.body && entry.body.system);
@@ -728,8 +815,14 @@ export class V2Writer {
728
815
  // deletes requestId from the entry before writing, and the seam must be
729
816
  // free to call us before or after those deletes.
730
817
  const rid = handle.rid || `${handle.seq}`;
818
+ // Write to the shard that owns this seq — the request-time paths snapshot
819
+ // on the handle (NOT s.paths, which a shard rotation may have since
820
+ // rebound to the fresh active dir). Falls back to the session's current
821
+ // paths for legacy handles without a snapshot.
822
+ const donePaths = handle.paths || s.paths;
823
+ const doneJournal = handle.journal || s.journal;
731
824
  this._queue.appendTo(
732
- s.paths.responsesPath,
825
+ donePaths.responsesPath,
733
826
  JSON.stringify({
734
827
  seq: handle.seq,
735
828
  rid,
@@ -740,7 +833,7 @@ export class V2Writer {
740
833
  );
741
834
 
742
835
  const usage = respBody && respBody.usage ? respBody.usage : null;
743
- s.journal.writeDone({
836
+ doneJournal.writeDone({
744
837
  seq: handle.seq,
745
838
  rid,
746
839
  ts: opts.doneTs || new Date().toISOString(),
@@ -760,11 +853,154 @@ export class V2Writer {
760
853
  if (this._onActivity && s.paths) {
761
854
  try { this._onActivity(s.paths.dir); } catch { /* nudge only — never disturb the write */ }
762
855
  }
856
+ // Close the in-flight guard opened at ingestRequest and, when this was
857
+ // the last open request, run any armed shard rotation (quiescent point).
858
+ this._closeHandle(handle);
763
859
  } catch (err) {
764
860
  reportSwallowed('v2-write.ingestCompletion', err);
765
861
  }
766
862
  }
767
863
 
864
+ /** Open an in-flight handle: every counted handle must close exactly once
865
+ * (see _closeHandle). Centralized so the increment sites can't drift. */
866
+ _openHandle(handle) {
867
+ if (!handle || typeof handle.seq !== 'number') return;
868
+ handle.s._inflight = (handle.s._inflight || 0) + 1;
869
+ handle.counted = true;
870
+ }
871
+
872
+ /** Close a counted handle exactly once (the `counted` latch makes a double
873
+ * close a no-op) and, when it was the session's last open request, run any
874
+ * armed shard rotation (quiescent point). `rotate:false` for paths where
875
+ * the handle is already unreachable (late-handle eviction) — re-arming the
876
+ * rotation latch there would be wasted work. */
877
+ _closeHandle(handle, { rotate = true } = {}) {
878
+ const s = handle && (handle.s || this._sessions.get(handle.sid));
879
+ if (!s) return;
880
+ if (typeof handle.seq === 'number' && handle.counted && s._inflight > 0) {
881
+ handle.counted = false; // one-shot latch: a double completion can't double-decrement
882
+ s._inflight -= 1;
883
+ if (rotate && s._inflight === 0) this._maybeRotate(s);
884
+ }
885
+ }
886
+
887
+ /** Release a request's in-flight count WITHOUT writing a done/response line —
888
+ * for requests that will never complete (fetch reject on Esc/network error,
889
+ * stream read abort). Without it `_inflight` leaks ≥1 and the session never
890
+ * rotates again for this process's lifetime. */
891
+ releaseHandle(handle) {
892
+ try {
893
+ this._closeHandle(handle);
894
+ } catch (err) { reportSwallowed('v2-write.release-handle', err); }
895
+ }
896
+
897
+ /** Arm shard rotation once the live dir crosses the threshold. Cheap: an O(1)
898
+ * counter bump per new user prompt. The actual cut is deferred to
899
+ * _maybeRotate (quiescent point). */
900
+ _armShardRotation(s) {
901
+ if (!s || s._shardArmed || s._rotating) return;
902
+ // Only rotate live session trees — the offline converter writes to a
903
+ // staging sibling (sessionsDirName 'sessions-migrating') whose promote/
904
+ // verify flow assumes one dir per logical session.
905
+ if (this._sessionsDirName !== 'sessions') return;
906
+ // Prompt-count trigger (no disk probing): the per-session counter
907
+ // `_partPrompts` is bumped on each NEW main-conversation user prompt (see
908
+ // _countShardPrompt). On first contact (a re-attached/restarted session)
909
+ // seed it from the LIVE meta's `shardPromptsActive` (persisted at the last
910
+ // rotation); the prompts.jsonl LINE COUNT is only the legacy fallback —
911
+ // that file is archived with its shard (PROMPTS-capped), so seeding from
912
+ // it after a rotation would under-count and let a near-threshold shard
913
+ // grow unboundedly across restarts.
914
+ if (!s._promptsSeeded) {
915
+ s._promptsSeeded = true;
916
+ let seeded = null;
917
+ try {
918
+ const meta = JSON.parse(readFileSync(s.paths.metaPath, 'utf-8'));
919
+ if (meta && typeof meta.shardPromptsActive === 'number' && meta.shardPromptsActive >= 0) seeded = meta.shardPromptsActive;
920
+ } catch { /* no meta (legacy/external producer) — fall back to the file scan */ }
921
+ if (seeded == null) {
922
+ let lines = 0;
923
+ try { for (const _ of iterateJsonlLines(s.paths.promptsPath)) lines++; } catch { lines = 0; }
924
+ seeded = lines;
925
+ }
926
+ s._partPrompts = seeded;
927
+ }
928
+ if ((s._partPrompts || 0) < this._shardThresholdPrompts()) return;
929
+ s._shardArmed = true;
930
+ // An armed cut takes effect at the next quiescent point (the request start
931
+ // with none open, or the last completion) — _maybeRotate runs from both. If
932
+ // THIS request armed it and nothing is in flight yet, cut right away.
933
+ if ((s._inflight || 0) === 0) this._maybeRotate(s);
934
+ }
935
+
936
+ _shardThresholdPrompts() {
937
+ return (typeof this._shardPrompts === 'number' && this._shardPrompts > 0) ? this._shardPrompts : SHARD_PROMPT_THRESHOLD;
938
+ }
939
+
940
+ /** Count one NEW main-conversation user prompt toward the shard ceiling and
941
+ * bump the per-session counter. Rule: read the conv store's CURRENT wire
942
+ * length (read-only, no side effect); a fresh user turn appends a
943
+ * non-tool-result user message at [prevCount, len). A SNAPSHOT (restart /
944
+ * -c / compact / dual-writer) has prevCount < len only for genuinely new
945
+ * tail content — so scanning that slice never recounts history. Tool-loop
946
+ * follow-ups append only tool_result/assistant and do NOT count.
947
+ * @returns {boolean} true when this entry carried a new user prompt. */
948
+ _countShardPrompt(s, kind, msgs) {
949
+ if (kind !== 'main' || !msgs || msgs.length === 0) return false;
950
+ const prevCount = s.convs.count('main');
951
+ for (let i = prevCount; i < msgs.length; i++) {
952
+ const m = msgs[i];
953
+ if (m && m.role === 'user' && !this._isToolResultMsg(m)) {
954
+ s._partPrompts = (s._partPrompts || 0) + 1;
955
+ return true;
956
+ }
957
+ }
958
+ return false;
959
+ }
960
+
961
+ /** Run an armed rotation at a quiescent point — SYNCHRONOUSLY, before the
962
+ * triggering request's `_ingestInto`. The cut is safe only when: no request
963
+ * is in flight on this session (its completion must land in the same shard
964
+ * as its req) AND the write queue is idle (a chunked drain re-opens the
965
+ * target path per chunk, so a mid-drain rename would tear a line across
966
+ * shards). When the queue is busy the cut stays armed and retries at the
967
+ * next request start / completion. */
968
+ _maybeRotate(s) {
969
+ if (!s || s._rotating) return;
970
+ if ((s._inflight || 0) > 0) return; // completion of the last one re-triggers
971
+ if (!s._shardArmed) return;
972
+ if (!this._queue.isIdle) {
973
+ // The drain hasn't settled — a mid-drain rename would tear a chunked line
974
+ // across shards. Park ONE retry on the drain-complete callback (the true
975
+ // idle point) instead of busy-retrying per request.
976
+ if (!s._shardRetryQueued) {
977
+ s._shardRetryQueued = true;
978
+ this._queue.onIdle(() => {
979
+ s._shardRetryQueued = false;
980
+ this._maybeRotate(s);
981
+ });
982
+ }
983
+ return;
984
+ }
985
+ s._rotating = true;
986
+ try {
987
+ const rotated = rotateSessionDir(this, s);
988
+ if (rotated) {
989
+ // Re-claim the freshly created active dir so multi-window isolation
990
+ // survives the cut (the old claim rode the rename into the shard).
991
+ if (this._claimsEnabled() && acquireSessionClaim(s.paths.dir).ok) {
992
+ this._claimedDirs.add(s.paths.dir);
993
+ }
994
+ s._shardArmed = false;
995
+ s._partPrompts = 0; // fresh active shard starts its prompt count over
996
+ }
997
+ } catch (err) {
998
+ reportSwallowed('v2-write.shard-rotate', err);
999
+ } finally {
1000
+ s._rotating = false;
1001
+ }
1002
+ }
1003
+
768
1004
  /** Session directory of the writer's current (fallback-routing) session, or
769
1005
  * null before the first sid-bearing request. The read side uses this to
770
1006
  * resolve "the live session" for /events cold loads (S6b). */
@@ -782,6 +1018,16 @@ export class V2Writer {
782
1018
  return this._currentSid || null;
783
1019
  }
784
1020
 
1021
+ /** True when a wire message is a tool_result carrier (not a fresh user
1022
+ * prompt). The shard cut only opens on a genuine user turn — tool-loop
1023
+ * follow-ups append tool_result blocks at the wire tail and must not count. */
1024
+ _isToolResultMsg(msg) {
1025
+ const c = msg && msg.content;
1026
+ if (typeof c === 'string') return false; // plain-text user prompt
1027
+ if (!Array.isArray(c)) return false;
1028
+ return c.some((b) => b && b.type === 'tool_result');
1029
+ }
1030
+
785
1031
  /** Lifecycle hook: drop in-memory conversation continuity so the next
786
1032
  * request snapshots fresh. Journal seq keeps counting (same process, same
787
1033
  * session dirs — seq must stay monotonic per session). NOTE: the