cc-viewer 1.9.34 → 1.9.35

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.
@@ -90,7 +90,25 @@ export class V2Writer {
90
90
  // — a crash skips release harmlessly (claim validity is pid liveness).
91
91
  this._claimedDirs = new Set();
92
92
  this._currentSid = null; // last successfully resolved session (fallback routing §8.3)
93
- this._pendingNoSid = []; // requests seen before any sid (cold-start heartbeats).
93
+ // Multi-instance (same-cwd twin): per-instance fallback pointer so a
94
+ // metadata-less request (heartbeat/countTokens) from twin B routes to B's
95
+ // own session, never to the process-global _currentSid (twin A). Keyed by
96
+ // `_ccvInstance` → {sid, project}. Only ever SET on a main-agent turn
97
+ // (teammate/subagent children inherit the parent's x-ccv-instance but run
98
+ // their own sid — letting them set this would hijack the parent's pointer).
99
+ this._currentSidByInstance = new Map(); // instKey → {sid, project}
100
+ this._pendingNoSid = []; // legacy (no-instance) requests seen before any sid.
101
+ // Per-instance cold-start hold buckets: instKeyOr'' → {project, items:[]}.
102
+ // Kept separate from _pendingNoSid so a twin's held heartbeats flush only on
103
+ // that twin's first sid-bearing request, not on the other twin's.
104
+ this._pendingNoSidByInstance = new Map();
105
+ // forceNew (2026-11): instanceKeys of RETIRED generations (an SDK forceNew teardown).
106
+ // A retired instance's late traffic (a draining child's heartbeat/completion) may still
107
+ // write into its OWN old dir (history stays consistent) but must NEVER move the live
108
+ // pointers (`_currentSid` / `_currentSidByInstance` / `_onSessionResolved`) — else the
109
+ // fresh generation's bound cold-load flips back to the old conversation. Append-only;
110
+ // random keys never collide with a future generation. Cleared only by resetSessions().
111
+ this._retiredInstances = new Set();
94
112
  // Contract with the caller: originalMessages held here must be a reference
95
113
  // the caller never MUTATES (the interceptor's original array is only ever
96
114
  // REASSIGNED away from body.messages, never mutated in place — safe).
@@ -114,10 +132,12 @@ export class V2Writer {
114
132
  this._adopted = new Set();
115
133
  // In-terminal /resume switch (SessionStart hook, source:'resume'): the
116
134
  // next MAIN request must be re-routed to the resumed conversation's dir.
117
- // Per-project (was a single value): keyed by sanitized project, so a scoped
118
- // reset clears only the switched-away project's pending switch. Value:
119
- // {transcriptUuid, hookSid}; consumed one-shot on the next main request.
120
- this._pendingResumeSwitch = new Map();
135
+ // Two-level: project → instance. The instance level (R1) stops a same-cwd
136
+ // twin from consuming the OTHER twin's armed switch; '' is the legacy
137
+ // (no-instance) slot, preserving the old per-project behavior for producers
138
+ // that carry no x-ccv-instance. Value: {transcriptUuid, hookSid}; consumed
139
+ // one-shot on the matching instance's next main request.
140
+ this._pendingResumeSwitch = new Map(); // projSan → Map<instKeyOr'', {transcriptUuid, hookSid}>
121
141
  }
122
142
 
123
143
  /** P2: true once any session's FIRST main wire already carried assistant
@@ -190,6 +210,11 @@ export class V2Writer {
190
210
  // live window's dir — it just doesn't stamp ownership of its own.
191
211
  const prev = latestMainSession(projectDir, { skipForeignLive: true });
192
212
  if (!prev || !prev.sessionId) return null;
213
+ // Same-process twin guard: the pid-level skipForeignLive above is blind to a
214
+ // same-cwd twin of THIS process (shared pid). A `-c`/history-replay on one
215
+ // twin must never adopt the OTHER twin's live dir (two Journals, one file).
216
+ if (this._isBoundToOtherInstance(basename(prev.dir), project,
217
+ (entry && typeof entry._ccvInstance === 'string' && entry._ccvInstance) ? entry._ccvInstance : null)) return null;
193
218
  if (this._claimsEnabled()) {
194
219
  if (!acquireSessionClaim(prev.dir).ok) return null;
195
220
  // Record immediately (not only in _session): a throw between here and
@@ -199,6 +224,27 @@ export class V2Writer {
199
224
  return { dirName: basename(prev.dir), identityUUID: prev.sessionId };
200
225
  }
201
226
 
227
+ /** Per-instance fallback pointer for metadata-less routing (R3): the sid a
228
+ * twin's heartbeat/countTokens should resolve to. Returns null when the
229
+ * instance has not yet run a main turn — in that case the caller must NOT
230
+ * fall back to the process-global `_currentSid` (that would write twin B's
231
+ * cold-start traffic into twin A's dir). */
232
+ _currentSidFor(instKey) {
233
+ if (!instKey) return this._currentSid;
234
+ const cur = this._currentSidByInstance.get(instKey);
235
+ return cur ? cur.sid : null;
236
+ }
237
+
238
+ /** The sid an instance is CURRENTLY bound to (main-turn routing pointer), or null.
239
+ * Read-only; used by the resume twin-ownership guard to tell "this instance owns the
240
+ * conversation it is actively writing" apart from "this instance merely shares a
241
+ * deterministic key with a dead prior author". */
242
+ currentSidForInstance(instKey) {
243
+ if (typeof instKey !== 'string' || !instKey) return null;
244
+ const cur = this._currentSidByInstance.get(instKey);
245
+ return cur ? cur.sid : null;
246
+ }
247
+
202
248
  /** In-terminal /resume signal (interceptor.markSessionStart → here): arm a
203
249
  * one-shot routing switch. `transcriptUuid` is the resumed conversation's
204
250
  * stable identity (transcript basename); `hookSid` is the fresh session
@@ -206,14 +252,19 @@ export class V2Writer {
206
252
  * conversation was never recorded by ccv (it must not be the old wire sid:
207
253
  * `<ts>_<oldSid>` would be re-resolved back to the OLD dir by
208
254
  * resolveSessionDirName). Last-wins across repeated /resume picks. */
209
- beginResumeSwitch({ transcriptUuid, hookSid, project } = {}) {
255
+ beginResumeSwitch({ transcriptUuid, hookSid, project, instanceKey = null } = {}) {
210
256
  try {
211
257
  if (!transcriptUuid || typeof transcriptUuid !== 'string') return;
212
258
  // Keyed by the project the resumed conversation belongs to (defaults to the
213
259
  // currently-bound project — markSessionStart's guard already ensures the
214
260
  // hook's cwd matches it). Per-project so a scoped reset clears only that one.
215
261
  const key = sanitizePathComponent(project || this._projectFn() || '');
216
- this._pendingResumeSwitch.set(key, {
262
+ const inst = (typeof instanceKey === 'string' && /^ccv-[0-9a-f]+$/.test(instanceKey)) ? instanceKey : '';
263
+ let bucket = this._pendingResumeSwitch.get(key);
264
+ if (!bucket) { bucket = new Map(); this._pendingResumeSwitch.set(key, bucket); }
265
+ // Last-wins across repeated /resume picks, but ONLY within the same
266
+ // (project, instance) — a twin must not clobber its sibling's armed switch.
267
+ bucket.set(inst, {
217
268
  transcriptUuid,
218
269
  hookSid: (typeof hookSid === 'string' && hookSid) ? hookSid : null,
219
270
  });
@@ -222,6 +273,33 @@ export class V2Writer {
222
273
  }
223
274
  }
224
275
 
276
+ /** Same-process live-bind guard (R1/R7): is `dirName` currently bound in THIS
277
+ * process's `_sessions` to a DIFFERENT instance? The pid-level `owner.lock`
278
+ * guard (`isForeignLiveOwned`) is blind to same-cwd twins — both share this
279
+ * process's pid, so a twin adopting the other's live dir would produce two
280
+ * Journal objects writing the same file with independently-seeded seqs
281
+ * (certain corruption). Used by the resume-switch and `-c` adoption paths to
282
+ * fall back to fork semantics instead. */
283
+ _isBoundToOtherInstance(dirName, project, instKey) {
284
+ const projectDir = join(this._logDir, sanitizePathComponent(project));
285
+ const targetDir = join(projectDir, this._sessionsDirName, dirName);
286
+ for (const s of this._sessions.values()) {
287
+ if (s && s.paths && s.paths.dir === targetDir) {
288
+ const owner = s._instanceKey || null;
289
+ // Same identity → not a conflict (a twin re-joining its OWN dir).
290
+ if (owner === instKey && owner !== null) return false;
291
+ // Owner is a known twin but the caller is a DIFFERENT instance, OR the
292
+ // caller carries no instance identity while the dir is owned by one
293
+ // (a legacy producer must not re-bind a twin's dir — that is the very
294
+ // "two Journals, one file" this guard exists to prevent). Both conflict.
295
+ // An unattributed legacy binding (owner null) with an unattributed caller
296
+ // (instKey null) is allowed to preserve legacy self re-join semantics.
297
+ return !(owner === null && instKey === null);
298
+ }
299
+ }
300
+ return false;
301
+ }
302
+
225
303
  /**
226
304
  * Consume the pending /resume switch for the arriving MAIN request: pick
227
305
  * the target dir, take its claim, drop the old same-sid binding, and return
@@ -238,10 +316,13 @@ export class V2Writer {
238
316
  * it, not by the incoming `sid`
239
317
  * @returns {{dirName:string, identityUUID:string}}
240
318
  */
241
- _resolveResumeSwitch(sid, project, prevSid = null) {
319
+ _resolveResumeSwitch(sid, project, prevSid = null, instanceKey = null) {
242
320
  const key = this._projKey(project);
243
- const sw = this._pendingResumeSwitch.get(key);
244
- this._pendingResumeSwitch.delete(key); // one-shot
321
+ const bucket = this._pendingResumeSwitch.get(key);
322
+ const inst = (typeof instanceKey === 'string' && instanceKey) ? instanceKey : '';
323
+ const sw = bucket ? bucket.get(inst) : null;
324
+ if (bucket) { bucket.delete(inst); if (bucket.size === 0) this._pendingResumeSwitch.delete(key); } // one-shot
325
+ if (!sw) return null;
245
326
  const projectDir = join(this._logDir, sanitizePathComponent(project));
246
327
  let dirName = resolveSessionDirName(projectDir, sw.transcriptUuid, this._sessionsDirName);
247
328
  let identity = sw.transcriptUuid;
@@ -251,9 +332,13 @@ export class V2Writer {
251
332
  // unconditional skipForeignLive): even a non-claiming writer must never
252
333
  // re-bind into a dir another live window is writing. The acquire below
253
334
  // additionally arbitrates for claiming writers.
335
+ // Same-process twin guard: the pid-level check above is blind to two
336
+ // same-cwd instances of THIS process (shared pid) — also refuse a dir
337
+ // currently bound to a different instance here (manual /resume in a twin).
254
338
  if (isForeignLiveOwned(targetDir)
339
+ || this._isBoundToOtherInstance(dirName, project, inst)
255
340
  || (this._claimsEnabled() && !acquireSessionClaim(targetDir).ok)) {
256
- dirName = null; // live foreign owner — never share its journal
341
+ dirName = null; // live foreign owner / live twin — never share its journal
257
342
  }
258
343
  }
259
344
  if (dirName) {
@@ -459,13 +544,24 @@ export class V2Writer {
459
544
  if (!this._diskOk()) return null;
460
545
 
461
546
  const parsed = parseUserId(entry.body && entry.body.metadata && entry.body.metadata.user_id);
547
+ // Instance this request belongs to (same-cwd twin routing). Extracted once
548
+ // at the top so the resume-switch/adoption/metadata-less paths all agree.
549
+ const instKey = (typeof entry._ccvInstance === 'string' && entry._ccvInstance) ? entry._ccvInstance : null;
550
+ // forceNew (2026-11): a RETIRED generation (SDK forceNew teardown) may still be
551
+ // draining — its trailing completion should land in its OWN old dir, but it must
552
+ // never move `_currentSid` / `_currentSidByInstance` / `_onSessionResolved`, and its
553
+ // metadata-less traffic must not be routed or held (it would misroute into the fresh
554
+ // generation's dir). Read once; gates below.
555
+ const retired = !!(instKey && this._retiredInstances.has(instKey));
462
556
  // Captured BEFORE the reassignment below: when a /resume switch arrives
463
557
  // on a FRESH wire sid, the departing conversation's binding is keyed by
464
558
  // this previous sid, not the incoming one (review P2 — the fresh-sid
465
559
  // variant would otherwise leak the old dir's claim + map entry until
466
560
  // process exit, blocking other windows from resuming that ended
467
- // conversation).
468
- const prevSid = this._currentSid;
561
+ // conversation). Per-instance (R3): a twin must depart from ITS OWN
562
+ // previous sid, not the process-global last-writer — otherwise twin A's
563
+ // /resume would resolve against twin B's binding and release B's claim.
564
+ const prevSid = this._currentSidFor(instKey);
469
565
  let sid;
470
566
  if (parsed) {
471
567
  sid = parsed.sessionId;
@@ -484,9 +580,20 @@ export class V2Writer {
484
580
  const entryProject = (typeof entry._resumeProject === 'string' && entry._resumeProject)
485
581
  ? entry._resumeProject
486
582
  : this._projectFn();
487
- if (entryProject && entryProject === this._projectFn()) {
583
+ if (entryProject && entryProject === this._projectFn() && !retired) {
488
584
  this._currentSid = sid;
489
585
  }
586
+ // Per-instance pointer (R3): pin the sid for THIS instance so its later
587
+ // metadata-less requests route back here. MAIN-AGENT GATE mirrors the
588
+ // `_onSessionResolved` gate below: only the main interactive claude's own
589
+ // turn sets it. A teammate/subagent child INHERITS the parent's
590
+ // `x-ccv-instance` but runs its OWN conversation/sid — without this gate
591
+ // it would overwrite the parent instance's pointer with the teammate's
592
+ // sid, misrouting the parent's heartbeats into the teammate's session.
593
+ const isMainAgentTurn = entry.mainAgent === true && !entry.teammate && !entry.isHeartbeat && !entry.isCountTokens;
594
+ if (instKey && isMainAgentTurn && !retired) {
595
+ this._currentSidByInstance.set(instKey, { sid, project: entryProject });
596
+ }
490
597
  // Feed the PTY sid index: this request's owning project just resolved a
491
598
  // concrete sessionId, so the PTY serving that project can be addressed by
492
599
  // sid. Multi-instance (2026-10-06): also forward the self-reported instanceKey
@@ -499,11 +606,34 @@ export class V2Writer {
499
606
  // its OWN conversation/sid — without this gate it would overwrite the parent record's
500
607
  // sessionId with the teammate's sid, mis-pinning the instance. Teammate / heartbeat /
501
608
  // count_tokens requests are skipped.
502
- const isMainAgentTurn = entry.mainAgent === true && !entry.teammate && !entry.isHeartbeat && !entry.isCountTokens;
503
- if (this._onSessionResolved && entryProject && isMainAgentTurn) {
504
- const instKey = (typeof entry._ccvInstance === 'string' && entry._ccvInstance) ? entry._ccvInstance : null;
609
+ if (this._onSessionResolved && entryProject && isMainAgentTurn && !retired) {
505
610
  try { this._onSessionResolved(sid, entryProject, instKey); } catch (err) { reportSwallowed('v2-write.session-resolved', err); }
506
611
  }
612
+ } else if (instKey) {
613
+ // forceNew (2026-11): a retired generation's metadata-less traffic is dropped, not
614
+ // routed (its pointer is gone) nor held (a held heartbeat would later flush into the
615
+ // NEW generation's dir). Returning null writes nothing — clean for a dead generation.
616
+ if (retired) return null;
617
+ // Metadata-less request from a known instance: route to that instance's
618
+ // own session. If it has not run a main turn yet, there is NO pointer —
619
+ // deliberately do NOT fall back to the process-global `_currentSid`,
620
+ // which would write twin B's cold-start heartbeat into twin A's dir.
621
+ const own = this._currentSidByInstance.get(instKey);
622
+ if (own) {
623
+ sid = own.sid;
624
+ } else {
625
+ let bucket = this._pendingNoSidByInstance.get(instKey);
626
+ if (!bucket) { bucket = { project, items: [] }; this._pendingNoSidByInstance.set(instKey, bucket); }
627
+ if (bucket.items.length < 64) {
628
+ bucket.items.push({ entry, originalMessages, rid: entry.requestId || null });
629
+ return null;
630
+ }
631
+ // Bucket overflow safety valve: mint a throwaway noid sid for THIS
632
+ // request only. Deliberately NOT written into _currentSidByInstance —
633
+ // this branch may be a heartbeat/teammate (not a gated main turn), and
634
+ // a noid must never become the instance's durable pointer.
635
+ sid = `noid-${process.pid}-${Date.now()}`;
636
+ }
507
637
  } else if (this._currentSid) {
508
638
  sid = this._currentSid; // §8.3 fallback: route metadata-less requests to the active session
509
639
  } else {
@@ -532,7 +662,9 @@ export class V2Writer {
532
662
  // probes and heartbeats wear main-agent body shapes but are not the
533
663
  // user's resumed turn — consuming on them would re-bind too early
534
664
  // with the same result, but keep the gate strict for clarity).
535
- if (this._pendingResumeSwitch.has(this._projKey(project)) && entry.mainAgent
665
+ // Instance-keyed (R1): a twin consumes only ITS OWN armed switch.
666
+ const rsBucket = this._pendingResumeSwitch.get(this._projKey(project));
667
+ if (rsBucket && rsBucket.has(instKey || '') && entry.mainAgent
536
668
  && !entry.isCountTokens && !entry.isHeartbeat) {
537
669
  // Locally guarded (review P2): the switch resolution does dir-scan
538
670
  // fs work (resolveSessionDirName → readdirSync) whose residual
@@ -540,7 +672,7 @@ export class V2Writer {
540
672
  // outer catch and drop THIS request entirely — the resumed
541
673
  // conversation's first main turn. A failure must degrade to normal
542
674
  // routing (recorded in the current dir), never to a lost entry.
543
- try { adoptTarget = this._resolveResumeSwitch(sid, project, prevSid); }
675
+ try { adoptTarget = this._resolveResumeSwitch(sid, project, prevSid, instKey); }
544
676
  catch (err) { reportSwallowed('v2-write.resume-switch-apply', err); }
545
677
  }
546
678
  if (!adoptTarget) {
@@ -608,9 +740,16 @@ export class V2Writer {
608
740
 
609
741
  // Flush requests that arrived before the first sid (they belong here).
610
742
  // Their handles are parked in _lateHandles so a completion that arrives
611
- // after the flush still gets its done line (folded by rid).
612
- if (this._pendingNoSid.length > 0) {
743
+ // after the flush still gets its done line (folded by rid). R3: flush the
744
+ // legacy no-instance bucket AND only THIS request's instance bucket — a
745
+ // twin's held heartbeats must never be flushed into the other twin's dir.
746
+ const instBucket = instKey ? this._pendingNoSidByInstance.get(instKey) : null;
747
+ if (this._pendingNoSid.length > 0 || (instBucket && instBucket.items.length > 0)) {
613
748
  const pending = this._pendingNoSid.splice(0);
749
+ if (instBucket) {
750
+ pending.push(...instBucket.items);
751
+ this._pendingNoSidByInstance.delete(instKey);
752
+ }
614
753
  for (const p of pending) {
615
754
  const pseq = this._ingestInto(s, sid, p.entry, p.originalMessages);
616
755
  const prid = p.rid; // captured at hold time — the seam may have deleted entry.requestId by now
@@ -1041,6 +1180,8 @@ export class V2Writer {
1041
1180
  s.resolver.reset();
1042
1181
  }
1043
1182
  this._currentSid = null;
1183
+ this._currentSidByInstance.clear();
1184
+ this._pendingNoSidByInstance.clear();
1044
1185
  } catch (err) {
1045
1186
  reportSwallowed('v2-write.reset', err);
1046
1187
  }
@@ -1085,14 +1226,21 @@ export class V2Writer {
1085
1226
  }
1086
1227
  }
1087
1228
  this._pendingNoSid.length = 0;
1229
+ this._pendingNoSidByInstance.clear();
1088
1230
  this._lateHandles.clear();
1089
1231
  // _currentSid only clears when it pointed at the dropped project — the
1090
1232
  // background project's live "current" pointer survives a scoped reset.
1091
1233
  if (matchAll) {
1092
1234
  this._currentSid = null;
1235
+ this._currentSidByInstance.clear();
1093
1236
  } else {
1094
1237
  const cur = this._currentSid ? this._sessions.get(this._currentSid) : null;
1095
1238
  if (this._currentSid && !cur) this._currentSid = null;
1239
+ // Drop only the switched-away project's per-instance pointers (mirrors
1240
+ // the _currentSid rule): a background project's twin keeps its pointer.
1241
+ for (const [k, v] of [...this._currentSidByInstance]) {
1242
+ if (sanitizePathComponent(v.project || '') === targetSan) this._currentSidByInstance.delete(k);
1243
+ }
1096
1244
  }
1097
1245
  // `-c` adoption latch + pending /resume switch, both per-project now: a
1098
1246
  // scoped reset clears only the switched-away project's latch (a background
@@ -1100,6 +1248,7 @@ export class V2Writer {
1100
1248
  if (matchAll) {
1101
1249
  this._adopted.clear();
1102
1250
  this._pendingResumeSwitch.clear();
1251
+ this._retiredInstances.clear(); // full reset: no retired generation survives a workspace wipe
1103
1252
  } else {
1104
1253
  this._adopted.delete(targetSan);
1105
1254
  this._pendingResumeSwitch.delete(targetSan);
@@ -1109,6 +1258,85 @@ export class V2Writer {
1109
1258
  }
1110
1259
  }
1111
1260
 
1261
+ /** Same-project forceNew relaunch (R2): a NEW claude instance is being spawned
1262
+ * in the SAME cwd as a live twin. The twin keeps its session bindings
1263
+ * (`_sessions`) and owner.lock claims (`_claimedDirs`) — releasing them would
1264
+ * expose its live dirs to the sibling's cold-load/adoption. Only
1265
+ * launch-boundary state that could hijack or misroute the FRESH twin is
1266
+ * cleared: held pre-sid traffic, late handles, and any armed /resume switch
1267
+ * (which belongs to the outgoing launch context, not the new twin). The
1268
+ * `-c` adoption latch is intentionally LEFT SET — forceNew never adopts an
1269
+ * old folder, and clearing it would wrongly re-enable adoption for the
1270
+ * still-live twin. Same-process mis-adoption is prevented by the
1271
+ * `_isBoundToOtherInstance` guard in _resolveAdoption/_resolveResumeSwitch,
1272
+ * not by poisoning the project latch. */
1273
+ resetForLiveRelaunch(targetProject) {
1274
+ try {
1275
+ const key = this._projKey(targetProject);
1276
+ this._pendingNoSid.length = 0;
1277
+ this._pendingNoSidByInstance.clear();
1278
+ // Late handles are _openHandle-counted when parked; a bare clear() would
1279
+ // leak their in-flight count and wedge shard rotation for the surviving
1280
+ // twin's session (resetSessions gets away with it only because it also
1281
+ // drops the sessions). Close each without re-arming rotation first.
1282
+ for (const h of this._lateHandles.values()) this._closeHandle(h, { rotate: false });
1283
+ this._lateHandles.clear();
1284
+ this._pendingResumeSwitch.delete(key);
1285
+ // Clear the process-global current pointer only when it pointed at this
1286
+ // project (mirrors the scoped-reset terminal state), so the fresh twin's
1287
+ // pre-sid traffic cannot follow it into the OLD twin's dir. The
1288
+ // per-instance pointers are kept — they are how the still-live twin's own
1289
+ // metadata-less traffic keeps routing to its own dir.
1290
+ if (this._currentSid) {
1291
+ const cur = this._sessions.get(this._currentSid);
1292
+ if (!cur || this._projKey(cur.project || '') === key) this._currentSid = null;
1293
+ }
1294
+ // DELIBERATELY NOT touched: _sessions, _claimedDirs, _adopted,
1295
+ // _currentSidByInstance.
1296
+ } catch (err) {
1297
+ reportSwallowed('v2-write.reset-relaunch', err);
1298
+ }
1299
+ }
1300
+
1301
+ /**
1302
+ * Retire a CLOSED random-key SDK session (2026-11). Marks the instanceKey retired so
1303
+ * its late traffic stops moving the live pointers, and clears the per-instance routing
1304
+ * state the closed session held.
1305
+ *
1306
+ * Call ONLY from the explicit SDK close path (routes/resume.js, wasFreshKey===true) —
1307
+ * a random per-generation key is never re-created, so retirement is permanent and safe.
1308
+ * Never from a launch or initForWorkspace/resetForLiveRelaunch: a same-cwd sibling stays
1309
+ * LIVE and depends on its per-instance pointers surviving a relaunch.
1310
+ */
1311
+ retireInstance(instKey) {
1312
+ if (typeof instKey !== 'string' || !/^ccv-[0-9a-f]+$/.test(instKey)) return;
1313
+ this._retiredInstances.add(instKey);
1314
+ // Cap the append-only set (random keys never collide with a future generation).
1315
+ if (this._retiredInstances.size > 64) this._retiredInstances.delete(this._retiredInstances.values().next().value);
1316
+ // The retired instance's own routing state: its metadata-less traffic must not route
1317
+ // to its old sid, and any held cold-start bucket must never flush into the new dir.
1318
+ const prior = this._currentSidByInstance.get(instKey);
1319
+ this._currentSidByInstance.delete(instKey);
1320
+ this._pendingNoSidByInstance.delete(instKey);
1321
+ if (prior && this._currentSid === prior.sid) this._currentSid = null;
1322
+ }
1323
+
1324
+ /**
1325
+ * Release a CLOSED instance's per-instance routing state WITHOUT retiring the key
1326
+ * (2026-11, same-cwd sibling close). Unlike retireInstance this does NOT add the key to
1327
+ * `_retiredInstances`: a DETERMINISTIC cwd-derived key is re-created by a later normal
1328
+ * relaunch, so retiring it would permanently gate the legitimate rebuilt session. Only
1329
+ * clears the closed instance's per-instance pointer + cold-start bucket so its draining
1330
+ * traffic stops moving the live pointers. Used by the SDK close path for wasFreshKey=false.
1331
+ */
1332
+ releaseInstance(instKey) {
1333
+ if (typeof instKey !== 'string' || !/^ccv-[0-9a-f]+$/.test(instKey)) return;
1334
+ const prior = this._currentSidByInstance.get(instKey);
1335
+ this._currentSidByInstance.delete(instKey);
1336
+ this._pendingNoSidByInstance.delete(instKey);
1337
+ if (prior && this._currentSid === prior.sid) this._currentSid = null;
1338
+ }
1339
+
1112
1340
  /** Flush pending queue writes (tests / graceful shutdown). */
1113
1341
  async flush() {
1114
1342
  await this._queue.flush();
@@ -101,6 +101,14 @@ function _getOrInit(key) {
101
101
  batchBuffer: '',
102
102
  batchScheduled: false,
103
103
  sessionId: null, // claude session uuid once its first turn mints one (fed via setPtySessionId)
104
+ // forceNew "brand-new conversation" launch mark (2026-11): set only by
105
+ // ensurePtyForCwd({forceNew:true}) (file explorer "New Workspace (Session)"
106
+ // on the current root). routes/events.js reads it to suppress the same-cwd
107
+ // cold-load fallback while this instance has no main turn of its own.
108
+ // Cleared in setPtySessionIdForInstance (first main turn binds a session);
109
+ // NEVER reset in _spawnClaudeImpl/_respawnInto (a self-heal respawn is still
110
+ // the same fresh instance).
111
+ freshLaunch: false,
104
112
  };
105
113
  ptys.set(key, s);
106
114
  }
@@ -341,7 +349,12 @@ export async function spawnClaude(proxyPort, cwd, extraArgs = [], claudePath = n
341
349
  while (_spawnInflight.has(key)) { try { await _spawnInflight.get(key); } catch { } }
342
350
  const p = _spawnClaudeImpl(key, proxyPort, cwd, extraArgs, claudePath, isNpmVersion, serverPort, serverProtocol, internalToken);
343
351
  _spawnInflight.set(key, p);
344
- try { return await p; } finally { if (_spawnInflight.get(key) === p) _spawnInflight.delete(key); }
352
+ try {
353
+ // Resolve with the record's OWN instanceKey (never activePtyKey — a concurrent spawn
354
+ // for another cwd can re-point the shared pointer before this spawn settles).
355
+ const ptyProcess = await p;
356
+ return { key, ptyProcess };
357
+ } finally { if (_spawnInflight.get(key) === p) _spawnInflight.delete(key); }
345
358
  }
346
359
 
347
360
  // Self-heal respawn: re-run claude in the SAME record (same instanceKey) after a boot crash
@@ -477,6 +490,11 @@ async function _spawnClaudeImpl(key, proxyPort, cwd, extraArgs = [], claudePath
477
490
  env.CCV_EDITOR_PORT = String(serverPort);
478
491
  env.CCVIEWER_PORT = String(serverPort); // For ask-hook bridge
479
492
  env.CCVIEWER_PROTOCOL = serverProtocol; // For ask/perm-bridge (http vs https)
493
+ // Per-spawn instance key for the SessionStart hook bridge (R1): lets the
494
+ // in-terminal /resume signal be routed to THIS exact same-cwd instance
495
+ // instead of any sibling twin sharing the project. `key` is the record's
496
+ // instanceKey, stable across self-heal respawns of the same record.
497
+ env.CCVIEWER_INSTANCE_KEY = key;
480
498
  if (internalToken) {
481
499
  // Anti-CSRF token for bridge → server calls (round-3 P1). Same shared
482
500
  // secret across ask / perm / turn-end bridges so server can route-check
@@ -971,6 +989,7 @@ async function _spawnShellImpl(key) {
971
989
  delete shellEnv.CCV_EDITOR_PORT;
972
990
  delete shellEnv.CCVIEWER_PROTOCOL;
973
991
  delete shellEnv.CCVIEWER_INTERNAL_TOKEN;
992
+ delete shellEnv.CCVIEWER_INSTANCE_KEY; // a hand-typed claude is not this record's instance
974
993
  // Also disable the mouse for claude typed by hand in the interactive shell; same reason
975
994
  // as spawnClaude.
976
995
  shellEnv.CLAUDE_CODE_DISABLE_MOUSE ??= '1';
@@ -1239,6 +1258,12 @@ export function setPtySessionIdForInstance(instanceKey, sessionId) {
1239
1258
  if (s.sessionId && s.sessionId !== sessionId) sidToKey.delete(s.sessionId);
1240
1259
  s.sessionId = sessionId;
1241
1260
  sidToKey.set(sessionId, instanceKey);
1261
+ // forceNew lifecycle (2026-11): the mark's job ends once this instance owns a real
1262
+ // session. Binding a session id means a main turn landed (v2-writer only calls this
1263
+ // on a main-turn gate), so the instance now has its own conversation and the cold-load
1264
+ // fallback suppression must lift — a later chip-click / reload serves that conversation,
1265
+ // and a /resume adopted into this instance stops being hidden behind an empty view.
1266
+ s.freshLaunch = false;
1242
1267
  return true;
1243
1268
  }
1244
1269
 
@@ -1447,11 +1472,11 @@ export function attachPtyFor({ cwd, project, instanceKey } = {}) {
1447
1472
  }
1448
1473
 
1449
1474
  /**
1450
- * parallel-project chips. Returns [{ key, instanceKey, cwd, ptyKind, pid, isActive }] for
1475
+ * parallel-project chips. Returns [{ key, instanceKey, cwd, ptyKind, pid, isActive, freshLaunch }] for
1451
1476
  * records whose process is still running (ptyProcess != null); exited-but-
1452
1477
  * unreaped records are excluded. `key`/`instanceKey` are the opaque per-spawn instanceKey
1453
1478
  * the Map is keyed on; `cwd` is the record's real working dir (never the key). `isActive`
1454
- * marks the PTY the main view is attached to. Read-only.
1479
+ * marks the PTY the main view is attached to. `freshLaunch` is the forceNew mark. Read-only.
1455
1480
  */
1456
1481
  export function listLivePtys() {
1457
1482
  const out = [];
@@ -1464,6 +1489,10 @@ export function listLivePtys() {
1464
1489
  ptyKind: s.ptyKind || null,
1465
1490
  pid: s.ptyProcess.pid,
1466
1491
  isActive: key === activePtyKey,
1492
+ // forceNew mark (2026-11): routes/events.js reads this to suppress the same-cwd
1493
+ // cold-load fallback for a deliberately brand-new instance. Additive; consumers
1494
+ // that build their own rows (resume.js) are unaffected.
1495
+ freshLaunch: s.freshLaunch === true,
1467
1496
  });
1468
1497
  }
1469
1498
  return out;
@@ -1644,7 +1673,7 @@ export function getPtyBootState() {
1644
1673
  *
1645
1674
  * @returns {Promise<{ spawned:boolean, attached:boolean, key:string|null, running:boolean }>}
1646
1675
  */
1647
- export async function ensurePtyForCwd({ cwd, proxyPort, extraArgs = [], claudePath = null, isNpmVersion = false, serverPort = null, serverProtocol = 'http', internalToken = null } = {}) {
1676
+ export async function ensurePtyForCwd({ cwd, proxyPort, extraArgs = [], claudePath = null, isNpmVersion = false, serverPort = null, serverProtocol = 'http', internalToken = null, forceNew = false } = {}) {
1648
1677
  if (typeof cwd !== 'string' || !cwd) return { spawned: false, attached: false, key: null, running: false };
1649
1678
  // Serialize concurrent launches for the SAME cwd (review P1 / TOCTOU): the live-scan below
1650
1679
  // + `spawnClaude` are two separate steps, so two simultaneous launches of one cwd could both
@@ -1653,19 +1682,36 @@ export async function ensurePtyForCwd({ cwd, proxyPort, extraArgs = [], claudePa
1653
1682
  // in-flight promise here — the second caller waits for the first, then re-scans and finds
1654
1683
  // the now-live record (attaching instead of spawning).
1655
1684
  while (_cwdLaunchInflight.has(cwd)) { try { await _cwdLaunchInflight.get(cwd); } catch { } }
1656
- // Prefer an already-LIVE claude for this exact cwd (not a shell). Re-attaching rather than
1657
- // re-spawning preserves the running session and avoids a duplicate process.
1658
- for (const [k, s] of ptys) {
1659
- if (s && s.cwd === cwd && s.ptyProcess && s.ptyKind === 'claude') {
1660
- activePtyKey = k; // attach the main view to the live record
1661
- return { spawned: false, attached: true, key: k, running: true };
1685
+ // forceNew (context menu "New Workspace (Session)" on the CURRENT root): a second
1686
+ // concurrent claude in the same cwd is the whole point — skip the reuse scan. The per-cwd
1687
+ // in-flight slot is still taken, so a concurrent normal launch cannot re-attach mid-spawn.
1688
+ if (!forceNew) {
1689
+ // Prefer an already-LIVE claude for this exact cwd (not a shell). Re-attaching rather than
1690
+ // re-spawning preserves the running session and avoids a duplicate process.
1691
+ for (const [k, s] of ptys) {
1692
+ if (s && s.cwd === cwd && s.ptyProcess && s.ptyKind === 'claude') {
1693
+ activePtyKey = k; // attach the main view to the live record
1694
+ return { spawned: false, attached: true, key: k, running: true };
1695
+ }
1662
1696
  }
1663
1697
  }
1664
1698
  const p = spawnClaude(proxyPort, cwd, extraArgs, claudePath, isNpmVersion, serverPort, serverProtocol, internalToken);
1665
1699
  _cwdLaunchInflight.set(cwd, p);
1666
1700
  try {
1667
- await p;
1668
- return { spawned: true, attached: false, key: activePtyKey, running: true };
1701
+ const { key } = await p; // the SPAWNED record's key — not activePtyKey (race-safe)
1702
+ // forceNew: this record's conversation starts EMPTY by design. Mark it (the record
1703
+ // exists: _spawnClaudeImpl set ptyProcess before resolving) so every later
1704
+ // `?project&instance` cold-load — including a reload or another tab — suppresses the
1705
+ // cross-instance fallback that would otherwise serve the live twin's OLD conversation.
1706
+ // The client only learns this key from the launch HTTP response (sent after this
1707
+ // resolves), so the mark is always in place before any reader. Gate on forceNew: the
1708
+ // `await p` above is shared with the non-forceNew cold-launch path (the reuse scan
1709
+ // found nothing), and marking that would wrongly blank a normal re-opened instance.
1710
+ if (forceNew) {
1711
+ const rec = ptys.get(key);
1712
+ if (rec) rec.freshLaunch = true;
1713
+ }
1714
+ return { spawned: true, attached: false, key, running: true };
1669
1715
  } finally {
1670
1716
  if (_cwdLaunchInflight.get(cwd) === p) _cwdLaunchInflight.delete(cwd);
1671
1717
  }
@@ -427,14 +427,23 @@ export async function serveEventStream(sink, params, deps) {
427
427
  // Instance dead / no live record / lookup failure → '' → no cwd filter
428
428
  // (conservative, identical to today's whole-pool fallback; never mis-excludes history).
429
429
  let targetCwd = '';
430
+ // forceNew (2026-11): a brand-new instance ("New Workspace (Session)") carries the
431
+ // `freshLaunch` mark — on its PTY record (PTY mode) or its SDK session row (SDK mode,
432
+ // projected through listSdkSessions). Suppress the same-cwd cold-load fallback for it
433
+ // so the view starts EMPTY instead of serving the old conversation. Server-authoritative,
434
+ // so it holds for a reload or a second tab, not just the launching client. Lookup
435
+ // failure / dead record → false → today's fallback (sid-not-found handles a dead one).
436
+ let suppressFallback = false;
430
437
  if (instanceParam) {
431
438
  try {
432
- const rec = listLivePtys().find((p) => p && p.instanceKey === instanceParam)
433
- || findSdkSessionByInstance(instanceParam);
439
+ const ptyRec = listLivePtys().find((p) => p && p.instanceKey === instanceParam);
440
+ const sdkRec = findSdkSessionByInstance(instanceParam);
441
+ const rec = ptyRec || sdkRec;
434
442
  targetCwd = rec && rec.cwd ? normalizeSessionCwd(rec.cwd) : '';
435
- } catch (err) { targetCwd = ''; reportSwallowed('events.target-cwd', err); }
443
+ suppressFallback = !!((ptyRec && ptyRec.freshLaunch) || (sdkRec && sdkRec.freshLaunch));
444
+ } catch (err) { targetCwd = ''; suppressFallback = false; reportSwallowed('events.target-cwd', err); }
436
445
  }
437
- return latestMainSessionDir(join(LOG_DIR, sanitizePathComponent(projectParam)), { skipForeignLive: true, instanceKey: instanceParam || '', targetCwd }) || null;
446
+ return latestMainSessionDir(join(LOG_DIR, sanitizePathComponent(projectParam)), { skipForeignLive: true, instanceKey: instanceParam || '', targetCwd, suppressFallback }) || null;
438
447
  } catch (err) {
439
448
  reportSwallowed('events.project-resolve', err, { project: projectParam });
440
449
  return null;
@@ -466,6 +475,9 @@ export async function serveEventStream(sink, params, deps) {
466
475
  // per-project live feed streams its first turn in place the moment the PTY writes its
467
476
  // first session dir. Only a DEAD instance keeps the explicit sid-not-found posture (the
468
477
  // client toasts + auto-detaches to the bound view — unchanged from before this fix).
478
+ // forceNew (2026-11) reaches this same empty view a third way: the freshLaunch mark makes
479
+ // resolveColdSource return null (suppressFallback), so a same-cwd twin's OLD conversation
480
+ // is never served to the brand-new instance.
469
481
  const instanceNoSession = !!(instanceParam && !sidParam && !viewColdDir);
470
482
  let instanceAlive = false;
471
483
  if (instanceNoSession) {