Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(memory): gbrain's own claude-cli calls are never banked or extracted (#5820)

garrytanba53f345c376
diff --git a/src/commands/doctor/checks/self-capture.ts b/src/commands/doctor/checks/self-capture.ts
index d6d7865bd8..0d95972f37 100644
--- a/src/commands/doctor/checks/self-capture.ts
+++ b/src/commands/doctor/checks/self-capture.ts
@@ -11,11 +11,11 @@
* a self-capture cannot be decided from this host. Best-effort: both counts
* read the local filesystem of the brain host.
*/
-import { readdirSync } from 'node:fs';
+import { readdirSync, statSync } from 'node:fs';
import { basename, dirname, join, relative } from 'node:path';
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
-import { claudeCliSelfSessionIds } from '../../../core/ai/providers/claude-cli-scratch.ts';
+import { claudeCliSelfProjectDirs, isClaudeCliSelfSessionId } from '../../../core/ai/providers/claude-cli-scratch.ts';
import { claudeProjectsDir } from '../../../core/bootstrap/host-specs.ts';
import { corpusFileSessionId } from '../../../core/context/corpus-segments.ts';
import { pruneDir } from '../../../core/sync.ts';
@@ -63,27 +63,32 @@ export async function selfCaptureCheck(engine: BrainEngine, opts: { projectsRoot
// An unreadable corpus root throws (unknown health); unreadable subdirectories make the counts a lower bound.
const { files, unreadable } = corpusTextFiles(corpusDir);
const projectsRoot = opts.projectsRoot ?? claudeProjectsDir();
- const selfIds = claudeCliSelfSessionIds(projectsRoot);
+ const selfDirs = claudeCliSelfProjectDirs(projectsRoot);
const known = harnessSessionIds(projectsRoot);
const classified: string[] = [], unclassifiable: string[] = [];
+ let newestMs = 0;
for (const file of files) {
const session = corpusFileSessionId(basename(file));
- if (selfIds.has(session)) classified.push(file);
- else if (!known.has(session)) unclassifiable.push(file);
+ if (isClaudeCliSelfSessionId(session, selfDirs)) {
+ classified.push(file);
+ try { newestMs = Math.max(newestMs, statSync(file).mtimeMs); } catch { /* raced away */ }
+ } else if (!known.has(session)) unclassifiable.push(file);
}
+ const newest = newestMs ? new Date(newestMs).toISOString() : null;
const quarantineDir = join(dirname(corpusDir), `${basename(corpusDir)}.quarantine`);
const destinations = classified.slice(0, SAMPLE).map(file => ({ file, dir: join(quarantineDir, dirname(relative(corpusDir, file))) }));
const commands = [`mkdir -p ${[...new Set([quarantineDir, ...destinations.map(d => d.dir)])].map(quote).join(' ')}`,
...destinations.map(({ file, dir }) => `for f in ${quote(file)}*; do mv -n -- "$f" ${quote(dir)}/; done`)];
const details = { classified: classified.length, unclassifiable: unclassifiable.length, corpus_files: files.length, unreadable_dirs: unreadable,
count: unreadable ? 'lower_bound' : 'exact', truncated: classified.length > SAMPLE, ...(unreadable ? { health: 'unknown' } : {}),
- corpus_dir: corpusDir, quarantine_dir: quarantineDir, classified_sample: classified.slice(0, SAMPLE).map(file => relative(corpusDir, file)),
+ newest_capture_at: newest, corpus_dir: corpusDir, quarantine_dir: quarantineDir, classified_sample: classified.slice(0, SAMPLE).map(file => relative(corpusDir, file)),
quarantine_commands: commands, docs: 'docs/guides/repair.md#quarantine-self-captured-corpus-files' };
const unknownNote = unclassifiable.length ? ` ${unclassifiable.length} corpus file(s) have no harness transcript left, so whether they are self-captures cannot be decided here; review them by hand.` : '';
if (unreadable) return { name, status: 'warn', details, message: `${unreadable} session corpus director${unreadable === 1 ? 'y' : 'ies'} could not be read, so self-capture health is unknown `
+ `(at least ${classified.length} identified self-capture(s)). Fix the directory permissions on the brain host and rerun gbrain doctor.${unknownNote}` };
if (!classified.length) return { name, status: 'ok', details, message: `No identified gbrain self-capture remains in the session corpus.${unknownNote}` };
- return { name, status: 'warn', details, message: `${classified.length} session corpus file(s) were captured from gbrain's own claude-cli sessions (#5413). `
+ return { name, status: 'warn', details, message: `${classified.length} session corpus file(s) were captured from gbrain's own claude-cli sessions (#5413); the newest is from ${newest}. `
+ + `This gbrain no longer creates them (#5820), so the count stops growing once every hook and serve process runs it; the existing files need one quarantine. `
+ `Dream and the sweep skip them, but they stay in the corpus until you move them. Nothing was moved or deleted. Quarantine them on the brain host: `
+ `${commands.slice(0, 3).join(' && ')}${classified.length > 2 ? ' … (full list: gbrain doctor --json, check self_capture; recipe: docs/guides/repair.md#quarantine-self-captured-corpus-files)' : ''}.${unknownNote}` };
} catch (error) {
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index c16ac329f8..8902fa7620 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -1448,6 +1448,11 @@ async function hookStop(io: HookIo): Promise<number> {
allowOversize: true,
});
if (!conf.ok) return `transcript_${conf.reason}`;
+ // #5820: the SessionEnd guard's fingerprint (#5413) — a turn from
+ // gbrain's own claude-cli subprocess is never banked, or extracting it
+ // spawns another claude-cli call that banks again.
+ const ws = io.cwd ?? (typeof j?.cwd === 'string' ? j.cwd : process.cwd());
+ if (isClaudeCliSelfTranscriptPath(conf.path) || isClaudeCliSelfTranscriptPath(ws)) return 'self_capture';
const findLastUser = (parsed: ReturnType<typeof parseTranscript>): WindowTurn | undefined => {
const index = parsed.genuineUserTurnIndexes.at(-1);
return index === undefined ? undefined : parsed.turns[index];
@@ -1524,7 +1529,7 @@ async function hookStop(io: HookIo): Promise<number> {
// skipped-vs-failed counters and any alerting stay honest.
const wbByDesign =
wbReason === 'wb_scheduled' || wbReason === 'wb_banked' || wbReason === 'wb_dup' ||
- wbReason === 'no_user_turn' || wbReason.startsWith('flush_skip_') ||
+ wbReason === 'no_user_turn' || wbReason === 'self_capture' || wbReason.startsWith('flush_skip_') ||
(WRITEBACK_SKIP_REASONS as readonly string[]).includes(wbReason);
await writeHeartbeat(io, {
ts: new Date().toISOString(),
diff --git a/src/core/ai/providers/claude-cli-scratch.ts b/src/core/ai/providers/claude-cli-scratch.ts
index ef4e7e2c75..ba86aae32f 100644
--- a/src/core/ai/providers/claude-cli-scratch.ts
+++ b/src/core/ai/providers/claude-cli-scratch.ts
@@ -15,7 +15,7 @@
* discovered path is a reliable fingerprint.
*/
-import { readdirSync, rmSync } from 'node:fs';
+import { existsSync, readdirSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { claudeProjectsDir } from '../../bootstrap/host-specs.ts';
@@ -55,17 +55,10 @@ export function isClaudeCliSelfTranscriptPath(path: string): boolean {
*/
export function claudeCliSelfSessionIds(projectsRoot: string = claudeProjectsDir()): Set<string> {
const ids = new Set<string>();
- let projects: string[];
- try {
- projects = readdirSync(projectsRoot);
- } catch {
- return ids;
- }
- for (const project of projects) {
- if (!isClaudeCliSelfTranscriptPath(project)) continue;
+ for (const project of claudeCliSelfProjectDirs(projectsRoot)) {
let files: string[];
try {
- files = readdirSync(join(projectsRoot, project));
+ files = readdirSync(project);
} catch {
continue;
}
@@ -76,6 +69,32 @@ export function claudeCliSelfSessionIds(projectsRoot: string = claudeProjectsDir
return ids;
}
+/** The harness project dirs of gbrain claude-cli scratch cwds (one listing of
+ * the projects root; no project's files are read). */
+export function claudeCliSelfProjectDirs(projectsRoot: string = claudeProjectsDir()): string[] {
+ try {
+ return readdirSync(projectsRoot)
+ .filter(isClaudeCliSelfTranscriptPath)
+ .map((project) => join(projectsRoot, project));
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * #5820 — the ONE single-session self-capture classifier (serve-side
+ * writeback harvest, the sweep's corpus pass, doctor `self_capture`): true
+ * when a scratch project holds `<id>.jsonl`. Pass `projectDirs` to classify
+ * many ids against one listing.
+ */
+export function isClaudeCliSelfSessionId(
+ id: string,
+ projectDirs: readonly string[] = claudeCliSelfProjectDirs(),
+): boolean {
+ if (!/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/.test(id)) return false;
+ return projectDirs.some((dir) => existsSync(join(dir, `${id}.jsonl`)));
+}
+
function isPidAlive(pid: number): boolean {
try {
process.kill(pid, 0);
diff --git a/src/core/context/checkpoint-harvest.ts b/src/core/context/checkpoint-harvest.ts
index 38681dd312..b45834371d 100644
--- a/src/core/context/checkpoint-harvest.ts
+++ b/src/core/context/checkpoint-harvest.ts
@@ -34,7 +34,8 @@ import type { BrainEngine } from '../engine.ts';
import type { CapabilityReport } from '../capability.ts';
import { acquireCorpusClaim, CORPUS_CLAIM_SUFFIX, CORPUS_INGESTED_SUFFIX } from '../sweep.ts';
import { appendCheckpointManifest } from './session-state.ts';
-import { corpusTextForExtraction, readSegmentLedger, HARVEST_RECEIPT_SUFFIX } from './corpus-segments.ts';
+import { corpusFileSessionId, corpusTextForExtraction, readSegmentLedger, selfCaptureSidecarJson, HARVEST_RECEIPT_SUFFIX } from './corpus-segments.ts';
+import { isClaudeCliSelfSessionId } from '../ai/providers/claude-cli-scratch.ts';
import { writeHeartbeat } from './hook-heartbeat.ts';
/** Bounded queue — overflow is a typed skip; the sweep backstop extracts later. */
@@ -399,6 +400,14 @@ async function runWritebackTurn(job: HarvestJob, full: string, ingestedPath: str
duplicate?: number;
superseded?: number;
}> {
+ // #5820: a turn banked from gbrain's own claude-cli session (an older
+ // binary's Stop hook, or a child that still ran user hooks) is terminal
+ // here exactly as in the sweep — extracting it would spawn another
+ // claude-cli call that banks again.
+ if (isClaudeCliSelfSessionId(corpusFileSessionId(job.file))) {
+ await writeFile(ingestedPath, selfCaptureSidecarJson());
+ return { outcome: 'ok', reason: 'self_capture' };
+ }
const { resolveWritebackConfig } = await import('../facts/writeback-config.ts');
const { loadConfig } = await import('../config.ts');
// Gate semantics ({gate:true}): a config READ FAILURE is OFF but NOT
diff --git a/src/core/context/corpus-segments.ts b/src/core/context/corpus-segments.ts
index ce3467c55b..a40aaf74bb 100644
--- a/src/core/context/corpus-segments.ts
+++ b/src/core/context/corpus-segments.ts
@@ -353,6 +353,13 @@ export function writebackOffSidecarJson(): string {
return JSON.stringify({ ingested_at: new Date().toISOString(), skipped: 'writeback_off' }) + '\n';
}
+/** The TERMINAL self_capture `.ingested` sidecar payload (#5413/#5820) —
+ * written identically by the serve harvest and the sweep, so neither retries
+ * a corpus file captured from gbrain's own claude-cli session. */
+export function selfCaptureSidecarJson(): string {
+ return JSON.stringify({ ingested_at: new Date().toISOString(), skipped: 'self_capture' }) + '\n';
+}
+
/**
* Bank one gated user turn as a writeback corpus file: redacted render
* (NEVER written unscanned — scanner unavailable is a typed skip, matching
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index 7d02c73457..7393ab1011 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -576,7 +576,7 @@ async function runCorpusIngestPass(
// OFF retires banked turns even when the brain cannot extract — otherwise
// the files linger eligible and a later re-enable would extract turns the
// operator already revoked (codex re-review, this wave).
- const { parseWbFileName, writebackOffSidecarJson, corpusFileSessionId, corpusTextForExtraction } = await import('./context/corpus-segments.ts');
+ const { parseWbFileName, writebackOffSidecarJson, selfCaptureSidecarJson, corpusFileSessionId, corpusTextForExtraction } = await import('./context/corpus-segments.ts');
const { resolveWritebackConfig } = await import('./facts/writeback-config.ts');
const { loadConfig: loadFileCfg } = await import('./config.ts');
const { isValidSourceId } = await import('./source-id.ts');
@@ -624,8 +624,8 @@ async function runCorpusIngestPass(
const { runFactsPipeline } = await import('./facts/backstop.ts');
const { isDreamOutput } = await import('./cycle/transcript-discovery.ts');
- const { claudeCliSelfSessionIds } = await import('./ai/providers/claude-cli-scratch.ts');
- const selfCaptureIds = claudeCliSelfSessionIds();
+ const { claudeCliSelfProjectDirs, isClaudeCliSelfSessionId } = await import('./ai/providers/claude-cli-scratch.ts');
+ const selfProjectDirs = claudeCliSelfProjectDirs();
for (let i = 0; i < candidates.length; i++) {
if (overBudget()) {
@@ -656,11 +656,8 @@ async function runCorpusIngestPass(
// #5413: a corpus file captured from gbrain's own claude-cli call, in
// any capture form. Extracting it spawns another claude-cli call; the
// classification is permanent, so the terminal sidecar stops the retry.
- if (selfCaptureIds.has(corpusFileSessionId(name))) {
- await writeFile(
- full + CORPUS_INGESTED_SUFFIX,
- JSON.stringify({ ingested_at: new Date().toISOString(), skipped: 'self_capture' }) + '\n',
- );
+ if (isClaudeCliSelfSessionId(corpusFileSessionId(name), selfProjectDirs)) {
+ await writeFile(full + CORPUS_INGESTED_SUFFIX, selfCaptureSidecarJson());
skip('self_capture');
continue;
}
diff --git a/test/checkpoint-harvest.serial.test.ts b/test/checkpoint-harvest.serial.test.ts
index f97e06ed64..69fe9a011a 100644
--- a/test/checkpoint-harvest.serial.test.ts
+++ b/test/checkpoint-harvest.serial.test.ts
@@ -18,7 +18,8 @@ import { detectCapabilities } from '../src/core/capability.ts';
import { RECIPES } from '../src/core/ai/recipes/index.ts';
import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';
import type { CapabilityReport } from '../src/core/capability.ts';
-import { CORPUS_CLAIM_SUFFIX, CORPUS_INGESTED_SUFFIX } from '../src/core/sweep.ts';
+import { CORPUS_CLAIM_SUFFIX, CORPUS_INGESTED_SUFFIX, runMaintenanceSweep } from '../src/core/sweep.ts';
+import { CLAUDE_CLI_CWD_PREFIX } from '../src/core/ai/providers/claude-cli-scratch.ts';
import { toCorpusText } from '../src/core/transcripts/claude-code-jsonl.ts';
import {
__drainCheckpointHarvestForTests,
@@ -720,3 +721,59 @@ describe('pasted content never reaches the extractor (#5812)', () => {
expect(prompts.join('\n')).toContain('I prefer dark roast coffee');
});
});
+
+describe('serve-lane self-capture skip (#5820)', () => {
+ let savedConfigDir: string | undefined;
+ beforeEach(() => {
+ savedConfigDir = process.env.CLAUDE_CONFIG_DIR;
+ const claudeDir = mkdtempSync(join(tmpdir(), 'gb-ckpt-claude-'));
+ tmpDirs.push(claudeDir);
+ process.env.CLAUDE_CONFIG_DIR = claudeDir;
+ const scratch = join(claudeDir, 'projects', `-tmp-${CLAUDE_CLI_CWD_PREFIX}4242`);
+ mkdirSync(scratch, { recursive: true });
+ writeFileSync(join(scratch, 'sess-self.jsonl'), '{}\n');
+ });
+ afterEach(() => {
+ if (savedConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;
+ else process.env.CLAUDE_CONFIG_DIR = savedConfigDir;
+ });
+
+ test('a banked self-capture scheduled over IPC makes zero extraction calls and leaves the terminal sidecar; the sweep then skips it', async () => {
+ await engine.setConfig('memory.auto_writeback', 'salient');
+ const prompts = recordingChatStub();
+ const g = gateWritebackTurn('Extract the facts from the following page and return them as JSON objects.');
+ if (!g.ok) throw new Error('fixture gated');
+ const banked = await bankWritebackTurn(corpusDir, 'sess-self', g.normalized, g.hash24);
+ const handler = makeContextPackIpcHandler(engine, 'default');
+ const ack = await handler({
+ kind: 'context_pack', protocol: 2, secret: 's', sessionId: 'sess-self', bankOnly: true,
+ window: [], flushCorpusFile: banked.flushCorpusFile!,
+ });
+ expect(ack?.checkpointFlush?.status).toBe('scheduled');
+ await __drainCheckpointHarvestForTests();
+ expect(prompts).toEqual([]);
+ const sidecar = JSON.parse(readFileSync(join(corpusDir, banked.flushCorpusFile! + CORPUS_INGESTED_SUFFIX), 'utf8'));
+ expect(sidecar.skipped).toBe('self_capture');
+ const hb = (await readHeartbeatTail(10)).filter((e) => e.event === 'writeback');
+ expect(hb[0]).toMatchObject({ outcome: 'ok', reason: 'self_capture' });
+
+ const swept = await runMaintenanceSweep(engine, { sourceId: 'default', capabilities: KEYED });
+ expect(swept.corpusIngested).toBe(0);
+ expect(swept.skipped).toContainEqual({ reason: 'already_ingested', count: 1 });
+ expect(prompts).toEqual([]);
+ const rows = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE source_session = 'sess-self'`);
+ expect(rows.length).toBe(0);
+ });
+
+ test('an ordinary session in the same corpus is still extracted', async () => {
+ await engine.setConfig('memory.auto_writeback', 'salient');
+ const prompts = recordingChatStub();
+ const g = gateWritebackTurn('I prefer dark roast coffee and I want it on every order.');
+ if (!g.ok) throw new Error('fixture gated');
+ const banked = await bankWritebackTurn(corpusDir, 'sess-human', g.normalized, g.hash24);
+ scheduleCheckpointHarvest({ engine, sourceId: 'default', sessionId: 'sess-human', corpusDir, file: banked.flushCorpusFile!, capabilities: KEYED, lane: 'writeback' });
+ await __drainCheckpointHarvestForTests();
+ expect(prompts.length).toBeGreaterThan(0);
+ expect(JSON.parse(readFileSync(join(corpusDir, banked.flushCorpusFile! + CORPUS_INGESTED_SUFFIX), 'utf8')).lane).toBe('writeback');
+ });
+});
diff --git a/test/doctor-self-capture.test.ts b/test/doctor-self-capture.test.ts
index fb092e0109..bcf7631f9a 100644
--- a/test/doctor-self-capture.test.ts
+++ b/test/doctor-self-capture.test.ts
@@ -58,6 +58,11 @@ describe('self_capture doctor check', () => {
expect(check.details).toMatchObject({ classified: 3, unclassifiable: 1, corpus_files: 5, count: 'exact' });
expect([...check.details!.classified_sample as string[]].sort()).toEqual(['nested/self-c.txt', 'self-a.txt', 'self-b.txt']);
expect(check.message).toContain('Nothing was moved or deleted');
+ // New captures stopped vs old files remain (#5820): the newest capture's
+ // time is reported so a growing count is visible.
+ expect(typeof check.details!.newest_capture_at).toBe('string');
+ expect(check.message).toContain(`the newest is from ${check.details!.newest_capture_at}`);
+ expect(check.message).toContain('no longer creates them (#5820)');
expect(check.message).toContain('mkdir -p');
expect(readdirSync(corpus).sort()).toEqual(before);
diff --git a/test/hook-writeback-stop.serial.test.ts b/test/hook-writeback-stop.serial.test.ts
index bc0730824d..8906d7499c 100644
--- a/test/hook-writeback-stop.serial.test.ts
+++ b/test/hook-writeback-stop.serial.test.ts
@@ -14,6 +14,7 @@ import type net from 'node:net';
import { runHook } from '../src/commands/hook.ts';
import { readHeartbeatTail } from '../src/core/context/hook-heartbeat.ts';
+import { CLAUDE_CLI_CWD_PREFIX } from '../src/core/ai/providers/claude-cli-scratch.ts';
import { startResolveIpcServer, ensureIpcSecret, resolveSocketPath, type ContextPackRequest, } from '../src/core/context/resolve-ipc.ts';
import type { TurnContextResult } from '../src/core/context/turn-context.ts';
@@ -335,3 +336,25 @@ describe('hook stop — pasted content (#5812)', () => {
expect((await wbHeartbeats())[0]?.reason).toBe('no_user_turn');
});
});
+
+describe('hook stop — gbrain claude-cli self-capture (#5820)', () => {
+ const PROMPT = 'Extract the facts from the following page and return them as JSON objects.';
+
+ test('a Stop payload from a claude-cli scratch session banks nothing: by-design self_capture', async () => {
+ writeConfig({ writeback: 'salient' });
+ const t = writeTurns([{ role: 'user', text: PROMPT }, { role: 'assistant', text: '{"facts":[]}' }], `-tmp-${CLAUDE_CLI_CWD_PREFIX}4242`);
+ expect(await runHook(['stop'], { ...io, transcriptRoot: t.root, stdin: JSON.stringify({ session_id: 's-wb', transcript_path: t.path }) })).toBe(0);
+ expect(bankedTexts()).toEqual([]);
+ const hb = await wbHeartbeats();
+ expect(hb.map((e) => [e.reason, e.outcome])).toEqual([['self_capture', 'ok']]);
+ });
+
+ test('the payload cwd fingerprint alone is enough', async () => {
+ writeConfig({ writeback: 'salient' });
+ const t = writeTurns([{ role: 'user', text: PROMPT }, { role: 'assistant', text: '{"facts":[]}' }]);
+ const cwd = join(tmpdir(), `${CLAUDE_CLI_CWD_PREFIX}4242`);
+ expect(await runHook(['stop'], { ...io, transcriptRoot: t.root, stdin: JSON.stringify({ session_id: 's-wb', transcript_path: t.path, cwd }) })).toBe(0);
+ expect(bankedTexts()).toEqual([]);
+ expect((await wbHeartbeats())[0]?.reason).toBe('self_capture');
+ });
+});
diff --git a/test/transcripts-self-exclusion.test.ts b/test/transcripts-self-exclusion.test.ts
index fcc2346951..563ca2fa51 100644
--- a/test/transcripts-self-exclusion.test.ts
+++ b/test/transcripts-self-exclusion.test.ts
@@ -30,6 +30,9 @@ import {
CLAUDE_CLI_CWD_PREFIX,
claudeCliCwdDir,
claudeCliConfigDir,
+ claudeCliSelfProjectDirs,
+ claudeCliSelfSessionIds,
+ isClaudeCliSelfSessionId,
isClaudeCliSelfTranscriptPath,
sweepDeadClaudeCliScratchDirs,
} from '../src/core/ai/providers/claude-cli-scratch.ts';
@@ -94,6 +97,29 @@ describe('transcript discovery — claude-cli self-session exclusion (#4472)', (
});
});
+describe('single-session self-capture classifier (#5820)', () => {
+ test('true only for a session id held by a scratch project; agrees with the set form', () => {
+ const dirs = claudeCliSelfProjectDirs(projectsRoot);
+ expect(dirs.map((d) => basename(d))).toEqual([`-private-tmp-${CLAUDE_CLI_CWD_PREFIX}12345`]);
+ expect(isClaudeCliSelfSessionId('session-self', dirs)).toBe(true);
+ expect(isClaudeCliSelfSessionId('session-user', dirs)).toBe(false);
+ expect(isClaudeCliSelfSessionId('no-such-session', dirs)).toBe(false);
+ expect([...claudeCliSelfSessionIds(projectsRoot)]).toEqual(['session-self']);
+ });
+
+ test('a path-shaped id never escapes the scratch projects', () => {
+ const dirs = claudeCliSelfProjectDirs(projectsRoot);
+ expect(isClaudeCliSelfSessionId('../-Users-alice-code-myapp/session-user', dirs)).toBe(false);
+ expect(isClaudeCliSelfSessionId('..', dirs)).toBe(false);
+ expect(isClaudeCliSelfSessionId('', dirs)).toBe(false);
+ });
+
+ test('a missing projects root classifies nothing', () => {
+ expect(claudeCliSelfProjectDirs(join(projectsRoot, 'missing'))).toEqual([]);
+ expect(isClaudeCliSelfSessionId('session-self', [])).toBe(false);
+ });
+});
+
describe('transcript discovery — claude-code subagent log exclusion (#4796)', () => {
test('subagent logs are not sessions: discovery skips them, real projects still surface', () => {
const names = discoverTranscriptFiles(roots).map((f) => basename(f.path));