@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.
- package/CHANGELOG.md +60 -0
- package/dist/types/cli/doctor/probe-types.d.ts +1 -1
- package/dist/types/cli/doctor/session-owners-probe.d.ts +7 -0
- package/dist/types/cli/doctor/session-owners.d.ts +16 -0
- package/dist/types/cli/github-release.d.ts +16 -0
- package/dist/types/cli/session-owners-cli.d.ts +13 -0
- package/dist/types/cli/update-cli.d.ts +2 -0
- package/dist/types/commands/sdk.d.ts +23 -14
- package/dist/types/config/settings-schema.d.ts +6 -0
- package/dist/types/exec/bash-shell-guardian.d.ts +61 -0
- package/dist/types/export/html/html-export-destination.d.ts +16 -0
- package/dist/types/sdk/bus/telegram-daemon-contract.d.ts +1 -1
- package/dist/types/sdk/host/control/runtime-gate.d.ts +7 -0
- package/dist/types/session/internal/graph-successor-proof.d.ts +33 -0
- package/dist/types/session/internal/managed-session-storage.d.ts +6 -1
- package/dist/types/session/internal/session-claim-set.d.ts +69 -0
- package/dist/types/session/operator-error-message.d.ts +29 -0
- package/dist/types/session/session-manager.d.ts +57 -3
- package/dist/types/session/session-owners-layout.d.ts +24 -0
- package/dist/types/session/session-ownership-mode.d.ts +45 -0
- package/dist/types/session/session-ownership.d.ts +195 -0
- package/dist/types/session/session-storage.d.ts +36 -0
- package/dist/types/slash-commands/helpers/parse.d.ts +1 -0
- package/package.json +12 -8
- package/scripts/verify-gjc-sdk-canonicalization.ts +2 -0
- package/src/cli/doctor/probe-types.ts +1 -1
- package/src/cli/doctor/probe.ts +9 -5
- package/src/cli/doctor/runner.ts +6 -1
- package/src/cli/doctor/session-owners-probe.ts +69 -0
- package/src/cli/doctor/session-owners.ts +106 -0
- package/src/cli/github-release.ts +100 -0
- package/src/cli/session-owners-cli.ts +118 -0
- package/src/cli/stats-cli.ts +19 -1
- package/src/cli/update-cli.ts +50 -3
- package/src/cli-ordinary.ts +1 -1
- package/src/commands/sdk.ts +36 -33
- package/src/commands/session.ts +10 -2
- package/src/config/settings-schema.ts +18 -0
- package/src/config/settings.ts +127 -13
- package/src/exec/bash-shell-guardian.ts +181 -12
- package/src/exec/isolated-shell.ts +13 -3
- package/src/export/html/html-export-destination.ts +47 -2
- package/src/export/html/index.ts +161 -13
- package/src/internal-urls/docs-index.generated.ts +4 -4
- package/src/main.ts +20 -14
- package/src/modes/acp/acp-agent.ts +6 -0
- package/src/modes/action-registry.ts +4 -1
- package/src/modes/controllers/command-controller.ts +12 -5
- package/src/modes/controllers/extension-ui-controller.ts +6 -22
- package/src/modes/controllers/input-controller.ts +3 -2
- package/src/modes/controllers/selector-controller.ts +14 -1
- package/src/modes/interactive-mode.ts +6 -3
- package/src/modes/print-mode.ts +2 -1
- package/src/modes/runtime-init.ts +2 -17
- package/src/modes/utils/ui-helpers.ts +5 -3
- package/src/sdk/bus/index.ts +22 -0
- package/src/sdk/bus/telegram-daemon-contract.ts +1 -1
- package/src/sdk/host/control/dispatch.ts +5 -1
- package/src/sdk/host/control/runtime-gate.ts +22 -0
- package/src/sdk/host/host.ts +4 -1
- package/src/sdk/session-readonly/metadata.ts +24 -18
- package/src/sdk/session.ts +2 -0
- package/src/session/agent-session.ts +101 -22
- package/src/session/internal/graph-successor-proof.ts +108 -0
- package/src/session/internal/managed-session-storage.ts +8 -1
- package/src/session/internal/session-claim-set.ts +242 -0
- package/src/session/operator-error-message.ts +79 -0
- package/src/session/session-manager.ts +524 -108
- package/src/session/session-owners-layout.ts +52 -0
- package/src/session/session-ownership-mode.ts +176 -0
- package/src/session/session-ownership.ts +851 -0
- package/src/session/session-storage.ts +60 -16
- package/src/setup/credential-import.ts +2 -1
- package/src/slash-commands/builtin-registry.ts +2 -0
- package/src/slash-commands/helpers/parse.ts +3 -1
|
@@ -0,0 +1,851 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session ownership core: one session is open for writing in one live process.
|
|
3
|
+
*
|
|
4
|
+
* A claim is a kernel lock on `<trusted home>/.gjc/runtime/session-owners/<key>.session-owner`
|
|
5
|
+
* (the native `FileLock`), so it ends when its holder exits, however it exits. A holder record
|
|
6
|
+
* beside it names the holder for warnings; the lock is the truth and the record only a label.
|
|
7
|
+
*
|
|
8
|
+
* Dormant: no caller outside this module and its tests yet. The claim set, the mode setting and
|
|
9
|
+
* the factory wiring arrive in later steps of the single-owner programme.
|
|
10
|
+
*/
|
|
11
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
12
|
+
import * as fs from "node:fs";
|
|
13
|
+
import * as os from "node:os";
|
|
14
|
+
import * as path from "node:path";
|
|
15
|
+
import {
|
|
16
|
+
type FileLock,
|
|
17
|
+
type FileLockAcquireResult,
|
|
18
|
+
FileLockAcquireStatus,
|
|
19
|
+
FileLockFailure,
|
|
20
|
+
type FileLockProbeResult,
|
|
21
|
+
FileLockProbeState,
|
|
22
|
+
probeFileLock,
|
|
23
|
+
tryAcquireFileLock,
|
|
24
|
+
} from "@gajae-code/natives";
|
|
25
|
+
import { recordSessionOwnershipCounts } from "@gajae-code/stats/session-ownership";
|
|
26
|
+
import { getStatsDbPath, getTrustedHomeDir, isEnoent, logger } from "@gajae-code/utils";
|
|
27
|
+
import { VERSION } from "@gajae-code/utils/cli-metadata";
|
|
28
|
+
import { observeProcess, processIncarnation } from "../sdk/broker/process-incarnation";
|
|
29
|
+
import {
|
|
30
|
+
classifySessionOwnerEntry,
|
|
31
|
+
SESSION_OWNER_RECORD_SUFFIX,
|
|
32
|
+
SESSION_OWNER_SIDECAR_SUFFIX,
|
|
33
|
+
SESSION_OWNERS_RELATIVE_DIR,
|
|
34
|
+
} from "./session-owners-layout";
|
|
35
|
+
import { type SessionOwnershipTestHookSlot, sessionOwnershipTestHookSlot } from "./session-ownership-mode";
|
|
36
|
+
import {
|
|
37
|
+
assertAppendLockHomeNotSharedWritable,
|
|
38
|
+
assertNoReparsePath,
|
|
39
|
+
assertRuntimeLockDirectoryUnchanged,
|
|
40
|
+
canonicalPathSync,
|
|
41
|
+
prepareRuntimeLockDirectory,
|
|
42
|
+
type RuntimeLockDirectory,
|
|
43
|
+
} from "./session-storage";
|
|
44
|
+
|
|
45
|
+
const SIDECAR_SUFFIX = SESSION_OWNER_SIDECAR_SUFFIX;
|
|
46
|
+
const RECORD_SUFFIX = SESSION_OWNER_RECORD_SUFFIX;
|
|
47
|
+
const RECORD_VERSION = 1;
|
|
48
|
+
const RECORD_MAX_BYTES = 4096;
|
|
49
|
+
/** Every native call answers within this budget, or reports `timed_out`. */
|
|
50
|
+
const NATIVE_BUDGET_MS = 2_000;
|
|
51
|
+
const PROBE_CONCURRENCY = 16;
|
|
52
|
+
const SAFE_ID = /^[A-Za-z0-9_-]{1,128}$/;
|
|
53
|
+
/** Keys must not differ only in case: macOS volumes are case-insensitive by default. */
|
|
54
|
+
const PLAIN_KEY = /^[a-z0-9_-]{1,128}$/;
|
|
55
|
+
const SAFE_HOST = /^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$/;
|
|
56
|
+
const SAFE_VERSION = /^[0-9A-Za-z.+-]{1,64}$/;
|
|
57
|
+
/** A UTC instant as `Date#toISOString` writes it; anything else in a record is not shown. */
|
|
58
|
+
const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
|
|
59
|
+
|
|
60
|
+
export const SESSION_OWNER_SURFACES = ["app", "terminal", "print", "sdk-host", "acp-host", "sdk"] as const;
|
|
61
|
+
export type SessionOwnerBaseSurface = (typeof SESSION_OWNER_SURFACES)[number];
|
|
62
|
+
/** Where the holder runs; a subagent child carries its parent's surface plus ` (subagent)`. */
|
|
63
|
+
export type SessionOwnerSurface = SessionOwnerBaseSurface | `${SessionOwnerBaseSurface} (subagent)`;
|
|
64
|
+
|
|
65
|
+
/** A verified holder: its lock is held, and (on this host) its pid and incarnation match its record. */
|
|
66
|
+
export interface SessionOwnerHolder {
|
|
67
|
+
readonly surface: SessionOwnerSurface;
|
|
68
|
+
readonly pid: number;
|
|
69
|
+
/** Present only when the holder runs on another host, whose pid cannot be checked here. */
|
|
70
|
+
readonly host?: string;
|
|
71
|
+
readonly gjcVersion?: string;
|
|
72
|
+
readonly claimedAt?: string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export type SessionOwnerUnknownReason = "unavailable" | "timed_out" | "failed";
|
|
76
|
+
|
|
77
|
+
export type SessionOwnerProbe =
|
|
78
|
+
| { readonly state: "free" }
|
|
79
|
+
| { readonly state: "held"; readonly self: boolean; readonly holder?: SessionOwnerHolder }
|
|
80
|
+
| { readonly state: "unknown"; readonly reason: SessionOwnerUnknownReason; readonly code?: string };
|
|
81
|
+
|
|
82
|
+
export interface SessionOwnerClaim {
|
|
83
|
+
readonly sessionId: string;
|
|
84
|
+
readonly surface: SessionOwnerSurface;
|
|
85
|
+
/** True when this process already held the session and this claim shares it. */
|
|
86
|
+
readonly shared: boolean;
|
|
87
|
+
readonly released: boolean;
|
|
88
|
+
/** Drop this claim. Idempotent; the last claim of a session removes the record, then unlocks. */
|
|
89
|
+
release(): void;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export type SessionOwnerClaimResult =
|
|
93
|
+
| { readonly status: "claimed"; readonly claim: SessionOwnerClaim }
|
|
94
|
+
| { readonly status: "held"; readonly holder?: SessionOwnerHolder }
|
|
95
|
+
/** Fail-open: no claim was taken and the caller proceeds as before (design §2.7). */
|
|
96
|
+
| { readonly status: "skipped"; readonly reason: "unavailable" | "timed_out"; readonly code?: string };
|
|
97
|
+
|
|
98
|
+
/** Lock calls, replaceable by tests to reach the fail-open paths. */
|
|
99
|
+
export interface SessionOwnerLockBackend {
|
|
100
|
+
tryAcquire(sidecar: string, timeoutMs: number): Promise<FileLockAcquireResult>;
|
|
101
|
+
probe(sidecar: string, timeoutMs: number): Promise<FileLockProbeResult>;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Test-only seams. Code, not environment, so a project `.env` cannot reach them. One object per
|
|
106
|
+
* process (see {@link sessionOwnershipTestHookSlot}), shared by every copy of this module.
|
|
107
|
+
*/
|
|
108
|
+
export const SessionOwnershipTestHooks: SessionOwnershipTestHookSlot & {
|
|
109
|
+
lockBackend?: SessionOwnerLockBackend;
|
|
110
|
+
/** Runs after a record's temp file is written and before it is renamed into place. */
|
|
111
|
+
beforeRecordPublish?: () => void;
|
|
112
|
+
} = sessionOwnershipTestHookSlot();
|
|
113
|
+
|
|
114
|
+
const nativeBackend: SessionOwnerLockBackend = {
|
|
115
|
+
tryAcquire: (sidecar, timeoutMs) => tryAcquireFileLock(sidecar, timeoutMs),
|
|
116
|
+
probe: (sidecar, timeoutMs) => probeFileLock(sidecar, timeoutMs),
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
function backend(): SessionOwnerLockBackend {
|
|
120
|
+
return SessionOwnershipTestHooks.lockBackend ?? nativeBackend;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* A failure that refuses the session, as the append lock refuses it (design §2.7). `code` is the
|
|
125
|
+
* machine code: `owners_directory_unsafe` (a safety check refused the directory),
|
|
126
|
+
* `owners_directory_io` (the filesystem refused, e.g. EROFS or ENOSPC; see `errno`),
|
|
127
|
+
* `owners_directory_changed`, or the lock's own failure code.
|
|
128
|
+
*/
|
|
129
|
+
export class SessionOwnershipError extends Error {
|
|
130
|
+
readonly code: string;
|
|
131
|
+
readonly errno: string | undefined;
|
|
132
|
+
readonly operatorMessage =
|
|
133
|
+
"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.";
|
|
134
|
+
|
|
135
|
+
constructor(code: string, options?: { cause?: unknown; errno?: string }) {
|
|
136
|
+
super(`session_ownership_failed: ${code}`, options);
|
|
137
|
+
this.name = "SessionOwnershipError";
|
|
138
|
+
this.code = code;
|
|
139
|
+
this.errno = options?.errno;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Classify a directory setup failure: a filesystem errno, or a refused safety check. */
|
|
144
|
+
function directoryFailure(error: unknown): SessionOwnershipError {
|
|
145
|
+
const errno = (error as { code?: unknown } | undefined)?.code;
|
|
146
|
+
if (typeof errno === "string" && /^E[A-Z0-9]+$/.test(errno))
|
|
147
|
+
return new SessionOwnershipError("owners_directory_io", { cause: error, errno });
|
|
148
|
+
return new SessionOwnershipError("owners_directory_unsafe", { cause: error });
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// =============================================================================
|
|
152
|
+
// Key and directory
|
|
153
|
+
// =============================================================================
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* The sidecar key for a session id: the id itself when it is a lower-case safe file name,
|
|
157
|
+
* otherwise `h-<hash>`. Ids with upper case are hashed so two ids differing only in case never
|
|
158
|
+
* share a sidecar on a case-insensitive volume; ids starting with `h-` are hashed so no id can
|
|
159
|
+
* name another's sidecar.
|
|
160
|
+
*/
|
|
161
|
+
export function sessionOwnerKey(sessionId: string): string {
|
|
162
|
+
if (sessionId.length === 0) throw new TypeError("session id must not be empty");
|
|
163
|
+
if (PLAIN_KEY.test(sessionId) && !sessionId.startsWith("h-")) return sessionId;
|
|
164
|
+
return `h-${createHash("sha256").update(sessionId, "utf8").digest("hex").slice(0, 32)}`;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function trustedHome(): string {
|
|
168
|
+
return canonicalPathSync(SessionOwnershipTestHooks.homeOverride ?? getTrustedHomeDir());
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function sessionOwnersDirectory(): string {
|
|
172
|
+
return path.join(trustedHome(), SESSION_OWNERS_RELATIVE_DIR);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** The append lock's checks without creating anything; `undefined` when no claim was ever made here. */
|
|
176
|
+
function inspectOwnersDirectory(): string | undefined {
|
|
177
|
+
const home = trustedHome();
|
|
178
|
+
assertAppendLockHomeNotSharedWritable(home);
|
|
179
|
+
const owners = path.join(home, SESSION_OWNERS_RELATIVE_DIR);
|
|
180
|
+
assertNoReparsePath(owners);
|
|
181
|
+
try {
|
|
182
|
+
if (!fs.lstatSync(owners).isDirectory()) throw new Error("session_owners_not_directory");
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (isEnoent(error)) return undefined;
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
return owners;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function assertOwnersDirectoryUnchanged(directory: RuntimeLockDirectory): void {
|
|
191
|
+
try {
|
|
192
|
+
assertRuntimeLockDirectoryUnchanged(directory.directories, "owners_directory_changed", directory.label);
|
|
193
|
+
} catch (error) {
|
|
194
|
+
throw new SessionOwnershipError("owners_directory_changed", { cause: error });
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// =============================================================================
|
|
199
|
+
// Holder record
|
|
200
|
+
// =============================================================================
|
|
201
|
+
|
|
202
|
+
interface OwnerRecord {
|
|
203
|
+
readonly v: number;
|
|
204
|
+
readonly sessionId: string;
|
|
205
|
+
readonly claimNonce: string;
|
|
206
|
+
readonly pid: number;
|
|
207
|
+
readonly processIncarnation: string | null;
|
|
208
|
+
readonly surface: SessionOwnerSurface;
|
|
209
|
+
readonly host: string;
|
|
210
|
+
readonly gjcVersion: string;
|
|
211
|
+
readonly claimedAt: string;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function isSurface(value: unknown): value is SessionOwnerSurface {
|
|
215
|
+
if (typeof value !== "string") return false;
|
|
216
|
+
const base = value.endsWith(" (subagent)") ? value.slice(0, -" (subagent)".length) : value;
|
|
217
|
+
return (SESSION_OWNER_SURFACES as readonly string[]).includes(base);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function parseRecord(text: string): OwnerRecord | undefined {
|
|
221
|
+
let value: unknown;
|
|
222
|
+
try {
|
|
223
|
+
value = JSON.parse(text);
|
|
224
|
+
} catch {
|
|
225
|
+
return undefined;
|
|
226
|
+
}
|
|
227
|
+
if (typeof value !== "object" || value === null) return undefined;
|
|
228
|
+
const r = value as Record<string, unknown>;
|
|
229
|
+
const valid =
|
|
230
|
+
r.v === RECORD_VERSION &&
|
|
231
|
+
typeof r.sessionId === "string" &&
|
|
232
|
+
typeof r.claimNonce === "string" &&
|
|
233
|
+
typeof r.pid === "number" &&
|
|
234
|
+
Number.isSafeInteger(r.pid) &&
|
|
235
|
+
r.pid > 0 &&
|
|
236
|
+
(r.processIncarnation === null || typeof r.processIncarnation === "string") &&
|
|
237
|
+
isSurface(r.surface) &&
|
|
238
|
+
typeof r.host === "string" &&
|
|
239
|
+
r.host.length <= 255 &&
|
|
240
|
+
typeof r.gjcVersion === "string" &&
|
|
241
|
+
typeof r.claimedAt === "string" &&
|
|
242
|
+
r.claimedAt.length <= 64;
|
|
243
|
+
return valid ? (r as unknown as OwnerRecord) : undefined;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Read a record without following a link, bounded; any defect reads as no record. */
|
|
247
|
+
function readRecord(recordPath: string): OwnerRecord | undefined {
|
|
248
|
+
let fd: number;
|
|
249
|
+
try {
|
|
250
|
+
fd = fs.openSync(recordPath, fs.constants.O_RDONLY | fs.constants.O_NONBLOCK | (fs.constants.O_NOFOLLOW ?? 0));
|
|
251
|
+
} catch {
|
|
252
|
+
return undefined;
|
|
253
|
+
}
|
|
254
|
+
try {
|
|
255
|
+
const stat = fs.fstatSync(fd);
|
|
256
|
+
if (!stat.isFile() || stat.size > RECORD_MAX_BYTES) return undefined;
|
|
257
|
+
// Only this user's gjc writes records here; anything else is not a label to show.
|
|
258
|
+
const uid = process.getuid?.();
|
|
259
|
+
if (uid !== undefined && stat.uid !== uid) return undefined;
|
|
260
|
+
const buffer = Buffer.alloc(stat.size);
|
|
261
|
+
const read = fs.readSync(fd, buffer, 0, buffer.byteLength, 0);
|
|
262
|
+
return parseRecord(buffer.subarray(0, read).toString("utf8"));
|
|
263
|
+
} catch {
|
|
264
|
+
return undefined;
|
|
265
|
+
} finally {
|
|
266
|
+
fs.closeSync(fd);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Publish a record atomically: an exclusive owner-only temp file, then a rename over the old one. */
|
|
271
|
+
function writeRecord(recordPath: string, record: OwnerRecord): void {
|
|
272
|
+
const temp = `${recordPath}.${record.claimNonce}.tmp`;
|
|
273
|
+
const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0);
|
|
274
|
+
let published = false;
|
|
275
|
+
try {
|
|
276
|
+
const fd = fs.openSync(temp, flags, 0o600);
|
|
277
|
+
try {
|
|
278
|
+
fs.writeSync(fd, JSON.stringify(record));
|
|
279
|
+
} finally {
|
|
280
|
+
fs.closeSync(fd);
|
|
281
|
+
}
|
|
282
|
+
SessionOwnershipTestHooks.beforeRecordPublish?.();
|
|
283
|
+
fs.renameSync(temp, recordPath);
|
|
284
|
+
published = true;
|
|
285
|
+
} finally {
|
|
286
|
+
// The temp name carries this claim's nonce, so it is never another writer's file.
|
|
287
|
+
if (!published) fs.rmSync(temp, { force: true });
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** A record's `claimedAt`, re-serialised, or `undefined` when it is not a plain UTC instant. */
|
|
292
|
+
function safeInstant(value: string): string | undefined {
|
|
293
|
+
if (!ISO_INSTANT.test(value)) return undefined;
|
|
294
|
+
const ms = Date.parse(value);
|
|
295
|
+
return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** The holder a record names, if it checks out; otherwise `undefined` ("another gjc process"). */
|
|
299
|
+
function verifiedHolder(record: OwnerRecord | undefined, sessionId: string): SessionOwnerHolder | undefined {
|
|
300
|
+
if (!record || record.sessionId !== sessionId) return undefined;
|
|
301
|
+
const gjcVersion = SAFE_VERSION.test(record.gjcVersion) ? record.gjcVersion : undefined;
|
|
302
|
+
const base = { surface: record.surface, pid: record.pid, gjcVersion, claimedAt: safeInstant(record.claimedAt) };
|
|
303
|
+
// A live pid with a matching start incarnation is this host's process even if the host name
|
|
304
|
+
// changed since the record was written (macOS renames hosts with the network).
|
|
305
|
+
if (observeProcess(record.pid, record.processIncarnation ?? undefined) === "alive") return base;
|
|
306
|
+
if (record.host === os.hostname() || !SAFE_HOST.test(record.host)) return undefined;
|
|
307
|
+
return { ...base, host: record.host };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// =============================================================================
|
|
311
|
+
// Process-global registry
|
|
312
|
+
// =============================================================================
|
|
313
|
+
|
|
314
|
+
interface RegistryEntry {
|
|
315
|
+
readonly sessionId: string;
|
|
316
|
+
readonly surface: SessionOwnerSurface;
|
|
317
|
+
readonly nonce: string;
|
|
318
|
+
readonly claimedAt: string;
|
|
319
|
+
readonly recordPath: string;
|
|
320
|
+
readonly lock: FileLock;
|
|
321
|
+
holders: number;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
interface SessionOwnerRegistry {
|
|
325
|
+
/** Held claims by sidecar path; the count is how many claims share one lock. */
|
|
326
|
+
readonly entries: Map<string, RegistryEntry>;
|
|
327
|
+
/** Acquires in flight, so a second claim in this process waits instead of contending. */
|
|
328
|
+
readonly pending: Map<string, Promise<void>>;
|
|
329
|
+
/** Set once a lock call reports `unavailable`: claims are off for this process. */
|
|
330
|
+
unavailable: string | undefined;
|
|
331
|
+
/** In-process event counts (design §2.9); added after v1 shipped, so a v1 registry may lack it. */
|
|
332
|
+
counters?: Map<SessionOwnershipCounter, number>;
|
|
333
|
+
/** Counts already written to the stats database, and whether the exit write is armed. */
|
|
334
|
+
persisted?: { readonly counts: Map<SessionOwnershipCounter, number>; armed: boolean };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** Versioned, so two copies of this module in one realm share one registry (design §2.5). */
|
|
338
|
+
const REGISTRY_KEY = Symbol.for("gajae-code.session-ownership.registry.v1");
|
|
339
|
+
|
|
340
|
+
function registry(): SessionOwnerRegistry {
|
|
341
|
+
const store = globalThis as unknown as Record<symbol, SessionOwnerRegistry | undefined>;
|
|
342
|
+
let found = store[REGISTRY_KEY];
|
|
343
|
+
if (!found) {
|
|
344
|
+
found = { entries: new Map(), pending: new Map(), unavailable: undefined };
|
|
345
|
+
store[REGISTRY_KEY] = found;
|
|
346
|
+
}
|
|
347
|
+
return found;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Test-only: forget the `unavailable` latch and the counters, and drop any claim a test leaked, unlocking it, then
|
|
352
|
+
* throw if one was leaked. The registry is clean either way, so one leak fails one test only.
|
|
353
|
+
*/
|
|
354
|
+
export function resetSessionOwnershipForTests(): void {
|
|
355
|
+
const current = registry();
|
|
356
|
+
current.unavailable = undefined;
|
|
357
|
+
current.counters?.clear();
|
|
358
|
+
current.persisted?.counts.clear();
|
|
359
|
+
const leaked = [...current.entries.values()];
|
|
360
|
+
current.entries.clear();
|
|
361
|
+
for (const entry of leaked) entry.lock.release();
|
|
362
|
+
if (leaked.length > 0) throw new Error(`${leaked.length} session claim(s) were never released`);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Events counted for the observe phase (design §2.9). Lock-level: `claim_taken` and
|
|
367
|
+
* `claim_released` count locks, not shared references, so a clean process ends with
|
|
368
|
+
* taken - released - held_at_exit = 0.
|
|
369
|
+
*/
|
|
370
|
+
export const SESSION_OWNERSHIP_COUNTERS = [
|
|
371
|
+
"claim_taken",
|
|
372
|
+
"claim_released",
|
|
373
|
+
/** A claim refused because another process holds the session. */
|
|
374
|
+
"claim_conflict",
|
|
375
|
+
/** A claim skipped by the narrow fail-open policy (design §2.7). */
|
|
376
|
+
"fail_open",
|
|
377
|
+
/** Locks this process still held when it exited: a missed release. */
|
|
378
|
+
"held_at_exit",
|
|
379
|
+
"release_after_deferred_timeout",
|
|
380
|
+
"session_write_without_claim",
|
|
381
|
+
/** Claims still in the claim set of a manager that was garbage-collected: a missed release. */
|
|
382
|
+
"claims_abandoned",
|
|
383
|
+
/** A manager's session id changed outside any transition, so no settle followed it. */
|
|
384
|
+
"bind_outside_transition",
|
|
385
|
+
/** A claim for a non-current id was added outside any transition: an unrelated settle could drop it. */
|
|
386
|
+
"target_staged_outside_transition",
|
|
387
|
+
] as const;
|
|
388
|
+
export type SessionOwnershipCounter = (typeof SESSION_OWNERSHIP_COUNTERS)[number];
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Count an event. The first count of a process arms one write of its counts to the local stats
|
|
392
|
+
* database at exit, so a process that never counts (mode `off`) writes nothing.
|
|
393
|
+
*/
|
|
394
|
+
export function countSessionOwnershipEvent(name: SessionOwnershipCounter, by = 1): void {
|
|
395
|
+
const current = registry();
|
|
396
|
+
current.counters ??= new Map();
|
|
397
|
+
current.counters.set(name, (current.counters.get(name) ?? 0) + by);
|
|
398
|
+
current.persisted ??= { counts: new Map(), armed: false };
|
|
399
|
+
if (current.persisted.armed) return;
|
|
400
|
+
current.persisted.armed = true;
|
|
401
|
+
process.once("exit", () => persistSessionOwnershipCounters({ atExit: true }));
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** A snapshot of this process's counts; a name never counted reads 0. */
|
|
405
|
+
export function sessionOwnershipCounters(): Readonly<Record<SessionOwnershipCounter, number>> {
|
|
406
|
+
const counters = registry().counters;
|
|
407
|
+
const snapshot = {} as Record<SessionOwnershipCounter, number>;
|
|
408
|
+
for (const name of SESSION_OWNERSHIP_COUNTERS) snapshot[name] = counters?.get(name) ?? 0;
|
|
409
|
+
return snapshot;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Where counts go: the stats database, or under a test home only the path a test names. */
|
|
413
|
+
function countersDbPath(): string | undefined {
|
|
414
|
+
if (SessionOwnershipTestHooks.homeOverride !== undefined) return SessionOwnershipTestHooks.statsDbPath;
|
|
415
|
+
return getStatsDbPath();
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Write the counts not yet written to the local stats database (design §2.9). Synchronous, as it
|
|
420
|
+
* runs from the `exit` handler, which also counts the locks still held as `held_at_exit`; it runs
|
|
421
|
+
* after the shutdown cleanup that releases them. Any failure drops the counts: they are local
|
|
422
|
+
* diagnostics, and never leave the machine.
|
|
423
|
+
*/
|
|
424
|
+
export function persistSessionOwnershipCounters(options: { readonly atExit?: boolean } = {}): void {
|
|
425
|
+
const current = registry();
|
|
426
|
+
if (options.atExit && current.entries.size > 0) countSessionOwnershipEvent("held_at_exit", current.entries.size);
|
|
427
|
+
const counters = current.counters;
|
|
428
|
+
if (!counters) return;
|
|
429
|
+
current.persisted ??= { counts: new Map(), armed: false };
|
|
430
|
+
const persisted = current.persisted.counts;
|
|
431
|
+
const delta: Partial<Record<SessionOwnershipCounter, number>> = {};
|
|
432
|
+
for (const [name, count] of counters) {
|
|
433
|
+
const unwritten = count - (persisted.get(name) ?? 0);
|
|
434
|
+
if (unwritten > 0) delta[name] = unwritten;
|
|
435
|
+
}
|
|
436
|
+
if (Object.keys(delta).length === 0) return;
|
|
437
|
+
try {
|
|
438
|
+
const dbPath = countersDbPath();
|
|
439
|
+
if (dbPath === undefined) return;
|
|
440
|
+
recordSessionOwnershipCounts(dbPath, delta, { timestamp: Date.now(), gjcVersion: VERSION });
|
|
441
|
+
for (const [name, count] of counters) persisted.set(name, count);
|
|
442
|
+
} catch (error) {
|
|
443
|
+
logger.debug("Session ownership counters were not recorded", { error: String(error) });
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function markUnavailable(code: string | undefined): string {
|
|
448
|
+
const current = registry();
|
|
449
|
+
const latched = code ?? "unavailable";
|
|
450
|
+
if (current.unavailable === undefined) {
|
|
451
|
+
current.unavailable = latched;
|
|
452
|
+
logger.warn("Session ownership is unavailable; claims are off for this process", { code: latched });
|
|
453
|
+
}
|
|
454
|
+
return current.unavailable;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
class Claim implements SessionOwnerClaim {
|
|
458
|
+
readonly #sidecar: string;
|
|
459
|
+
readonly #entry: RegistryEntry;
|
|
460
|
+
readonly shared: boolean;
|
|
461
|
+
#released = false;
|
|
462
|
+
|
|
463
|
+
constructor(sidecar: string, entry: RegistryEntry, shared: boolean) {
|
|
464
|
+
this.#sidecar = sidecar;
|
|
465
|
+
this.#entry = entry;
|
|
466
|
+
this.shared = shared;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
get sessionId(): string {
|
|
470
|
+
return this.#entry.sessionId;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
get surface(): SessionOwnerSurface {
|
|
474
|
+
return this.#entry.surface;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
get released(): boolean {
|
|
478
|
+
return this.#released;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
release(): void {
|
|
482
|
+
if (this.#released) return;
|
|
483
|
+
this.#released = true;
|
|
484
|
+
const entry = this.#entry;
|
|
485
|
+
entry.holders -= 1;
|
|
486
|
+
if (entry.holders > 0) return;
|
|
487
|
+
const entries = registry().entries;
|
|
488
|
+
// A test reset dropped and unlocked this entry; the sidecar may now name a newer claim.
|
|
489
|
+
if (entries.get(this.#sidecar) !== entry) return;
|
|
490
|
+
// Synchronous from here to the unlock, so no claim in this process can meet its own lock.
|
|
491
|
+
entries.delete(this.#sidecar);
|
|
492
|
+
countSessionOwnershipEvent("claim_released");
|
|
493
|
+
// Remove the record before the lock, so a successor's record is never removed; leave a
|
|
494
|
+
// record whose nonce is not ours.
|
|
495
|
+
if (readRecord(entry.recordPath)?.claimNonce === entry.nonce) {
|
|
496
|
+
try {
|
|
497
|
+
fs.unlinkSync(entry.recordPath);
|
|
498
|
+
} catch (error) {
|
|
499
|
+
if (!isEnoent(error)) logger.warn("Session owner record removal failed", { error: String(error) });
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
entry.lock.release();
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function selfHolder(entry: RegistryEntry): SessionOwnerHolder {
|
|
507
|
+
return { surface: entry.surface, pid: process.pid, gjcVersion: VERSION, claimedAt: entry.claimedAt };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// =============================================================================
|
|
511
|
+
// Claim and probe
|
|
512
|
+
// =============================================================================
|
|
513
|
+
|
|
514
|
+
function failOpen(reason: "unavailable" | "timed_out", code: string | undefined): SessionOwnerClaimResult {
|
|
515
|
+
countSessionOwnershipEvent("fail_open");
|
|
516
|
+
return { status: "skipped", reason, code };
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* Claim `sessionId` for this process. A session this process already holds is shared (design D10).
|
|
521
|
+
* Throws `SessionOwnershipError` when the owners directory or the lock fails in a way that must
|
|
522
|
+
* refuse the session; only `unavailable` and `timed_out` fail open (design §2.7).
|
|
523
|
+
*/
|
|
524
|
+
export async function claimSessionOwner(
|
|
525
|
+
sessionId: string,
|
|
526
|
+
request: { readonly surface: SessionOwnerSurface },
|
|
527
|
+
): Promise<SessionOwnerClaimResult> {
|
|
528
|
+
const key = sessionOwnerKey(sessionId);
|
|
529
|
+
const current = registry();
|
|
530
|
+
if (current.unavailable !== undefined) return failOpen("unavailable", current.unavailable);
|
|
531
|
+
let directory: RuntimeLockDirectory;
|
|
532
|
+
try {
|
|
533
|
+
directory = prepareRuntimeLockDirectory("session-owners", trustedHome());
|
|
534
|
+
} catch (error) {
|
|
535
|
+
throw directoryFailure(error);
|
|
536
|
+
}
|
|
537
|
+
const owners = directory.path;
|
|
538
|
+
const sidecar = path.join(owners, `${key}${SIDECAR_SUFFIX}`);
|
|
539
|
+
for (;;) {
|
|
540
|
+
const held = current.entries.get(sidecar);
|
|
541
|
+
if (held) {
|
|
542
|
+
held.holders += 1;
|
|
543
|
+
return { status: "claimed", claim: new Claim(sidecar, held, true) };
|
|
544
|
+
}
|
|
545
|
+
const pending = current.pending.get(sidecar);
|
|
546
|
+
if (!pending) break;
|
|
547
|
+
await pending;
|
|
548
|
+
}
|
|
549
|
+
// The acquire waited on may have found the platform unavailable.
|
|
550
|
+
if (current.unavailable !== undefined) return failOpen("unavailable", current.unavailable);
|
|
551
|
+
const { promise, resolve } = Promise.withResolvers<void>();
|
|
552
|
+
current.pending.set(sidecar, promise);
|
|
553
|
+
try {
|
|
554
|
+
assertOwnersDirectoryUnchanged(directory);
|
|
555
|
+
const result = await backend().tryAcquire(sidecar, NATIVE_BUDGET_MS);
|
|
556
|
+
switch (result.status) {
|
|
557
|
+
case FileLockAcquireStatus.Acquired: {
|
|
558
|
+
if (!result.lock) throw new SessionOwnershipError("acquired_without_lock");
|
|
559
|
+
// A swap during the acquire would leave this lock in a directory other processes no
|
|
560
|
+
// longer see; release it and refuse, as the append lock does.
|
|
561
|
+
try {
|
|
562
|
+
assertOwnersDirectoryUnchanged(directory);
|
|
563
|
+
} catch (error) {
|
|
564
|
+
result.lock.release();
|
|
565
|
+
throw error;
|
|
566
|
+
}
|
|
567
|
+
const entry: RegistryEntry = {
|
|
568
|
+
sessionId,
|
|
569
|
+
surface: request.surface,
|
|
570
|
+
nonce: randomUUID(),
|
|
571
|
+
claimedAt: new Date().toISOString(),
|
|
572
|
+
recordPath: path.join(owners, `${key}${RECORD_SUFFIX}`),
|
|
573
|
+
lock: result.lock,
|
|
574
|
+
holders: 1,
|
|
575
|
+
};
|
|
576
|
+
try {
|
|
577
|
+
writeRecord(entry.recordPath, {
|
|
578
|
+
v: RECORD_VERSION,
|
|
579
|
+
sessionId,
|
|
580
|
+
claimNonce: entry.nonce,
|
|
581
|
+
pid: process.pid,
|
|
582
|
+
processIncarnation: processIncarnation(process.pid) ?? null,
|
|
583
|
+
surface: entry.surface,
|
|
584
|
+
host: os.hostname(),
|
|
585
|
+
gjcVersion: VERSION,
|
|
586
|
+
claimedAt: entry.claimedAt,
|
|
587
|
+
});
|
|
588
|
+
} catch (error) {
|
|
589
|
+
// The lock is the truth; without a record the holder reads as "another gjc process".
|
|
590
|
+
// A record left by an earlier holder must not name that holder instead: this claim
|
|
591
|
+
// holds the lock, so no live process owns it.
|
|
592
|
+
logger.warn("Session owner record write failed", { error: String(error) });
|
|
593
|
+
try {
|
|
594
|
+
fs.unlinkSync(entry.recordPath);
|
|
595
|
+
} catch (unlinkError) {
|
|
596
|
+
if (!isEnoent(unlinkError))
|
|
597
|
+
logger.warn("Stale session owner record removal failed", { error: String(unlinkError) });
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
current.entries.set(sidecar, entry);
|
|
601
|
+
countSessionOwnershipEvent("claim_taken");
|
|
602
|
+
return { status: "claimed", claim: new Claim(sidecar, entry, false) };
|
|
603
|
+
}
|
|
604
|
+
case FileLockAcquireStatus.Held:
|
|
605
|
+
countSessionOwnershipEvent("claim_conflict");
|
|
606
|
+
return {
|
|
607
|
+
status: "held",
|
|
608
|
+
holder: verifiedHolder(readRecord(path.join(owners, `${key}${RECORD_SUFFIX}`)), sessionId),
|
|
609
|
+
};
|
|
610
|
+
case FileLockAcquireStatus.Unavailable:
|
|
611
|
+
return failOpen("unavailable", markUnavailable(result.code));
|
|
612
|
+
case FileLockAcquireStatus.TimedOut:
|
|
613
|
+
// A stall is not a platform property: skip this claim only, and try again next time.
|
|
614
|
+
logger.warn("Session ownership claim timed out; this claim is skipped", { code: result.code });
|
|
615
|
+
return failOpen("timed_out", result.code);
|
|
616
|
+
default:
|
|
617
|
+
throw new SessionOwnershipError(result.code ?? "lock_failed");
|
|
618
|
+
}
|
|
619
|
+
} finally {
|
|
620
|
+
current.pending.delete(sidecar);
|
|
621
|
+
resolve();
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** `present`, `missing`, or the code of the failure that refused the directory. */
|
|
626
|
+
type OwnersDirectoryState = "present" | "missing" | { readonly failed: string };
|
|
627
|
+
|
|
628
|
+
async function probeOne(owners: string, state: OwnersDirectoryState, sessionId: string): Promise<SessionOwnerProbe> {
|
|
629
|
+
const current = registry();
|
|
630
|
+
const sidecar = path.join(owners, `${sessionOwnerKey(sessionId)}${SIDECAR_SUFFIX}`);
|
|
631
|
+
// This process's own claims come first: the registry knows them whatever the directory says.
|
|
632
|
+
for (let pending = current.pending.get(sidecar); pending; pending = current.pending.get(sidecar)) await pending;
|
|
633
|
+
const own = current.entries.get(sidecar);
|
|
634
|
+
if (own) return { state: "held", self: true, holder: selfHolder(own) };
|
|
635
|
+
if (state === "missing") return { state: "free" };
|
|
636
|
+
if (typeof state === "object") return { state: "unknown", reason: "failed", code: state.failed };
|
|
637
|
+
if (current.unavailable !== undefined) return { state: "unknown", reason: "unavailable", code: current.unavailable };
|
|
638
|
+
const result = await backend().probe(sidecar, NATIVE_BUDGET_MS);
|
|
639
|
+
switch (result.state) {
|
|
640
|
+
case FileLockProbeState.Free:
|
|
641
|
+
return { state: "free" };
|
|
642
|
+
case FileLockProbeState.Held: {
|
|
643
|
+
const recordPath = sidecar.slice(0, -SIDECAR_SUFFIX.length) + RECORD_SUFFIX;
|
|
644
|
+
return { state: "held", self: false, holder: verifiedHolder(readRecord(recordPath), sessionId) };
|
|
645
|
+
}
|
|
646
|
+
default: {
|
|
647
|
+
const reason = result.reason ?? FileLockFailure.Failed;
|
|
648
|
+
// Only an unsupported platform proves a claim would fail too: on macOS the probe is an
|
|
649
|
+
// F_GETLK query while a claim is flock(2), so a probe's ENOTSUP says nothing about claims.
|
|
650
|
+
if (reason === FileLockFailure.Unavailable && result.code === "unsupported_platform")
|
|
651
|
+
markUnavailable(result.code);
|
|
652
|
+
return { state: "unknown", reason, code: result.code };
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* Report, for each id, whether a live process holds it, without taking anything. Three-valued:
|
|
659
|
+
* destructive operations need `free`. Throws only for an empty id, and never creates the directory.
|
|
660
|
+
*/
|
|
661
|
+
export async function probeSessionOwners(sessionIds: readonly string[]): Promise<Map<string, SessionOwnerProbe>> {
|
|
662
|
+
const ids = [...new Set(sessionIds)];
|
|
663
|
+
for (const id of ids) sessionOwnerKey(id);
|
|
664
|
+
const results = new Map<string, SessionOwnerProbe>();
|
|
665
|
+
const owners = sessionOwnersDirectory();
|
|
666
|
+
let state: OwnersDirectoryState;
|
|
667
|
+
try {
|
|
668
|
+
state = inspectOwnersDirectory() === undefined ? "missing" : "present";
|
|
669
|
+
} catch (error) {
|
|
670
|
+
logger.warn("Session owners directory failed its checks", { error: String(error) });
|
|
671
|
+
state = { failed: directoryFailure(error).code };
|
|
672
|
+
}
|
|
673
|
+
for (let start = 0; start < ids.length; start += PROBE_CONCURRENCY) {
|
|
674
|
+
const batch = ids.slice(start, start + PROBE_CONCURRENCY);
|
|
675
|
+
const probes = await Promise.all(batch.map(id => probeOne(owners, state, id)));
|
|
676
|
+
for (const [index, id] of batch.entries()) results.set(id, probes[index]);
|
|
677
|
+
}
|
|
678
|
+
return results;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
export async function probeSessionOwner(sessionId: string): Promise<SessionOwnerProbe> {
|
|
682
|
+
const probe = (await probeSessionOwners([sessionId])).get(sessionId);
|
|
683
|
+
if (!probe) throw new Error("probe returned no result");
|
|
684
|
+
return probe;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// =============================================================================
|
|
688
|
+
// Inventory (read-only; design §2.9)
|
|
689
|
+
// =============================================================================
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* What the record beside a held sidecar says: `verified` (its holder checks out), `holder_gone` (a
|
|
693
|
+
* process on this host that no longer exists, impossible under a kernel lock and so a bug signal),
|
|
694
|
+
* `unverified` (alive but unprovable), `absent`, or `invalid` (unreadable, or naming another key).
|
|
695
|
+
*/
|
|
696
|
+
export type SessionOwnerRecordState = "verified" | "holder_gone" | "unverified" | "absent" | "invalid";
|
|
697
|
+
|
|
698
|
+
/** A held (or unprobeable) sidecar. Every field is checked: records are untrusted input. */
|
|
699
|
+
export interface SessionOwnerSidecar {
|
|
700
|
+
readonly key: string;
|
|
701
|
+
readonly state: "held" | "unknown";
|
|
702
|
+
/** This process holds it. */
|
|
703
|
+
readonly self: boolean;
|
|
704
|
+
readonly record: SessionOwnerRecordState;
|
|
705
|
+
/** The id the record names, only when it maps to this key and is a safe id. */
|
|
706
|
+
readonly sessionId?: string;
|
|
707
|
+
readonly holder?: SessionOwnerHolder;
|
|
708
|
+
/** The pid of a `holder_gone` record. */
|
|
709
|
+
readonly gonePid?: number;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
export interface SessionOwnersInventory {
|
|
713
|
+
readonly directory: "missing" | "present";
|
|
714
|
+
readonly sidecars: number;
|
|
715
|
+
readonly records: number;
|
|
716
|
+
/** Entries that are neither a sidecar nor a record with a well-formed key. */
|
|
717
|
+
readonly unrecognized: number;
|
|
718
|
+
/** Allocated size of the directory and its entries (apparent size where blocks are not reported). */
|
|
719
|
+
readonly diskBytes: number;
|
|
720
|
+
readonly held: readonly SessionOwnerSidecar[];
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function describeRecord(
|
|
724
|
+
record: OwnerRecord | undefined,
|
|
725
|
+
key: string,
|
|
726
|
+
): Omit<SessionOwnerSidecar, "key" | "state" | "self"> {
|
|
727
|
+
if (!record) return { record: "absent" };
|
|
728
|
+
if (record.sessionId.length === 0 || sessionOwnerKey(record.sessionId) !== key) return { record: "invalid" };
|
|
729
|
+
const sessionId = SAFE_ID.test(record.sessionId) ? record.sessionId : undefined;
|
|
730
|
+
const holder = verifiedHolder(record, record.sessionId);
|
|
731
|
+
if (holder) return { record: "verified", sessionId, holder };
|
|
732
|
+
const gone =
|
|
733
|
+
record.host === os.hostname() && observeProcess(record.pid, record.processIncarnation ?? undefined) === "exited";
|
|
734
|
+
return gone ? { record: "holder_gone", sessionId, gonePid: record.pid } : { record: "unverified", sessionId };
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* Every held sidecar under the owners directory, with its checked holder, plus the directory's
|
|
739
|
+
* counts. Read-only: it probes and reads, never claims, writes, unlinks or creates the directory.
|
|
740
|
+
* `keys` limits the probes (and the counts) to those sidecars, for a second look at suspects; this
|
|
741
|
+
* process's own claims, read from the registry, are always included.
|
|
742
|
+
* Throws `SessionOwnershipError` when the directory fails the append lock's safety checks.
|
|
743
|
+
*/
|
|
744
|
+
export async function inspectSessionOwners(
|
|
745
|
+
options: { readonly keys?: readonly string[] } = {},
|
|
746
|
+
): Promise<SessionOwnersInventory> {
|
|
747
|
+
const current = registry();
|
|
748
|
+
let owners: string | undefined;
|
|
749
|
+
try {
|
|
750
|
+
owners = inspectOwnersDirectory();
|
|
751
|
+
} catch (error) {
|
|
752
|
+
throw directoryFailure(error);
|
|
753
|
+
}
|
|
754
|
+
const self = new Map<string, RegistryEntry>();
|
|
755
|
+
for (const [sidecar, entry] of current.entries) self.set(path.basename(sidecar, SIDECAR_SUFFIX), entry);
|
|
756
|
+
const held: SessionOwnerSidecar[] = [...self].map(([key, entry]) => ({
|
|
757
|
+
key,
|
|
758
|
+
state: "held",
|
|
759
|
+
self: true,
|
|
760
|
+
record: "verified",
|
|
761
|
+
sessionId: SAFE_ID.test(entry.sessionId) ? entry.sessionId : undefined,
|
|
762
|
+
holder: selfHolder(entry),
|
|
763
|
+
}));
|
|
764
|
+
const counts = { sidecars: 0, records: 0, unrecognized: 0, diskBytes: 0 };
|
|
765
|
+
if (!owners) return { directory: "missing", ...counts, held };
|
|
766
|
+
const keys: string[] = [];
|
|
767
|
+
const names = options.keys ? options.keys.map(key => `${key}${SIDECAR_SUFFIX}`) : [".", ...fs.readdirSync(owners)];
|
|
768
|
+
for (const name of names) {
|
|
769
|
+
let isFile = false;
|
|
770
|
+
try {
|
|
771
|
+
const stat = fs.lstatSync(path.join(owners, name));
|
|
772
|
+
counts.diskBytes += stat.blocks ? stat.blocks * 512 : stat.size;
|
|
773
|
+
isFile = stat.isFile();
|
|
774
|
+
} catch {}
|
|
775
|
+
if (name === ".") continue;
|
|
776
|
+
const entry = classifySessionOwnerEntry(name, isFile);
|
|
777
|
+
if (entry.kind === "sidecar") {
|
|
778
|
+
counts.sidecars += 1;
|
|
779
|
+
if (!self.has(entry.key)) keys.push(entry.key);
|
|
780
|
+
} else if (entry.kind === "record") counts.records += 1;
|
|
781
|
+
else counts.unrecognized += 1;
|
|
782
|
+
}
|
|
783
|
+
const directory = owners;
|
|
784
|
+
const inspectOne = async (key: string): Promise<SessionOwnerSidecar | undefined> => {
|
|
785
|
+
let state: SessionOwnerSidecar["state"] = "unknown";
|
|
786
|
+
if (current.unavailable === undefined) {
|
|
787
|
+
const probe = await backend().probe(path.join(directory, `${key}${SIDECAR_SUFFIX}`), NATIVE_BUDGET_MS);
|
|
788
|
+
if (probe.state === FileLockProbeState.Free) return undefined;
|
|
789
|
+
if (probe.state === FileLockProbeState.Held) state = "held";
|
|
790
|
+
}
|
|
791
|
+
const record = readRecord(path.join(directory, `${key}${RECORD_SUFFIX}`));
|
|
792
|
+
return { key, state, self: false, ...describeRecord(record, key) };
|
|
793
|
+
};
|
|
794
|
+
for (let start = 0; start < keys.length; start += PROBE_CONCURRENCY) {
|
|
795
|
+
const found = await Promise.all(keys.slice(start, start + PROBE_CONCURRENCY).map(inspectOne));
|
|
796
|
+
for (const sidecar of found) if (sidecar) held.push(sidecar);
|
|
797
|
+
}
|
|
798
|
+
held.sort((a, b) => a.key.localeCompare(b.key));
|
|
799
|
+
return { directory: "present", ...counts, held };
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// =============================================================================
|
|
803
|
+
// Refusal
|
|
804
|
+
// =============================================================================
|
|
805
|
+
|
|
806
|
+
const SURFACE_NOUNS: Record<SessionOwnerBaseSurface, string> = {
|
|
807
|
+
app: "the Gajae Code app",
|
|
808
|
+
terminal: "another terminal",
|
|
809
|
+
print: "a gjc -p run",
|
|
810
|
+
"sdk-host": "an SDK session host",
|
|
811
|
+
"acp-host": "an ACP session host",
|
|
812
|
+
sdk: "an application using the gjc SDK",
|
|
813
|
+
};
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* How a holder is named to a person (design §3.4). The holder is checked again here, because a
|
|
817
|
+
* caller may build one: anything malformed reads as "another gjc process", never as raw text.
|
|
818
|
+
*/
|
|
819
|
+
export function sessionOwnerHolderPhrase(holder: SessionOwnerHolder | undefined): string {
|
|
820
|
+
if (!holder || !Number.isSafeInteger(holder.pid) || holder.pid <= 0 || !isSurface(holder.surface))
|
|
821
|
+
return "another gjc process";
|
|
822
|
+
if (holder.host !== undefined)
|
|
823
|
+
return SAFE_HOST.test(holder.host)
|
|
824
|
+
? `a gjc process on ${holder.host} (pid ${holder.pid})`
|
|
825
|
+
: "another gjc process";
|
|
826
|
+
const subagent = holder.surface.endsWith(" (subagent)");
|
|
827
|
+
const base = (subagent ? holder.surface.slice(0, -" (subagent)".length) : holder.surface) as SessionOwnerBaseSurface;
|
|
828
|
+
const noun = SURFACE_NOUNS[base];
|
|
829
|
+
return subagent ? `a subagent of ${noun} (pid ${holder.pid})` : `${noun} (pid ${holder.pid})`;
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/**
|
|
833
|
+
* A session another live process holds for writing. `message` is the stable machine code; the
|
|
834
|
+
* fixed, path-free `operatorMessage` is what a person sees.
|
|
835
|
+
*/
|
|
836
|
+
export class SessionHeldError extends Error {
|
|
837
|
+
readonly code = "session_held";
|
|
838
|
+
readonly sessionId: string;
|
|
839
|
+
readonly holder: SessionOwnerHolder | undefined;
|
|
840
|
+
readonly operatorMessage: string;
|
|
841
|
+
|
|
842
|
+
constructor(sessionId: string, holder?: SessionOwnerHolder) {
|
|
843
|
+
super("session_held");
|
|
844
|
+
this.name = "SessionHeldError";
|
|
845
|
+
this.sessionId = sessionId;
|
|
846
|
+
this.holder = holder;
|
|
847
|
+
// Only a safe id is quoted, shortened as the CLI shows it; any other id may hold any text.
|
|
848
|
+
const subject = SAFE_ID.test(sessionId) ? `Session ${sessionId.slice(0, 8)}` : "This session";
|
|
849
|
+
this.operatorMessage = `${subject} is open for writing in ${sessionOwnerHolderPhrase(holder)}. Only one process can write a session at a time. Close it there, or fork it to continue in a copy.`;
|
|
850
|
+
}
|
|
851
|
+
}
|