@gajae-code/coding-agent 0.22.1 → 0.22.2

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 (75) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/types/cli/doctor/probe-types.d.ts +1 -1
  3. package/dist/types/cli/doctor/session-owners-probe.d.ts +7 -0
  4. package/dist/types/cli/doctor/session-owners.d.ts +16 -0
  5. package/dist/types/cli/github-release.d.ts +16 -0
  6. package/dist/types/cli/session-owners-cli.d.ts +13 -0
  7. package/dist/types/cli/update-cli.d.ts +2 -0
  8. package/dist/types/commands/sdk.d.ts +23 -14
  9. package/dist/types/config/settings-schema.d.ts +6 -0
  10. package/dist/types/exec/bash-shell-guardian.d.ts +61 -0
  11. package/dist/types/export/html/html-export-destination.d.ts +16 -0
  12. package/dist/types/sdk/bus/telegram-daemon-contract.d.ts +1 -1
  13. package/dist/types/sdk/host/control/runtime-gate.d.ts +7 -0
  14. package/dist/types/session/internal/graph-successor-proof.d.ts +33 -0
  15. package/dist/types/session/internal/managed-session-storage.d.ts +6 -1
  16. package/dist/types/session/internal/session-claim-set.d.ts +69 -0
  17. package/dist/types/session/operator-error-message.d.ts +29 -0
  18. package/dist/types/session/session-manager.d.ts +57 -3
  19. package/dist/types/session/session-owners-layout.d.ts +24 -0
  20. package/dist/types/session/session-ownership-mode.d.ts +45 -0
  21. package/dist/types/session/session-ownership.d.ts +195 -0
  22. package/dist/types/session/session-storage.d.ts +36 -0
  23. package/dist/types/slash-commands/helpers/parse.d.ts +1 -0
  24. package/package.json +12 -8
  25. package/scripts/verify-gjc-sdk-canonicalization.ts +2 -0
  26. package/src/cli/doctor/probe-types.ts +1 -1
  27. package/src/cli/doctor/probe.ts +9 -5
  28. package/src/cli/doctor/runner.ts +6 -1
  29. package/src/cli/doctor/session-owners-probe.ts +69 -0
  30. package/src/cli/doctor/session-owners.ts +106 -0
  31. package/src/cli/github-release.ts +100 -0
  32. package/src/cli/session-owners-cli.ts +118 -0
  33. package/src/cli/stats-cli.ts +19 -1
  34. package/src/cli/update-cli.ts +50 -3
  35. package/src/cli-ordinary.ts +1 -1
  36. package/src/commands/sdk.ts +36 -33
  37. package/src/commands/session.ts +10 -2
  38. package/src/config/settings-schema.ts +18 -0
  39. package/src/config/settings.ts +127 -13
  40. package/src/exec/bash-shell-guardian.ts +181 -12
  41. package/src/exec/isolated-shell.ts +13 -3
  42. package/src/export/html/html-export-destination.ts +47 -2
  43. package/src/export/html/index.ts +161 -13
  44. package/src/internal-urls/docs-index.generated.ts +4 -4
  45. package/src/main.ts +20 -14
  46. package/src/modes/acp/acp-agent.ts +6 -0
  47. package/src/modes/action-registry.ts +4 -1
  48. package/src/modes/controllers/command-controller.ts +12 -5
  49. package/src/modes/controllers/extension-ui-controller.ts +6 -22
  50. package/src/modes/controllers/input-controller.ts +3 -2
  51. package/src/modes/controllers/selector-controller.ts +14 -1
  52. package/src/modes/interactive-mode.ts +6 -3
  53. package/src/modes/print-mode.ts +2 -1
  54. package/src/modes/runtime-init.ts +2 -17
  55. package/src/modes/utils/ui-helpers.ts +5 -3
  56. package/src/sdk/bus/index.ts +22 -0
  57. package/src/sdk/bus/telegram-daemon-contract.ts +1 -1
  58. package/src/sdk/host/control/dispatch.ts +5 -1
  59. package/src/sdk/host/control/runtime-gate.ts +22 -0
  60. package/src/sdk/host/host.ts +4 -1
  61. package/src/sdk/session-readonly/metadata.ts +24 -18
  62. package/src/sdk/session.ts +2 -0
  63. package/src/session/agent-session.ts +101 -22
  64. package/src/session/internal/graph-successor-proof.ts +108 -0
  65. package/src/session/internal/managed-session-storage.ts +8 -1
  66. package/src/session/internal/session-claim-set.ts +242 -0
  67. package/src/session/operator-error-message.ts +79 -0
  68. package/src/session/session-manager.ts +524 -108
  69. package/src/session/session-owners-layout.ts +52 -0
  70. package/src/session/session-ownership-mode.ts +176 -0
  71. package/src/session/session-ownership.ts +851 -0
  72. package/src/session/session-storage.ts +60 -16
  73. package/src/setup/credential-import.ts +2 -1
  74. package/src/slash-commands/builtin-registry.ts +2 -0
  75. package/src/slash-commands/helpers/parse.ts +3 -1
@@ -58,6 +58,7 @@ import {
58
58
  logger,
59
59
  parseJsonlLenient,
60
60
  pathIsWithin,
61
+ postmortem,
61
62
  resolveEquivalentPath,
62
63
  Snowflake,
63
64
  toError,
@@ -139,6 +140,12 @@ import {
139
140
  resolveTextBlobSync,
140
141
  sweepResidentCacheRoot,
141
142
  } from "./blob-store";
143
+ import {
144
+ type GraphSuccessorRefusal,
145
+ graphSuccessorRefusalMessage,
146
+ proveOwnCommittedGraph,
147
+ sanitizeLoadedSessionEntryReplayMetadata,
148
+ } from "./internal/graph-successor-proof";
142
149
  import {
143
150
  deleteManagedSessionCandidate,
144
151
  isRecoverableOwnerOnlyModeDrift,
@@ -170,10 +177,12 @@ import {
170
177
  retainManagedDirectoryAuthority,
171
178
  } from "./internal/managed-session-storage";
172
179
  import {
180
+ ManagedSessionBusyError,
173
181
  type ManagedSessionTransactionScope,
174
182
  withManagedSessionTransaction,
175
183
  } from "./internal/managed-session-transaction";
176
184
  import { classifyNativePublishOutcome, formatNativePublishDiagnostic } from "./internal/native-publish-outcome";
185
+ import { SessionClaimSet, sessionClaimSetCapability } from "./internal/session-claim-set";
177
186
  import {
178
187
  applyReducerDelta,
179
188
  type BaseAnchor,
@@ -2661,6 +2670,20 @@ export class SharedSessionMutationUnsupportedError extends Error {
2661
2670
  }
2662
2671
  }
2663
2672
 
2673
+ export type { GraphSuccessorRefusal } from "./internal/graph-successor-proof";
2674
+
2675
+ /** A refused graph successor that names the reason; still a shared-mutation refusal. */
2676
+ export class GraphSuccessorUnavailableError extends SharedSessionMutationUnsupportedError {
2677
+ constructor(
2678
+ operation: string,
2679
+ readonly reason: GraphSuccessorRefusal,
2680
+ ) {
2681
+ super(operation);
2682
+ this.message = graphSuccessorRefusalMessage(reason);
2683
+ this.name = "GraphSuccessorUnavailableError";
2684
+ }
2685
+ }
2686
+
2664
2687
  /**
2665
2688
  * Typed near-limit rewrite outcome (follow-up to #4566).
2666
2689
  *
@@ -2762,6 +2785,31 @@ export class SessionTranscriptOversizedError extends Error {
2762
2785
  this.size = size;
2763
2786
  }
2764
2787
  }
2788
+ /**
2789
+ * A transcript above the eager-load cap that the bounded session-memory loader cannot serve:
2790
+ * branched, patch-bearing, uncompacted, pre-v5, or malformed. `reason` is the loader's fallback reason.
2791
+ */
2792
+ export class SessionTranscriptBoundedOpenError extends Error {
2793
+ readonly code = "bounded_open_unsupported";
2794
+ readonly size: number;
2795
+ readonly reason: string;
2796
+
2797
+ constructor(size: number, reason: string) {
2798
+ super(`Session transcript is not eligible for bounded loading (${reason})`);
2799
+ this.name = "SessionTranscriptBoundedOpenError";
2800
+ this.size = size;
2801
+ this.reason = reason;
2802
+ }
2803
+ }
2804
+ /** The source of a bounded read-only snapshot was replaced or truncated after the snapshot opened. */
2805
+ export class SessionSnapshotSourceChangedError extends Error {
2806
+ readonly code = "snapshot_source_changed";
2807
+
2808
+ constructor() {
2809
+ super("Session transcript was replaced or truncated after the read-only snapshot opened");
2810
+ this.name = "SessionSnapshotSourceChangedError";
2811
+ }
2812
+ }
2765
2813
  /** Default synchronous session-context materialization budget (512 MiB). */
2766
2814
  export const SESSION_CONTEXT_MATERIALIZATION_BUDGET_BYTES_DEFAULT = 512 * 1024 * 1024;
2767
2815
  /** Ceiling for a `GJC_SESSION_CONTEXT_BUDGET_BYTES` override (8 GiB) so the memory guard stays meaningful. */
@@ -5979,14 +6027,6 @@ function cloneSessionEntry(entry: SessionEntry): SessionEntry {
5979
6027
  return cloned;
5980
6028
  }
5981
6029
 
5982
- /** Match eager-resume replay sanitation whenever an entry is loaded from a bounded sidecar path. */
5983
- function sanitizeLoadedSessionEntryReplayMetadata(entry: SessionEntry): SessionEntry {
5984
- if (entry.type === "message" && entry.message.role === "assistant") {
5985
- entry.message = sanitizeRehydratedOpenAIResponsesAssistantMessage(entry.message);
5986
- }
5987
- return entry;
5988
- }
5989
-
5990
6030
  function materializeProviderVisibleEntrySync(entry: SessionEntry, stores: ResidentBlobStores): SessionEntry {
5991
6031
  if (entry.type === "compaction") {
5992
6032
  const cache = new Map<string, string>();
@@ -7971,6 +8011,8 @@ export class SessionManager {
7971
8011
  }>
7972
8012
  | undefined;
7973
8013
  #sessionId: string = "";
8014
+ /** The session claims this manager holds (design §2.5); empty unless a factory or transition hands one in. */
8015
+ readonly #ownershipClaims = new SessionClaimSet();
7974
8016
  #committedIdentityGeneration = 0;
7975
8017
  #committedIdentity: { id: string; file: string | undefined } | undefined;
7976
8018
  #titleMutationRevision = 0;
@@ -7980,6 +8022,8 @@ export class SessionManager {
7980
8022
  #preparedNewSessions = new Set<PreparedNewSessionState>();
7981
8023
  /** Provenance is manager-owned; fresh successors do not inherit shared restrictions. */
7982
8024
  readonly #preparedGraphSourceIds = new WeakMap<PreparedNewSessionState, string>();
8025
+ /** Successors proven against the committed transcript. */
8026
+ readonly #committedGraphSuccessors = new WeakSet<PreparedNewSessionState>();
7983
8027
  #sessionName: string | undefined;
7984
8028
  #titleSource: "auto" | "user" | undefined;
7985
8029
  #sessionFile: string | undefined;
@@ -7992,6 +8036,13 @@ export class SessionManager {
7992
8036
  * direct checks on fork, draft, artifact, blob, move, discard/delete, and state-restore methods.
7993
8037
  */
7994
8038
  #readOnlySnapshot = false;
8039
+ /** Private sidecar cache of a bounded read-only snapshot, set before its open; see {@link openReadOnlySnapshot}. */
8040
+ #snapshotSidecarStore: EphemeralBlobStore | undefined;
8041
+ #snapshotSidecarUnregister: (() => void) | undefined;
8042
+ /** Once set, the sidecar root resolves to nothing (never the source). */
8043
+ #snapshotSidecarsDisposed = false;
8044
+ /** Bounded snapshot's source identity and validated size; the cold export scan stops there. */
8045
+ #snapshotScanIdentity: { dev: bigint; ino: bigint; size: number } | undefined;
7995
8046
  #strictResumeMutationPending = false;
7996
8047
  #resumedDraftConsumed = false;
7997
8048
  #ensuredOnDisk: boolean = false;
@@ -9022,6 +9073,7 @@ export class SessionManager {
9022
9073
 
9023
9074
  /** Restore a rollback snapshot, reopening cold authority instead of hydrating it. @internal */
9024
9075
  async restoreRollbackState(snapshot: SessionManagerStateSnapshot): Promise<void> {
9076
+ using _rotation = this.#ownershipClaims.transition();
9025
9077
  if (this.#readOnlySnapshot) throw new Error("read_only_snapshot");
9026
9078
  const issued = this.#authenticateStateSnapshot(snapshot);
9027
9079
  if (!issued.coldRestoreFile) {
@@ -9108,7 +9160,7 @@ export class SessionManager {
9108
9160
  } catch (error) {
9109
9161
  logger.warn("Failed to release predecessor rollback sidecar authority", { error: toError(error).message });
9110
9162
  }
9111
- this.#sessionId = issued.sessionId;
9163
+ this.#bindSessionId(issued.sessionId);
9112
9164
  this.#sessionName = issued.sessionName;
9113
9165
  this.#titleSource = issued.titleSource;
9114
9166
  this.#sessionFile = issued.coldRestoreFile;
@@ -9201,6 +9253,7 @@ export class SessionManager {
9201
9253
  }
9202
9254
 
9203
9255
  restoreState(snapshot: SessionManagerStateSnapshot): void {
9256
+ using _rotation = this.#ownershipClaims.transition();
9204
9257
  if (this.#readOnlySnapshot) throw new Error("read_only_snapshot");
9205
9258
  this.#assertArtifactOpen();
9206
9259
  const issued = this.#resolveAdoptedStateSnapshot(snapshot);
@@ -9241,7 +9294,7 @@ export class SessionManager {
9241
9294
  }
9242
9295
  }
9243
9296
  managedTransition?.adopt();
9244
- this.#sessionId = issued.sessionId;
9297
+ this.#bindSessionId(issued.sessionId);
9245
9298
  this.#sessionName = issued.sessionName;
9246
9299
  this.#titleSource = issued.titleSource;
9247
9300
  this.#sessionFile = issued.sessionFile;
@@ -9297,7 +9350,7 @@ export class SessionManager {
9297
9350
  this.#persistError = undefined;
9298
9351
  this.#closeRetryOriginError = undefined;
9299
9352
  this.#persistErrorReported = false;
9300
- this.#sessionId = state.sessionId;
9353
+ this.#bindSessionId(state.sessionId);
9301
9354
  this.#sessionName = state.header.title;
9302
9355
  this.#titleSource = state.header.titleSource;
9303
9356
  this.#sessionFile = state.sessionFile;
@@ -9516,7 +9569,7 @@ export class SessionManager {
9516
9569
  prepared.dispose();
9517
9570
  return false;
9518
9571
  }
9519
- this.#sessionId = header.id;
9572
+ this.#bindSessionId(header.id);
9520
9573
  this.#sessionName = header.title;
9521
9574
  this.#titleSource = header.titleSource;
9522
9575
  this.#needsFullRewriteOnNextPersist = false;
@@ -9591,12 +9644,7 @@ export class SessionManager {
9591
9644
  sessionFile: string,
9592
9645
  ): Promise<SessionStorageExclusiveLock | "published" | undefined> {
9593
9646
  if (!this.#storage.acquireExclusiveLockSync) return undefined;
9594
- const sidecarRoot =
9595
- this.destination.kind === "managed"
9596
- ? this.#managedSidecarRoot(sessionFile)
9597
- : sessionFile.endsWith(".jsonl")
9598
- ? sessionFile.slice(0, -6)
9599
- : sessionFile;
9647
+ const sidecarRoot = this.#sidecarRootFor(sessionFile);
9600
9648
  if (!sidecarRoot) return undefined;
9601
9649
  const lockPath = `${sidecarRoot}/.session-memory.spill.build-lock`;
9602
9650
  const commitPath = `${sidecarRoot}/.session-memory.spill.commit`;
@@ -9733,7 +9781,7 @@ export class SessionManager {
9733
9781
  }
9734
9782
  this.#managedPersistExpectedIdentity =
9735
9783
  this.destination.kind === "managed" ? this.#captureManagedPersistIdentity(sessionFile) : undefined;
9736
- this.#sessionId = discovery.header.id;
9784
+ this.#bindSessionId(discovery.header.id);
9737
9785
  this.#sessionName = discovery.header.title;
9738
9786
  this.#titleSource = discovery.header.titleSource;
9739
9787
  this.#needsFullRewriteOnNextPersist = false;
@@ -10436,12 +10484,7 @@ export class SessionManager {
10436
10484
  throw new Error("Could not open session: unstable");
10437
10485
  };
10438
10486
  revalidateStrictResume();
10439
- const sidecarRoot =
10440
- this.destination.kind === "managed"
10441
- ? this.#managedSidecarRoot(resolvedSessionFile)
10442
- : resolvedSessionFile.endsWith(".jsonl")
10443
- ? resolvedSessionFile.slice(0, -6)
10444
- : resolvedSessionFile;
10487
+ const sidecarRoot = this.#sidecarRootFor(resolvedSessionFile);
10445
10488
  let transcriptSize: number | undefined;
10446
10489
  try {
10447
10490
  transcriptSize = this.#statSync(resolvedSessionFile).size;
@@ -10485,15 +10528,7 @@ export class SessionManager {
10485
10528
  if ((strictResume || requireExisting) && transcriptMissing) throw new Error("Could not open session: unstable");
10486
10529
  if (initializeMissing && transcriptMissing) {
10487
10530
  if (stagedRollbackCandidate) throw new Error("Could not open session: unstable");
10488
- const fresh = this.#freshSessionState(undefined, resolvedSessionFile);
10489
- const prepared = this.#prepareFreshSessionTransition(fresh, "memory-fallback");
10490
- this.#applyFreshSessionMetadata(fresh);
10491
- this.#commitResidentTextStoreTransition(prepared);
10492
- this.#retireEphemeralArtifacts();
10493
- if (!stagedRollbackCandidate) this.#writeTerminalBreadcrumb(resolvedSessionFile);
10494
- await this.#rewriteFile();
10495
- this.#flushed = true;
10496
- this.#ensuredOnDisk = true;
10531
+ await this.#initializeFreshTranscriptAt(resolvedSessionFile);
10497
10532
  return;
10498
10533
  }
10499
10534
  if (strictResume?.reuseEntries !== false) strictManagedFallbackEntries = strictResume?.inspection.entries;
@@ -10515,15 +10550,7 @@ export class SessionManager {
10515
10550
  revalidateStrictResume();
10516
10551
  if (entries.length === 0) {
10517
10552
  if (stagedRollbackCandidate) throw new Error("Could not open session: unstable");
10518
- const fresh = this.#freshSessionState(undefined, resolvedSessionFile);
10519
- const prepared = this.#prepareFreshSessionTransition(fresh, "memory-fallback");
10520
- this.#applyFreshSessionMetadata(fresh);
10521
- this.#commitResidentTextStoreTransition(prepared);
10522
- this.#retireEphemeralArtifacts();
10523
- if (!stagedRollbackCandidate) this.#writeTerminalBreadcrumb(resolvedSessionFile);
10524
- await this.#rewriteFile();
10525
- this.#flushed = true;
10526
- this.#ensuredOnDisk = true;
10553
+ await this.#initializeFreshTranscriptAt(resolvedSessionFile);
10527
10554
  return;
10528
10555
  }
10529
10556
  const header = entries.find(entry => entry.type === "session") as SessionHeader | undefined;
@@ -10548,7 +10575,7 @@ export class SessionManager {
10548
10575
  "memory-fallback",
10549
10576
  );
10550
10577
  this.#sessionFile = resolvedSessionFile;
10551
- this.#sessionId = sessionId;
10578
+ this.#bindSessionId(sessionId);
10552
10579
  this.#sessionName = header?.title;
10553
10580
  this.#titleSource = header?.titleSource;
10554
10581
  this.#needsFullRewriteOnNextPersist = migrationApplied;
@@ -10566,6 +10593,23 @@ export class SessionManager {
10566
10593
  }
10567
10594
  }
10568
10595
 
10596
+ /**
10597
+ * Install a fresh session at `resolvedSessionFile` and persist its header: the
10598
+ * missing-file and empty-transcript outcomes of `#initSessionFile`. Callers refuse a
10599
+ * staged rollback candidate before calling.
10600
+ */
10601
+ async #initializeFreshTranscriptAt(resolvedSessionFile: string): Promise<void> {
10602
+ const fresh = this.#freshSessionState(undefined, resolvedSessionFile);
10603
+ const prepared = this.#prepareFreshSessionTransition(fresh, "memory-fallback");
10604
+ this.#applyFreshSessionMetadata(fresh);
10605
+ this.#commitResidentTextStoreTransition(prepared);
10606
+ this.#retireEphemeralArtifacts();
10607
+ this.#writeTerminalBreadcrumb(resolvedSessionFile);
10608
+ await this.#rewriteFile();
10609
+ this.#flushed = true;
10610
+ this.#ensuredOnDisk = true;
10611
+ }
10612
+
10569
10613
  #writeTerminalBreadcrumb(sessionFile: string): void {
10570
10614
  if (this.#stagedPublication && !this.#stagedPublication.committed) return;
10571
10615
  writeTerminalBreadcrumb(this.cwd, sessionFile);
@@ -10597,7 +10641,7 @@ export class SessionManager {
10597
10641
  policy,
10598
10642
  );
10599
10643
  this.#sessionFile = resolvedSessionFile;
10600
- this.#sessionId = header.id;
10644
+ this.#bindSessionId(header.id);
10601
10645
  this.#sessionName = header.title;
10602
10646
  this.#titleSource = header.titleSource;
10603
10647
  this.#needsFullRewriteOnNextPersist = migrationApplied;
@@ -10617,6 +10661,7 @@ export class SessionManager {
10617
10661
 
10618
10662
  /** Switch to a different session file (used for resume and branching). */
10619
10663
  async setSessionFile(sessionFile: string, options?: { deferEphemeralArtifactRetirement?: boolean }): Promise<void> {
10664
+ using _rotation = this.#ownershipClaims.transition();
10620
10665
  this.#assertArtifactOpen();
10621
10666
  this.#assertRecoveryHydrationWritable();
10622
10667
  const resolvedSessionFile = this.#storage instanceof FileSessionStorage ? path.resolve(sessionFile) : sessionFile;
@@ -10825,7 +10870,7 @@ export class SessionManager {
10825
10870
  managedTransition?.adopt();
10826
10871
  this.#clearManagedTranscriptRelocationResolver();
10827
10872
  this.#sessionFile = resolvedSessionFile;
10828
- this.#sessionId = sessionId;
10873
+ this.#bindSessionId(sessionId);
10829
10874
  this.#sessionName = header?.title;
10830
10875
  this.#titleSource = header?.titleSource;
10831
10876
  this.#needsFullRewriteOnNextPersist = migrationApplied;
@@ -10898,7 +10943,7 @@ export class SessionManager {
10898
10943
  this.#persistError = previous.persistError;
10899
10944
  this.#closeRetryOriginError = previous.closeRetryOriginError;
10900
10945
  this.#persistErrorReported = previous.persistErrorReported;
10901
- this.#sessionId = previous.sessionId;
10946
+ this.#bindSessionId(previous.sessionId);
10902
10947
  this.#sessionName = previous.sessionName;
10903
10948
  this.#titleSource = previous.titleSource;
10904
10949
  this.#sessionFile = previous.sessionFile;
@@ -11060,6 +11105,7 @@ export class SessionManager {
11060
11105
  const stage = this.#getPreparedNewSessionStage(prepared);
11061
11106
  this.#assertPreparedGraphPublicationAllowed(stage);
11062
11107
  if (!this.persist || !stage.sessionFile || stage.flushed) return;
11108
+ this.#ownershipClaims.checkWrite("new session successor", stage.sessionId);
11063
11109
  const entries = await Promise.all(
11064
11110
  stage.fileEntries.map(entry => prepareEntryForPersistence(entry, this.#blobStore)),
11065
11111
  );
@@ -11164,11 +11210,16 @@ export class SessionManager {
11164
11210
  /** Prepare a forked successor without publishing it through public manager state. @internal */
11165
11211
  async prepareFork(): Promise<PreparedNewSession | undefined> {
11166
11212
  if (this.#readOnlySnapshot) throw new Error("read_only_snapshot");
11167
- this.assertLegacyMutationAllowed("prepare fork");
11213
+ this.#requireGraphSuccessorRoute("prepare fork");
11168
11214
  await this.#retryPreparedNewSessionCleanups();
11169
11215
  if (!this.persist || !this.#sessionFile) return undefined;
11170
11216
  await this.#closePersistWriter();
11171
- this.assertLegacyMutationAllowed("prepare fork");
11217
+ const route = this.#requireGraphSuccessorRoute("prepare fork");
11218
+ if (route === "committed") {
11219
+ // Prove ownership before hydration can load peer entries as resident.
11220
+ const owned = this.#proveOwnCommittedGraph([]);
11221
+ if (typeof owned === "string") throw new GraphSuccessorUnavailableError("prepare fork", owned);
11222
+ }
11172
11223
  this.#ensureFullHotView();
11173
11224
  const sourceFile = this.#sessionFile;
11174
11225
  const sourceId = this.#sessionId;
@@ -11186,12 +11237,13 @@ export class SessionManager {
11186
11237
  cwd: this.cwd,
11187
11238
  parentSession: sourceId,
11188
11239
  };
11189
- const entries: FileEntry[] = [
11190
- header,
11191
- ...materializeResidentEntriesForReadSync(this.#fileEntries, this.#residentBlobStores()).filter(
11192
- (entry): entry is SessionEntry => entry.type !== "session",
11193
- ),
11194
- ];
11240
+ const sourceEntries = materializeResidentEntriesForReadSync(this.#fileEntries, this.#residentBlobStores()).filter(
11241
+ (entry): entry is SessionEntry => entry.type !== "session",
11242
+ );
11243
+ // Prove before copying artifacts.
11244
+ const proof = route === "committed" ? this.#proveOwnCommittedGraph(sourceEntries) : undefined;
11245
+ if (typeof proof === "string") throw new GraphSuccessorUnavailableError("prepare fork", proof);
11246
+ const entries: FileEntry[] = [header, ...sourceEntries];
11195
11247
  const stage: PreparedNewSessionState = {
11196
11248
  sessionId,
11197
11249
  sessionFile,
@@ -11208,17 +11260,23 @@ export class SessionManager {
11208
11260
  this.#preparedNewSessions.add(stage);
11209
11261
  this.#freezePreparedNewSessionIdentity(stage);
11210
11262
  this.#preparedGraphSourceIds.set(stage, sourceId);
11263
+ if (route === "committed") this.#committedGraphSuccessors.add(stage);
11211
11264
  try {
11212
11265
  await this.copyArtifactsForFork(sourceFile, sessionFile);
11213
11266
  this.#assertPreparedGraphPublicationAllowed(stage);
11214
- const content = `${entries.map(entry => JSON.stringify(prepareEntryForPersistenceSync(entry, this.#blobStore))).join("\n")}\n`;
11215
- if (this.destination.kind === "managed") {
11216
- this.#managedTranscriptStore(sessionFile).publishNoReplaceSync(
11217
- path.basename(sessionFile),
11218
- Buffer.from(content, "utf8"),
11219
- );
11267
+ this.#ownershipClaims.checkWrite("fork successor", stage.sessionId);
11268
+ if (proof) {
11269
+ await this.#publishCommittedGraphSuccessor(stage, sourceFile, proof, [], "prepare fork");
11220
11270
  } else {
11221
- this.#storage.writeTextSync(sessionFile, content);
11271
+ const content = `${entries.map(entry => JSON.stringify(prepareEntryForPersistenceSync(entry, this.#blobStore))).join("\n")}\n`;
11272
+ if (this.destination.kind === "managed") {
11273
+ this.#managedTranscriptStore(sessionFile).publishNoReplaceSync(
11274
+ path.basename(sessionFile),
11275
+ Buffer.from(content, "utf8"),
11276
+ );
11277
+ } else {
11278
+ this.#storage.writeTextSync(sessionFile, content);
11279
+ }
11222
11280
  }
11223
11281
  } catch (error) {
11224
11282
  try {
@@ -11236,15 +11294,16 @@ export class SessionManager {
11236
11294
 
11237
11295
  /** Prepare a path-only branch successor without publishing it through public manager state. @internal */
11238
11296
  async prepareBranchedSession(leafId: string): Promise<PreparedNewSession> {
11239
- this.assertLegacyMutationAllowed("prepare branched session");
11297
+ this.#requireGraphSuccessorRoute("prepare branched session");
11240
11298
  this.#assertRecoveryHydrationWritable();
11241
11299
  await this.#retryPreparedNewSessionCleanups();
11242
- this.assertLegacyMutationAllowed("prepare branched session");
11300
+ this.#requireGraphSuccessorRoute("prepare branched session");
11243
11301
  const sourceId = this.#sessionId;
11302
+ const sourceFile = this.#sessionFile;
11244
11303
  const branchPath = this.#getCanonicalBranchClones(leafId);
11245
11304
  if (branchPath.length === 0) throw new Error(`Entry ${leafId} not found`);
11246
11305
  await this.#closePersistWriter();
11247
- this.#assertLogicalSessionMutationAllowed(sourceId, "prepare branched session", true);
11306
+ const route = this.#requireGraphSuccessorRoute("prepare branched session", sourceId);
11248
11307
  const timestamp = new Date().toISOString();
11249
11308
  const sessionId = createSessionId();
11250
11309
  const sessionFile = this.persist
@@ -11257,7 +11316,8 @@ export class SessionManager {
11257
11316
  id: sessionId,
11258
11317
  timestamp,
11259
11318
  cwd: this.cwd,
11260
- parentSession: this.persist ? this.#sessionFile : undefined,
11319
+ // The committed route records the source id; the legacy route keeps the path.
11320
+ parentSession: route === "committed" ? sourceId : this.persist ? this.#sessionFile : undefined,
11261
11321
  };
11262
11322
  const pathWithoutLabels = branchPath.filter(entry => entry.type !== "label");
11263
11323
  const pathEntryIds = new Set(pathWithoutLabels.map(entry => entry.id));
@@ -11277,11 +11337,10 @@ export class SessionManager {
11277
11337
  labelEntries.push(labelEntry);
11278
11338
  labelParentId = labelEntry.id;
11279
11339
  }
11280
- const entries: FileEntry[] = [
11281
- header,
11282
- ...materializeResidentEntriesForReadSync(pathWithoutLabels, this.#residentBlobStores()),
11283
- ...labelEntries,
11284
- ];
11340
+ const sourceEntries = materializeResidentEntriesForReadSync(pathWithoutLabels, this.#residentBlobStores());
11341
+ const proof = route === "committed" ? this.#proveOwnCommittedGraph(sourceEntries) : undefined;
11342
+ if (typeof proof === "string") throw new GraphSuccessorUnavailableError("prepare branched session", proof);
11343
+ const entries: FileEntry[] = [header, ...sourceEntries, ...labelEntries];
11285
11344
  const stage: PreparedNewSessionState = {
11286
11345
  sessionId,
11287
11346
  sessionFile,
@@ -11298,8 +11357,18 @@ export class SessionManager {
11298
11357
  this.#preparedNewSessions.add(stage);
11299
11358
  this.#freezePreparedNewSessionIdentity(stage);
11300
11359
  this.#preparedGraphSourceIds.set(stage, sourceId);
11360
+ if (route === "committed") this.#committedGraphSuccessors.add(stage);
11301
11361
  try {
11302
- if (sessionFile) {
11362
+ if (sessionFile) this.#ownershipClaims.checkWrite("branch successor", stage.sessionId);
11363
+ if (proof) {
11364
+ await this.#publishCommittedGraphSuccessor(
11365
+ stage,
11366
+ sourceFile,
11367
+ proof,
11368
+ labelEntries,
11369
+ "prepare branched session",
11370
+ );
11371
+ } else if (sessionFile) {
11303
11372
  const content = `${entries.map(entry => JSON.stringify(prepareEntryForPersistenceSync(entry, this.#blobStore))).join("\n")}\n`;
11304
11373
  if (this.destination.kind === "managed") {
11305
11374
  this.#managedTranscriptStore(sessionFile).publishNoReplaceSync(
@@ -11326,6 +11395,7 @@ export class SessionManager {
11326
11395
 
11327
11396
  /** Publish a prepared successor synchronously after all readiness awaits succeed. @internal */
11328
11397
  commitPreparedNewSession(prepared: PreparedNewSession): void {
11398
+ using _rotation = this.#ownershipClaims.transition();
11329
11399
  this.#assertRecoveryHydrationWritable();
11330
11400
  const stage = prepared as PreparedNewSessionState;
11331
11401
  if (!this.#preparedNewSessions.has(stage) || stage.committed || stage.discarded) {
@@ -11383,7 +11453,7 @@ export class SessionManager {
11383
11453
  this.#persistError = undefined;
11384
11454
  this.#closeRetryOriginError = undefined;
11385
11455
  this.#persistErrorReported = false;
11386
- this.#sessionId = stage.sessionId;
11456
+ this.#bindSessionId(stage.sessionId);
11387
11457
  this.#sessionName = stage.sessionName;
11388
11458
  this.#titleSource = stage.titleSource;
11389
11459
  this.#sessionFile = stage.sessionFile;
@@ -11599,6 +11669,7 @@ export class SessionManager {
11599
11669
  * @returns { oldSessionFile, newSessionFile } or undefined if not persisting
11600
11670
  */
11601
11671
  async fork(): Promise<{ oldSessionFile: string; newSessionFile: string } | undefined> {
11672
+ using _rotation = this.#ownershipClaims.transition();
11602
11673
  if (this.#readOnlySnapshot) throw new Error("read_only_snapshot");
11603
11674
  this.assertLegacyMutationAllowed("fork session");
11604
11675
  if (!this.persist || !this.#sessionFile) return undefined;
@@ -11646,6 +11717,7 @@ export class SessionManager {
11646
11717
  this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session", true);
11647
11718
  forkArtifactPublication = await this.copyArtifactsForFork(oldSessionFile, newSessionFile);
11648
11719
  this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session", true);
11720
+ this.#ownershipClaims.checkWrite("fork successor", newSessionId);
11649
11721
  // Publish each already-materialized entry through the staged writer without
11650
11722
  // joining the transcript into another whole-file string/Buffer. Retired cold
11651
11723
  // history was rehydrated above and is therefore not omitted.
@@ -11754,7 +11826,7 @@ export class SessionManager {
11754
11826
  }
11755
11827
  throw failure;
11756
11828
  }
11757
- this.#sessionId = newSessionId;
11829
+ this.#bindSessionId(newSessionId);
11758
11830
  this.#sessionFile = newSessionFile;
11759
11831
  this.#sessionName = newHeader.title;
11760
11832
  this.#titleSource = newHeader.titleSource;
@@ -13146,6 +13218,17 @@ export class SessionManager {
13146
13218
  return false;
13147
13219
  }
13148
13220
 
13221
+ /**
13222
+ * The persistence failure that every later append rethrows before writing, if one is
13223
+ * latched: a {@link ManagedAppendIdentityMismatchError} after another process changed
13224
+ * the transcript, or an earlier write failure. Near-limit outcomes are not latched.
13225
+ * @internal
13226
+ */
13227
+ getLatchedPersistenceFailure(): Error | undefined {
13228
+ if (!this.persist || !this.#sessionFile) return undefined;
13229
+ return this.#persistError;
13230
+ }
13231
+
13149
13232
  /** Ownership loss remains observable even when an agent event listener aborts the turn. */
13150
13233
  getAppendIdentityMismatch(): ManagedAppendIdentityMismatchError | undefined {
13151
13234
  return this.#persistError instanceof ManagedAppendIdentityMismatchError ? this.#persistError : undefined;
@@ -13251,6 +13334,7 @@ export class SessionManager {
13251
13334
  return undefined;
13252
13335
  }
13253
13336
  // Note: caller must await _closePersistWriter() before calling this if switching files
13337
+ this.#ownershipClaims.checkWrite("persist writer open");
13254
13338
  this.#persistWriter = new NdjsonFileWriter(this.#storage, this.#sessionFile, {
13255
13339
  ...(this.#storage.acquireExclusiveLockSync
13256
13340
  ? { appendLock: (lockPath: string) => this.#storage.acquireExclusiveLockSync!(lockPath) }
@@ -13700,6 +13784,35 @@ export class SessionManager {
13700
13784
  const resolvedCandidate = path.resolve(candidate);
13701
13785
  return resolvedCandidate === resolvedRoot || resolvedCandidate.startsWith(`${resolvedRoot}${path.sep}`);
13702
13786
  }
13787
+ /** Session-memory sidecar directory: snapshot cache, managed instance cache, or artifact dir. */
13788
+ #sidecarRootFor(sessionFile: string | undefined): string | undefined {
13789
+ if (this.#snapshotSidecarStore)
13790
+ return this.#snapshotSidecarsDisposed ? undefined : this.#snapshotSidecarStore.dir;
13791
+ if (this.destination.kind === "managed") return this.#managedSidecarRoot(sessionFile);
13792
+ if (!sessionFile) return undefined;
13793
+ return sessionFile.endsWith(".jsonl") ? sessionFile.slice(0, -6) : sessionFile;
13794
+ }
13795
+
13796
+ /** Remove a bounded snapshot's private sidecar cache; idempotent. */
13797
+ #disposeSnapshotSidecars(): void {
13798
+ this.#snapshotSidecarUnregister?.();
13799
+ this.#snapshotSidecarUnregister = undefined;
13800
+ if (!this.#snapshotSidecarStore) return;
13801
+ // Keep the store so the root never falls back to the source and the cold runtime stays cold.
13802
+ this.#snapshotSidecarsDisposed = true;
13803
+ this.#snapshotSidecarStore.dispose();
13804
+ }
13805
+
13806
+ #disposeSnapshotSidecarsBestEffort(): void {
13807
+ try {
13808
+ this.#disposeSnapshotSidecars();
13809
+ } catch (error) {
13810
+ // The instance keeps its owner token, so a later sweep reaps it once this process exits.
13811
+ const reason = error instanceof ResidentCacheTrustError ? error.reason : "cleanup_failed";
13812
+ logger.warn("Failed to remove the read-only snapshot sidecar cache", { reason });
13813
+ }
13814
+ }
13815
+
13703
13816
  #managedSidecarRoot(sessionFile = this.#sessionFile): string | undefined {
13704
13817
  if (this.destination.kind !== "managed" || !sessionFile || process.platform === "win32") return undefined;
13705
13818
  if (this.#managedSidecarCacheStore && this.#managedSidecarCacheSessionFile === sessionFile)
@@ -13976,7 +14089,13 @@ export class SessionManager {
13976
14089
  /** Create (or reset) the sidecar runtime for the current lifecycle. */
13977
14090
  #resetSidecarRuntime(ineligible = false, preserveLegacySidecars = false): SessionMemorySidecarRuntime {
13978
14091
  this.#sidecarBranchActivationDirty = false;
13979
- if (!preserveLegacySidecars && this.#sessionFile && this.destination.kind !== "managed") {
14092
+ // A bounded snapshot never deletes beside the source.
14093
+ if (
14094
+ !preserveLegacySidecars &&
14095
+ !this.#snapshotSidecarStore &&
14096
+ this.#sessionFile &&
14097
+ this.destination.kind !== "managed"
14098
+ ) {
13980
14099
  for (const legacyPath of [
13981
14100
  `${this.#sessionFile}.spill.idx`,
13982
14101
  `${this.#sessionFile}.spill.tail`,
@@ -13993,12 +14112,7 @@ export class SessionManager {
13993
14112
  }
13994
14113
  }
13995
14114
  }
13996
- const sidecarRoot =
13997
- this.destination.kind === "managed"
13998
- ? this.#managedSidecarRoot()
13999
- : this.#sessionFile?.endsWith(".jsonl")
14000
- ? this.#sessionFile.slice(0, -6)
14001
- : this.#sessionFile;
14115
+ const sidecarRoot = this.#sidecarRootFor(this.#sessionFile);
14002
14116
  this.#managedRangeExpectedDescriptor =
14003
14117
  this.destination.kind === "managed" && this.#sessionFile
14004
14118
  ? (this.#managedDescriptorSnapshotOrNull() ?? undefined)
@@ -16433,7 +16547,7 @@ export class SessionManager {
16433
16547
  );
16434
16548
  transition.preserveSelectedLeaf(leafId);
16435
16549
  this.#commitResidentTextStoreTransition(transition, false);
16436
- this.#sessionId = header.id;
16550
+ this.#bindSessionId(header.id);
16437
16551
  this.#sessionName = header.title;
16438
16552
  this.#titleSource = header.titleSource;
16439
16553
  if (migrationApplied) this.#needsFullRewriteOnNextPersist = true;
@@ -17152,6 +17266,7 @@ export class SessionManager {
17152
17266
  this.#ensureFullHotView();
17153
17267
  const sessionFile = this.#sessionFile;
17154
17268
  if (!sessionFile) return;
17269
+ this.#ownershipClaims.checkWrite("rewrite");
17155
17270
  this.#withSessionPersistenceFenceSync(() => {
17156
17271
  if (this.destination.kind === "managed") {
17157
17272
  const bytes = Buffer.from(`${entries.map(entry => JSON.stringify(entry)).join("\n")}\n`, "utf8");
@@ -17593,6 +17708,7 @@ export class SessionManager {
17593
17708
  }
17594
17709
  if (this.destination.kind === "managed") {
17595
17710
  try {
17711
+ this.#ownershipClaims.checkWrite("default model promotion");
17596
17712
  if (stage.boundedCold) {
17597
17713
  if (!stage.managedAppendExpectation) throw new Error("Managed bounded append expectation is missing");
17598
17714
  const bytes = Buffer.concat(
@@ -17625,6 +17741,7 @@ export class SessionManager {
17625
17741
  return { kind: "unknown", error: new Error("Missing staged session replacement") };
17626
17742
  }
17627
17743
  try {
17744
+ this.#ownershipClaims.checkWrite("default model promotion");
17628
17745
  this.#closePersistWriterInternalSync();
17629
17746
  if (stage.boundedCold) {
17630
17747
  if (!this.#storage.replaceExactSync || !stage.sourceStat || !stage.sourceSha256) {
@@ -17753,7 +17870,29 @@ export class SessionManager {
17753
17870
  if (this.#persistError) throw this.#persistError;
17754
17871
  }
17755
17872
 
17873
+ /**
17874
+ * {@link flush} for a caller that is leaving this transcript: `/resume`, `/new`,
17875
+ * `/fork` or shutdown.
17876
+ *
17877
+ * Once another process changes a managed transcript, the append fence latches
17878
+ * {@link ManagedAppendIdentityMismatchError} and every later flush rethrows it. The
17879
+ * fence rejected those appends before writing any byte and managed appends are
17880
+ * synchronous, so nothing is left to flush; rethrowing would trap the operator in a
17881
+ * session whose only recovery is to leave it. Every other flush failure still throws.
17882
+ * @internal
17883
+ */
17884
+ async flushBeforeLeaving(): Promise<void> {
17885
+ try {
17886
+ await this.flush();
17887
+ } catch (error) {
17888
+ if (error === undefined || error !== this.getAppendIdentityMismatch()) throw error;
17889
+ }
17890
+ }
17891
+
17756
17892
  #releaseClosedSessionState(): void {
17893
+ // The terminal step of every close (close, a terminal closeStrict, a rejected open), so the
17894
+ // claims go with the state they protect.
17895
+ this.#ownershipClaims.releaseAll();
17757
17896
  this.#clearManagedTranscriptRelocationResolver();
17758
17897
  const runtime = this.#sidecarRuntime;
17759
17898
  if (runtime) {
@@ -17845,6 +17984,14 @@ export class SessionManager {
17845
17984
 
17846
17985
  /** Close the persistent writer after flushing all pending data. */
17847
17986
  async close(): Promise<void> {
17987
+ try {
17988
+ await this.#closeSession();
17989
+ } finally {
17990
+ this.#disposeSnapshotSidecarsBestEffort();
17991
+ }
17992
+ }
17993
+
17994
+ async #closeSession(): Promise<void> {
17848
17995
  this.#beginArtifactClose();
17849
17996
  await this.closeCwdMoveAdmission();
17850
17997
  await this.joinCwdTransition();
@@ -17927,6 +18074,18 @@ export class SessionManager {
17927
18074
  * writer closure before any destructive operation.
17928
18075
  */
17929
18076
  async closeStrict(): Promise<SessionManagerCloseOutcome> {
18077
+ try {
18078
+ const outcome = await this.#closeStrictSession();
18079
+ // `close_unknown` is terminal for its callers too; only a retryable close keeps its claims,
18080
+ // because the retry still writes under them.
18081
+ if (outcome.kind !== "close_failed_retryable") this.#ownershipClaims.releaseAll();
18082
+ return outcome;
18083
+ } finally {
18084
+ this.#disposeSnapshotSidecarsBestEffort();
18085
+ }
18086
+ }
18087
+
18088
+ async #closeStrictSession(): Promise<SessionManagerCloseOutcome> {
17930
18089
  this.#beginArtifactClose();
17931
18090
  this.#strictClosePending = true;
17932
18091
  await this.closeCwdMoveAdmission();
@@ -19611,6 +19770,7 @@ export class SessionManager {
19611
19770
  return { kind: "skipped", reason: "named" };
19612
19771
  if (!current()) return { kind: "skipped", reason: "stale" };
19613
19772
  try {
19773
+ this.#ownershipClaims.checkWrite("shared title", sessionId);
19614
19774
  const record: HeaderPatchRecord = { type: "header_patch", patch };
19615
19775
  if (snapshot) {
19616
19776
  attempted = true;
@@ -19737,6 +19897,7 @@ export class SessionManager {
19737
19897
  if (this.#sharedAppendOnly) SessionManagerTestHooks.beforeSharedAppendPublish?.();
19738
19898
  this.#refreshManagedTranscriptRelocation();
19739
19899
  if (!this.#sessionFile) throw new Error("Managed transcript path is unavailable");
19900
+ this.#ownershipClaims.checkWrite("managed append");
19740
19901
  this.#withSessionPersistenceFenceSync(() => {
19741
19902
  const sessionFile = this.#sessionFile!;
19742
19903
  const store = this.#managedTranscriptStore(sessionFile);
@@ -20681,8 +20842,131 @@ export class SessionManager {
20681
20842
 
20682
20843
  #assertPreparedGraphPublicationAllowed(stage: PreparedNewSessionState): void {
20683
20844
  const sourceId = this.#preparedGraphSourceIds.get(stage);
20684
- if (sourceId !== undefined)
20685
- this.#assertLogicalSessionMutationAllowed(sourceId, "publish prepared graph successor", true);
20845
+ if (sourceId === undefined) return;
20846
+ if (this.#committedGraphSuccessors.has(stage)) {
20847
+ // Adoption never writes the source; only an in-flight publication refuses.
20848
+ if ((this.#activeSharedMutationSessionCounts.get(sourceId) ?? 0) > 0)
20849
+ throw new GraphSuccessorUnavailableError("publish prepared graph successor", "publication-in-flight");
20850
+ return;
20851
+ }
20852
+ this.#assertLogicalSessionMutationAllowed(sourceId, "publish prepared graph successor", true);
20853
+ }
20854
+
20855
+ /** Why a fork or branch cannot be prepared now; non-throwing and write-free, for use before any effect. */
20856
+ graphSuccessorRefusal(target: { leafId?: string; wholeSession?: boolean } = {}): GraphSuccessorRefusal | undefined {
20857
+ let refusal: GraphSuccessorRefusal | undefined;
20858
+ try {
20859
+ if (target.leafId !== undefined && !this.#resolveEntry(target.leafId)) refusal = "unknown-entry";
20860
+ else {
20861
+ const route = this.#graphSuccessorRoute(this.#sessionId);
20862
+ if (route !== "committed") refusal = route === "legacy" ? undefined : route;
20863
+ else {
20864
+ const entries =
20865
+ target.wholeSession === true
20866
+ ? this.#fileEntries.filter((entry): entry is SessionEntry => entry.type !== "session")
20867
+ : target.leafId !== undefined
20868
+ ? this.#getCanonicalBranchClones(target.leafId).filter(entry => entry.type !== "label")
20869
+ : [];
20870
+ const proof = this.#proveOwnCommittedGraph(
20871
+ materializeResidentEntriesForReadSync(entries, this.#residentBlobStores()),
20872
+ );
20873
+ if (typeof proof === "string") refusal = proof;
20874
+ }
20875
+ }
20876
+ } catch (error) {
20877
+ logger.warn("Graph successor probe failed", { error: toError(error).message });
20878
+ refusal = "unreadable";
20879
+ }
20880
+ if (refusal) logger.debug("Graph successor unavailable", { sessionId: this.#sessionId, reason: refusal });
20881
+ return refusal;
20882
+ }
20883
+
20884
+ /** "legacy" without shared bars (admission unchanged), "committed" when only the bars refuse, else the refusal. */
20885
+ #graphSuccessorRoute(sessionId: string): "legacy" | "committed" | GraphSuccessorRefusal {
20886
+ const barred = this.#sharedAppendBarSessionIds.has(sessionId) || this.#sharedRewriteBarSessionIds.has(sessionId);
20887
+ if (!barred) return "legacy";
20888
+ if (
20889
+ (this.#activeSharedMutationSessionCounts.get(sessionId) ?? 0) > 0 ||
20890
+ (SessionManager.#sharedPublicationsInFlight.get(sessionId) ?? 0) > 0
20891
+ )
20892
+ return "publication-in-flight";
20893
+ return this.destination.kind === "managed" && this.persist ? "committed" : "not-admitted";
20894
+ }
20895
+
20896
+ /** The route for `operation` on the current session, throwing the refusal. */
20897
+ #requireGraphSuccessorRoute(operation: string, sourceId = this.#sessionId): "legacy" | "committed" {
20898
+ if (this.#sessionId !== sourceId) throw new GraphSuccessorUnavailableError(operation, "changed");
20899
+ const route = this.#graphSuccessorRoute(sourceId);
20900
+ if (route === "legacy") {
20901
+ this.assertLegacyMutationAllowed(operation);
20902
+ return route;
20903
+ }
20904
+ if (route === "committed") return route;
20905
+ throw new GraphSuccessorUnavailableError(operation, route);
20906
+ }
20907
+
20908
+ /** {@link proveOwnCommittedGraph} over this opener's committed transcript; read-only. */
20909
+ #proveOwnCommittedGraph(
20910
+ sourceEntries: readonly SessionEntry[],
20911
+ ): { lines: string[]; digest: string } | GraphSuccessorRefusal {
20912
+ const sessionFile = this.#sessionFile;
20913
+ const readSnapshot = this.#storage.readSnapshotSync?.bind(this.#storage);
20914
+ if (this.destination.kind !== "managed" || !this.persist || !sessionFile || !readSnapshot) return "not-admitted";
20915
+ // A cold-retired view cannot prove ownership: its resident ids are incomplete.
20916
+ if (this.#coldSidecarActive()) return "large-session";
20917
+ let bytes: Uint8Array;
20918
+ try {
20919
+ bytes = readSnapshot(sessionFile).bytes;
20920
+ } catch {
20921
+ return "unreadable";
20922
+ }
20923
+ // A scratch store: blob refs are content hashes the committed lines already hold.
20924
+ const scratch = new MemoryBlobStore();
20925
+ return proveOwnCommittedGraph({
20926
+ bytes,
20927
+ sessionId: this.#sessionId,
20928
+ ownIds: new Set(this.#residentEntryIds()),
20929
+ sourceEntries,
20930
+ serialize: entry => prepareEntryForPersistenceSync(entry, scratch),
20931
+ onMismatch: entryId => logger.warn("Committed session entry differs from the resident entry", { entryId }),
20932
+ });
20933
+ }
20934
+
20935
+ /** Publish a proven successor; under the source's lease only the proven digest is re-checked. */
20936
+ async #publishCommittedGraphSuccessor(
20937
+ stage: PreparedNewSessionState,
20938
+ sourceFile: string | undefined,
20939
+ proof: { lines: string[]; digest: string },
20940
+ addedEntries: readonly FileEntry[],
20941
+ operation: string,
20942
+ ): Promise<void> {
20943
+ const sourceId = this.#preparedGraphSourceIds.get(stage);
20944
+ const sessionFile = stage.sessionFile;
20945
+ this.#refreshManagedTranscriptRelocation();
20946
+ if (!sourceId || !sourceFile || !sessionFile || this.#sessionFile !== sourceFile)
20947
+ throw new GraphSuccessorUnavailableError(operation, "changed");
20948
+ const locksDirectory = managedSessionTransactionLocksDirectory(path.dirname(sourceFile));
20949
+ fs.mkdirSync(locksDirectory, { recursive: true, mode: 0o700 });
20950
+ const lines = [JSON.stringify(stage.header), ...proof.lines];
20951
+ for (const entry of addedEntries)
20952
+ lines.push(JSON.stringify(prepareEntryForPersistenceSync(entry, this.#blobStore)));
20953
+ try {
20954
+ await withManagedSessionTransaction({ locksDirectory, sessionId: sourceId }, async scope => {
20955
+ scope.assertOwned();
20956
+ if (this.#sessionFile !== sourceFile) throw new GraphSuccessorUnavailableError(operation, "changed");
20957
+ this.#requireGraphSuccessorRoute(operation, sourceId);
20958
+ if (this.#committedDigestSync(sourceFile) !== proof.digest)
20959
+ throw new GraphSuccessorUnavailableError(operation, "changed");
20960
+ scope.assertOwned();
20961
+ this.#managedTranscriptStore(sessionFile).publishNoReplaceSync(
20962
+ path.basename(sessionFile),
20963
+ Buffer.from(`${lines.join("\n")}\n`, "utf8"),
20964
+ );
20965
+ });
20966
+ } catch (error) {
20967
+ if (error instanceof ManagedSessionBusyError) throw new GraphSuccessorUnavailableError(operation, "busy");
20968
+ throw error;
20969
+ }
20686
20970
  }
20687
20971
 
20688
20972
  #assertDiscardTranscriptAllowed(bytes: Buffer): void {
@@ -21054,6 +21338,7 @@ export class SessionManager {
21054
21338
  this.#residentBlobStores(),
21055
21339
  ).map(entry => prepareEntryForPersistenceSync(entry, this.#blobStore));
21056
21340
  const bytes = Buffer.from(`${entries.map(entry => JSON.stringify(entry)).join("\n")}\n`, "utf8");
21341
+ this.#ownershipClaims.checkWrite("shared bootstrap");
21057
21342
  scope.assertOwned();
21058
21343
  store.assertBound();
21059
21344
  store.publishNoReplaceSync(name, bytes);
@@ -22218,7 +22503,10 @@ export class SessionManager {
22218
22503
 
22219
22504
  visitEntriesForExport(visitor: (entry: SessionEntry) => void): void {
22220
22505
  if (this.#coldSidecarActive() && this.#sessionFile) {
22221
- const size = this.#statSync(this.#sessionFile).size;
22506
+ // A bounded snapshot exports exactly the bytes validated at open.
22507
+ const size = this.#snapshotScanIdentity
22508
+ ? this.#assertSnapshotSourceRetained(this.#snapshotScanIdentity)
22509
+ : this.#statSync(this.#sessionFile).size;
22222
22510
  const failure = scanTranscriptLinesBounded(
22223
22511
  this.#boundedReadStorage(),
22224
22512
  this.#sessionFile,
@@ -22247,6 +22535,7 @@ export class SessionManager {
22247
22535
  },
22248
22536
  );
22249
22537
  if (failure) throw new Error(`export_transcript_scan_failed:${failure}`);
22538
+ if (this.#snapshotScanIdentity) this.#assertSnapshotSourceRetained(this.#snapshotScanIdentity);
22250
22539
  return;
22251
22540
  }
22252
22541
  const cache = new Map<string, string>();
@@ -22263,6 +22552,14 @@ export class SessionManager {
22263
22552
  );
22264
22553
  }
22265
22554
  }
22555
+ /** Returns the snapshot's validated size; throws if the source was replaced or truncated. */
22556
+ #assertSnapshotSourceRetained(identity: { dev: bigint; ino: bigint; size: number }): number {
22557
+ const current = this.#statSync(this.#sessionFile!);
22558
+ if (current.dev !== identity.dev || current.ino !== identity.ino || current.size < identity.size)
22559
+ throw new SessionSnapshotSourceChangedError();
22560
+ return identity.size;
22561
+ }
22562
+
22266
22563
  getEntriesForExport(): SessionEntry[] {
22267
22564
  this.#ensureFullHotView();
22268
22565
  const cache = new Map<string, string>();
@@ -22677,7 +22974,10 @@ export class SessionManager {
22677
22974
 
22678
22975
  async #sanitizeLoadedOpenAIResponsesReplayMetadataAndPersist(): Promise<boolean> {
22679
22976
  const patches = this.#sanitizeLoadedOpenAIResponsesReplayMetadata();
22680
- if (!this.isManagedDestination()) await this.#persistPatches(patches);
22977
+ if (!this.isManagedDestination()) {
22978
+ if (patches.length > 0) this.assertLegacyMutationAllowed("sanitize loaded OpenAI Responses replay metadata");
22979
+ await this.#persistPatches(patches);
22980
+ }
22681
22981
  return patches.length > 0;
22682
22982
  }
22683
22983
 
@@ -22687,7 +22987,6 @@ export class SessionManager {
22687
22987
  if (entry.type !== "message" || entry.message.role !== "assistant") continue;
22688
22988
  const sanitizedMessage = sanitizeRehydratedOpenAIResponsesAssistantMessage(entry.message);
22689
22989
  if (sanitizedMessage === entry.message) continue;
22690
- this.assertLegacyMutationAllowed("sanitize loaded OpenAI Responses replay metadata");
22691
22990
  entry.message = sanitizedMessage;
22692
22991
  patches.push({ type: "entry_patch", entryId: entry.id, patch: { message: sanitizedMessage } });
22693
22992
  }
@@ -22821,6 +23120,19 @@ export class SessionManager {
22821
23120
 
22822
23121
  return roots;
22823
23122
  }
23123
+ [sessionClaimSetCapability](): SessionClaimSet {
23124
+ return this.#ownershipClaims;
23125
+ }
23126
+
23127
+ /**
23128
+ * Every change of this manager's session id goes through here, so the claim set always knows the
23129
+ * current id. Bookkeeping only: it never claims, and releases happen when a transition settles.
23130
+ */
23131
+ #bindSessionId(sessionId: string): void {
23132
+ this.#sessionId = sessionId;
23133
+ this.#ownershipClaims.bind(sessionId);
23134
+ }
23135
+
22824
23136
  [sessionManagerReadCapability](): SessionManagerReadAccess {
22825
23137
  return this.#internalReadAccess;
22826
23138
  }
@@ -22891,6 +23203,7 @@ export class SessionManager {
22891
23203
  * Returns the new session file path, or undefined if not persisting.
22892
23204
  */
22893
23205
  createBranchedSession(leafId: string): string | undefined {
23206
+ using _rotation = this.#ownershipClaims.transition();
22894
23207
  this.assertLegacyMutationAllowed("create branched session");
22895
23208
  this.#assertRecoveryHydrationWritable();
22896
23209
  this.#ensureFullHotView();
@@ -22968,6 +23281,7 @@ export class SessionManager {
22968
23281
  "retain-and-throw",
22969
23282
  );
22970
23283
  try {
23284
+ this.#ownershipClaims.checkWrite("branch successor", newSessionId);
22971
23285
  if (this.destination.kind === "managed") {
22972
23286
  this.#managedTranscriptStore(newSessionFile).publishNoReplaceSync(
22973
23287
  path.basename(newSessionFile),
@@ -22980,7 +23294,7 @@ export class SessionManager {
22980
23294
  transition.dispose();
22981
23295
  throw error;
22982
23296
  }
22983
- this.#sessionId = newSessionId;
23297
+ this.#bindSessionId(newSessionId);
22984
23298
  this.#sessionFile = newSessionFile;
22985
23299
  this.#clearManagedTranscriptRelocationResolver();
22986
23300
  this.#flushed = true;
@@ -23017,7 +23331,7 @@ export class SessionManager {
23017
23331
  },
23018
23332
  "retain-and-throw",
23019
23333
  );
23020
- this.#sessionId = newSessionId;
23334
+ this.#bindSessionId(newSessionId);
23021
23335
  this.#clearManagedTranscriptRelocationResolver();
23022
23336
  this.#commitResidentTextStoreTransition(transition);
23023
23337
  this.#noteCommittedIdentityChange(previousSessionId, previousSessionFile);
@@ -24586,19 +24900,35 @@ export class SessionManager {
24586
24900
  sessionMemoryMode,
24587
24901
  );
24588
24902
  if (opened.kind === "error") {
24589
- if (opened.reason === "legacy_migration_disabled") throw new SessionMigrationPolicyError();
24590
- if (opened.reason === "artifact_capacity_exceeded")
24591
- throw new SessionArtifactCapacityError(
24592
- opened.message ?? "Session artifacts exceed the migration capacity.",
24593
- );
24594
- if (opened.reason === "oversized") throw new SessionTranscriptOversizedError(opened.size ?? 0);
24595
- if (opened.reason === "context_too_large") throw new SessionContextTooLargeError(opened.size ?? 0);
24596
- if (opened.reason === "migration_busy") throw new SessionMigrationBusyError();
24597
- throw new Error(`Could not open session: ${opened.reason}`);
24903
+ throw SessionManager.#typedStrictOpenError(opened) ?? new Error(`Could not open session: ${opened.reason}`);
24598
24904
  }
24599
24905
  return opened.manager;
24600
24906
  }
24601
24907
 
24908
+ /**
24909
+ * The typed error for a strict-open failure whose reason the operator can act on, or
24910
+ * `undefined` for a reason the caller handles itself (a generic open error, or skipping
24911
+ * a `--continue` candidate).
24912
+ */
24913
+ static #typedStrictOpenError(failure: StrictSessionOpenFailure): Error | undefined {
24914
+ switch (failure.reason) {
24915
+ case "legacy_migration_disabled":
24916
+ return new SessionMigrationPolicyError();
24917
+ case "artifact_capacity_exceeded":
24918
+ return new SessionArtifactCapacityError(
24919
+ failure.message ?? "Session artifacts exceed the migration capacity.",
24920
+ );
24921
+ case "oversized":
24922
+ return new SessionTranscriptOversizedError(failure.size ?? 0);
24923
+ case "context_too_large":
24924
+ return new SessionContextTooLargeError(failure.size ?? 0);
24925
+ case "migration_busy":
24926
+ return new SessionMigrationBusyError();
24927
+ default:
24928
+ return undefined;
24929
+ }
24930
+ }
24931
+
24602
24932
  static async openNestedManaged(
24603
24933
  filePath: string,
24604
24934
  destination: SessionDestination,
@@ -25065,6 +25395,7 @@ export class SessionManager {
25065
25395
  const sessionFile = manager.#sessionFile;
25066
25396
  if (!sessionFile) throw new Error("fork_transcript_session_file_unavailable");
25067
25397
  const activeManager = manager;
25398
+ manager.#ownershipClaims.checkWrite("fork successor");
25068
25399
  // Publish each already-parsed entry through the staged writer without joining
25069
25400
  // another whole-file string/Buffer. The parse/resident graph is still the
25070
25401
  // compatibility path; retired cold history is never omitted.
@@ -25421,8 +25752,13 @@ export class SessionManager {
25421
25752
  * only), no version-migration rewrite, no session-memory sidecars or legacy
25422
25753
  * sidecar cleanup, and no managed-store adoption. Shared content-addressed blobs
25423
25754
  * and the process resident cache under the agent dir may still be written, as
25424
- * on every load. Session memory stays `"off"`, so transcripts above the eager
25425
- * inspection cap fail with {@link SessionTranscriptOversizedError}.
25755
+ * on every load.
25756
+ *
25757
+ * Above the eager cap (up to {@link BOUNDED_RESUME_TRANSCRIPT_MAX_BYTES}, not on
25758
+ * Windows) it uses the bounded loader, with sidecars in a private owner-only
25759
+ * sidecar-cache instance that close, a failed open and shutdown remove. Only
25760
+ * linear, compacted v5 transcripts without patches qualify; others fail with
25761
+ * {@link SessionTranscriptBoundedOpenError}. Export reads only the validated prefix.
25426
25762
  *
25427
25763
  * The returned manager ({@link isReadOnlySnapshot}) throws `read_only_snapshot` from:
25428
25764
  * transcript appends and edits, rename and star, branch and leaf changes, rewrite,
@@ -25449,6 +25785,19 @@ export class SessionManager {
25449
25785
  storage: SessionStorage = new FileSessionStorage(),
25450
25786
  ): Promise<SessionManager> {
25451
25787
  if (storage instanceof FileSessionStorage) filePath = canonicalizeTrustedPath(filePath);
25788
+ let sourceStat: SessionStorageStat | undefined;
25789
+ try {
25790
+ sourceStat = storage.statSync(filePath);
25791
+ } catch {
25792
+ // A missing or unreadable source is reported by the strict inspection below.
25793
+ }
25794
+ if (
25795
+ sourceStat !== undefined &&
25796
+ sourceStat.size > eagerHydrationMaxBytes() &&
25797
+ storage instanceof FileSessionStorage &&
25798
+ process.platform !== "win32"
25799
+ )
25800
+ return SessionManager.#openBoundedReadOnlySnapshot(filePath, storage, sourceStat);
25452
25801
  const inspected = inspectResumeSessionFile(filePath, storage);
25453
25802
  if ("kind" in inspected) {
25454
25803
  if (inspected.reason === "oversized") throw new SessionTranscriptOversizedError(inspected.size ?? 0);
@@ -25475,11 +25824,83 @@ export class SessionManager {
25475
25824
  return manager;
25476
25825
  }
25477
25826
 
25827
+ /** Bounded first-open without `#initSessionFile` (no breadcrumb, eager fallback, or file creation). */
25828
+ static async #openBoundedReadOnlySnapshot(
25829
+ filePath: string,
25830
+ storage: FileSessionStorage,
25831
+ sourceStat: SessionStorageStat,
25832
+ ): Promise<SessionManager> {
25833
+ const size = sourceStat.size;
25834
+ if (size > BOUNDED_RESUME_TRANSCRIPT_MAX_BYTES) throw new SessionTranscriptOversizedError(size);
25835
+ const inspected = inspectTranscriptHeaderBounded(filePath, storage, BOUNDED_RESUME_TRANSCRIPT_MAX_BYTES);
25836
+ if (!inspected.ok) {
25837
+ if (inspected.error.reason === "oversized")
25838
+ throw new SessionTranscriptOversizedError(inspected.error.size ?? 0);
25839
+ if (inspected.error.reason === "missing")
25840
+ throw Object.assign(new Error(`ENOENT: no such file or directory, open '${filePath}'`), { code: "ENOENT" });
25841
+ throw new Error(`Could not open session: ${inspected.error.reason}`);
25842
+ }
25843
+ const destination = explicitDestination(path.dirname(filePath));
25844
+ const manager = new SessionManager(
25845
+ inspected.inspection.cwd ?? getProjectDir(),
25846
+ destination.directory,
25847
+ true,
25848
+ storage,
25849
+ destination,
25850
+ );
25851
+ manager.#sessionMemoryMode = "enabled";
25852
+ try {
25853
+ const instanceDir = openVerifiedResidentCacheInstanceDir(
25854
+ getSidecarCacheRootDir(manager.#residentCacheProfileAgentDir()),
25855
+ );
25856
+ manager.#snapshotSidecarStore = EphemeralBlobStore.adoptVerifiedDir(instanceDir);
25857
+ // Adopted instances are outside the resident-cache exit sweep.
25858
+ manager.#snapshotSidecarUnregister = postmortem.register("session-snapshot-sidecars", () =>
25859
+ manager.#disposeSnapshotSidecarsBestEffort(),
25860
+ );
25861
+ if (!(await manager.#tryBoundedFirstOpen(filePath)))
25862
+ throw new SessionTranscriptBoundedOpenError(
25863
+ size,
25864
+ manager.#lazyReopenFallbackReason ?? "bounded_first_open_failed",
25865
+ );
25866
+ // The open validated `tail.transcriptSize` bytes of the pre-open inode.
25867
+ const opened = manager.#statSync(filePath);
25868
+ const validatedSize = manager.#sidecarRuntime?.tail.transcriptSize;
25869
+ if (
25870
+ validatedSize === undefined ||
25871
+ opened.dev !== sourceStat.dev ||
25872
+ opened.ino !== sourceStat.ino ||
25873
+ opened.size < validatedSize
25874
+ )
25875
+ throw new SessionTranscriptBoundedOpenError(size, "bounded_first_open_descriptor_changed");
25876
+ manager.#snapshotScanIdentity = { dev: sourceStat.dev, ino: sourceStat.ino, size: validatedSize };
25877
+ manager.buildSessionContext();
25878
+ } catch (error) {
25879
+ manager.#readOnlySnapshot = true;
25880
+ try {
25881
+ await manager.close();
25882
+ } catch (cleanupError) {
25883
+ throw new AggregateError(
25884
+ [toError(error), toError(cleanupError)],
25885
+ "Rejected read-only snapshot cleanup failed",
25886
+ );
25887
+ }
25888
+ throw error;
25889
+ }
25890
+ manager.#readOnlySnapshot = true;
25891
+ return manager;
25892
+ }
25893
+
25478
25894
  /** True for a manager from {@link SessionManager.openReadOnlySnapshot}; see that method for what it refuses. */
25479
25895
  isReadOnlySnapshot(): boolean {
25480
25896
  return this.#readOnlySnapshot;
25481
25897
  }
25482
25898
 
25899
+ /** A read-only snapshot above the eager cap, which reads its source lazily while exporting. */
25900
+ isBoundedReadOnlySnapshot(): boolean {
25901
+ return this.#readOnlySnapshot && this.#snapshotScanIdentity !== undefined;
25902
+ }
25903
+
25483
25904
  /**
25484
25905
  * Hydrate an existing predecessor transcript for recovery without taking any
25485
25906
  * write-capable action. The caller must retain the returned context and use
@@ -25567,6 +25988,7 @@ export class SessionManager {
25567
25988
  "retain-and-throw",
25568
25989
  );
25569
25990
  try {
25991
+ this.#ownershipClaims.checkWrite("recovery promotion");
25570
25992
  if (this.destination.kind === "managed") {
25571
25993
  const store = this.#managedTranscriptStore();
25572
25994
  const sourceName = path.basename(context.identity.canonicalPath);
@@ -25733,14 +26155,8 @@ export class SessionManager {
25733
26155
  sessionMemoryMode,
25734
26156
  );
25735
26157
  if (opened.kind === "error") {
25736
- if (opened.reason === "legacy_migration_disabled") throw new SessionMigrationPolicyError();
25737
- if (opened.reason === "artifact_capacity_exceeded")
25738
- throw new SessionArtifactCapacityError(
25739
- opened.message ?? "Session artifacts exceed the migration capacity.",
25740
- );
25741
- if (opened.reason === "oversized") throw new SessionTranscriptOversizedError(opened.size ?? 0);
25742
- if (opened.reason === "context_too_large") throw new SessionContextTooLargeError(opened.size ?? 0);
25743
- if (opened.reason === "migration_busy") throw new SessionMigrationBusyError();
26158
+ const typed = SessionManager.#typedStrictOpenError(opened);
26159
+ if (typed) throw typed;
25744
26160
  return undefined;
25745
26161
  }
25746
26162
  return opened.manager;