@gajae-code/coding-agent 0.22.2 → 0.22.3

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 (122) hide show
  1. package/CHANGELOG.md +115 -0
  2. package/dist/types/cli/append-system-prompt.d.ts +7 -0
  3. package/dist/types/cli/doctor/session-owners.d.ts +8 -2
  4. package/dist/types/cli/public-command-errors.d.ts +1 -0
  5. package/dist/types/cli/session-picker.d.ts +16 -3
  6. package/dist/types/cli/update-cli.d.ts +0 -2
  7. package/dist/types/cli-ordinary.d.ts +1 -1
  8. package/dist/types/commands/sdk.d.ts +2 -0
  9. package/dist/types/config/machine-identity.d.ts +11 -0
  10. package/dist/types/config/model-registry.d.ts +9 -0
  11. package/dist/types/config/settings-schema.d.ts +84 -4
  12. package/dist/types/lsp/client.d.ts +9 -0
  13. package/dist/types/lsp/types.d.ts +2 -0
  14. package/dist/types/main.d.ts +40 -3
  15. package/dist/types/modes/components/session-held-warning.d.ts +27 -0
  16. package/dist/types/modes/components/session-selector.d.ts +32 -1
  17. package/dist/types/modes/controllers/selector-controller.d.ts +8 -1
  18. package/dist/types/modes/interactive-mode.d.ts +12 -1
  19. package/dist/types/sdk/broker/broker.d.ts +3 -0
  20. package/dist/types/sdk/broker/lifecycle-ledger.d.ts +5 -2
  21. package/dist/types/sdk/broker/lifecycle.d.ts +2 -0
  22. package/dist/types/sdk/broker/session-index.d.ts +11 -0
  23. package/dist/types/sdk/bus/index.d.ts +1 -1
  24. package/dist/types/sdk/host/control/dispatch.d.ts +3 -0
  25. package/dist/types/sdk/host/registration-test-hold.d.ts +7 -0
  26. package/dist/types/sdk/index.d.ts +1 -0
  27. package/dist/types/sdk/lifecycle/service.d.ts +3 -0
  28. package/dist/types/sdk/session-api-key.d.ts +11 -4
  29. package/dist/types/sdk/session-readonly/format.d.ts +7 -0
  30. package/dist/types/sdk/session.d.ts +11 -0
  31. package/dist/types/sdk/startup-capability.d.ts +11 -2
  32. package/dist/types/session/agent-session.d.ts +1 -2
  33. package/dist/types/session/internal/managed-session-storage.d.ts +1 -1
  34. package/dist/types/session/internal/session-claim-set.d.ts +168 -13
  35. package/dist/types/session/session-handover.d.ts +62 -0
  36. package/dist/types/session/session-manager.d.ts +75 -15
  37. package/dist/types/session/session-owner-holder.d.ts +77 -0
  38. package/dist/types/session/session-ownership-mode.d.ts +45 -2
  39. package/dist/types/session/session-ownership.d.ts +25 -29
  40. package/dist/types/session/yield-queue.d.ts +13 -0
  41. package/dist/types/tools/bash.d.ts +7 -0
  42. package/dist/types/tools/browser/deferred-profile-cleanup.d.ts +3 -0
  43. package/dist/types/tools/browser/launch.d.ts +24 -1
  44. package/dist/types/tools/index.d.ts +6 -0
  45. package/dist/types/tools/output-meta.d.ts +17 -11
  46. package/dist/types/tools/tool-result.d.ts +1 -0
  47. package/package.json +9 -7
  48. package/scripts/compile-args.ts +6 -3
  49. package/scripts/run-acp-conformance.ts +36 -10
  50. package/scripts/verify-gjc-sdk-canonicalization.ts +2 -0
  51. package/src/cli/append-system-prompt.ts +34 -0
  52. package/src/cli/auth-broker-cli.ts +5 -1
  53. package/src/cli/doctor/session-owners.ts +8 -2
  54. package/src/cli/public-command-errors.ts +4 -0
  55. package/src/cli/session-picker.ts +57 -7
  56. package/src/cli/update-cli.ts +0 -22
  57. package/src/cli-ordinary.ts +2 -17
  58. package/src/commands/sdk.ts +37 -15
  59. package/src/config/machine-identity.ts +31 -2
  60. package/src/config/model-registry.ts +40 -6
  61. package/src/config/settings-schema.ts +50 -6
  62. package/src/config/settings.ts +65 -3
  63. package/src/gjc-runtime/launch-tmux.ts +4 -1
  64. package/src/internal-urls/docs-index.generated.ts +12 -12
  65. package/src/lsp/client.ts +60 -6
  66. package/src/lsp/index.ts +2 -6
  67. package/src/lsp/types.ts +2 -0
  68. package/src/main.ts +364 -93
  69. package/src/modes/DESIGN.md +36 -0
  70. package/src/modes/acp/acp-agent.ts +215 -31
  71. package/src/modes/components/session-held-warning.ts +62 -0
  72. package/src/modes/components/session-selector.ts +234 -11
  73. package/src/modes/controllers/goal-mode-controller.ts +14 -2
  74. package/src/modes/controllers/selector-controller.ts +192 -3
  75. package/src/modes/interactive-mode.ts +40 -2
  76. package/src/prompts/tools/bash.md +1 -1
  77. package/src/prompts/tools/monitor.md +1 -1
  78. package/src/runtime-mcp/manager.ts +5 -1
  79. package/src/sdk/acp/adapter.ts +2 -0
  80. package/src/sdk/broker/broker.ts +29 -2
  81. package/src/sdk/broker/lifecycle-ledger.ts +9 -7
  82. package/src/sdk/broker/lifecycle.ts +280 -39
  83. package/src/sdk/broker/session-index.ts +24 -0
  84. package/src/sdk/bus/index.ts +1 -0
  85. package/src/sdk/bus/lifecycle-commands.ts +4 -0
  86. package/src/sdk/cli/session-cli.ts +8 -0
  87. package/src/sdk/host/control/dispatch.ts +18 -0
  88. package/src/sdk/host/host.ts +5 -0
  89. package/src/sdk/host/registration-test-hold.ts +51 -0
  90. package/src/sdk/host/session-runtime.test.ts +42 -0
  91. package/src/sdk/index.ts +10 -0
  92. package/src/sdk/lifecycle/service.ts +33 -10
  93. package/src/sdk/prompt-failure.ts +4 -0
  94. package/src/sdk/protocol/operation-registry.ts +7 -1
  95. package/src/sdk/session-api-key.ts +31 -16
  96. package/src/sdk/session-readonly/format.ts +10 -0
  97. package/src/sdk/session-readonly/scope.ts +2 -1
  98. package/src/sdk/session.ts +60 -7
  99. package/src/sdk/startup-capability.ts +27 -2
  100. package/src/session/agent-session.ts +411 -58
  101. package/src/session/internal/managed-session-storage.ts +16 -2
  102. package/src/session/internal/session-claim-set.ts +527 -49
  103. package/src/session/session-handover.ts +283 -0
  104. package/src/session/session-manager.ts +907 -148
  105. package/src/session/session-owner-holder.ts +177 -0
  106. package/src/session/session-ownership-mode.ts +84 -12
  107. package/src/session/session-ownership.ts +115 -89
  108. package/src/session/yield-queue.ts +43 -0
  109. package/src/session-import/provider-service.ts +8 -0
  110. package/src/setup/provider-onboarding.ts +5 -5
  111. package/src/task/executor.ts +2 -0
  112. package/src/tools/bash.ts +10 -0
  113. package/src/tools/browser/deferred-profile-cleanup.ts +20 -0
  114. package/src/tools/browser/launch.ts +133 -14
  115. package/src/tools/browser/registry.ts +72 -19
  116. package/src/tools/index.ts +10 -1
  117. package/src/tools/monitor.ts +267 -29
  118. package/src/tools/output-meta.ts +61 -28
  119. package/src/tools/tool-catalog.generated.ts +2 -2
  120. package/src/tools/tool-result.ts +5 -0
  121. package/dist/types/cli/macos-community-app.d.ts +0 -41
  122. package/src/cli/macos-community-app.ts +0 -1449
@@ -81,6 +81,7 @@ import {
81
81
  type HeaderPatchRecord,
82
82
  isEntryPatchRecord,
83
83
  isHeaderPatchRecord,
84
+ isSessionTranscriptFileName,
84
85
  isSupportedSessionVersion,
85
86
  type MutableSessionHeaderFields,
86
87
  parseStoredSessionEntries,
@@ -182,7 +183,20 @@ import {
182
183
  withManagedSessionTransaction,
183
184
  } from "./internal/managed-session-transaction";
184
185
  import { classifyNativePublishOutcome, formatNativePublishDiagnostic } from "./internal/native-publish-outcome";
185
- import { SessionClaimSet, sessionClaimSetCapability } from "./internal/session-claim-set";
186
+ import {
187
+ attemptSessionClaim,
188
+ claimRefusal,
189
+ claimsUnder,
190
+ probeHeldSessions,
191
+ type ResolvedSessionOwnership,
192
+ resolveSessionOwnership,
193
+ type SessionClaimAttempt,
194
+ type SessionClaimOutcome,
195
+ SessionClaimSet,
196
+ type SessionOwnershipDecision,
197
+ sessionClaimSetCapability,
198
+ withScopedSessionClaim,
199
+ } from "./internal/session-claim-set";
186
200
  import {
187
201
  applyReducerDelta,
188
202
  type BaseAnchor,
@@ -283,6 +297,13 @@ import {
283
297
  toRecapLineageEntry,
284
298
  } from "./recap";
285
299
  import { type SessionManagerReadAccess, sessionManagerReadCapability } from "./session-manager-internal";
300
+ import {
301
+ probeSessionOwners,
302
+ SessionHeldError,
303
+ type SessionOwnerClaim,
304
+ type SessionOwnerProbe,
305
+ SessionOwnershipError,
306
+ } from "./session-ownership";
286
307
  import { isStagedSessionPath, SESSION_STAGING_DIRNAME } from "./session-staging-paths";
287
308
  import type {
288
309
  ManagedSessionSecurityContext,
@@ -1981,9 +2002,52 @@ export type CommittedTranscriptRead =
1981
2002
  | { readonly kind: "absent" }
1982
2003
  | { readonly kind: "unsupported"; readonly reason: string };
1983
2004
 
1984
- /** The managed store's cross-process identity fence; the message is its only channel. */
1985
- function isManagedReplaceIdentityMismatch(error: unknown): boolean {
1986
- return error instanceof Error && error.message === "managed_replace_identity_mismatch";
2005
+ /**
2006
+ * Every spelling the managed store's identity fence refuses a write with, before writing it.
2007
+ * `identity_changed_after_write` (the bytes were written, then the file changed) is not one: it
2008
+ * keeps the uncertain committed-append handling.
2009
+ */
2010
+ const MANAGED_PRE_WRITE_REFUSAL_MESSAGES = new Set([
2011
+ "managed_replace_identity_mismatch",
2012
+ "managed_replace_failed:identity_mismatch",
2013
+ "identity_mismatch",
2014
+ "source_changed",
2015
+ ]);
2016
+
2017
+ /**
2018
+ * The managed store's cross-process identity fence refused this write before writing it: another
2019
+ * writer changed the transcript. The message is its only channel, and only a raw (unwrapped)
2020
+ * refusal counts: a {@link ManagedCommittedMutationError} means the write may have landed (on
2021
+ * macOS a `source_changed` can come from the check after publication), so it stays uncertain.
2022
+ * The managed append and rewrite convert a refusal to {@link ManagedAppendIdentityMismatchError},
2023
+ * the operator stop.
2024
+ */
2025
+ function isPreWriteIdentityRefusal(error: unknown): boolean {
2026
+ if (error instanceof ManagedAppendIdentityMismatchError) return true;
2027
+ if (error instanceof ManagedCommittedMutationError) return false;
2028
+ return error instanceof Error && MANAGED_PRE_WRITE_REFUSAL_MESSAGES.has(error.message);
2029
+ }
2030
+
2031
+ /**
2032
+ * The native write gave up waiting for another writer's hold on the transcript, before writing
2033
+ * anything. A retryable refusal: it neither latches a persistence failure nor stops the writer.
2034
+ */
2035
+ function isTranscriptBusy(error: unknown): boolean {
2036
+ return error instanceof Error && error.message === "transcript_busy";
2037
+ }
2038
+
2039
+ /**
2040
+ * Whether `observed` is the transcript a manager last wrote or bound (`expected`): the same file
2041
+ * object with the same bytes. Metadata-only drift (a touch) is not a change.
2042
+ */
2043
+ function sameManagedTranscript(observed: ManagedFileSnapshot["identity"], expected: ManagedFileIdentity): boolean {
2044
+ return (
2045
+ observed.dev === expected.dev &&
2046
+ observed.ino === expected.ino &&
2047
+ observed.nlink === expected.nlink &&
2048
+ observed.size === expected.size &&
2049
+ (expected.sha256 === undefined || observed.sha256 === expected.sha256)
2050
+ );
1987
2051
  }
1988
2052
 
1989
2053
  /** Title publication has patch evidence, not a conversation-graph entry ID. */
@@ -2185,6 +2249,8 @@ export function reconcileUncertainAppend(input: AppendReconciliationInput): Appe
2185
2249
  */
2186
2250
  function classifyAppendFailure(error: unknown): DurableAppendOutcome {
2187
2251
  if (error instanceof ManagedAppendIdentityMismatchError) return { kind: "not_committed", error };
2252
+ // Enforce's write gate refuses before writing, and the entry is rolled back.
2253
+ if (isOwnershipWriteRefusal(error)) return { kind: "not_committed", error };
2188
2254
  if (error instanceof SessionAppendPersistenceError) {
2189
2255
  if (error.phase === "prior_failure") return { kind: "not_committed", error };
2190
2256
  return { kind: "unknown", id: error.entryId, error };
@@ -2605,6 +2671,30 @@ export const SESSION_LIMIT_RECOVERY_ACTIONS =
2605
2671
  export const SESSION_OVERSIZED_RECOVERY_MESSAGE =
2606
2672
  "The selected session transcript is too large to resume safely. Resume a different session, or remove/archive this transcript after confirming its content is no longer needed.";
2607
2673
 
2674
+ /**
2675
+ * Enforce's write gate refused a write before it wrote anything (another process holds the session,
2676
+ * or its claim failed): not a persistence failure, and nothing to keep in memory.
2677
+ */
2678
+ function isOwnershipWriteRefusal(error: unknown): error is SessionHeldError | SessionOwnershipError {
2679
+ return error instanceof SessionHeldError || error instanceof SessionOwnershipError;
2680
+ }
2681
+
2682
+ type HeaderPatchField = keyof HeaderPatchRecord["patch"];
2683
+ const HEADER_FIELDS = ["cwd", "title", "titleSource", "starred"] as const satisfies readonly HeaderPatchField[];
2684
+ type HeaderField = (typeof HEADER_FIELDS)[number];
2685
+ /** Compile-time: every header patch field is listed above. */
2686
+ const HEADER_FIELDS_COMPLETE: Exclude<HeaderPatchField, HeaderField> extends never ? true : never = true;
2687
+ void HEADER_FIELDS_COMPLETE;
2688
+ interface HeaderFieldValue {
2689
+ readonly present: boolean;
2690
+ readonly value: unknown;
2691
+ }
2692
+ /** A header's committed field values, and the last applied patch per field group (title and titleSource are one). */
2693
+ interface HeaderPatchState {
2694
+ readonly committed: Map<HeaderField, HeaderFieldValue>;
2695
+ readonly lastApplied: Map<"cwd" | "title" | "starred", symbol>;
2696
+ }
2697
+
2608
2698
  export class SessionAppendPersistenceError extends Error {
2609
2699
  readonly phase: SessionAppendPersistenceFailurePhase;
2610
2700
  readonly entryId: string;
@@ -4469,11 +4559,18 @@ interface BoundedTranscriptInspection {
4469
4559
  cwd: string | undefined;
4470
4560
  }
4471
4561
 
4562
+ /**
4563
+ * The header of a transcript, read from its first line. `growing: true` accepts a transcript that a
4564
+ * live holder is appending to: the header line itself never changes, only the size and mtime do.
4565
+ */
4472
4566
  function inspectTranscriptHeaderBounded(
4473
4567
  filePath: string,
4474
4568
  storage: SessionStorage,
4475
4569
  maxBytes: number,
4476
- ): { ok: true; inspection: { cwd: string | undefined } } | { ok: false; error: ResumeTailError } {
4570
+ options: { readonly growing?: boolean } = {},
4571
+ ): { ok: true; inspection: { cwd: string | undefined; sessionId: string } } | { ok: false; error: ResumeTailError } {
4572
+ const stable = (left: SessionStorageStat, right: SessionStorageStat) =>
4573
+ options.growing === true || sameResumeStat(left, right);
4477
4574
  const canonicalPath = resolveEquivalentPath(path.resolve(filePath));
4478
4575
  let before: SessionStorageStat;
4479
4576
  try {
@@ -4488,7 +4585,7 @@ function inspectTranscriptHeaderBounded(
4488
4585
  try {
4489
4586
  const length = Math.min(before.size, BOUNDED_FIRST_OPEN_MAX_LINE_BYTES + 1);
4490
4587
  const range = storage.readRangeSync(canonicalPath, 0, length);
4491
- if (!sameResumeStat(before, range.stat)) return { ok: false, error: { kind: "error", reason: "unstable" } };
4588
+ if (!stable(before, range.stat)) return { ok: false, error: { kind: "error", reason: "unstable" } };
4492
4589
  const newline = range.bytes.indexOf(0x0a);
4493
4590
  if (newline < 0 || newline > BOUNDED_FIRST_OPEN_MAX_LINE_BYTES)
4494
4591
  return { ok: false, error: { kind: "error", reason: "malformed" } };
@@ -4497,8 +4594,11 @@ function inspectTranscriptHeaderBounded(
4497
4594
  if (header.type !== "session" || typeof header.id !== "string")
4498
4595
  return { ok: false, error: { kind: "error", reason: "malformed" } };
4499
4596
  const after = storage.statSync(canonicalPath);
4500
- if (!sameResumeStat(before, after)) return { ok: false, error: { kind: "error", reason: "unstable" } };
4501
- return { ok: true, inspection: { cwd: typeof header.cwd === "string" ? header.cwd : undefined } };
4597
+ if (!stable(before, after)) return { ok: false, error: { kind: "error", reason: "unstable" } };
4598
+ return {
4599
+ ok: true,
4600
+ inspection: { cwd: typeof header.cwd === "string" ? header.cwd : undefined, sessionId: header.id },
4601
+ };
4502
4602
  } catch {
4503
4603
  return { ok: false, error: { kind: "error", reason: "malformed" } };
4504
4604
  }
@@ -7135,8 +7235,7 @@ export function listProjectSessionTranscriptFiles(cwd: string): string[] {
7135
7235
  }
7136
7236
  if (
7137
7237
  entry.isFile() &&
7138
- !entry.name.startsWith(".") &&
7139
- entry.name.endsWith(".jsonl") &&
7238
+ isSessionTranscriptFileName(entry.name) &&
7140
7239
  isProjectSessionTranscriptPath(projectGjcDir, entryPath)
7141
7240
  ) {
7142
7241
  files.push(entryPath);
@@ -8011,8 +8110,10 @@ export class SessionManager {
8011
8110
  }>
8012
8111
  | undefined;
8013
8112
  #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();
8113
+ /** The session claims this manager holds (design §2.5), under the decision its factory made. */
8114
+ readonly #ownershipClaims: SessionClaimSet;
8115
+ /** Per header object: what its transcript last received, for rolling back a refused header patch. */
8116
+ readonly #headerPatchStates = new WeakMap<SessionHeader, HeaderPatchState>();
8016
8117
  #committedIdentityGeneration = 0;
8017
8118
  #committedIdentity: { id: string; file: string | undefined } | undefined;
8018
8119
  #titleMutationRevision = 0;
@@ -8191,6 +8292,8 @@ export class SessionManager {
8191
8292
  #persistenceFenceDepth = 0;
8192
8293
  /** Publication fence counter carried by the mutable `.spill.commit` marker. */
8193
8294
  #commitGen = 0;
8295
+ /** Set only while `forkFrom` builds a fork whose caller switches to it next: no breadcrumb yet. */
8296
+ #deferForkBreadcrumb = false;
8194
8297
  /** Failed staged persistence retains its exact writer and temporary pathname for retryable cleanup. */
8195
8298
  /** Candidate-owned session publication state; set only by staged factories. */
8196
8299
  #stagedPublication:
@@ -8320,10 +8423,12 @@ export class SessionManager {
8320
8423
  private cwd: string,
8321
8424
  private sessionDir: string,
8322
8425
  private readonly persist: boolean,
8426
+ ownership: ResolvedSessionOwnership,
8323
8427
  storage: SessionStorage,
8324
8428
  private destination: SessionDestination = explicitDestination(sessionDir),
8325
8429
  skipEnsureSessionDir = false,
8326
8430
  ) {
8431
+ this.#ownershipClaims = new SessionClaimSet(persist ? ownership : "exempt");
8327
8432
  this.#storage = new Proxy(storage, {
8328
8433
  get: (target, property, receiver) => {
8329
8434
  const value = Reflect.get(target, property, receiver);
@@ -9090,10 +9195,12 @@ export class SessionManager {
9090
9195
  const candidateDestination = managedTransition?.destination ?? this.destination;
9091
9196
  let candidate: SessionManager;
9092
9197
  try {
9198
+ // A loader: its state moves into this manager, whose claim set keeps the restored id.
9093
9199
  candidate = new SessionManager(
9094
9200
  this.cwd,
9095
9201
  this.sessionDir,
9096
9202
  this.persist,
9203
+ "exempt",
9097
9204
  this.#storage,
9098
9205
  candidateDestination,
9099
9206
  true,
@@ -10502,6 +10609,7 @@ export class SessionManager {
10502
10609
  boundedTranscriptAdmitted &&
10503
10610
  (await this.#tryInitSessionFileFromSidecar(resolvedSessionFile, stagedRollbackCandidate))
10504
10611
  ) {
10612
+ if (this.#ownershipClaims.claiming) await this.#ownershipClaims.claim(this.#sessionId);
10505
10613
  if (!stagedRollbackCandidate) this.#writeTerminalBreadcrumb(resolvedSessionFile);
10506
10614
  revalidateStrictResume();
10507
10615
  return;
@@ -10512,6 +10620,7 @@ export class SessionManager {
10512
10620
  boundedTranscriptAdmitted &&
10513
10621
  (await this.#tryBoundedFirstOpen(resolvedSessionFile))
10514
10622
  ) {
10623
+ if (this.#ownershipClaims.claiming) await this.#ownershipClaims.claim(this.#sessionId);
10515
10624
  if (publishedSidecarWasPresent && this.#lazyReopenAttempted && !this.#lazyReopenSucceeded) {
10516
10625
  this.#sessionMemoryMode = "shadow";
10517
10626
  this.#sessionMemoryAutoDisabledReason = "sidecar_reload_failures";
@@ -10580,6 +10689,7 @@ export class SessionManager {
10580
10689
  this.#titleSource = header?.titleSource;
10581
10690
  this.#needsFullRewriteOnNextPersist = migrationApplied;
10582
10691
  this.#commitResidentTextStoreTransition(prepared);
10692
+ if (this.#ownershipClaims.claiming) await this.#ownershipClaims.claim(sessionId);
10583
10693
  if (!stagedRollbackCandidate) this.#writeTerminalBreadcrumb(resolvedSessionFile);
10584
10694
  this.#flushed = true;
10585
10695
  this.#ensuredOnDisk = true;
@@ -10604,6 +10714,8 @@ export class SessionManager {
10604
10714
  this.#applyFreshSessionMetadata(fresh);
10605
10715
  this.#commitResidentTextStoreTransition(prepared);
10606
10716
  this.#retireEphemeralArtifacts();
10717
+ // Before the breadcrumb, the first write: a factory's claim refuses here in enforce.
10718
+ if (this.#ownershipClaims.claiming) await this.#ownershipClaims.claim(fresh.sessionId);
10607
10719
  this.#writeTerminalBreadcrumb(resolvedSessionFile);
10608
10720
  await this.#rewriteFile();
10609
10721
  this.#flushed = true;
@@ -10612,6 +10724,7 @@ export class SessionManager {
10612
10724
 
10613
10725
  #writeTerminalBreadcrumb(sessionFile: string): void {
10614
10726
  if (this.#stagedPublication && !this.#stagedPublication.committed) return;
10727
+ if (this.#deferForkBreadcrumb) return;
10615
10728
  writeTerminalBreadcrumb(this.cwd, sessionFile);
10616
10729
  }
10617
10730
 
@@ -10659,8 +10772,18 @@ export class SessionManager {
10659
10772
  this.#newSessionSync();
10660
10773
  }
10661
10774
 
10662
- /** Switch to a different session file (used for resume and branching). */
10775
+ /**
10776
+ * Switch to a different session file (used for resume and branching). Under enforce, a target
10777
+ * another process holds is refused with {@link SessionHeldError} before anything changes.
10778
+ */
10663
10779
  async setSessionFile(sessionFile: string, options?: { deferEphemeralArtifactRetirement?: boolean }): Promise<void> {
10780
+ return this.withSwitchTargetAdmission(sessionFile, () => this.#setSessionFileAdmitted(sessionFile, options));
10781
+ }
10782
+
10783
+ async #setSessionFileAdmitted(
10784
+ sessionFile: string,
10785
+ options?: { deferEphemeralArtifactRetirement?: boolean },
10786
+ ): Promise<void> {
10664
10787
  using _rotation = this.#ownershipClaims.transition();
10665
10788
  this.#assertArtifactOpen();
10666
10789
  this.#assertRecoveryHydrationWritable();
@@ -10824,6 +10947,8 @@ export class SessionManager {
10824
10947
  if (entries.length > 0) {
10825
10948
  const header = entries.find(entry => entry.type === "session") as SessionHeader | undefined;
10826
10949
  const sessionId = header?.id ?? createSessionId();
10950
+ // The switch target, claimed inside this rotation before its migration or sanitize persist.
10951
+ if (this.#ownershipClaims.claiming) await this.#ownershipClaims.claim(sessionId);
10827
10952
  const migrationApplied = candidateMigrationApplied || migrateToCurrentVersion(entries);
10828
10953
  await resolveBlobRefsInEntries(entries, this.#blobStore);
10829
10954
  const prepared = this.#prepareResidentTextStoreTransition(
@@ -10893,6 +11018,7 @@ export class SessionManager {
10893
11018
  return;
10894
11019
  }
10895
11020
  const fresh = this.#freshSessionState(undefined, resolvedSessionFile);
11021
+ if (this.#ownershipClaims.claiming) await this.#ownershipClaims.claim(fresh.sessionId);
10896
11022
  const prepared = this.#prepareFreshSessionTransition(fresh, "retain-and-throw");
10897
11023
  try {
10898
11024
  await this.#closePersistWriter();
@@ -10972,6 +11098,8 @@ export class SessionManager {
10972
11098
 
10973
11099
  /** Start a new session. Closes any existing writer first. */
10974
11100
  async newSession(options?: NewSessionOptions): Promise<string | undefined> {
11101
+ // One rotation for the prepare's claim and the commit, so the target is never staged outside one.
11102
+ using _rotation = this.#ownershipClaims.transition();
10975
11103
  this.#assertRecoveryHydrationWritable();
10976
11104
  const prepared = await this.prepareNewSession(options);
10977
11105
  try {
@@ -11030,6 +11158,7 @@ export class SessionManager {
11030
11158
  };
11031
11159
  this.#preparedNewSessions.add(stage);
11032
11160
  this.#freezePreparedNewSessionIdentity(stage);
11161
+ if (this.#ownershipClaims.claiming) await this.#ownershipClaims.claim(sessionId);
11033
11162
  return stage;
11034
11163
  }
11035
11164
 
@@ -11262,6 +11391,7 @@ export class SessionManager {
11262
11391
  this.#preparedGraphSourceIds.set(stage, sourceId);
11263
11392
  if (route === "committed") this.#committedGraphSuccessors.add(stage);
11264
11393
  try {
11394
+ if (this.#ownershipClaims.claiming) await this.#ownershipClaims.claim(sessionId);
11265
11395
  await this.copyArtifactsForFork(sourceFile, sessionFile);
11266
11396
  this.#assertPreparedGraphPublicationAllowed(stage);
11267
11397
  this.#ownershipClaims.checkWrite("fork successor", stage.sessionId);
@@ -11359,6 +11489,7 @@ export class SessionManager {
11359
11489
  this.#preparedGraphSourceIds.set(stage, sourceId);
11360
11490
  if (route === "committed") this.#committedGraphSuccessors.add(stage);
11361
11491
  try {
11492
+ if (sessionFile && this.#ownershipClaims.claiming) await this.#ownershipClaims.claim(sessionId);
11362
11493
  if (sessionFile) this.#ownershipClaims.checkWrite("branch successor", stage.sessionId);
11363
11494
  if (proof) {
11364
11495
  await this.#publishCommittedGraphSuccessor(
@@ -11496,6 +11627,8 @@ export class SessionManager {
11496
11627
  }
11497
11628
  this.#preparedNewSessions.delete(stage);
11498
11629
  stage.discarded = true;
11630
+ // The target's claim goes now, or at the end of the transition this discard runs in.
11631
+ this.#ownershipClaims.settle();
11499
11632
  if (this.#preparedNewSessions.size === 0 && this.#fileEntries.length === 0) this.#releaseOwnedManagedAuthority();
11500
11633
  }
11501
11634
 
@@ -11547,6 +11680,15 @@ export class SessionManager {
11547
11680
  : new AggregateError(errors, "Prepared session temporary-file cleanup failed.");
11548
11681
  }
11549
11682
 
11683
+ /**
11684
+ * The decision a scoped claim on another session is made under: this manager's, or, for an
11685
+ * exempt manager (an in-memory TUI's picker still writes other sessions' files), the process's.
11686
+ */
11687
+ #scopedClaimOwnership(): ResolvedSessionOwnership {
11688
+ const ownership = this.#ownershipClaims.ownership;
11689
+ return ownership === "exempt" ? resolveSessionOwnership() : ownership;
11690
+ }
11691
+
11550
11692
  /** Tombstone and exact-delete managed transcripts, detaching the active transcript first. */
11551
11693
  async dropSession(sessionPath: string): Promise<void> {
11552
11694
  // The own-session check below compares unresolved paths, so an aliased spelling of
@@ -11571,17 +11713,28 @@ export class SessionManager {
11571
11713
  const candidate = listing.owned.find(candidate => path.resolve(candidate.path) === requestedPath);
11572
11714
  if (!candidate) throw new Error("Managed session deletion requires exact logical authorization.");
11573
11715
  this.#assertLogicalSessionMutationAllowed(candidate.sessionId, "drop session", true);
11574
- if (this.#sessionFile && path.resolve(this.#sessionFile) === requestedPath) await this.newSession();
11575
- await this.#closePersistWriter();
11576
- this.#assertLogicalSessionMutationAllowed(candidate.sessionId, "drop session", true);
11577
- const deleted = await deleteManagedSessionCandidate(resolved.scope, candidate);
11578
- if (deleted.kind === "error" && deleted.code === "migration_busy") throw new SessionMigrationBusyError();
11579
- if (deleted.kind !== "deleted" && deleted.kind !== "already_deleted")
11580
- throw new Error(`Could not delete managed session: ${deleted.message}`);
11716
+ // Scoped claim (design §1 row 17): taken before the detach, so a held session is never touched.
11717
+ await withScopedSessionClaim(this.#scopedClaimOwnership(), candidate.sessionId, "delete", async () => {
11718
+ if (this.#sessionFile && path.resolve(this.#sessionFile) === requestedPath) await this.newSession();
11719
+ await this.#closePersistWriter();
11720
+ this.#assertLogicalSessionMutationAllowed(candidate.sessionId, "drop session", true);
11721
+ const deleted = await deleteManagedSessionCandidate(resolved.scope, candidate);
11722
+ if (deleted.kind === "error" && deleted.code === "migration_busy") throw new SessionMigrationBusyError();
11723
+ if (deleted.kind !== "deleted" && deleted.kind !== "already_deleted")
11724
+ throw new Error(`Could not delete managed session: ${deleted.message}`);
11725
+ });
11581
11726
  } else {
11582
- if (this.#sessionFile && path.resolve(this.#sessionFile) === requestedPath) await this.newSession();
11583
- await this.#closePersistWriter();
11584
- await this.#storage.deleteSessionWithArtifacts(sessionPath);
11727
+ const drop = async (): Promise<void> => {
11728
+ if (this.#sessionFile && path.resolve(this.#sessionFile) === requestedPath) await this.newSession();
11729
+ await this.#closePersistWriter();
11730
+ await this.#storage.deleteSessionWithArtifacts(sessionPath);
11731
+ };
11732
+ await SessionManager.#deleteUnderHeaderClaim(
11733
+ sessionPath,
11734
+ this.#storage,
11735
+ this.#scopedClaimOwnership(),
11736
+ drop,
11737
+ );
11585
11738
  }
11586
11739
  } catch (err) {
11587
11740
  if (isEnoent(err)) return;
@@ -11715,6 +11868,7 @@ export class SessionManager {
11715
11868
  let transition: PreparedResidentStoreTransition | undefined;
11716
11869
  try {
11717
11870
  this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session", true);
11871
+ if (this.#ownershipClaims.claiming) await this.#ownershipClaims.claim(newSessionId);
11718
11872
  forkArtifactPublication = await this.copyArtifactsForFork(oldSessionFile, newSessionFile);
11719
11873
  this.#assertLogicalSessionMutationAllowed(oldSessionId, "fork session", true);
11720
11874
  this.#ownershipClaims.checkWrite("fork successor", newSessionId);
@@ -12792,6 +12946,10 @@ export class SessionManager {
12792
12946
  destination.fsyncTree();
12793
12947
  };
12794
12948
  try {
12949
+ // The move republishes this session's transcript at its new path, if it has one on disk.
12950
+ // Checked before any publication effect, so the strict seam refuses with nothing moved.
12951
+ if (oldSessionFile !== newSessionFile && this.#storage.existsSync(oldSessionFile))
12952
+ this.#ownershipClaims.checkWrite("session move");
12795
12953
  await this.#runMovePublicationListeners(moveDetails);
12796
12954
  publicationStarted = true;
12797
12955
  } catch (error) {
@@ -12825,6 +12983,11 @@ export class SessionManager {
12825
12983
  };
12826
12984
  managedTranscript = managedSourceStore.readExpected(path.basename(oldSessionFile));
12827
12985
  hadSessionFile = managedTranscript !== null;
12986
+ // The move adopts the copied transcript and rewrites it from resident entries: bytes
12987
+ // this manager never loaded (a writer it cannot see appended them) would be dropped.
12988
+ const persisted = this.#managedPersistExpectedIdentity;
12989
+ if (managedTranscript && persisted && !sameManagedTranscript(managedTranscript.identity, persisted))
12990
+ throw new ManagedAppendIdentityMismatchError(path.basename(oldSessionFile));
12828
12991
  if (managedTranscript) {
12829
12992
  await managedDestinationStore.publishNoReplace(
12830
12993
  path.basename(newSessionFile),
@@ -13235,6 +13398,11 @@ export class SessionManager {
13235
13398
  }
13236
13399
  #recordPersistError(err: unknown): Error {
13237
13400
  const normalized = toError(err);
13401
+ // Enforce's write gate refused the write before it wrote anything: not a persistence failure,
13402
+ // so nothing latches and the next write is judged on its own.
13403
+ if (isOwnershipWriteRefusal(normalized)) return normalized;
13404
+ // So is a bounded wait for another writer that ran out: nothing was written.
13405
+ if (isTranscriptBusy(normalized)) return normalized;
13238
13406
  if (!this.#persistError) this.#persistError = normalized;
13239
13407
  if (!this.#persistErrorReported) {
13240
13408
  this.#persistErrorReported = true;
@@ -13325,6 +13493,8 @@ export class SessionManager {
13325
13493
  return undefined;
13326
13494
  }
13327
13495
  if (this.#persistWriter && this.#persistWriterPath === this.#sessionFile) {
13496
+ // Every append through an open writer, not only its open, passes enforce's write gate.
13497
+ this.#ownershipClaims.refuseWriteIfRefused();
13328
13498
  if (this.#persistWriter.isOpen()) return this.#persistWriter;
13329
13499
  // Cached writer for the current file is mid-close (queued
13330
13500
  // `#closePersistWriterInternal` has flipped `#closing` but not yet
@@ -17300,11 +17470,24 @@ export class SessionManager {
17300
17470
  capBytes: MANAGED_ARTIFACT_MAX_FILE_BYTES,
17301
17471
  });
17302
17472
  }
17473
+ // Another writer changed the transcript under this rewrite: stop as every fence
17474
+ // refusal does.
17475
+ if (isPreWriteIdentityRefusal(err)) throw new ManagedAppendIdentityMismatchError(relativePath);
17303
17476
  throw err;
17304
17477
  }
17305
17478
  const descriptor = store.descriptorExpected(relativePath);
17306
17479
  if (!descriptor) throw new Error("managed_replace_identity_unavailable");
17307
- this.#managedPersistExpectedIdentity = this.#captureManagedPersistIdentity(sessionFile);
17480
+ // The replace returns no identity, so it is read back: only the bytes just written may
17481
+ // become this manager's identity. An append that landed in between is another writer's,
17482
+ // and adopting it would let the next rewrite drop it.
17483
+ const written = this.#captureManagedPersistIdentity(sessionFile);
17484
+ if (
17485
+ written.size !== bytes.byteLength ||
17486
+ written.sha256 !== crypto.createHash("sha256").update(bytes).digest("hex")
17487
+ )
17488
+ // The kept, now stale identity fails every later write closed; undefined would not.
17489
+ throw new ManagedAppendIdentityMismatchError(relativePath);
17490
+ this.#managedPersistExpectedIdentity = written;
17308
17491
  this.#publishCommitMarkerFromCurrentTranscriptSync();
17309
17492
  return;
17310
17493
  }
@@ -17333,6 +17516,10 @@ export class SessionManager {
17333
17516
  throw toError(err);
17334
17517
  }
17335
17518
  });
17519
+ // The whole header is on disk now, including any patch still queued behind this rewrite.
17520
+ const written = entries.find(entry => entry.type === "session") as SessionHeader | undefined;
17521
+ const live = this.#fileEntries.find(entry => entry.type === "session") as SessionHeader | undefined;
17522
+ if (written && live) this.#markHeaderCommitted(live, written, HEADER_FIELDS);
17336
17523
  }
17337
17524
 
17338
17525
  async #writeBoundedDefaultModelSelection(
@@ -17982,6 +18169,19 @@ export class SessionManager {
17982
18169
  this.#releaseRejectedOpenResources();
17983
18170
  }
17984
18171
 
18172
+ /**
18173
+ * Take over a manager its holder dropped after `close()` failed (a bounded fork's swap or rollback):
18174
+ * retry only the writer close while it is retryable, then release its resources and claims, so a
18175
+ * claim lives exactly as long as the writer. Never a full `close()`: that could rewrite a
18176
+ * transcript the holder has already discarded.
18177
+ * @internal
18178
+ */
18179
+ retryCloseInBackground(): void {
18180
+ void this.#retryRejectedOpenWriterCleanup().catch(error => {
18181
+ logger.warn("Dropped session manager writer cleanup failed", { error: toError(error).message });
18182
+ });
18183
+ }
18184
+
17985
18185
  /** Close the persistent writer after flushing all pending data. */
17986
18186
  async close(): Promise<void> {
17987
18187
  try {
@@ -19282,16 +19482,51 @@ export class SessionManager {
19282
19482
  if (!header || this.isSessionStarred() === starred) return false;
19283
19483
  await this.#ensureStarPatchCapability(header);
19284
19484
  this.assertLegacyMutationAllowed("set session starred");
19285
- const previous = header.starred;
19286
- try {
19287
- await this.#appendHeaderPatch({ starred });
19288
- return true;
19289
- } catch (error) {
19290
- if (previous === undefined) delete header.starred;
19291
- else header.starred = previous;
19292
- this.#headerExportRevision++;
19293
- throw error;
19485
+ // A failure puts `starred` back unless a later star patch has set it since (#appendHeaderPatch).
19486
+ await this.#appendHeaderPatch({ starred }, { restoreOnFailure: true });
19487
+ return true;
19488
+ }
19489
+
19490
+ /** Set header fields to the given values (`present: false` removes the field). */
19491
+ #restoreHeaderFields(header: SessionHeader, values: readonly (readonly [HeaderField, HeaderFieldValue])[]): void {
19492
+ const restored = header as unknown as Record<string, unknown>;
19493
+ for (const [field, { present, value }] of values) {
19494
+ if (present) restored[field] = value;
19495
+ else delete restored[field];
19294
19496
  }
19497
+ this.#headerExportRevision++;
19498
+ }
19499
+
19500
+ /**
19501
+ * Record that the transcript now holds `written`'s values for `fields` (default: the fields it
19502
+ * sets), once a header is being tracked; an untracked header is seeded from itself when patched.
19503
+ */
19504
+ #markHeaderCommitted(
19505
+ header: SessionHeader,
19506
+ written: Partial<Record<HeaderField, unknown>>,
19507
+ fields: readonly HeaderField[] = HEADER_FIELDS.filter(field => written[field] !== undefined),
19508
+ ): void {
19509
+ const state = this.#headerPatchStates.get(header);
19510
+ if (!state) return;
19511
+ for (const field of fields)
19512
+ state.committed.set(field, { present: written[field] !== undefined, value: written[field] });
19513
+ }
19514
+
19515
+ /**
19516
+ * What the transcript last received for each header field, and which queued patch last set each
19517
+ * field group in memory; seeded from the header the first time it is patched.
19518
+ */
19519
+ #headerPatchState(header: SessionHeader): HeaderPatchState {
19520
+ let state = this.#headerPatchStates.get(header);
19521
+ if (!state) {
19522
+ const read = (field: HeaderField): HeaderFieldValue => ({
19523
+ present: header[field] !== undefined,
19524
+ value: header[field],
19525
+ });
19526
+ state = { committed: new Map(HEADER_FIELDS.map(field => [field, read(field)])), lastApplied: new Map() };
19527
+ this.#headerPatchStates.set(header, state);
19528
+ }
19529
+ return state;
19295
19530
  }
19296
19531
 
19297
19532
  async setSessionStarredForPicker(session: SessionInfo, starred: boolean): Promise<void> {
@@ -19304,6 +19539,7 @@ export class SessionManager {
19304
19539
  starred,
19305
19540
  this.destination.kind === "explicit" ? this.destination.directory : undefined,
19306
19541
  this.#publishedSharedSession(session.id),
19542
+ this.#scopedClaimOwnership(),
19307
19543
  );
19308
19544
  }
19309
19545
 
@@ -19370,6 +19606,12 @@ export class SessionManager {
19370
19606
  !pickerDiskIdentityMatchesManagedSnapshot(expectedDiskIdentity, snapshot.identity)
19371
19607
  )
19372
19608
  throw new Error("Selected session identity changed. Reopen the session picker.");
19609
+ // The star adopts the transcript it writes as this manager's own. Bytes this manager
19610
+ // never loaded (a writer it cannot see appended them) must not become its own, or its
19611
+ // next full rewrite passes the identity fence and drops them.
19612
+ const persisted = this.destination.kind === "managed" ? this.#managedPersistExpectedIdentity : undefined;
19613
+ if (persisted && !sameManagedTranscript(snapshot.identity, persisted))
19614
+ throw new ManagedAppendIdentityMismatchError(relativePath);
19373
19615
  const content = snapshot.bytes.toString("utf8");
19374
19616
  const newline = content.indexOf("\n");
19375
19617
  const rawHeader: unknown = JSON.parse(newline === -1 ? content : content.slice(0, newline));
@@ -19411,6 +19653,7 @@ export class SessionManager {
19411
19653
  if (!liveHeader) throw new Error("Selected session identity changed. Reopen the session picker.");
19412
19654
  liveHeader.starredPatchVersion = 1;
19413
19655
  applyHeaderPatch(liveHeader, { starred });
19656
+ this.#markHeaderCommitted(liveHeader, { starred }, ["starred"]);
19414
19657
  this.#headerExportRevision++;
19415
19658
  if (this.destination.kind === "managed") {
19416
19659
  this.#adoptManagedPersistIdentity(sessionFile);
@@ -19430,12 +19673,20 @@ export class SessionManager {
19430
19673
  session: SessionInfo,
19431
19674
  starred: boolean,
19432
19675
  explicitSessionDir?: string,
19676
+ ownership?: SessionOwnershipDecision,
19433
19677
  ): Promise<void> {
19434
- await SessionManager.#setPickerCandidateStar(session, starred, explicitSessionDir, false);
19678
+ await SessionManager.#setPickerCandidateStar(
19679
+ session,
19680
+ starred,
19681
+ explicitSessionDir,
19682
+ false,
19683
+ resolveSessionOwnership(ownership),
19684
+ );
19435
19685
  }
19436
19686
 
19437
19687
  /**
19438
- * Star a non-live picker candidate. A `shared` candidate (a predecessor this manager
19688
+ * Star a non-live picker candidate, under a scoped claim of its id (design §1 row 17).
19689
+ * A `shared` candidate (a predecessor this manager
19439
19690
  * published through shared admission) is patched only by an append under its managed
19440
19691
  * session transaction lease, like a shared title; a whole-transcript header upgrade
19441
19692
  * is refused because it would move a live peer's transcript identity.
@@ -19445,6 +19696,7 @@ export class SessionManager {
19445
19696
  starred: boolean,
19446
19697
  explicitSessionDir: string | undefined,
19447
19698
  shared: boolean,
19699
+ ownership: ResolvedSessionOwnership,
19448
19700
  ): Promise<void> {
19449
19701
  if (isStagedSessionPath(session.path)) throw new Error("Staged session paths are not resumable");
19450
19702
  const directory = await fs.promises.realpath(path.dirname(session.path));
@@ -19465,15 +19717,17 @@ export class SessionManager {
19465
19717
  )
19466
19718
  throw new Error("Session is not an authorized managed candidate.");
19467
19719
  }
19468
- if (!shared) {
19469
- SessionManager.#writePickerCandidateStar(session, starred, directory);
19470
- return;
19471
- }
19472
- const locksDirectory = managedSessionTransactionLocksDirectory(directory);
19473
- fs.mkdirSync(locksDirectory, { recursive: true, mode: 0o700 });
19474
- await withManagedSessionTransaction({ locksDirectory, sessionId: session.id }, scope =>
19475
- SessionManager.#writePickerCandidateStar(session, starred, directory, scope),
19476
- );
19720
+ await withScopedSessionClaim(ownership, session.id, starred ? "star" : "unstar", async () => {
19721
+ if (!shared) {
19722
+ SessionManager.#writePickerCandidateStar(session, starred, directory);
19723
+ return;
19724
+ }
19725
+ const locksDirectory = managedSessionTransactionLocksDirectory(directory);
19726
+ fs.mkdirSync(locksDirectory, { recursive: true, mode: 0o700 });
19727
+ await withManagedSessionTransaction({ locksDirectory, sessionId: session.id }, scope =>
19728
+ SessionManager.#writePickerCandidateStar(session, starred, directory, scope),
19729
+ );
19730
+ });
19477
19731
  }
19478
19732
 
19479
19733
  static #writePickerCandidateStar(
@@ -19540,7 +19794,11 @@ export class SessionManager {
19540
19794
  header.starredPatchVersion = 1;
19541
19795
  delete header.starred;
19542
19796
  this.#headerExportRevision++;
19543
- if (!this.persist || !this.#sessionFile || !this.#storage.existsSync(this.#sessionFile)) return;
19797
+ if (!this.persist || !this.#sessionFile || !this.#storage.existsSync(this.#sessionFile)) {
19798
+ // Nothing on disk yet: the transcript is written from this header.
19799
+ this.#markHeaderCommitted(header, header, HEADER_FIELDS);
19800
+ return;
19801
+ }
19544
19802
  this.#needsFullRewriteOnNextPersist = true;
19545
19803
  try {
19546
19804
  await this.#persistPatches([{ type: "header_patch", patch: {} }]);
@@ -19636,7 +19894,10 @@ export class SessionManager {
19636
19894
  // persistence lane had started: the identity fence refused before writing, so
19637
19895
  // the transcript never received this title. Leaving it applied would make the
19638
19896
  // opener show a title the shared transcript does not carry.
19639
- const definitelyNotCommitted = !persistenceStarted || error instanceof ManagedAppendIdentityMismatchError;
19897
+ const definitelyNotCommitted =
19898
+ !persistenceStarted ||
19899
+ error instanceof ManagedAppendIdentityMismatchError ||
19900
+ isOwnershipWriteRefusal(error);
19640
19901
  if (
19641
19902
  definitelyNotCommitted &&
19642
19903
  this.#titleMutationRevision === revision &&
@@ -19822,6 +20083,7 @@ export class SessionManager {
19822
20083
  const header = this.#fileEntries.find(entry => entry.type === "session") as SessionHeader | undefined;
19823
20084
  if (header) {
19824
20085
  applyHeaderPatch(header, patch);
20086
+ this.#markHeaderCommitted(header, patch);
19825
20087
  this.#headerExportRevision++;
19826
20088
  }
19827
20089
  this.#sessionName = sanitized;
@@ -19868,6 +20130,8 @@ export class SessionManager {
19868
20130
  onPersistenceStart?: () => void;
19869
20131
  onPersistenceCheck?: () => void;
19870
20132
  isPersistenceOwner?: () => boolean;
20133
+ /** On any other failure too, put this patch's fields back to what the transcript holds (setSessionStarred). */
20134
+ restoreOnFailure?: boolean;
19871
20135
  },
19872
20136
  ): Promise<void> {
19873
20137
  this.assertLegacyMutationAllowed("append header patch");
@@ -19876,21 +20140,47 @@ export class SessionManager {
19876
20140
  } else this.#assertRecoveryHydrationWritable();
19877
20141
  const header = this.#fileEntries.find(entry => entry.type === "session") as SessionHeader | undefined;
19878
20142
  if (!header) return;
20143
+ // Patches apply in memory now and write later, in queue order. Each field group remembers the
20144
+ // last patch applied to it, and the header remembers what its transcript last received.
20145
+ const state = this.#headerPatchState(header);
20146
+ const token = Symbol("header patch");
20147
+ const fields = HEADER_FIELDS.filter(
20148
+ field => patch[field] !== undefined && (field !== "starred" || header.starredPatchVersion === 1),
20149
+ );
20150
+ const group = (field: HeaderField) => (field === "titleSource" ? "title" : field);
20151
+ for (const field of fields) state.lastApplied.set(group(field), token);
19879
20152
  applyHeaderPatch(header, patch);
19880
20153
  this.#headerExportRevision++;
19881
- const records: HeaderPatchRecord[] =
20154
+ // The star companion record is built at write time, from what the transcript holds then.
20155
+ const records = (): HeaderPatchRecord[] =>
19882
20156
  header.starredPatchVersion === 1 && patch.starred === undefined
19883
20157
  ? [
19884
- { type: "header_patch", patch: { starred: header.starred === true } },
20158
+ { type: "header_patch", patch: { starred: state.committed.get("starred")?.value === true } },
19885
20159
  { type: "header_patch", patch },
19886
20160
  ]
19887
20161
  : [{ type: "header_patch", patch }];
19888
- await this.#persistPatches(
19889
- records,
19890
- options?.onPersistenceStart,
19891
- options?.onPersistenceCheck,
19892
- options?.isPersistenceOwner,
19893
- );
20162
+ try {
20163
+ await this.#persistPatches(
20164
+ records,
20165
+ options?.onPersistenceStart,
20166
+ options?.onPersistenceCheck,
20167
+ options?.isPersistenceOwner,
20168
+ () => this.#markHeaderCommitted(header, patch, fields),
20169
+ );
20170
+ } catch (error) {
20171
+ // An ownership refusal (nothing written), or any failure where the caller asks: put back what
20172
+ // the transcript holds, so no later full rewrite writes a header the transcript never received.
20173
+ // Only fields no later patch has set since: a later patch's own write or failure settles those.
20174
+ // A failure after the append landed finds this patch's value already committed.
20175
+ if ((isOwnershipWriteRefusal(error) || options?.restoreOnFailure) && this.#fileEntries.includes(header)) {
20176
+ const owned = fields.filter(field => state.lastApplied.get(group(field)) === token);
20177
+ this.#restoreHeaderFields(
20178
+ header,
20179
+ owned.map(field => [field, state.committed.get(field) ?? { present: false, value: undefined }] as const),
20180
+ );
20181
+ }
20182
+ throw error;
20183
+ }
19894
20184
  }
19895
20185
 
19896
20186
  #appendManagedRecordsSync(records: readonly (FileEntry | SessionPatchRecord)[]): void {
@@ -19904,33 +20194,48 @@ export class SessionManager {
19904
20194
  const relativePath = path.basename(sessionFile);
19905
20195
  const bytes = Buffer.from(`${records.map(record => JSON.stringify(record)).join("\n")}\n`, "utf8");
19906
20196
  let receipt: ManagedAppendReceipt;
19907
- if (this.#managedPersistExpectedIdentity) {
19908
- try {
19909
- receipt = store.appendExpectedIdentitySync(relativePath, bytes, this.#managedPersistExpectedIdentity);
19910
- } catch (err) {
19911
- const predecessorMissing = store.descriptorExpected(relativePath) === null;
19912
- if (!isEnoent(err) && (!(err instanceof ManagedAppendIdentityMismatchError) || !predecessorMissing))
19913
- throw err;
19914
- // Appending only the new records would create a truncated transcript.
19915
- // Recreate the missing file from the complete resident entry set instead.
19916
- this.#managedPersistExpectedIdentity = undefined;
19917
- this.#rewriteFileSync();
19918
- return;
19919
- }
19920
- } else receipt = store.appendSync(relativePath, bytes);
20197
+ try {
20198
+ if (this.#managedPersistExpectedIdentity) {
20199
+ try {
20200
+ receipt = store.appendExpectedIdentitySync(relativePath, bytes, this.#managedPersistExpectedIdentity);
20201
+ } catch (err) {
20202
+ let predecessorMissing = false;
20203
+ try {
20204
+ predecessorMissing = store.descriptorExpected(relativePath) === null;
20205
+ } catch (descriptorError) {
20206
+ // A transcript still changing under the read is present, not missing.
20207
+ if (!isPreWriteIdentityRefusal(descriptorError)) throw descriptorError;
20208
+ }
20209
+ if (!isEnoent(err) && (!isPreWriteIdentityRefusal(err) || !predecessorMissing)) throw err;
20210
+ // Appending only the new records would create a truncated transcript.
20211
+ // Recreate the missing file from the complete resident entry set instead.
20212
+ this.#managedPersistExpectedIdentity = undefined;
20213
+ this.#rewriteFileSync();
20214
+ return;
20215
+ }
20216
+ } else receipt = store.appendSync(relativePath, bytes);
20217
+ } catch (err) {
20218
+ // The one conversion for a managed append: a refusal before writing (another process
20219
+ // changed the transcript) stops the writer as every fence refusal does. A failure after
20220
+ // the write keeps the uncertain committed-append handling.
20221
+ throw isPreWriteIdentityRefusal(err) ? new ManagedAppendIdentityMismatchError(relativePath) : err;
20222
+ }
19921
20223
  this.#managedPersistExpectedIdentity = receipt.identity;
19922
20224
  this.#publishSessionCommitMarkerSync(receipt.descriptor);
19923
20225
  });
19924
20226
  }
19925
20227
 
20228
+ /** `records` may be built at write time; `onCommitted` runs in queue order once they are on disk. */
19926
20229
  async #persistPatches(
19927
- records: readonly SessionPatchRecord[],
20230
+ recordsOrBuild: readonly SessionPatchRecord[] | (() => readonly SessionPatchRecord[]),
19928
20231
  onPersistenceStart?: () => void,
19929
20232
  onPersistenceCheck?: () => void,
19930
20233
  isPersistenceOwner?: () => boolean,
20234
+ onCommitted?: () => void,
19931
20235
  ): Promise<void> {
19932
20236
  this.assertLegacyMutationAllowed("persist patches");
19933
- if (records.length === 0) return;
20237
+ const recordsNow = () => (typeof recordsOrBuild === "function" ? recordsOrBuild() : recordsOrBuild);
20238
+ if (recordsNow().length === 0) return;
19934
20239
  try {
19935
20240
  this.#refreshManagedTranscriptRelocation();
19936
20241
  } catch (error) {
@@ -19939,6 +20244,8 @@ export class SessionManager {
19939
20244
  }
19940
20245
  if (!this.persist || !this.#sessionFile || !this.#storage.existsSync(this.#sessionFile)) {
19941
20246
  if (this.#coldSidecarActive()) this.#deactivateColdForBranchMutation();
20247
+ // Nothing on disk yet: the transcript is written from memory, patch included.
20248
+ onCommitted?.();
19942
20249
  return;
19943
20250
  }
19944
20251
  let sessionFile = this.#sessionFile;
@@ -19964,13 +20271,14 @@ export class SessionManager {
19964
20271
  !this.#flushed ||
19965
20272
  (header?.version ?? 1) < CURRENT_SESSION_VERSION
19966
20273
  ) {
20274
+ // A full rewrite records the whole header as committed (#writeEntriesAtomicallySync).
19967
20275
  await this.#rewriteFileContents({ check: onPersistenceCheck, start: markPersistenceStart });
19968
20276
  sessionFile = this.#sessionFile!;
19969
20277
  if (publishResumeBreadcrumb) writeTerminalBreadcrumb(this.cwd, sessionFile);
19970
20278
  this.#readOnlyResume = false;
19971
20279
  return;
19972
20280
  }
19973
- const persistedRecords = records.map(record =>
20281
+ const persistedRecords = recordsNow().map(record =>
19974
20282
  record.type === "entry_patch"
19975
20283
  ? (prepareEntryForPersistenceSync(
19976
20284
  materializeResidentEntryForPersistenceSync(
@@ -20007,6 +20315,7 @@ export class SessionManager {
20007
20315
  return true;
20008
20316
  });
20009
20317
  if (written) {
20318
+ if (persisted) onCommitted?.();
20010
20319
  if (rewriteRequired) {
20011
20320
  await this.#rewriteFileContents({ check: onPersistenceCheck, start: markPersistenceStart });
20012
20321
  persisted = true;
@@ -20338,6 +20647,11 @@ export class SessionManager {
20338
20647
  // append. Preserve its type after rolling back the rejected entry.
20339
20648
  if (error instanceof ManagedAppendIdentityMismatchError) throw error;
20340
20649
  if (error instanceof SharedAppendRewriteRequiredError) throw error;
20650
+ // So is enforce's write gate: another process holds the session, or its claim failed
20651
+ // (nothing was written).
20652
+ if (isOwnershipWriteRefusal(error)) throw error;
20653
+ // A busy transcript wrote nothing either; the next write tries again.
20654
+ if (isTranscriptBusy(error)) throw error;
20341
20655
  throw new SessionAppendPersistenceError(
20342
20656
  priorPersistenceError ? "prior_failure" : "current_append",
20343
20657
  residentEntry.id,
@@ -20639,7 +20953,7 @@ export class SessionManager {
20639
20953
  this.#readOnlyResume = wasReadOnly;
20640
20954
  // The lease does not exclude a writer that is not using it; the identity fence is
20641
20955
  // the real check, and a rejection there means the transcript moved.
20642
- if (isManagedReplaceIdentityMismatch(error)) return "stale";
20956
+ if (isPreWriteIdentityRefusal(error)) return "stale";
20643
20957
  throw error;
20644
20958
  }
20645
20959
  const published = await this.captureCommittedSnapshot();
@@ -20766,6 +21080,29 @@ export class SessionManager {
20766
21080
  );
20767
21081
  }
20768
21082
 
21083
+ /**
21084
+ * Refuse, with {@link ManagedAppendIdentityMismatchError}, a destructive control (`/drop`) on a
21085
+ * managed transcript that is no longer the one this manager last wrote or bound: a writer it
21086
+ * cannot see (ownership off, an older binary) changed it, and its entries would go with it.
21087
+ */
21088
+ assertTranscriptUnchanged(): void {
21089
+ if (this.#persistError instanceof ManagedAppendIdentityMismatchError) throw this.#persistError;
21090
+ const expected = this.#managedPersistExpectedIdentity;
21091
+ const sessionFile = this.#sessionFile;
21092
+ if (this.destination.kind !== "managed" || !expected || !sessionFile) return;
21093
+ const relativePath = path.basename(sessionFile);
21094
+ const observed = this.#managedTranscriptStore(sessionFile).captureBoundedAppendExpectation(relativePath);
21095
+ if (!observed) return;
21096
+ if (
21097
+ observed.dev !== expected.dev.toString() ||
21098
+ observed.ino !== expected.ino.toString() ||
21099
+ observed.nlink !== expected.nlink.toString() ||
21100
+ observed.size !== String(expected.size) ||
21101
+ (expected.sha256 !== undefined && observed.sha256 !== expected.sha256)
21102
+ )
21103
+ throw new ManagedAppendIdentityMismatchError(relativePath);
21104
+ }
21105
+
20769
21106
  /** Refuse before caller-side agent, UI, settings, or external effects. */
20770
21107
  assertLegacyMutationAllowed(operation: string): void {
20771
21108
  this.#assertLogicalSessionMutationAllowed(this.#sessionId, operation, true);
@@ -23281,6 +23618,8 @@ export class SessionManager {
23281
23618
  "retain-and-throw",
23282
23619
  );
23283
23620
  try {
23621
+ // Sync: the fresh id is claimed in the background, which covers this write.
23622
+ this.#ownershipClaims.claimInBackground(newSessionId);
23284
23623
  this.#ownershipClaims.checkWrite("branch successor", newSessionId);
23285
23624
  if (this.destination.kind === "managed") {
23286
23625
  this.#managedTranscriptStore(newSessionFile).publishNoReplaceSync(
@@ -23414,10 +23753,20 @@ export class SessionManager {
23414
23753
  cwd: string,
23415
23754
  destinationInput?: SessionDestinationInput,
23416
23755
  storage: SessionStorage = new FileSessionStorage(),
23756
+ ownership?: SessionOwnershipDecision,
23417
23757
  ): SessionManager {
23418
23758
  const destination = destinationFor(cwd, destinationInput, storage);
23419
- const manager = new SessionManager(cwd, destination.directory, true, storage, destination);
23759
+ const manager = new SessionManager(
23760
+ cwd,
23761
+ destination.directory,
23762
+ true,
23763
+ resolveSessionOwnership(ownership),
23764
+ storage,
23765
+ destination,
23766
+ );
23420
23767
  manager.#initNewSession();
23768
+ // Sync factory: the fresh id is claimed in the background; nothing is written before a turn.
23769
+ manager.#ownershipClaims.claimInBackground(manager.#sessionId);
23421
23770
  return manager;
23422
23771
  }
23423
23772
 
@@ -23432,6 +23781,7 @@ export class SessionManager {
23432
23781
  migrationPolicy,
23433
23782
  this.destination,
23434
23783
  expectedIdentity,
23784
+ { ownership: this.#ownershipClaims.ownership },
23435
23785
  );
23436
23786
  }
23437
23787
 
@@ -23448,12 +23798,17 @@ export class SessionManager {
23448
23798
  return preparedPath;
23449
23799
  }
23450
23800
 
23451
- /** Resolve a default-managed candidate through binding validation and copy-retain migration before mutation. */
23801
+ /**
23802
+ * Resolve a default-managed candidate through binding validation and copy-retain migration before mutation.
23803
+ * The migration runs under a scoped claim of the candidate's id. With `readInPlaceWhenHeld` (a fork's
23804
+ * source) a candidate another process holds is not migrated: the caller reads it where it is.
23805
+ */
23452
23806
  static async prepareManagedCandidateForWrite(
23453
23807
  filePath: string,
23454
23808
  migrationPolicy: SessionDirectoryMigrationPolicy,
23455
23809
  destination: SessionDestination,
23456
23810
  expectedIdentity?: ResumeSessionIdentity,
23811
+ options?: { readonly ownership?: SessionOwnershipDecision; readonly readInPlaceWhenHeld?: boolean },
23457
23812
  ): Promise<string> {
23458
23813
  if (!trustedSessionDestinations.has(destination) || destination.kind !== "managed")
23459
23814
  throw new Error("Managed candidate preparation requires a trusted managed destination authority");
@@ -23520,6 +23875,28 @@ export class SessionManager {
23520
23875
  }
23521
23876
  : {}),
23522
23877
  };
23878
+ const owner = resolveSessionOwnership(options?.ownership);
23879
+ const sessionId = inspected.identity.sessionId;
23880
+ if (options?.readInPlaceWhenHeld && claimsUnder(owner)) {
23881
+ // Probe first, so a source held elsewhere is never contended; one this process holds migrates.
23882
+ // A probe that fails (an id no sidecar can name, a directory error) reads as unknown: observe
23883
+ // never refuses on it.
23884
+ let probe: SessionOwnerProbe | undefined;
23885
+ try {
23886
+ probe = (await probeSessionOwners([sessionId])).get(sessionId);
23887
+ } catch (error) {
23888
+ logger.debug("Fork source probe failed; treated as unknown", { error: toError(error).message });
23889
+ }
23890
+ if (probe?.state === "held" && !probe.self) return filePath;
23891
+ }
23892
+ const migrationClaim: SessionClaimAttempt = claimsUnder(owner)
23893
+ ? await attemptSessionClaim(owner, sessionId)
23894
+ : { status: "none" };
23895
+ // A fork's source is read where it is whenever it cannot be claimed for its migration: held
23896
+ // elsewhere, or a claim enforce would refuse (a failed one). Any other caller is refused.
23897
+ const refusal = claimRefusal(owner, sessionId, migrationClaim);
23898
+ if (options?.readInPlaceWhenHeld && (migrationClaim.status === "held" || refusal)) return filePath;
23899
+ if (refusal) throw refusal;
23523
23900
  let opened: ManagedOpenCandidateResult;
23524
23901
  try {
23525
23902
  opened = await openManagedCandidateForWrite(
@@ -23534,6 +23911,8 @@ export class SessionManager {
23534
23911
  if (error instanceof Error && error.message.startsWith("Managed root authority changed"))
23535
23912
  managedDestinationStore.assertBound();
23536
23913
  throw error;
23914
+ } finally {
23915
+ if (migrationClaim.status === "claimed") migrationClaim.claim.release();
23537
23916
  }
23538
23917
  if (opened.kind === "error") {
23539
23918
  managedDestinationStore.assertBound();
@@ -23670,6 +24049,9 @@ export class SessionManager {
23670
24049
  fresh.header.title = sourceHeader.title;
23671
24050
  fresh.header.titleSource = sourceHeader.titleSource;
23672
24051
  if (!fresh.sessionFile) return false;
24052
+ if (this.#ownershipClaims.claiming) await this.#ownershipClaims.claim(fresh.sessionId);
24053
+ // The fork's transcript is published before this manager binds any id, so the check names it.
24054
+ this.#ownershipClaims.checkWrite("fork successor", fresh.sessionId);
23673
24055
  const staged = this.#storage.openStagedWriter(fresh.sessionFile, {
23674
24056
  securityContext: this.destination.kind === "managed" ? this.destination.securityContext : undefined,
23675
24057
  });
@@ -23747,7 +24129,7 @@ export class SessionManager {
23747
24129
  }
23748
24130
  }
23749
24131
  await this.#initSessionFile(fresh.sessionFile);
23750
- writeTerminalBreadcrumb(this.cwd, fresh.sessionFile);
24132
+ if (!this.#deferForkBreadcrumb) writeTerminalBreadcrumb(this.cwd, fresh.sessionFile);
23751
24133
  return true;
23752
24134
  } catch (error) {
23753
24135
  try {
@@ -23870,6 +24252,9 @@ export class SessionManager {
23870
24252
  fresh.header.title = sourceHeader.title;
23871
24253
  fresh.header.titleSource = sourceHeader.titleSource;
23872
24254
  if (!fresh.sessionFile) return undefined;
24255
+ if (this.#ownershipClaims.claiming) await this.#ownershipClaims.claim(fresh.sessionId);
24256
+ // The fork's transcript is published before this manager binds any id, so the check names it.
24257
+ this.#ownershipClaims.checkWrite("fork successor", fresh.sessionId);
23873
24258
  const staged = snapshot.storage.openStagedWriter(fresh.sessionFile, {
23874
24259
  securityContext: this.destination.kind === "managed" ? this.destination.securityContext : undefined,
23875
24260
  });
@@ -23951,11 +24336,21 @@ export class SessionManager {
23951
24336
  storage: SessionStorage = new FileSessionStorage(),
23952
24337
  migrationPolicy: SessionDirectoryMigrationPolicy = "copy-retain",
23953
24338
  sessionMemoryMode: SessionMemoryMode = "shadow",
24339
+ ownership?: SessionOwnershipDecision,
24340
+ options: {
24341
+ /**
24342
+ * `false` when the caller switches to the fork next: the switch moves the terminal
24343
+ * breadcrumb once it lands, so an abandoned fork never becomes `--continue`'s target.
24344
+ */
24345
+ readonly writeBreadcrumb?: boolean;
24346
+ } = {},
23954
24347
  ): Promise<SessionManager> {
24348
+ const owner = resolveSessionOwnership(ownership);
23955
24349
  const destination = destinationFor(cwd, destinationInput, storage);
23956
24350
  const dir = destination.directory;
23957
- const manager = new SessionManager(cwd, dir, true, storage, destination);
24351
+ const manager = new SessionManager(cwd, dir, true, owner, storage, destination);
23958
24352
  manager.#sessionMemoryMode = sessionMemoryMode;
24353
+ manager.#deferForkBreadcrumb = options.writeBreadcrumb === false;
23959
24354
  let managedSourcePath = sourcePath;
23960
24355
  if (destination.kind === "managed" && storage instanceof FileSessionStorage) {
23961
24356
  const resolvedSource = path.resolve(sourcePath);
@@ -23964,10 +24359,13 @@ export class SessionManager {
23964
24359
  pathIsWithin(sessionsRoot, resolvedSource) &&
23965
24360
  path.dirname(resolvedSource) !== path.resolve(destination.directory)
23966
24361
  ) {
24362
+ // The source is migrated only under a scoped claim, and read in place when another process holds it.
23967
24363
  managedSourcePath = await SessionManager.prepareManagedCandidateForWrite(
23968
24364
  sourcePath,
23969
24365
  migrationPolicy,
23970
24366
  destination,
24367
+ undefined,
24368
+ { ownership: owner, readInPlaceWhenHeld: true },
23971
24369
  );
23972
24370
  }
23973
24371
  }
@@ -24012,8 +24410,10 @@ export class SessionManager {
24012
24410
  if (
24013
24411
  inspected.ok &&
24014
24412
  (await manager.#tryForkFromBoundedSource(managedSourcePath, inspected.inspection.identity))
24015
- )
24413
+ ) {
24414
+ manager.#deferForkBreadcrumb = false;
24016
24415
  return manager;
24416
+ }
24017
24417
  }
24018
24418
  if (manager.#boundedManagedSource && sourceSize <= eagerHydrationMaxBytes()) {
24019
24419
  const boundedSource = manager.#boundedManagedSource;
@@ -24062,9 +24462,17 @@ export class SessionManager {
24062
24462
  manager.#applyFreshSessionMetadata(fresh);
24063
24463
  manager.#commitResidentTextStoreTransition(transition);
24064
24464
  manager.#retireEphemeralArtifacts();
24065
- if (fresh.sessionFile) writeTerminalBreadcrumb(manager.cwd, fresh.sessionFile);
24465
+ if (fresh.sessionFile && !manager.#deferForkBreadcrumb) writeTerminalBreadcrumb(manager.cwd, fresh.sessionFile);
24066
24466
  manager.sanitizeLoadedOpenAIResponsesReplayMetadata();
24067
- await manager.#rewriteFile();
24467
+ if (manager.#ownershipClaims.claiming) await manager.#ownershipClaims.claim(fresh.sessionId);
24468
+ try {
24469
+ await manager.#rewriteFile();
24470
+ } catch (error) {
24471
+ // A failed fork keeps no claim: the lock goes with the manager that never published.
24472
+ manager.#ownershipClaims.releaseAll();
24473
+ throw error;
24474
+ }
24475
+ manager.#deferForkBreadcrumb = false;
24068
24476
  return manager;
24069
24477
  }
24070
24478
 
@@ -24091,7 +24499,15 @@ export class SessionManager {
24091
24499
  if (path.resolve(stagedSessionFile) === path.resolve(finalPath))
24092
24500
  throw new Error("Staged session path collides with final transcript");
24093
24501
 
24094
- const manager = new SessionManager(getProjectDir(), stagingDir, true, storage, finalDestination);
24502
+ const manager = new SessionManager(
24503
+ getProjectDir(),
24504
+ stagingDir,
24505
+ true,
24506
+ // Subagent children claim nothing yet (single-owner design §13 L2: per-child claims deferred).
24507
+ "exempt",
24508
+ storage,
24509
+ finalDestination,
24510
+ );
24095
24511
  manager.#stagedPublication = {
24096
24512
  finalSessionFile: finalPath,
24097
24513
  stagedSessionFile,
@@ -24142,7 +24558,15 @@ export class SessionManager {
24142
24558
  if (path.resolve(stagedSessionFile) === path.resolve(finalPath))
24143
24559
  throw new Error("Staged session path collides with final transcript");
24144
24560
  const stagedDestination = SessionManager.nestedManagedDestination(stagingStore, stagedDir);
24145
- const manager = new SessionManager(getProjectDir(), stagedDir, true, storage, stagedDestination);
24561
+ const manager = new SessionManager(
24562
+ getProjectDir(),
24563
+ stagedDir,
24564
+ true,
24565
+ // Subagent children claim nothing yet (single-owner design §13 L2: per-child claims deferred).
24566
+ "exempt",
24567
+ storage,
24568
+ stagedDestination,
24569
+ );
24146
24570
  manager.#stagedPublication = {
24147
24571
  finalSessionFile: finalPath,
24148
24572
  stagedSessionFile,
@@ -24472,6 +24896,117 @@ export class SessionManager {
24472
24896
  storage: SessionStorage = new FileSessionStorage(),
24473
24897
  migrationPolicy: SessionDirectoryMigrationPolicy = "copy-retain",
24474
24898
  sessionMemoryMode: SessionMemoryMode = "shadow",
24899
+ ownership?: SessionOwnershipDecision,
24900
+ ): Promise<SessionManager> {
24901
+ const owner = resolveSessionOwnership(ownership);
24902
+ const admission = await SessionManager.#admitExistingTranscript(owner, filePath, storage);
24903
+ try {
24904
+ return await SessionManager.#openAdmitted(
24905
+ filePath,
24906
+ destinationInput,
24907
+ storage,
24908
+ migrationPolicy,
24909
+ sessionMemoryMode,
24910
+ owner,
24911
+ );
24912
+ } finally {
24913
+ // The manager took its own share of the claim; this one only covered the open.
24914
+ admission?.release();
24915
+ }
24916
+ }
24917
+
24918
+ /**
24919
+ * Enforce's claim of an existing transcript's header id, taken before `open` reads, builds or
24920
+ * writes anything for it (5a): the bounded paths build session-memory sidecars, and every path may
24921
+ * sanitize or write the breadcrumb, before the manager's own claim. That claim then shares this
24922
+ * one. Nothing outside enforce, and nothing for a transcript whose header cannot be read here: a
24923
+ * missing one gets a fresh id, claimed where it is minted; an unreadable one fails in the open.
24924
+ */
24925
+ static async #admitExistingTranscript(
24926
+ owner: ResolvedSessionOwnership,
24927
+ filePath: string,
24928
+ storage: SessionStorage,
24929
+ ): Promise<SessionOwnerClaim | undefined> {
24930
+ if (owner === "exempt" || owner.mode !== "enforce" || !(storage instanceof FileSessionStorage)) return undefined;
24931
+ // A holder appending to the transcript changes its size, never its header.
24932
+ const header = inspectTranscriptHeaderBounded(filePath, storage, BOUNDED_RESUME_TRANSCRIPT_MAX_BYTES, {
24933
+ growing: true,
24934
+ });
24935
+ if (!header.ok) return undefined;
24936
+ const sessionId = header.inspection.sessionId;
24937
+ const attempt = await attemptSessionClaim(owner, sessionId, undefined, { admission: true });
24938
+ const refusal = claimRefusal(owner, sessionId, attempt);
24939
+ if (refusal) throw refusal;
24940
+ return attempt.status === "claimed" ? attempt.claim : undefined;
24941
+ }
24942
+
24943
+ /** The surface and mode this manager claims with, for a claim taken on its behalf (Continue here). */
24944
+ get ownershipDecision(): ResolvedSessionOwnership {
24945
+ return this.#ownershipClaims.ownership;
24946
+ }
24947
+
24948
+ /**
24949
+ * Enforce's admission of a switch target (design §1 rows 3 and 9): `open`'s pre-claim of the
24950
+ * target's header id, taken before the switch emits any event or begins its transition. It throws
24951
+ * {@link SessionHeldError} for a session another process holds. The returned claim is an
24952
+ * admission: the rotation's own claim of the target releases it when it lands, so the switched-to
24953
+ * session never has it as a second holder; the caller still releases it on every path (a no-op
24954
+ * by then), which covers a switch that ends before it claims. `undefined`, with nothing awaited,
24955
+ * outside enforce, so other modes keep their ordering.
24956
+ */
24957
+ switchTargetAdmission(sessionFile: string): Promise<SessionOwnerClaim | undefined> | undefined {
24958
+ const owner = this.#ownershipClaims.ownership;
24959
+ if (owner === "exempt" || owner.mode !== "enforce") return undefined;
24960
+ return SessionManager.#admitExistingTranscript(owner, sessionFile, this.#storage);
24961
+ }
24962
+
24963
+ /**
24964
+ * Run `run` under {@link switchTargetAdmission}'s claim of `sessionFile`, released once `run`
24965
+ * settles. Outside enforce `run` is called at once, with nothing awaited before it.
24966
+ */
24967
+ withSwitchTargetAdmission<T>(sessionFile: string, run: () => Promise<T>): Promise<T> {
24968
+ const admission = this.switchTargetAdmission(sessionFile);
24969
+ return admission ? SessionManager.#runAdmitted(admission, run) : run();
24970
+ }
24971
+
24972
+ static async #runAdmitted<T>(admission: Promise<SessionOwnerClaim | undefined>, run: () => Promise<T>): Promise<T> {
24973
+ const claim = await admission;
24974
+ try {
24975
+ return await run();
24976
+ } finally {
24977
+ claim?.release();
24978
+ }
24979
+ }
24980
+
24981
+ /**
24982
+ * Enforce's refusal for the session in an existing transcript that another process holds, from a
24983
+ * probe of its header id: what an interactive launch warns about before it opens or forks
24984
+ * (design §3.1). `undefined`, with nothing awaited, outside enforce.
24985
+ */
24986
+ static probeHeldTranscript(
24987
+ filePath: string,
24988
+ ownership?: SessionOwnershipDecision,
24989
+ ): Promise<SessionHeldError | undefined> | undefined {
24990
+ const owner = resolveSessionOwnership(ownership);
24991
+ if (owner === "exempt" || owner.mode !== "enforce") return undefined;
24992
+ const header = inspectTranscriptHeaderBounded(
24993
+ filePath,
24994
+ new FileSessionStorage(),
24995
+ BOUNDED_RESUME_TRANSCRIPT_MAX_BYTES,
24996
+ { growing: true },
24997
+ );
24998
+ if (!header.ok) return undefined;
24999
+ const sessionId = header.inspection.sessionId;
25000
+ return probeHeldSessions(owner, [sessionId])?.then(held => held.get(sessionId));
25001
+ }
25002
+
25003
+ static async #openAdmitted(
25004
+ filePath: string,
25005
+ destinationInput: SessionDestinationInput | undefined,
25006
+ storage: SessionStorage,
25007
+ migrationPolicy: SessionDirectoryMigrationPolicy,
25008
+ sessionMemoryMode: SessionMemoryMode,
25009
+ owner: ResolvedSessionOwnership,
24475
25010
  ): Promise<SessionManager> {
24476
25011
  const destination =
24477
25012
  destinationInput === undefined
@@ -24484,7 +25019,14 @@ export class SessionManager {
24484
25019
  path.dirname(path.resolve(filePath)) !== path.resolve(destination.directory) ||
24485
25020
  isStagedSessionPath(filePath)
24486
25021
  )
24487
- return SessionManager.#openUnserialized(filePath, destination, storage, migrationPolicy, sessionMemoryMode);
25022
+ return SessionManager.#openUnserialized(
25023
+ filePath,
25024
+ destination,
25025
+ storage,
25026
+ migrationPolicy,
25027
+ sessionMemoryMode,
25028
+ owner,
25029
+ );
24488
25030
 
24489
25031
  const store = managedStoreFromContext(destination.securityContext, destination.directory);
24490
25032
  let constructed: SessionManager | undefined;
@@ -24507,6 +25049,7 @@ export class SessionManager {
24507
25049
  storage,
24508
25050
  migrationPolicy,
24509
25051
  sessionMemoryMode,
25052
+ owner,
24510
25053
  );
24511
25054
  }
24512
25055
  let sessionId: string;
@@ -24556,6 +25099,7 @@ export class SessionManager {
24556
25099
  storage,
24557
25100
  migrationPolicy,
24558
25101
  sessionMemoryMode,
25102
+ owner,
24559
25103
  );
24560
25104
  constructed = manager;
24561
25105
  scope.assertOwned();
@@ -24584,6 +25128,7 @@ export class SessionManager {
24584
25128
  storage: SessionStorage,
24585
25129
  migrationPolicy: SessionDirectoryMigrationPolicy,
24586
25130
  sessionMemoryMode: SessionMemoryMode,
25131
+ owner: ResolvedSessionOwnership,
24587
25132
  ): Promise<SessionManager> {
24588
25133
  if (isStagedSessionPath(filePath)) throw new Error("Staged session paths are not resumable");
24589
25134
  const destination =
@@ -24617,18 +25162,8 @@ export class SessionManager {
24617
25162
  if (!boundedAdmission) {
24618
25163
  const inspected = inspectResumeSessionFile(filePath, storage);
24619
25164
  if ("kind" in inspected) {
24620
- if (inspected.reason === "missing") {
24621
- const manager = new SessionManager(
24622
- getProjectDir(),
24623
- destination.directory,
24624
- true,
24625
- storage,
24626
- destination,
24627
- );
24628
- manager.#sessionMemoryMode = sessionMemoryMode;
24629
- await manager.#initSessionFile(filePath, true);
24630
- return manager;
24631
- }
25165
+ if (inspected.reason === "missing")
25166
+ return await SessionManager.#openMissing(filePath, destination, owner, storage, sessionMemoryMode);
24632
25167
  if (inspected.reason === "oversized") throw new SessionTranscriptOversizedError(inspected.size ?? 0);
24633
25168
  throw new Error(`Could not open session: ${inspected.reason}`);
24634
25169
  }
@@ -24637,17 +25172,25 @@ export class SessionManager {
24637
25172
  header.cwd || getProjectDir(),
24638
25173
  destination.directory,
24639
25174
  true,
25175
+ owner,
24640
25176
  storage,
24641
25177
  destination,
24642
25178
  );
24643
25179
  manager.#sessionMemoryMode = sessionMemoryMode;
24644
- await manager.#hydrateExistingSession(
24645
- filePath,
24646
- inspected.entries,
24647
- inspected.migrationApplied,
24648
- inspected.identity.sha256,
24649
- );
24650
- await manager.#sanitizeLoadedOpenAIResponsesReplayMetadataAndPersist();
25180
+ if (manager.#ownershipClaims.claiming) await manager.#ownershipClaims.claim(header.id);
25181
+ try {
25182
+ await manager.#hydrateExistingSession(
25183
+ filePath,
25184
+ inspected.entries,
25185
+ inspected.migrationApplied,
25186
+ inspected.identity.sha256,
25187
+ );
25188
+ await manager.#sanitizeLoadedOpenAIResponsesReplayMetadataAndPersist();
25189
+ } catch (error) {
25190
+ // A failed open keeps no claim: the lock goes with the manager that never opened.
25191
+ manager.#ownershipClaims.releaseAll();
25192
+ throw error;
25193
+ }
24651
25194
  manager.buildSessionContext();
24652
25195
  return manager;
24653
25196
  }
@@ -24655,12 +25198,8 @@ export class SessionManager {
24655
25198
  ? { ok: true as const, inspection: { cwd: (strictSmallInspection.entries[0] as SessionHeader).cwd } }
24656
25199
  : inspectTranscriptHeaderBounded(filePath, storage, BOUNDED_RESUME_TRANSCRIPT_MAX_BYTES);
24657
25200
  if (!inspected.ok) {
24658
- if (inspected.error.reason === "missing") {
24659
- const manager = new SessionManager(getProjectDir(), destination.directory, true, storage, destination);
24660
- manager.#sessionMemoryMode = sessionMemoryMode;
24661
- await manager.#initSessionFile(filePath, true);
24662
- return manager;
24663
- }
25201
+ if (inspected.error.reason === "missing")
25202
+ return await SessionManager.#openMissing(filePath, destination, owner, storage, sessionMemoryMode);
24664
25203
  if (inspected.error.reason === "oversized")
24665
25204
  throw new SessionTranscriptOversizedError(inspected.error.size ?? 0);
24666
25205
  throw new Error(`Could not open session: ${inspected.error.reason}`);
@@ -24669,6 +25208,7 @@ export class SessionManager {
24669
25208
  inspected.inspection.cwd ?? getProjectDir(),
24670
25209
  destination.directory,
24671
25210
  true,
25211
+ owner,
24672
25212
  storage,
24673
25213
  destination,
24674
25214
  );
@@ -24738,6 +25278,7 @@ export class SessionManager {
24738
25278
  getProjectDir(),
24739
25279
  destination.directory,
24740
25280
  true,
25281
+ owner,
24741
25282
  storage,
24742
25283
  destination,
24743
25284
  true,
@@ -24753,6 +25294,9 @@ export class SessionManager {
24753
25294
  manager.#commitResidentTextStoreTransition(prepared, false);
24754
25295
  manager.#retireEphemeralArtifacts();
24755
25296
  const content = `${JSON.stringify(prepareEntryForPersistenceSync(fresh.header, manager.#blobStore))}\n`;
25297
+ if (manager.#ownershipClaims.claiming) await manager.#ownershipClaims.claim(fresh.sessionId);
25298
+ managedInspectionStore.assertBound();
25299
+ manager.#ownershipClaims.checkWrite("open create");
24756
25300
  managedInspectionStore.publishNoReplaceSync(path.basename(filePath), Buffer.from(content, "utf8"));
24757
25301
  const publishedTranscript = managedInspectionStore.readExpected(path.basename(filePath));
24758
25302
  if (publishedTranscript?.bytes?.equals(Buffer.from(content, "utf8")) !== true)
@@ -24811,7 +25355,7 @@ export class SessionManager {
24811
25355
  }
24812
25356
 
24813
25357
  if (managedResumeBounded && sameManagedDirectory) {
24814
- const manager = new SessionManager(getProjectDir(), destination.directory, true, storage, destination);
25358
+ const manager = new SessionManager(getProjectDir(), destination.directory, true, owner, storage, destination);
24815
25359
  manager.#sessionMemoryMode = sessionMemoryMode;
24816
25360
  try {
24817
25361
  await manager.#initSessionFile(
@@ -24882,12 +25426,8 @@ export class SessionManager {
24882
25426
  managedInspectionStore = undefined;
24883
25427
  const inspected = inspectResumeSessionFile(filePath, storage);
24884
25428
  if ("kind" in inspected) {
24885
- if (inspected.reason === "missing") {
24886
- const manager = new SessionManager(getProjectDir(), destination.directory, true, storage, destination);
24887
- manager.#sessionMemoryMode = sessionMemoryMode;
24888
- await manager.#initSessionFile(filePath, true);
24889
- return manager;
24890
- }
25429
+ if (inspected.reason === "missing")
25430
+ return await SessionManager.#openMissing(filePath, destination, owner, storage, sessionMemoryMode);
24891
25431
  if (inspected.reason === "oversized") throw new SessionTranscriptOversizedError(inspected.size ?? 0);
24892
25432
  if (inspected.reason === "context_too_large") throw new SessionContextTooLargeError(inspected.size ?? 0);
24893
25433
  throw new Error(`Could not open session: ${inspected.reason}`);
@@ -24898,6 +25438,7 @@ export class SessionManager {
24898
25438
  storage,
24899
25439
  migrationPolicy,
24900
25440
  sessionMemoryMode,
25441
+ owner,
24901
25442
  );
24902
25443
  if (opened.kind === "error") {
24903
25444
  throw SessionManager.#typedStrictOpenError(opened) ?? new Error(`Could not open session: ${opened.reason}`);
@@ -24905,6 +25446,37 @@ export class SessionManager {
24905
25446
  return opened.manager;
24906
25447
  }
24907
25448
 
25449
+ /**
25450
+ * `open` of a missing path: a fresh session, claimed before its header is written. A failed
25451
+ * open keeps no claim: if the header write throws, the lock goes with the manager that never opened.
25452
+ */
25453
+ /**
25454
+ * A missing transcript at `filePath`: a fresh session created there. Enforce's refusal of its
25455
+ * claim leaves nothing behind, not even the session directory, when this open created it.
25456
+ */
25457
+ static async #openMissing(
25458
+ filePath: string,
25459
+ destination: SessionDestination,
25460
+ owner: ResolvedSessionOwnership,
25461
+ storage: SessionStorage,
25462
+ sessionMemoryMode: SessionMemoryMode,
25463
+ ): Promise<SessionManager> {
25464
+ const directory = destination.directory;
25465
+ const createdHere = storage instanceof FileSessionStorage && !fs.existsSync(directory);
25466
+ const manager = new SessionManager(getProjectDir(), directory, true, owner, storage, destination);
25467
+ manager.#sessionMemoryMode = sessionMemoryMode;
25468
+ const created = createdHere ? await fs.promises.lstat(directory, { bigint: true }) : undefined;
25469
+ try {
25470
+ await manager.#initSessionFile(filePath, true);
25471
+ } catch (error) {
25472
+ manager.#ownershipClaims.releaseAll();
25473
+ if (error instanceof SessionHeldError || error instanceof SessionOwnershipError)
25474
+ await removeCreatedDirectoryIfEmpty(directory, created && { dev: created.dev, ino: created.ino });
25475
+ throw error;
25476
+ }
25477
+ return manager;
25478
+ }
25479
+
24908
25480
  /**
24909
25481
  * The typed error for a strict-open failure whose reason the operator can act on, or
24910
25482
  * `undefined` for a reason the caller handles itself (a generic open error, or skipping
@@ -24937,6 +25509,8 @@ export class SessionManager {
24937
25509
  cwdOverride?: string,
24938
25510
  sessionMemoryMode: SessionMemoryMode = "shadow",
24939
25511
  ): Promise<SessionManager> {
25512
+ // A subagent child claims nothing yet (single-owner design §13 L2: per-child claims deferred).
25513
+ const owner: ResolvedSessionOwnership = "exempt";
24940
25514
  if (destination.kind !== "managed" || !trustedSessionDestinations.has(destination))
24941
25515
  throw new Error("Nested managed session authority is unavailable");
24942
25516
  const resolved = path.resolve(filePath);
@@ -24960,6 +25534,7 @@ export class SessionManager {
24960
25534
  cwdOverride ? path.resolve(cwdOverride) : getProjectDir(),
24961
25535
  destination.directory,
24962
25536
  true,
25537
+ owner,
24963
25538
  storage,
24964
25539
  destination,
24965
25540
  );
@@ -25033,7 +25608,7 @@ export class SessionManager {
25033
25608
  header && cwdOverride && resolveEquivalentPath(header.cwd) !== resolveEquivalentPath(sessionCwd),
25034
25609
  );
25035
25610
  if (header && cwdChanged) header.cwd = sessionCwd;
25036
- const manager = new SessionManager(sessionCwd, destination.directory, true, storage, destination);
25611
+ const manager = new SessionManager(sessionCwd, destination.directory, true, owner, storage, destination);
25037
25612
  manager.#sessionMemoryMode = sessionMemoryMode;
25038
25613
  try {
25039
25614
  let transcriptChanged = false;
@@ -25140,12 +25715,49 @@ export class SessionManager {
25140
25715
  }
25141
25716
  }
25142
25717
 
25143
- /** Delete an authorized managed or project-local picker candidate. */
25144
- static async deleteManagedCandidate(sessionPath: string): Promise<void> {
25718
+ /** Delete an authorized managed or project-local picker candidate, under a scoped claim of its id (design §1 row 17). */
25719
+ static async deleteManagedCandidate(sessionPath: string, ownership?: SessionOwnershipDecision): Promise<void> {
25145
25720
  const storage = new FileSessionStorage();
25146
- const inspected = inspectTranscriptHeaderBounded(sessionPath, storage, BOUNDED_RESUME_TRANSCRIPT_MAX_BYTES);
25721
+ // `growing`: a holder may be appending; the header line never changes.
25722
+ const inspected = inspectTranscriptHeaderBounded(sessionPath, storage, BOUNDED_RESUME_TRANSCRIPT_MAX_BYTES, {
25723
+ growing: true,
25724
+ });
25147
25725
  if (!inspected.ok || !inspected.inspection.cwd) throw new Error("Session has no valid workspace header.");
25148
25726
  const headerCwd = inspected.inspection.cwd;
25727
+ await withScopedSessionClaim(resolveSessionOwnership(ownership), inspected.inspection.sessionId, "delete", () =>
25728
+ SessionManager.#deleteAuthorizedCandidate(sessionPath, headerCwd),
25729
+ );
25730
+ }
25731
+
25732
+ /**
25733
+ * Delete a picker candidate of an explicit `--session-dir` (transcript and artifacts), under a
25734
+ * scoped claim of the id its header names (design §1 row 17).
25735
+ */
25736
+ static async deleteExplicitCandidate(sessionPath: string, ownership?: SessionOwnershipDecision): Promise<void> {
25737
+ const storage = new FileSessionStorage();
25738
+ await SessionManager.#deleteUnderHeaderClaim(sessionPath, storage, resolveSessionOwnership(ownership), () =>
25739
+ storage.deleteSessionWithArtifacts(sessionPath),
25740
+ );
25741
+ }
25742
+
25743
+ /**
25744
+ * Run a delete under a scoped claim of the id `sessionPath`'s header names. A transcript without
25745
+ * a readable header names no session a claim could cover; a live holder always has a valid one.
25746
+ */
25747
+ static async #deleteUnderHeaderClaim(
25748
+ sessionPath: string,
25749
+ storage: SessionStorage,
25750
+ ownership: ResolvedSessionOwnership,
25751
+ remove: () => Promise<void>,
25752
+ ): Promise<void> {
25753
+ const header = inspectTranscriptHeaderBounded(sessionPath, storage, BOUNDED_RESUME_TRANSCRIPT_MAX_BYTES, {
25754
+ growing: true,
25755
+ });
25756
+ if (header.ok) await withScopedSessionClaim(ownership, header.inspection.sessionId, "delete", remove);
25757
+ else await remove();
25758
+ }
25759
+
25760
+ static async #deleteAuthorizedCandidate(sessionPath: string, headerCwd: string): Promise<void> {
25149
25761
  const projectGjcDir = path.join(path.resolve(headerCwd), ".gjc");
25150
25762
  if (isProjectSessionTranscriptPath(projectGjcDir, sessionPath)) {
25151
25763
  const relativePath = path.relative(projectGjcDir, path.resolve(sessionPath)).split(path.sep).join("/");
@@ -25213,7 +25825,9 @@ export class SessionManager {
25213
25825
  _migrationPolicy: SessionDirectoryMigrationPolicy = "copy-retain",
25214
25826
  sessionMemoryMode: SessionMemoryMode = "shadow",
25215
25827
  sourceEntryId?: string | null,
25828
+ ownership?: SessionOwnershipDecision,
25216
25829
  ): Promise<StrictSessionForkResult> {
25830
+ const owner = resolveSessionOwnership(ownership);
25217
25831
  if (
25218
25832
  sourceEntryId !== undefined &&
25219
25833
  sourceEntryId !== null &&
@@ -25236,7 +25850,14 @@ export class SessionManager {
25236
25850
  (sessionMemoryMode === "enabled" ||
25237
25851
  (sessionMemoryMode === "auto" && snapshot.identity.size > eagerHydrationMaxBytes()))
25238
25852
  ) {
25239
- const boundedManager = new SessionManager(cwd, destination.directory, true, snapshot.storage, destination);
25853
+ const boundedManager = new SessionManager(
25854
+ cwd,
25855
+ destination.directory,
25856
+ true,
25857
+ owner,
25858
+ snapshot.storage,
25859
+ destination,
25860
+ );
25240
25861
  boundedManager.#sessionMemoryMode = sessionMemoryMode;
25241
25862
  if (
25242
25863
  destination.kind === "managed" &&
@@ -25364,7 +25985,7 @@ export class SessionManager {
25364
25985
  let privateStagingPublished = false;
25365
25986
 
25366
25987
  try {
25367
- manager = new SessionManager(cwd, privateStagingDir ?? dir, true, snapshot.storage, forkDestination);
25988
+ manager = new SessionManager(cwd, privateStagingDir ?? dir, true, owner, snapshot.storage, forkDestination);
25368
25989
  manager.#sessionMemoryMode = sessionMemoryMode;
25369
25990
  await resolveBlobRefsInEntries(forkEntries, manager.#blobStore);
25370
25991
  const sourceHeader = forkEntries[0] as SessionHeader | undefined;
@@ -25395,6 +26016,7 @@ export class SessionManager {
25395
26016
  const sessionFile = manager.#sessionFile;
25396
26017
  if (!sessionFile) throw new Error("fork_transcript_session_file_unavailable");
25397
26018
  const activeManager = manager;
26019
+ if (manager.#ownershipClaims.claiming) await manager.#ownershipClaims.claim(fresh.sessionId);
25398
26020
  manager.#ownershipClaims.checkWrite("fork successor");
25399
26021
  // Publish each already-parsed entry through the staged writer without joining
25400
26022
  // another whole-file string/Buffer. The parse/resident graph is still the
@@ -25811,6 +26433,7 @@ export class SessionManager {
25811
26433
  header.cwd || getProjectDir(),
25812
26434
  destination.directory,
25813
26435
  true,
26436
+ "exempt",
25814
26437
  storage,
25815
26438
  destination,
25816
26439
  );
@@ -25845,6 +26468,7 @@ export class SessionManager {
25845
26468
  inspected.inspection.cwd ?? getProjectDir(),
25846
26469
  destination.directory,
25847
26470
  true,
26471
+ "exempt",
25848
26472
  storage,
25849
26473
  destination,
25850
26474
  );
@@ -25911,7 +26535,9 @@ export class SessionManager {
25911
26535
  identity: ResumeSessionIdentity,
25912
26536
  destinationInput?: SessionDestinationInput,
25913
26537
  storage: SessionStorage = new FileSessionStorage(),
26538
+ ownership?: SessionOwnershipDecision,
25914
26539
  ): Promise<RecoveryHydrationOpenResult> {
26540
+ const owner = resolveSessionOwnership(ownership);
25915
26541
  const destination =
25916
26542
  destinationInput === undefined
25917
26543
  ? explicitDestination(path.dirname(identity.canonicalPath))
@@ -25926,16 +26552,25 @@ export class SessionManager {
25926
26552
  header.cwd || getProjectDir(),
25927
26553
  destination.directory,
25928
26554
  true,
26555
+ owner,
25929
26556
  storage,
25930
26557
  destination,
25931
26558
  );
25932
- await manager.#hydrateExistingSession(
25933
- identity.canonicalPath,
25934
- inspected.entries,
25935
- false,
25936
- inspected.identity.sha256,
25937
- "memory-only",
25938
- );
26559
+ // Claimed at open: the promotion that follows writes under this claim.
26560
+ if (manager.#ownershipClaims.claiming) await manager.#ownershipClaims.claim(header.id);
26561
+ try {
26562
+ await manager.#hydrateExistingSession(
26563
+ identity.canonicalPath,
26564
+ inspected.entries,
26565
+ false,
26566
+ inspected.identity.sha256,
26567
+ "memory-only",
26568
+ );
26569
+ } catch (error) {
26570
+ // A failed open keeps no claim: the lock goes with the manager that never opened.
26571
+ manager.#ownershipClaims.releaseAll();
26572
+ throw error;
26573
+ }
25939
26574
  const revalidated = inspectResumeSessionFile(identity.canonicalPath, storage);
25940
26575
  if ("kind" in revalidated || !sameResumeIdentity(identity, revalidated.identity)) {
25941
26576
  await manager.close();
@@ -26022,12 +26657,76 @@ export class SessionManager {
26022
26657
  * the returned discriminant; an error result never creates, rewrites, or adopts
26023
26658
  * the selected path. Breadcrumb ownership begins only after `kind: "opened"`.
26024
26659
  */
26025
- static async openExistingStrict(
26660
+ static openExistingStrict(
26026
26661
  identity: ResumeSessionIdentity,
26027
26662
  destinationInput?: SessionDestinationInput,
26028
26663
  storage: SessionStorage = new FileSessionStorage(),
26029
26664
  migrationPolicy: SessionDirectoryMigrationPolicy = "copy-retain",
26030
26665
  sessionMemoryMode: SessionMemoryMode = "shadow",
26666
+ ownership?: SessionOwnershipDecision,
26667
+ ): Promise<StrictSessionOpenResult> {
26668
+ const owner = resolveSessionOwnership(ownership);
26669
+ // `off` and exempt run the open exactly as before ownership, with no added await.
26670
+ if (!claimsUnder(owner))
26671
+ return SessionManager.#openExistingStrictClaimed(
26672
+ identity,
26673
+ destinationInput,
26674
+ storage,
26675
+ migrationPolicy,
26676
+ sessionMemoryMode,
26677
+ owner,
26678
+ { claim: undefined, outcome: { status: "none" } },
26679
+ );
26680
+ return SessionManager.#openExistingStrictUnderClaim(
26681
+ identity,
26682
+ destinationInput,
26683
+ storage,
26684
+ migrationPolicy,
26685
+ sessionMemoryMode,
26686
+ owner,
26687
+ );
26688
+ }
26689
+
26690
+ static async #openExistingStrictUnderClaim(
26691
+ identity: ResumeSessionIdentity,
26692
+ destinationInput: SessionDestinationInput | undefined,
26693
+ storage: SessionStorage,
26694
+ migrationPolicy: SessionDirectoryMigrationPolicy,
26695
+ sessionMemoryMode: SessionMemoryMode,
26696
+ owner: ResolvedSessionOwnership,
26697
+ ): Promise<StrictSessionOpenResult> {
26698
+ // Claimed before the migration and the sanitize persist; handed to the manager once it exists,
26699
+ // and released on every path that ends before that. Enforce refuses here, before anything exists.
26700
+ const attempt = await attemptSessionClaim(owner, identity.sessionId);
26701
+ const refusal = claimRefusal(owner, identity.sessionId, attempt);
26702
+ if (refusal) throw refusal;
26703
+ const pending = {
26704
+ claim: attempt.status === "claimed" ? attempt.claim : undefined,
26705
+ outcome: attempt.status === "claimed" ? { status: "claimed" as const } : attempt,
26706
+ };
26707
+ try {
26708
+ return await SessionManager.#openExistingStrictClaimed(
26709
+ identity,
26710
+ destinationInput,
26711
+ storage,
26712
+ migrationPolicy,
26713
+ sessionMemoryMode,
26714
+ owner,
26715
+ pending,
26716
+ );
26717
+ } finally {
26718
+ pending.claim?.release();
26719
+ }
26720
+ }
26721
+
26722
+ static async #openExistingStrictClaimed(
26723
+ identity: ResumeSessionIdentity,
26724
+ destinationInput: SessionDestinationInput | undefined,
26725
+ storage: SessionStorage,
26726
+ migrationPolicy: SessionDirectoryMigrationPolicy,
26727
+ sessionMemoryMode: SessionMemoryMode,
26728
+ owner: ResolvedSessionOwnership,
26729
+ pending: { claim: SessionOwnerClaim | undefined; readonly outcome: SessionClaimOutcome },
26031
26730
  ): Promise<StrictSessionOpenResult> {
26032
26731
  const destination =
26033
26732
  destinationInput === undefined
@@ -26036,11 +26735,13 @@ export class SessionManager {
26036
26735
  let sessionPath = identity.canonicalPath;
26037
26736
  if (destination.kind === "managed" && storage instanceof FileSessionStorage) {
26038
26737
  try {
26738
+ // The claim taken above covers this migration; a second attempt would only count twice.
26039
26739
  sessionPath = await SessionManager.prepareManagedCandidateForWrite(
26040
26740
  sessionPath,
26041
26741
  migrationPolicy,
26042
26742
  destination,
26043
26743
  identity,
26744
+ { ownership: "exempt" },
26044
26745
  );
26045
26746
  } catch (error) {
26046
26747
  if (error instanceof SessionMigrationPolicyError)
@@ -26065,14 +26766,23 @@ export class SessionManager {
26065
26766
  const entries = inspected.entries;
26066
26767
  const header = entries[0] as SessionHeader;
26067
26768
  const dir = destination.directory;
26068
- const manager = new SessionManager(header.cwd || getProjectDir(), dir, true, storage, destination);
26769
+ const manager = new SessionManager(header.cwd || getProjectDir(), dir, true, owner, storage, destination);
26770
+ manager.#ownershipClaims.noteOutcome(identity.sessionId, pending.outcome);
26771
+ if (pending.claim) manager.#ownershipClaims.add(pending.claim);
26772
+ pending.claim = undefined;
26069
26773
  manager.#sessionMemoryMode = sessionMemoryMode;
26070
- await manager.#hydrateExistingSession(
26071
- sessionPath,
26072
- entries,
26073
- inspected.migrationApplied,
26074
- inspected.identity.sha256,
26075
- );
26774
+ try {
26775
+ await manager.#hydrateExistingSession(
26776
+ sessionPath,
26777
+ entries,
26778
+ inspected.migrationApplied,
26779
+ inspected.identity.sha256,
26780
+ );
26781
+ } catch (error) {
26782
+ // A failed open keeps no claim: the lock goes with the manager that never opened.
26783
+ manager.#ownershipClaims.releaseAll();
26784
+ throw error;
26785
+ }
26076
26786
  manager.#readOnlyResume = true;
26077
26787
  const ownershipInspection = revalidateResumeSessionIdentity(sessionPath, storage, inspected.identity);
26078
26788
  if (ownershipInspection.kind === "error") {
@@ -26090,7 +26800,8 @@ export class SessionManager {
26090
26800
  }
26091
26801
 
26092
26802
  /**
26093
- * Continue the most recent session, or create new if none.
26803
+ * Continue the most recent session, or create new if none. In enforce, throws `SessionHeldError`
26804
+ * when the session it would continue is open for writing in another process.
26094
26805
  * @param cwd Working directory
26095
26806
  * @param sessionDir Optional session directory. If omitted, uses default (~/.gjc/agent/sessions/<encoded-cwd>/).
26096
26807
  */
@@ -26100,10 +26811,57 @@ export class SessionManager {
26100
26811
  storage: SessionStorage = new FileSessionStorage(),
26101
26812
  migrationPolicy: SessionDirectoryMigrationPolicy = "copy-retain",
26102
26813
  sessionMemoryMode: SessionMemoryMode = "shadow",
26814
+ ownership?: SessionOwnershipDecision,
26103
26815
  ): Promise<SessionManager> {
26816
+ const owner = resolveSessionOwnership(ownership);
26104
26817
  const destination = destinationFor(cwd, destinationInput, storage);
26105
26818
  const dir = destination.directory;
26819
+ const boundedCandidate = (selectedSize: number | undefined): boolean =>
26820
+ selectedSize !== undefined &&
26821
+ selectedSize > eagerHydrationMaxBytes() &&
26822
+ selectedSize <= BOUNDED_RESUME_TRANSCRIPT_MAX_BYTES &&
26823
+ (sessionMemoryMode === "enabled" ||
26824
+ (sessionMemoryMode === "auto" &&
26825
+ process.platform !== "win32" &&
26826
+ selectedSize >= autoModeMinTranscriptBytes()));
26827
+ // Whether a candidate enforce refused as held would have been chosen, decided without a
26828
+ // writable open and by today's rules: a bounded candidate must be continuable; any other one
26829
+ // is chosen once its read-only inspection passes, or ends the search with its size error.
26830
+ const heldCandidateWouldBeChosen = async (selectedPath: string): Promise<boolean> => {
26831
+ let selectedSize: number | undefined;
26832
+ try {
26833
+ selectedSize = storage.statSync(selectedPath).size;
26834
+ } catch {}
26835
+ if (boundedCandidate(selectedSize)) {
26836
+ let snapshot: SessionManager | undefined;
26837
+ try {
26838
+ snapshot = await SessionManager.openReadOnlySnapshot(selectedPath, storage);
26839
+ return canContinuePersistedHistory(snapshot.buildSessionContext().messages);
26840
+ } catch {
26841
+ // Unreadable as a snapshot: count it as chosen, so the search still ends at it.
26842
+ return true;
26843
+ } finally {
26844
+ await snapshot?.close().catch(() => undefined);
26845
+ }
26846
+ }
26847
+ const inspected = await SessionManager.inspectSessionTailReadOnly(selectedPath, storage);
26848
+ return (
26849
+ inspected.kind !== "error" || inspected.reason === "oversized" || inspected.reason === "context_too_large"
26850
+ );
26851
+ };
26852
+ // Per candidate, in today's order (design §1 row 4): enforce refuses a held candidate inside its
26853
+ // open, before any write. A held candidate that would have been chosen ends the search with that
26854
+ // refusal, for the caller to start fresh or refuse; one that is not continuable is skipped.
26106
26855
  const openSelectedStrictly = async (selectedPath: string): Promise<SessionManager | undefined> => {
26856
+ try {
26857
+ return await openCandidate(selectedPath);
26858
+ } catch (error) {
26859
+ if (error instanceof SessionHeldError && !(await heldCandidateWouldBeChosen(selectedPath)))
26860
+ return undefined;
26861
+ throw error;
26862
+ }
26863
+ };
26864
+ const openCandidate = async (selectedPath: string): Promise<SessionManager | undefined> => {
26107
26865
  let selectedSize: number | undefined;
26108
26866
  try {
26109
26867
  selectedSize = storage.statSync(selectedPath).size;
@@ -26119,23 +26877,22 @@ export class SessionManager {
26119
26877
  path.dirname(path.resolve(selectedPath)) !== path.resolve(destination.directory) &&
26120
26878
  pathIsWithin(path.resolve(destination.securityContext.sessionsRoot), path.resolve(selectedPath))
26121
26879
  ) {
26122
- openPath = await SessionManager.prepareManagedCandidateForWrite(selectedPath, migrationPolicy, destination);
26880
+ openPath = await SessionManager.prepareManagedCandidateForWrite(
26881
+ selectedPath,
26882
+ migrationPolicy,
26883
+ destination,
26884
+ undefined,
26885
+ { ownership: owner },
26886
+ );
26123
26887
  }
26124
- const boundedSelected =
26125
- selectedSize !== undefined &&
26126
- selectedSize > eagerHydrationMaxBytes() &&
26127
- selectedSize <= BOUNDED_RESUME_TRANSCRIPT_MAX_BYTES &&
26128
- (sessionMemoryMode === "enabled" ||
26129
- (sessionMemoryMode === "auto" &&
26130
- process.platform !== "win32" &&
26131
- selectedSize >= autoModeMinTranscriptBytes()));
26132
- if (boundedSelected) {
26888
+ if (boundedCandidate(selectedSize)) {
26133
26889
  const manager = await SessionManager.open(
26134
26890
  openPath,
26135
26891
  destination,
26136
26892
  storage,
26137
26893
  migrationPolicy,
26138
26894
  sessionMemoryMode,
26895
+ owner,
26139
26896
  );
26140
26897
  if (canContinuePersistedHistory(manager.buildSessionContext().messages)) return manager;
26141
26898
  await manager.close();
@@ -26153,6 +26910,7 @@ export class SessionManager {
26153
26910
  storage,
26154
26911
  migrationPolicy,
26155
26912
  sessionMemoryMode,
26913
+ owner,
26156
26914
  );
26157
26915
  if (opened.kind === "error") {
26158
26916
  const typed = SessionManager.#typedStrictOpenError(opened);
@@ -26200,8 +26958,9 @@ export class SessionManager {
26200
26958
  const opened = await openSelectedStrictly(mostRecent);
26201
26959
  if (opened) return opened;
26202
26960
  }
26203
- const manager = new SessionManager(cwd, dir, true, storage, destination);
26961
+ const manager = new SessionManager(cwd, dir, true, owner, storage, destination);
26204
26962
  manager.#initNewSession();
26963
+ if (manager.#ownershipClaims.claiming) await manager.#ownershipClaims.claim(manager.#sessionId);
26205
26964
  return manager;
26206
26965
  }
26207
26966
 
@@ -26210,7 +26969,7 @@ export class SessionManager {
26210
26969
  cwd: string = getProjectDir(),
26211
26970
  storage: SessionStorage = new MemorySessionStorage(),
26212
26971
  ): SessionManager {
26213
- const manager = new SessionManager(cwd, "", false, storage);
26972
+ const manager = new SessionManager(cwd, "", false, "exempt", storage);
26214
26973
  manager.#initNewSession();
26215
26974
  return manager;
26216
26975
  }