Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Ten small fixes from contributor reports: agent-session repair, doctor, prompt hook, sync, transcripts, enrich (#9555)
Garry Tanbaefe65a696d
diff --git a/changelog.d/capy-small-fix-wave-1.md b/changelog.d/capy-small-fix-wave-1.mdnew file mode 100644index 0000000000..1400bc6798--- /dev/null+++ b/changelog.d/capy-small-fix-wave-1.md@@ -0,0 +1,13 @@+**Ten small fixes from outside reports: agent-session repair, doctor, the prompt hook, sync, transcript ingest and enrich.**++### Fixed+- `gbrain repair agent-session-facts` no longer counts sessions that already carry a speaker sidecar toward another session's repeated opening, so an owner session whose prompt was replayed by marked workers is no longer listed as ambiguous (#9521, reported and first fixed by @Masashi-Ono0611).+- `gbrain doctor --only memory_writeback` connects the database instead of reporting it unreachable (#9513, reported and first fixed by @Masashi-Ono0611).+- The Retrieval Reflex recipe's health check and setup steps run only its own doctor check, so an unrelated failing check no longer fails the integration (#9228, reported and first fixed by @johnerik).+- A facts-absorb job that finished by skipping (superseded, page missing, extraction off) no longer counts as proof the page was extracted, so a later rewrite that keeps the body still queues extraction (#9248, reported and first fixed by @Masashi-Ono0611).+- Task notifications and teammate messages no longer get the brain-first nudge, in the main prompt hook and in the turn-rule hook; prompts a person types are unchanged (#9163, reported and first fixed by @Masashi-Ono0611).+- A failed commit-ledger location lookup is retried on the next call instead of being remembered for the life of the process (#8870, reported and first fixed by @sx4im).+- `gbrain sync --all --parallel N` caps how many sources run at once, as its help says, and `--max-sources` still wins when both are given (#8951, reported and first fixed by @Masashi-Ono0611).+- `gbrain transcripts ingest` skips Claude Code's per-project `sessions-index.json` instead of reporting an unknown format on every run (#9115, reported and first fixed by @Masashi-Ono0611).+- The autopilot-install doctor test names its installer target, so on macOS it can no longer load a real LaunchAgent (#9545, reported and first fixed by @Kkkkkuro).+- `gbrain enrich` stops asking the provider for a prompt cache, because its system prompt is below the smallest cacheable prefix and the cache was written on every call but never read (#9541, reported and first fixed by @mattverlaque).diff --git a/docs/guides/repair.md b/docs/guides/repair.mdindex a894af037e..16654497d4 100644--- a/docs/guides/repair.md+++ b/docs/guides/repair.md@@ -2781,7 +2781,7 @@ gbrain doctor| Class | Meaning | Re-attributed || --- | --- | --- || `evidenced` | The fact's session has a speaker sidecar (`<session>.speaker.json` in the corpus directory, its `sourced/` spool or beside the session's corpus files), you named it with `--session <id>`, or its `<session>.source.json` records a working directory under a `--cwd <prefix>` you passed (compared on whole path segments after resolving symlinks). | By `--apply --expect <hash> --yes` |-| `ambiguous` | The session's first message (spaces collapsed, lowercased, at least 40 characters) matches the first 160 characters of the first message of at least 3 other sessions: a template brief. A heuristic, so it is listed in every preview but applied only on request. | Only with `--include-ambiguous` and that preview's hash |+| `ambiguous` | The session's first message (spaces collapsed, lowercased, at least 40 characters) matches the first 160 characters of the first message of at least 3 other sessions that have no speaker sidecar: a template brief. A heuristic, so it is listed in every preview but applied only on request. | Only with `--include-ambiguous` and that preview's hash || `excluded:owner_also_said` | The same claim and entity also has an active fact attributed to you from a session that is not suspect, so you said it too. | Never |Only active capture-lane facts (`hook:writeback`, `hook:compact`,diff --git a/recipes/retrieval-reflex.md b/recipes/retrieval-reflex.mdindex 8c0e25cedb..9cc8caf56b 100644--- a/recipes/retrieval-reflex.md+++ b/recipes/retrieval-reflex.md@@ -9,7 +9,7 @@ requires: []secrets: []health_checks:- type: command- argv: [gbrain, doctor, --json]+ argv: [gbrain, doctor, --only, retrieval_reflex_health, --json]label: Retrieval reflex wiring (see retrieval_reflex_health)setup_time: 2 mincost_estimate: "$0 — zero-LLM deterministic layer + a prose policy skill"@@ -42,11 +42,11 @@ This reflex has two halves:**You are the installer.** Run these steps on behalf of the user.1. Confirm the deterministic layer isn't disabled:- `gbrain doctor --json | jq '.checks[] | select(.name=="retrieval_reflex_health")'`+ `gbrain doctor --only retrieval_reflex_health --json`2. Install the policy skill into the host repo (the OpenClaw/agent repo thatholds `skills/RESOLVER.md` or `AGENTS.md`):`gbrain integrations install retrieval-reflex --target <host-repo>`-3. Verify: re-run `gbrain doctor` and confirm `retrieval_reflex_health` is `ok`.+3. Verify: re-run `gbrain doctor --only retrieval_reflex_health --json` and confirm `retrieval_reflex_health` is `ok`.The deterministic layer needs no install. On a PGLite brain it resolves throughthe running `gbrain serve` (or a host-provided capability); if neither isdiff --git a/recipes/retrieval-reflex/install/post-install-hint.md b/recipes/retrieval-reflex/install/post-install-hint.mdindex 4972a55a94..faab2f3b7a 100644--- a/recipes/retrieval-reflex/install/post-install-hint.md+++ b/recipes/retrieval-reflex/install/post-install-hint.md@@ -13,7 +13,7 @@ operator knows what to do next.### 1. Confirm the deterministic pointer layer is healthy```bash-gbrain doctor --json | jq '.checks[] | select(.name=="retrieval_reflex_health")'+gbrain doctor --only retrieval_reflex_health --json```The pointer layer lives in the gbrain context engine (zero-LLM, on bydiff --git a/src/commands/doctor/checks/local-runtime.ts b/src/commands/doctor/checks/local-runtime.tsindex 799b598387..1c62995c09 100644--- a/src/commands/doctor/checks/local-runtime.ts+++ b/src/commands/doctor/checks/local-runtime.ts@@ -73,6 +73,7 @@ async function runMemorableRelay(ctx: DoctorContext): Promise<Check[]> {export const memorableRelayEntry: DoctorEntry = {name: 'memorable_relay_health',emits: ['memorable_relay_health', 'memory_writeback'],+ engineChecks: ['memory_writeback'],run: runMemorableRelay,};diff --git a/src/commands/enrich.ts b/src/commands/enrich.tsindex fb4b1ee7b0..249c3a0f14 100644--- a/src/commands/enrich.ts+++ b/src/commands/enrich.ts@@ -231,6 +231,7 @@ function completedKey(sourceId: string, slug: string): string {// Default synthesis via the gateway.// ---------------------------------------------------------------------------+/** No prompt cache: the system prompt is below the smallest cacheable prefix, so a cache would only mark this page's evidence (#9541). */export const defaultSynthesize: SynthesizeFn = async ({ system, user, model, abortSignal }) => {const res = await chat({model,@@ -238,7 +239,6 @@ export const defaultSynthesize: SynthesizeFn = async ({ system, user, model, abomessages: [{ role: 'user', content: user }],maxTokens: isThinkingModel(model) ? THINKING_MODEL_MAX_OUTPUT_TOKENS : 2048,abortSignal,- cacheSystem: true,});return res.text;};diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 39ef1fb12c..cb6d3f4e2d 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -1147,13 +1147,13 @@ async function hookUserPrompt(io: HookIo): Promise<number> {// rides the same rail (systemMessage + additionalContext) when no push// failure is pending. Both are cache/file readers, budgeted by the race.turnRule = io.turnRule !== undefined ? io.turnRule : brainFirstTurnRule(io.harness ?? 'claude-code', io.cwd ?? hookSessionCwd());+ const j = await readStdinJson(io, 300);+ // #8028, #9163: a task notification or agent-team message arrives as a prompt but is no human turn: no context, no rule.+ if (typeof j?.prompt === 'string' && /^\s*<(task-notification|teammate-message)[\s>]/.test(j.prompt)) { turnRule = null; return { outcome: 'ok', reason: 'harness_prompt' }; }// The turn-rule lane's connection may reach another brain, so it never reads this machine's context or banners.if (process.env.GBRAIN_HOOK_LANE === TURN_RULE_LANE) return { outcome: 'ok', reason: 'rule_only' };banner = io.disablePushBanner ? null : (pendingPushFailureBanner() ?? pendingBackupBanner());- const j = await readStdinJson(io, 300);if (!j) return { outcome: 'degraded', reason: 'no_stdin' };- // #8028: a task notification or agent-team message arrives as a prompt but is no human turn.- if (typeof j.prompt === 'string' && /^\s*<(task-notification|teammate-message)[\s>]/.test(j.prompt)) return { outcome: 'ok', reason: 'harness_prompt' };// S3#8: transcript_path is untrusted input. A present-but-unconfined// path aborts the event (heartbeat + empty stdout), never "best effort".diff --git a/src/commands/sync/args.ts b/src/commands/sync/args.tsindex ff7eb3d23a..99940b592b 100644--- a/src/commands/sync/args.ts+++ b/src/commands/sync/args.ts@@ -423,7 +423,7 @@ export function parseSyncFanoutFlags(args: string[], syncAll: boolean) {console.error(`--timeout requires either --source <id> or --all to scope the per-source budget.`);process.exit(1);}- return { serialFlag, noAutoEmbed, maxSources, strategyArg, srcSubpath, excludePatterns, includeHiddenPatterns, concurrency, timeoutSeconds, explicitSourceArg };+ return { serialFlag, noAutoEmbed, maxSources: maxSources ?? parallelOverride, strategyArg, srcSubpath, excludePatterns, includeHiddenPatterns, concurrency, timeoutSeconds, explicitSourceArg };}export type SyncFanoutFlags = ReturnType<typeof parseSyncFanoutFlags>;diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.tsindex c8d3ff323f..33d1e42326 100644--- a/src/commands/transcripts.ts+++ b/src/commands/transcripts.ts@@ -29,6 +29,7 @@ import {isClaudeCodeSubagentFile,isClaudeCodeWorkflowArtifactFile,isClaudeCodeRemoteControlStateFile,+ isClaudeCodeSessionsIndexFile,} from '../core/transcripts/claude-code.ts';interface RecentOpts {@@ -309,7 +310,8 @@ export async function expandPaths(specs: string[]): Promise<string[]> {!isGrokSessionSidecarStrict(p) &&!isClaudeCodeSubagentFile(p) &&!isClaudeCodeWorkflowArtifactFile(p) &&- !isClaudeCodeRemoteControlStateFile(p),+ !isClaudeCodeRemoteControlStateFile(p) &&+ !isClaudeCodeSessionsIndexFile(p),);}diff --git a/src/core/git/commit-ledger.ts b/src/core/git/commit-ledger.tsindex e83f0cbf27..bdffd920c5 100644--- a/src/core/git/commit-ledger.ts+++ b/src/core/git/commit-ledger.ts@@ -41,9 +41,9 @@ export type LedgerRecord =| { v: 1; e: 'intent'; t: string; writer: LedgerWriter; head_before: string | null; msg_sha256: string; worktree: string | null; pid: number; host: string | null };interface Location { common: string; gitDir: string; worktree: string | null }-const locations = new Map<string, Location | null>();+const locations = new Map<string, Location>();-/** The repository's common dir, this checkout's git dir and toplevel (null for a bare repository); null outside git. */+/** The repository's common dir, this checkout's git dir and toplevel (null for a bare repository); null outside git. Only a found location is remembered. */export function ledgerLocation(root: string): Location | null {let key = resolve(root);try { key = realpathSync(key); } catch { /* resolved below */ }@@ -59,7 +59,7 @@ export function ledgerLocation(root: string): Location | null {found = { gitDir, common, worktree };}} catch { found = null; }- locations.set(key, found);+ if (found) locations.set(key, found);return found;}diff --git a/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.tsindex d4831f105d..8fcc0190c1 100644--- a/src/core/persistence/effect-facts.ts+++ b/src/core/persistence/effect-facts.ts@@ -64,7 +64,8 @@ async function extractionPendingForPage(engine: BrainEngine, pageId: number): Prasync function extractionCompletedForPage(engine: BrainEngine, pageId: number): Promise<boolean> {const [row] = await engine.executeRaw<{ done: boolean }>(`SELECT EXISTS (SELECT 1 FROM minion_jobs- WHERE name = 'facts-absorb' AND status = 'completed' AND data->>'page_id' = $1) AS done`,+ WHERE name = 'facts-absorb' AND status = 'completed' AND data->>'page_id' = $1+ AND result->>'skipped' IS NULL) AS done`,[String(pageId)]);return row?.done === true;}diff --git a/src/core/repair/agent-session-facts.ts b/src/core/repair/agent-session-facts.tsindex 9ae544c355..b714822eab 100644--- a/src/core/repair/agent-session-facts.ts+++ b/src/core/repair/agent-session-facts.ts@@ -16,8 +16,8 @@* compared on path boundaries).* - ambiguous: the session's first user turn (whitespace-normalized,* lowercased, at least 40 characters) shares its first 160 characters with- * the first user turn of at least 3 other retained sessions (a template- * brief). Listed fact by fact; re-attributed only with+ * the first user turn of at least 3 other retained sessions with no+ * speaker sidecar (a template brief). Listed fact by fact; re-attributed only with* `--include-ambiguous` and the hash of that preview.* - excluded: an evidenced or ambiguous row whose claim and entity also have* an active user-attributed row from a session that is not suspect (the@@ -61,7 +61,7 @@ import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saimport { corpusFileSessionId, corpusSpoolDir, parseWbFileName, speakerFileName } from '../context/corpus-segments.ts';import { readSessionSource } from '../context/corpus-source.ts';import { parseCorpusTurns } from '../context/corpus-turns.ts';-import { DETECTED_PRINCIPAL, readSpeakerSidecar, speakerContextNote } from '../context/session-speaker.ts';+import { DETECTED_PRINCIPAL, readSpeakerSidecar, speakerContextNote, type SpeakerSidecar } from '../context/session-speaker.ts';import { stripPastedContent } from '../transcripts/pasted-content.ts';import { wholeBodySnapshot } from '../persistence/segmented-apply.ts';import { shellQuote } from '../shell-quote.ts';@@ -205,21 +205,28 @@ function corpusIndex(corpusDir: string | null): CorpusIndex {if (key === 'unread') { index.unreadSessions.add(session); continue; }if (!key) continue;index.openings.set(session, key);+ if (sessionSidecar(corpusDir, paths, session)) continue;index.openingSessions.set(key, (index.openingSessions.get(key) ?? new Set<string>()).add(session));}return index;}+/** A session's speaker sidecar, read in the corpus root, the spool dir and beside each of its corpus files. */+function sessionSidecar(corpusDir: string, paths: string[], session: string): { dir: string; sidecar: SpeakerSidecar } | null {+ for (const dir of new Set([corpusDir, corpusSpoolDir(corpusDir), ...paths.map(path => dirname(path))])) {+ const sidecar = readSpeakerSidecar(dir, session);+ if (sidecar) return { dir, sidecar };+ }+ return null;+}+function sessionVerdict(session: string, index: CorpusIndex, opts: AgentSessionOptions, cwdPrefixes: string[]): Verdict {const fallbackPrincipal = opts.principal ?? DETECTED_PRINCIPAL;const corpusDir = index.corpusDir;- const dirs = corpusDir ? [...new Set([corpusDir, corpusSpoolDir(corpusDir), ...(index.files.get(session) ?? []).map(path => dirname(path))])] : [];- for (const dir of dirs) {- const sidecar = readSpeakerSidecar(dir, session);- if (sidecar) {- return { klass: 'evidenced', reason: 'speaker_sidecar', principal: sidecar.principal,- evidence: `${relative(corpusDir!, join(dir, speakerFileName(session)))} (principal ${sidecar.principal})` };- }+ const found = corpusDir ? sessionSidecar(corpusDir, index.files.get(session) ?? [], session) : null;+ if (found) {+ return { klass: 'evidenced', reason: 'speaker_sidecar', principal: found.sidecar.principal,+ evidence: `${relative(corpusDir!, join(found.dir, speakerFileName(session)))} (principal ${found.sidecar.principal})` };}if (opts.sessions?.includes(session)) return { klass: 'evidenced', reason: 'operator_session', principal: fallbackPrincipal, evidence: `--session ${session}` };const record = corpusDir ? readSessionSource(corpusSpoolDir(corpusDir), session) : null;@@ -229,7 +236,8 @@ function sessionVerdict(session: string, index: CorpusIndex, opts: AgentSessionOif (prefix) return { klass: 'evidenced', reason: 'operator_cwd', principal: fallbackPrincipal, evidence: `cwd ${record.cwd} under --cwd ${prefix}` };}const key = index.openings.get(session);- const others = key ? index.openingSessions.get(key)!.size - 1 : 0;+ const group = key ? index.openingSessions.get(key) : undefined;+ const others = group ? group.size - (group.has(session) ? 1 : 0) : 0;if (others >= OPENING_MIN_OTHERS) {return { klass: 'ambiguous', reason: 'repeated_opening', principal: fallbackPrincipal, evidence: `first user turn shared with ${others} other session(s)` };}diff --git a/src/core/transcripts/claude-code.ts b/src/core/transcripts/claude-code.tsindex 54b1d4f896..d5f03f9588 100644--- a/src/core/transcripts/claude-code.ts+++ b/src/core/transcripts/claude-code.ts@@ -95,6 +95,11 @@ export function isClaudeCodeRemoteControlStateFile(path: string): boolean {return base.endsWith(CCR_TIP_SUFFIX) || base === CCR_BRIDGE_POINTER;}+/** True for Claude Code's per-project session index (`sessions-index.json`), which lists sessions and holds no turns. */+export function isClaudeCodeSessionsIndexFile(path: string): boolean {+ return (path.split(/[/\\]/).pop() ?? '') === 'sessions-index.json';+}+/** Keys that mark a Claude Code project transcript. */function looksLikeClaudeLine(obj: Record<string, unknown>): boolean {if (diff --git a/test/ai/gateway-cache-breakpoint.test.ts b/test/ai/gateway-cache-breakpoint.test.tsindex 0a45bb9aa1..46e3de5565 100644--- a/test/ai/gateway-cache-breakpoint.test.ts+++ b/test/ai/gateway-cache-breakpoint.test.ts@@ -37,12 +37,34 @@ import {__setGenerateTextTransportForTests,} from '../../src/core/ai/gateway.ts';import { OPENROUTER_CACHE_HEADER } from '../../src/core/ai/recipes/openrouter.ts';+import { defaultSynthesize } from '../../src/commands/enrich.ts';+import { buildEnrichPrompt } from '../../src/core/enrich/thin.ts';afterAll(() => {resetGateway();__setGenerateTextTransportForTests(null);});+describe('#9541: enrich write-ups ask for no prompt cache', () => {+ test('neither the call nor the system block carries a breakpoint, and the system prompt is below the smallest cacheable prefix', async () => {+ resetGateway();+ let captured: any;+ __setGenerateTextTransportForTests(async (args: any) => {+ captured = args;+ return { content: [{ type: 'text', text: '## Summary\nok' }], finishReason: 'stop', usage: { inputTokens: 1, outputTokens: 1 } } as any;+ });+ configureGateway({ chat_model: 'anthropic:claude-sonnet-4-6', env: { ANTHROPIC_API_KEY: 'fake' } });+ const { system, user } = buildEnrichPrompt({ slug: 'people/alice-example', title: 'Alice Example', kind: 'person', currentBody: '',+ evidence: [{ source_slug: 'meetings/kickoff', text: 'Alice Example leads the launch.' }] });+ // Anthropic caches no prefix under 1024 tokens; at about 4 characters a token this prompt is far below it.+ expect(system.length).toBeLessThan(2048);+ await defaultSynthesize({ system, user, model: 'anthropic:claude-sonnet-4-6' });+ expect(JSON.stringify(captured.messages)).toContain('Alice Example leads the launch.');+ expect(captured.providerOptions?.anthropic?.cacheControl).toBeUndefined();+ expect(captured.system).toBe(system);+ });+});+describe('gbrain#2490 — Anthropic cache breakpoint placement', () => {beforeEach(() => {resetGateway();diff --git a/test/brain-first-turn-rule.test.ts b/test/brain-first-turn-rule.test.tsindex c89a03fd42..f7461a6e74 100644--- a/test/brain-first-turn-rule.test.ts+++ b/test/brain-first-turn-rule.test.ts@@ -98,6 +98,31 @@ describe('per-turn rule: Claude Code and Codex user-prompt hook', () => {});});+describe('per-turn rule: turns no person typed (#9163)', () => {+ async function prompt(text: string, extra: Record<string, string | undefined> = {}): Promise<string> {+ let out = '';+ await withEnv(env(home([{ harness: 'claude-code', status: 'installed' }]), extra), async () => {+ await runHook(['user-prompt'], { stdin: JSON.stringify({ prompt: text, session_id: 's1' }), write: (s) => { out += s; },+ configOverride: null, disablePushBanner: true, disableTelemetry: true });+ });+ return out;+ }+ const NOTIFICATION = '<task-notification>\n<task-id>t1</task-id>\n<status>completed</status>\n</task-notification>';+ const TEAMMATE = '<teammate-message teammate_id="lead">rebase on main</teammate-message>';++ test('a task notification or teammate message gets no rule; a typed turn keeps it', async () => {+ expect(await prompt(NOTIFICATION)).toBe('');+ expect(await prompt(TEAMMATE)).toBe('');+ expect(await prompt('what did alice-example decide about the launch?')).toContain('check GBrain first');+ });++ test('the turn-rule lane skips them too', async () => {+ const lane = { GBRAIN_HOOK_LANE: 'turn-rule' };+ expect(await prompt(NOTIFICATION, lane)).toBe('');+ expect(await prompt('what did alice-example decide about the launch?', lane)).toContain('check GBrain first');+ });+});+describe('per-turn rule names the tools where tool_search hides them', () => {test('OpenClaw: names the gbrain tools and the tool_search / tool_call route; Hermes: names mcp__<server>__<tool>', () => {const starter = { kind: 'mcp', server: 'gbrain', surface: 'starter' } as const;diff --git a/test/commit-ledger.test.ts b/test/commit-ledger.test.tsindex 502cd17090..4e741b50b3 100644--- a/test/commit-ledger.test.ts+++ b/test/commit-ledger.test.ts@@ -6,7 +6,7 @@ import { execFileSync } from 'node:child_process';import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { LEDGER_ROTATE_BYTES, ledgerFiles, messageDigest, readLedger, recordCommit, recordIntent } from '../src/core/git/commit-ledger.ts';+import { LEDGER_ROTATE_BYTES, ledgerFiles, ledgerLocation, messageDigest, readLedger, recordCommit, recordIntent } from '../src/core/git/commit-ledger.ts';import { commitPathsLocked } from '../src/core/git/commit-push.ts';const dir = mkdtempSync(join(tmpdir(), 'gbrain-commit-ledger-'));@@ -92,6 +92,14 @@ test('commit-push records an intent with head_before and the message digest, theexpect(records.find(r => r.e === 'commit')).toMatchObject({ writer: 'commit_push', sha });});+test('#8870: a failed location lookup is not remembered; the directory is found once it becomes a repository', () => {+ const root = join(dir, `not-yet-${n++}`);+ mkdirSync(root);+ expect(ledgerLocation(root)).toBeNull();+ git(root, ['init', '-q', '-b', 'main']);+ expect(ledgerLocation(root)).toMatchObject({ gitDir: join(root, '.git'), common: join(root, '.git'), worktree: root });+});+test('messageDigest applies git whitespace cleanup', () => {expect(messageDigest('subject \n\n\n\nbody\n\n')).toBe(messageDigest('subject\n\nbody'));expect(messageDigest('a')).not.toBe(messageDigest('b'));diff --git a/test/doctor-autopilot-install-pending-6755.test.ts b/test/doctor-autopilot-install-pending-6755.test.tsindex 68ae5aadd3..18eb600b75 100644--- a/test/doctor-autopilot-install-pending-6755.test.ts+++ b/test/doctor-autopilot-install-pending-6755.test.ts@@ -55,11 +55,12 @@ describe('skipped Phase F: doctor line to verified clear', () => {const bin = join(home, 'bin');mkdirSync(bin);writeFileSync(join(bin, 'gbrain'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });- await withEnv({ HOME: userHome, GBRAIN_HOME: home, RENDER: '1', GBRAIN_NON_INTERACTIVE: '1', PATH: `${bin}:${process.env.PATH}` }, async () => {+ // An explicit target: RENDER=1 selects the start-script installer only off macOS, where it would load a real LaunchAgent (#9545).+ await withEnv({ HOME: userHome, GBRAIN_HOME: home, GBRAIN_NON_INTERACTIVE: '1', PATH: `${bin}:${process.env.PATH}` }, async () => {const log = console.log;console.log = () => {};try {- await runAutopilot({ kind: 'postgres', getConfig: async () => null, executeRaw: async () => [] } as never, [...argv, '--no-inject']);+ await runAutopilot({ kind: 'postgres', getConfig: async () => null, executeRaw: async () => [] } as never, [...argv, '--target', 'ephemeral-container', '--no-inject']);} finally { console.log = log; }});diff --git a/test/doctor-only-engine-checks.test.ts b/test/doctor-only-engine-checks.test.tsindex ba17b1a6dd..89e3c91062 100644--- a/test/doctor-only-engine-checks.test.ts+++ b/test/doctor-only-engine-checks.test.ts@@ -43,6 +43,11 @@ describe('doctor --only engine need (#6303)', () => {expect(onlyNeedsEngine(new Set(['pglite_data_dir', 'supervisor', 'harness_wiring']))).toBe(false);});+ test('#9513: --only memory_writeback connects the engine; the relay check beside it stays engine-free', () => {+ expect(onlyNeedsEngine(new Set(['memory_writeback']))).toBe(true);+ expect(onlyNeedsEngine(new Set(['memorable_relay_health']))).toBe(false);+ });+test('declared engine checks are names the entry emits', () => {for (const entry of DOCTOR_CHECK_REGISTRY) {for (const name of entry.engineChecks ?? []) expect(`${entry.name}:${entry.emits.includes(name)}`).toBe(`${entry.name}:true`);diff --git a/test/integrations.test.ts b/test/integrations.test.tsindex af896f89b8..f2f88b2b1c 100644--- a/test/integrations.test.ts+++ b/test/integrations.test.ts@@ -1,5 +1,5 @@import { describe, test, expect, beforeAll, beforeEach, afterEach } from 'bun:test';-import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, readFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { resolve, sep } from 'node:path';@@ -20,6 +20,17 @@ const RECIPES_DIR = resolve(import.meta.dir, '..', 'recipes');// --- parseRecipe tests ---+describe('retrieval-reflex recipe health check (#9228)', () => {+ test('runs only its own doctor check, a name doctor --only can select', async () => {+ const recipe = parseRecipe(readFileSync(join(RECIPES_DIR, 'retrieval-reflex.md'), 'utf8'), 'retrieval-reflex.md')!;+ expect(recipe.frontmatter.health_checks).toEqual([+ expect.objectContaining({ type: 'command', argv: ['gbrain', 'doctor', '--only', 'retrieval_reflex_health', '--json'] }),+ ]);+ const { DOCTOR_CHECK_REGISTRY } = await import('../src/commands/doctor/registry.ts');+ expect(DOCTOR_CHECK_REGISTRY.some((entry) => entry.emits.includes('retrieval_reflex_health'))).toBe(true);+ });+});+describe('parseRecipe', () => {test('parses valid recipe with full frontmatter', () => {const content = `---diff --git a/test/persistence-facts-backstop.test.ts b/test/persistence-facts-backstop.test.tsindex 40bfaa4283..4e54bba4df 100644--- a/test/persistence-facts-backstop.test.ts+++ b/test/persistence-facts-backstop.test.ts@@ -236,6 +236,20 @@ test('#6071: an extraction that did not complete does not count as extracted', (expect(await rewrite(retitled('Renamed after a failed extraction'))).toEqual({ status: { queued: true }, effectQueued: true });}));+test.each(['superseded', 'page_missing', 'extraction_disabled'])('#9248: a completed facts-absorb job whose result is skipped %s does not count as extracted', (reason) => fixture(async () => {+ await publish();+ await finishExtractions();+ await engine.executeRaw("UPDATE minion_jobs SET result = jsonb_build_object('skipped', $1::text) WHERE name = 'facts-absorb'", [reason]);+ expect(await rewrite(retitled('Renamed after a skipped extraction'))).toEqual({ status: { queued: true }, effectQueued: true });+}));++test('#9248 control: a completed facts-absorb job with an extraction result still counts as extracted', () => fixture(async () => {+ await publish();+ await finishExtractions();+ await engine.executeRaw(`UPDATE minion_jobs SET result = '{"mode":"inline","inserted":2,"duplicate":0,"superseded":0,"fact_ids":[1,2]}'::jsonb WHERE name = 'facts-absorb'`);+ expect(await rewrite(retitled('Renamed after a real extraction'))).toEqual({ status: { skipped: 'body_unchanged' }, effectQueued: false });+}));+test('a slug-bound writer\'s backstop refusal says the page was written and who widens the grant', async () => {const row = { slug: 'notes/a', authority: { slugPrefixes: ['notes/'] } } as unknown as WriteRequest;await expect(authorizeFactsBackstop(engine, row)).rejects.toMatchObject({ code: 'permission_denied',diff --git a/test/repair-agent-session-facts.test.ts b/test/repair-agent-session-facts.test.tsindex 36e34a6ef7..fb81e1e2c4 100644--- a/test/repair-agent-session-facts.test.ts+++ b/test/repair-agent-session-facts.test.ts@@ -22,6 +22,8 @@ import { runRepairCommand } from '../src/commands/repair.ts';import { agentSessionFactsCheck } from '../src/commands/doctor/checks/agent-session-facts.ts';import { runWaveChecks } from '../src/commands/doctor/wave-checks.ts';import { writeSpeakerSidecar, speakerContextNote } from '../src/core/context/session-speaker.ts';+import { speakerFileName } from '../src/core/context/corpus-segments.ts';+import { classifyAgentSessionFacts } from '../src/core/repair/agent-session-facts.ts';import { withCoordinatedWrite } from '../src/core/persistence/context.ts';import { writeSingleFact } from '../src/core/facts/write-single.ts';import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';@@ -183,6 +185,40 @@ describe('gbrain repair agent-session-facts, unmanaged repo-less brain', () => {expect(listed[template]).toBe('ambiguous');}, 120_000);+ test('#9521: sessions with a speaker sidecar that replay an owner opening do not make the owner session repeated_opening', async () => {+ const opening = 'Walk me through why the quarterly export job got slower this week, step by step.';+ const write = (id: string) => writeFileSync(join(corpus, `${id}.txt`), `[user]\n${opening}\n\n[assistant]\nSure.`);+ write('sess-original');+ for (const n of [1, 2, 3, 4]) {+ write(`sess-replay${n}`);+ writeSpeakerSidecar(corpus, `sess-replay${n}`, { principal: 'agent-launched', source: 'detected' }, 'claude');+ }+ const ownerFact = await insert('Prefers short export logs', 'sess-original');+ const replayFact = await insert('Prefers verbose export logs', 'sess-replay1');+ const template = await insert('Prefers tidy branches', 'sess-t1');+ const listed = classes(await repair(engine, []));+ expect(listed[ownerFact]).toBeUndefined();+ expect(listed[replayFact]).toBe('evidenced');+ expect(listed[template]).toBe('ambiguous');+ }, 120_000);++ test('#9521: a speaker sidecar removed between pages of one run leaves its session classified instead of throwing', async () => {+ const opening = 'Walk me through why the nightly import job got slower this week, step by step.';+ const write = (id: string) => writeFileSync(join(corpus, `${id}.txt`), `[user]\n${opening}\n\n[assistant]\nSure.`);+ for (const n of [1, 2, 3]) {+ write(`sess-replay${n}`);+ writeSpeakerSidecar(corpus, `sess-replay${n}`, { principal: 'agent-launched', source: 'detected' }, 'claude');+ }+ const replayFact = await insert('Prefers verbose import logs', 'sess-replay1');+ const indexes = new Map();+ const first = await classifyAgentSessionFacts(engine, ['default'], { corpusDir: corpus, ids: [replayFact], indexes });+ expect(first.candidates.map(c => c.class)).toEqual(['evidenced']);+ rmSync(join(corpus, speakerFileName('sess-replay1')));+ const second = await classifyAgentSessionFacts(engine, ['default'], { corpusDir: corpus, ids: [replayFact], indexes });+ expect(second.candidates).toEqual([]);+ expect(second.not_suspect).toBe(1);+ }, 120_000);+test('apply re-attributes, adds the note, retires only all-agent takes, deletes nothing; ambiguous needs --include-ambiguous', async () => {await engine.putPage(ALICE, { type: 'person', title: 'Alice Example', compiled_truth: '# Alice Example' }, { sourceId: 'default' });const a = await insert('Prefers terse status updates', 'sess-sidecar');diff --git a/test/sync-parallel-sources-8951.test.ts b/test/sync-parallel-sources-8951.test.tsnew file mode 100644index 0000000000..b4e9fb5cc1--- /dev/null+++ b/test/sync-parallel-sources-8951.test.ts@@ -0,0 +1,19 @@+/**+ * #8951: `sync --all --parallel N` is documented as the number of sources run at once, but only --max-sources+ * reached the dispatcher. --parallel now caps sources too; --max-sources wins when both are given.+ */+import { describe, expect, test } from 'bun:test';+import { parseSyncFanoutFlags } from '../src/commands/sync/args.ts';++describe('sync --all source cap (#8951)', () => {+ test('--parallel N caps the sources run at once', () => {+ expect(parseSyncFanoutFlags(['--all', '--parallel', '2'], true).maxSources).toBe(2);+ });+ test('--max-sources wins over --parallel, in either order', () => {+ expect(parseSyncFanoutFlags(['--all', '--parallel', '2', '--max-sources', '3'], true).maxSources).toBe(3);+ expect(parseSyncFanoutFlags(['--all', '--max-sources', '3', '--parallel', '5'], true).maxSources).toBe(3);+ });+ test('neither flag leaves the cap to the dispatcher default', () => {+ expect(parseSyncFanoutFlags(['--all'], true).maxSources).toBeUndefined();+ });+});diff --git a/test/transcripts-expand-paths.test.ts b/test/transcripts-expand-paths.test.tsindex 639881aac1..428abde107 100644--- a/test/transcripts-expand-paths.test.ts+++ b/test/transcripts-expand-paths.test.ts@@ -142,6 +142,21 @@ describe('expandPaths Claude Code Remote Control state files (#5597)', () => {});});+describe('expandPaths Claude Code sessions-index.json (#9115)', () => {+ test('directory expansion drops the per-project sessions index and keeps the session; a near-miss name stays', async () => {+ const d = tdir();+ const proj = join(d, '.claude', 'projects', 'proj-slug');+ mkdirSync(proj, { recursive: true });+ const session = join(proj, '18c0ffee-1234-4321-9999-abcdefabcdef.jsonl');+ writeFileSync(session, JSON.stringify({ sessionId: 's1', type: 'user', message: { role: 'user', content: 'hi' } }) + '\n');+ writeFileSync(join(proj, 'sessions-index.json'), '{"version":1,"entries":[]}');+ const nearMiss = join(proj, 'my-sessions-index.json');+ writeFileSync(nearMiss, '[]');+ expect((await expandPaths([proj])).sort()).toEqual([session, nearMiss].sort());+ expect(await expandPaths([join(proj, 'sessions-index.json')])).toEqual([]);+ });+});+describe('expandPaths tilde expansion', () => {test('expandTilde: bare ~ and ~/x resolve to the home dir; a mid-string ~ is untouched', () => {expect(expandTilde('~')).toBe(homedir());