@gajae-code/coding-agent 0.22.1 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/types/cli/doctor/probe-types.d.ts +1 -1
  3. package/dist/types/cli/doctor/session-owners-probe.d.ts +7 -0
  4. package/dist/types/cli/doctor/session-owners.d.ts +16 -0
  5. package/dist/types/cli/github-release.d.ts +16 -0
  6. package/dist/types/cli/session-owners-cli.d.ts +13 -0
  7. package/dist/types/cli/update-cli.d.ts +2 -0
  8. package/dist/types/commands/sdk.d.ts +23 -14
  9. package/dist/types/config/settings-schema.d.ts +6 -0
  10. package/dist/types/exec/bash-shell-guardian.d.ts +61 -0
  11. package/dist/types/export/html/html-export-destination.d.ts +16 -0
  12. package/dist/types/sdk/bus/telegram-daemon-contract.d.ts +1 -1
  13. package/dist/types/sdk/host/control/runtime-gate.d.ts +7 -0
  14. package/dist/types/session/internal/graph-successor-proof.d.ts +33 -0
  15. package/dist/types/session/internal/managed-session-storage.d.ts +6 -1
  16. package/dist/types/session/internal/session-claim-set.d.ts +69 -0
  17. package/dist/types/session/operator-error-message.d.ts +29 -0
  18. package/dist/types/session/session-manager.d.ts +57 -3
  19. package/dist/types/session/session-owners-layout.d.ts +24 -0
  20. package/dist/types/session/session-ownership-mode.d.ts +45 -0
  21. package/dist/types/session/session-ownership.d.ts +195 -0
  22. package/dist/types/session/session-storage.d.ts +36 -0
  23. package/dist/types/slash-commands/helpers/parse.d.ts +1 -0
  24. package/package.json +12 -8
  25. package/scripts/verify-gjc-sdk-canonicalization.ts +2 -0
  26. package/src/cli/doctor/probe-types.ts +1 -1
  27. package/src/cli/doctor/probe.ts +9 -5
  28. package/src/cli/doctor/runner.ts +6 -1
  29. package/src/cli/doctor/session-owners-probe.ts +69 -0
  30. package/src/cli/doctor/session-owners.ts +106 -0
  31. package/src/cli/github-release.ts +100 -0
  32. package/src/cli/session-owners-cli.ts +118 -0
  33. package/src/cli/stats-cli.ts +19 -1
  34. package/src/cli/update-cli.ts +50 -3
  35. package/src/cli-ordinary.ts +1 -1
  36. package/src/commands/sdk.ts +36 -33
  37. package/src/commands/session.ts +10 -2
  38. package/src/config/settings-schema.ts +18 -0
  39. package/src/config/settings.ts +127 -13
  40. package/src/exec/bash-shell-guardian.ts +181 -12
  41. package/src/exec/isolated-shell.ts +13 -3
  42. package/src/export/html/html-export-destination.ts +47 -2
  43. package/src/export/html/index.ts +161 -13
  44. package/src/internal-urls/docs-index.generated.ts +4 -4
  45. package/src/main.ts +20 -14
  46. package/src/modes/acp/acp-agent.ts +6 -0
  47. package/src/modes/action-registry.ts +4 -1
  48. package/src/modes/controllers/command-controller.ts +12 -5
  49. package/src/modes/controllers/extension-ui-controller.ts +6 -22
  50. package/src/modes/controllers/input-controller.ts +3 -2
  51. package/src/modes/controllers/selector-controller.ts +14 -1
  52. package/src/modes/interactive-mode.ts +6 -3
  53. package/src/modes/print-mode.ts +2 -1
  54. package/src/modes/runtime-init.ts +2 -17
  55. package/src/modes/utils/ui-helpers.ts +5 -3
  56. package/src/sdk/bus/index.ts +22 -0
  57. package/src/sdk/bus/telegram-daemon-contract.ts +1 -1
  58. package/src/sdk/host/control/dispatch.ts +5 -1
  59. package/src/sdk/host/control/runtime-gate.ts +22 -0
  60. package/src/sdk/host/host.ts +4 -1
  61. package/src/sdk/session-readonly/metadata.ts +24 -18
  62. package/src/sdk/session.ts +2 -0
  63. package/src/session/agent-session.ts +101 -22
  64. package/src/session/internal/graph-successor-proof.ts +108 -0
  65. package/src/session/internal/managed-session-storage.ts +8 -1
  66. package/src/session/internal/session-claim-set.ts +242 -0
  67. package/src/session/operator-error-message.ts +79 -0
  68. package/src/session/session-manager.ts +524 -108
  69. package/src/session/session-owners-layout.ts +52 -0
  70. package/src/session/session-ownership-mode.ts +176 -0
  71. package/src/session/session-ownership.ts +851 -0
  72. package/src/session/session-storage.ts +60 -16
  73. package/src/setup/credential-import.ts +2 -1
  74. package/src/slash-commands/builtin-registry.ts +2 -0
  75. package/src/slash-commands/helpers/parse.ts +3 -1
@@ -14,8 +14,10 @@ import { type ResumeSessionIdentity, type SessionStorageStat } from "../sdk/sess
14
14
  import type { SessionRecapRecord } from "../sdk/session-recap";
15
15
  import { ArtifactManager } from "./artifacts";
16
16
  import { type BlobPutResult, BlobStore } from "./blob-store";
17
+ import { type GraphSuccessorRefusal } from "./internal/graph-successor-proof";
17
18
  import { type ManagedMigrationPolicy } from "./internal/managed-session-scope";
18
19
  import { ManagedAppendIdentityMismatchError, type ManagedAppendReceipt, type ManagedBoundedAppendExpectation, type ManagedDirectoryRoot, ManagedSessionDescendantStore } from "./internal/managed-session-storage";
20
+ import { SessionClaimSet, sessionClaimSetCapability } from "./internal/session-claim-set";
19
21
  import { type BaseAnchor, BoundedLabelsPinsStore, type CommittedTail, type DescriptorSnapshot, type DictionaryPartitionCommit, FixedCacheAccount, type MetadataDeltaValue, type ParentBucketCommit, type ReducerState, type ReopenClassification, SessionMemoryAccountant } from "./internal/session-memory-sidecar";
20
22
  import { type MemoryGuardCreateCheckpointInput, type MemoryGuardParticipantIngressLease, type MemoryGuardRestoreInput, type MemoryGuardRestoreResult, type MemoryGuardSessionManagerCheckpointV1 } from "./memory-guard-checkpoint-participant";
21
23
  import { type BashExecutionMessage, type CustomMessage, type FileMentionMessage, type HookMessage, type PythonExecutionMessage } from "./messages";
@@ -995,6 +997,12 @@ export declare class SharedSessionMutationUnsupportedError extends Error {
995
997
  readonly code = "shared_session_mutation_unsupported";
996
998
  constructor(operation: string);
997
999
  }
1000
+ export type { GraphSuccessorRefusal } from "./internal/graph-successor-proof";
1001
+ /** A refused graph successor that names the reason; still a shared-mutation refusal. */
1002
+ export declare class GraphSuccessorUnavailableError extends SharedSessionMutationUnsupportedError {
1003
+ readonly reason: GraphSuccessorRefusal;
1004
+ constructor(operation: string, reason: GraphSuccessorRefusal);
1005
+ }
998
1006
  export declare class SessionNearLimitRewriteError extends Error {
999
1007
  readonly code: "near_limit_rewrite";
1000
1008
  /** Serialized transcript size (bytes) rejected by the managed store. */
@@ -1023,6 +1031,21 @@ export declare class SessionTranscriptOversizedError extends Error {
1023
1031
  readonly size: number;
1024
1032
  constructor(size: number);
1025
1033
  }
1034
+ /**
1035
+ * A transcript above the eager-load cap that the bounded session-memory loader cannot serve:
1036
+ * branched, patch-bearing, uncompacted, pre-v5, or malformed. `reason` is the loader's fallback reason.
1037
+ */
1038
+ export declare class SessionTranscriptBoundedOpenError extends Error {
1039
+ readonly code = "bounded_open_unsupported";
1040
+ readonly size: number;
1041
+ readonly reason: string;
1042
+ constructor(size: number, reason: string);
1043
+ }
1044
+ /** The source of a bounded read-only snapshot was replaced or truncated after the snapshot opened. */
1045
+ export declare class SessionSnapshotSourceChangedError extends Error {
1046
+ readonly code = "snapshot_source_changed";
1047
+ constructor();
1048
+ }
1026
1049
  /** Default synchronous session-context materialization budget (512 MiB). */
1027
1050
  export declare const SESSION_CONTEXT_MATERIALIZATION_BUDGET_BYTES_DEFAULT: number;
1028
1051
  /** Ceiling for a `GJC_SESSION_CONTEXT_BUDGET_BYTES` override (8 GiB) so the memory guard stays meaningful. */
@@ -1633,6 +1656,13 @@ export declare class SessionManager {
1633
1656
  * share this exclusive transition so concurrent moves cannot interleave.
1634
1657
  */
1635
1658
  moveTo(newCwd: string, options?: SessionCwdMoveOptions): Promise<void>;
1659
+ /**
1660
+ * The persistence failure that every later append rethrows before writing, if one is
1661
+ * latched: a {@link ManagedAppendIdentityMismatchError} after another process changed
1662
+ * the transcript, or an earlier write failure. Near-limit outcomes are not latched.
1663
+ * @internal
1664
+ */
1665
+ getLatchedPersistenceFailure(): Error | undefined;
1636
1666
  /** Ownership loss remains observable even when an agent event listener aborts the turn. */
1637
1667
  getAppendIdentityMismatch(): ManagedAppendIdentityMismatchError | undefined;
1638
1668
  /**
@@ -1661,6 +1691,18 @@ export declare class SessionManager {
1661
1691
  ensureOnDisk(): Promise<void>;
1662
1692
  /** Flush pending writes to disk. Call before switching sessions or on shutdown. */
1663
1693
  flush(): Promise<void>;
1694
+ /**
1695
+ * {@link flush} for a caller that is leaving this transcript: `/resume`, `/new`,
1696
+ * `/fork` or shutdown.
1697
+ *
1698
+ * Once another process changes a managed transcript, the append fence latches
1699
+ * {@link ManagedAppendIdentityMismatchError} and every later flush rethrows it. The
1700
+ * fence rejected those appends before writing any byte and managed appends are
1701
+ * synchronous, so nothing is left to flush; rethrowing would trap the operator in a
1702
+ * session whose only recovery is to leave it. Every other flush failure still throws.
1703
+ * @internal
1704
+ */
1705
+ flushBeforeLeaving(): Promise<void>;
1664
1706
  /** Close the persistent writer after flushing all pending data. */
1665
1707
  close(): Promise<void>;
1666
1708
  /** Flush while open, then strictly close; retryable close skips the invalid second flush. */
@@ -1862,6 +1904,11 @@ export declare class SessionManager {
1862
1904
  assertLegacyMutationAllowed(operation: string): void;
1863
1905
  /** Additive legacy appends are safe once a control publication's transaction has settled. */
1864
1906
  assertLegacyAppendAllowed(operation: string): void;
1907
+ /** Why a fork or branch cannot be prepared now; non-throwing and write-free, for use before any effect. */
1908
+ graphSuccessorRefusal(target?: {
1909
+ leafId?: string;
1910
+ wholeSession?: boolean;
1911
+ }): GraphSuccessorRefusal | undefined;
1865
1912
  /**
1866
1913
  * Append this process's next entry into a transcript other openers may also be writing.
1867
1914
  *
@@ -2162,6 +2209,7 @@ export declare class SessionManager {
2162
2209
  * Orphaned entries (broken parent chain) are also returned as roots.
2163
2210
  */
2164
2211
  getTree(): SessionTreeNode[];
2212
+ [sessionClaimSetCapability](): SessionClaimSet;
2165
2213
  [sessionManagerReadCapability](): SessionManagerReadAccess;
2166
2214
  /**
2167
2215
  * Start a new branch from an earlier entry.
@@ -2277,8 +2325,13 @@ export declare class SessionManager {
2277
2325
  * only), no version-migration rewrite, no session-memory sidecars or legacy
2278
2326
  * sidecar cleanup, and no managed-store adoption. Shared content-addressed blobs
2279
2327
  * and the process resident cache under the agent dir may still be written, as
2280
- * on every load. Session memory stays `"off"`, so transcripts above the eager
2281
- * inspection cap fail with {@link SessionTranscriptOversizedError}.
2328
+ * on every load.
2329
+ *
2330
+ * Above the eager cap (up to {@link BOUNDED_RESUME_TRANSCRIPT_MAX_BYTES}, not on
2331
+ * Windows) it uses the bounded loader, with sidecars in a private owner-only
2332
+ * sidecar-cache instance that close, a failed open and shutdown remove. Only
2333
+ * linear, compacted v5 transcripts without patches qualify; others fail with
2334
+ * {@link SessionTranscriptBoundedOpenError}. Export reads only the validated prefix.
2282
2335
  *
2283
2336
  * The returned manager ({@link isReadOnlySnapshot}) throws `read_only_snapshot` from:
2284
2337
  * transcript appends and edits, rename and star, branch and leaf changes, rewrite,
@@ -2303,6 +2356,8 @@ export declare class SessionManager {
2303
2356
  static openReadOnlySnapshot(filePath: string, storage?: SessionStorage): Promise<SessionManager>;
2304
2357
  /** True for a manager from {@link SessionManager.openReadOnlySnapshot}; see that method for what it refuses. */
2305
2358
  isReadOnlySnapshot(): boolean;
2359
+ /** A read-only snapshot above the eager cap, which reads its source lazily while exporting. */
2360
+ isBoundedReadOnlySnapshot(): boolean;
2306
2361
  /**
2307
2362
  * Hydrate an existing predecessor transcript for recovery without taking any
2308
2363
  * write-capable action. The caller must retain the returned context and use
@@ -2370,4 +2425,3 @@ export declare class SessionManager {
2370
2425
  */
2371
2426
  deleteSessionVerified(target: VerifiedSessionDeleteTarget): Promise<VerifiedSessionDeleteResult>;
2372
2427
  }
2373
- export {};
@@ -0,0 +1,24 @@
1
+ /** The owners directory, relative to the trusted home. */
2
+ export declare const SESSION_OWNERS_RELATIVE_DIR: string;
3
+ export declare const SESSION_OWNER_SIDECAR_SUFFIX = ".session-owner";
4
+ export declare const SESSION_OWNER_RECORD_SUFFIX = ".owner.json";
5
+ /** A sidecar or record file name's key, as `sessionOwnerKey` produces it. */
6
+ export declare const SESSION_OWNER_KEY_NAME: RegExp;
7
+ export type SessionOwnerEntryKind = {
8
+ readonly kind: "sidecar";
9
+ readonly key: string;
10
+ } | {
11
+ readonly kind: "record";
12
+ readonly key: string;
13
+ } | {
14
+ readonly kind: "unrecognized";
15
+ };
16
+ /** Classify one directory entry. Only a regular file with a well-formed key is a sidecar or record. */
17
+ export declare function classifySessionOwnerEntry(name: string, isFile: boolean): SessionOwnerEntryKind;
18
+ export interface SessionOwnerEntryCounts {
19
+ readonly sidecars: number;
20
+ readonly records: number;
21
+ readonly unrecognized: number;
22
+ }
23
+ /** Count a directory's entries from `readdir` file types alone: no lock, no stat per entry. */
24
+ export declare function countSessionOwnerEntries(directory: string): SessionOwnerEntryCounts;
@@ -0,0 +1,45 @@
1
+ import { type ProjectEnvSnapshot } from "@gajae-code/utils/env-file";
2
+ export declare const SESSION_OWNERSHIP_MODES: readonly ["off", "observe", "enforce"];
3
+ export type SessionOwnershipMode = (typeof SESSION_OWNERSHIP_MODES)[number];
4
+ export declare const DEFAULT_SESSION_OWNERSHIP_MODE: SessionOwnershipMode;
5
+ export declare const SESSION_OWNERSHIP_ENV = "GJC_SESSION_OWNERSHIP";
6
+ /** Test-only seams shared by the ownership modules. Code, not environment, so a project `.env` cannot reach them. */
7
+ export interface SessionOwnershipTestHookSlot {
8
+ /** Trusted home for this process's claims and probes. The bun test preload sets it for every test process. */
9
+ homeOverride?: string;
10
+ /** Replaces the resolved mode. */
11
+ mode?: SessionOwnershipMode;
12
+ /**
13
+ * The strict seam (design §2.5): a write the detector flags throws `SessionWriteWithoutClaimError`
14
+ * instead of only being logged and counted. Entry-path and control-matrix tests turn it on.
15
+ */
16
+ strictWriteDetection?: boolean;
17
+ /**
18
+ * Where ownership counters are written. While `homeOverride` is set (every test process), counts
19
+ * go here or nowhere, so a test never writes the operator's stats database.
20
+ */
21
+ statsDbPath?: string;
22
+ }
23
+ export declare function sessionOwnershipTestHookSlot(): SessionOwnershipTestHookSlot;
24
+ /**
25
+ * The effective mode: the setting (an invalid value reads as the default), lowered by `override`
26
+ * when that is a valid, lower mode. `override` never raises the mode.
27
+ */
28
+ export declare function resolveSessionOwnershipMode(setting: unknown, override: string | undefined): SessionOwnershipMode;
29
+ /**
30
+ * `GJC_SESSION_OWNERSHIP` as the operator set it. A value that matches the project dotenv
31
+ * snapshot was loaded by Bun from the repository and is ignored, as is any value when that
32
+ * snapshot could not be read in full.
33
+ */
34
+ export declare function trustedSessionOwnershipOverride(env: NodeJS.ProcessEnv, snapshot: ProjectEnvSnapshot): string | undefined;
35
+ /** Test-only: forget the cached override, so a test can change the environment. */
36
+ export declare function resetSessionOwnershipModeForTests(): void;
37
+ /** Test-only: whether this process has read `GJC_SESSION_OWNERSHIP` since the last reset. */
38
+ export declare function sessionOwnershipOverrideWasRead(): boolean;
39
+ /** Settings supplies the global-only `session.ownership.mode` value. Without a source the default applies. */
40
+ export declare function setSessionOwnershipSettingSource(source: (() => unknown) | undefined): void;
41
+ /**
42
+ * The mode for this process now. With the setting `off` it returns before reading the environment,
43
+ * so `off` does no work beyond reading the setting.
44
+ */
45
+ export declare function sessionOwnershipMode(): SessionOwnershipMode;
@@ -0,0 +1,195 @@
1
+ import { type FileLockAcquireResult, type FileLockProbeResult } from "@gajae-code/natives";
2
+ import { type SessionOwnershipTestHookSlot } from "./session-ownership-mode";
3
+ export declare const SESSION_OWNER_SURFACES: readonly ["app", "terminal", "print", "sdk-host", "acp-host", "sdk"];
4
+ export type SessionOwnerBaseSurface = (typeof SESSION_OWNER_SURFACES)[number];
5
+ /** Where the holder runs; a subagent child carries its parent's surface plus ` (subagent)`. */
6
+ export type SessionOwnerSurface = SessionOwnerBaseSurface | `${SessionOwnerBaseSurface} (subagent)`;
7
+ /** A verified holder: its lock is held, and (on this host) its pid and incarnation match its record. */
8
+ export interface SessionOwnerHolder {
9
+ readonly surface: SessionOwnerSurface;
10
+ readonly pid: number;
11
+ /** Present only when the holder runs on another host, whose pid cannot be checked here. */
12
+ readonly host?: string;
13
+ readonly gjcVersion?: string;
14
+ readonly claimedAt?: string;
15
+ }
16
+ export type SessionOwnerUnknownReason = "unavailable" | "timed_out" | "failed";
17
+ export type SessionOwnerProbe = {
18
+ readonly state: "free";
19
+ } | {
20
+ readonly state: "held";
21
+ readonly self: boolean;
22
+ readonly holder?: SessionOwnerHolder;
23
+ } | {
24
+ readonly state: "unknown";
25
+ readonly reason: SessionOwnerUnknownReason;
26
+ readonly code?: string;
27
+ };
28
+ export interface SessionOwnerClaim {
29
+ readonly sessionId: string;
30
+ readonly surface: SessionOwnerSurface;
31
+ /** True when this process already held the session and this claim shares it. */
32
+ readonly shared: boolean;
33
+ readonly released: boolean;
34
+ /** Drop this claim. Idempotent; the last claim of a session removes the record, then unlocks. */
35
+ release(): void;
36
+ }
37
+ export type SessionOwnerClaimResult = {
38
+ readonly status: "claimed";
39
+ readonly claim: SessionOwnerClaim;
40
+ } | {
41
+ readonly status: "held";
42
+ readonly holder?: SessionOwnerHolder;
43
+ }
44
+ /** Fail-open: no claim was taken and the caller proceeds as before (design §2.7). */
45
+ | {
46
+ readonly status: "skipped";
47
+ readonly reason: "unavailable" | "timed_out";
48
+ readonly code?: string;
49
+ };
50
+ /** Lock calls, replaceable by tests to reach the fail-open paths. */
51
+ export interface SessionOwnerLockBackend {
52
+ tryAcquire(sidecar: string, timeoutMs: number): Promise<FileLockAcquireResult>;
53
+ probe(sidecar: string, timeoutMs: number): Promise<FileLockProbeResult>;
54
+ }
55
+ /**
56
+ * Test-only seams. Code, not environment, so a project `.env` cannot reach them. One object per
57
+ * process (see {@link sessionOwnershipTestHookSlot}), shared by every copy of this module.
58
+ */
59
+ export declare const SessionOwnershipTestHooks: SessionOwnershipTestHookSlot & {
60
+ lockBackend?: SessionOwnerLockBackend;
61
+ /** Runs after a record's temp file is written and before it is renamed into place. */
62
+ beforeRecordPublish?: () => void;
63
+ };
64
+ /**
65
+ * A failure that refuses the session, as the append lock refuses it (design §2.7). `code` is the
66
+ * machine code: `owners_directory_unsafe` (a safety check refused the directory),
67
+ * `owners_directory_io` (the filesystem refused, e.g. EROFS or ENOSPC; see `errno`),
68
+ * `owners_directory_changed`, or the lock's own failure code.
69
+ */
70
+ export declare class SessionOwnershipError extends Error {
71
+ readonly code: string;
72
+ readonly errno: string | undefined;
73
+ readonly operatorMessage = "gjc could not check safely whether another process has this session open, so it was not opened for writing. Check that .gjc/runtime in your home directory belongs to you and is writable.";
74
+ constructor(code: string, options?: {
75
+ cause?: unknown;
76
+ errno?: string;
77
+ });
78
+ }
79
+ /**
80
+ * The sidecar key for a session id: the id itself when it is a lower-case safe file name,
81
+ * otherwise `h-<hash>`. Ids with upper case are hashed so two ids differing only in case never
82
+ * share a sidecar on a case-insensitive volume; ids starting with `h-` are hashed so no id can
83
+ * name another's sidecar.
84
+ */
85
+ export declare function sessionOwnerKey(sessionId: string): string;
86
+ export declare function sessionOwnersDirectory(): string;
87
+ /**
88
+ * Test-only: forget the `unavailable` latch and the counters, and drop any claim a test leaked, unlocking it, then
89
+ * throw if one was leaked. The registry is clean either way, so one leak fails one test only.
90
+ */
91
+ export declare function resetSessionOwnershipForTests(): void;
92
+ /**
93
+ * Events counted for the observe phase (design §2.9). Lock-level: `claim_taken` and
94
+ * `claim_released` count locks, not shared references, so a clean process ends with
95
+ * taken - released - held_at_exit = 0.
96
+ */
97
+ export declare const SESSION_OWNERSHIP_COUNTERS: readonly ["claim_taken", "claim_released",
98
+ /** A claim refused because another process holds the session. */
99
+ "claim_conflict",
100
+ /** A claim skipped by the narrow fail-open policy (design §2.7). */
101
+ "fail_open",
102
+ /** Locks this process still held when it exited: a missed release. */
103
+ "held_at_exit", "release_after_deferred_timeout", "session_write_without_claim",
104
+ /** Claims still in the claim set of a manager that was garbage-collected: a missed release. */
105
+ "claims_abandoned",
106
+ /** A manager's session id changed outside any transition, so no settle followed it. */
107
+ "bind_outside_transition",
108
+ /** A claim for a non-current id was added outside any transition: an unrelated settle could drop it. */
109
+ "target_staged_outside_transition"];
110
+ export type SessionOwnershipCounter = (typeof SESSION_OWNERSHIP_COUNTERS)[number];
111
+ /**
112
+ * Count an event. The first count of a process arms one write of its counts to the local stats
113
+ * database at exit, so a process that never counts (mode `off`) writes nothing.
114
+ */
115
+ export declare function countSessionOwnershipEvent(name: SessionOwnershipCounter, by?: number): void;
116
+ /** A snapshot of this process's counts; a name never counted reads 0. */
117
+ export declare function sessionOwnershipCounters(): Readonly<Record<SessionOwnershipCounter, number>>;
118
+ /**
119
+ * Write the counts not yet written to the local stats database (design §2.9). Synchronous, as it
120
+ * runs from the `exit` handler, which also counts the locks still held as `held_at_exit`; it runs
121
+ * after the shutdown cleanup that releases them. Any failure drops the counts: they are local
122
+ * diagnostics, and never leave the machine.
123
+ */
124
+ export declare function persistSessionOwnershipCounters(options?: {
125
+ readonly atExit?: boolean;
126
+ }): void;
127
+ /**
128
+ * Claim `sessionId` for this process. A session this process already holds is shared (design D10).
129
+ * Throws `SessionOwnershipError` when the owners directory or the lock fails in a way that must
130
+ * refuse the session; only `unavailable` and `timed_out` fail open (design §2.7).
131
+ */
132
+ export declare function claimSessionOwner(sessionId: string, request: {
133
+ readonly surface: SessionOwnerSurface;
134
+ }): Promise<SessionOwnerClaimResult>;
135
+ /**
136
+ * Report, for each id, whether a live process holds it, without taking anything. Three-valued:
137
+ * destructive operations need `free`. Throws only for an empty id, and never creates the directory.
138
+ */
139
+ export declare function probeSessionOwners(sessionIds: readonly string[]): Promise<Map<string, SessionOwnerProbe>>;
140
+ export declare function probeSessionOwner(sessionId: string): Promise<SessionOwnerProbe>;
141
+ /**
142
+ * What the record beside a held sidecar says: `verified` (its holder checks out), `holder_gone` (a
143
+ * process on this host that no longer exists, impossible under a kernel lock and so a bug signal),
144
+ * `unverified` (alive but unprovable), `absent`, or `invalid` (unreadable, or naming another key).
145
+ */
146
+ export type SessionOwnerRecordState = "verified" | "holder_gone" | "unverified" | "absent" | "invalid";
147
+ /** A held (or unprobeable) sidecar. Every field is checked: records are untrusted input. */
148
+ export interface SessionOwnerSidecar {
149
+ readonly key: string;
150
+ readonly state: "held" | "unknown";
151
+ /** This process holds it. */
152
+ readonly self: boolean;
153
+ readonly record: SessionOwnerRecordState;
154
+ /** The id the record names, only when it maps to this key and is a safe id. */
155
+ readonly sessionId?: string;
156
+ readonly holder?: SessionOwnerHolder;
157
+ /** The pid of a `holder_gone` record. */
158
+ readonly gonePid?: number;
159
+ }
160
+ export interface SessionOwnersInventory {
161
+ readonly directory: "missing" | "present";
162
+ readonly sidecars: number;
163
+ readonly records: number;
164
+ /** Entries that are neither a sidecar nor a record with a well-formed key. */
165
+ readonly unrecognized: number;
166
+ /** Allocated size of the directory and its entries (apparent size where blocks are not reported). */
167
+ readonly diskBytes: number;
168
+ readonly held: readonly SessionOwnerSidecar[];
169
+ }
170
+ /**
171
+ * Every held sidecar under the owners directory, with its checked holder, plus the directory's
172
+ * counts. Read-only: it probes and reads, never claims, writes, unlinks or creates the directory.
173
+ * `keys` limits the probes (and the counts) to those sidecars, for a second look at suspects; this
174
+ * process's own claims, read from the registry, are always included.
175
+ * Throws `SessionOwnershipError` when the directory fails the append lock's safety checks.
176
+ */
177
+ export declare function inspectSessionOwners(options?: {
178
+ readonly keys?: readonly string[];
179
+ }): Promise<SessionOwnersInventory>;
180
+ /**
181
+ * How a holder is named to a person (design §3.4). The holder is checked again here, because a
182
+ * caller may build one: anything malformed reads as "another gjc process", never as raw text.
183
+ */
184
+ export declare function sessionOwnerHolderPhrase(holder: SessionOwnerHolder | undefined): string;
185
+ /**
186
+ * A session another live process holds for writing. `message` is the stable machine code; the
187
+ * fixed, path-free `operatorMessage` is what a person sees.
188
+ */
189
+ export declare class SessionHeldError extends Error {
190
+ readonly code = "session_held";
191
+ readonly sessionId: string;
192
+ readonly holder: SessionOwnerHolder | undefined;
193
+ readonly operatorMessage: string;
194
+ constructor(sessionId: string, holder?: SessionOwnerHolder);
195
+ }
@@ -3,6 +3,40 @@ import { FileSessionReader, type SessionStorageRangeSnapshot, type SessionStorag
3
3
  import type { ManagedGcProtocolScopeInspector } from "./internal/managed-session-scope";
4
4
  import { type ManagedDirectoryRoot } from "./internal/managed-session-storage";
5
5
  import { type TaskArtifactOwnerDeletionEvidence, type TaskArtifactOwnerRetirementContinuation, type TaskArtifactOwnerRetirementOutcome, type TaskArtifactOwnerStorageContext } from "./task-artifact-owner-codec";
6
+ export declare function canonicalPathSync(value: string): string;
7
+ /**
8
+ * The lock namespace is reached by pathname under the trusted home, so another principal
9
+ * able to rename entries in that home could swap `.gjc` between the identity checks and the
10
+ * lock operations. Refuse a home that another POSIX user can write: foreign-owned, world-
11
+ * writable without the sticky bit, or group-writable through a group other than the user's
12
+ * primary group. (Windows profile DACLs grant only the user, SYSTEM, and Administrators.)
13
+ */
14
+ export declare function assertAppendLockHomeNotSharedWritable(home: string): void;
15
+ export interface DirectoryIdentity {
16
+ readonly path: string;
17
+ readonly dev: bigint;
18
+ readonly ino: bigint;
19
+ }
20
+ /** A prepared `<home>/.gjc/runtime/<name>` lock directory plus the identities of `.gjc`, `runtime` and itself. */
21
+ export interface RuntimeLockDirectory {
22
+ readonly path: string;
23
+ readonly directories: readonly DirectoryIdentity[];
24
+ /** The noun error text uses for this namespace's directories, e.g. `append-lock`. */
25
+ readonly label: string;
26
+ }
27
+ /**
28
+ * Fails closed when any directory of the prepared lock namespace was replaced after setup,
29
+ * so a principal able to rename entries in `.gjc` cannot redirect a writer to a fresh,
30
+ * empty lock directory and enter the critical section beside another writer.
31
+ */
32
+ export declare function assertRuntimeLockDirectoryUnchanged(directories: readonly DirectoryIdentity[], code?: string, label?: string): void;
33
+ /**
34
+ * Create `<trusted home>/.gjc/runtime/<name>` for kernel or exclusive-file locks, with the
35
+ * checks every lock namespace shares, and capture its directories' identities for
36
+ * {@link assertRuntimeLockDirectoryUnchanged}. Throws (fails closed) on a home other users can
37
+ * write, a reparse component, or a directory whose owner-only mode or ACL does not verify.
38
+ */
39
+ export declare function prepareRuntimeLockDirectory(name: string, trustedHome?: string): RuntimeLockDirectory;
6
40
  export interface SessionStorageExactReplacementExpectation {
7
41
  readonly stat: SessionStorageStat;
8
42
  readonly sha256: string;
@@ -412,6 +446,8 @@ export type NativeDirectoryTreeSnapshot = {
412
446
  * stays `0600`.
413
447
  */
414
448
  export declare function writeExplicitOwnerOnlyTextSync(pathname: string, content: string): void;
449
+ /** Reject a symlink/junction/reparse component before a storage path is created or opened. */
450
+ export declare function assertNoReparsePath(pathname: string): void;
415
451
  /** Physically observed commit-marker state; corrupt JSON is still `present`. */
416
452
  export type SessionCommitMarkerState = {
417
453
  kind: "missing";
@@ -24,6 +24,7 @@ export declare function commandConsumed(): {
24
24
  export declare function usage(text: string, runtime: SlashCommandRuntime): Promise<SlashCommandResult>;
25
25
  /** Split `<verb> <rest>` on the first whitespace; lowercases `verb`. */
26
26
  export declare function parseSubcommand(input: string): ParsedSubcommand;
27
+ /** Human text for a failed slash command; session refusals render their operator message. */
27
28
  export declare function errorMessage(error: unknown): string;
28
29
  /**
29
30
  * Parse `<name?> [--scope project|user]`-style argument strings used by
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@gajae-code/coding-agent",
4
- "version": "0.22.1",
4
+ "version": "0.22.2",
5
5
  "description": "Gajae Code CLI with read, bash, edit, write tools and session management",
6
6
  "homepage": "https://gajae-code.com",
7
7
  "author": "Yeachan-Heo and Gajae Code Contributors",
@@ -30,7 +30,7 @@
30
30
  },
31
31
  "scripts": {
32
32
  "build": "bun run verify:markit-vendor && bun scripts/build-binary.ts",
33
- "check": "bun run verify:markit-vendor && biome check . && bun run check:types",
33
+ "check": "bun run verify:markit-vendor && bun ../../scripts/check-biome-max-size.ts && biome check . && bun run check:types",
34
34
  "check:runtime": "bun run generate-hotkeys-docs --check && bun run verify:sdk-canonicalization",
35
35
  "check:types": "bun run generate-docs-index && tsc -p tsconfig.json --noEmit",
36
36
  "check:autorouting-map": "bun scripts/check-autorouting-tier-map.ts",
@@ -57,12 +57,12 @@
57
57
  "@agentclientprotocol/sdk": "1.3.0",
58
58
  "@babel/parser": "^7.29.3",
59
59
  "@mozilla/readability": "^0.6.0",
60
- "@gajae-code/stats": "0.22.1",
61
- "@gajae-code/agent-core": "0.22.1",
62
- "@gajae-code/ai": "0.22.1",
63
- "@gajae-code/natives": "0.22.1",
64
- "@gajae-code/tui": "0.22.1",
65
- "@gajae-code/utils": "0.22.1",
60
+ "@gajae-code/stats": "0.22.2",
61
+ "@gajae-code/agent-core": "0.22.2",
62
+ "@gajae-code/ai": "0.22.2",
63
+ "@gajae-code/natives": "0.22.2",
64
+ "@gajae-code/tui": "0.22.2",
65
+ "@gajae-code/utils": "0.22.2",
66
66
  "@puppeteer/browsers": "^2.13.0",
67
67
  "@types/turndown": "5.0.6",
68
68
  "@xterm/headless": "^6.0.0",
@@ -140,6 +140,10 @@
140
140
  "./session/session-manager-internal.js": null,
141
141
  "./session/sdk-run-capability": null,
142
142
  "./session/sdk-run-capability.js": null,
143
+ "./session/session-ownership": null,
144
+ "./session/session-ownership.js": null,
145
+ "./session/session-ownership-mode": null,
146
+ "./session/session-ownership-mode.js": null,
143
147
  "./extensibility/extensions/function-hooks-internal": null,
144
148
  "./extensibility/extensions/function-hooks-internal.js": null,
145
149
  "./sdk": {
@@ -1782,6 +1782,8 @@ function scanPackageExports(contents: string, sourceFiles: readonly string[]): s
1782
1782
 
1783
1783
  function forbiddenMachineModule(file: string): string | undefined {
1784
1784
  if (file === "packages/coding-agent/src/modes/acp/acp-event-mapper.ts") return undefined;
1785
+ // Import-free error-text helper: it formats operator messages and cannot reach session state.
1786
+ if (file === "packages/coding-agent/src/session/operator-error-message.ts") return undefined;
1785
1787
  if (file === "packages/coding-agent/src/main.ts" || file === "packages/coding-agent/src/modes/interactive-mode.ts")
1786
1788
  return "process bootstrap/main session host";
1787
1789
  if (file === "packages/coding-agent/src/sdk/session.ts") return "direct session mutation module";
@@ -10,7 +10,7 @@ export const PROBE_OUTPUT_LIMIT_BYTES = 64 * 1024;
10
10
  */
11
11
  export const PROJECTION_RECEIPT_BUDGET_BYTES = PROBE_OUTPUT_LIMIT_BYTES - 1024;
12
12
 
13
- export type DoctorProbeKind = "native" | "projection";
13
+ export type DoctorProbeKind = "native" | "projection" | "session-owners";
14
14
 
15
15
  export interface DoctorProbeReceipt {
16
16
  readonly schemaVersion: 1;
@@ -5,8 +5,15 @@ import { PROBE_OUTPUT_LIMIT_BYTES } from "./probe-types";
5
5
  const loaders = {
6
6
  native: () => import("./native-probe"),
7
7
  projection: () => import("./projection-probe"),
8
+ "session-owners": () => import("./session-owners-probe"),
8
9
  };
9
10
 
11
+ async function collect(kind: DoctorProbeKind): Promise<DoctorProbeReceipt> {
12
+ if (kind === "native") return (await loaders.native()).collectNativeProbe();
13
+ if (kind === "projection") return (await loaders.projection()).collectProjectionProbe();
14
+ return (await loaders["session-owners"]()).collectSessionOwnersProbe();
15
+ }
16
+
10
17
  /** Only the fixed product probes are executable; no caller-provided program or module path. */
11
18
  export async function runDoctorProbe(kind: DoctorProbeKind): Promise<void> {
12
19
  // The projection probe loads real product modules, and any warning they emit
@@ -16,16 +23,13 @@ export async function runDoctorProbe(kind: DoctorProbeKind): Promise<void> {
16
23
  logger.setTransports({ console: false, file: false });
17
24
  let receipt: DoctorProbeReceipt;
18
25
  try {
19
- receipt =
20
- kind === "native"
21
- ? await (await loaders.native()).collectNativeProbe()
22
- : await (await loaders.projection()).collectProjectionProbe();
26
+ receipt = await collect(kind);
23
27
  } catch {
24
28
  receipt = {
25
29
  schemaVersion: 1,
26
30
  kind,
27
31
  status: "failed",
28
- reasonCode: kind === "native" ? "native_load_failed" : "projection_load_failed",
32
+ reasonCode: `${kind.replace("-", "_")}_load_failed`,
29
33
  checks: [],
30
34
  };
31
35
  }
@@ -8,6 +8,7 @@ import { collectDoctorProbe } from "./probe-client";
8
8
  import { executeSelectedDoctorRepair, planSelectedDoctorRepair, refuseUnsettledDoctorRepair } from "./repairs";
9
9
  import { finalizeReport } from "./report";
10
10
  import { collectServiceTargets } from "./service-targets";
11
+ import { SESSION_COLLECTOR } from "./session-owners";
11
12
  import type { DoctorCheck, DoctorCoverage, DoctorRepair, DoctorReport } from "./types";
12
13
 
13
14
  const NATIVE_COLLECTOR: DoctorCollector = {
@@ -68,6 +69,7 @@ const COLLECTORS: readonly DoctorCollector[] = [
68
69
  PLUGIN_COLLECTOR,
69
70
  NATIVE_COLLECTOR,
70
71
  PROJECTION_COLLECTOR,
72
+ SESSION_COLLECTOR,
71
73
  ];
72
74
 
73
75
  function coverage(checks: readonly DoctorCheck[], requested: number): DoctorCoverage {
@@ -162,7 +164,10 @@ function selectedCollectors(options: DoctorOptions): { collectors: DoctorCollect
162
164
  };
163
165
  if (options.checks.length === 0) {
164
166
  for (const collector of COLLECTORS)
165
- if (options.mode !== "dry-run" || (collector.id !== "native" && collector.id !== "projection"))
167
+ if (
168
+ options.mode !== "dry-run" ||
169
+ (collector.id !== "native" && collector.id !== "projection" && collector.id !== "session")
170
+ )
166
171
  add(collector.id);
167
172
  } else {
168
173
  for (const selector of options.checks) {
@@ -0,0 +1,69 @@
1
+ import { inspectSessionOwners, SessionOwnershipError } from "../../session/session-ownership";
2
+ import { doctorCheck } from "./checks";
3
+ import { doctorErrno } from "./files";
4
+ import type { DoctorProbeReceipt } from "./probe-types";
5
+ import type { DoctorCheck } from "./types";
6
+
7
+ /** A successor that just took a dead holder's lock replaces its record within this window. */
8
+ const RECHECK_MS = 250;
9
+ /** The collector replaces this with its own target id. */
10
+ const PROBE_TARGET = "t1:session-owners:probe";
11
+
12
+ function receipt(
13
+ reasonCode: string,
14
+ check: Pick<DoctorCheck, "execution" | "health" | "evidence">,
15
+ ): DoctorProbeReceipt {
16
+ return {
17
+ schemaVersion: 1,
18
+ kind: "session-owners",
19
+ status: "completed",
20
+ reasonCode,
21
+ checks: [
22
+ doctorCheck("session.owners.holders", PROBE_TARGET, { evidenceLevel: "observed", reasonCode, ...check }),
23
+ ],
24
+ };
25
+ }
26
+
27
+ /**
28
+ * Held sidecars whose record names a process that no longer exists: impossible under a kernel lock,
29
+ * so a bug signal. A suspect is flagged only if a second look, at the suspects alone, finds its lock
30
+ * still held and the same dead pid still named. The sidecar count is the collector's, from `readdir`.
31
+ */
32
+ export async function collectSessionOwnersProbe(recheckMs = RECHECK_MS): Promise<DoctorProbeReceipt> {
33
+ try {
34
+ const first = await inspectSessionOwners();
35
+ if (first.directory === "missing")
36
+ return receipt("session_owners_absent", { execution: "completed", health: "not_applicable", evidence: {} });
37
+ const held = first.held.filter(sidecar => sidecar.state === "held");
38
+ let gone = held.filter(sidecar => sidecar.record === "holder_gone");
39
+ if (gone.length > 0) {
40
+ await Bun.sleep(recheckMs);
41
+ const suspects = new Map(gone.map(sidecar => [sidecar.key, sidecar.gonePid]));
42
+ const again = await inspectSessionOwners({ keys: [...suspects.keys()] });
43
+ gone = again.held.filter(
44
+ sidecar =>
45
+ sidecar.record === "holder_gone" &&
46
+ sidecar.state === "held" &&
47
+ suspects.get(sidecar.key) === sidecar.gonePid,
48
+ );
49
+ }
50
+ return receipt(gone.length > 0 ? "session_owner_holder_gone" : "session_owner_holders_consistent", {
51
+ execution: "completed",
52
+ health: gone.length > 0 ? "warning" : "ok",
53
+ evidence: { count: held.length, counts: { holderGone: gone.length } },
54
+ });
55
+ } catch (error) {
56
+ if (error instanceof SessionOwnershipError)
57
+ return receipt(`session_${error.code}`, {
58
+ execution: "completed",
59
+ health: "error",
60
+ evidence: error.errno ? { errno: error.errno } : {},
61
+ });
62
+ // Not a refused directory: the inspection itself failed (an unreadable entry, for example).
63
+ return receipt("session_owners_inspection_failed", {
64
+ execution: "blocked",
65
+ health: "unknown",
66
+ evidence: { errno: doctorErrno(error) },
67
+ });
68
+ }
69
+ }