Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(doctor): --only runs one wave check; self-session lookups read once
garrytanff713923640a
diff --git a/docs/architecture/key-files/core-ai-continued.md b/docs/architecture/key-files/core-ai-continued.mdindex d3c88b1fe2..0f3d5a5c62 100644--- a/docs/architecture/key-files/core-ai-continued.md+++ b/docs/architecture/key-files/core-ai-continued.md@@ -8,7 +8,7 @@ Provider adapters, recipes and the Voyage width plumbing.- `src/core/ai/providers/claude-cli-continuation.ts` — what text a claude-cli print-mode run answered. Claude Code continues a response that hit its output cap on its own (meta "Resume directly" nudge, second request), and the envelope's `result` / `stop_reason` are then only the continuation's. `resolveClaudeCliAnswer(run, requestedCap)` keeps the envelope `result` when there was no continuation (or the envelope already says `max_tokens`); otherwise it rebuilds the answer from the call's own events (consecutive assistant events sharing a `message.id` are one segment; `<synthetic>` error messages are skipped), joining the segments' text in order. A rebuild needs the last segment's final text block to equal `result`, no `tombstone` event, every earlier text-bearing segment to report `max_tokens` or no stop reason, and every user event between segments to be a "Resume directly" nudge; anything else is `continuation_unproven` with reason `segments_unmatched`. Without events (a bare envelope) a continuation is inferred from `num_turns > 1` or output tokens above the cap (the forwarded positive-integer `maxOutputTokens`, else `CLAUDE_CLI_DEFAULT_OUTPUT_CAP` = 32000) and refused as `events_missing`; an event array with no assistant message under those signals is `no_assistant_events`; one segment with output above a requested cap is `segments_unmatched`. Each reason's first refusal in a process writes one notice naming its remedy (`CONTINUATION_UNPROVEN_REMEDY`: upgrade the CLI for the first two, raise the caller's output cap for the third). Nothing is read from disk, so a hermetic `CLAUDE_CONFIG_DIR` changes nothing. The notice is one `[claude-cli] continuation_unproven (<reason>)` stderr line; `continuationUnprovenMetadata` builds the provider metadata. Pinned by `test/claude-cli-continuation-6791.test.ts`.-- `src/core/ai/providers/claude-cli-scratch.ts` — the claude-cli provider's per-PID scratch dirs (`claudeCliCwdDir`/`claudeCliConfigDir` off the `CLAUDE_CLI_CWD_PREFIX`/`CLAUDE_CLI_CONFIG_PREFIX` basename constants, plus `sweepDeadClaudeCliScratchDirs`), split into a dependency-light module so transcript discovery (`src/core/transcripts/discover.ts`) can call `isClaudeCliSelfTranscriptPath(path)` WITHOUT importing the provider's @ai-sdk surface. Each `claude --print` subprocess runs with cwd = a per-PID scratch dir (context isolation — no local CLAUDE.md auto-discovery), and Claude Code records a session transcript for that cwd under `~/.claude/projects/<slugified-cwd>/`; those sessions are gbrain's OWN internal LLM calls, and importing them back is a self-ingestion feedback loop (prompt scaffolding + page content re-entering as "conversations"). The prefix is lowercase `[a-z-]` only, so it survives Claude Code's cwd slugification verbatim and a substring match on the discovered path is a reliable self-exclusion fingerprint. `claudeCliSelfSessionIds(projectsRoot = claudeProjectsDir())` lists the session ids of those harness transcripts; `isClaudeCliSelfSessionId(id, projectDirs = claudeCliSelfProjectDirs())` is the single-session classifier (#5820) shared by the serve-side writeback harvest, the sweep and doctor `self_capture`: one listing of the projects root, then an existence check per prefix-matched scratch project (path-shaped ids are refused); the session-end hook named each corpus file `<session id>.txt`, so dream discovery and the sweep's corpus pass use the set to skip self-captures written before the hook refused them (best-effort: a pruned harness transcript leaves its capture unclassifiable). Pinned by `test/transcripts-self-exclusion.test.ts`.+- `src/core/ai/providers/claude-cli-scratch.ts` — the claude-cli provider's per-PID scratch dirs (`claudeCliCwdDir`/`claudeCliConfigDir` off the `CLAUDE_CLI_CWD_PREFIX`/`CLAUDE_CLI_CONFIG_PREFIX` basename constants, plus `sweepDeadClaudeCliScratchDirs`), split into a dependency-light module so transcript discovery (`src/core/transcripts/discover.ts`) can call `isClaudeCliSelfTranscriptPath(path)` WITHOUT importing the provider's @ai-sdk surface. Each `claude --print` subprocess runs with cwd = a per-PID scratch dir (context isolation — no local CLAUDE.md auto-discovery), and Claude Code records a session transcript for that cwd under `~/.claude/projects/<slugified-cwd>/`; those sessions are gbrain's OWN internal LLM calls, and importing them back is a self-ingestion feedback loop (prompt scaffolding + page content re-entering as "conversations"). The prefix is lowercase `[a-z-]` only, so it survives Claude Code's cwd slugification verbatim and a substring match on the discovered path is a reliable self-exclusion fingerprint. `claudeCliSelfSessionIds(projectsRoot = claudeProjectsDir())` lists the session ids of those harness transcripts; `isClaudeCliSelfSessionId(id, projectDirs = claudeCliSelfProjectDirs())` is the single-session classifier (#5820) shared by the serve-side writeback harvest and the sweep: one listing of the projects root, then an existence check per prefix-matched scratch project (path-shaped ids are refused); `claudeCliSelfSessions(projectsRoot)` maps each self session id to the first scratch project holding it from one listing per project, and the bulk classifiers (doctor `self_capture`, `classifyCapturedFacts`) look ids up there, so their filesystem reads do not grow with the number of items (#7343, `test/doctor-only-wave-7343.test.ts`); the session-end hook named each corpus file `<session id>.txt`, so dream discovery and the sweep's corpus pass use the set to skip self-captures written before the hook refused them (best-effort: a pruned harness transcript leaves its capture unclassifiable). Pinned by `test/transcripts-self-exclusion.test.ts`.- `src/core/ai/recipes/anthropic.ts` — Anthropic recipe (chat + expansion touchpoints). Canonical id is `claude-sonnet-4-6` (no date suffix); a reverse alias `claude-sonnet-4-6-20250929 → claude-sonnet-4-6` keeps stale user configs working (rescues `facts.extraction_model` and `models.dream.synthesize`). Recipe shape pinned by `test/anthropic-model-ids.test.ts`.diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex 9c808727f4..ed78ee2e6c 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -305,19 +305,22 @@ export const staleMentionsEntry: DoctorEntry = {};async function runTimelineHistory(ctx: DoctorContext): Promise<Check[]> {- const { orphanRatioSourceId, progress } = ctx;+ const { orphanRatioSourceId, progress, only } = ctx;const engine = connectedEngine(ctx);const checks: Check[] = [];// 9d. Wave 2 residual-state signals (#5567, #5525): database-only timeline// rows and derived pages without explicit visibility. Bounded, never throw.+ // #7343: under --only, run just the named checks of this entry.progress.heartbeat('timeline_history');{- const { timelineHistoryCheck } = await import('./timeline-history.ts');- checks.push(await timelineHistoryCheck(engine, orphanRatioSourceId));+ if (!only || only.has('timeline_history')) {+ const { timelineHistoryCheck } = await import('./timeline-history.ts');+ checks.push(await timelineHistoryCheck(engine, orphanRatioSourceId));+ }// Wave checks registered in doctor/wave-checks.ts rather than inline here.const { runWaveChecks } = await import('../wave-checks.ts');- for (const finding of await runWaveChecks(engine, { only: 'wave', sourceIds: orphanRatioSourceId ? [orphanRatioSourceId] : undefined })) checks.push(finding.check);+ for (const finding of await runWaveChecks(engine, { only: 'wave', ids: only ?? undefined, sourceIds: orphanRatioSourceId ? [orphanRatioSourceId] : undefined })) checks.push(finding.check);}return checks;}diff --git a/src/commands/doctor/checks/self-capture.ts b/src/commands/doctor/checks/self-capture.tsindex 0d95972f37..00d1ba354a 100644--- a/src/commands/doctor/checks/self-capture.ts+++ b/src/commands/doctor/checks/self-capture.ts@@ -15,7 +15,7 @@ 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 { claudeCliSelfProjectDirs, isClaudeCliSelfSessionId } from '../../../core/ai/providers/claude-cli-scratch.ts';+import { claudeCliSelfSessionIds } 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,13 +63,13 @@ 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 selfDirs = claudeCliSelfProjectDirs(projectsRoot);+ const selfSessions = claudeCliSelfSessionIds(projectsRoot);const known = harnessSessionIds(projectsRoot);const classified: string[] = [], unclassifiable: string[] = [];let newestMs = 0;for (const file of files) {const session = corpusFileSessionId(basename(file));- if (isClaudeCliSelfSessionId(session, selfDirs)) {+ if (selfSessions.has(session)) {classified.push(file);try { newestMs = Math.max(newestMs, statSync(file).mtimeMs); } catch { /* raced away */ }} else if (!known.has(session)) unclassifiable.push(file);diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 3cd61938dc..4a0281967c 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -423,8 +423,8 @@ export function checkHealthUnknown(check: Check): boolean {export interface WaveFinding { spec: WaveCheckSpec; check: Check; state: 'ok' | 'finding' | 'unknown' }/** Run wave checks; a throwing check becomes an unknown finding instead of aborting the rest. */-export async function runWaveChecks(engine: BrainEngine, opts: WaveScope & { only?: WaveCheckSpec['registration']; remote?: boolean } = {}): Promise<WaveFinding[]> {- const specs = WAVE_CHECKS.filter(spec => (!opts.only || spec.registration === opts.only) && (!opts.remote || !spec.hostOnly));+export async function runWaveChecks(engine: BrainEngine, opts: WaveScope & { only?: WaveCheckSpec['registration']; ids?: ReadonlySet<string>; remote?: boolean } = {}): Promise<WaveFinding[]> {+ const specs = WAVE_CHECKS.filter(spec => (!opts.only || spec.registration === opts.only) && (!opts.ids || opts.ids.has(spec.id)) && (!opts.remote || !spec.hostOnly));const findings: WaveFinding[] = [];for (const spec of specs) {let check: Check;diff --git a/src/core/ai/providers/claude-cli-scratch.ts b/src/core/ai/providers/claude-cli-scratch.tsindex ba86aae32f..1a1acb4bda 100644--- a/src/core/ai/providers/claude-cli-scratch.ts+++ b/src/core/ai/providers/claude-cli-scratch.ts@@ -25,6 +25,8 @@ export const CLAUDE_CLI_CWD_PREFIX = 'gbrain-claude-cli-cwd-';/** Basename prefix of the per-PID hermetic CLAUDE_CONFIG_DIR (#4119). */export const CLAUDE_CLI_CONFIG_PREFIX = 'gbrain-claude-cli-config-';+const SESSION_ID_RE = /^[A-Za-z0-9_-][A-Za-z0-9._-]*$/;+/** The per-PID scratch cwd path for this process. */export function claudeCliCwdDir(pid: number = process.pid): string {return join(tmpdir(), `${CLAUDE_CLI_CWD_PREFIX}${pid}`);@@ -54,7 +56,17 @@ export function isClaudeCliSelfTranscriptPath(path: string): boolean {* has since pruned is unclassifiable and stays in the corpus.*/export function claudeCliSelfSessionIds(projectsRoot: string = claudeProjectsDir()): Set<string> {- const ids = new Set<string>();+ return new Set(claudeCliSelfSessions(projectsRoot).keys());+}++/**+ * #7343: every self session id mapped to the first scratch project holding its+ * transcript, from one listing per scratch project. Bulk classifiers (doctor+ * `self_capture`, `captured_facts_active`) look ids up here instead of+ * checking every scratch project once per item.+ */+export function claudeCliSelfSessions(projectsRoot: string = claudeProjectsDir()): Map<string, string> {+ const sessions = new Map<string, string>();for (const project of claudeCliSelfProjectDirs(projectsRoot)) {let files: string[];try {@@ -63,10 +75,11 @@ export function claudeCliSelfSessionIds(projectsRoot: string = claudeProjectsDircontinue;}for (const file of files) {- if (file.endsWith('.jsonl')) ids.add(file.slice(0, -'.jsonl'.length));+ const id = file.slice(0, -'.jsonl'.length);+ if (file.endsWith('.jsonl') && SESSION_ID_RE.test(id) && !sessions.has(id)) sessions.set(id, project);}}- return ids;+ return sessions;}/** The harness project dirs of gbrain claude-cli scratch cwds (one listing of@@ -91,7 +104,7 @@ export function isClaudeCliSelfSessionId(id: string,projectDirs: readonly string[] = claudeCliSelfProjectDirs(),): boolean {- if (!/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/.test(id)) return false;+ if (!SESSION_ID_RE.test(id)) return false;return projectDirs.some((dir) => existsSync(join(dir, `${id}.jsonl`)));}diff --git a/src/core/repair/captured-facts.ts b/src/core/repair/captured-facts.tsindex 1cff4c4499..b5bc10eb7d 100644--- a/src/core/repair/captured-facts.ts+++ b/src/core/repair/captured-facts.ts@@ -49,7 +49,7 @@ import type { PreparedMutation } from '../persistence/coordinator.ts';import type { WriteRequest } from '../persistence/model.ts';import { submitPageMutation } from '../persistence/page-mutations.ts';import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';-import { claudeCliSelfProjectDirs, isClaudeCliSelfSessionId } from '../ai/providers/claude-cli-scratch.ts';+import { claudeCliSelfSessions } from '../ai/providers/claude-cli-scratch.ts';import { claudeProjectsDir } from '../bootstrap/host-specs.ts';import { corpusFileSessionId, corpusTextForExtraction } from '../context/corpus-segments.ts';import { pruneDir } from '../sync.ts';@@ -167,7 +167,7 @@ export async function classifyCapturedFacts(db: BrainEngine, sourceIds: string[]ORDER BY f.source_id, f.id`, [sourceIds, [...CAPTURE_LANES], opts.ids ?? null]);if (!rows.length) return { candidates: [], unclassifiable: 0, not_suspect: 0, unreadable_corpus_files: [] };const projectsRoot = opts.projectsRoot ?? claudeProjectsDir();- const selfDirs = claudeCliSelfProjectDirs(projectsRoot);+ const selfSessions = claudeCliSelfSessions(projectsRoot);const known = harnessSessionIds(projectsRoot);const corpusDir = opts.corpusDir === undefined ? await db.getConfig(CORPUS_KEY) : opts.corpusDir;const unreadable: string[] = [];@@ -194,10 +194,8 @@ export async function classifyCapturedFacts(db: BrainEngine, sourceIds: string[]const classified: Array<Hit | 'unclassifiable' | 'not_suspect'> = rows.map(row => {const session = captureSessionId(row.source_session);if (!session) return 'unclassifiable';- if (isClaudeCliSelfSessionId(session, selfDirs)) {- const dir = selfDirs.find(d => existsSync(join(d, `${session}.jsonl`)))!;- return { klass: 'evidenced', reason: 'self_capture_transcript', session, evidence: join(basename(dir), `${session}.jsonl`) };- }+ const selfDir = selfSessions.get(session);+ if (selfDir) return { klass: 'evidenced', reason: 'self_capture_transcript', session, evidence: join(basename(selfDir), `${session}.jsonl`) };const quarantined = quarantine.get(session);if (quarantined?.length) return { klass: 'evidenced', reason: 'self_capture_quarantined', session, evidence: basename(quarantined[0]!) };const paste = pasteOnlyWords(session);diff --git a/test/doctor-only-wave-7343.test.ts b/test/doctor-only-wave-7343.test.tsnew file mode 100644index 0000000000..48dc5afcb6--- /dev/null+++ b/test/doctor-only-wave-7343.test.ts@@ -0,0 +1,115 @@+/**+ * #7343: `gbrain doctor --only <wave check>` ran every wave check, and the+ * self-session classifier made one existence check per scratch project per+ * item.+ *+ * - The timeline_history entry runs only the checks `--only` names: a wave+ * check alone, timeline_history only when named, everything without --only.+ * - `captured_facts_active` (classifyCapturedFacts) and `self_capture` read+ * each scratch project once, so the filesystem calls do not grow with the+ * number of facts or corpus files, and the classification is unchanged.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import * as fs from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { timelineHistoryEntry } from '../src/commands/doctor/checks/graph-health.ts';+import { selfCaptureCheck } from '../src/commands/doctor/checks/self-capture.ts';+import { classifyCapturedFacts } from '../src/core/repair/captured-facts.ts';+import { CLAUDE_CLI_CWD_PREFIX } from '../src/core/ai/providers/claude-cli-scratch.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';++const noProgress = new Proxy({}, { get: () => () => undefined }) as DoctorContext['progress'];+const SCRATCH_PROJECTS = 6;+const SESSIONS = 30;++let engine: PGLiteEngine;+const root = fs.mkdtempSync(join(tmpdir(), 'gbrain-7343-'));+const projects = join(root, 'claude', 'projects');+const corpus = join(root, 'corpus');+const lastScratch = `-tmp-${CLAUDE_CLI_CWD_PREFIX}${1000 + SCRATCH_PROJECTS - 1}`;+const selfSessions = Array.from({ length: SESSIONS }, (_, i) => i).filter(i => i % 3 === 0).map(i => `sess-${i}`);++function ctxFor(only: Set<string> | null): DoctorContext {+ return {+ engine, args: ['--json'], jsonOutput: true, fastMode: false, doFix: false, dryRun: false, scope: 'brain', orphanRatioSourceId: undefined,+ progress: noProgress, skillsDirResolution: { dir: null, source: 'none' }, skillsDir: null, autoFixReport: null, schemaVersion: 0,+ connectionFailed: false, only, tier: 'standard',+ };+}++const names = async (only: Set<string> | null) => ((await timelineHistoryEntry.run(ctxFor(only))) as Array<{ name: string }>).map(c => c.name);++/** Counts fs calls whose path lies under the harness projects root while `run` executes. */+async function projectFsCalls<T>(run: () => Promise<T>): Promise<{ result: T; exists: number; readdirs: number }> {+ const under = (p: unknown) => typeof p === 'string' && p.startsWith(projects);+ const exists = spyOn(fs, 'existsSync');+ const readdir = spyOn(fs, 'readdirSync');+ try {+ const result = await run();+ return { result, exists: exists.mock.calls.filter(([p]) => under(p)).length, readdirs: readdir.mock.calls.filter(([p]) => under(p)).length };+ } finally {+ exists.mockRestore();+ readdir.mockRestore();+ }+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ fs.mkdirSync(corpus, { recursive: true });+ for (let p = 0; p < SCRATCH_PROJECTS; p++) fs.mkdirSync(join(projects, `-tmp-${CLAUDE_CLI_CWD_PREFIX}${1000 + p}`), { recursive: true });+ fs.mkdirSync(join(projects, '-home-user-work'), { recursive: true });+ for (let i = 0; i < SESSIONS; i++) {+ const id = `sess-${i}`;+ fs.writeFileSync(join(projects, selfSessions.includes(id) ? lastScratch : '-home-user-work', `${id}.jsonl`), '{}\n');+ fs.writeFileSync(join(corpus, `${id}.txt`), `[user]\nsession ${i}\n`);+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_session)+ VALUES ('default', 'people/alice-example', $1, 'fact', 'private', 'hook:writeback', $2)`, [`Alice Example fact number ${i}`, id]);+ }+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+ fs.rmSync(root, { recursive: true, force: true });+});++describe('#7343 doctor --only selects single wave checks', () => {+ test('a wave check named in --only runs alone', async () => {+ expect(await names(new Set(['writer_version']))).toEqual(['writer_version']);+ }, 60_000);++ test('timeline_history runs only when named, and alone', async () => {+ expect(await names(new Set(['timeline_history']))).toEqual(['timeline_history']);+ }, 60_000);++ test('two named wave checks run in entry order, and nothing else', async () => {+ expect(await names(new Set(['keyword_plan', 'segmented_storage']))).toEqual(['segmented_storage', 'keyword_plan']);+ }, 60_000);++ test('without --only the entry still emits every check it declares', async () => {+ expect(await names(null)).toEqual([...timelineHistoryEntry.emits]);+ }, 120_000);+});++describe('#7343 self-session lookups read each scratch project once', () => {+ test('classifyCapturedFacts: no per-fact existence checks, same classes', async () => {+ const { result, exists, readdirs } = await projectFsCalls(() => classifyCapturedFacts(engine, ['default'], { projectsRoot: projects, corpusDir: corpus }));+ const evidenced = result.candidates.filter(c => c.reason === 'self_capture_transcript');+ expect(evidenced.map(c => c.session).sort()).toEqual([...selfSessions].sort());+ expect(evidenced.every(c => c.evidence === join(lastScratch, `${c.session}.jsonl`))).toBe(true);+ expect(result.not_suspect).toBe(SESSIONS - selfSessions.length);+ expect(exists).toBe(0);+ expect(readdirs).toBeLessThanOrEqual(2 * (SCRATCH_PROJECTS + 2));+ }, 60_000);++ test('selfCaptureCheck: no per-file existence checks, same counts', async () => {+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);+ const { result, exists, readdirs } = await projectFsCalls(() => selfCaptureCheck(engine, { projectsRoot: projects }));+ expect(result.details).toMatchObject({ classified: selfSessions.length, unclassifiable: 0, corpus_files: SESSIONS });+ expect(exists).toBe(0);+ expect(readdirs).toBeLessThanOrEqual(2 * (SCRATCH_PROJECTS + 2));+ }, 60_000);+});