cc-viewer 1.9.21 → 1.9.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +2 -1
  2. package/cli.js +50 -14
  3. package/dist/assets/{App-C4f2Dpy9.js → App-DEA3HoZr.js} +2 -2
  4. package/dist/assets/{MdxEditorPanel-D7aQDQJp.js → MdxEditorPanel-CTAS2DJv.js} +1 -1
  5. package/dist/assets/{Mobile-D9ekLQFS.js → Mobile-CgVpXvs2.js} +1 -1
  6. package/dist/assets/{ProxyStatsModal-CWpgyVKI.js → ProxyStatsModal-C4sl-cuB.js} +1 -1
  7. package/dist/assets/index-CS47d9oh.js +2 -0
  8. package/dist/assets/seqResourceLoaders-CORH46PN.js +2 -0
  9. package/dist/assets/seqResourceLoaders-v4YzKhTS.css +41 -0
  10. package/dist/index.html +1 -1
  11. package/findcc.js +4 -4
  12. package/node_modules/@ccv/core/src/contentFilter.js +4 -1
  13. package/node_modules/@ccv/core/src/ultraplanTemplates.js +199 -0
  14. package/package.json +1 -1
  15. package/server/i18n.js +97 -14
  16. package/server/interceptor.js +6 -0
  17. package/server/lib/async-write-queue.js +18 -0
  18. package/server/lib/auth.js +11 -3
  19. package/server/lib/base-path.js +89 -18
  20. package/server/lib/base-url.js +209 -0
  21. package/server/lib/ensure-hooks.js +134 -2
  22. package/server/lib/im/im-bridge-core.js +16 -0
  23. package/server/lib/log-management.js +21 -1
  24. package/server/lib/plugin-runtime.js +24 -5
  25. package/server/lib/scheduled-task-executor.js +14 -2
  26. package/server/lib/scheduled-task-store.js +129 -18
  27. package/server/lib/sdk-manager.js +113 -11
  28. package/server/lib/v2/adapter.js +147 -15
  29. package/server/lib/v2/conversation-store.js +9 -0
  30. package/server/lib/v2/journal.js +35 -0
  31. package/server/lib/v2/layout.js +67 -1
  32. package/server/lib/v2/live-feed.js +15 -0
  33. package/server/lib/v2/replay.js +11 -3
  34. package/server/lib/v2/session-select.js +34 -2
  35. package/server/lib/v2/shard-manager.js +249 -0
  36. package/server/lib/v2/v2-writer.js +252 -6
  37. package/server/pty-manager.js +103 -4
  38. package/server/routes/events.js +75 -4
  39. package/server/routes/logs.js +47 -16
  40. package/server/routes/misc.js +15 -5
  41. package/server/routes/scheduled-tasks.js +13 -0
  42. package/server/server.js +123 -23
  43. package/dist/assets/index-CocpEURl.js +0 -2
  44. package/dist/assets/seqResourceLoaders-BhiCEaUt.js +0 -2
  45. package/dist/assets/seqResourceLoaders-DbccWwKz.css +0 -41
@@ -31,13 +31,14 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
31
31
  import { join, dirname, basename } from 'node:path';
32
32
  import { reportSwallowed } from '../../lib/error-report.js';
33
33
  import { isMainAgentRequest } from '../interceptor-core.js';
34
- import { readSession } from './replay.js';
34
+ import { readSession, readJsonlTolerant } from './replay.js';
35
35
  import { iterateJsonlLines } from './jsonl-read.js';
36
36
  import { isDiscardableSession } from './session-select.js';
37
37
  import { LIVE_SESSION_MTIME_MS } from '../log-file-utils.js';
38
- import { blobPath, isSupportedWireFormat } from './layout.js';
38
+ import { blobPath, isSupportedWireFormat, shardReadRoot } from './layout.js';
39
39
  import { SingleFlight } from './singleflight.js';
40
40
  import { listV2Sessions } from './session-list.js';
41
+ import { readShardCuts } from './shard-manager.js';
41
42
 
42
43
  // Same stamping rules as the v1 interceptor (KEEP IN SYNC: server/interceptor.js
43
44
  // requestEntry construction) — recomputed from the journal's url, not from kind,
@@ -612,13 +613,34 @@ export class SessionSynthesizer {
612
613
  /**
613
614
  * Cold generator over ONE session dir: yields items (see SessionSynthesizer)
614
615
  * in seq order — the eager feeding of the shared synthesis engine.
616
+ *
617
+ * opts.beforeSeq (sharding, 2026-11): forwarded to readSession — journal lines
618
+ * and conversation events with seq >= beforeSeq are dropped BEFORE the eager
619
+ * seed, so a frozen `.part<N>` shard replays exactly the requests up to the
620
+ * cut (its incremental snapshot is self-contained at that boundary). The
621
+ * responses read below is filtered the same way (first-write-wins by seq).
615
622
  */
616
623
  function* iterateSessionItems(sessionDir, opts = {}) {
617
- const projectDir = dirname(dirname(sessionDir));
618
- const sessionId = basename(sessionDir);
624
+ // Path derivation: a live session is <project>/sessions/<dirName> (so
625
+ // projectDir = dirname(dirname(sessionDir)) and readSession's default
626
+ // sessionsDirName 'sessions' resolves it). A frozen SHARD lives INSIDE the
627
+ // session dir at <project>/sessions/<dirName>/parts/<N>/ — one level deeper —
628
+ // so the same naive derivation would point readSession at a nonexistent
629
+ // path. layout's shardReadRoot owns the shape detection + coordinate
630
+ // derivation.
631
+ let projectDir = dirname(dirname(sessionDir));
632
+ let sessionsDirName = 'sessions';
633
+ let sessionId = basename(sessionDir);
634
+ const shardRoot = shardReadRoot(sessionDir);
635
+ if (shardRoot) {
636
+ projectDir = shardRoot.projectDir;
637
+ sessionsDirName = shardRoot.sessionsDirName;
638
+ sessionId = shardRoot.sessionId;
639
+ }
640
+ const beforeSeq = (typeof opts.beforeSeq === 'number' && opts.beforeSeq > 0) ? opts.beforeSeq : null;
619
641
  let session;
620
642
  try {
621
- session = readSession(projectDir, sessionId);
643
+ session = readSession(projectDir, sessionId, sessionsDirName, { beforeSeq });
622
644
  } catch (err) {
623
645
  // One unreadable session must degrade to "not rendered", never crash the
624
646
  // whole scan (issue #129: an oversized file crash-looped every startup).
@@ -640,7 +662,13 @@ function* iterateSessionItems(sessionDir, opts = {}) {
640
662
  // before any req is pumped — every gate then resolves exactly like the
641
663
  // historical whole-file read.
642
664
  for (const [key, events] of session.convEvents) synth._conv(key).events = events;
643
- synth._responses = readResponsesRaw(sessionDir);
665
+ const responses = readResponsesRaw(sessionDir);
666
+ if (beforeSeq != null) {
667
+ for (const seq of responses.keys()) {
668
+ if (seq >= beforeSeq) responses.delete(seq);
669
+ }
670
+ }
671
+ synth._responses = responses;
644
672
  synth._dones = session.dones;
645
673
  const seqs = [...session.reqs.keys()].sort((a, b) => a - b);
646
674
  for (const seq of seqs) {
@@ -821,13 +849,13 @@ export function _v2WindowStatsForTest(reset = false) {
821
849
  * The result is IMMUTABLE and shared across coalesced callers — window
822
850
  * selection must not mutate `recs`/`ring`.
823
851
  */
824
- export async function scanV2Descriptors(sessionDir) {
852
+ export async function scanV2Descriptors(sessionDir, opts = {}) {
825
853
  _windowStats.scanRuns++;
826
854
  const dedup = new Map(); // key → descriptor (insertion order = output order)
827
855
  const ring = []; // newest ≤3 isMain descriptors, pre-dedup iteration order
828
856
  let nokey = 0;
829
857
  let n = 0;
830
- for (const d of iterateV2Items(sessionDir, { descriptorOnly: true })) {
858
+ for (const d of iterateV2Items(sessionDir, { descriptorOnly: true, beforeSeq: opts.beforeSeq })) {
831
859
  const key = d.ts && d.url ? `${d.ts}|${d.url}` : `__nokey_${nokey++}`;
832
860
  dedup.set(key, d);
833
861
  // Ring criterion is item.isMain (kind==='main' on a non-teammate session):
@@ -881,9 +909,12 @@ function selectV2Window(scan, opts = {}) {
881
909
  }
882
910
 
883
911
  /** Level-1 shared Pass A + per-caller selection. `cached` gates the TTL
884
- * micro-cache read (F5b: /events live-attach must never consume it). */
912
+ * micro-cache read (F5b: /events live-attach must never consume it). The
913
+ * scan key includes beforeSeq so a shard-window scan never coalesces with
914
+ * the full-session scan of the same dir (different folds, different recs). */
885
915
  export async function computeV2Window(sessionDir, opts = {}) {
886
- const scan = await _scanFlight.run(`scan:${sessionDir}`, () => scanV2Descriptors(sessionDir), { cached: !!opts.cached });
916
+ const beforeSeq = (typeof opts.beforeSeq === 'number' && opts.beforeSeq > 0) ? opts.beforeSeq : 0;
917
+ const scan = await _scanFlight.run(`scan:${sessionDir}|${beforeSeq}`, () => scanV2Descriptors(sessionDir, { beforeSeq: beforeSeq || undefined }), { cached: !!opts.cached });
887
918
  return selectV2Window(scan, opts);
888
919
  }
889
920
 
@@ -899,7 +930,7 @@ export async function computeV2Window(sessionDir, opts = {}) {
899
930
  * equivalent (algorithm review F6). `collect` mode fills a slot array in
900
931
  * Pass A output order instead: byte-identical to the historical single pass.
901
932
  */
902
- async function materializeV2Window(sessionDir, win, { collect = false, onEntry = null, promoteKeys = null } = {}) {
933
+ async function materializeV2Window(sessionDir, win, { collect = false, onEntry = null, promoteKeys = null, noBaselinePromotion = false } = {}) {
903
934
  const memberIdx = new Map();
904
935
  win.members.forEach((d, i) => memberIdx.set(itemKey(d.sessionId, d.seq), i));
905
936
  const ringKeys = new Set(win.ring.map((d) => itemKey(d.sessionId, d.seq)));
@@ -928,7 +959,10 @@ async function materializeV2Window(sessionDir, win, { collect = false, onEntry =
928
959
  // the detail view needs the full replayed state for BOTH the target and
929
960
  // its prevMain (Body Diff / cacheLoss compare whole messages arrays).
930
961
  // The window baseline promotes only win.baselineKey (the window start).
931
- if (k === win.baselineKey || (promoteKeys && promoteKeys.has(k))) {
962
+ // noBaselinePromotion (shard "load earlier" pages): a shard page must be a
963
+ // PURE increment slice, not a checkpoint — otherwise each page replays the
964
+ // shard's whole prefix and the client renders the overlap twice.
965
+ if (!noBaselinePromotion && (k === win.baselineKey || (promoteKeys && promoteKeys.has(k)))) {
932
966
  const state = item.stateRef || [];
933
967
  const rebuilt = { ...item.entry, body: { ...item.entry.body, messages: state } };
934
968
  rebuilt._isCheckpoint = true;
@@ -1023,11 +1057,16 @@ export async function readV2SingleEntry(sessionDir, opts = {}) {
1023
1057
 
1024
1058
  export async function readV2WindowedEntries(sessionDir, opts = {}) {
1025
1059
  const cached = !!opts.cached;
1026
- const key = `win:${sessionDir}|${opts.limit || 0}|${opts.before || ''}`;
1060
+ // beforeSeq scopes the window content (sharding) — it MUST be in the key or
1061
+ // two "load earlier" pages of the same shard coalesce onto the first cursor.
1062
+ // noBaselinePromotion is in the key for the same reason: a promoted and a
1063
+ // non-promoted read of the same window must never share a flight/result.
1064
+ const beforeSeq = (typeof opts.beforeSeq === 'number' && opts.beforeSeq > 0) ? opts.beforeSeq : 0;
1065
+ const key = `win:${sessionDir}|${opts.limit || 0}|${opts.before || ''}|${beforeSeq}|${opts.noBaselinePromotion ? 1 : 0}`;
1027
1066
  return _windowFlight.run(key, async () => {
1028
1067
  _windowStats.materializeRuns++;
1029
1068
  const win = await computeV2Window(sessionDir, opts);
1030
- const { slots, mainAgentRing } = await materializeV2Window(sessionDir, win, { collect: true });
1069
+ const { slots, mainAgentRing } = await materializeV2Window(sessionDir, win, { collect: true, noBaselinePromotion: !!opts.noBaselinePromotion });
1031
1070
  const entries = [];
1032
1071
  for (let i = 0; i < slots.length; i++) {
1033
1072
  if (slots[i] !== undefined) {
@@ -1043,12 +1082,100 @@ export async function readV2WindowedEntries(sessionDir, opts = {}) {
1043
1082
  entries,
1044
1083
  hasMore: win.hasMore,
1045
1084
  oldestTimestamp: win.oldestTimestamp,
1085
+ // The DELIVERED window's oldest seq (win.members[0] is the tail-sliced
1086
+ // window start, not the whole shard's min) — the cursor for "load
1087
+ // earlier" must advance from the delivered edge, or a limit-truncated
1088
+ // page would skip the shard's middle history.
1089
+ oldestSeq: (win.members && win.members.length > 0 && typeof win.members[0].seq === 'number') ? win.members[0].seq : null,
1046
1090
  totalCount: win.totalCount,
1047
1091
  mainAgentRing,
1048
1092
  };
1049
1093
  }, { cached });
1050
1094
  }
1051
1095
 
1096
+ /**
1097
+ * Sharded windowed read (2026-11): read the session's history OLDER than
1098
+ * `beforeSeq`. Frozen shards live INSIDE the session dir at
1099
+ * `<project>/sessions/<base>/parts/<N>/` and each is a self-contained session
1100
+ * dir (its meta.json is copied in at the cut): its incremental snapshot replays
1101
+ * to the state at the cut, so the window's baseline promotion (selectV2Window)
1102
+ * is byte-exact without touching the active shard.
1103
+ *
1104
+ * Target selection is cursor-driven and handles BOTH cross-shard and
1105
+ * within-shard paging: each shard owns the seq interval (prevCut, cutSeq]; the
1106
+ * shard that owns `beforeSeq - 1` is the one to read (its cut is the first
1107
+ * cutSeq >= beforeSeq - 1), so a limit-truncated page stays on the SAME shard
1108
+ * for the next click instead of skipping the shard's middle history.
1109
+ *
1110
+ * @param {string} sessionDir - ACTIVE session dir (the base)
1111
+ * @param {{beforeSeq: number, limit?: number, cached?: boolean}} opts
1112
+ * @returns {Promise<{entries: string[], hasMore: boolean, oldestTimestamp: string,
1113
+ * oldestSeq: number|null, partIndex: number, totalCount: number, mainAgentRing: string[]}>}
1114
+ * hasMore = this shard window has older entries OR an even-older shard exists.
1115
+ */
1116
+ export async function readV2ShardEntries(sessionDir, opts = {}) {
1117
+ const beforeSeq = (typeof opts.beforeSeq === 'number' && opts.beforeSeq > 0) ? opts.beforeSeq : null;
1118
+ const cached = opts.cached !== false;
1119
+ const empty = { entries: [], hasMore: false, oldestTimestamp: '', oldestSeq: null, partIndex: 0, totalCount: 0, mainAgentRing: [] };
1120
+ if (beforeSeq == null) return empty;
1121
+
1122
+ // Each shard's journal max seq (= its cut), via the shared marker-aware
1123
+ // reader (cut.json first, journal-scan fallback for pre-marker shards) —
1124
+ // same source as the routes' initial cursor, so the two can never disagree
1125
+ // on where a shard boundary lies. Empty = not sharded.
1126
+ const cuts = readShardCuts(sessionDir);
1127
+ if (cuts.length === 0) return empty;
1128
+ // Shard intervals: shard i owns (cuts[i-1].cutSeq, cuts[i].cutSeq]; the first
1129
+ // shard owns (0, cuts[0].cutSeq]. The shard owning `beforeSeq-1` is the FIRST
1130
+ // whose cutSeq >= beforeSeq-1 — that keeps a mid-shard cursor on the same
1131
+ // shard for within-shard paging. A cursor PAST every cut (beforeSeq newer
1132
+ // than the newest frozen cut) still has history in the ACTIVE shard's own
1133
+ // pre-window prefix — read it there first.
1134
+ const want = beforeSeq - 1;
1135
+ const newestCut = cuts.length > 0 ? cuts[cuts.length - 1].cutSeq : 0;
1136
+ if (want > newestCut) {
1137
+ // A shard page is a pure increment slice prepended onto the client's
1138
+ // baseline — baseline promotion would re-deliver the overlap and the
1139
+ // client renders it twice (same rule as the frozen branch below).
1140
+ const win = await readV2WindowedEntries(sessionDir, { limit: opts.limit, beforeSeq, cached, noBaselinePromotion: true });
1141
+ let activeOldestSeq = (typeof win.oldestSeq === 'number' && win.oldestSeq > 0) ? win.oldestSeq : null;
1142
+ if (activeOldestSeq == null) activeOldestSeq = newestCut > 0 ? newestCut + 1 : null;
1143
+ return {
1144
+ entries: win.entries,
1145
+ hasMore: win.hasMore || cuts.length > 0,
1146
+ oldestTimestamp: win.oldestTimestamp,
1147
+ oldestSeq: activeOldestSeq,
1148
+ partIndex: 0, // active shard
1149
+ totalCount: win.totalCount,
1150
+ mainAgentRing: win.mainAgentRing,
1151
+ };
1152
+ }
1153
+ let targetIdx = -1;
1154
+ for (let i = 0; i < cuts.length; i++) {
1155
+ if (cuts[i].cutSeq >= want) { targetIdx = i; break; }
1156
+ }
1157
+ if (targetIdx === -1) return empty; // cursor is at/below every shard's start — nothing older
1158
+ const target = cuts[targetIdx];
1159
+ const prevCut = targetIdx > 0 ? cuts[targetIdx - 1].cutSeq : 0;
1160
+
1161
+ const win = await readV2WindowedEntries(target.dir, { limit: opts.limit, beforeSeq, cached, noBaselinePromotion: true });
1162
+ // Cursor for the NEXT older read: the DELIVERED window's oldest seq (the
1163
+ // tail-sliced window start), so a limit-truncated page advances from its own
1164
+ // edge. Falls back to just past the shard's start when the window is empty.
1165
+ let oldestSeq = (typeof win.oldestSeq === 'number' && win.oldestSeq > 0) ? win.oldestSeq : null;
1166
+ if (oldestSeq == null && target.cutSeq > 0) oldestSeq = prevCut + 1;
1167
+ const hasOlderShard = targetIdx > 0;
1168
+ return {
1169
+ entries: win.entries,
1170
+ hasMore: win.hasMore || hasOlderShard,
1171
+ oldestTimestamp: win.oldestTimestamp,
1172
+ oldestSeq,
1173
+ partIndex: target.partIndex,
1174
+ totalCount: win.totalCount,
1175
+ mainAgentRing: win.mainAgentRing,
1176
+ };
1177
+ }
1178
+
1052
1179
  /**
1053
1180
  * Streaming window read (S10a): same selection semantics as
1054
1181
  * readV2WindowedEntries but entries are delivered one at a time via `onEntry`
@@ -1064,7 +1191,12 @@ export async function readV2WindowedEntries(sessionDir, opts = {}) {
1064
1191
  */
1065
1192
  export async function streamV2WindowedEntries(sessionDir, opts, onEntry) {
1066
1193
  const win = await computeV2Window(sessionDir, opts);
1067
- if (opts.onReady) opts.onReady({ totalCount: win.totalCount, hasMore: win.hasMore, oldestTs: win.oldestTimestamp || null });
1194
+ // oldestSeq = the DELIVERED window's oldest seq (the tail-sliced window
1195
+ // start) — lets the cold-load shard cursor anchor at the live window's edge
1196
+ // instead of the newest frozen shard's cut, so the active shard's own
1197
+ // pre-window prefix stays reachable.
1198
+ const windowOldestSeq = (win.members && win.members.length > 0 && typeof win.members[0].seq === 'number') ? win.members[0].seq : null;
1199
+ if (opts.onReady) opts.onReady({ totalCount: win.totalCount, hasMore: win.hasMore, oldestTs: win.oldestTimestamp || null, oldestSeq: windowOldestSeq });
1068
1200
  // Bounded window (limit>0): collect into slots and emit in Pass A output
1069
1201
  // order — byte-order parity with the historical single pass. Unbounded paths
1070
1202
  // (limit=0: /api/requests, workspaces reload, explicit ?limit=0) stream in
@@ -62,6 +62,15 @@ export class ConversationStore {
62
62
  this._fpOf = this._exactFps === true ? this._exactFpOf : fingerprintMsg;
63
63
  }
64
64
 
65
+ /** Read-only current wire length of a conversation (0 when never ingested).
66
+ * No side effects (unlike _state, which seeds epoch/fps) — used by the
67
+ * shard-rotation prompt-node check in v2-writer to read the length BEFORE
68
+ * deciding whether this request opens a fresh user turn. */
69
+ count(convKey) {
70
+ const st = this._convs.get(convKey);
71
+ return st ? st.count : 0;
72
+ }
73
+
65
74
  _state(convKey) {
66
75
  let st = this._convs.get(convKey);
67
76
  if (!st) {
@@ -9,6 +9,10 @@
9
9
  // (or the process died) — that IS the v1 placeholder, minus the duplicated body.
10
10
 
11
11
  import { iterateJsonlLines } from './jsonl-read.js';
12
+ import { readdirSync } from 'node:fs';
13
+ import { dirname, join } from 'node:path';
14
+ import { shardPartsDir } from './layout.js';
15
+ import { reportSwallowed } from '../../lib/error-report.js';
12
16
 
13
17
  export class Journal {
14
18
  /**
@@ -24,7 +28,38 @@ export class Journal {
24
28
  // resetSessions, process re-attach) would restart at 1 and collide with
25
29
  // prior lines — the reader folds by seq, so collisions silently corrupt.
26
30
  // Journal lines are small; a one-time full read at session bind is cheap.
31
+ //
32
+ // Sharding (2026-11): after a rotation the live journal restarts EMPTY while
33
+ // the archived `parts/<N>/journal.jsonl` hold the earlier seqs. A restart
34
+ // that re-seeds only from the live journal would restart at 1 and collide
35
+ // with every frozen shard. Seed from the max across the live journal AND
36
+ // every archived shard.
27
37
  this._seq = Journal._maxSeqIn(paths.journalPath);
38
+ const shardMax = Journal._maxSeqAcrossShards(paths.journalPath);
39
+ if (shardMax > this._seq) this._seq = shardMax;
40
+ }
41
+
42
+ /** Max journal seq across the session's archived `parts/<N>/` shards (0 when
43
+ * none/unreadable). Sits in journal.js (not shard-manager) to avoid an
44
+ * import cycle — shard-manager's rotate path constructs Journal. */
45
+ static _maxSeqAcrossShards(journalPath) {
46
+ const partsDir = shardPartsDir(dirname(journalPath));
47
+ let names;
48
+ // A non-ENOENT readdir failure must not silently reseed seq at 1 — that
49
+ // collides with every frozen shard's seqs. Report and keep the 0 fallback
50
+ // only for the genuinely-absent parts/ dir.
51
+ try { names = readdirSync(partsDir, { withFileTypes: true }); }
52
+ catch (err) {
53
+ if (err && err.code !== 'ENOENT') reportSwallowed('v2-journal.shard-seq-scan', err);
54
+ return 0;
55
+ }
56
+ let max = 0;
57
+ for (const e of names) {
58
+ if (!e.isDirectory()) continue;
59
+ const n = Journal._maxSeqIn(join(partsDir, e.name, 'journal.jsonl'));
60
+ if (n > max) max = n;
61
+ }
62
+ return max;
28
63
  }
29
64
 
30
65
  static _maxSeqIn(journalPath) {
@@ -7,7 +7,8 @@
7
7
 
8
8
  import { mkdirSync, writeFileSync, renameSync, existsSync, openSync, writeSync, fsyncSync, closeSync, readdirSync, statSync } from 'node:fs';
9
9
  import { readdir as readdirAsync, stat as statAsync } from 'node:fs/promises';
10
- import { join, resolve } from 'node:path';
10
+ import { join, resolve, dirname, basename } from 'node:path';
11
+ import { reportSwallowed } from '../../lib/error-report.js';
11
12
 
12
13
  // The wire-format version this build writes AND the only one it reads.
13
14
  // Stamped into meta.json and the journal sentinel at session creation; the
@@ -215,3 +216,68 @@ export function ensureConvDirSync(paths, convKey) {
215
216
  mkdirSync(dir, { recursive: true });
216
217
  return dir;
217
218
  }
219
+
220
+ // ─── Sharding path ownership ────────────────────────────────────────────────
221
+ // A session dir keeps ALL of its history under ONE folder — copy/move/download/
222
+ // delete of the session dir carries every shard:
223
+ // <project>/sessions/<dirName>/ — active shard (live files at the root)
224
+ // <project>/sessions/<dirName>/parts/<N>/ — frozen shard N (N = 1,2,… oldest→newest)
225
+ // sessions/ enumerators only ever look ONE level down, so the nested parts/
226
+ // subtree is invisible to them. These helpers are the ONLY join sites for
227
+ // parts/ paths (single-owner discipline, same as every other v2 path here).
228
+
229
+ /** The parts/ subdir INSIDE one session dir that holds its frozen shards. */
230
+ export function shardPartsDir(sessionDir) {
231
+ return join(sessionDir, 'parts');
232
+ }
233
+
234
+ /** Frozen shard dir for shard N of a session. */
235
+ export function shardPartDir(sessionDir, n) {
236
+ return join(sessionDir, 'parts', String(n));
237
+ }
238
+
239
+ /**
240
+ * Enumerate frozen shards of one session, oldest first. Each entry
241
+ * { partIndex, dir }. Reads the session's own parts/ subdir.
242
+ * @param {string} sessionDir - absolute path of the ACTIVE session dir
243
+ * @returns {Array<{ partIndex: number, dir: string }>}
244
+ */
245
+ export function listShards(sessionDir) {
246
+ const root = shardPartsDir(sessionDir);
247
+ const out = [];
248
+ let names = [];
249
+ try {
250
+ names = readdirSync(root, { withFileTypes: true });
251
+ } catch (err) {
252
+ if (err && err.code !== 'ENOENT') reportSwallowed('v2-shard.list', err);
253
+ return out; // no parts/ dir → no frozen shards
254
+ }
255
+ for (const e of names) {
256
+ if (!e.isDirectory()) continue;
257
+ const n = Number(e.name);
258
+ if (!Number.isInteger(n) || n < 1) continue;
259
+ out.push({ partIndex: n, dir: join(root, e.name) });
260
+ }
261
+ out.sort((a, b) => a.partIndex - b.partIndex);
262
+ return out;
263
+ }
264
+
265
+ /**
266
+ * Resolve a session-dir-or-shard-dir to the readSession coordinates of its
267
+ * SHARD root. A frozen shard lives INSIDE the session dir at
268
+ * <project>/sessions/<base>/parts/<N>/ — one level deeper than a normal
269
+ * session dir — so the naive projectDir derivation would point readSession at
270
+ * a nonexistent path. Returns null for a normal (non-shard) session dir.
271
+ * @returns {{ base: string, projectDir: string, sessionsDirName: string, sessionId: string } | null}
272
+ */
273
+ export function shardReadRoot(sessionDir) {
274
+ if (basename(dirname(sessionDir)) !== 'parts') return null;
275
+ const base = basename(dirname(dirname(sessionDir))); // <dirName>
276
+ return {
277
+ base,
278
+ projectDir: dirname(dirname(dirname(dirname(sessionDir)))), // <project>
279
+ sessionsDirName: join('sessions', base, 'parts'), // sessions/<base>/parts
280
+ sessionId: basename(sessionDir), // <N>
281
+ };
282
+ }
283
+
@@ -706,6 +706,21 @@ export class V2LiveFeed {
706
706
  if (fresh) this._scheduleRead(fresh);
707
707
  }
708
708
 
709
+ /** Shard rotation (2026-11): the writer archived the dir's live files into
710
+ * `parts/<N>/` and rebuilt a fresh skeleton at the SAME path. The shrink→
711
+ * rebuild heuristic would re-attach with suppressExisting:true and swallow
712
+ * the fresh shard's first post-cut entries as "history". Rebuild WITHOUT
713
+ * suppression: the fresh skeleton is brand-new content to broadcast. */
714
+ reattachAfterShardRotation(dir) {
715
+ const cur = this._sessions.get(dir);
716
+ if (cur) {
717
+ this._closeCursor(cur);
718
+ this._sessions.delete(dir);
719
+ }
720
+ const fresh = this._attach(dir, { suppressExisting: false });
721
+ if (fresh) this._scheduleRead(fresh);
722
+ }
723
+
709
724
  _emitDrained(cur) {
710
725
  cur.synth.sweepDeadlines();
711
726
  const items = cur.synth.drain();
@@ -45,8 +45,14 @@ export function listSessionIds(projectDir, sessionsDirName = 'sessions') {
45
45
  * this build doesn't understand returns `unsupported: true` with EMPTY folds —
46
46
  * callers must refuse it loudly instead of interpreting bytes they can't parse.
47
47
  * A missing version (torn creation) is treated as the current one.
48
+ *
49
+ * opts.beforeSeq (sharding, 2026-11): when set, only journal req/done lines and
50
+ * conversation events with seq < beforeSeq are folded — a frozen `.part<N>`
51
+ * shard is read as "the session up to the cut", never leaking the active
52
+ * shard's later seqs into the window. The maps stay seq-keyed either way.
48
53
  */
49
- export function readSession(projectDir, sessionId, sessionsDirName = 'sessions') {
54
+ export function readSession(projectDir, sessionId, sessionsDirName = 'sessions', opts = {}) {
55
+ const beforeSeq = (typeof opts.beforeSeq === 'number' && opts.beforeSeq > 0) ? opts.beforeSeq : null;
50
56
  const dir = join(projectDir, sessionsDirName, sessionId);
51
57
  let meta = null;
52
58
  try { meta = JSON.parse(readFileSync(join(dir, 'meta.json'), 'utf-8')); } catch { }
@@ -59,6 +65,7 @@ export function readSession(projectDir, sessionId, sessionsDirName = 'sessions')
59
65
  const reqs = new Map();
60
66
  const dones = new Map();
61
67
  for (const line of readJsonlTolerant(join(dir, 'journal.jsonl'))) {
68
+ if (beforeSeq != null && typeof line.seq === 'number' && line.seq >= beforeSeq) continue;
62
69
  if (line.ph === 'req') reqs.set(line.seq, line);
63
70
  else if (line.ph === 'done' && !dones.has(line.seq)) dones.set(line.seq, line);
64
71
  else if (line.ph === 'meta' && typeof line.wireFormat === 'number') {
@@ -77,8 +84,9 @@ export function readSession(projectDir, sessionId, sessionsDirName = 'sessions')
77
84
  if (!/^e\d+\.jsonl$/.test(f)) continue;
78
85
  events.push(...readJsonlTolerant(join(convRoot, entry.name, f)));
79
86
  }
80
- events.sort((a, b) => a.seq - b.seq);
81
- convEvents.set(entry.name, events);
87
+ const filtered = beforeSeq == null ? events : events.filter((ev) => typeof ev.seq === 'number' && ev.seq < beforeSeq);
88
+ filtered.sort((a, b) => a.seq - b.seq);
89
+ convEvents.set(entry.name, filtered);
82
90
  }
83
91
  }
84
92
  return { sessionId, dir, meta, wireFormat, reqs, dones, convEvents };
@@ -19,12 +19,13 @@
19
19
  // does NOT use listV2Sessions (dirSizeSync recursion + prompts head-reads +
20
20
  // full turn counting): this runs on every cold `/events` connection.
21
21
 
22
- import { existsSync, readFileSync, openSync, readSync, closeSync } from 'node:fs';
22
+ import { existsSync, readFileSync, openSync, readSync, closeSync, readdirSync } from 'node:fs';
23
23
  import { join } from 'node:path';
24
24
  import { StringDecoder } from 'node:string_decoder';
25
25
  import { listSessionIds } from './replay.js';
26
- import { isSupportedWireFormat, normalizeSessionCwd } from './layout.js';
26
+ import { isSupportedWireFormat, normalizeSessionCwd, shardPartsDir } from './layout.js';
27
27
  import { isForeignLiveOwned } from './session-owner.js';
28
+ import { reportSwallowed } from '../../lib/error-report.js';
28
29
 
29
30
  /**
30
31
  * Find the on-disk dir NAME of an existing session for `sessionId` (a UUID), or
@@ -125,6 +126,11 @@ function scanJournal(dir, budget, onLine, ioErrorResult = false) {
125
126
  * @returns {boolean}
126
127
  */
127
128
  export function sessionHasMainTurn(dir) {
129
+ // Sharding (2026-11): a session whose live journal was just rotated holds only
130
+ // the sentinel — its main history is archived under parts/. The parts/ archive
131
+ // means the session HAS had main turns, so report true instead of letting the
132
+ // session vanish from latest-main/cold-load selection until the next request.
133
+ if (_hasArchivedParts(dir)) return true;
128
134
  return scanJournal(dir, MAIN_REQ_SCAN_BUDGET, (line) => {
129
135
  // Cheap prefilter before JSON.parse: a main req line carries both.
130
136
  if (!line.includes('"ph":"req"') || !line.includes('"kind":"main"')) return false;
@@ -135,6 +141,21 @@ export function sessionHasMainTurn(dir) {
135
141
  });
136
142
  }
137
143
 
144
+ /** True when the session dir has an archived `parts/<N>/` shard (i.e. it has
145
+ * already lived through at least one rotation's worth of history). */
146
+ function _hasArchivedParts(dir) {
147
+ try {
148
+ for (const e of readdirSync(shardPartsDir(dir), { withFileTypes: true })) {
149
+ if (e.isDirectory() && Number.isInteger(Number(e.name)) && Number(e.name) >= 1) return true;
150
+ }
151
+ } catch (err) {
152
+ // ENOENT = not sharded; anything else is a real read error that must not be
153
+ // misread as "no shards" (a just-rotated session would vanish from lists).
154
+ if (err && err.code !== 'ENOENT') reportSwallowed('v2-session-select.parts-scan', err);
155
+ }
156
+ return false;
157
+ }
158
+
138
159
  /**
139
160
  * Does this session dir have at least one COMPLETED main turn — a `kind:'main'`
140
161
  * request whose `done` line is also present? A streaming scan correlating
@@ -150,6 +171,10 @@ export function sessionHasMainTurn(dir) {
150
171
  * @returns {boolean}
151
172
  */
152
173
  export function sessionHasCompletedMainTurn(dir) {
174
+ // Sharding (2026-11): an archived parts/ shard means the session HAS completed
175
+ // main turns (they were folded before the cut) — report true rather than let a
176
+ // just-rotated session (sentinel-only live journal) drop out of selection.
177
+ if (_hasArchivedParts(dir)) return true;
153
178
  const mainSeqs = new Set(); // seqs of kind:'main' req lines seen so far
154
179
  const doneSeqs = new Set(); // seqs of done lines seen so far
155
180
  return scanJournal(dir, COMPLETED_TURN_SCAN_BUDGET, (line) => {
@@ -186,6 +211,13 @@ export function sessionHasCompletedMainTurn(dir) {
186
211
  * @returns {boolean}
187
212
  */
188
213
  export function sessionHasMainOrTeammateReq(dir) {
214
+ // Sharding (2026-11): right after a rotation the live journal holds only the
215
+ // sentinel — the main/teammate history is archived under `parts/`. A session
216
+ // with a parts/ archive IS main-bearing (it had real turns before the cut);
217
+ // treating it as discardable would vanish it from every list/resume/live
218
+ // surface until the next request lands. Delegates to the same helper the
219
+ // other gates use.
220
+ if (_hasArchivedParts(dir)) return true;
189
221
  // ioErrorResult=true: a transient read error must KEEP the session (treat
190
222
  // as main-bearing) — hiding a real session is the worse failure direction;
191
223
  // a missing journal still returns false (discard is correct there).