Skip to content

Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA

TypeScript

v1.91.88.0 fix(memory): transcript ingest lands on managed gbrain 0.60, /retro global counts every session (Wave 9 Lane F) (#3136)

Garry Tan3d52b269051e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a810bb6a3..c1ba6f111 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,15 @@
# Changelog
+## [1.91.88.0] - 2026-10-11
+
+**Transcript ingest lands on gbrain 0.60, and `/retro global` counts every Claude Code session in its real repository.**
+
+- **Transcript sources get a checkout (#3097).** gbrain 0.60's managed persistence refuses any import into a source with no active worktree binding on this host, and gstack registered every transcript source path-less, so every transcript page was refused (`owner_unavailable`) on every run. On a managed brain each transcript source is now bound to its own checkout, `<state root>/gbrain-transcript-sources/<source-id>/`, created by gstack as a git repository of its own (so gbrain binds that directory and never an enclosing checkout such as a brain-synced state root). A path-less source an earlier run registered is bound on the next run, the same way `gbrain sources add <id> --path` attaches a path to it; a resumed timeout checkpoint is admitted the same way before it imports. After each import the checkout holds one commit, the current page files, amended in place with no reflog so `git gc --auto` prunes old snapshots; it stays uncommitted while any page in the source lacks its file, so `gbrain sync` of the source can never soft-delete those pages. gstack never binds a source someone else holds (another host, or another directory on this host) and prints the owner, the inspect command and the release or re-bind commands, and it binds nothing under an ephemeral state root (`GSTACK_EPHEMERAL=1`). Classic (unmanaged) brains keep path-less sources, unchanged.
+- **global-discover reads the session's own cwd (#1315).** Claude Code project directories were decoded by turning every `-` into `/`, which fails for every hyphenated path, and the cwd fallback read a 64 KB prefix that recent sessions' first record outgrows. Each session's cwd is now read from its own JSONL, whole lines up to 1 MiB (a longer line is skipped and counted in a warning), and resolved through git to its worktree root: root and subdirectory sessions count the same, linked worktrees count with their repository, a nested repository counts as itself, and sessions outside a repository are not counted as one.
+
+Thanks @Simba3696 for the root-cause diagnosis (#3097).
+Thanks @Akagilnc for the two-bug diagnosis and measurements (#1315).
+
## [1.91.87.0] - 2026-10-11
**The paid CSO producer gives `/cso` the Agent tool users have, so independent review and repair verification can run in the evaluation. The producer's receipt now counts subagent tokens.**
diff --git a/VERSION b/VERSION
index 96604cf14..3556d31f1 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.91.87.0
+1.91.88.0
diff --git a/agents-digest/gstack-AGENTS.md b/agents-digest/gstack-AGENTS.md
index d7bacbb05..2e53138ce 100644
--- a/agents-digest/gstack-AGENTS.md
+++ b/agents-digest/gstack-AGENTS.md
@@ -1,4 +1,4 @@
-# gstack digest v1.91.87.0 — regenerate/re-copy after upgrading gstack
+# gstack digest v1.91.88.0 — regenerate/re-copy after upgrading gstack
Behavioral rules from gstack (https://github.com/garrytan/gstack), compressed
for agent hosts without a full skill install. The full skills add workflows,
diff --git a/bin/gstack-global-discover.ts b/bin/gstack-global-discover.ts
index 2361a2327..6703c64ae 100644
--- a/bin/gstack-global-discover.ts
+++ b/bin/gstack-global-discover.ts
@@ -10,8 +10,8 @@
*/
import { existsSync, readdirSync, statSync, readFileSync, openSync, readSync, closeSync } from "fs";
-import { join, basename, dirname } from "path";
-import { execSync } from "child_process";
+import { join, basename, dirname, resolve } from "path";
+import { spawnSync } from "child_process";
import { homedir } from "os";
import { canonicalRemote } from "../lib/remote-identity";
@@ -153,31 +153,65 @@ export function normalizeRemoteUrl(url: string): string {
// ── Git helpers ────────────────────────────────────────────────────────────
-function isGitRepo(dir: string): boolean {
- return existsSync(join(dir, ".git"));
+interface GitProject {
+ /** Worktree root the session ran in (a linked worktree is its own root). */
+ root: string;
+ /** The repository's main worktree, shared by its linked worktrees. */
+ main: string;
}
-function getGitRemote(cwd: string): string | null {
- if (!existsSync(cwd) || !isGitRepo(cwd)) return null;
- try {
- const remote = execSync("git remote get-url origin", {
- cwd,
+const PROJECT_MEMO = new Map<string, GitProject | null>();
+
+/**
+ * The git project a session's recorded cwd belongs to: its worktree root and
+ * the repository it shares with linked worktrees. A subdirectory resolves to
+ * the same root as the root itself; a cwd outside any work tree (a plain
+ * directory, or inside .git) has no project.
+ */
+function gitProject(cwd: string): GitProject | null {
+ const memo = PROJECT_MEMO.get(cwd);
+ if (memo !== undefined) return memo;
+ let project: GitProject | null = null;
+ if (existsSync(cwd)) {
+ const r = spawnSync("git", ["-C", cwd, "rev-parse", "--is-inside-work-tree", "--show-prefix", "--path-format=absolute", "--git-common-dir"], {
encoding: "utf-8",
timeout: 5000,
- stdio: ["pipe", "pipe", "pipe"],
- }).trim();
- return remote || null;
- } catch (err: any) {
- // Expected: no remote configured, repo not found, git not installed
- if (err?.status !== undefined) return null; // non-zero exit from git
- if (err?.code === 'ENOENT') return null; // git binary not found
- throw err;
+ stdio: ["ignore", "pipe", "ignore"],
+ });
+ const [inside, prefix, common] = r.status === 0 ? r.stdout.replace(/\r?\n$/, "").split(/\r?\n/) : [];
+ if (inside === "true" && prefix !== undefined && common) {
+ // Strip the prefix from the recorded cwd instead of taking git's
+ // --show-toplevel, so the root keeps the session's own spelling
+ // (a symlinked home, a native Windows drive path).
+ const up = prefix.split("/").filter(Boolean).map(() => "..");
+ project = { root: resolve(cwd, ...up), main: basename(common) === ".git" ? dirname(common) : common };
+ }
}
+ PROJECT_MEMO.set(cwd, project);
+ return project;
+}
+
+function getGitRemote(root: string): string | null {
+ const r = spawnSync("git", ["-C", root, "remote", "get-url", "origin"], {
+ encoding: "utf-8",
+ timeout: 5000,
+ stdio: ["ignore", "pipe", "ignore"],
+ });
+ return r.status === 0 && r.stdout.trim() ? r.stdout.trim() : null;
}
// ── Scanners ───────────────────────────────────────────────────────────────
-function scanClaudeCode(since: Date): Session[] {
+/** JSONL lines longer than this are skipped (and counted) while looking for a session's cwd. */
+const MAX_CWD_LINE_BYTES = 1024 * 1024;
+const MAX_CWD_LINES = 30;
+const MAX_CWD_SCAN_BYTES = 16 * 1024 * 1024;
+
+export interface CwdScanStats {
+ oversizedLines: number;
+}
+
+function scanClaudeCode(since: Date, stats: CwdScanStats): Session[] {
const projectsDir = join(homedir(), ".claude", "projects");
if (!existsSync(projectsDir)) return [];
@@ -193,115 +227,99 @@ function scanClaudeCode(since: Date): Session[] {
for (const dirName of dirs) {
const dirPath = join(projectsDir, dirName);
+ let recentFiles: string[];
try {
- const stat = statSync(dirPath);
- if (!stat.isDirectory()) continue;
- } catch {
- continue;
- }
-
- // Find JSONL files
- let jsonlFiles: string[];
- try {
- jsonlFiles = readdirSync(dirPath).filter((f) => f.endsWith(".jsonl"));
+ if (!statSync(dirPath).isDirectory()) continue;
+ recentFiles = readdirSync(dirPath).filter((f) => {
+ if (!f.endsWith(".jsonl")) return false;
+ try {
+ return statSync(join(dirPath, f)).mtime >= since;
+ } catch {
+ return false;
+ }
+ });
} catch {
continue;
}
- if (jsonlFiles.length === 0) continue;
- // Coarse mtime pre-filter: check if any JSONL file is recent
- const hasRecentFile = jsonlFiles.some((f) => {
- try {
- return statSync(join(dirPath, f)).mtime >= since;
- } catch (err: any) {
- if (err?.code === 'ENOENT' || err?.code === 'EACCES') return false;
- throw err;
- }
- });
- if (!hasRecentFile) continue;
-
- // Resolve cwd
- let cwd = resolveClaudeCodeCwd(dirPath, dirName, jsonlFiles);
- if (!cwd) continue;
-
- // Count only JSONL files modified within the window as sessions
- const recentFiles = jsonlFiles.filter((f) => {
- try {
- return statSync(join(dirPath, f)).mtime >= since;
- } catch (err: any) {
- if (err?.code === 'ENOENT' || err?.code === 'EACCES') return false;
- throw err;
- }
- });
- for (let i = 0; i < recentFiles.length; i++) {
- sessions.push({ tool: "claude_code", cwd });
+ // The project is the cwd each session recorded, never the directory name:
+ // Claude Code encodes "/" and "-" alike as "-", so the name cannot be
+ // decoded (#1315). A session that recorded no cwd in its first lines
+ // belongs to the same project as its siblings in this directory.
+ const cwds = recentFiles.map((f) => extractCwdFromJsonl(join(dirPath, f), stats));
+ const sibling = cwds.find((c): c is string => !!c);
+ for (const cwd of cwds) {
+ const resolved = cwd ?? sibling;
+ if (resolved) sessions.push({ tool: "claude_code", cwd: resolved });
}
}
return sessions;
}
-function resolveClaudeCodeCwd(
- dirPath: string,
- dirName: string,
- jsonlFiles: string[]
-): string | null {
- // Fast-path: decode directory name
- // e.g., -Users-garrytan-git-repo → /Users/garrytan/git/repo
- const decoded = dirName.replace(/^-/, "/").replace(/-/g, "/");
- if (existsSync(decoded)) return decoded;
-
- // Fallback: read cwd from first JSONL file
- // Sort by mtime descending, pick most recent
- const sorted = jsonlFiles
- .map((f) => {
- try {
- return { name: f, mtime: statSync(join(dirPath, f)).mtime.getTime() };
- } catch (err: any) {
- if (err?.code === 'ENOENT' || err?.code === 'EACCES') return null;
- throw err;
- }
- })
- .filter(Boolean)
- .sort((a, b) => b!.mtime - a!.mtime) as { name: string; mtime: number }[];
-
- for (const file of sorted.slice(0, 3)) {
- const cwd = extractCwdFromJsonl(join(dirPath, file.name));
- if (cwd && existsSync(cwd)) return cwd;
+/**
+ * The cwd recorded in the first lines of a session JSONL. Lines are read whole
+ * up to 1 MiB each (Claude Code can open with a queue-operation record far
+ * larger than a fixed prefix); a longer line is skipped and counted in
+ * `stats.oversizedLines`, and the scan moves on to the next line.
+ */
+export function extractCwdFromJsonl(filePath: string, stats: CwdScanStats = { oversizedLines: 0 }): string | null {
+ let fd: number;
+ try {
+ fd = openSync(filePath, "r");
+ } catch {
+ return null;
}
-
- return null;
-}
-
-export function extractCwdFromJsonl(filePath: string): string | null {
- // Read a capped prefix so huge JSONL files don't blow up memory. 64KB
- // comfortably fits the largest observed session headers; the old 8KB cap
- // would sometimes fall inside a single long line and silently drop the
- // project (JSON.parse failure on the truncated tail).
- const MAX_BYTES = 64 * 1024;
- const MAX_LINES = 30;
try {
- const fd = openSync(filePath, "r");
- const buf = Buffer.alloc(MAX_BYTES);
- const bytesRead = readSync(fd, buf, 0, MAX_BYTES, 0);
- closeSync(fd);
- const text = buf.toString("utf-8", 0, bytesRead);
- // Drop the final segment — it may be an incomplete line at the cap boundary.
- const parts = text.split("\n");
- const completeLines = parts.length > 1 ? parts.slice(0, -1) : parts;
- for (const line of completeLines.slice(0, MAX_LINES)) {
- if (!line.trim()) continue;
+ const chunk = Buffer.alloc(64 * 1024);
+ let pieces: Buffer[] = [];
+ let lineBytes = 0;
+ let lines = 0;
+ let position = 0;
+ const endLine = (): string | null => {
+ lines++;
+ const oversized = lineBytes > MAX_CWD_LINE_BYTES;
+ const text = oversized ? "" : Buffer.concat(pieces).toString("utf-8");
+ pieces = [];
+ lineBytes = 0;
+ if (oversized) {
+ stats.oversizedLines++;
+ return null;
+ }
+ if (!text.trim()) return null;
try {
- const obj = JSON.parse(line);
- if (obj.cwd) return obj.cwd;
+ const obj = JSON.parse(text);
+ return typeof obj?.cwd === "string" && obj.cwd ? obj.cwd : null;
} catch {
- continue;
+ return null;
+ }
+ };
+ const keep = (part: Buffer) => {
+ lineBytes += part.length;
+ if (lineBytes <= MAX_CWD_LINE_BYTES) pieces.push(Buffer.from(part));
+ else pieces = [];
+ };
+ while (lines < MAX_CWD_LINES && position < MAX_CWD_SCAN_BYTES) {
+ const n = readSync(fd, chunk, 0, chunk.length, position);
+ if (n === 0) return lineBytes > 0 ? endLine() : null;
+ position += n;
+ const data = chunk.subarray(0, n);
+ let start = 0;
+ for (let nl = data.indexOf(10, start); nl !== -1; nl = data.indexOf(10, start)) {
+ keep(data.subarray(start, nl));
+ start = nl + 1;
+ const cwd = endLine();
+ if (cwd) return cwd;
+ if (lines >= MAX_CWD_LINES) return null;
}
+ keep(data.subarray(start));
}
+ return null;
} catch {
- // File read error
+ return null;
+ } finally {
+ closeSync(fd);
}
- return null;
}
// Separates interactive Codex CLI and Desktop work from codex exec runs and
@@ -491,50 +509,28 @@ function scanGemini(since: Date): Session[] {
// ── Deduplication ──────────────────────────────────────────────────────────
async function resolveAndDeduplicate(sessions: Session[]): Promise<Repo[]> {
- // Group sessions by cwd
- const byCwd = new Map<string, Session[]>();
+ // Group sessions by repository: the origin remote when there is one, else
+ // the main worktree, so linked worktrees and subdirectories of one
+ // repository count together and a nested repository counts as its own.
+ const byRemote = new Map<string, { main: string; paths: string[]; sessions: Session[] }>();
for (const s of sessions) {
- const existing = byCwd.get(s.cwd) || [];
- existing.push(s);
- byCwd.set(s.cwd, existing);
- }
-
- // Resolve git remotes for each cwd
- const cwds = Array.from(byCwd.keys());
- const remoteMap = new Map<string, string>(); // cwd → normalized remote
-
- for (const cwd of cwds) {
- const raw = getGitRemote(cwd);
- if (raw) {
- remoteMap.set(cwd, normalizeRemoteUrl(raw));
- } else if (existsSync(cwd) && isGitRepo(cwd)) {
- remoteMap.set(cwd, `local:${cwd}`);
- }
- }
-
- // Group by normalized remote
- const byRemote = new Map<string, { paths: string[]; sessions: Session[] }>();
- for (const [cwd, cwdSessions] of byCwd) {
- const remote = remoteMap.get(cwd);
- if (!remote) continue;
-
- const existing = byRemote.get(remote) || { paths: [], sessions: [] };
- if (!existing.paths.includes(cwd)) existing.paths.push(cwd);
- existing.sessions.push(...cwdSessions);
+ const project = gitProject(s.cwd);
+ if (!project) continue;
+ const raw = getGitRemote(project.root);
+ const remote = raw ? normalizeRemoteUrl(raw) : `local:${project.main}`;
+ const existing = byRemote.get(remote) || { main: project.main, paths: [], sessions: [] };
+ if (!existing.paths.includes(project.root)) existing.paths.push(project.root);
+ existing.sessions.push(s);
byRemote.set(remote, existing);
}
// Build Repo objects
const repos: Repo[] = [];
for (const [remote, data] of byRemote) {
- // Find first valid path
- const validPath = data.paths.find((p) => existsSync(p) && isGitRepo(p));
- if (!validPath) continue;
-
// Derive name from remote URL
let name: string;
if (remote.startsWith("local:")) {
- name = basename(remote.replace("local:", ""));
+ name = basename(data.main);
} else {
try {
const url = new URL(remote);
@@ -576,7 +572,8 @@ async function main() {
const startDate = sinceDate.toISOString().split("T")[0];
// Run all scanners
- const ccSessions = scanClaudeCode(sinceDate);
+ const cwdStats: CwdScanStats = { oversizedLines: 0 };
+ const ccSessions = scanClaudeCode(sinceDate, cwdStats);
const codexSessions = scanCodex(sinceDate);
const geminiSessions = scanGemini(sinceDate);
@@ -587,6 +584,13 @@ async function main() {
`Discovered: ${ccSessions.length} CC sessions, ${codexSessions.length} Codex sessions, ${geminiSessions.length} Gemini sessions`
);
+ if (cwdStats.oversizedLines > 0) {
+ console.error(
+ `Skipped ${cwdStats.oversizedLines} Claude Code JSONL line(s) over 1 MiB while reading session cwds; ` +
+ `a session whose cwd appears only after such lines counts with its project directory's other sessions.`,
+ );
+ }
+
// Deduplicate
const repos = await resolveAndDeduplicate(allSessions);
diff --git a/bin/gstack-memory-ingest.ts b/bin/gstack-memory-ingest.ts
index c5c5bef0b..fc5ca3fe7 100644
--- a/bin/gstack-memory-ingest.ts
+++ b/bin/gstack-memory-ingest.ts
@@ -2290,18 +2290,26 @@ async function ingestPassScoped(args: CliArgs, state: IngestState, scope: Transc
// structured counts and per-file failures.
// A4: one partition per gbrain source; a transcript source is registered
// (non-federated) before its first import, or its pages stay local.
- const listed: { ids: Set<string> | null } = { ids: null };
+ const catalog: { value: SourceCatalog | null } = { value: null };
for (const batch of resumed ? [{ sourceId: resumed.sourceId, pages: [...resumed.staged.values()] }] : planBatches(toImport, state)) {
- if (!resumed && batch.sourceId?.startsWith("gstack-transcripts")) {
+ let checkout: string | null = null;
+ // A resumed partition (a timeout checkpoint, possibly staged before the
+ // source had a checkout) is admitted the same way before it imports.
+ if (batch.sourceId?.startsWith("gstack-transcripts") && batch.pages.length > 0) {
const repo = isUnattributed(batch.pages[0]) ? "(no repository)" : batch.pages[0].git_remote!;
- const why = ensureTranscriptSource(state, batch.sourceId, repo, listed);
- if (why) {
+ const admitted = admitTranscriptSource(state, batch.sourceId, repo, catalog);
+ if ("why" in admitted) {
base.kept_local += batch.pages.length;
- reportPage(`kept ${batch.pages.length} transcript page(s) for ${repo} on this machine: ${why}. They import once the source can be registered (upgrade gbrain with gstack-gbrain-install).`);
+ reportPage(`kept ${batch.pages.length} transcript page(s) for ${repo} on this machine: ${admitted.why}`);
+ // The pages were never stamped, so they are prepared again next run;
+ // a resumed stage is dropped rather than resumed into a refusal forever.
+ if (resumed) cleanupStagingDir(resumed.stagingDir);
continue;
}
+ checkout = admitted.checkout;
}
await importPartition(run, batch.pages, batch.sourceId, resumed);
+ if (checkout) snapshotTranscriptCheckout(batch.sourceId!, checkout);
// Other sources still import after one source's import fails; only a
// timeout (whose checkpoint a later import would overwrite) stops the run.
if (run.stopImports) break;
@@ -2403,34 +2411,246 @@ function planBatches(pages: PreparedPage[], state: IngestState): Array<{ sourceI
}
/**
- * Register a transcript source before its first import: machine-local and
- * never federated. Registration is cached in state so it runs once per
- * repository. Returns null when the source is usable, else why it is not.
+ * Transcript source binding (#3097), against gbrain 0.60's managed persistence
+ * (src/core/persistence: import-mutations, source-lifecycle, ownership):
+ *
+ * - A managed import lands only when the source has an active worktree
+ * binding owned by this host; a path-less source (`sources add <id>` with no
+ * --path) never gets one, so every import into it is refused with
+ * owner_unavailable.
+ * - A binding is a checkout: `sources add <id> --path <dir>` binds the git
+ * root enclosing <dir> (any enclosing checkout, such as a brain-synced state
+ * root, would be claimed whole), and requires committed content unless
+ * --force. Re-running it on a path-less source of the same id attaches the
+ * binding (the supported migration); a source that already has a path or a
+ * binding is refused (source_id_taken). Claiming someone else's checkout
+ * (`sources writer claim`, transfers, `sources set-path`) is the host
+ * administrator's decision, so gstack never does it.
+ * - Every managed write is written through to <checkout>/<slug>.md, and a
+ * `gbrain sync` of the source imports the files at the checkout's HEAD and
+ * soft-deletes pages whose file HEAD does not track; on an unborn HEAD it
+ * refuses and changes nothing.
+ *
+ * So each transcript source gets its own checkout under the state root,
+ * created by gstack and never shared. The checkout stays unborn until every
+ * page gbrain holds for the source has its file there, then holds exactly one
+ * commit: the current page files, amended after each import, with no reflog,
+ * so `git gc --auto` prunes superseded snapshots (retention: one file per live
+ * page plus one packed snapshot, never one copy per run).
*/
-function ensureTranscriptSource(
+const TRANSCRIPT_CHECKOUTS_DIR = join(GSTACK_HOME, "gbrain-transcript-sources");
+const TRANSCRIPT_TROUBLESHOOTING = "docs/troubleshooting.md#memory-ingest-transcript-checkout";
+
+export function transcriptCheckoutPath(id: string, root = TRANSCRIPT_CHECKOUTS_DIR): string {
+ return join(root, id);
+}
+
+/** What gstack knows about gbrain's sources, read once per run. */
+interface SourceCatalog {
+ rows: Map<string, { local_path?: string | null; page_count?: number }>;
+ managed: boolean;
+ hostId: string | null;
+ bindings: Map<string, { owner_host_id?: string | null; local_path?: string | null; relative_path?: string; state?: string }>;
+}
+
+function readSourceCatalog(): SourceCatalog {
+ const json = (args: string[]): any => {
+ const r = spawnGbrain(args, { timeout: 30_000 });
+ try {
+ return r.status === 0 ? JSON.parse(r.stdout || "null") : null;
+ } catch {
+ return null;
+ }
+ };
+ const rows = new Map(parseSourcesList(json(["sources", "list", "--json"])).filter((row) => typeof row.id === "string").map((row) => [row.id!, row as any]));
+ // gbrain before 0.60 has no writer status: it is never managed.
+ const status = json(["sources", "writer", "status", "--json"]);
+ const managed = status?.mode === "managed" || (status?.mode === undefined && status?.enabled === true);
+ const bindings = new Map<string, any>((Array.isArray(status?.bindings) ? status.bindings : []).map((b: any) => [b.source_id, b]));
+ return { rows, managed, hostId: status?.local_host_id ?? status?.host_id ?? null, bindings };
+}
+
+function samePath(a: string, b: string): boolean {
+ try {
+ return realpathSync(a) === realpathSync(b);
+ } catch {
+ return false;
+ }
+}
+
+function checkoutGit(dir: string, args: string[]) {
+ return spawnSync("git", ["-C", dir, "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", ...args], {
+ encoding: "utf-8",
+ timeout: 60_000,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+}
+
+/** Create (or reuse) the checkout gstack owns for one transcript source. Returns an error, or null. */
+function prepareTranscriptCheckout(dir: string): string | null {
+ try {
+ mkdirSync(dir, { recursive: true });
+ if (!existsSync(join(dir, ".git"))) {
+ const steps = [
+ ["init", "-q"],
+ ["config", "core.logAllRefUpdates", "false"],
+ ["config", "gc.auto", "256"],
+ ["config", "gc.pruneExpire", "now"],
+ ["config", "user.name", "gstack transcript ingest"],
+ ["config", "user.email", "gstack-transcripts@localhost"],
+ ];
+ for (const step of steps) {
+ const r = checkoutGit(dir, step);
+ if (r.status !== 0) return `git ${step[0]} failed in ${dir}: ${(r.stderr || "").trim().split("\n")[0]}`;
+ }
+ }
+ // gbrain's ownership markers are not pages; they stay out of the snapshot.
+ if (!existsSync(join(dir, ".gitignore"))) writeFileSync(join(dir, ".gitignore"), ".gbrain-*\n", "utf-8");
+ return null;
+ } catch (err) {
+ return `could not create ${dir}: ${(err as Error).message}`;
+ }
+}
+
+/**
+ * Make a transcript source usable before an import into it: register it, and
+ * on a managed brain bind it to its own checkout (migrating a path-less source
+ * gstack registered earlier). Returns the bound checkout (null when the brain
+ * needs none), or why the partition must stay on this machine.
+ */
+function admitTranscriptSource(
state: IngestState,
id: string,
repo: string,
- listed: { ids: Set<string> | null },
-): string | null {
- if (state.sources?.[id]) return null;
- if (!listed.ids) {
- const r = spawnGbrain(["sources", "list", "--json"], { timeout: 30_000 });
- let raw: unknown = null;
- try {
- raw = r.status === 0 ? JSON.parse(r.stdout || "null") : null;
- } catch {}
- listed.ids = new Set(parseSourcesList(raw).map((row) => row.id).filter((x): x is string => typeof x === "string"));
- }
- if (!listed.ids.has(id)) {
- const add = spawnGbrain(["sources", "add", id, "--no-federated", "--name", `gstack transcripts: ${repo}`], { timeout: 30_000 });
- if (add.status !== 0) {
- return `could not register gbrain source ${id} (${(add.stderr || add.stdout || `exit ${add.status}`).trim().split("\n")[0].slice(0, 200)})`;
+ catalog: { value: SourceCatalog | null },
+): { checkout: string | null } | { why: string } {
+ const c = (catalog.value ??= readSourceCatalog());
+ const row = c.rows.get(id);
+ const name = `gstack transcripts: ${repo}`;
+ const registered = () => {
+ (state.sources ??= {})[id] = { repo, registered_at: state.sources?.[id]?.registered_at ?? new Date().toISOString() };
+ };
+ const gbrainError = (r: { status: number | null; stdout?: string; stderr?: string }) =>
+ (r.stderr || r.stdout || `exit ${r.status}`).trim().split("\n").find((l) => /error|refus|fail/i.test(l))?.slice(0, 240) ??
+ (r.stderr || r.stdout || `exit ${r.status}`).trim().split("\n")[0].slice(0, 240);
+
+ if (!c.managed) {
+ if (!row) {
+ const add = spawnGbrain(["sources", "add", id, "--no-federated", "--name", name], { timeout: 30_000 });
+ if (add.status !== 0) {
+ return { why: `could not register gbrain source ${id} (${gbrainError(add)}). They import once the source can be registered (upgrade gbrain with gstack-gbrain-install)` };
+ }
+ c.rows.set(id, { local_path: null, page_count: 0 });
+ }
+ registered();
+ return { checkout: null };
+ }
+
+ const checkout = transcriptCheckoutPath(id);
+ const binding = c.bindings.get(id);
+ if (binding || row?.local_path) {
+ const bound = binding?.local_path ? join(binding.local_path, binding.relative_path ?? "") : null;
+ const boundHere = bound !== null && (bound === checkout || samePath(bound, checkout));
+ const present = existsSync(join(checkout, ".git"));
+ if (boundHere && binding!.owner_host_id === c.hostId && binding!.state === "active" && present) {
+ registered();
+ return { checkout };
+ }
+ const inspect = `Inspect it with: gbrain sources writer status --source ${id} --json.`;
+ if (boundHere && binding!.owner_host_id === c.hostId) {
+ return {
+ why:
+ `gbrain source ${id} is bound to gstack's checkout ${checkout}, but ${present ? `the binding is ${binding!.state}` : "the checkout is missing"}, so gbrain would refuse the import. ` +
+ `${inspect} Restore the checkout from a backup of the state root, or ask gbrain how to recover it (gbrain doctor --json). See ${TRANSCRIPT_TROUBLESHOOTING}`,
+ };
+ }
+ const owner = !binding?.owner_host_id ? "no owning host" : binding.owner_host_id === c.hostId ? "this host" : `host ${binding.owner_host_id}`;
+ return {
+ why:
+ `gbrain source ${id} is held by another owner (${owner}, checkout ${bound ?? row?.local_path ?? "(none on this host)"}), not by gstack's checkout ${checkout}, so gstack leaves it alone. ` +
+ `${inspect} To hand it to gstack, its owner releases it (gbrain sources writer transfer prepare ${id}, on the owning host) or you re-bind it on this host with: ` +
+ `gbrain sources set-path ${id} ${checkout}. See ${TRANSCRIPT_TROUBLESHOOTING}`,
+ };
+ }
+
+ if (process.env.GSTACK_EPHEMERAL === "1") {
+ return {
+ why:
+ `gbrain source ${id} needs a checkout to accept imports, and this state root (${GSTACK_HOME}) is ephemeral (GSTACK_EPHEMERAL=1), ` +
+ `so gstack does not bind one: the brain would keep pointing at a directory that vanishes with this machine. ` +
+ `Fix: GSTACK_STATE_ROOT=<durable directory> gstack-memory-ingest --bulk (without GSTACK_EPHEMERAL=1). See ${TRANSCRIPT_TROUBLESHOOTING}`,
+ };
+ }
+ const prepared = prepareTranscriptCheckout(checkout);
+ if (prepared) return { why: `could not prepare the checkout for gbrain source ${id}: ${prepared}. See ${TRANSCRIPT_TROUBLESHOOTING}` };
+ // --force: the checkout is an ordinary directory until its first snapshot.
+ const add = spawnGbrain(["sources", "add", id, "--path", checkout, "--no-federated", "--force", "--name", name, "--json"], { timeout: 60_000 });
+ if (add.status !== 0) {
+ return {
+ why:
+ `could not bind gbrain source ${id} to ${checkout} (${gbrainError(add)}). ` +
+ `Inspect it with: gbrain sources writer status --source ${id} --json. See ${TRANSCRIPT_TROUBLESHOOTING}`,
+ };
+ }
+ c.bindings.set(id, { owner_host_id: c.hostId, local_path: checkout, relative_path: "", state: "active" });
+ if (row) {
+ // Pages that predate managed persistence have no file in the checkout yet;
+ // re-import them so each gets one and the checkout can be snapshotted.
+ let requeued = 0;
+ for (const [path, entry] of Object.entries(state.sessions)) {
+ if (entry.source_id !== id || !["ingested", "imported_unverified"].includes(entry.status)) continue;
+ setEntry(state, path, { ...entry, status: "refused", reason: `re-import into the checkout of ${id} (#3097)` });
+ requeued++;
+ }
+ reportPage(
+ `bound gbrain source ${id} to ${checkout}: it had no checkout, so gbrain refused every import into it (#3097)` +
+ (requeued ? `; ${requeued} page(s) imported before the binding are re-imported on the next run` : ""),
+ );
+ } else {
+ c.rows.set(id, { local_path: checkout, page_count: 0 });
+ }
+ registered();
+ return { checkout };
+}
+
+/**
+ * After an import into a bound transcript source: commit its page files as
+ * the checkout's single snapshot, once every page gbrain holds for the source
+ * has its file, so `gbrain sync` of the source never mistakes a page for a
+ * deleted file.
+ */
+function snapshotTranscriptCheckout(id: string, checkout: string): void {
+ let files = 0;
+ (function walk(dir: string) {
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
+ if (e.name === ".git") continue;
+ if (e.isDirectory()) walk(join(dir, e.name));
+ else if (e.name.endsWith(".md")) files++;
+ }
+ })(checkout);
+ const r = spawnGbrain(["sources", "list", "--json"], { timeout: 30_000 });
+ let pages: number | undefined;
+ try {
+ pages = parseSourcesList(JSON.parse(r.stdout || "null")).find((row) => row.id === id)?.page_count as number | undefined;
+ } catch {}
+ const hasHead = checkoutGit(checkout, ["rev-parse", "--verify", "-q", "HEAD"]).status === 0;
+ if (typeof pages !== "number" || files < pages) {
+ if (!hasHead) {
+ reportPage(
+ `left the checkout of ${id} uncommitted: gbrain holds ${pages ?? "an unknown number of"} page(s) for it and ${files} have a file in ${checkout}, ` +
+ `so a commit now would let gbrain sync soft-delete the rest. The missing files are written as their pages re-import.`,
+ );
}
- listed.ids.add(id);
+ return;
+ }
+ if (checkoutGit(checkout, ["add", "-A"]).status !== 0) return;
+ if (hasHead && checkoutGit(checkout, ["diff", "--cached", "--quiet"]).status === 0) return;
+ const commit = checkoutGit(checkout, ["commit", "-q", "--no-verify", ...(hasHead ? ["--amend"] : []), "-m", `gstack transcript pages (${files})`]);
+ if (commit.status !== 0) {
+ reportPage(`could not snapshot the checkout of ${id} (${(commit.stderr || "").trim().split("\n")[0]}); its pages are in the brain, and the snapshot is retried after the next import.`);
+ return;
}
- (state.sources ??= {})[id] = { repo, registered_at: new Date().toISOString() };
- return null;
+ checkoutGit(checkout, ["gc", "--auto", "--quiet"]);
}
/** Print even under --quiet: a page that did not land must never be silent (A1). */
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index f2806f9a1..b863c3523 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -1189,6 +1189,27 @@ and re-imports the ones missing from your brain. That check needs a local gbrain
**Fix.** Fix permissions or free disk space under your gstack state root, then `/sync-gbrain`.
+<a id="memory-ingest-transcript-checkout"></a>
+### `[memory-ingest] kept N transcript page(s) for <repo> on this machine: gbrain source <id> ...`
+
+On a managed gbrain brain (0.60+), an import lands only in a source bound to a
+checkout this host owns, so gstack binds each transcript source to its own
+checkout, `<state root>/gbrain-transcript-sources/<id>/`, before importing.
+The partition stays on this machine, unstamped, and imports on a later run when:
+
+- **held by another owner**: the source is bound to another host or another
+ directory. gstack never takes it over. Inspect it with
+ `gbrain sources writer status --source <id> --json`; the owner releases it
+ (`gbrain sources writer transfer prepare <id>` on the owning host) or you
+ re-bind it here with `gbrain sources set-path <id> <checkout>`.
+- **the state root is ephemeral** (`GSTACK_EPHEMERAL=1`): a binding would point
+ at a directory that vanishes with the machine. Run with a durable root:
+ `GSTACK_STATE_ROOT=<durable directory> gstack-memory-ingest --bulk`.
+- **bound to gstack's checkout, but it is missing or not active**: restore the
+ checkout from a backup of the state root, or follow `gbrain doctor --json`.
+- **could not bind**: the message carries gbrain's refusal; inspect the source
+ with the writer status command above.
+
<a id="gbrain-artifacts-not-indexed"></a>
### `curated artifacts pushed to git, but gbrain source <id> has 0 indexed pages. Fix: gbrain sync --source <id>, then re-run /sync-gbrain`
diff --git a/package.json b/package.json
index 9ff86cbbd..7a7e220ac 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "gstack",
- "version": "1.91.87",
+ "version": "1.91.88",
"description": "Garry's Stack — Claude Code skills + fast headless browser. One repo, one install, entire AI engineering workflow.",
"license": "MIT",
"type": "module",
diff --git a/test/global-discover.test.ts b/test/global-discover.test.ts
index f6af69801..fd0c80631 100644
--- a/test/global-discover.test.ts
+++ b/test/global-discover.test.ts
@@ -439,13 +439,13 @@ describe("gstack-global-discover", () => {
});
});
- describe("extractCwdFromJsonl 64KB cap (PR #1169 bug #8)", () => {
+ describe("extractCwdFromJsonl reads whole lines up to 1 MiB (PR #1169 bug #8, #1315)", () => {
// Regression: the old 8KB cap landed mid-line on Claude Code sessions with
// long headers, JSON.parse threw on the truncated tail, the catch
// `continue`d silently, and the project disappeared from discovery.
// The fix raised the cap to 64KB AND drops the trailing partial segment
// before parsing.
- let extractCwdFromJsonl: (filePath: string) => string | null;
+ let extractCwdFromJsonl: (filePath: string, stats?: { oversizedLines: number }) => string | null;
let tmpDir: string;
beforeEach(async () => {
@@ -483,19 +483,31 @@ describe("gstack-global-discover", () => {
expect(extractCwdFromJsonl(filePath)).toBe("/tmp/repo-12k");
});
- test("80KB single line (overflows 64KB cap): returns null without crashing", () => {
- // One line >64KB with no newline inside the read window. The 64KB read
- // captures a truncated prefix, parts.length === 1, no trailing drop
- // applies, JSON.parse throws, catch returns null. The fix's
- // trailing-partial-drop must not crash on this shape.
- const padding = "y".repeat(80 * 1024);
- const line = JSON.stringify({ cwd: "/tmp/repo-80k", type: "header", notes: padding });
- expect(line.length).toBeGreaterThan(64 * 1024);
+ test("86KB queue-operation first line, cwd on the third record: returns cwd (#1315)", () => {
+ // Recent Claude Code sessions open with one queue-operation record larger
+ // than the old 64KB prefix; cwd first appears on a later record.
+ const filePath = join(tmpDir, "queue-op-86k.jsonl");
+ const first = JSON.stringify({ type: "queue-operation", operation: "enqueue", content: "q".repeat(86 * 1024) });
+ const second = JSON.stringify({ type: "summary" });
+ const third = JSON.stringify({ type: "attachment", cwd: "/tmp/repo-86k" });
+ expect(first.length).toBeGreaterThan(64 * 1024);
+ writeFileSync(filePath, [first, second, third].join("\n") + "\n");
+ expect(extractCwdFromJsonl(filePath)).toBe("/tmp/repo-86k");
+ });
- const filePath = join(tmpDir, "header-80k.jsonl");
- writeFileSync(filePath, line + "\n");
- // Don't throw, just return null.
- expect(extractCwdFromJsonl(filePath)).toBeNull();
+ test("a line over 1 MiB is skipped and counted; the next line's cwd is returned", () => {
+ const filePath = join(tmpDir, "oversized.jsonl");
+ const huge = JSON.stringify({ cwd: "/tmp/repo-huge", notes: "y".repeat(1024 * 1024 + 10) });
+ writeFileSync(filePath, huge + "\n" + JSON.stringify({ cwd: "/tmp/repo-after-huge" }) + "\n");
+ const stats = { oversizedLines: 0 };
+ expect(extractCwdFromJsonl(filePath, stats)).toBe("/tmp/repo-after-huge");
+ expect(stats.oversizedLines).toBe(1);
+ });
+
+ test("a file with no trailing newline still yields its cwd", () => {
+ const filePath = join(tmpDir, "no-newline.jsonl");
+ writeFileSync(filePath, JSON.stringify({ cwd: "/tmp/repo-no-newline" }));
+ expect(extractCwdFromJsonl(filePath)).toBe("/tmp/repo-no-newline");
});
test("complete line followed by partial second line: returns first line's cwd", () => {
@@ -526,4 +538,111 @@ describe("gstack-global-discover", () => {
expect(extractCwdFromJsonl(filePath)).toBe("/tmp/repo-skip-bad");
});
});
+
+ describe("Claude Code project resolution from the recorded cwd (#1315)", () => {
+ let home: string;
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), "gstack-cc-projects-"));
+ });
+ afterEach(() => rmSync(home, { recursive: true, force: true }));
+
+ const git = (cwd: string, ...args: string[]) => {
+ const r = spawnSync("git", ["-C", cwd, ...args], {
+ encoding: "utf-8",
+ timeout: 30_000,
+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: join(home, ".gitconfig"), GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "[email protected]", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "[email protected]" },
+ });
+ expect(r.status).toBe(0);
+ return r.stdout;
+ };
+ function repo(rel: string, remote?: string): string {
+ const dir = join(home, rel);
+ mkdirSync(dir, { recursive: true });
+ git(dir, "init", "-q");
+ git(dir, "commit", "-q", "--allow-empty", "-m", "init");
+ if (remote) git(dir, "remote", "add", "origin", remote);
+ return dir;
+ }
+ /** One Claude Code session whose cwd appears on its third record, in a project dir named like Claude Code names it. */
+ function session(cwd: string, id: string): void {
+ const dir = join(home, ".claude", "projects", cwd.replace(/[\\/.:]/g, "-"));
+ mkdirSync(dir, { recursive: true });
+ const lines = [
+ { type: "queue-operation", operation: "enqueue", content: "q".repeat(70 * 1024) },
+ { type: "summary" },
+ { type: "user", cwd, message: { role: "user", content: "hi" } },
+ ];
+ writeFileSync(join(dir, `${id}.jsonl`), lines.map((l) => JSON.stringify(l)).join("\n") + "\n");
+ }
+ function discover(): { repos: Array<{ name: string; remote: string; paths: string[]; sessions: { claude_code: number } }>; tools: { claude_code: { total_sessions: number } } } {
+ const r = spawnSync("bun", ["run", scriptPath, "--since", "1h", "--format", "json"], {
+ encoding: "utf-8",
+ timeout: 60_000,
+ env: { ...process.env, HOME: home, USERPROFILE: home, CODEX_SESSIONS_DIR: join(home, "no-codex"), GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: join(home, ".gitconfig") },
+ });
+ expect(r.status).toBe(0);
+ return JSON.parse(r.stdout);
+ }
+
+ test("root and subdirectory sessions of a hyphenated repository count the same", () => {
+ const root = repo("work/ai-blogger-lab", "https://github.com/acme/ai-blogger-lab.git");
+ mkdirSync(join(root, "packages", "web-app"), { recursive: true });
+ session(root, "root-1");
+ session(root, "root-2");
+ session(join(root, "packages", "web-app"), "sub-1");
+ session(join(root, "packages", "web-app"), "sub-2");
+ const json = discover();
+ const r = json.repos.find((x) => x.remote === "https://github.com/acme/ai-blogger-lab")!;
+ expect(r.sessions.claude_code).toBe(4);
+ expect(r.paths).toEqual([root]);
+ expect(r.name).toBe("ai-blogger-lab");
+ });
+
+ test("a linked worktree counts with its repository, under its own path", () => {
+ const main = repo("work/app", "[email protected]:acme/app.git");
+ const wt = join(home, "work", "app-feature-x");
+ git(main, "worktree", "add", "-q", wt);
+ session(main, "main-1");
+ session(join(wt), "wt-1");
+ const r = discover().repos.find((x) => x.remote === "https://github.com/acme/app")!;
+ expect(r.sessions.claude_code).toBe(2);
+ expect(r.paths.sort()).toEqual([main, wt].sort());
+ });
+
+ test("a linked worktree of a repository with no remote still counts with its repository", () => {
+ const main = repo("work/local-only");
+ const wt = join(home, "work", "local-only-wt");
+ git(main, "worktree", "add", "-q", wt);
+ session(main, "l-1");
+ session(wt, "l-2");
+ const local = discover().repos.filter((x) => x.remote.startsWith("local:"));
+ expect(local).toHaveLength(1);
+ expect(local[0].sessions.claude_code).toBe(2);
+ expect(local[0].name).toBe("local-only");
+ });
+
+ test("a nested repository counts as its own repository, not its parent's", () => {
+ const outer = repo("work/outer", "https://github.com/acme/outer.git");
+ const inner = repo("work/outer/vendor/inner", "https://github.com/acme/inner.git");
+ session(outer, "o-1");
+ session(inner, "i-1");
+ session(join(inner), "i-2");
+ const json = discover();
+ expect(json.repos.find((x) => x.remote === "https://github.com/acme/outer")!.sessions.claude_code).toBe(1);
+ expect(json.repos.find((x) => x.remote === "https://github.com/acme/inner")!.sessions.claude_code).toBe(2);
+ });
+
+ test("sessions outside any repository, or inside .git, are not counted as a repository", () => {
+ const plain = join(home, "notes", "my-notes");
+ mkdirSync(plain, { recursive: true });
+ const r = repo("work/real", "https://github.com/acme/real.git");
+ session(plain, "p-1");
+ session(join(r, ".git"), "g-1");
+ session(r, "r-1");
+ const json = discover();
+ expect(json.tools.claude_code.total_sessions).toBe(3);
+ expect(json.repos).toHaveLength(1);
+ expect(json.repos[0].sessions.claude_code).toBe(1);
+ });
+ });
});
diff --git a/test/helpers/fake-gbrain-brain.ts b/test/helpers/fake-gbrain-brain.ts
index 8db931b95..297a5c89e 100644
--- a/test/helpers/fake-gbrain-brain.ts
+++ b/test/helpers/fake-gbrain-brain.ts
@@ -13,6 +13,13 @@
* FAKE_LIST_UNSCOPED=1 `list` ignores --source-id (pre-0.46.25)
* FAKE_BUSY=1 list/get answer {"error":"pglite_busy"} with exit 1
* FAKE_NO_SOURCES=1 `sources add` is unsupported
+ * FAKE_MANAGED=1 gbrain 0.60 managed persistence: `sources writer status`
+ * reports bindings; `sources add --path` binds (and binds a
+ * path-less source of the same id); an import into a source
+ * with no active binding owned by FAKE_HOST_ID (default
+ * host-local) is refused per file, and a bound import writes
+ * each page through to the checkout
+ * FAKE_COPY_STAGE=<dir> import copies the staged directory to <dir> first
* Every call is appended to $HOME/gbrain-calls.log.
*/
import { chmodSync, mkdirSync, writeFileSync } from "fs";
@@ -35,11 +42,17 @@ const save = () => fs.writeFileSync(brainFile, JSON.stringify(brain, null, 2));
const flag = (name) => { const i = args.indexOf(name); return i === -1 ? undefined : args[i + 1]; };
const busy = () => { if (env.FAKE_BUSY === "1") { console.log(JSON.stringify({ error: "pglite_busy" })); process.exit(1); } };
const cmd = args[0];
+const managed = env.FAKE_MANAGED === "1";
+const hostId = env.FAKE_HOST_ID || "host-local";
+const ownBinding = (id) => { const b = brain.sources[id]?.binding; return b && b.owner_host_id === hostId && b.state === "active" ? b : null; };
if (cmd === "--help") { console.log("Commands:\\n import <dir> Import"); process.exit(0); }
if (cmd === "import") {
const dir = args[1];
const source = flag("--source-id") ?? "default";
if (!brain.sources[source]) { console.error("Source not found: " + source); process.exit(1); }
+ if (env.FAKE_COPY_STAGE) fs.cpSync(dir, env.FAKE_COPY_STAGE, { recursive: true });
+ const binding = managed && source !== "default" ? ownBinding(source) : null;
+ const refused = managed && source !== "default" && !binding;
const files = [];
(function walk(d) {
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
@@ -63,6 +76,11 @@ if (cmd === "import") {
console.error(" Skipped " + rel + ": Invalid YAML frontmatter");
continue;
}
+ if (refused) {
+ skipped++; errors++;
+ failures.push({ path: rel, error: "Managed import must run on the active canonical owner for the selected source." });
+ continue;
+ }
if (env.FAKE_PENDING && rel.includes(env.FAKE_PENDING)) {
skipped++;
console.error(" Pending: " + rel + " was accepted and is still publishing; rerun to confirm it.");
@@ -74,6 +92,11 @@ if (cmd === "import") {
brain.pages[source] ??= {};
if (brain.pages[source][slug]?.sha === sha) skipped++; else imported++;
brain.pages[source][slug] = { sha };
+ if (binding) {
+ const target = path.join(binding.local_path, rel);
+ fs.mkdirSync(path.dirname(target), { recursive: true });
+ fs.writeFileSync(target, body);
+ }
}
save();
const report = env.FAKE_OLD_JSON === "1"
@@ -99,14 +122,33 @@ if (cmd === "get") {
process.exit(0);
}
if (cmd === "sources" && args[1] === "list") {
- console.log(JSON.stringify({ sources: Object.entries(brain.sources).map(([id, s]) => ({ id, federated: s.federated, page_count: Object.keys(brain.pages[id] ?? {}).length })) }));
+ console.log(JSON.stringify({ sources: Object.entries(brain.sources).map(([id, s]) => ({ id, federated: s.federated, local_path: s.local_path ?? null, page_count: Object.keys(brain.pages[id] ?? {}).length })) }));
+ process.exit(0);
+}
+if (cmd === "sources" && args[1] === "writer" && args[2] === "status" && managed) {
+ const bindings = Object.entries(brain.sources).filter(([, s]) => s.binding).map(([id, s]) => ({
+ source_id: id, relative_path: "", owner_host_id: s.binding.owner_host_id, state: s.binding.state,
+ local_path: s.binding.owner_host_id === hostId ? s.binding.local_path : null,
+ }));
+ console.log(JSON.stringify({ enabled: true, mode: "managed", local_host_id: hostId, bindings }));
process.exit(0);
}
if (cmd === "sources" && args[1] === "add") {
if (env.FAKE_NO_SOURCES === "1") { console.error("Unknown command: sources add"); process.exit(2); }
- brain.sources[args[2]] = { federated: args.includes("--federated") };
+ const id = args[2];
+ const localPath = flag("--path");
+ const existing = brain.sources[id];
+ if (existing && (!managed || !localPath || existing.local_path || existing.binding)) {
+ console.error("Error [source_id_taken]: Source ID is already registered."); process.exit(1);
+ }
+ if (managed && localPath && !args.includes("--force") && !fs.existsSync(path.join(localPath, ".git"))) {
+ console.error("Error [not_a_git_repo]: The source path must contain committed Git content."); process.exit(1);
+ }
+ brain.sources[id] = { ...existing, federated: existing ? existing.federated : args.includes("--federated"),
+ ...(localPath ? { local_path: localPath } : {}),
+ ...(managed && localPath ? { binding: { owner_host_id: hostId, local_path: localPath, state: "active" } } : {}) };
save();
- console.log("Source added: " + args[2]);
+ console.log("Source added: " + id);
process.exit(0);
}
console.error("Unknown command: " + cmd);
diff --git a/test/memory-ingest-sources.test.ts b/test/memory-ingest-sources.test.ts
index ce4385ff8..9c3dac3f4 100644
--- a/test/memory-ingest-sources.test.ts
+++ b/test/memory-ingest-sources.test.ts
@@ -5,12 +5,12 @@
* federated source, and stay on the machine when the brain is remote.
*/
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { spawnSync } from "child_process";
import { installFakeBrain } from "./helpers/fake-gbrain-brain";
-import { transcriptSourceId } from "../bin/gstack-memory-ingest";
+import { transcriptCheckoutPath, transcriptSourceId } from "../bin/gstack-memory-ingest";
const SCRIPT = join(import.meta.dir, "..", "bin", "gstack-memory-ingest.ts");
@@ -132,4 +132,139 @@ describe("memory ingest: per-repository transcript sources (A4)", () => {
expect(calls().some((c) => c[0] === "import")).toBe(false);
expect(sessions()[path]).toBeUndefined();
});
+
+ describe("managed gbrain 0.60: each transcript source is bound to its own checkout (#3097)", () => {
+ const managed = (extra: Record<string, string> = {}) => ({ FAKE_MANAGED: "1", ...extra });
+ function runWith(args: string[], extra: Record<string, string>) {
+ const r = spawnSync(process.execPath, [SCRIPT, "--sources", "transcript", ...args], { env: { ...env, ...extra }, cwd: home, encoding: "utf-8", timeout: 60_000 });
+ return { status: r.status, stdout: r.stdout || "", stderr: r.stderr || "" };
+ }
+ const git = (dir: string, ...args: string[]) => spawnSync("git", ["-C", dir, ...args], { env, encoding: "utf-8", timeout: 10_000 });
+ const pageFiles = (dir: string): string[] => readdirSync(dir, { recursive: true, withFileTypes: true })
+ .filter((e) => e.isFile() && e.name.endsWith(".md")).map((e) => e.name).sort();
+ const alpha = transcriptSourceId("github.com/acme/alpha");
+ const checkout = () => transcriptCheckoutPath(alpha, join(gstackHome, "gbrain-transcript-sources"));
+ const seedBrain = (sources: Record<string, unknown>, pages: Record<string, unknown> = {}) =>
+ writeFileSync(brain.brainFile, JSON.stringify({ sources: { default: { federated: true }, ...sources }, pages }));
+
+ it("a fresh source is bound to a checkout under the state root, imports, and keeps one snapshot commit across runs", () => {
+ const first = session("alpha00000000001", repo("alpha"));
+ const r = runWith(["--bulk", "--quiet"], managed());
+ expect(r.status).toBe(0);
+ const add = calls().find((c) => c[0] === "sources" && c[1] === "add" && c[2] === alpha)!;
+ expect(add).toEqual(expect.arrayContaining(["--path", checkout(), "--no-federated"]));
+ expect(fakeBrain().sources[alpha].binding).toMatchObject({ owner_host_id: "host-local", local_path: checkout(), state: "active" });
+ expect(sessions()[first]).toMatchObject({ status: "ingested", source_id: alpha });
+ expect(pageFiles(checkout())).toHaveLength(1);
+ expect(git(checkout(), "rev-list", "--count", "HEAD").stdout.trim()).toBe("1");
+ expect(git(checkout(), "status", "--porcelain").stdout.trim()).toBe("");
+
+ // Second run: a new session lands, the source is not added again, and
+ // the checkout still holds exactly one commit with both pages.
+ session("alpha00000000002", join(home, "repos", "alpha"));
+ rmSync(brain.callLog);
+ expect(runWith(["--incremental", "--quiet"], managed()).status).toBe(0);
+ expect(calls().some((c) => c[0] === "sources" && c[1] === "add")).toBe(false);
+ expect(pageFiles(checkout())).toHaveLength(2);
+ expect(git(checkout(), "rev-list", "--count", "HEAD").stdout.trim()).toBe("1");
+ expect(git(checkout(), "ls-files").stdout.trim().split("\n").filter((f) => f.endsWith(".md"))).toHaveLength(2);
+ expect(git(checkout(), "reflog").stdout.trim()).toBe("");
+ });
+
+ it("an existing path-less source registered by an earlier run is migrated on the next run and its imports land", () => {
+ const path = session("alpha00000000001", repo("alpha"));
+ seedBrain({ [alpha]: { federated: false } });
+ writeFileSync(join(gstackHome, ".transcript-ingest-state.json"), JSON.stringify({
+ schema_version: 2, last_writer: "gstack-memory-ingest", sessions: {},
+ sources: { [alpha]: { repo: "github.com/acme/alpha", registered_at: "2026-10-01T00:00:00Z" } },
+ }));
+ const r = runWith(["--bulk", "--quiet"], managed());
+ expect(r.status).toBe(0);
+ expect(r.stderr).toContain(`bound gbrain source ${alpha} to ${checkout()}: it had no checkout`);
+ expect(fakeBrain().sources[alpha]).toMatchObject({ local_path: checkout(), binding: { owner_host_id: "host-local" } });
+ expect(sessions()[path]).toMatchObject({ status: "ingested", source_id: alpha });
+ expect(git(checkout(), "rev-list", "--count", "HEAD").stdout.trim()).toBe("1");
+ });
+
+ it("a migrated source whose pages predate the binding stays uncommitted until they re-import, then snapshots", () => {
+ const path = session("alpha00000000001", repo("alpha"));
+ // Imported before managed persistence: the page is in the brain, with no file.
+ expect(runWith(["--bulk", "--quiet"], {}).status).toBe(0);
+ expect(sessions()[path]).toMatchObject({ status: "ingested", source_id: alpha });
+ session("alpha00000000002", join(home, "repos", "alpha"));
+ const r = runWith(["--incremental", "--quiet"], managed());
+ expect(r.status).toBe(0);
+ expect(r.stderr).toContain("1 page(s) imported before the binding are re-imported on the next run");
+ expect(r.stderr).toContain(`left the checkout of ${alpha} uncommitted: gbrain holds 2 page(s) for it and 1 have a file`);
+ expect(git(checkout(), "rev-parse", "--verify", "-q", "HEAD").status).not.toBe(0);
+ expect(sessions()[path].status).toBe("refused");
+ expect(runWith(["--incremental", "--quiet"], managed()).status).toBe(0);
+ expect(sessions()[path]).toMatchObject({ status: "ingested", source_id: alpha });
+ expect(pageFiles(checkout())).toHaveLength(2);
+ expect(git(checkout(), "rev-list", "--count", "HEAD").stdout.trim()).toBe("1");
+ });
+
+ it("a resumed timeout checkpoint staged before the upgrade is admitted and migrated before it imports", () => {
+ const path = session("alpha00000000001", repo("alpha"));
+ const stage = join(gstackHome, `.staging-ingest-1-2-src-${alpha}`);
+ // Before the upgrade: a path-less source, and a stage left behind by an import that never landed.
+ runWith(["--bulk", "--quiet"], { FAKE_FAIL: "transcripts", FAKE_COPY_STAGE: stage });
+ expect(fakeBrain().sources[alpha].local_path).toBeUndefined();
+ expect(sessions()[path]).toBeUndefined();
+ expect(existsSync(stage)).toBe(true);
+ rmSync(brain.callLog);
+ const r = runWith(["--bulk", "--quiet"], managed({ GSTACK_INGEST_RESUME_DIR: stage }));
+ expect(r.status).toBe(0);
+ const log = calls();
+ const add = log.findIndex((c) => c[0] === "sources" && c[1] === "add" && c.includes("--path"));
+ const imp = log.findIndex((c) => c[0] === "import" && c[1] === stage);
+ expect(add).toBeGreaterThan(-1);
+ expect(imp).toBeGreaterThan(add);
+ expect(sessions()[path]).toMatchObject({ status: "ingested", source_id: alpha });
+ expect(existsSync(stage)).toBe(false);
+ });
+
+ it("a source held by another owner is left alone, with a message naming the owner and the commands", () => {
+ const path = session("alpha00000000001", repo("alpha"));
+ seedBrain({ [alpha]: { federated: false, binding: { owner_host_id: "host-other", local_path: "/srv/other/alpha", state: "active" } } });
+ const r = runWith(["--bulk", "--quiet"], managed());
+ expect(r.status).toBe(0);
+ expect(r.stderr).toContain(`gbrain source ${alpha} is held by another owner (host host-other, checkout (none on this host))`);
+ expect(r.stderr).toContain(`gbrain sources writer status --source ${alpha} --json`);
+ expect(r.stderr).toContain(`gbrain sources set-path ${alpha} ${checkout()}`);
+ expect(r.stderr).toContain("docs/troubleshooting.md#memory-ingest-transcript-checkout");
+ expect(calls().some((c) => c[0] === "sources" && c[1] === "add")).toBe(false);
+ expect(calls().some((c) => c[0] === "import")).toBe(false);
+ expect(fakeBrain().sources[alpha].binding.owner_host_id).toBe("host-other");
+ expect(sessions()[path]).toBeUndefined();
+ expect(existsSync(checkout())).toBe(false);
+ });
+
+ it("a source this host bound to a different directory is not taken over either", () => {
+ session("alpha00000000001", repo("alpha"));
+ const elsewhere = join(home, "elsewhere");
+ mkdirSync(elsewhere);
+ seedBrain({ [alpha]: { federated: false, local_path: elsewhere, binding: { owner_host_id: "host-local", local_path: elsewhere, state: "active" } } });
+ const r = runWith(["--bulk", "--quiet"], managed());
+ expect(r.stderr).toContain(`is held by another owner (this host, checkout ${elsewhere})`);
+ expect(calls().some((c) => c[0] === "import")).toBe(false);
+ expect(fakeBrain().sources[alpha].binding.local_path).toBe(elsewhere);
+ });
+
+ it("binding is refused under an ephemeral state root; an already-bound source still imports there", () => {
+ const path = session("alpha00000000001", repo("alpha"));
+ const r = runWith(["--bulk", "--quiet"], managed({ GSTACK_EPHEMERAL: "1" }));
+ expect(r.status).toBe(0);
+ expect(r.stderr).toContain("this state root");
+ expect(r.stderr).toContain("is ephemeral (GSTACK_EPHEMERAL=1), so gstack does not bind one");
+ expect(r.stderr).toContain("GSTACK_STATE_ROOT=<durable directory> gstack-memory-ingest --bulk");
+ expect(calls().some((c) => c[0] === "sources" && c[1] === "add")).toBe(false);
+ expect(sessions()[path]).toBeUndefined();
+ // Bound on a durable run, then ingesting again on an ephemeral one.
+ expect(runWith(["--bulk", "--quiet"], managed()).status).toBe(0);
+ session("alpha00000000002", join(home, "repos", "alpha"));
+ expect(runWith(["--incremental", "--quiet"], managed({ GSTACK_EPHEMERAL: "1" })).status).toBe(0);
+ expect(pageFiles(checkout())).toHaveLength(2);
+ });
+ });
});