Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(hooks): let a not-yet-written transcript reach the prompt-only path (#5465, #5724)
garrytanc1105c89d2c3
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 6cb9e2c8e8..f2d9b874bc 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -171,7 +171,7 @@ test/frontmatter-install-hook.test.ts frontmatter install-hook (B13) 22 readFiletest/get-page-federated-scope.test.ts #2555 get_chunks federated scope 5 source-surface-helpertest/get-page-federated-scope.test.ts #4275 alias hop scope: archived sources, include_deleted, fuzzy precedence, grant precedence 5 source-surface-helpertest/harness-onboarding.test.ts harness identity and private handoff 5 readFileSync-test/hook-command.serial.test.ts user-prompt 15 source-surface-helper+test/hook-command.serial.test.ts user-prompt 16 source-surface-helpertest/hook-push-spawn-env.test.ts spawnDetachedPush env handoff 2 readFileSynctest/hook-push-spawn-env.test.ts tryExecAsync env handoff 1 readFileSynctest/integrations-install.test.ts installRecipeIntoHostRepo — happy path 6 readFileSyncdiff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 8902fa7620..6c07828585 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -1657,6 +1657,8 @@ async function hookSessionEnd(io: HookIo): Promise<number> {}if (!conf.ok) {degrade(`transcript_${conf.reason}`);+ } else if (conf.absent) {+ degrade('transcript_unreadable');} else if (isClaudeCliSelfTranscriptPath(conf.path) ||(ws !== undefined && isClaudeCliSelfTranscriptPath(ws))diff --git a/src/core/transcripts/claude-code-jsonl.ts b/src/core/transcripts/claude-code-jsonl.tsindex 41c58b125a..6cfe24dc18 100644--- a/src/core/transcripts/claude-code-jsonl.ts+++ b/src/core/transcripts/claude-code-jsonl.ts@@ -28,7 +28,8 @@* ~/.claude/projects, `.jsonl` extension, lstat-rejected symlinks, byte cap.*/-import { closeSync, lstatSync, openSync, readFileSync, readSync, statSync } from 'node:fs';+import { closeSync, existsSync, lstatSync, openSync, readFileSync, readSync, statSync } from 'node:fs';+import { dirname } from 'node:path';import { isPathContained } from '../path-confine.ts';import { detectWslMountRoot, translateWindowsPath } from '../wsl-paths.ts';import { stripPastedContent } from './pasted-content.ts';@@ -68,7 +69,7 @@ export const TRANSCRIPT_HARD_CAP_BYTES = 50 * 1024 * 1024;// ── Confinement [S3#8] ──────────────────────────────────────────────────────export type ConfineTranscriptResult =- | { ok: true; path: string; size: number }+ | { ok: true; path: string; size: number; absent?: boolean }| { ok: false; reason: 'missing_path' | 'not_jsonl' | 'unreadable' | 'symlink' | 'not_file' | 'too_large' | 'outside_projects_dir' };/**@@ -77,7 +78,12 @@ export type ConfineTranscriptResult =* lstat'ed so a symlink is SEEN, never followed), regular file, byte cap,* and realpath containment in ~/.claude/projects (`isPathContained` resolves* intermediate symlinked directories, so a planted dir-symlink that escapes- * the tree also fails). Fail-closed on every error.+ * the tree also fails). Fail-closed on every error — with ONE deliberate+ * exception (#5465): an ENOENT leaf whose parent resolves inside the tree+ * validates ok with `absent: true`, because Claude Code writes transcripts+ * asynchronously and a not-yet-created file has nothing to read (the same+ * trust as no transcript_path at all). An absent parent, or any other lstat+ * failure, still fails closed.** Cross-OS install (#4522, Claude Code on the Windows host + gbrain in WSL):* the hook stdin's transcript_path arrives as a Windows drive literal@@ -109,38 +115,50 @@ export function confineTranscriptPath(const mountRoot = opts.wslMountRoot !== undefined ? opts.wslMountRoot : detectWslMountRoot();const translated = mountRoot !== null ? translateWindowsPath(p, mountRoot) : null;const candidate = translated ?? p;- let st: ReturnType<typeof lstatSync>;- try {- st = lstatSync(candidate);- } catch {- return { ok: false, reason: 'unreadable' };- }- if (st.isSymbolicLink()) return { ok: false, reason: 'symlink' };- if (!st.isFile()) return { ok: false, reason: 'not_file' };- // #5701: the size gate belongs to the READER, not the confinement. Every- // hook lane tail-reads a bounded window through parseTranscript (128KB- // writeback probe, 2MB user-prompt, 10MB session end), so refusing a- // legitimate >50MiB session here dropped automatic capture for long-running- // Claude Code sessions while the bounded read would have worked: one- // 12-hour heartbeat window recorded 41 `transcript_too_large` degrades.- // Callers that opt in skip the gate; path, symlink and root confinement- // still apply, and the full-file import path (parseClaudeSessionFile, whose- // cap lives in TRANSCRIPT_JSONL_HARD_CAP) is untouched.- const cap = opts.maxBytes ?? TRANSCRIPT_HARD_CAP_BYTES;- if (!opts.allowOversize && st.size > cap) return { ok: false, reason: 'too_large' };const rootRaw = opts.root ?? claudeProjectsDir();const root = (mountRoot !== null ? translateWindowsPath(rootRaw, mountRoot) : null) ?? rootRaw;- if (!isPathContained(candidate, root)) {+ // Containment against the resolved tree, shared by the existing-file and+ // absent-leaf paths. realpathSync resolves intermediate symlinked segments+ // (the planted dir-symlink escape), so the caller's pinned root — not the+ // path's own shape — decides membership.+ const containedIn = (leaf: string): boolean => {+ if (isPathContained(leaf, root)) return true;// Cross-OS fallback (#4522): only for a path we translated ourselves and// only when the caller didn't pin an explicit root.const derived =mountRoot !== null && translated !== null && opts.root === undefined? deriveTranslatedProjectsRoot(translated, mountRoot): null;- if (derived === null || !isPathContained(candidate, derived)) {- return { ok: false, reason: 'outside_projects_dir' };- }+ return derived !== null && isPathContained(leaf, derived);+ };+ let st: ReturnType<typeof lstatSync>;+ try {+ st = lstatSync(candidate);+ } catch (e) {+ // #5465: Claude Code writes the transcript asynchronously, so on turn 1+ // of a fresh session (or the only turn of `claude -p`) the path can be+ // absent. A CONFINED absent path has nothing to read — the same trust as+ // no transcript_path at all — so it validates with absent:true and the+ // caller's prompt-only path runs instead of aborting the event. An+ // absent path whose parent escapes the tree stays a rejection, and every+ // non-ENOENT lstat failure (EACCES, ENOTDIR, …) stays fail-closed.+ if ((e as NodeJS.ErrnoException).code !== 'ENOENT') return { ok: false, reason: 'unreadable' };+ const parent = dirname(candidate);+ // No directory component (a bare filename — e.g. an untranslated Windows+ // drive literal on a non-WSL host) or an absent parent: containment is+ // unprovable, so fail closed exactly as before.+ if (parent === '.' || !existsSync(parent)) return { ok: false, reason: 'unreadable' };+ if (!containedIn(parent)) return { ok: false, reason: 'outside_projects_dir' };+ return { ok: true, path: candidate, size: 0, absent: true };}+ if (st.isSymbolicLink()) return { ok: false, reason: 'symlink' };+ if (!st.isFile()) return { ok: false, reason: 'not_file' };+ // #5701: the size gate belongs to the READER, not the confinement. Every+ // hook lane tail-reads a bounded window through parseTranscript, so callers+ // that opt in skip the gate; path, symlink and root confinement still apply.+ const cap = opts.maxBytes ?? TRANSCRIPT_HARD_CAP_BYTES;+ if (!opts.allowOversize && st.size > cap) return { ok: false, reason: 'too_large' };+ if (!containedIn(candidate)) return { ok: false, reason: 'outside_projects_dir' };return { ok: true, path: candidate, size: st.size };}diff --git a/test/claude-code-jsonl.test.ts b/test/claude-code-jsonl.test.tsindex 2a0dedce77..832017400d 100644--- a/test/claude-code-jsonl.test.ts+++ b/test/claude-code-jsonl.test.ts@@ -267,9 +267,8 @@ describe('confineTranscriptPath [S3#8]', () => {expect(confineTranscriptPath(link, { root })).toEqual({ ok: false, reason: 'symlink' });});- test('rejects: missing file / non-string / byte cap', () => {+ test('rejects: non-string / byte cap', () => {const root = tdir();- expect(confineTranscriptPath(join(root, 'nope.jsonl'), { root })).toEqual({ ok: false, reason: 'unreadable' });expect(confineTranscriptPath(undefined, { root })).toEqual({ ok: false, reason: 'missing_path' });expect(confineTranscriptPath(42 as unknown as string, { root })).toEqual({ ok: false, reason: 'missing_path' });const big = join(root, 'big.jsonl');@@ -330,6 +329,29 @@ describe('confineTranscriptPath [S3#8]', () => {expect(parsed.bytesRead).toBeLessThanOrEqual(64 * 1024);});+ // #5465: Claude Code writes transcripts asynchronously, so the path can be+ // absent on turn 1 of a fresh session. A CONFINED absent leaf validates ok+ // with absent:true (nothing to read — the same trust as no path at all),+ // which lets the user-prompt hook build its prompt-only context block+ // instead of aborting the event. Every escape class stays rejected.+ test('an absent leaf inside the tree validates absent; escapes still reject', () => {+ const root = tdir();+ const proj = join(root, 'proj-slug');+ mkdirSync(proj, { recursive: true });+ const absent = join(proj, '18c0ffee-1234-4321-9999-abcdefabcdef.jsonl');+ expect(confineTranscriptPath(absent, { root })).toEqual({ ok: true, path: absent, size: 0, absent: true });+ // Absent OUTSIDE the tree: still an escape, not a missing file.+ const outside = tdir();+ expect(confineTranscriptPath(join(outside, 'nope.jsonl'), { root })).toEqual({ ok: false, reason: 'outside_projects_dir' });+ // Absent parent (containment unprovable): fail closed, as before.+ expect(confineTranscriptPath(join(root, 'no-such-dir', 'nope.jsonl'), { root })).toEqual({ ok: false, reason: 'unreadable' });+ // A symlinked parent that escapes the tree is still seen (the parent+ // resolves outside → not contained).+ const escape = join(root, 'escape');+ symlinkSync(outside, escape);+ expect(confineTranscriptPath(join(escape, 'nope.jsonl'), { root })).toEqual({ ok: false, reason: 'outside_projects_dir' });+ });+test('rejects: directory named like a transcript', () => {const root = tdir();const dirAsFile = join(root, 'dir.jsonl');diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.tsindex 9b73768493..5d9f834fe2 100644--- a/test/hook-command.serial.test.ts+++ b/test/hook-command.serial.test.ts@@ -469,6 +469,35 @@ describe('user-prompt', () => {expect((await lastHeartbeat())?.reason).toBe('transcript_outside_projects_dir');});+ // #5465: Claude Code writes transcripts asynchronously, so turn 1 of a+ // fresh session (or the only turn of `claude -p`) can hand the hook a+ // path that does not exist yet. A CONFINED absent path has nothing to+ // read — the same trust as no transcript_path at all — so the event+ // proceeds prompt-only instead of aborting with transcript_unreadable.+ test('#5465: an absent transcript inside the root still delivers prompt-only context', async () => {+ const dataDir = join(tmp, 'data');+ writePgliteConfig(dataDir);+ await startServer({ dataDir, blockText: 'CTX: first-turn context' });+ const projectsRoot = join(tmp, 'projects-root-5465');+ // The project DIRECTORY exists (Claude Code creates it); only the+ // session file is not written yet — the shape the issue observed.+ mkdirSync(join(projectsRoot, 'proj-slug'), { recursive: true });+ const absent = join(projectsRoot, 'proj-slug', 'fresh-session.jsonl');+ const out = collectStdout();+ expect(+ await runHook(['user-prompt'], {+ ...out.io,+ stdin: JSON.stringify({ prompt: 'first turn of a fresh session', transcript_path: absent }),+ transcriptRoot: projectsRoot,+ }),+ ).toBe(0);+ const parsed = JSON.parse(out.get().trim());+ expect(parsed.hookSpecificOutput.additionalContext).toBe('CTX: first-turn context');+ const hb = await lastHeartbeat();+ expect(hb?.outcome).toBe('ok');+ expect(hb?.turns).toBe(1);+ });+test('unauthorized (server holds a different secret) degrades cleanly', async () => {const dataDir = join(tmp, 'data');writePgliteConfig(dataDir);