@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
@@ -0,0 +1,106 @@
1
+ import * as fs from "node:fs/promises";
2
+ import * as path from "node:path";
3
+ import { getTrustedHomeDir } from "@gajae-code/utils";
4
+ import {
5
+ countSessionOwnerEntries,
6
+ SESSION_OWNERS_RELATIVE_DIR,
7
+ type SessionOwnerEntryCounts,
8
+ } from "../../session/session-owners-layout";
9
+ import { type DoctorCollector, doctorCheck } from "./checks";
10
+ import { doctorErrno } from "./files";
11
+ import { canonicalDigest } from "./ids";
12
+ import { collectDoctorProbe, type DoctorProbeResult } from "./probe-client";
13
+ import type { DoctorCheck } from "./types";
14
+
15
+ /** Above this many sidecars, gc pruning is not keeping up (design §2.9). */
16
+ export const SESSION_OWNER_SIDECAR_LIMIT = 10_000;
17
+
18
+ /** The sidecar count, from `readdir` alone, so it stands even when the lock probe times out. */
19
+ function sidecarCheck(targetId: string, counts: SessionOwnerEntryCounts | { readonly errno?: string }): DoctorCheck {
20
+ if (!("sidecars" in counts))
21
+ return doctorCheck("session.owners.sidecars", targetId, {
22
+ execution: "blocked",
23
+ health: "unknown",
24
+ evidenceLevel: "observed",
25
+ reasonCode: "session_owner_sidecars_unreadable",
26
+ evidence: counts.errno ? { errno: counts.errno } : {},
27
+ });
28
+ const over = counts.sidecars > SESSION_OWNER_SIDECAR_LIMIT;
29
+ return doctorCheck("session.owners.sidecars", targetId, {
30
+ execution: "completed",
31
+ health: over ? "warning" : "ok",
32
+ evidenceLevel: "observed",
33
+ reasonCode: over ? "session_owner_sidecars_over_limit" : "session_owner_sidecars_within_limit",
34
+ evidence: {
35
+ count: counts.sidecars,
36
+ counts: { records: counts.records, unrecognized: counts.unrecognized, limit: SESSION_OWNER_SIDECAR_LIMIT },
37
+ },
38
+ });
39
+ }
40
+
41
+ /** The holders check from the probe child, or why the probe gave none. */
42
+ function holdersChecks(targetId: string, result: DoctorProbeResult): DoctorCheck[] {
43
+ if (result.status === "completed" && result.receipt)
44
+ return result.receipt.checks
45
+ .filter(check => check.id === "session.owners.holders")
46
+ .map(check => ({ ...check, targetId }));
47
+ return [
48
+ doctorCheck("session.owners.holders", targetId, {
49
+ execution: result.status === "timeout" ? "timeout" : result.status === "cancelled" ? "cancelled" : "blocked",
50
+ health: "unknown",
51
+ evidenceLevel: "observed",
52
+ reasonCode: result.reasonCode,
53
+ }),
54
+ ];
55
+ }
56
+
57
+ /** Both checks for a present owners directory; exported for tests of the probe-failure paths. */
58
+ export function sessionOwnersChecks(
59
+ targetId: string,
60
+ counts: SessionOwnerEntryCounts | { readonly errno?: string },
61
+ probe: DoctorProbeResult,
62
+ ): DoctorCheck[] {
63
+ return [...holdersChecks(targetId, probe), sidecarCheck(targetId, counts)];
64
+ }
65
+
66
+ /**
67
+ * Session ownership (design §2.9). A home with no owners directory has nothing to check, so no
68
+ * probe runs. Otherwise the sidecar count comes from `readdir` here, and a probe child does the
69
+ * lock work, as native code may fail to load.
70
+ */
71
+ export const SESSION_COLLECTOR: DoctorCollector = {
72
+ id: "session",
73
+ dependsOn: [],
74
+ timeoutMs: 5_000,
75
+ async collect(context) {
76
+ let owners: string;
77
+ try {
78
+ owners = path.join(getTrustedHomeDir(), SESSION_OWNERS_RELATIVE_DIR);
79
+ } catch {
80
+ owners = "";
81
+ }
82
+ const targetId = `t1:session-owners:r${canonicalDigest(["session-owners", owners])}`;
83
+ const absent =
84
+ owners !== "" &&
85
+ (await fs.lstat(owners).then(
86
+ () => false,
87
+ (error: NodeJS.ErrnoException) => error.code === "ENOENT",
88
+ ));
89
+ if (absent)
90
+ return ["session.owners.holders", "session.owners.sidecars"].map(id =>
91
+ doctorCheck(id, targetId, {
92
+ execution: "completed",
93
+ health: "not_applicable",
94
+ evidenceLevel: "observed",
95
+ reasonCode: "session_owners_absent",
96
+ }),
97
+ );
98
+ let counts: SessionOwnerEntryCounts | { readonly errno?: string };
99
+ try {
100
+ counts = countSessionOwnerEntries(owners);
101
+ } catch (error) {
102
+ counts = { errno: doctorErrno(error) };
103
+ }
104
+ return sessionOwnersChecks(targetId, counts, await collectDoctorProbe(context, "session-owners"));
105
+ },
106
+ };
@@ -38,6 +38,10 @@ export interface GithubReleaseLookupOptions {
38
38
  webOrigin?: string;
39
39
  timeoutMs?: number;
40
40
  useAmbientToken?: boolean;
41
+ /** Skip releases that don't have this binary asset. */
42
+ requiredBinaryAsset?: string;
43
+ /** Callback to log when a release is skipped due to missing asset. */
44
+ onSkippedRelease?: (tag: string, version: string) => void;
41
45
  }
42
46
 
43
47
  /** A GitHub REST response that failed, carrying the status the caller must branch on. */
@@ -64,12 +68,30 @@ interface GithubReleaseJson {
64
68
  draft?: unknown;
65
69
  prerelease?: unknown;
66
70
  html_url?: unknown;
71
+ assets?: unknown[];
72
+ }
73
+
74
+ interface GithubReleaseAsset {
75
+ name?: unknown;
67
76
  }
68
77
 
69
78
  export function isSafeReleaseTag(tag: string): boolean {
70
79
  return TAG_RE.test(tag) && !tag.includes("..") && !tag.includes("/");
71
80
  }
72
81
 
82
+ /**
83
+ * Check if a release has a binary asset matching the given name.
84
+ */
85
+ export function releaseHasBinaryAsset(release: GithubReleaseJson, assetName: string): boolean {
86
+ if (!Array.isArray(release.assets)) return false;
87
+ for (const asset of release.assets) {
88
+ if (typeof asset !== "object" || asset === null) continue;
89
+ const record = asset as GithubReleaseAsset;
90
+ if (record.name === assetName) return true;
91
+ }
92
+ return false;
93
+ }
94
+
73
95
  export function versionFromTag(tag: string): string {
74
96
  return tag.startsWith("v") ? tag.slice(1) : tag;
75
97
  }
@@ -204,6 +226,84 @@ export async function fetchGithubChannelRelease(options: GithubReleaseLookupOpti
204
226
  "The nightly channel has no published GitHub prerelease yet; it is populated by the scheduled nightly workflow.",
205
227
  );
206
228
  }
229
+
230
+ // For stable releases, when checking for binary assets, fetch multiple releases
231
+ // to find one with the required asset. If not checking for assets, use the
232
+ // traditional /releases/latest endpoint.
233
+ if (options.requiredBinaryAsset) {
234
+ try {
235
+ const fetchImpl = options.fetchImpl ?? fetch;
236
+ const timeoutMs = options.timeoutMs ?? 20_000;
237
+ const token = options.useAmbientToken ? readToken(options.lookupEnv) : undefined;
238
+ let page = 1;
239
+ let hasNextPage = true;
240
+
241
+ while (hasNextPage) {
242
+ const listUrl = `${apiOrigin}/repos/${RELEASE_REPO}/releases?per_page=50&page=${page}`;
243
+ const response = await fetchImpl(listUrl, {
244
+ headers: githubReleaseHeaders(token),
245
+ signal: AbortSignal.timeout(timeoutMs),
246
+ redirect: "follow",
247
+ });
248
+
249
+ if (!response.ok) {
250
+ throw new GithubApiStatusError(listUrl, response.status);
251
+ }
252
+
253
+ const payload = await response.json();
254
+ if (!Array.isArray(payload)) {
255
+ throw new Error(`${listUrl} did not return a release list`);
256
+ }
257
+
258
+ // Check if there's a next page by looking at the Link header
259
+ const linkHeader = response.headers.get("link");
260
+ hasNextPage = linkHeader?.includes('rel="next"') ?? false;
261
+
262
+ for (const entry of payload) {
263
+ if (typeof entry !== "object" || entry === null) continue;
264
+ const record = entry as GithubReleaseJson;
265
+ if (record.draft === true || record.prerelease === true) continue;
266
+ const tag = typeof record.tag_name === "string" ? record.tag_name : "";
267
+ if (!isSafeReleaseTag(tag)) continue;
268
+ const version = versionFromTag(tag);
269
+ if (!STABLE_VERSION_RE.test(version)) continue;
270
+
271
+ // Check if this release has the required asset
272
+ if (!releaseHasBinaryAsset(record, options.requiredBinaryAsset)) {
273
+ if (options.onSkippedRelease) {
274
+ options.onSkippedRelease(tag, version);
275
+ }
276
+ continue;
277
+ }
278
+
279
+ return {
280
+ tag,
281
+ version,
282
+ channel,
283
+ htmlUrl: typeof record.html_url === "string" ? record.html_url : undefined,
284
+ warnings: [],
285
+ };
286
+ }
287
+
288
+ page++;
289
+ }
290
+
291
+ // If we get here, no release with the asset was found after paginating through all releases
292
+ throw new Error(
293
+ `The stable channel has no published release with the ${options.requiredBinaryAsset} asset yet`,
294
+ );
295
+ } catch (error) {
296
+ if (error instanceof GithubApiStatusError && error.isRateLimited) {
297
+ // When checking for assets, rate-limit is a hard error because we cannot fall back
298
+ // to web lookups without losing the asset predicate.
299
+ throw new Error(
300
+ `${error.message} during binary asset verification. ${TOKEN_HINT}. Install updates using the npm registry (bun install -g gajae-code@latest) or wait for rate-limit reset.`,
301
+ );
302
+ }
303
+ throw error;
304
+ }
305
+ }
306
+
207
307
  const url = `${apiOrigin}/repos/${RELEASE_REPO}/releases/latest`;
208
308
  try {
209
309
  return parseRelease(await readGithubJson(url, options), "stable");
@@ -0,0 +1,118 @@
1
+ /**
2
+ * `gjc session owners`: which processes hold sessions open for writing (design §2.9).
3
+ *
4
+ * Read-only. It probes sidecar locks and reads holder records; it never claims, breaks or
5
+ * rewrites anything, and never creates the owners directory. Every printed field comes from
6
+ * {@link inspectSessionOwners}, which checks record fields against fixed shapes.
7
+ */
8
+ import { formatBytes, formatDuration } from "@gajae-code/utils";
9
+ import { nativeProcessBindings } from "@gajae-code/utils/native-process";
10
+ import {
11
+ inspectSessionOwners,
12
+ type SessionOwnerSidecar,
13
+ SessionOwnershipError,
14
+ type SessionOwnersInventory,
15
+ } from "../session/session-ownership";
16
+
17
+ const MAX_ANCESTORS = 64;
18
+
19
+ /** This process's ancestors, nearest first; init and anything unreadable end the walk. */
20
+ function processAncestors(): Set<number> {
21
+ const ancestors = new Set<number>();
22
+ let pid: number | null | undefined = process.ppid;
23
+ while (pid && pid > 1 && !ancestors.has(pid) && ancestors.size < MAX_ANCESTORS) {
24
+ ancestors.add(pid);
25
+ try {
26
+ pid = nativeProcessBindings().Process.fromPid(pid)?.ppid;
27
+ } catch {
28
+ pid = undefined;
29
+ }
30
+ }
31
+ return ancestors;
32
+ }
33
+
34
+ export interface SessionOwnerRow extends SessionOwnerSidecar {
35
+ /** Held by this process or one of its ancestors (a gjc whose shell ran this command). */
36
+ readonly processTree: boolean;
37
+ readonly ageMs?: number;
38
+ }
39
+
40
+ export interface SessionOwnersReport extends Omit<SessionOwnersInventory, "held"> {
41
+ readonly owners: readonly SessionOwnerRow[];
42
+ }
43
+
44
+ export async function collectSessionOwnersReport(now = Date.now()): Promise<SessionOwnersReport> {
45
+ const inventory = await inspectSessionOwners();
46
+ const ancestors = processAncestors();
47
+ const { held, ...counts } = inventory;
48
+ const owners = held.map((sidecar): SessionOwnerRow => {
49
+ const holder = sidecar.holder;
50
+ const claimedAt = holder?.claimedAt ? Date.parse(holder.claimedAt) : Number.NaN;
51
+ const ageMs = Number.isFinite(claimedAt) && claimedAt <= now ? now - claimedAt : undefined;
52
+ const processTree =
53
+ sidecar.self || (holder !== undefined && holder.host === undefined && ancestors.has(holder.pid));
54
+ return { ...sidecar, processTree, ...(ageMs === undefined ? {} : { ageMs }) };
55
+ });
56
+ return { ...counts, owners };
57
+ }
58
+
59
+ function ownerLine(owner: SessionOwnerRow): string {
60
+ const fields = [owner.sessionId ?? owner.key];
61
+ const holder = owner.holder;
62
+ if (owner.state === "unknown") fields.push("lock state unknown");
63
+ if (holder) {
64
+ fields.push(holder.surface, `pid ${holder.pid}`);
65
+ if (holder.host) fields.push(`host ${holder.host}`);
66
+ if (owner.ageMs !== undefined) fields.push(`held ${formatDuration(owner.ageMs)}`);
67
+ if (holder.gjcVersion) fields.push(`gjc ${holder.gjcVersion}`);
68
+ if (owner.self) fields.push("this process");
69
+ } else if (owner.record === "holder_gone") fields.push(`holder pid ${owner.gonePid} is gone (record is stale)`);
70
+ else fields.push(`another gjc process (record ${owner.record})`);
71
+ return ` ${fields.join(" ")}`;
72
+ }
73
+
74
+ export function renderSessionOwnersText(report: SessionOwnersReport): string[] {
75
+ if (report.directory === "missing" && report.owners.length === 0)
76
+ return ["No session owners directory: no session has been claimed under this home."];
77
+ const lines = [
78
+ `Sidecars: ${report.sidecars}, records: ${report.records}, on disk: ${formatBytes(report.diskBytes)}` +
79
+ (report.unrecognized > 0 ? `, unrecognized entries: ${report.unrecognized}` : ""),
80
+ ];
81
+ const tree = report.owners.filter(owner => owner.processTree);
82
+ const others = report.owners.filter(owner => !owner.processTree);
83
+ lines.push("Held by this process tree:", ...(tree.length > 0 ? tree.map(ownerLine) : [" none"]));
84
+ lines.push("Held by other processes:", ...(others.length > 0 ? others.map(ownerLine) : [" none"]));
85
+ return lines;
86
+ }
87
+
88
+ /** A refusal the operator can act on: a fixed message and a machine code, never a stack or a path. */
89
+ function commandFailure(error: unknown): { code: string; message: string } | undefined {
90
+ if (error instanceof SessionOwnershipError) return { code: error.code, message: error.operatorMessage };
91
+ const errno = (error as { code?: unknown } | undefined)?.code;
92
+ if (typeof errno === "string" && /^E[A-Z0-9]+$/.test(errno))
93
+ return { code: errno, message: `gjc could not read the session owners directory (${errno}).` };
94
+ return undefined;
95
+ }
96
+
97
+ /** `gjc session owners [--json]`. A refused or unreadable directory exits 1 with its code. */
98
+ export async function runSessionOwnersCommand(json: boolean): Promise<void> {
99
+ let report: SessionOwnersReport;
100
+ try {
101
+ report = await collectSessionOwnersReport();
102
+ } catch (error) {
103
+ const failure = commandFailure(error);
104
+ if (!failure) throw error;
105
+ if (json)
106
+ process.stdout.write(
107
+ `${JSON.stringify({ ok: false, reason: "session_owners_unavailable", code: failure.code }, null, 2)}\n`,
108
+ );
109
+ else process.stderr.write(`${failure.message}\n`);
110
+ process.exitCode = 1;
111
+ return;
112
+ }
113
+ process.stdout.write(
114
+ json
115
+ ? `${JSON.stringify({ ok: true, ...report }, null, 2)}\n`
116
+ : `${renderSessionOwnersText(report).join("\n")}\n`,
117
+ );
118
+ }
@@ -136,7 +136,7 @@ export async function runStatsCommand(cmd: StatsCommandArgs): Promise<void> {
136
136
  async function printStatsSummary(): Promise<void> {
137
137
  const { getDashboardStats } = await import("@gajae-code/stats");
138
138
  const stats = await getDashboardStats();
139
- const { overall, failures, byModel, byFolder, byAgent, cacheMissAttribution } = stats;
139
+ const { overall, failures, byModel, byFolder, byAgent, cacheMissAttribution, sessionOwnership } = stats;
140
140
 
141
141
  console.log(chalk.bold("\n=== AI Usage Statistics ===\n"));
142
142
 
@@ -210,6 +210,24 @@ async function printStatsSummary(): Promise<void> {
210
210
  }
211
211
  }
212
212
 
213
+ // Recorded only by processes with session ownership on; absent otherwise.
214
+ // Names and versions are checked by the reader (plain identifiers), so they print as they are.
215
+ if (sessionOwnership) {
216
+ const day = (ms: number) => new Date(ms).toISOString().slice(0, 10);
217
+ const list = (counters: Readonly<Record<string, number>>) =>
218
+ Object.entries(counters)
219
+ .map(([name, count]) => `${name}=${count}`)
220
+ .join(", ");
221
+ console.log(chalk.bold("\nSession Ownership (local counters, all time):"));
222
+ console.log(
223
+ ` Recorded: ${day(sessionOwnership.firstAt)} to ${day(sessionOwnership.lastAt)}, ${sessionOwnership.reports} process reports`,
224
+ );
225
+ for (const [name, count] of Object.entries(sessionOwnership.counters)) console.log(` ${name}: ${count}`);
226
+ console.log(" By version:");
227
+ for (const [version, entry] of Object.entries(sessionOwnership.byVersion))
228
+ console.log(` ${version} (${entry.reports} reports): ${list(entry.counters)}`);
229
+ }
230
+
213
231
  console.log("");
214
232
  }
215
233
 
@@ -472,23 +472,65 @@ async function resolveUpdateTarget(): Promise<UpdateTarget> {
472
472
  /** Lookup options for the GitHub release check. */
473
473
  export interface LatestReleaseLookupOptions extends GithubReleaseLookupOptions {
474
474
  channel?: UpdateChannel;
475
+ /** When true for stable releases, checks that the release has the binary asset for the current platform. */
476
+ forBinaryUpdate?: boolean;
475
477
  }
476
478
 
477
479
  /**
478
480
  * Get the latest release info for a channel from GitHub releases.
479
481
  * Stable uses `/releases/latest`. Nightly uses the newest published prerelease.
482
+ * When checking for binary assets (stable channel with forBinaryUpdate=true),
483
+ * fetches multiple releases to find one with the binary for the current platform.
480
484
  */
481
485
  async function getLatestRelease(options?: LatestReleaseLookupOptions): Promise<ReleaseInfo> {
482
486
  const channel = options?.channel ?? "stable";
483
- const release = await fetchGithubChannelRelease({ ...options, channel, useAmbientToken: true });
487
+ const skippedReleases: Array<{ tag: string; version: string }> = [];
488
+ let requiredBinaryAsset = options?.requiredBinaryAsset;
489
+
490
+ const releaseOptions: typeof options & {
491
+ requiredBinaryAsset?: string;
492
+ onSkippedRelease?: (tag: string, version: string) => void;
493
+ } = {
494
+ ...options,
495
+ channel,
496
+ useAmbientToken: true,
497
+ };
498
+
499
+ // For stable releases when checking for binary updates, require the binary
500
+ // asset to be present and try multiple releases until we find one that has it
501
+ if (channel === "stable" && "forBinaryUpdate" in (options ?? {}) && options?.forBinaryUpdate) {
502
+ const binaryName = getBinaryName();
503
+ releaseOptions.requiredBinaryAsset = binaryName;
504
+ requiredBinaryAsset = binaryName;
505
+ }
506
+
507
+ // When checking for binary assets, set up callback to track skipped releases
508
+ // If a callback was already provided in options, we still need to track internally
509
+ if (releaseOptions.requiredBinaryAsset) {
510
+ const userCallback = releaseOptions.onSkippedRelease;
511
+ releaseOptions.onSkippedRelease = (tag, version) => {
512
+ skippedReleases.push({ tag, version });
513
+ if (userCallback) {
514
+ userCallback(tag, version);
515
+ }
516
+ };
517
+ }
518
+
519
+ const release = await fetchGithubChannelRelease(releaseOptions);
484
520
  if (!isSafeReleaseTag(release.tag)) {
485
521
  throw new Error(`Refusing unsafe GitHub release tag: ${release.tag}`);
486
522
  }
523
+
524
+ const warnings = [...(release.warnings || [])];
525
+ for (const skipped of skippedReleases) {
526
+ warnings.push(`release ${skipped.tag} has no asset for ${requiredBinaryAsset} yet`);
527
+ }
528
+
487
529
  return {
488
530
  tag: release.tag,
489
531
  version: release.version || versionFromTag(release.tag),
490
532
  registry: `https://github.com/${RELEASE_REPO}`,
491
- warnings: release.warnings,
533
+ warnings,
492
534
  };
493
535
  }
494
536
 
@@ -2185,9 +2227,14 @@ export async function runUpdateCommand(
2185
2227
  return flushTelemetryBeforeExit();
2186
2228
  }
2187
2229
 
2230
+ // For binary and migration updates, check that the release has the binary asset
2231
+ // for the current platform. Otherwise, fall back to the latest stable release
2232
+ // without checking for assets (e.g., for npm/bun installations).
2233
+ const forBinaryUpdate = target?.method === "binary" || target?.method === "migrate";
2234
+
2188
2235
  let release: ReleaseInfo;
2189
2236
  try {
2190
- release = await lookupRelease({ channel });
2237
+ release = await lookupRelease({ channel, forBinaryUpdate });
2191
2238
  } catch (err) {
2192
2239
  record("update_check_completed", { channel, result: "failed" });
2193
2240
  console.error(chalk.red(`Failed to check for updates: ${err}`));
@@ -179,7 +179,7 @@ export async function runOrdinaryCli(argv: string[]): Promise<void> {
179
179
  return;
180
180
  }
181
181
  if (argv[0] === "--internal-doctor-probe") {
182
- if (argv.length !== 2 || (argv[1] !== "native" && argv[1] !== "projection")) {
182
+ if (argv.length !== 2 || (argv[1] !== "native" && argv[1] !== "projection" && argv[1] !== "session-owners")) {
183
183
  process.stderr.write("gjc doctor: invalid internal probe invocation\n");
184
184
  process.exitCode = 2;
185
185
  return;
@@ -136,13 +136,16 @@ export async function lifecycleArgs(
136
136
  * How long a session host tolerates losing the broker it was launched under
137
137
  * before treating itself as orphaned.
138
138
  *
139
- * A host is reachable only through its own broker: routing lives in the broker
140
- * process and a replacement broker never adopts hosts from an earlier
141
- * incarnation, so a host that outlives its broker is stranded no matter how
142
- * healthy the agent directory looks afterwards. The grace still has to outlast
143
- * a restart-shaped gap, because a broker that is merely slow to republish must
144
- * never cost a live host — but it must stay finite, or every crashed or
145
- * torn-down broker leaks a detached multi-hundred-megabyte host forever.
139
+ * Brokers route through the agent directory's session index and the host's
140
+ * endpoint file, not through per-broker state, so a replacement broker for the
141
+ * same agent directory reaches a host its predecessor launched. The window
142
+ * therefore only runs while no live broker is published at all. It still has to
143
+ * outlast a restart-shaped gap, because a broker that is merely slow to
144
+ * republish must never cost a live host, but it must stay finite for an idle
145
+ * host, or every broker that is gone for good leaks a detached
146
+ * multi-hundred-megabyte host. A host holding its session-work lease is the one
147
+ * exception: it never exits on broker absence, so a turn that never settles keeps
148
+ * the host alive until it is closed or signalled.
146
149
  */
147
150
  export const SESSION_HOST_BROKER_ABSENCE_GRACE_MS = 10 * 60_000;
148
151
  const SESSION_HOST_BROKER_POLL_MS = 15_000;
@@ -206,54 +209,56 @@ async function waitForBrokerStartupTestGate(gateFile: string): Promise<void> {
206
209
  }
207
210
 
208
211
  /**
209
- * Identity of the broker incarnation an observation describes, or `null` when
210
- * it carries no usable identity.
211
- *
212
- * Two observations with different identities are two different brokers, never
213
- * the same broker seen twice: `incarnation` is start-time derived, so it
214
- * separates a genuine survivor from a successor that merely reused the pid.
212
+ * Whether a discovery observation identifies a broker at all (owner id, pid or
213
+ * incarnation). Which broker it is does not matter to a session host: any live
214
+ * broker for the agent directory can route to it.
215
215
  */
216
- function brokerPublicationIdentity(observation: unknown): string | null {
217
- if (!observation || typeof observation !== "object") return null;
216
+ function isIdentifiedBrokerPublication(observation: unknown): boolean {
217
+ if (!observation || typeof observation !== "object") return false;
218
218
  const { ownerId, pid, incarnation } = observation as {
219
219
  ownerId?: unknown;
220
220
  pid?: unknown;
221
221
  incarnation?: unknown;
222
222
  };
223
- const parts = [
224
- typeof ownerId === "string" ? ownerId : "",
225
- Number.isSafeInteger(pid) ? String(pid) : "",
226
- typeof incarnation === "string" ? incarnation : "",
227
- ];
228
- return parts.some(part => part !== "") ? parts.join(":") : null;
223
+ return (
224
+ (typeof ownerId === "string" && ownerId !== "") ||
225
+ Number.isSafeInteger(pid) ||
226
+ (typeof incarnation === "string" && incarnation !== "")
227
+ );
229
228
  }
230
229
 
231
230
  /**
232
- * Resolves only once the broker this host was launched under has been
233
- * unobservable for the full grace window.
231
+ * Resolves only once no live broker has been published for the agent directory
232
+ * for the full grace window, and the host is not doing session work.
234
233
  *
235
- * The first identifiable publication pins that broker. A later publication from
236
- * a different incarnation is a replacement, and a replacement cannot route to
237
- * this host — observing one is evidence of being stranded, not of being alive —
238
- * so it accrues against the bound instead of resetting it. Only the pinned
239
- * broker reappearing resets the window. An unreadable or unidentifiable
234
+ * Any identifiable publication resets the window, including one from a
235
+ * replacement incarnation: the replacement routes through the shared session
236
+ * index, so it can still reach this host. An unreadable or unidentifiable
240
237
  * publication is not proof of orphanhood but accrues against the same bound.
238
+ *
239
+ * `readWorkLease` reports whether the host's session-work lease is held. It
240
+ * defaults to the lease the host's SDK runtime publishes (the AgentSession's
241
+ * `sessionWorkLease`, registered by the notifications bus at host startup). A
242
+ * turn in flight is never cut short by broker absence: the window keeps
243
+ * accruing, but the host only exits once the lease is released. If the bound was
244
+ * crossed during the turn, the host exits on the first poll after the turn ends.
241
245
  */
242
246
  export async function watchSessionHostBrokerLiveness(deps: {
243
247
  agentDir: string;
244
248
  now?: () => number;
245
249
  sleep?: (ms: number) => Promise<void>;
246
250
  readDiscovery?: (agentDir: string) => Promise<unknown>;
251
+ readWorkLease?: () => boolean;
247
252
  graceMs?: number;
248
253
  pollMs?: number;
249
254
  }): Promise<void> {
250
255
  const now = deps.now ?? Date.now;
251
256
  const sleep = deps.sleep ?? (async ms => await Bun.sleep(ms));
252
257
  const readDiscovery = deps.readDiscovery ?? readBrokerDiscovery;
258
+ const readWorkLease = deps.readWorkLease ?? sessionHostWorkLeaseActive;
253
259
  const graceMs = deps.graceMs ?? SESSION_HOST_BROKER_ABSENCE_GRACE_MS;
254
260
  const pollMs = deps.pollMs ?? SESSION_HOST_BROKER_POLL_MS;
255
261
  let absentSince: number | null = null;
256
- let ownBroker: string | null = null;
257
262
  for (;;) {
258
263
  let live: unknown = null;
259
264
  try {
@@ -261,13 +266,11 @@ export async function watchSessionHostBrokerLiveness(deps: {
261
266
  } catch {
262
267
  // Transient read failures are ambiguity, not proof of orphanhood.
263
268
  }
264
- const identity = brokerPublicationIdentity(live);
265
- if (identity !== null && (ownBroker === null || identity === ownBroker)) {
266
- ownBroker ??= identity;
269
+ if (isIdentifiedBrokerPublication(live)) {
267
270
  absentSince = null;
268
271
  } else {
269
272
  absentSince ??= now();
270
- if (now() - absentSince >= graceMs) return;
273
+ if (now() - absentSince >= graceMs && !readWorkLease()) return;
271
274
  }
272
275
  await sleep(pollMs);
273
276
  }
@@ -1,4 +1,5 @@
1
1
  import { Args, Command, Flags } from "@gajae-code/utils/cli";
2
+ import { runSessionOwnersCommand } from "../cli/session-owners-cli";
2
3
  import {
3
4
  attachGjcTmuxSession,
4
5
  createGjcTmuxSession,
@@ -45,12 +46,13 @@ function sessionJson(session: SessionJsonDto): SessionJsonDto {
45
46
  }
46
47
 
47
48
  export default class Session extends Command {
48
- static description = "List, inspect, attach, and remove tagged GJC-managed tmux sessions";
49
+ static description =
50
+ "List, inspect, attach, and remove tagged GJC-managed tmux sessions, or list session owners (`owners`)";
49
51
  static strict = false;
50
52
 
51
53
  static args = {
52
54
  action: Args.string({
53
- description: "list (default), status, create, attach, or remove",
55
+ description: "list (default), status, create, attach, remove, or owners",
54
56
  required: false,
55
57
  }),
56
58
  session: Args.string({
@@ -76,6 +78,7 @@ export default class Session extends Command {
76
78
  "gjc session attach <session>",
77
79
  "gjc session remove <session>",
78
80
  "gjc session force-close <session> --session-id <id>",
81
+ "gjc session owners --json",
79
82
  ];
80
83
 
81
84
  async run(): Promise<void> {
@@ -115,6 +118,11 @@ export default class Session extends Command {
115
118
  return;
116
119
  }
117
120
 
121
+ if (action === "owners") {
122
+ await runSessionOwnersCommand(json);
123
+ return;
124
+ }
125
+
118
126
  if (!sessionName) throw new Error("missing_session_name");
119
127
 
120
128
  if (action === "status") {
@@ -479,6 +479,16 @@ export const SETTINGS_SCHEMA = {
479
479
  values: ["copy-retain", "disabled"] as const,
480
480
  default: "copy-retain",
481
481
  },
482
+ // Single-owner session claims. The whole `session.ownership.` namespace is global-only (see
483
+ // settings.ts), and later sub-flags sit beside `mode`, so the mode is a leaf, not the parent.
484
+ // Hidden from the UI while the claims are wired in; `off` makes no claim and no lock call.
485
+ "session.ownership.mode": {
486
+ type: "enum",
487
+ // Kept equal to SESSION_OWNERSHIP_MODES (a test checks); listed here so the schema imports nothing new.
488
+ values: ["off", "observe", "enforce"] as const,
489
+ default: "off",
490
+ description: "Not yet active; reserved for single-owner session claims.",
491
+ },
482
492
  "workspaceTree.mode": {
483
493
  type: "enum",
484
494
  values: ["eager", "lazy"] as const,
@@ -4553,6 +4563,14 @@ export function validateSettingPatch(patch: Record<string, unknown>): Array<{ pa
4553
4563
  });
4554
4564
  continue;
4555
4565
  }
4566
+ if (path === "session.ownership" || path.startsWith("session.ownership.")) {
4567
+ issues.push({
4568
+ path,
4569
+ detail:
4570
+ "Session ownership settings need operator consent: use gjc config set or the config file, not config.patch.",
4571
+ });
4572
+ continue;
4573
+ }
4556
4574
  if (NOTIFICATION_BINDING_PATCH_PATHS.has(path as SettingPath)) {
4557
4575
  issues.push({
4558
4576
  path,