SLOPSHOPPER

harness

Skills and guard hooks: ai-code-cleanup, interrogate, shape-task, verify-change, setup, a shared-worktree git guard, and a guard against reading API-key config…

commandtoastpromptmodelprocesstimer
v0.4.29MITupdated 2026-10-18Paradox07127/claude-utopia/plugins/harness
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · harness
› fix the failing auth test and add an audit log call ● harness: harness: reflect failed: SyntaxError: JSON Parse error: Unexpected identifier "dev" ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /memory-check ⎿ harness: No memory directory for /work/app ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

claude-utopia

Under active development. This repo is updated continuously, and interfaces, names and defaults can change between versions. Star or watch the repo to follow the changes.

简体中文

Five Claude Code plugins built on mods (function hooks), plus two agent templates.

PluginWhat it does
dashboardA status band above the prompt for running subagents and mmrun reviews, a line under the prompt with context use and the tightest rate-limit window, and a seven-page workbench (Overview / Agents / Reviews / GPU / Timeline / Usage / Progress) opened with /dashboard, /subagents, /mmrun, /gpu, /timeline. The Reviews, GPU and Progress tabs show once they have data: an ~/.claude/mmruns folder, a GPU host, a progress board. The Timeline page draws the main loop's turns as a waterfall of model requests and tool calls, with a hotspot view of the slowest tools and turns. Renders subagent cards, test summaries and blocked-command notices in the transcript.
harnessSkills: ai-code-cleanup, interrogate, shape-task, verify-change, setup. Guards: refuse subagents on blocked models, refuse git commands that discard uncommitted work in the shared main worktree, refuse tool calls that would print API-key config files (~/.claude.json and its backups, Claude settings, Codex config and auth, grok auth, OpenViking config) or an environment dump (env, printenv, export -p, set, …) into the transcript, run /compact when the main thread idles until the prompt cache is about to expire.
mmCross-model code review and delegation: /mm:review runs codex / grok / agy in parallel as read-only reviewers, /mm:run hands a task to another model in its own worktree. Ships the mmrun CLI. A guard refuses reading mmrun's *.raw event streams (except a lone tail of 50 lines or fewer) and moves a foreground mmrun wait to the background.
next-promptPredicts your next message. After each main-thread turn, one fork of the session's own model (reusing its prompt cache, no tools, nothing written to the transcript) writes the message you are likely to send next; it shows as the prompt box's dim suggestion, Tab to take. A reply of NONE shows nothing. /prediction-stats prints how many were taken or near-taken, the characters kept, the abstentions, the median fork time and the cache share. Hides Claude Code's own suggestion in the terminal; in the desktop app set "promptSuggestionEnabled": false. One fork per turn, billed to your session.
progressA per-project progress board. After each turn you typed that changed files or made a commit, the plugin asks Sonnet to record the work as 1–3 nodes (title, summary, status, kind, links to earlier nodes); the main model spends no tokens on it. The board is kept under ~/.claude/progress/ or committed with the project, as you choose once per project. The plugin mirrors the board to an optional Artifact canvas. Works without dashboard; with it, the workbench's Progress page lists the board.
agents/worker and researcher subagent templates to copy into ~/.claude/agents/.

Screenshots

The status band above the prompt while a worker subagent runs, with the transcript cards for the dispatched agent and the test summary. Context use and the rate-limit window show only in the line under the prompt:

Status band and transcript cards in the terminal

The workbench's Timeline page: each model request of the last turn, its tool calls and the critical path.

Workbench Timeline page in the terminal

Both screenshots come from a real terminal session with language set to English. With zh-CN, the same UI is drawn in Chinese; see 简体中文.

Requirements

  • Claude Code 2.1.287 or later (mods are on by default from that version). Drawing works in the terminal and the Desktop Code tab; the VS Code panel and claude -p run the hooks without drawing.
  • harness: python3.
  • mm: at least one of the codex, grok or agy CLIs, plus bash, git, jq, python3. The grok and agy read-only fence uses sandbox-exec, so it is macOS only; codex uses its own sandbox.
  • dashboard GPU page: key-based ssh to the hosts and nvidia-smi (or tegrastats) on them.
  • Optional: /mm:run suggests the /impeccable skill for frontend tasks, and verify-change suggests the codegraph_impact MCP tool. Neither ships here; they are used when installed, and the plugins work without them.

Install

Let Claude do it: paste this into a Claude Code session.

Fetch and follow the instructions in https://raw.githubusercontent.com/Paradox07127/claude-utopia/main/INSTALL.md

Or by hand:

claude plugin marketplace add Paradox07127/claude-utopia
claude plugin install dashboard@claude-utopia
claude plugin install harness@claude-utopia
claude plugin install mm@claude-utopia
claude plugin install next-prompt@claude-utopia
claude plugin install progress@claude-utopia

Then start a new Claude Code session. Run the setup skill (/harness:setup) at any time to review and change the options below.

Options

Set with /plugin configure <plugin>@claude-utopia, or claude plugin configure <plugin>@claude-utopia --values-stdin with a JSON object of strings. Changes take effect in the next session.

PluginKeyDefaultMeaning
dashboardlanguageautoUI language: auto, zh-CN or en. auto follows the settings language, then LC_ALL / LANG, else English.
dashboardgpuHostsemptyComma-separated ssh hosts; ssh <host> … in Bash opens that host's GPU page.
dashboardcacheTtlMinutes60The fallback prompt cache TTL: after this many idle minutes the band warns that the next message rewrites the prompt cache. Used only until the real TTL is known; a TTL read from the transcript or reported by a model switch overrides it.
dashboardtoastPeerAskstrueToast when another Claude Code session asks a permission or its turn fails. Other sessions' toasts show only in the session you typed in last within two minutes, or in every session when you typed in none.
dashboardtoastPeerRepliestrueToast when another session replies after a turn of two minutes or more. Shown by the same rule.
dashboardaskSoundfalsePlay a short chime with the toast of another session asking a permission or failing. Needs toastPeerAsks.
dashboardtoastRunstrueToast when an mmrun model returns, fails or goes stale.
harnesslanguageautoSame as above, for the harness toast.
harnessblockedSubagentModelsemptyComma-separated; a subagent whose model name contains any entry is refused. Empty allows all.
harnesssharedTreeGitGuardtrueIn the main worktree, refuse git commands that discard uncommitted changes or rewrite HEAD: checkout <path>, checkout --force / -f, restore (except --staged alone), stash (except list, show, create), clean (except -n / --dry-run), switch --discard-changes / --force / -f, reset --hard, commit --amend. Linked worktrees are exempt.
harnessidleCompacttrueWhen the main thread sits idle until just before the prompt cache expires, run /compact automatically: with a 1h cache 10 minutes before, at 100k tokens or more; with a 5m cache 1 minute before, at 200k or more. The TTL is read from the transcript.
mmreviewModelscodex,grokModels /mm:review uses when no --models is given.

next-prompt and progress have no options.

Skills, command docs and every instruction the plugins send to the model are in English; skill descriptions also carry Chinese trigger words so Chinese prompts match them. Claude replies in your language. Only the drawn UI follows language.

Privacy and trust

Mods run in-process with your user permissions, like any plugin hook. mm sends the code under review to the external model CLIs you have installed, under their own accounts and terms. Nothing here phones home.

harness hides the built-in general-purpose agent when worker.md or researcher.md exists in ~/.claude/agents/ or the project's .claude/agents/.

License

MIT

Source 15 files
hooks/index.ts 15 lines
1import type { Register } from 'claude-code'
2
3import { register as registerMemory } from './memory-hooks'
4import { register as registerReflect } from './reflect-hooks'
5import { register as registerHarness } from './register'
6import { register as registerRuleCheck } from './rule-check-hooks'
7
8// The source tree's entry, as the engine loads one module per plugin; a release ships each half as a plugin of its own.
9export const register: Register = (on, options) => {
10  registerHarness(on, options)
11  registerMemory(on, options)
12  registerReflect(on, options)
13  registerRuleCheck(on, options)
14}
15
hooks/memory-hooks.ts 73 lines
1import type { EngineInterface, HookFailure, Register } from 'claude-code'
2import { pickLang } from './i18n'
3import type { Lang } from './i18n'
4import { checkMemoryDir, decodeProjectDir, encodePath, formatReport, mainTreeOf, pathsToCheck, strings } from './memory-check'
5import type { MemoryDir, Problem } from './memory-check'
6
7const COMMAND = 'memory-check'
8const INDEX = 'MEMORY.md'
9
10// Lives here, not in i18n.ts: validate only follows $ into functions declared in the same file.
11async function resolveLang($: EngineInterface, option: unknown): Promise<Lang> {
12  const settings = await $.settings.read()
13  return pickLang(option, settings.language, (await $.env.get('LC_ALL')) || (await $.env.get('LANG')))
14}
15
16function logFailure($: EngineInterface, event: string, error: HookFailure): void {
17  $.ui.log(`harness: ${event} hook failed (${error.kind}): ${error.message ?? 'no message'}`, { to: 'debug' })
18}
19
20async function readMemoryDir($: EngineInterface, dir: string): Promise<MemoryDir> {
21  const entries = (await $.fs.list(dir)).filter(entry => entry.kind === 'file' && entry.name.endsWith('.md'))
22  const files = await Promise.all(entries.filter(entry => entry.name !== INDEX).map(async entry => ({ name: entry.name, text: await $.fs.read(`${dir}/${entry.name}`) })))
23  const index = entries.some(entry => entry.name === INDEX) ? await $.fs.read(`${dir}/${INDEX}`) : null
24  return { index, files }
25}
26
27async function checkDir($: EngineInterface, dir: string, root: string | null, home: string): Promise<Problem[]> {
28  const memory = await readMemoryDir($, dir)
29  const paths = pathsToCheck(memory, root, home)
30  const found = await Promise.all(paths.map(path => $.fs.exists(path)))
31  return checkMemoryDir(memory, new Set(paths.filter((_, i) => found[i])), root, home)
32}
33
34/** Reads memory only: the session project's dir, or with `all` every project's. */
35async function memoryCheck($: EngineInterface, args: string, language: unknown): Promise<string> {
36  const lang = await resolveLang($, language)
37  const home = (await $.env.get('HOME')) ?? ''
38  const projects = `${home}/.claude/projects`
39  if (args.trim() === 'all') {
40    const problems: Problem[] = []
41    let count = 0
42    const listDirs = async (dir: string) => (await $.fs.list(dir).catch(() => [])).filter(entry => entry.kind !== 'file').map(entry => entry.name)
43    for (const project of await listDirs(projects)) {
44      const dir = `${projects}/${project}/memory`
45      if (!(await $.fs.exists(dir))) continue
46      count += 1
47      const root = await decodeProjectDir(project, listDirs)
48      problems.push(...(await checkDir($, dir, root, home)).map(p => ({ ...p, file: `${project}/${p.file}` })))
49    }
50    return formatReport(problems, count, lang)
51  }
52  const root = await $.session.root()
53  // A linked worktree shares the main tree's memory.
54  const main = mainTreeOf(await $.fs.read(`${root}/.git`).catch(() => ''))
55  for (const candidate of main === null ? [root] : [root, main]) {
56    const dir = `${projects}/${encodePath(candidate)}/memory`
57    if (await $.fs.exists(dir)) return formatReport(await checkDir($, dir, candidate, home), 1, lang)
58  }
59  return strings[lang].noDir(root)
60}
61
62export const register: Register = (on, options) => {
63  on('session.start', { cwd: /^/ }, async ($, e, next) => {
64    await $.command.register({ name: COMMAND, description: 'List problems in Claude Code memory: broken index links, unlisted files, bad frontmatter, paths gone; `all` for every project' })
65    return next(e)
66  }).catch(($, e, next) => {
67    logFailure($, 'session.start', next.error)
68    return next(e)
69  })
70
71  on('command.run', { command: COMMAND }, async ($, e) => ({ text: await memoryCheck($, e.args, options.language) }))
72}
73
hooks/reflect-hooks.ts 153 lines
1import type { EngineInterface, HookFailure, Register } from 'claude-code'
2import { pickLang } from './i18n'
3import type { Lang } from './i18n'
4
5const COMMAND = 'reflect'
6const SCRIPT = 'hooks/reflect.py'
7const NOTES_DIR = '.notes/reflect'
8// Today counts as the first of the days the script reads.
9const DAYS = 7
10const SCRIPT_TIMEOUT_MS = 120_000
11const MODEL = 'sonnet'
12const MAX_TOKENS = 2000
13const MAX_PROPOSALS = 5
14
15// Sent first and marked for the prompt cache, so it must not vary between calls.
16const INSTRUCTIONS: Record<Lang, string> = {
17  'zh-CN': `你在为一个 Claude Code 插件仓库做每日反思。下面的 JSON 是脚本统计出的近 7 天摩擦候选,每个模式至少出现 2 次:
18kind 是类别(guard.block 守卫拦截;guard.false-positive 被拦后 2 次调用内换写法跑通的疑似误报;subagent.over-turns 超过 80 轮的子 agent;user.correction 用户以"别/不要/不是/我说过/no/don't/stop"开头的纠正;reply.language 违反"用简体中文回复"的回复),key 是规则 id 或 agent 类型,count 是次数,target 是猜的落点,evidence 是证据(会话 id、时间、原文片段)。
19
20用简体中文起草最多 ${MAX_PROPOSALS} 条改进提案,按收益排序。每条严格用这个格式:
21
22## <序号>. <一句话标题>
23- 现象:……
24- 证据:会话 id 前 8 位、时间、原文片段,只引用给出的证据
25- 落点:\`file:line\`;不知道就写"待定"
26- 建议改法:……
27- 置信度:高 / 中 / 低,附一句理由
28
29规则:
30- 只根据证据下结论,不编造文件、行号或次数。
31- 任何会放宽守卫、权限或安全检查的提案,标题末尾加"(需人工)"。
32- 同一根因的候选合成一条。
33- 不写提案以外的开场白或总结。`,
34  en: `You are writing the daily reflection for a Claude Code plugin repository. The JSON below holds friction candidates a script counted over the last 7 days, each pattern seen at least twice:
35kind is the category (guard.block: guard blocks; guard.false-positive: a block followed within 2 calls by a rewritten call that succeeded; subagent.over-turns: subagents past 80 turns; user.correction: user prompts opening with a correction such as "no," "don't" or "stop"; reply.language: replies that broke the reply-language rule), key the rule id or agent type, count how often, target a guessed location, evidence the session id, time and an excerpt.
36
37Draft at most ${MAX_PROPOSALS} improvement proposals in English, most valuable first. Use exactly this format for each:
38
39## <number>. <one-line title>
40- Symptom: ...
41- Evidence: first 8 characters of the session id, time, excerpt; quote only the evidence given
42- Target: \`file:line\`; "unknown" when you do not know
43- Suggested change: ...
44- Confidence: high / medium / low, with one sentence why
45
46Rules:
47- Conclude only from the evidence; never invent files, line numbers or counts.
48- End the title of any proposal that would loosen a guard, a permission or a safety check with "(needs human review)".
49- Merge candidates with one root cause into one proposal.
50- Write nothing besides the proposals.`,
51}
52
53const zh = {
54  heading: (day: string) => `# 反思 ${day}`,
55  toast: (count: number, path: string) => `反思:${count} 条提案 · ${path}`,
56  wrote: (count: number, path: string) => `反思:${count} 条提案,写在 ${path}`,
57  none: `反思:近 ${DAYS} 天没有出现 2 次以上的摩擦,没写提案`,
58  failed: '反思失败,原因见 debug 日志',
59}
60
61const en: typeof zh = {
62  heading: (day: string) => `# Reflection ${day}`,
63  toast: (count: number, path: string) => `Reflection: ${count} proposals · ${path}`,
64  wrote: (count: number, path: string) => `Reflection: ${count} proposals, written to ${path}`,
65  none: `Reflection: no friction seen twice in the last ${DAYS} days, so no proposals`,
66  failed: 'Reflection failed; see the debug log',
67}
68
69const strings: Record<Lang, typeof zh> = { 'zh-CN': zh, en }
70
71// Lives here, not in i18n.ts: validate only follows $ into functions declared in the same file.
72async function resolveLang($: EngineInterface, option: unknown): Promise<Lang> {
73  const settings = await $.settings.read()
74  return pickLang(option, settings.language, (await $.env.get('LC_ALL')) || (await $.env.get('LANG')))
75}
76
77function logFailure($: EngineInterface, event: string, error: HookFailure): void {
78  $.ui.log(`harness: ${event} hook failed (${error.kind}): ${error.message ?? 'no message'}`, { to: 'debug' })
79}
80
81const pad2 = (n: number) => String(n).padStart(2, '0')
82
83/** The local day `back` days before `at`'s, as YYYY-MM-DD. */
84function dayOf(at: number, back = 0): string {
85  const now = new Date(at)
86  const date = new Date(now.getFullYear(), now.getMonth(), now.getDate() - back, 12)
87  return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`
88}
89
90/** The event ledger's project key: the main worktree's root with / as -, so a linked worktree's session shares it. */
91async function projectKey($: EngineInterface): Promise<string> {
92  const root = (await $.session.repo().catch(() => null))?.root ?? (await $.session.root())
93  return root.replace(/\//g, '-')
94}
95
96/** Runs reflect.py; with candidates, drafts proposals once, writes them under the session root and toasts. `path` null: none. */
97async function reflect($: EngineInterface, language: unknown): Promise<{ count: number; path: string | null }> {
98  const now = await $.clock.now()
99  // Taken before the slow steps, so a /cd meanwhile does not move the note to another repo.
100  const root = await $.session.root()
101  // `--project=` keeps argparse from reading a key that starts with - as an option.
102  // root may be the plugin's directory or its .claude-plugin directory.
103  const script = (await $.fs.exists(`${$.plugin.root}/${SCRIPT}`)) ? `${$.plugin.root}/${SCRIPT}` : `${$.plugin.root}/../${SCRIPT}`
104  const argv = ['python3', script,`--project=${await projectKey($)}`, '--since', dayOf(now, DAYS - 1), '--json']
105  const run = await $.process.run(argv, { timeoutMs: SCRIPT_TIMEOUT_MS })
106  if (run.exitCode !== 0) throw new Error(`reflect.py exited ${run.exitCode}: ${run.stderr.slice(0, 300)}`)
107  const { candidates } = JSON.parse(run.stdout) as { candidates?: unknown }
108  if (!Array.isArray(candidates) || candidates.length === 0) {
109    $.ui.log('harness: reflect found no candidates', { to: 'debug' })
110    return { count: 0, path: null }
111  }
112  const lang = await resolveLang($, language)
113  const reply = await $.model.complete({ model: MODEL, maxTokens: MAX_TOKENS, prompt: [{ text: INSTRUCTIONS[lang], cache: true }, { text: JSON.stringify(candidates) }] })
114  if (!reply.isAnswered) throw new Error(`reflect draft not answered: ${reply.reason}`)
115  const count = Math.min(MAX_PROPOSALS, reply.text.match(/^## /gm)?.length ?? 0)
116  const path = `${NOTES_DIR}/${dayOf(now)}.md`
117  await $.fs.write(`${root}/${path}`, `${strings[lang].heading(dayOf(now))}\n\n${reply.text.trim()}\n`)
118  $.ui.toast(strings[lang].toast(count, path))
119  return { count, path }
120}
121
122/** reflect once per local day per project: the first session to start claims the day. */
123async function reflectDaily($: EngineInterface, language: unknown): Promise<void> {
124  const parent = `${(await $.env.get('HOME')) ?? ''}/.claude/harness/reflect/${await projectKey($)}`
125  await $.process.run(['mkdir', '-p', parent])
126  // mkdir without -p fails on an existing directory, so of sessions starting together exactly one claims the day.
127  if ((await $.process.run(['mkdir', `${parent}/${dayOf(await $.clock.now())}`])).exitCode !== 0) return
128  await reflect($, language)
129}
130
131export const register: Register = (on, options) => {
132  // The script and the draft outlast a hook's budget, so the daily run goes on a timer.
133  on('session.start', { cwd: /^/ }, async ($, e, next) => {
134    await $.command.register({ name: COMMAND, description: 'Count the last 7 days of friction (guard blocks, likely false positives, long subagents, corrections, reply language) and draft proposals into .notes/reflect/' })
135    $.clock.after(0, () => void reflectDaily($, options.language).catch(error => $.ui.log(`harness: reflect failed: ${String(error)}`, { to: 'debug' })))
136    return next(e)
137  }).catch(($, e, next) => {
138    logFailure($, 'session.start', next.error)
139    return next(e)
140  })
141
142  on('command.run', { command: COMMAND }, async $ => {
143    const t = strings[await resolveLang($, options.language)]
144    try {
145      const { count, path } = await reflect($, options.language)
146      return { text: path === null ? t.none : t.wrote(count, path) }
147    } catch (error) {
148      $.ui.log(`harness: reflect failed: ${String(error)}`, { to: 'debug' })
149      return { text: t.failed }
150    }
151  })
152}
153
hooks/register.tsx 256 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, HookFailure, Register, Timer } from 'claude-code'
3import type { HarnessIdle } from '../types'
4import { register as registerGuards } from './guards'
5import { pickLang, strings } from './i18n'
6import type { Lang } from './i18n'
7
8const AGENT_DEFS = ['worker.md', 'researcher.md']
9
10const MINUTE_MS = 60_000
11const CACHE_TTL_MS = { '5m': 5 * MINUTE_MS, '1h': 60 * MINUTE_MS } as const
12// leadMs: the compaction request itself reads the cached prefix, so it has to land this long before the cache expires.
13// minTokens: below it a compaction saves little on the next request yet loses the conversation's detail.
14const COMPACT_RULE = {
15  '1h': { leadMs: 10 * MINUTE_MS, minTokens: 100_000 },
16  '5m': { leadMs: MINUTE_MS, minTokens: 200_000 },
17} as const
18// The last main-thread reply sits within this tail; $.fs.read refuses files over 4 MiB and transcripts grow past that.
19const TRANSCRIPT_TAIL_BYTES = 256 * 1024
20const TAIL_TIMEOUT_MS = 5_000
21// Sits in the prompt: any change to it spends the prompt cache.
22const ASK_GUIDANCE =
23  'Ask only what blocks you. Prefer one question per dialog, at most two. Give 2–3 distinct options, each with a one-line consequence, and mark one "(Recommended)" with its reason. Say which default you will assume for anything you do not ask. For an open-ended question, ask in plain prose instead of options.'
24
25type CacheTtl = keyof typeof CACHE_TTL_MS
26type TranscriptLine = {
27  type?: string
28  isSidechain?: boolean
29  message?: { usage?: { cache_creation?: { ephemeral_1h_input_tokens?: number; ephemeral_5m_input_tokens?: number } } }
30}
31
32const idle = atom({ plugin: 'harness', key: 'idle' } as const, { lastReplyAt: null, lastStepAt: null, ttl: null } as HarnessIdle)
33
34// Module timers die with the module on reload; session.start fires again then and re-arms it from $.state.
35let idleTimer: Timer | null = null
36
37// Lives here, not in i18n.ts: validate only follows $ into functions declared in the same file.
38async function resolveLang($: EngineInterface, option: unknown): Promise<Lang> {
39  const settings = await $.settings.read()
40  return pickLang(option, settings.language, (await $.env.get('LC_ALL')) || (await $.env.get('LANG')))
41}
42
43function logFailure($: EngineInterface, event: string, error: HookFailure): void {
44  $.ui.log(`harness: ${event} hook failed (${error.kind}): ${error.message ?? 'no message'}`, { to: 'debug' })
45}
46
47/** The rule for the stored TTL; state saved before the field existed lacks it, and unknown means 1h. */
48async function compactRule($: EngineInterface): Promise<{ ttlMs: number; leadMs: number; minTokens: number }> {
49  const ttl = (await read($, idle)).ttl ?? '1h'
50  return { ttlMs: CACHE_TTL_MS[ttl], ...COMPACT_RULE[ttl] }
51}
52
53/** The cache TTL of the last main-thread reply that wrote the cache, or null when the tail holds none. */
54function transcriptTtl(tail: string): CacheTtl | null {
55  const lines = tail.split('\n')
56  for (let i = lines.length - 1; i >= 0; i -= 1) {
57    let line: TranscriptLine | null
58    try {
59      line = JSON.parse(lines[i] ?? '') as TranscriptLine | null
60    } catch {
61      // The first line of a `tail -c` read is usually cut, the last may still be being written.
62      continue
63    }
64    if (line?.type !== 'assistant' || line.isSidechain === true) continue
65    const written = line.message?.usage?.cache_creation
66    if ((written?.ephemeral_1h_input_tokens ?? 0) > 0) return '1h'
67    if ((written?.ephemeral_5m_input_tokens ?? 0) > 0) return '5m'
68  }
69  return null
70}
71
72/** Compacts a context of at least the TTL's minTokens; a compaction refused mid-turn is not retried. */
73async function compactIdle($: EngineInterface, language: unknown): Promise<void> {
74  idleTimer = null
75  if (((await $.session.usage()).context.tokens ?? 0) < (await compactRule($)).minTokens) return
76  // A headless (SDK, desktop app) session refuses $.session.compact but still runs /compact.
77  const done = await $.session.compact().catch(() => $.command.run({ command: 'compact' }).then(() => ({ skip: undefined })).catch(() => undefined))
78  if (done === undefined || done.skip !== undefined) return
79  await update($, idle, was => ({ ...was, lastReplyAt: null }))
80  $.ui.toast(strings[await resolveLang($, language)].idleCompacted)
81}
82
83/** Sets the one timer for the TTL's leadMs before the cache expires. */
84async function armIdle($: EngineInterface, language: unknown): Promise<void> {
85  idleTimer?.cancel()
86  idleTimer = null
87  const { lastReplyAt } = await read($, idle)
88  if (lastReplyAt === null) return
89  const { ttlMs, leadMs } = await compactRule($)
90  const left = Math.max(0, lastReplyAt + ttlMs - leadMs - (await $.clock.now()))
91  idleTimer = $.clock.after(left, () => void compactIdle($, language))
92}
93
94// The direct-path rules of guard-secret.ts: globs relative to HOME (`*` also crosses `/`), and names matched anywhere.
95const HOME_SECRETS = ['.claude.json', '.claude.json.*', '.claude/backups/*', '.claude/settings.json', '.claude/settings.json.*',
96  '.claude/settings.local.json', '.codex/config.toml', '.codex/config.toml.*', '.codex/auth.json',
97  '.openviking/*', '.grok/auth.json', '.claude/file-history/*', '.codex/shell_snapshots/*']
98const SECRET_NAMES = ['ovcli.conf', 'ov.conf']
99const HOME_SECRET_RES = HOME_SECRETS.map(glob => new RegExp(`^${glob.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`, 'i'))
100
101// Case-insensitive: the default macOS volume is, and a case alias keeps its own spelling in realPath.
102function isSecretPath(path: string, home: string | undefined): boolean {
103  if (SECRET_NAMES.includes(path.slice(path.lastIndexOf('/') + 1).toLowerCase())) return true
104  return home !== undefined && path.toLowerCase().startsWith(`${home.toLowerCase()}/`) && HOME_SECRET_RES.some(re => re.test(path.slice(home.length + 1)))
105}
106
107export const register: Register = (on, options) => {
108  registerGuards(on, options)
109  const blocked = String(options.blockedSubagentModels).split(',').map(name => name.trim()).filter(name => name !== '')
110  on('agent.spawn', ($, e, next) => {
111    const model = e.model?.toLowerCase()
112    const hit = model === undefined ? undefined : blocked.find(name => model.includes(name.toLowerCase()))
113    return hit !== undefined
114      ? { deny: `harness: subagents never use ${hit}. Omit model; the agent definition sets it.` }
115      : next(e)
116  }).catch(($, e, next) => {
117    // It cannot tell whether the model was blocked, so it fails closed: undefined would leave the hook absent and let the spawn through.
118    logFailure($, 'agent.spawn', next.error)
119    return { deny: 'harness: the subagent model check failed, so the spawn is refused. Retry, or omit model and let the agent definition decide.' }
120  })
121
122  // The engine reads an @-mentioned file itself and raises no tool.call, so the PreToolUse guard never sees it.
123  on('prompt.mention', async ($, e, next) => {
124    const home = await $.env.get('HOME')
125    // A stat that rejects falls to the catch below, which denies; a path with no realPath (a dangling link) is denied too.
126    if (home !== undefined) {
127      const [{ realPath }, { realPath: realHome }] = await Promise.all([$.fs.stat(e.path, { resolve: true }), $.fs.stat(home, { resolve: true })])
128      if (realPath !== undefined && ![e.path, realPath].some(path => [home, realHome].some(h => isSecretPath(path, h)))) return next(e)
129    }
130    return { deny: `harness: @${e.mention} holds API keys, and attaching it would save them in the transcript. Ask the user to look at it; to check it, use metadata only (ls, stat, wc).` }
131  }).catch(($, e, next) => {
132    // A failed guard is skipped and the file read, so it fails closed unless the file already passed it.
133    logFailure($, 'prompt.mention', next.error)
134    return next.called ? next(e) : { deny: 'harness: the secret-file check failed, so the mentioned file is not attached. Retry, or ask the user to paste what is needed.' }
135  })
136
137  // Stats per offer instead of caching at session.start: the root moves with /cd and worktree moves.
138  on('agent.offer', { agent: 'general-purpose' }, async ($, e, next) => {
139    const root = await $.session.root().catch(() => undefined)
140    const home = await $.env.get('HOME')
141    const dirs = [root, home].filter(dir => dir !== undefined).map(dir => `${dir}/.claude/agents`)
142    for (const dir of dirs) {
143      for (const name of AGENT_DEFS) {
144        const st = await $.fs.stat(`${dir}/${name}`).catch(() => undefined)
145        if (st?.kind === 'file') return { isOffered: false }
146      }
147    }
148    return next(e)
149  }).catch(($, e, next) => {
150    logFailure($, 'agent.offer', next.error)
151    return next(e)
152  })
153
154  on('tool.describe', { tool: 'AskUserQuestion' }, async ($, e, next) => {
155    const beneath = await next(e)
156    return { ...beneath, description: `${beneath.description}\n\n${ASK_GUIDANCE}` }
157  }).catch(($, e, next) => {
158    logFailure($, 'tool.describe', next.error)
159    return next(e)
160  })
161
162  if (!options.idleCompact) return
163
164  on('session.start', async ($, e, next) => {
165    await armIdle($, options.language)
166    return next(e)
167  }).catch(($, e, next) => {
168    logFailure($, 'session.start', next.error)
169    return next(e)
170  })
171
172  // A request that reads the cache refreshes it, so the cache expires counting from when the last main request was sent.
173  on('turn.step', async function* ($, e, next) {
174    if (e.agentId === undefined) {
175      const lastStepAt = await $.clock.now()
176      await update($, idle, was => ({ ...was, lastStepAt }))
177    }
178    return yield* next(e)
179  }).catch(async function* ($, e, next) {
180    logFailure($, 'turn.step', next.error)
181    return yield* next(e)
182  })
183
184  on('turn.complete', async ($, e, next) => {
185    if (e.agentId === undefined) {
186      const now = await $.clock.now()
187      await update($, idle, was => ({ ...was, lastReplyAt: was.lastStepAt ?? now }))
188      await armIdle($, options.language)
189    }
190    return next(e)
191  }).catch(($, e, next) => {
192    logFailure($, 'turn.complete', next.error)
193    return next(e)
194  })
195
196  on('prompt.submit', async ($, e, next) => {
197    idleTimer?.cancel()
198    idleTimer = null
199    await update($, idle, was => ({ ...was, lastReplyAt: null, lastStepAt: null }))
200    return next(e)
201  }).catch(($, e, next) => {
202    logFailure($, 'prompt.submit', next.error)
203    return next(e)
204  })
205
206  // A /clear, resume or exit ends the conversation the timer was armed for; session.start does not fire for the next one.
207  on('session.end', async ($, e, next) => {
208    idleTimer?.cancel()
209    idleTimer = null
210    await update($, idle, was => ({ ...was, lastReplyAt: null, lastStepAt: null }))
211    return next(e)
212  }).catch(($, e, next) => {
213    logFailure($, 'session.end', next.error)
214    return next(e)
215  })
216
217  // A compaction keeps the conversation (compactIdle already leaves no timer); startup is left to session.start.
218  on('classic.SessionStart', async ($, e, next) => {
219    if (e.agent_id !== undefined || e.source === 'compact' || e.source === 'startup') return next(e)
220    idleTimer?.cancel()
221    idleTimer = null
222    await update($, idle, was => ({ ...was, lastReplyAt: null, lastStepAt: null }))
223    return next(e)
224  }).catch(($, e, next) => {
225    logFailure($, 'classic.SessionStart', next.error)
226    return next(e)
227  })
228
229  on('classic.PostModelSwitch', async ($, e, next) => {
230    if (e.agent_id !== undefined) return next(e)
231    await update($, idle, was => ({ ...was, ttl: e.cache_ttl }))
232    await armIdle($, options.language)
233    return next(e)
234  }).catch(($, e, next) => {
235    logFailure($, 'classic.PostModelSwitch', next.error)
236    return next(e)
237  })
238
239  // The transcript tells the TTL the main thread really gets (5m on an API key or past the plan limit) without a model switch.
240  on('classic.Stop', async ($, e, next) => {
241    if (e.agent_id !== undefined) return next(e)
242    if (e.transcript_path !== '') {
243      const tail = await $.process.run(['tail', '-c', String(TRANSCRIPT_TAIL_BYTES), e.transcript_path], { timeoutMs: TAIL_TIMEOUT_MS })
244      const ttl = tail.exitCode === 0 ? transcriptTtl(tail.stdout) : null
245      if (ttl !== null) {
246        await update($, idle, was => ({ ...was, ttl }))
247        await armIdle($, options.language)
248      }
249    }
250    return next(e)
251  }).catch(($, e, next) => {
252    logFailure($, 'classic.Stop', next.error)
253    return next(e)
254  })
255}
256
hooks/rule-check-hooks.ts 92 lines
1import type { EngineInterface, HookFailure, Register } from 'claude-code'
2import { pickLang } from './i18n'
3import type { Lang } from './i18n'
4import { FRESH, HINT, afterReply, isLanguageViolation } from './rule-check'
5import type { RuleState } from './rule-check'
6
7const STATE_KEY = 'ruleCheck'
8
9// Ledger appends of this load, one at a time: $.fs has no append, so each is a read and a whole write.
10let appending: Promise<unknown> = Promise.resolve()
11
12// Lives here, not in i18n.ts: validate only follows $ into functions declared in the same file.
13async function resolveLang($: EngineInterface, option: unknown): Promise<Lang> {
14  const settings = await $.settings.read()
15  return pickLang(option, settings.language, (await $.env.get('LC_ALL')) || (await $.env.get('LANG')))
16}
17
18function logFailure($: EngineInterface, event: string, error: HookFailure): void {
19  $.ui.log(`harness: ${event} hook failed (${error.kind}): ${error.message ?? 'no message'}`, { to: 'debug' })
20}
21
22async function stateOf($: EngineInterface, session: string): Promise<RuleState> {
23  const stored = await $.store.get(`${STATE_KEY}:${session}`)
24  return typeof stored === 'object' && stored !== null ? { ...FRESH, ...(stored as Partial<RuleState>) } : FRESH
25}
26
27// A session back in the fresh state leaves no key behind.
28async function saveState($: EngineInterface, session: string, state: RuleState): Promise<void> {
29  const isFresh = (Object.keys(FRESH) as (keyof RuleState)[]).every(key => state[key] === FRESH[key])
30  if (isFresh) await $.store.delete(`${STATE_KEY}:${session}`)
31  else await $.store.set(`${STATE_KEY}:${session}`, state)
32}
33
34const pad2 = (n: number) => String(n).padStart(2, '0')
35
36function dayOf(at: number): string {
37  const date = new Date(at)
38  return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`
39}
40
41/** Appends a rule.hint line to this session's .harness.jsonl of the event ledger, the format guards.ts's recordBlock() writes. */
42async function recordHint($: EngineInterface, session: string): Promise<void> {
43  const at = await $.clock.now()
44  // The main worktree's root, so a linked worktree's session shares its project.
45  const root = (await $.session.repo().catch(() => null))?.root ?? (await $.session.root())
46  const path = `${(await $.env.get('HOME')) ?? ''}/.claude/harness/events/${root.replace(/\//g, '-')}/${dayOf(at)}/${session}.harness.jsonl`
47  const line = JSON.stringify({
48    timestamp: new Date(at).toISOString(),
49    event_name: 'rule.hint',
50    severity_text: 'INFO',
51    attributes: { 'session.id': session, 'rule.id': 'reply-language', 'rule.name': 'rule-check' },
52  })
53  const write = appending.then(async () => {
54    // Only a missing file counts as empty: any other read failure throws rather than overwrite the day's lines.
55    const before = (await $.fs.exists(path)) ? String(await $.fs.read(path)) : ''
56    await $.fs.write(path, `${before}${before === '' || before.endsWith('\n') ? '' : '\n'}${line}\n`)
57  })
58  appending = write.catch(() => undefined)
59  await write
60}
61
62export const register: Register = (on, options) => {
63  // A matcher on every hook: in the source tree register.tsx holds the matcher-less one on each of these events, and the engine refuses a second.
64  on('turn.complete', { reason: 'answer' }, async ($, e, next) => {
65    const done = await next(e)
66    if (e.agentId === undefined && (await resolveLang($, options.language)) === 'zh-CN') {
67      const session = await $.session.id()
68      await saveState($, session, afterReply(await stateOf($, session), isLanguageViolation(e.answer)))
69    }
70    return done
71  }).catch(($, e, next) => {
72    logFailure($, 'turn.complete', next.error)
73    return next(e)
74  })
75
76  // The hint rides after the new prompt, where only Claude reads it.
77  on('prompt.submit', { wait: [true, false] }, async ($, e, next) => {
78    // A failure here would skip the plugin's whole prompt.submit chain, prediction logging included, so it only drops the hint.
79    const session = await $.session.id().catch(() => null)
80    const state = session === null ? FRESH : await stateOf($, session).catch(() => FRESH)
81    if (session === null || !state.owed) return next(e)
82    await saveState($, session, { ...state, owed: false })
83    // The language may have left zh-CN since the reply that owed the hint.
84    if ((await resolveLang($, options.language).catch(() => null)) !== 'zh-CN') return next(e)
85    await recordHint($, session).catch(error => $.ui.log(`harness: rule.hint not recorded: ${String(error)}`, { to: 'debug' }))
86    return next({ ...e, context: [...(e.context ?? []), HINT] })
87  }).catch(($, e, next) => {
88    logFailure($, 'prompt.submit', next.error)
89    return next(e)
90  })
91}
92
hooks/i18n.ts 21 lines
1export type Lang = 'zh-CN' | 'en'
2
3const CHINESE = /^zh\b|chinese|中文|汉语|漢語|简体|繁體|mandarin/i
4
5/** `language` userConfig → UI language; `auto` follows settings `language`, then the locale, else English. */
6export function pickLang(option: unknown, settingsLanguage: unknown, locale: string | undefined): Lang {
7  if (option === 'zh-CN' || option === 'en') return option
8  if (typeof settingsLanguage === 'string' && settingsLanguage.trim() !== '') return CHINESE.test(settingsLanguage.trim()) ? 'zh-CN' : 'en'
9  return locale !== undefined && /^zh/i.test(locale) ? 'zh-CN' : 'en'
10}
11
12const zh = {
13  idleCompacted: '空闲将满缓存时效,已自动压缩上下文',
14}
15
16const en: typeof zh = {
17  idleCompacted: 'Idle near cache expiry: context compacted',
18}
19
20export const strings: Record<Lang, typeof zh> = { 'zh-CN': zh, en }
21
hooks/memory-check.ts 176 lines
1import type { Lang } from './i18n'
2
3export type MemoryFile = { name: string; text: string }
4/** One memory dir: MEMORY.md's text (null when absent) and its other .md files. */
5export type MemoryDir = { index: string | null; files: MemoryFile[] }
6
7export type Problem =
8  | { kind: 'dangling'; file: string; target: string }
9  | { kind: 'unlisted'; file: string }
10  | { kind: 'duplicate'; file: string; name: string; other: string }
11  | { kind: 'frontmatter'; file: string; missing: string[] }
12  | { kind: 'path'; file: string; path: string }
13
14const INDEX = 'MEMORY.md'
15const REPORT_LINES = 40
16const GROUPS: Problem['kind'][][] = [['dangling'], ['unlisted'], ['duplicate', 'frontmatter'], ['path']]
17// Split on whitespace and on the punctuation that wraps a path in prose or markdown; a glob or brace list falls apart.
18const WORD = /[^\s`'"()<>[\]{},;|*]+/g
19
20/** How Claude Code names a project's folder under ~/.claude/projects: every other character than a letter or digit becomes `-`. */
21export function encodePath(path: string): string {
22  return path.replace(/[^a-zA-Z0-9]/g, '-')
23}
24
25/** The folder a project dir name stands for: walks down from `/` taking the entries whose encoded name fits; null when none does. */
26export async function decodeProjectDir(encoded: string, list: (dir: string) => Promise<readonly string[]>): Promise<string | null> {
27  const walk = async (dir: string, rest: string): Promise<string | null> => {
28    for (const name of await list(dir)) {
29      const code = encodePath(name)
30      const path = `${dir === '/' ? '' : dir}/${name}`
31      if (rest === code) return path
32      if (rest.startsWith(`${code}-`)) {
33        const found = await walk(path, rest.slice(code.length + 1))
34        if (found !== null) return found
35      }
36    }
37    return null
38  }
39  return encoded.startsWith('-') ? walk('/', encoded.slice(1)) : null
40}
41
42/** The main worktree named by a linked worktree's `.git` file, or null. */
43export function mainTreeOf(gitFile: string): string | null {
44  return /^gitdir:\s*(.+)\/\.git\/worktrees\/[^/\n]+\s*$/m.exec(gitFile)?.[1] ?? null
45}
46
47function splitFrontmatter(text: string): { fields: Map<string, string>; body: string } {
48  const match = /^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text)
49  const fields = new Map<string, string>()
50  if (match === null) return { fields, body: text }
51  for (const [, key, value] of (match[1] ?? '').matchAll(/^([A-Za-z_][\w-]*):[ \t]*(.*)$/gm)) {
52    fields.set(key as string, (value ?? '').trim().replace(/^(["'])(.*)\1$/, '$2').trim())
53  }
54  return { fields, body: text.slice(match[0].length) }
55}
56
57function indexTargets(index: string): string[] {
58  return [...index.matchAll(/\]\(([^)\s]+)\)/g)].map(m => m[1] as string).filter(target => !target.includes('://'))
59}
60
61/** The paths a body names, as written without a `:line` suffix: absolute with two or more parts, `~/…`, or relative with a slash and an extension. */
62function mentionedPaths(body: string): string[] {
63  const found = new Set<string>()
64  // A code span holding an absolute or ~ path is one word, so a folder name may hold spaces.
65  const quoted = [...body.matchAll(/`((?:\/|~\/)[^`\n]*)`/g)].map(m => m[1] as string)
66  const rest = body.replace(/`(?:\/|~\/)[^`\n]*`/g, ' ')
67  for (const word of [...quoted, ...(rest.match(WORD) ?? [])]) {
68    // A URL, or a placeholder path such as `$HOME/x` or `<plugin>/<version>`.
69    if (word.includes('://') || /[$<>]/.test(word)) continue
70    const path = word.replace(/[.,:;!?]+$/, '').replace(/(?::\d+(?:-\d+)?)+$/, '').replace(/#.*$/, '')
71    const isRelative = !/^[/~]/.test(path) && path.includes('/') && /\/[^/]*\w\.[A-Za-z0-9]+$/.test(`/${path}`)
72    if (path.startsWith('~/') || /^\/[^/]+\/./.test(path) || isRelative) found.add(path)
73  }
74  return [...found]
75}
76
77function resolvePath(path: string, root: string | null, home: string): string | null {
78  if (path.startsWith('~/')) return home + path.slice(1)
79  if (path.startsWith('/')) return path
80  return root === null ? null : `${root}/${path.replace(/^\.\//, '')}`
81}
82
83/** Every absolute path the memory bodies name; repo-relative ones only when `root` is known. */
84export function pathsToCheck(dir: MemoryDir, root: string | null, home: string): string[] {
85  const paths = dir.files.flatMap(file => mentionedPaths(splitFrontmatter(file.text).body).map(path => resolvePath(path, root, home)))
86  return [...new Set(paths.filter((path): path is string => path !== null))]
87}
88
89/** The problems of one memory dir; `existing` holds those of `pathsToCheck` that exist. */
90export function checkMemoryDir(dir: MemoryDir, existing: ReadonlySet<string>, root: string | null, home: string): Problem[] {
91  const files = [...dir.files].sort((a, b) => a.name.localeCompare(b.name))
92  const names = new Set(files.map(file => file.name))
93  const targets = indexTargets(dir.index ?? '')
94  const problems: Problem[] = targets.filter(target => !names.has(target)).map(target => ({ kind: 'dangling', file: INDEX, target }))
95  problems.push(...files.filter(file => !targets.includes(file.name)).map(file => ({ kind: 'unlisted' as const, file: file.name })))
96  const firstByName = new Map<string, string>()
97  for (const file of files) {
98    const { fields, body } = splitFrontmatter(file.text)
99    const missing = ['name', 'description'].filter(key => (fields.get(key) ?? '') === '')
100    if (missing.length > 0) problems.push({ kind: 'frontmatter', file: file.name, missing })
101    const name = fields.get('name') ?? ''
102    const other = firstByName.get(name)
103    if (name !== '' && other !== undefined) problems.push({ kind: 'duplicate', file: file.name, name, other })
104    else if (name !== '') firstByName.set(name, file.name)
105    for (const path of mentionedPaths(body)) {
106      const resolved = resolvePath(path, root, home)
107      if (resolved !== null && !existing.has(resolved)) problems.push({ kind: 'path', file: file.name, path })
108    }
109  }
110  return problems
111}
112
113const zh = {
114  headings: {
115    dangling: '索引指向不存在的文件',
116    unlisted: 'MEMORY.md 没有列出的记忆文件',
117    duplicate: 'frontmatter 重名或缺项',
118    path: '提到的路径已不存在',
119  } as Record<string, string>,
120  problem: (p: Problem): string => {
121    switch (p.kind) {
122      case 'dangling': return `指向的 ${p.target} 不存在`
123      case 'unlisted': return '没有列在 MEMORY.md 里'
124      case 'duplicate': return `name「${p.name}」与 ${p.other} 重复`
125      case 'frontmatter': return `frontmatter 缺少 ${p.missing.join('、')}`
126      case 'path': return `${p.path} 不存在`
127    }
128  },
129  more: (n: number) => `… 另有 ${n} 条`,
130  total: (n: number, dirs: number) => `${dirs} 个记忆目录里共 ${n} 个问题`,
131  clean: (dirs: number) => `${dirs} 个记忆目录没有发现问题`,
132  noDir: (root: string) => `${root} 没有记忆目录`,
133}
134
135const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`
136
137const en: typeof zh = {
138  headings: {
139    dangling: 'Index links to missing files',
140    unlisted: 'Memory files MEMORY.md does not list',
141    duplicate: 'Duplicate or missing frontmatter',
142    path: 'Paths that no longer exist',
143  },
144  problem: p => {
145    switch (p.kind) {
146      case 'dangling': return `links ${p.target}, which does not exist`
147      case 'unlisted': return 'not listed in MEMORY.md'
148      case 'duplicate': return `same name "${p.name}" as ${p.other}`
149      case 'frontmatter': return `frontmatter lacks ${p.missing.join(', ')}`
150      case 'path': return `${p.path} does not exist`
151    }
152  },
153  more: n => `… ${n} more`,
154  total: (n, dirs) => `${plural(n, 'problem', 'problems')} in ${plural(dirs, 'memory directory', 'memory directories')}`,
155  clean: dirs => `No problems in ${plural(dirs, 'memory directory', 'memory directories')}`,
156  noDir: root => `No memory directory for ${root}`,
157}
158
159export const strings: Record<Lang, typeof zh> = { 'zh-CN': zh, en }
160
161/** The report grouped by check, cut at 40 lines, then the total; one line when nothing is wrong. */
162export function formatReport(problems: readonly Problem[], dirCount: number, lang: Lang): string {
163  const t = strings[lang]
164  if (problems.length === 0) return t.clean(dirCount)
165  const lines: { text: string; isProblem: boolean }[] = []
166  for (const kinds of GROUPS) {
167    const group = problems.filter(p => kinds.includes(p.kind))
168    if (group.length === 0) continue
169    lines.push({ text: t.headings[kinds[0] as string] as string, isProblem: false })
170    lines.push(...group.map(p => ({ text: `${p.file}: ${t.problem(p)}`, isProblem: true })))
171  }
172  const kept = lines.slice(0, REPORT_LINES)
173  const dropped = lines.slice(REPORT_LINES).filter(line => line.isProblem).length
174  return [...kept.map(line => line.text), ...(dropped > 0 ? [t.more(dropped)] : []), t.total(problems.length, dirCount)].join('\n')
175}
176
hooks/guards.ts 166 lines
1import type { EngineInterface, HookFailure, Register } from 'claude-code'
2
3import { sharedTreeGit } from './guard-git'
4import type { GuardIo } from './guard-io'
5import { secretFiles } from './guard-secret'
6import { basename, dirname } from './posixpath'
7
8// The variables git would otherwise read in place of the repository found from -C.
9const REPO_VARS = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE'] as const
10// A login name sh expands after an unquoted ~; any other ~name names no user and keeps the path.
11const USER_NAME = /^[A-Za-z0-9._][A-Za-z0-9._-]*$/
12const LOG_TIMEOUT_MS = 5_000
13const GIT_TIMEOUT_MS = 2_000
14const SESSION_ID = /^[\p{L}\p{N}_-]+$/u
15
16// Ledger appends of this load, one at a time: $.fs has no append, so each is a read and a whole write.
17let appending: Promise<unknown> = Promise.resolve()
18
19function logFailure($: EngineInterface, event: string, error: HookFailure): void {
20  $.ui.log(`harness: ${event} hook failed (${error.kind}): ${error.message ?? 'no message'}`, { to: 'debug' })
21}
22
23/** The host as the guards read it, for one call: stats and the environment read once. */
24function guardIo($: EngineInterface): GuardIo {
25  const stats = new Map<string, ReturnType<GuardIo['stat']>>()
26  let hostEnv: Promise<Map<string, string>> | undefined
27  let repoVars: Promise<string[]> | undefined
28
29  // $.env.get takes literal names only; any other is read from one `env -0`.
30  const env = async (name: string): Promise<string | undefined> => {
31    if (name === 'HOME') return $.env.get('HOME')
32    if (name === 'GIT_DIR') return $.env.get('GIT_DIR')
33    if (name === 'GIT_WORK_TREE') return $.env.get('GIT_WORK_TREE')
34    hostEnv ??= $.process.run(['env', '-0']).then(
35      got => new Map(got.stdout.split('\0').filter(line => line.includes('=')).map(line => [line.slice(0, line.indexOf('=')), line.slice(line.indexOf('=') + 1)])),
36      () => new Map(),
37    )
38    return (await hostEnv).get(name)
39  }
40
41  return {
42    env,
43    userHome: async name => {
44      if (name !== '' && !USER_NAME.test(name)) return undefined
45      const got = await $.process.run(['/bin/sh', '-c', `printf %s ~${name}`]).catch(() => undefined)
46      return got?.exitCode === 0 && got.stdout.startsWith('/') ? got.stdout : undefined
47    },
48    run: async (argv, init) => {
49      repoVars ??= Promise.all([$.env.get('GIT_DIR'), $.env.get('GIT_WORK_TREE'), $.env.get('GIT_COMMON_DIR'), $.env.get('GIT_INDEX_FILE')]).then(values =>
50        REPO_VARS.filter((_, i) => values[i] !== undefined),
51      )
52      const unset = (await repoVars).filter(name => init.env?.[name] === undefined)
53      const command = unset.length > 0 ? ['env', ...unset.flatMap(name => ['-u', name]), ...argv] : argv
54      return $.process.run(command, { env: init.env, timeoutMs: init.timeoutMs }).catch(() => undefined)
55    },
56    stat: path => {
57      let found = stats.get(path)
58      if (found === undefined) {
59        found = $.fs.stat(path, { resolve: true }).then(
60          got => ({ kind: got.kind, realPath: got.realPath }),
61          () => undefined,
62        )
63        stats.set(path, found)
64      }
65      return found
66    },
67    list: path =>
68      $.fs.list(path).then(
69        entries => entries.map(entry => ({ name: entry.name, kind: entry.kind })),
70        () => undefined,
71      ),
72    now: () => $.clock.now(),
73  }
74}
75
76/** The loop that made the call: null for the main thread or when no loop holds it, else the agent's id. */
77async function agentOf($: EngineInterface, toolUseId: string): Promise<string | null> {
78  const holds = (rows: { toolUses: { tool_use_id: string }[] }[]) => rows.some(row => row.toolUses.some(use => use.tool_use_id === toolUseId))
79  if (holds(await $.session.messages())) return null
80  for (const agent of await $.agent.list()) {
81    const rows = await $.session.messages({ agentId: agent.id })
82    if (Array.isArray(rows) && holds(rows)) return agent.id
83  }
84  return null
85}
86
87/** Appends one line to ~/.claude/harness/guard.jsonl; a log that cannot be written is skipped. */
88async function logDeny($: EngineInterface, guard: string, op: string, cwd: string, agentId: string | null): Promise<void> {
89  const home = await $.env.get('HOME')
90  if (home === undefined) return
91  const line = `${JSON.stringify({ at: await $.clock.now(), guard, decision: 'deny', op, cwd, agent_id: agentId })}\n`
92  await $.process
93    .run(['/bin/sh', '-c', 'mkdir -p "$(dirname "$1")" && cat >> "$1"', 'sh', `${home}/.claude/harness/guard.jsonl`], { stdin: line, timeoutMs: LOG_TIMEOUT_MS })
94    .catch(() => undefined)
95}
96
97const pad2 = (n: number) => String(n).padStart(2, '0')
98
99function dayOf(at: number): string {
100  const date = new Date(at)
101  return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`
102}
103
104/** The main working tree's root, so a linked worktree's session shares its project (as the dashboard's ledgers do); else cwd. */
105async function projectRoot($: EngineInterface, cwd: string): Promise<string> {
106  const got = await $.process.run(['git', '-C', cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir'], { timeoutMs: GIT_TIMEOUT_MS }).catch(() => undefined)
107  const common = got?.stdout.trim() ?? ''
108  return got?.exitCode === 0 && basename(common) === '.git' ? dirname(common) : cwd
109}
110
111/** Appends one guard.block line to the secret guard's file of the event ledger,
112 * ~/.claude/harness/events/<project>/<local day>/<session>.guard.jsonl; rule.name stays that of the Python guard it replaces. */
113async function recordBlock($: EngineInterface, cwd: string, rule: string, tool: string, target: string): Promise<void> {
114  const home = await $.env.get('HOME')
115  if (home === undefined) return
116  const at = await $.clock.now()
117  const id = await $.session.id().catch(() => '')
118  const session = SESSION_ID.test(id) ? id : 'unknown-session'
119  const line = JSON.stringify({
120    timestamp: new Date(at).toISOString(),
121    event_name: 'guard.block',
122    severity_text: 'WARN',
123    attributes: {
124      'session.id': session,
125      'rule.id': rule,
126      'rule.name': 'guard-secret-files',
127      tool,
128      target: Array.from(target.split(/\s+/).filter(word => word !== '').join(' ')).slice(0, 120).join(''),
129      decision: 'deny',
130    },
131  })
132  const path = `${home}/.claude/harness/events/${(await projectRoot($, cwd)).replace(/\//g, '-')}/${dayOf(at)}/${session}.guard.jsonl`
133  const write = appending.then(async () => {
134    // Only a missing file counts as empty: any other read failure throws rather than overwrite the day's lines.
135    const before = (await $.fs.exists(path)) ? String(await $.fs.read(path)) : ''
136    await $.fs.write(path, `${before}${before === '' || before.endsWith('\n') ? '' : '\n'}${line}\n`)
137  })
138  appending = write.catch(() => undefined)
139  await write
140}
141
142export const register: Register = (on, options) => {
143  // The option may arrive as a string as well as a boolean: "false" and "0" turn the guard off.
144  const isGitGuardOn = !['false', '0'].includes(String(options.sharedTreeGitGuard).toLowerCase())
145
146  // classic.PreToolUse, never tool.call: a tool.call hook on Bash breaks isolation: worktree subagents (claude-code#92533).
147  on('classic.PreToolUse', { tool: /^(?:Bash|Read|Edit|Write|Grep)$/ }, async ($, e, next) => {
148    const io = guardIo($)
149    const cwd = await $.session.cwd()
150    // Both guards check every call, so a call both refuse logs two lines and names both reasons.
151    const denials: { guard: string; op: string; reason: string }[] = []
152    const git = e.tool === 'Bash' && isGitGuardOn ? await sharedTreeGit(io, e.command, cwd) : undefined
153    if (git !== undefined) denials.push({ guard: 'shared-tree-git', ...git })
154    const secret = await secretFiles(io, e, cwd)
155    if (secret !== undefined) denials.push({ guard: 'secret-files', ...secret })
156    if (denials.length === 0) return next(e)
157    const agentId = await agentOf($, e.tool_use_id)
158    for (const one of denials) await logDeny($, one.guard, one.op, cwd, agentId)
159    if (secret !== undefined) await recordBlock($, cwd, secret.rule, e.tool, secret.target).catch(() => undefined)
160    return { deny: denials.map(one => one.reason).join('\n') }
161  }).catch(($, e, next) => {
162    logFailure($, 'classic.PreToolUse', next.error)
163    return next(e)
164  })
165}
166
hooks/rule-check.ts 42 lines
1// The reply-language rule, judged by code alone: the same stripping and threshold as reflect.py's is_language_violation.
2
3export const HINT = '上一条回复不是简体中文。按用户的规则用简体中文回复,代码和标识符保持原样。'
4
5const MIN_LETTERS = 40
6const MIN_CJK_SHARE = 0.3
7const MAX_SKIPPED = 16
8const FENCE = /```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)/g
9const INLINE = /`[^`\n]*`/g
10const URL = /\b[A-Za-z][A-Za-z0-9+.-]*:\/\/\S+/g
11const PATH = /\S*\/\S*/g
12const WORD = /[A-Za-z0-9_.]+/g
13// A word holding _, a digit, an inner dot or a lower-to-upper step is an identifier.
14const IDENT = /[_0-9]|[a-z][A-Z]|[A-Za-z0-9]\.[A-Za-z0-9]/
15const CJK = /[㐀-䶿一-鿿豈-﫿]/g
16const LATIN = /[A-Za-z]/g
17
18/** Below 0.3 CJK characters among the letters, over at least 40 letters, once code and identifiers are gone. */
19export function isLanguageViolation(text: string): boolean {
20  const prose = [FENCE, INLINE, URL, PATH].reduce((rest, re) => rest.replace(re, ' '), text).replace(WORD, word => (IDENT.test(word) ? ' ' : word))
21  const cjk = prose.match(CJK)?.length ?? 0
22  const latin = prose.match(LATIN)?.length ?? 0
23  return cjk + latin >= MIN_LETTERS && cjk / (cjk + latin) < MIN_CJK_SHARE
24}
25
26/**
27 * One session's check: `run` violations in a row, `skip` violations still to pass without a hint,
28 * `lastHinted` whether the last violation got one, `owed` whether the next prompt carries it.
29 */
30export type RuleState = { run: number; skip: number; lastHinted: boolean; owed: boolean }
31
32export const FRESH: RuleState = { run: 0, skip: 0, lastHinted: false, owed: false }
33
34/** The state after a main-thread reply: once 2 hints in a row were each followed by another violation, the next min(16, 2^(n-3)) go unhinted, n the run. */
35export function afterReply(state: RuleState, violated: boolean): RuleState {
36  if (!violated) return FRESH
37  const run = state.run + 1
38  if (state.skip > 0) return { run, skip: state.skip - 1, lastHinted: false, owed: false }
39  if (run >= 3 && state.lastHinted) return { run, skip: Math.min(MAX_SKIPPED, 2 ** (run - 3)) - 1, lastHinted: false, owed: false }
40  return { run, skip: 0, lastHinted: true, owed: true }
41}
42
hooks/guard-git.ts 518 lines
1// In a repo's main worktree, refuse git commands that discard uncommitted changes, and git commit --amend.
2// The main tree often has several writers (Claude sessions, foreground codex/grok); these commands take their changes away.
3// Linked worktrees (worker's .claude/worktrees/*, mmrun's .mm-wt/*) are allowed.
4// Shell is parsed as text: this guards against agent mistakes, not adversarial bypass. When the directory cannot be
5// determined, or git cannot tell whether it is the main tree, dangerous operations are treated as being on the main tree.
6import type { GuardIo } from './guard-io'
7import { expanduser, isdir, exists, realpath } from './guard-io'
8import { basename, isabs, join, normpath } from './posixpath'
9import { pySplit, shlexJoin, shlexSplit, shlexTokens } from './shlex'
10
11/** A directory that could not be determined. */
12const UNKNOWN = Symbol('unknown directory')
13type Dir = string | typeof UNKNOWN
14
15// Word characters (\w) are Unicode letters, digits and _.
16const QUOTED_HEREDOC = /<<-?\s*(['"])([\p{L}\p{N}_]+)\1[^\n]*\n.*?\n\s*\2\s*(?=\n|$)/gsu
17const ANY_HEREDOC = /<<-?\s*(['"]?)([\p{L}\p{N}_]+)\1[^\n]*\n.*?\n\s*\2\s*(?=\n|$)/gsu
18const GLOB = /[*?[]/
19const VAR = /\$\{([\p{L}\p{N}_]+)(?::?-([^}]*))?\}|\$([\p{L}\p{N}_]+)/gu
20const SEPARATORS = ';&|()\n'
21const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{', '}', 'time', 'exec', 'nohup'])
22const ASSIGN = /^([A-Za-z_][\p{L}\p{N}_]*)=(.*)$/su
23const SHELL_C = /^-[a-zA-Z]*c[a-zA-Z]*$/
24const REASON =
25  'Blocked on the shared main worktree: `{op}` would take away uncommitted changes from other sessions or the user. ' +
26  'Undo your own edit with a reverse Edit; for a clean baseline open a temporary worktree. Linked worktrees are exempt.'
27const AMEND = "Blocked on the shared main worktree: `{op}` would rewrite a commit already on the main tree's branch. Make a new commit instead. Linked worktrees are exempt."
28const UNVERIFIED =
29  'Blocked: `{op}` would take away uncommitted changes if this is the shared main worktree, and git could not tell ' +
30  '(git missing, timed out or failed). Make sure `git rev-parse --git-common-dir` works in that directory, ' +
31  'or run the command in a linked worktree.'
32// Short options that take a value, and long ones that may take it as the next word, per subcommand
33const VALUED: Record<string, [string, string[]]> = {
34  checkout: ['bB', ['--orphan', '--conflict']],
35  restore: ['s', ['--source']],
36  clean: ['e', ['--exclude']],
37  switch: ['cC', ['--create', '--force-create', '--orphan', '--conflict']],
38}
39// Git ignores an alias named like a builtin, so these are never looked up as aliases
40const BUILTINS = new Set(
41  ('add am apply archive bisect blame branch cat-file checkout cherry-pick clean clone commit config describe diff fetch ' +
42    'for-each-ref format-patch gc grep help init log ls-files ls-remote ls-tree merge merge-base mv notes pull push range-diff ' +
43    'rebase reflog remote reset restore rev-list rev-parse revert rm shortlog show show-ref stash status submodule switch ' +
44    'symbolic-ref tag version worktree').split(' '),
45)
46const ALIAS_DEPTH = 5
47// One check's git calls share GIT_BUDGET_MS, each cut at GIT_CALL_MS, so a hung git holds the tool call 7 s at most.
48const GIT_BUDGET_MS = 7_000
49const GIT_CALL_MS = 5_000
50
51type Git = { exitCode: number; stdout: string; stderr: string }
52
53/** One guard call: its I/O, the deadline its git calls share, and the dangerous ops git could not place. */
54type Run = { io: GuardIo; deadline: number; unchecked: string[] }
55
56/** The shell's variables: values the command set or unset, the host's environment beneath. */
57class Env {
58  private readonly io: GuardIo
59  private readonly own: Map<string, string | null>
60
61  constructor(io: GuardIo, own = new Map<string, string | null>()) {
62    this.io = io
63    this.own = own
64  }
65
66  copy(): Env {
67    return new Env(this.io, new Map(this.own))
68  }
69
70  async get(name: string): Promise<string | undefined> {
71    const value = this.own.get(name)
72    return value === null ? undefined : (value ?? (await this.io.env(name)))
73  }
74
75  set(name: string, value: string): void {
76    this.own.set(name, value)
77  }
78
79  unset(name: string): void {
80    this.own.set(name, null)
81  }
82}
83
84const uniq = <T>(items: Iterable<T>): T[] => [...new Set(items)]
85const first = (pattern: RegExp, text: string) => pattern.exec(text)
86
87/** git in target; the repository is found from target alone unless `env` sets GIT_DIR / GIT_WORK_TREE. */
88async function git(run: Run, target: string, args: string[], env: Record<string, string> = {}): Promise<Git | undefined> {
89  const left = run.deadline - (await run.io.now())
90  if (left <= 0) return undefined
91  return run.io.run(['git', '-C', target, ...args], { env: { ...env, LC_ALL: 'C' }, timeoutMs: Math.min(GIT_CALL_MS, left) })
92}
93
94/** true / false, or undefined when git could not answer (missing, timed out, failed). */
95async function isMainTree(run: Run, path: string): Promise<boolean | undefined> {
96  const out = await git(run, path, ['rev-parse', '--absolute-git-dir', '--git-common-dir'])
97  if (out === undefined) return undefined
98  if (out.exitCode !== 0) return out.stderr.includes('not a git repository') ? false : undefined
99  const lines = out.stdout.split('\n')
100  if (lines.length < 2 || !lines[0] || !lines[1]) return undefined
101  return (await realpath(run.io, lines[0])) === (await realpath(run.io, join(path, lines[1])))
102}
103
104/** Letters of short option clusters before `--`; a letter that takes a value ends its cluster (or takes the next word). */
105function shortFlags(args: string[], sub = ''): Set<string> {
106  const [short, long] = VALUED[sub] ?? ['', []]
107  const flags = new Set<string>()
108  let skip = false
109  for (const a of args) {
110    if (skip) {
111      skip = false
112    } else if (a === '--') {
113      break
114    } else if (long.includes(a)) {
115      skip = true
116    } else if (a.startsWith('-') && !a.startsWith('--')) {
117      const letters = Array.from(a).slice(1)
118      for (const [k, c] of letters.entries()) {
119        flags.add(c)
120        if (short.includes(c)) {
121          skip = k === letters.length - 1
122          break
123        }
124      }
125    }
126  }
127  return flags
128}
129
130async function checkoutOp(run: Run, rest: string[], target: Dir, probe: Dir): Promise<string | undefined> {
131  const flags = shortFlags(rest, 'checkout')
132  if (rest.includes('--force') || flags.has('f')) return 'git checkout --force'
133  if (rest.includes('--') || rest.some(a => ['--ours', '--theirs', '--patch', '-p'].includes(a) || a.startsWith('--pathspec-from-file'))) {
134    return 'git checkout <path>'
135  }
136  if (flags.has('b') || flags.has('B') || rest.includes('--orphan')) return undefined
137  const positional: string[] = []
138  let skip = false
139  for (const a of rest) {
140    if (skip) skip = false
141    else if (a === '--conflict' || a === '--track') skip = true
142    else if (!a.startsWith('-')) positional.push(a)
143  }
144  const [name] = positional
145  if (positional.length >= 2 || positional.includes('.') || (name !== undefined && GLOB.test(name))) return 'git checkout <path>'
146  if (name === undefined) return undefined
147  if (target === UNKNOWN) {
148    // Directory unknown: refs are shared by a repo's worktrees, so a ref that resolves in probe is a branch switch, else a file restore
149    const ref = probe === UNKNOWN ? undefined : await git(run, probe, ['rev-parse', '--verify', '--quiet', `${name}^{commit}`])
150    return ref?.exitCode === 0 ? undefined : 'git checkout <path>'
151  }
152  const ref = await git(run, target, ['rev-parse', '--verify', '--quiet', `${name}^{commit}`])
153  if (ref?.exitCode !== 0) {
154    // Not a commit: a path on disk or a deleted tracked file, both mean a file restore
155    const tracked = await git(run, target, ['ls-files', '--error-unmatch', '--', name])
156    if ((await exists(run.io, join(target, name))) || tracked?.exitCode === 0) return 'git checkout <path>'
157  }
158  return undefined
159}
160
161async function dangerous(run: Run, sub: string, rest: string[], target: Dir, probe: Dir): Promise<string | undefined> {
162  if (rest.includes('-h') || rest.includes('--help')) return undefined
163  const flags = shortFlags(rest, sub)
164  if (sub === 'checkout') return checkoutOp(run, rest, target, probe)
165  if (sub === 'restore') {
166    const staged = rest.includes('--staged') || flags.has('S')
167    const worktree = rest.includes('--worktree') || flags.has('W')
168    return staged && !worktree ? undefined : 'git restore'
169  }
170  if (sub === 'stash' && !['list', 'show', 'create'].includes(rest[0] ?? '')) return 'git stash'
171  if (sub === 'clean' && !(rest.includes('--dry-run') || flags.has('n'))) return 'git clean'
172  if (sub === 'switch' && (rest.includes('--discard-changes') || rest.includes('--force') || flags.has('f'))) return 'git switch --discard-changes'
173  if (sub === 'reset' && rest.includes('--hard')) return 'git reset --hard'
174  if (sub === 'commit' && rest.includes('--amend')) return 'git commit --amend'
175  return undefined
176}
177
178async function expand(io: GuardIo, word: string, env: Env, cwd: Dir): Promise<Dir> {
179  if (word.includes('`') || word.includes('$(')) return UNKNOWN
180  // $X, ${X}, ${X:-default}, ${X-default}; other ${...} forms leave a $ and count as unknown
181  let replaced = ''
182  let from = 0
183  for (const m of word.matchAll(VAR)) {
184    const value = await env.get(m[1] ?? m[3] ?? '')
185    replaced += word.slice(from, m.index) + (m[2] !== undefined && !value ? m[2] : (value ?? '$?'))
186    from = m.index + m[0].length
187  }
188  const path = await expanduser(io, replaced + word.slice(from))
189  if (path.includes('$')) return UNKNOWN
190  if (isabs(path)) return normpath(path)
191  return cwd === UNKNOWN ? UNKNOWN : normpath(join(cwd, path))
192}
193
194/** Contents of $(...) and `...` outside single quotes (single-quoted text is literal; the shell does not run it). */
195function substitutions(text: string): string[] {
196  const chars = Array.from(text)
197  const out: string[] = []
198  let quote = ''
199  let i = 0
200  while (i < chars.length) {
201    const c = chars[i]
202    if (c === '\\' && quote !== "'") {
203      i += 2
204      continue
205    }
206    if (c === "'" && quote !== '"') {
207      quote = quote === "'" ? '' : "'"
208    } else if (c === '"' && quote !== "'") {
209      quote = quote === '"' ? '' : '"'
210    } else if (quote !== "'" && c === '$' && chars[i + 1] === '(') {
211      let depth = 1
212      let j = i + 2
213      while (j < chars.length && depth > 0) {
214        depth += chars[j] === '(' ? 1 : chars[j] === ')' ? -1 : 0
215        j += 1
216      }
217      out.push(chars.slice(i + 2, j - 1).join(''))
218      i = j
219      continue
220    } else if (quote !== "'" && c === '`') {
221      const found = chars.indexOf('`', i + 1)
222      const j = found < 0 ? chars.length : found
223      out.push(chars.slice(i + 1, j).join(''))
224      i = j + 1
225      continue
226    }
227    i += 1
228  }
229  return out
230}
231
232/** Strip from a word-initial # outside quotes to end of line (the newline stays: it separates commands). */
233function stripComments(text: string): string {
234  const chars = Array.from(text)
235  let out = ''
236  let quote = ''
237  let i = 0
238  while (i < chars.length) {
239    const c = chars[i] ?? ''
240    if (c === '\\' && quote !== "'") {
241      out += chars.slice(i, i + 2).join('')
242      i += 2
243      continue
244    }
245    if ((c === "'" || c === '"') && (quote === '' || quote === c)) {
246      quote = quote === '' ? c : ''
247    } else if (c === '#' && quote === '' && (i === 0 || ' \t\n;&|('.includes(chars[i - 1] ?? ''))) {
248      const j = chars.indexOf('\n', i)
249      i = j < 0 ? chars.length : j
250      continue
251    }
252    out += c
253    i += 1
254  }
255  return out
256}
257
258/** The command text as [(preceding separator, words)] plus the $(...) contents to check separately.
259 * A quoted heredoc body is literal; an unquoted body is not run, but $(...) inside it is expanded. */
260function commands(command: string): { cmds: [string, string[]][]; extra: string[] } {
261  let text = stripComments(command.replace(QUOTED_HEREDOC, ''))
262  const extra = substitutions(text)
263  text = text.replace(ANY_HEREDOC, '').replaceAll('\\\n', ' ')
264  let tokens: string[]
265  try {
266    tokens = shlexTokens(text, ';&|()\n', ' \t\r')
267  } catch {
268    tokens = pySplit(text)
269  }
270  const cmds: [string, string[]][] = []
271  let cur: string[] = []
272  let sep = ''
273  for (const t of tokens) {
274    if (Array.from(t).every(c => SEPARATORS.includes(c))) {
275      if (cur.length > 0) cmds.push([sep, cur])
276      cur = []
277      sep = t
278    } else {
279      cur.push(t)
280    }
281  }
282  if (cur.length > 0) cmds.push([sep, cur])
283  return { cmds, extra }
284}
285
286/** The words of the command actually run, and the directory from env -C or undefined. */
287function stripWrappers(words: string[], env: Env): [string[], string | undefined] {
288  let chdir: string | undefined
289  while (words.length > 0) {
290    const w = basename(words[0] ?? '')
291    if (KEYWORDS.has(w)) {
292      words = words.slice(1)
293    } else if (w === 'sudo' || w === 'command' || w === 'nice') {
294      const takesArg = w === 'sudo' ? ['-u', '-g', '-p', '-C', '-D', '-h', '-U', '-r', '-t'] : w === 'nice' ? ['-n'] : []
295      words = words.slice(1)
296      while (words[0]?.startsWith('-')) words = words.slice(takesArg.includes(words[0]) ? 2 : 1)
297    } else if (w === 'env') {
298      words = words.slice(1)
299      while (words[0] !== undefined && (words[0].startsWith('-') || ASSIGN.test(words[0]))) {
300        const [opt, value] = words
301        const assign = first(ASSIGN, opt)
302        if (assign) {
303          env.set(assign[1] ?? '', assign[2] ?? '')
304        } else if ((opt === '-u' || opt === '--unset') && value !== undefined) {
305          env.unset(value)
306          words = words.slice(1)
307        } else if ((opt === '-C' || opt === '--chdir') && value !== undefined) {
308          chdir = value
309          words = words.slice(1)
310        } else if (opt.startsWith('--chdir=')) {
311          chdir = opt.slice('--chdir='.length)
312        }
313        words = words.slice(1)
314      }
315    } else {
316      return [words, chdir]
317    }
318  }
319  return [words, chdir]
320}
321
322/** The dangerous op that `git <args>` run from base would do on the main tree, or undefined. Aliases are expanded first. */
323async function gitOp(run: Run, args: string[], local: Env, base: Dir, probe: Dir, depth: number): Promise<string | undefined> {
324  let rundir = base
325  let worktree: Dir | undefined
326  let gitdir: string | undefined
327  let target: Dir = base
328  const aliases = new Map<string, string>()
329  let isResolved = false
330  for (let round = 0; round < ALIAS_DEPTH; round += 1) {
331    // git runs in the -C directory, but an explicit work tree (--work-tree / GIT_WORK_TREE) takes precedence
332    while (args[0]?.startsWith('-')) {
333      const [opt, value] = args
334      if (['-C', '-c', '--git-dir', '--work-tree', '--namespace'].includes(opt) && value !== undefined) {
335        if (opt === '-C') {
336          rundir = await expand(run.io, value, local, rundir)
337        } else if (opt === '-c' && value.toLowerCase().startsWith('alias.') && value.includes('=')) {
338          const cut = value.indexOf('=')
339          aliases.set(value.slice('alias.'.length, cut).toLowerCase(), value.slice(cut + 1))
340        } else if (opt === '--work-tree') {
341          worktree = value
342        } else if (opt === '--git-dir') {
343          gitdir = value
344          worktree = worktree || UNKNOWN
345        }
346        args = args.slice(2)
347      } else {
348        if (opt.startsWith('-C') && opt.length > 2) {
349          rundir = await expand(run.io, opt.slice(2), local, rundir)
350        } else if (opt.startsWith('--work-tree=')) {
351          worktree = opt.slice(opt.indexOf('=') + 1)
352        } else if (opt.startsWith('--git-dir=')) {
353          gitdir = opt.slice(opt.indexOf('=') + 1)
354          worktree = worktree || UNKNOWN
355        }
356        args = args.slice(1)
357      }
358    }
359    let tree = worktree
360    const envTree = await local.get('GIT_WORK_TREE')
361    if (tree === undefined && envTree !== undefined) tree = envTree
362    else if (tree === undefined && (await local.get('GIT_DIR')) !== undefined) tree = UNKNOWN
363    target = tree === undefined ? rundir : tree === UNKNOWN ? UNKNOWN : await expand(run.io, tree, local, rundir)
364    const [sub] = args
365    if (sub === undefined) return undefined
366    let alias = BUILTINS.has(sub) ? undefined : aliases.get(sub.toLowerCase())
367    if (alias === undefined && !BUILTINS.has(sub)) {
368      const repo: Record<string, string> = {}
369      for (const name of ['GIT_DIR', 'GIT_WORK_TREE']) {
370        const value = await local.get(name)
371        if (value !== undefined) repo[name] = value
372      }
373      if (gitdir !== undefined) repo.GIT_DIR = gitdir
374      if (typeof worktree === 'string') repo.GIT_WORK_TREE = worktree
375      const got = await git(run, rundir === UNKNOWN ? '/' : rundir, ['config', '--get', `alias.${sub}`], repo)
376      alias = got?.exitCode === 0 ? got.stdout.trim() : undefined
377    }
378    if (alias === undefined) {
379      isResolved = true
380      break
381    }
382    if (alias.startsWith('!')) {
383      // A shell alias runs from the top of the work tree with the remaining words appended
384      return depth < 3 ? check(run, `${alias.slice(1)} ${shlexJoin(args.slice(1))}`, target, depth + 1) : undefined
385    }
386    try {
387      args = [...shlexSplit(alias), ...args.slice(1)]
388    } catch {
389      return undefined
390    }
391  }
392  if (!isResolved) return undefined
393  const op = await dangerous(run, args[0] ?? '', args.slice(1), target, probe)
394  if (op !== undefined && target !== UNKNOWN) {
395    const onMain = await isMainTree(run, target)
396    if (onMain === undefined) run.unchecked.push(op)
397    else if (!onMain) return undefined
398  }
399  return op
400}
401
402async function check(run: Run, command: string, cwd: Dir, depth = 0): Promise<string | undefined> {
403  // heres: where the next command may run if it continues the && chain; maybe: where it may run once the chain breaks
404  let env = new Env(run.io)
405  let heres: Dir[] = [cwd]
406  let maybe: Dir[] | undefined
407  let prev: Dir[] = [UNKNOWN]
408  const outer: Dir[][] = []
409  const visited: Dir[] = [cwd]
410  const { cmds, extra } = commands(command)
411  for (const [i, [sep, cmdWords]] of cmds.entries()) {
412    let words = cmdWords
413    if (maybe !== undefined && sep !== '&&') {
414      heres = maybe
415      maybe = undefined
416    }
417    // Parentheses are a subshell: a cd inside stops applying after the closing paren
418    for (const c of sep) {
419      if (c === '(') outer.push(heres)
420      else if (c === ')' && outer.length > 0) heres = outer.pop() ?? heres
421    }
422    const local = env.copy()
423    for (let assign = first(ASSIGN, words[0] ?? ''); words.length > 0 && assign; assign = first(ASSIGN, words[0] ?? '')) {
424      local.set(assign[1] ?? '', assign[2] ?? '')
425      words = words.slice(1)
426    }
427    if (words.length === 0) {
428      env = local
429      continue
430    }
431    let chdir: string | undefined
432    ;[words, chdir] = stripWrappers(words, local)
433    const bases: Dir[] = []
434    for (const here of heres) bases.push(chdir === undefined ? here : await expand(run.io, chdir, local, here))
435    const dirs = uniq(bases)
436    if (words.length === 0) continue
437    const nextSep = cmds[i + 1]?.[0] ?? ''
438    const [cmd = '', ...rest] = words
439    if (cmd === 'export') {
440      for (const w of rest) {
441        const assign = first(ASSIGN, w)
442        if (assign) env.set(assign[1] ?? '', assign[2] ?? '')
443      }
444      continue
445    }
446    if (cmd === 'unset') {
447      for (const w of rest) env.unset(w)
448      continue
449    }
450    if (cmd === 'cd') {
451      const args = rest.filter(a => a !== '-L' && a !== '-P' && a !== '--')
452      let dests: Dir[] = []
453      if (args.length === 1 && args[0] === '-') dests = prev
454      else if (args[0] !== undefined) for (const h of heres) dests.push(await expand(run.io, args[0], local, h))
455      else dests = [await expanduser(run.io, '~')]
456      // A cd in a pipeline runs in a subshell and does not affect later commands
457      if ((sep + nextSep).includes('|') && !(sep + nextSep).includes('||')) continue
458      const kept: Dir[] = []
459      for (const d of dests) if (d === UNKNOWN || (await isdir(run.io, d))) kept.push(d)
460      dests = uniq(kept)
461      if (dests.length > 0) {
462        // A cd after && or || may not run: after ||, or once a following && chain breaks, the old directory stays possible
463        if (sep.includes('||')) {
464          ;[heres, prev] = [uniq([...(maybe ?? []), ...heres, ...dests]), heres]
465          maybe = undefined
466        } else if (sep.includes('&&')) {
467          ;[maybe, heres, prev] = [uniq([...(maybe !== undefined && maybe.length > 0 ? maybe : heres), ...dests]), dests, heres]
468        } else {
469          ;[heres, prev] = [dests, heres]
470        }
471        visited.push(...heres, ...(maybe ?? []))
472      }
473      continue
474    }
475    // Commands that launch others: the bash -c string is checked on its own; xargs / find -exec yield the command after them
476    const name = basename(cmd)
477    const cflag = words.slice(1, -1).findIndex(a => SHELL_C.test(a)) + 1
478    if (['bash', 'sh', 'zsh'].includes(name) && cflag > 0) {
479      for (const base of dirs) {
480        const op = depth < 3 ? await check(run, words[cflag + 1] ?? '', base, depth + 1) : undefined
481        if (op !== undefined) return op
482      }
483      continue
484    }
485    if (name === 'xargs') {
486      words = words.slice(1)
487      while (words[0]?.startsWith('-')) words = words.slice(['-I', '-n', '-P', '-L', '-s', '-d', '-E'].includes(words[0]) ? 2 : 1)
488    } else if (name === 'find') {
489      const start = words.findIndex(a => ['-exec', '-execdir', '-ok', '-okdir'].includes(a))
490      words = start < 0 ? [] : words.slice(start + 1)
491    }
492    if (words.length === 0 || basename(words[0] ?? '') !== 'git') continue
493    for (const base of dirs) {
494      const op = await gitOp(run, words.slice(1), local, base, cwd, depth)
495      if (op !== undefined) return op
496    }
497  }
498  if (depth < 3) {
499    // Which command a substitution sits in is not tracked, so check it in every directory the command visited
500    for (const inner of extra) {
501      for (const d of uniq(visited)) {
502        const op = await check(run, inner, d, depth + 1)
503        if (op !== undefined) return op
504      }
505    }
506  }
507  return undefined
508}
509
510/** The reason to refuse `command` run in cwd, the op it would do, or undefined to let it run. */
511export async function sharedTreeGit(io: GuardIo, command: string, cwd: string): Promise<{ op: string; reason: string } | undefined> {
512  const run: Run = { io, deadline: (await io.now()) + GIT_BUDGET_MS, unchecked: [] }
513  const op = await check(run, command, cwd)
514  if (op === undefined) return undefined
515  const template = run.unchecked.length > 0 ? UNVERIFIED : op === 'git commit --amend' ? AMEND : REASON
516  return { op, reason: template.replace('{op}', op) }
517}
518
hooks/guard-io.ts 44 lines
1import { basename, dirname, join } from './posixpath'
2
3/** What the guards read of the host; guards.ts answers it from `$`, a test from its own world. */
4export type GuardIo = {
5  /** A variable of the host process's environment; undefined when unset. */
6  env: (name: string) => Promise<string | undefined>
7  /** User `name`'s home directory ('' for the current user); undefined when there is no such user. */
8  userHome: (name: string) => Promise<string | undefined>
9  /** Runs argv with `env` set over the host's environment; undefined when it cannot start or runs past timeoutMs. */
10  run: (argv: readonly string[], init: { env?: Record<string, string>; timeoutMs: number }) => Promise<{ exitCode: number; stdout: string; stderr: string } | undefined>
11  /** What the path leads to, links followed, and where it lands; undefined when it leads nowhere. */
12  stat: (path: string) => Promise<{ kind: 'file' | 'dir' | 'other'; realPath?: string } | undefined>
13  /** The directory's entries; undefined when it cannot be listed. */
14  list: (path: string) => Promise<{ name: string; kind: 'file' | 'dir' | 'other' }[] | undefined>
15  /** Epoch milliseconds. */
16  now: () => Promise<number>
17}
18
19/** os.path.expanduser: `~` is $HOME (the user database when unset), `~name` that user's home; an unknown user keeps the path. */
20export async function expanduser(io: GuardIo, path: string): Promise<string> {
21  if (!path.startsWith('~')) return path
22  const cut = path.indexOf('/', 1) < 0 ? path.length : path.indexOf('/', 1)
23  const name = path.slice(1, cut)
24  const home = name === '' ? ((await io.env('HOME')) ?? (await io.userHome(''))) : await io.userHome(name)
25  if (home === undefined) return path
26  return home.replace(/\/+$/, '') + path.slice(cut) || '/'
27}
28
29/** os.path.realpath of an absolute path: resolved where it exists, its missing tail kept as written under its nearest existing directory. */
30export async function realpath(io: GuardIo, path: string): Promise<string> {
31  const found = await io.stat(path)
32  if (found !== undefined) return found.realPath ?? path
33  const parent = dirname(path)
34  return parent === path ? path : join(await realpath(io, parent), basename(path))
35}
36
37export async function isdir(io: GuardIo, path: string): Promise<boolean> {
38  return (await io.stat(path))?.kind === 'dir'
39}
40
41export async function exists(io: GuardIo, path: string): Promise<boolean> {
42  return (await io.stat(path)) !== undefined
43}
44
hooks/guard-secret.ts 459 lines
1// Refuse tool calls that would put the contents of API-key config files into the transcript (Read / Edit results,
2// Grep content, shell output such as cat, jq, diff or an environment dump).
3// Shell is parsed as text: this guards against agent mistakes, not adversarial bypass.
4import type { GuardIo } from './guard-io'
5import { exists, expanduser, realpath } from './guard-io'
6import { basename, dirname, join, normpath, split } from './posixpath'
7import { pySplit, shlexSplit } from './shlex'
8
9// Relative to HOME; `*` also crosses `/`
10const HOME_SECRETS = [
11  '.claude.json', '.claude.json.*', '.claude/backups/*', '.claude/settings.json', '.claude/settings.json.*',
12  '.claude/settings.local.json', '.codex/config.toml', '.codex/config.toml.*', '.codex/auth.json',
13  '.openviking/*', '.grok/auth.json', '.claude/file-history/*', '.codex/shell_snapshots/*',
14]
15const SECRET_NAMES = ['ovcli.conf', 'ov.conf'] // matched anywhere: the server side is reached over ssh
16// Word characters (\w) are Unicode letters, digits and _.
17const MENTION = new RegExp(
18  String.raw`\.claude\.json|\.claude/settings\.json|\.claude/settings\.local\.json|\.claude/backups` +
19    String.raw`|\.claude/file-history|\.codex/shell_snapshots|\.codex/config\.toml|\.codex/auth\.json|\.openviking(?:/|(?![\p{L}\p{N}_.\-]))|\.grok/auth\.json` +
20    String.raw`|(?<![\p{L}\p{N}_.\-])(?:ovcli|ov)\.conf(?![\p{L}\p{N}_.\-])`,
21  'iu',
22)
23const SPLIT = /&&|\|\||\$\(|[;&|()\n`]/y
24// Options whose value is the next word (rg --help, man grep); rg -r is --replace, grep -r is --recursive
25const VALUE_OPTIONS = {
26  rg: {
27    short: 'ABCdEefgjMmrTt',
28    long: [
29      '--after-context', '--before-context', '--context', '--max-depth', '--encoding', '--regexp', '--file', '--glob', '--threads', '--max-columns',
30      '--max-count', '--replace', '--type-not', '--type', '--pre', '--pre-glob', '--dfa-size-limit', '--engine', '--regex-size-limit', '--iglob',
31      '--ignore-file', '--max-filesize', '--type-add', '--type-clear', '--color', '--colors', '--context-separator', '--field-context-separator',
32      '--field-match-separator', '--hostname-bin', '--hyperlink-format', '--path-separator', '--sort', '--sortr', '--generate',
33    ],
34  },
35  grep: {
36    short: 'ABCDdefm',
37    long: [
38      '--after-context', '--before-context', '--context', '--devices', '--directories', '--regexp', '--file', '--max-count', '--exclude', '--exclude-dir',
39      '--include', '--include-dir', '--label', '--binary-files',
40    ],
41  },
42}
43const HEREDOC = /<<-?\s*(['"]?)([\p{L}\p{N}_]+)\1([^\n]*)\n(.*?)\n\s*\2\s*(?=\n|$)/gsu
44const SHELL_FED = /^(?:(?:ba|z|da|k)?sh|python[\p{Nd}.]*|node|ruby|perl|osascript)$/u
45const SHELLS = /^(?:ba|z|da|k)?sh$/
46const MESSAGE_FLAGS = ['-m', '--message', '-t', '--title', '-b', '--body'] // gh / git: the next word is text, not a file
47const WRAPPERS = ['sudo', 'command', 'time', 'nohup']
48const ASSIGN = /^[A-Za-z_][\p{L}\p{N}_]*=/u
49const METADATA = ['ls', 'stat', 'test', '[', 'chmod', 'chown', 'touch', 'wc', 'du', 'file', 'echo', 'printf']
50const QUIET_LONG = ['--files-with-matches', '--files-without-match', '--count', '--quiet']
51const SECRET_VAR = /KEY|TOKEN|SECRET|PASSWORD/iu
52const REASON =
53  'Blocked: `{call}` would put the contents of {file} into the transcript. That file holds API keys, and whatever ' +
54  'this call reads or prints is saved in the transcript. Ask the user to look at or change it; to check it, use ' +
55  'metadata only (ls, stat, wc, grep -c / grep -l); to find where the file name is mentioned in other files, ' +
56  'use grep -l or rg -l in Bash.'
57const ENV_REASON =
58  'Blocked: `{call}` would print environment variables into the transcript, and some of them hold API keys or ' +
59  'tokens that would be saved there. Print one named variable that is not a secret instead (printenv HOME).'
60
61type Found = { reason: string; call: string; file: string | undefined }
62type Tool = { tool: string; command?: unknown; file_path?: unknown; path?: unknown; output_mode?: unknown; glob?: unknown }
63/** One guard call: its I/O, the home directory as written, and `homes` (as written and resolved) lowercased. */
64type Run = { io: GuardIo; home: string; homes: string[] }
65
66/** fnmatch.translate: a shell pattern as an anchored regex source, `*` crossing `/`. */
67function translate(pattern: string): string {
68  const pat = Array.from(pattern)
69  const n = pat.length
70  let out = ''
71  let i = 0
72  let isStar = false
73  while (i < n) {
74    const c = pat[i] ?? ''
75    i += 1
76    if (c === '*' && isStar) continue
77    isStar = c === '*'
78    if (c === '*') {
79      out += '.*'
80    } else if (c === '?') {
81      out += '.'
82    } else if (c === '[') {
83      let j = i
84      if (pat[j] === '!') j += 1
85      if (pat[j] === ']') j += 1
86      while (j < n && pat[j] !== ']') j += 1
87      if (j >= n) {
88        out += '\\['
89        continue
90      }
91      let stuff: string
92      if (!pat.slice(i, j).includes('-')) {
93        stuff = pat.slice(i, j).join('').replaceAll('\\', '\\\\')
94      } else {
95        // Ranges: a reversed one (z-a) is dropped, as fnmatch does.
96        const chunks: string[] = []
97        let k = pat[i] === '!' ? i + 2 : i + 1
98        for (;;) {
99          k = pat.slice(0, j).indexOf('-', k)
100          if (k < 0) break
101          chunks.push(pat.slice(i, k).join(''))
102          i = k + 1
103          k += 3
104        }
105        const chunk = pat.slice(i, j).join('')
106        if (chunk !== '') chunks.push(chunk)
107        else chunks[chunks.length - 1] += '-'
108        for (let m = chunks.length - 1; m > 0; m -= 1) {
109          const left = chunks[m - 1] ?? ''
110          const right = chunks[m] ?? ''
111          if (left.slice(-1) > right.slice(0, 1)) {
112            chunks[m - 1] = left.slice(0, -1) + right.slice(1)
113            chunks.splice(m, 1)
114          }
115        }
116        stuff = chunks.map(s => s.replaceAll('\\', '\\\\').replaceAll('-', '\\-')).join('-')
117      }
118      i = j + 1
119      if (stuff === '') {
120        out += '(?!)'
121      } else if (stuff === '!') {
122        out += '.'
123      } else {
124        if (stuff.startsWith('!')) stuff = `^${stuff.slice(1)}`
125        else if (stuff.startsWith('^') || stuff.startsWith('[')) stuff = `\\${stuff}`
126        // A ] first in the set is literal to fnmatch; JavaScript reads [] as an empty set.
127        stuff = stuff.replace(/^(\^?)\]/, '$1\\]')
128        out += `[${stuff}]`
129      }
130    } else {
131      out += c.replace(/[\\^$.*+?()[\]{}|/]/g, '\\$&')
132    }
133  }
134  return `^(?:${out})$`
135}
136
137const compiled = new Map<string, RegExp>()
138
139function fnmatch(name: string, pattern: string): boolean {
140  let rx = compiled.get(pattern)
141  if (rx === undefined) {
142    rx = new RegExp(translate(pattern), 's')
143    compiled.set(pattern, rx)
144  }
145  return rx.test(name)
146}
147
148const hasMagic = (path: string) => /[*?[]/.test(path)
149
150/** glob.glob of an absolute pattern: hidden names only for a pattern part that starts with a dot. */
151async function glob(io: GuardIo, pathname: string, dirsOnly = false): Promise<string[]> {
152  const [dir, name] = split(pathname)
153  if (!hasMagic(pathname)) {
154    if (name !== '') return (await io.stat(pathname)) !== undefined ? [pathname] : []
155    return (await io.stat(dir))?.kind === 'dir' ? [pathname] : []
156  }
157  const dirs = dir !== pathname && hasMagic(dir) ? await glob(io, dir, true) : [dir]
158  const out: string[] = []
159  for (const d of dirs) {
160    let names: string[]
161    if (!hasMagic(name)) {
162      names = name === '' ? ((await io.stat(d))?.kind === 'dir' ? [name] : []) : (await io.stat(join(d, name))) !== undefined ? [name] : []
163    } else {
164      names = []
165      for (const entry of (await io.list(d)) ?? []) {
166        if (dirsOnly && entry.kind !== 'dir' && (entry.kind !== 'other' || (await io.stat(join(d, entry.name)))?.kind !== 'dir')) continue
167        if (entry.name.startsWith('.') && !name.startsWith('.')) continue
168        if (fnmatch(entry.name, name)) names.push(entry.name)
169      }
170    }
171    for (const found of names) out.push(join(d, found))
172  }
173  return out
174}
175
176/** The absolute path and its realpath, with ~, $HOME and ${HOME} expanded and relative paths taken from cwd. */
177async function paths(run: Run, path: string, cwd: string): Promise<string[]> {
178  const expanded = await expanduser(run.io, path.replace(/^\$(?:HOME|\{HOME\})(?=\/|\n?$)/, () => run.home))
179  const full = normpath(join(cwd, expanded))
180  return [...new Set([full, await realpath(run.io, full)])]
181}
182
183// Paths are compared lowercased: the default macOS volume is case-insensitive, so ~/.Codex/auth.json is the same file.
184function isSecret(run: Run, path: string): boolean {
185  path = path.toLowerCase()
186  if (SECRET_NAMES.includes(basename(path))) return true
187  return run.homes.some(h => path.startsWith(`${h}/`) && HOME_SECRETS.some(pat => fnmatch(path.slice(h.length + 1), pat)))
188}
189
190/** True when a home-anchored secret file lies under directory `path` at any depth. */
191function holdsSecret(run: Run, path: string): boolean {
192  const prefix = `${path.toLowerCase().replace(/\/+$/, '')}/`
193  return run.homes.some(h => HOME_SECRETS.some(pat => `${dirname(join(h, pat))}/` === prefix || join(h, pat).startsWith(prefix)))
194}
195
196function envDump(words: string[]): boolean {
197  const name = basename(words[0] ?? '')
198  let args = words.slice(1)
199  if (name === 'env') {
200    while (args[0] !== undefined && (['-0', '--null', '-u'].includes(args[0]) || ASSIGN.test(args[0]))) args = args.slice(args[0] === '-u' ? 2 : 1)
201    return args.length === 0
202  }
203  if (name === 'declare' || name === 'typeset') {
204    // An empty word counts as an option.
205    const isOption = (a: string) => a === '' || a.startsWith('-') || a.startsWith('+')
206    const options = args.filter(isOption)
207    // zsh `typeset NAME` and `-p NAME` print the value; `-x NAME` or an assignment NAME=V prints nothing
208    const names = args.filter(a => !isOption(a) && !a.includes('='))
209    return (
210      (options.length === args.length && !options.some(o => o.includes('f') || o.includes('F'))) ||
211      ((options.length === 0 || options.some(o => o.includes('p'))) && names.some(a => SECRET_VAR.test(a)))
212    )
213  }
214  return (
215    (name === 'printenv' && (args.length === 0 || args.some(a => SECRET_VAR.test(a)))) ||
216    (name === 'export' && (args.length === 0 || (args.length === 1 && args[0] === '-p'))) ||
217    (name === 'set' && args.length === 0)
218  )
219}
220
221function printsSecretVar(segment: string, words: string[]): boolean {
222  if (!['echo', 'printf'].includes(basename(words[0] ?? ''))) return false
223  // $NAME inside single quotes is not expanded; double-quoted strings are kept whole so their ' is literal
224  const text = segment.replace(/"(?:\\[^\n]|[^"\\])*"|'[^']*'/g, m => (m.startsWith('"') ? m : ''))
225  // \$NAME is literal, \\$NAME is not; ${NAME:+text} and ${NAME+text} print only the text
226  for (const m of text.matchAll(/(?<!\\)(?:\\\\)*\$(?:([A-Za-z_][\p{L}\p{N}_]*)|\{([A-Za-z_][\p{L}\p{N}_]*)(?![\p{L}\p{N}_]|:?\+))/gu)) {
227    if (SECRET_VAR.test((m[1] ?? '') + (m[2] ?? ''))) return true
228  }
229  return false
230}
231
232function allowed(words: string[]): boolean {
233  const name = basename(words[0] ?? '')
234  if (METADATA.includes(name)) return true
235  if (['grep', 'egrep', 'rg'].includes(name)) {
236    const quiet = name === 'rg' ? 'lcq' : 'lLcq' // rg -L is --follow and still prints matching lines
237    const short = new RegExp(`^-[A-Za-z]*[${quiet}][A-Za-z]*$`)
238    return words.slice(1).some(a => QUIET_LONG.includes(a) || short.test(a))
239  }
240  if (name !== 'git' || words[1] !== 'commit') return false
241  // -F reads the message from a file, so its path is checked like any other
242  return !words.some((a, i) => i > 1 && !MESSAGE_FLAGS.includes(words[i - 1] ?? '') && (a === '--file' || a.startsWith('--file=') || a.startsWith('-F')))
243}
244
245/** The words of an rg or grep call past options and their values, and whether -e or -f gave the pattern. */
246function operands(name: string, words: string[]): { operands: string[]; patternGiven: boolean } {
247  const table = name === 'rg' ? VALUE_OPTIONS.rg : VALUE_OPTIONS.grep
248  let patternGiven = false
249  let skip = false
250  const out: string[] = []
251  for (const a of words.slice(1)) {
252    if (skip) {
253      skip = false
254      continue
255    }
256    let option: string | undefined
257    if (a.startsWith('--')) {
258      const long = a.split('=')[0] ?? ''
259      if (table.long.includes(long)) [option, skip] = [long, !a.includes('=')]
260    } else if (/^-[A-Za-z0-9]+$/.test(a)) {
261      // the first value-taking letter of a cluster takes the rest of the word, or the next word when it is last
262      const at = Array.from(a).findIndex((ch, i) => i > 0 && table.short.includes(ch))
263      if (at > 0) [option, skip] = [`-${a[at]}`, at === a.length - 1]
264    }
265    if (option !== undefined) patternGiven ||= ['-e', '-f', '--regexp', '--file'].includes(option)
266    else if (!a.startsWith('-')) out.push(a)
267  }
268  return { operands: out, patternGiven }
269}
270
271/** True when rg, or grep with -r, gets no path operand and so searches the cwd. */
272function searchesCwd(name: string, words: string[]): boolean {
273  const args = words.slice(1)
274  if (name !== 'rg' && !args.some(a => /^-[A-Za-z]*[rR][A-Za-z]*$/.test(a) || ['--recursive', '--dereference-recursive'].includes(a))) return false
275  const given = operands(name, words)
276  return given.operands.length === (given.patternGiven ? 0 : 1)
277}
278
279/** The command cut at SPLIT outside quotes; inside double quotes only at $( and `, which still run there. */
280function splitCommands(command: string): string[] {
281  const out: string[] = []
282  const open: string[] = [] // quotes and substitutions not yet closed: ' " $( ( `
283  let start = 0
284  let i = 0
285  while (i < command.length) {
286    const top = open.at(-1)
287    const ch = command[i] ?? ''
288    if (top === "'") {
289      if (ch === "'") open.pop()
290      i += 1
291      continue
292    }
293    if (ch === '\\') {
294      i += 2
295      continue
296    }
297    if (top === '"') {
298      if (ch === '"') open.pop()
299      if (ch !== '`' && !command.startsWith('$(', i)) {
300        i += 1
301        continue
302      }
303    } else if (ch === "'" || ch === '"') {
304      open.push(ch)
305      i += 1
306      continue
307    } else if (ch === '#' && (i === 0 || /[\s;&|()`]/.test(command[i - 1] ?? ''))) {
308      // a quote in a comment opens nothing
309      const end = command.indexOf('\n', i)
310      i = end < 0 ? command.length : end
311      continue
312    }
313    SPLIT.lastIndex = i
314    const token = SPLIT.exec(command)?.[0]
315    if (token === undefined) {
316      i += 1
317      continue
318    }
319    if (token === '$(' || token === '(' || (token === '`' && top !== '`')) open.push(token)
320    else if ((token === ')' && (top === '$(' || top === '(')) || (token === '`' && top === '`')) open.pop()
321    out.push(command.slice(start, i))
322    i += token.length
323    start = i
324  }
325  out.push(command.slice(start))
326  return out
327}
328
329/** [segment, words] per simple command, past assignments and wrappers. */
330function simpleCommands(command: string): [string, string[]][] {
331  const out: [string, string[]][] = []
332  // The plain split cuts too much inside quotes, splitCommands too little past quotes like $'…'; refusing on both only refuses more
333  for (const segment of new Set([...splitCommands(command), ...command.split(new RegExp(SPLIT.source))])) {
334    let words: string[]
335    try {
336      words = shlexSplit(segment)
337    } catch {
338      words = pySplit(segment)
339    }
340    while (words[0] !== undefined && ASSIGN.test(words[0])) words = words.slice(1)
341    while (words[0] !== undefined && WRAPPERS.includes(words[0])) {
342      words = words.slice(1)
343      while (words[0]?.startsWith('-')) words = words.slice(1)
344    }
345    if (words.length > 0) out.push([segment, words])
346  }
347  return out
348}
349
350/** The command without heredoc bodies that are only text: kept when fed to a program `readers` matches,
351 * or when an unquoted delimiter lets the body run $( ) or backticks. */
352function dropHeredocs(command: string, readers = SHELL_FED): string {
353  return command.replace(HEREDOC, (whole: string, quote: string, _delimiter: string, rest: string, body: string, at: number) => {
354    const line = command.slice(at === 0 ? 0 : command.lastIndexOf('\n', at - 1) + 1, at) + rest
355    const isFed = simpleCommands(line).some(([, words]) => readers.test(basename(words[0] ?? '')))
356    const expands = quote === '' && /\$\(|`/.test(body)
357    return isFed || expands ? whole : rest
358  })
359}
360
361async function checkBash(run: Run, command: string, cwd: string): Promise<Found | undefined> {
362  // Code fed to python, node and the like is not shell: a word such as `set` there dumps nothing
363  for (const [segment, words] of simpleCommands(dropHeredocs(command, SHELLS))) {
364    if (envDump(words) || printsSecretVar(segment, words)) return { reason: ENV_REASON, call: segment.trim(), file: undefined }
365  }
366  let cwds = [cwd]
367  for (const [segment, words] of simpleCommands(dropHeredocs(command))) {
368    const name = basename(words[0] ?? '')
369    const isMessage = name === 'gh' || name === 'git'
370    if (name === 'cd' && words.length === 2) {
371      // a cd inside ( ) leaves the outer cwd as it was
372      const more: string[] = []
373      for (const c of cwds) more.push(...(await paths(run, words[1] ?? '', c)))
374      cwds = [...new Set([...cwds, ...more])]
375    }
376    const flag = SHELLS.test(name) ? words.findIndex((w, i) => i > 0 && /^-[A-Za-z]*c[A-Za-z]*$/.test(w)) : -1
377    const script = flag > 0 ? words[flag + 1] : undefined
378    if (script !== undefined) {
379      for (const c of cwds) {
380        const found = await checkBash(run, script, c)
381        if (found) return found
382      }
383    }
384    let text = segment
385    if (isMessage) {
386      text = words.filter((w, i) => !(i > 0 && MESSAGE_FLAGS.includes(words[i - 1] ?? '')) && !/^--(?:message|title|body)=/.test(w)).join(' ')
387    }
388    const mention = MENTION.exec(text)
389    if (mention && !allowed(words)) return { reason: REASON, call: segment.trim(), file: mention[0] }
390    // A recursive search of a directory such as ~/.codex prints lines of the secret files inside it
391    if (['grep', 'egrep', 'rg'].includes(name) && !allowed(words)) {
392      let hit: string | undefined
393      for (const a of operands(name, words).operands) {
394        const found: string[] = []
395        for (const c of cwds) found.push(...(await paths(run, a, c)))
396        if (found.some(p => holdsSecret(run, p))) {
397          hit = a
398          break
399        }
400      }
401      if (hit) return { reason: REASON, call: segment.trim(), file: `a file under ${hit}` }
402      const held = searchesCwd(name, words) ? cwds.find(c => holdsSecret(run, c)) : undefined
403      if (held) return { reason: REASON, call: segment.trim(), file: `a file under ${held}` }
404    }
405    if (!allowed(words)) {
406      for (const [i, a] of words.entries()) {
407        if (i === 0 || a.startsWith('-') || (isMessage && MESSAGE_FLAGS.includes(words[i - 1] ?? ''))) continue
408        const found = new Set<string>()
409        for (const c of cwds) for (const p of await paths(run, a, c)) found.add(p)
410        if (/[*?[]/.test(a)) {
411          for (const p of [...found]) for (const g of await glob(run.io, p)) for (const q of await paths(run, g, '/')) found.add(q)
412        }
413        if ([...found].some(p => isSecret(run, p))) return { reason: REASON, call: segment.trim(), file: a }
414      }
415    }
416  }
417  return undefined
418}
419
420async function find(run: Run, e: Tool, cwd: string): Promise<Found | undefined> {
421  if (e.tool === 'Bash') return checkBash(run, String(e.command), cwd)
422  if (e.tool === 'Read' || e.tool === 'Edit' || e.tool === 'Write') {
423    const path = String(e.file_path)
424    if ((await paths(run, path, cwd)).some(p => isSecret(run, p))) return { reason: REASON, call: `${e.tool} ${path}`, file: path }
425  }
426  if (e.tool === 'Grep' && e.output_mode === 'content') {
427    const path = typeof e.path === 'string' && e.path !== '' ? e.path : '.'
428    for (const p of await paths(run, path, cwd)) {
429      let holds = isSecret(run, p) || holdsSecret(run, p)
430      for (const name of SECRET_NAMES) holds ||= await exists(run.io, join(p, name))
431      if (holds) return { reason: REASON, call: `Grep (output_mode content) in ${path}`, file: `a file under ${path}` }
432    }
433    const pattern = e.glob
434    if (typeof pattern === 'string' && pattern !== '' && SECRET_NAMES.includes(pattern.replace(/^(?:\*\*\/)+/, '').toLowerCase())) {
435      return { reason: REASON, call: `Grep (output_mode content) in ${path} with glob ${pattern}`, file: pattern }
436    }
437  }
438  return undefined
439}
440
441/** The reason to refuse the call, the call as the log names it, and the rule and target the event ledger records; undefined to let it run. */
442export async function secretFiles(
443  io: GuardIo,
444  e: Tool,
445  cwd: string,
446): Promise<{ op: string; reason: string; rule: 'env-dump' | 'secret-file'; target: string } | undefined> {
447  const home = await expanduser(io, '~')
448  const run: Run = { io, home, homes: [...new Set([home, await realpath(io, home)].map(h => h.toLowerCase()))] }
449  const found = await find(run, e, cwd)
450  if (found === undefined) return undefined
451  const values: Record<string, string> = { call: found.call, file: String(found.file) }
452  return {
453    op: found.call,
454    reason: found.reason.replace(/\{(call|file)\}/g, (_, key: string) => values[key] ?? ''),
455    rule: found.reason === ENV_REASON ? 'env-dump' : 'secret-file',
456    target: e.tool === 'Bash' ? found.call : String(found.file),
457  }
458}
459