SLOPSHOPPER

claim-verifier

Judge each final answer for factual claims no tool result supports

commandtoastmodel
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · claim-verifier
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────────╮ │ claim-verifier │ ⏺ Read(src/auth.ts) │ claim-verifier: no flag #1 (0 in this │ ⎿ Read 6 lines │ session) │ ⏺ 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 › /claim ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

kokatsu's dotfiles

CI NixOS Home Manager Checked with Biome

Dotfiles repository for managing shell and tool configurations across macOS and Linux systems using Nix + Home Manager with Flakes.

Features

  • 🔄 Declarative & Reproducible - All configurations managed through Nix Flakes
  • 🖥️ Multi-platform - Supports Linux (x86_64, aarch64) and macOS ARM (Apple Silicon)
  • 📦 Unified Package Management - All CLI tools installed via Home Manager
  • 🔗 Automated Symlinks - Dotfiles automatically linked to ~/.config/

Setup

Prerequisites

  • macOS (arm64) or Linux (x86_64 / aarch64)
  • curl (for Nix installer)

Installation

# Install Nix (using Determinate Systems installer)
curl --proto '=https' --tlsv1.2 -sSf -L https://install.determinate.systems/nix | sh -s -- install

# Clone the repository
git clone https://github.com/kokatsu/dotfiles.git ~/dotfiles
cd ~/dotfiles

# Build and activate Home Manager configuration
DOTFILES_DIR="$PWD" nix run home-manager -- switch --flake . --impure

Usage

Apply Configuration Changes

# User environment (packages / dotfiles) on both Linux and macOS.
# Set this to the actual repository path on each PC.
DOTFILES_DIR="$HOME/dotfiles" home-manager switch --flake "$HOME/dotfiles" --impure

# macOS system settings + Homebrew (quit Chrome first: casks get upgraded in place)
sudo HOSTNAME=$(hostname -s) DOTFILES_DIR="$HOME/dotfiles" darwin-rebuild switch --flake "$HOME/dotfiles" --impure

Update Packages

nix flake update
deno run --allow-all scripts/update-deno-deps.ts --all
DOTFILES_DIR="$HOME/dotfiles" home-manager switch --flake "$HOME/dotfiles" --impure

Development

nix develop        # Enter development shell with every linter / formatter
just check         # Format check, lint, typos, script tests, and flake evaluation
just fmt           # Format everything (Nix, Lua, shell, TOML, YAML, JSON, TypeScript)
just               # List all recipes

Lefthook runs a subset of these on commit and push (formatters, linters, gitleaks, commitlint); the script tests and flake evaluation only run through just check and CI.

CI builds the flake checks on Linux x86_64, Linux ARM64, and macOS ARM64. Linux checks also build a WSL Home Manager configuration and verify its generated watch services, timers, and command paths. They do not start WSL or activate the configuration on Windows. MoonBit is installed only on Linux x86_64 and macOS ARM64 because the pinned MoonBit overlay does not support Linux ARM64.

Directory Structure

.
├── flake.nix          # Flake outputs and Home Manager/nix-darwin builders
├── flake.lock         # Locked dependencies for reproducibility
├── justfile           # Task runner: checks, formatters, tests
├── nix/
│   ├── home/          # Home Manager modules (packages, files, programs, services)
│   ├── darwin/        # macOS system and Homebrew configuration
│   └── overlays/      # Custom packages and upstream workarounds
├── bin/               # User scripts, linked to ~/.local/bin/scripts and on PATH
├── scripts/           # Test and helper scripts used by just and CI
├── karabiner-config/  # Karabiner-Elements rules written with karabiner.ts
└── .config/           # Dotfile sources linked by Home Manager
    ├── zsh/           # Zsh shell configuration
    ├── nvim/          # Neovim configuration
    ├── wezterm/       # WezTerm terminal configuration
    ├── claude/        # Claude Code settings, hooks, and skills
    └── ...            # Other tool configurations

Static application settings live in nix/home/programs/. Home Manager generates Git, Ghostty, ripgrep, Starship, Yazi, Biome, markdown-oxide, ov, Taplo, psql, Vim, Claude Code keybindings, and the Codex base configuration from Nix. Edit these modules, then run home-manager switch --flake . --impure to apply them.

Yazi plugins come from nixpkgs yaziPlugins where available; the remaining plugins and flavors are vendored under .config/yazi/. All are installed through programs.yazi; update them via nix flake update or in Git instead of using ya pkg. Yazi's init.lua and git-changes.sh also need home-manager switch --flake . --impure after editing to apply the changes. Lua, shell scripts, and repository tooling configurations remain under .config/.

Neovim's lazy.nvim, peek.nvim, blink.cmp, Pkl plugin, and Tree-sitter parsers are built by Nix and linked under ~/.local/share/nvim/nix-plugins/. Other Lua plugins still use lazy-lock.json and :Lazy. zeno.zsh uses fixed Deno/npm dependencies from the Nix store. Ruby LSP and its Rails/RuboCop gems are fixed in nix/ruby/ruby-lsp/; Neovim uses RUBY_LSP_COMMAND to avoid a user-installed gem taking precedence. Karabiner's managed Default profile is built by Nix, then merged into the writable JSON while retaining other profiles and GUI settings.

Renovate PRs regenerate Deno locks/hashes and Ruby gemsets in pr.yml.

Claude Code's settings.json keeps its writable repository link. Codex receives a writable copy of its generated configuration and preserves the existing local state sections during activation.

License

MIT. Third-party notices are listed in THIRD_PARTY_LICENSES.md.

Source 3 files
hooks/register.ts 182 lines
1import type { EngineInterface, ModelTextBlock, Register } from "claude-code";
2import { lineAppender } from "./append.ts";
3import { buildEvidence } from "./evidence.ts";
4
5const appendLine = lineAppender();
6
7const SYSTEM =
8  `You audit one assistant response for unsupported factual claims. The user message holds the evidence and then the response to judge. In the evidence, [user] is what the person typed, [assistant] is what the assistant said in an earlier turn, [tool ...] is a tool call with its output, and [context] is text the harness injected (environment, hook output, skill bodies, memory, instruction files).
9
10Flag a sentence only if it asserts a fact about code, files, specs, external services or tools, or the assistant's own past actions, and nothing in the evidence supports it. Support is [user] text, tool outputs, and [context] text that reports something checked or produced in this session (environment facts, hook output, skill bodies). Memory files (MEMORY.md and the memory notes it indexes) and instruction files (CLAUDE.md, AGENTS.md, rules) are context only: they tell you what the assistant was told, not what is true now, so a factual claim resting only on them is unsupported. This includes negative and capability claims (that something does not exist, cannot be done, or is not visible to the assistant) and claims about how Claude Code, its hooks and tools, or the assistant's own context work. An explanation or reason given in the response is not support, and neither is [assistant] text. Use [assistant] text only to check a sentence about what the assistant said earlier (e.g. 前回の回答で…と書いた); a sentence that repeats a fact from it is judged as if that text were absent. A search with zero results does not support a claim that something does not exist. Earlier tool outputs are truncated: if a claim concerns the subject of an earlier tool call and its support could lie in the truncated part, do not flag it.
11
12Also flag a sentence that leaves a question open (labels it unverified, inferred, unknown or not yet checked, e.g. 推定, 未確認, 確かめていない, 分からない) or hands it to the person or a later step to check, when the assistant could have settled it with its own tools: either the question is about the code being worked on and is the kind reading its code or config settles (what a function reads or writes, which inputs a feature accepts, whether a branch exists, where a value comes from), or the evidence names a local file of the same repository that likely answers it (notes or records from earlier work, a local copy of docs). For this rule, a record named in [context] or in any tool output counts as reason to flag, even though it is not support under the first rule. Do not flag under this rule a question that reading cannot settle, such as how a running system behaves or what live data holds; a repository or document the assistant can read with its tools, public or one the user has access to, including the published source of a tool or library the response names, does not count as unavailable; a sentence that separates what was checked from what was not is exempt only when the unchecked part is of that kind. For each sentence flagged under this rule, say what to read or search instead of what is missing.
13
14Do not flag, except under the rule above: a claim whose own sentence labels it as unverified, inferred, or a guess in any language (e.g. 未確認, 未検証, 推定); a sentence that explicitly says it covers everything that follows, or names the sentences it covers (e.g. 以下はすべて未検証), exempts those sentences, but a heading alone or a label on an unrelated sentence does not; opinions, recommendations, and plans; restatements of what the user said; small talk.
15
16Also do not flag these, which need no support: long-established, widely documented behavior of a mainstream technology, standard or product (what a Docker named volume keeps, PostgreSQL's identifier length limit, that HDMI carries no power), unless the claim concerns this environment's state or configuration, Claude Code, Codex or other AI agent tools including the assistant's own, what a given setting does, or a specific CLI flag, option, config key, API field, version or default value; a conclusion that follows directly from what the evidence shows, with no other reading a careful engineer would weigh (a docker binary at /usr/bin came from the distribution's packages), though a claim about a whole file, list or set of cases drawn from the part that was read is not such a conclusion; a side remark that neither the response's conclusion nor the person's next step depends on (who created a file, why the assistant left something alone), though a number, count, file:line, quote, or only/none/all claim is never a side remark.
17
18Apart from those exemptions, your own knowledge is not support, even when you believe the claim is true; judge only by the evidence. Judge only evidential support; never request any other work. Reply with JSON only: {"ok": true} when nothing is flagged, otherwise {"ok": false, "reason": "<every flagged sentence, quoted, each followed by what is missing>"}, the reason written in the language of the response.`;
19
20type Verdict = { ok: boolean; reason?: string };
21
22function parseVerdict(text: string): Verdict | undefined {
23  const json = text.match(/\{[\s\S]*\}/)?.[0];
24  if (json === undefined) return undefined;
25  try {
26    const v = JSON.parse(json) as Verdict;
27    return typeof v.ok === "boolean" ? v : undefined;
28  } catch {
29    return undefined;
30  }
31}
32
33async function logPath($: EngineInterface, sessionId: string): Promise<string> {
34  return `${await $.env.get(
35    "HOME",
36  )}/.local/state/claim-verifier/${sessionId}.jsonl`;
37}
38
39async function judge(
40  $: EngineInterface,
41  sessionId: string,
42  prompt: ModelTextBlock[],
43  evidenceChars: number,
44  latestChars: number,
45  rewrite: boolean,
46): Promise<Verdict | undefined> {
47  const started = Date.now();
48  const judged = await $.model.complete({
49    model: "sonnet",
50    system: [{ text: SYSTEM, cache: true }],
51    prompt,
52    maxTokens: 4096,
53    effort: "high",
54    timeoutMs: 110_000,
55  });
56  const mineMs = Date.now() - started;
57  const verdict = judged.isAnswered ? parseVerdict(judged.text) : undefined;
58  if (verdict?.ok === false) {
59    // A log row is one line: a newline inside it is drawn as U+FFFD.
60    const lines = (verdict.reason ?? "").split("\n").filter((line) =>
61      line.trim() !== ""
62    );
63    for (const line of ["根拠を確認できなかった文:", ...lines]) $.ui.log(line);
64  }
65
66  const path = await logPath($, sessionId);
67  const entry = {
68    at: new Date().toISOString(),
69    evidenceChars,
70    latestChars,
71    rewrite,
72    mineMs,
73    usage: judged.usage,
74    mine: verdict ??
75      {
76        error: judged.isAnswered
77          ? `unparsable: ${judged.text.slice(0, 200)}`
78          : judged.reason,
79      },
80  };
81  await appendLine(
82    {
83      exists: (p) => $.fs.exists(p),
84      read: (p) => $.fs.read(p),
85      write: (p, text) => $.fs.write(p, text),
86    },
87    path,
88    JSON.stringify(entry),
89  );
90  return verdict;
91}
92
93export const register: Register = (on) => {
94  on("session.start", async ($, e, next) => {
95    await $.command.register({
96      name: "claim",
97      description: "Put a claim-verifier flag into the prompt box to send",
98      argumentHint: "[n: 1 is the latest flag]",
99      immediate: true,
100    });
101    return next(e);
102  });
103
104  // The flag goes into the prompt box, never into the command's output, which
105  // the model would read: the person decides what, if anything, is sent.
106  on("command.run", { command: "claim" }, async ($, e) => {
107    const n = e.args.trim() === "" ? 1 : Number(e.args.trim());
108    const path = await logPath($, await $.session.id());
109    const log = (await $.fs.exists(path)) ? await $.fs.read(path) : "";
110    const flags = log.split("\n").filter((line) => line !== "")
111      .map((line) => JSON.parse(line) as { mine?: Verdict })
112      .flatMap((entry) => entry.mine?.ok === false ? [entry.mine] : []);
113    const flag = Number.isInteger(n) && n >= 1 ? flags.at(-n) : undefined;
114    if (flag === undefined) {
115      $.ui.toast(
116        `claim-verifier: no flag #${
117          e.args.trim() || 1
118        } (${flags.length} in this session)`,
119      );
120      return {};
121    }
122    const filled = await $.prompt.fill({
123      text:
124        `claim-verifier が根拠を確認できなかった文です。確認してください。\n${
125          flag.reason ?? ""
126        }`,
127      mode: "insert",
128    });
129    if (!filled.isFilled) {
130      $.ui.toast(
131        `claim-verifier: the prompt box did not take the flag (${
132          filled.refusal ?? "refused"
133        })`,
134      );
135    }
136    return {};
137  });
138
139  on("classic.Stop", async ($, e, next) => {
140    const messages = await $.session.messages({ as: "api" });
141    const answer = e.last_assistant_message ??
142      messages.findLast((m) => m.role === "assistant")?.content
143        .flatMap((b) => b.type === "text" ? [String(b.text)] : []).join("\n") ??
144      "";
145    const { earlier, latest, text: evidence, latestChars } = buildEvidence(
146      messages,
147    );
148    const prompt: ModelTextBlock[] = [
149      ...earlier.map((text, i) =>
150        i === earlier.length - 1 ? { text, cache: true as const } : { text }
151      ),
152      { text: latest },
153      { text: ["## Response to judge", answer].join("\n\n") },
154    ];
155
156    let verdict: Verdict | undefined;
157    try {
158      verdict = await judge(
159        $,
160        e.session_id,
161        prompt,
162        evidence.length,
163        latestChars,
164        e.stop_hook_active,
165      );
166    } catch (error: unknown) {
167      $.ui.log(`claim-verifier: ${String(error)}`, { to: "debug" });
168    }
169    const result = await next(e);
170    // One send-back per turn: the rewrite is judged and logged, never blocked,
171    // so a judge that keeps flagging cannot hold the turn open.
172    if (verdict?.ok !== false || e.stop_hook_active) return result;
173    return {
174      ...result,
175      block:
176        `根拠を確認できなかった文、または手元で確かめられるのに未確認とした文があります。ツールで確認してから、直前の回答全体を書き直してください。ツールで読める情報では確かめようがない文に限り、消すか未検証と明記してかまいません。この書き直しで、確かめていない数値・行番号・引用を新たに足さないでください。指摘されていない文の但し書きは残してください。読み手はこの書き直しだけを読むので、指摘への返答ではなく、元の回答に代わる完全な回答にしてください。\n${
177          verdict.reason ?? ""
178        }`,
179    };
180  }).catch((_$, e, next) => next(e));
181};
182
hooks/append.ts 20 lines
1export type LineFile = {
2  exists: (path: string) => Promise<boolean>;
3  read: (path: string) => Promise<string>;
4  write: (path: string, text: string) => Promise<void>;
5};
6
7// `$.fs` has no append, so each line is a read-modify-write; chaining them
8// keeps judges that finish close together from overwriting each other.
9export function lineAppender() {
10  let last: Promise<void> = Promise.resolve();
11  return (file: LineFile, path: string, line: string): Promise<void> => {
12    const run = last.then(async () => {
13      const previous = (await file.exists(path)) ? await file.read(path) : "";
14      await file.write(path, previous + line + "\n");
15    });
16    last = run.catch(() => {});
17    return run;
18  };
19}
20
hooks/evidence.ts 130 lines
1// `ApiMessage` is not exported by 'claude-code', so the shape is restated here.
2export type Block = { type: string; [field: string]: unknown };
3export type Message = {
4  role: "user" | "assistant";
5  content: readonly Block[];
6};
7
8export const EARLIER_CHARS = 30000;
9
10const REMINDER = "<system-reminder>";
11const STOP_FEEDBACK = "Stop hook feedback:";
12
13function clip(text: string, limit: number | undefined): string {
14  if (limit === undefined || text.length <= limit) return text;
15  return `${text.slice(0, limit)}\n[... ${
16    text.length - limit
17  } more chars truncated]`;
18}
19
20function textOf(block: Block): string {
21  return typeof block.text === "string" ? block.text : "";
22}
23
24// The harness wraps everything it injects in <system-reminder>, so an unwrapped
25// text block in a message without tool results is what the person typed.
26function isPrompt(m: Message): boolean {
27  return m.role === "user" &&
28    !m.content.some((b) => b.type === "tool_result") &&
29    m.content.some((b) => {
30      const text = textOf(b).trimStart();
31      return b.type === "text" && text !== "" &&
32        !text.startsWith(REMINDER) && !text.startsWith(STOP_FEEDBACK);
33    });
34}
35
36export function latestTurnStart(messages: readonly Message[]): number {
37  for (let i = messages.length - 1; i >= 0; i--) {
38    const m = messages[i];
39    if (m !== undefined && isPrompt(m)) return i;
40  }
41  return 0;
42}
43
44function resultText(content: unknown): string {
45  if (typeof content === "string") return content;
46  if (!Array.isArray(content)) return "";
47  return content.map((b: Block) =>
48    b.type === "text" ? textOf(b) : `[${b.type}]`
49  )
50    .join("\n");
51}
52
53type ToolUse = { name: string; input: unknown };
54
55function renderAnswer(m: Message): string[] {
56  return m.content.flatMap((b) => {
57    const text = textOf(b);
58    return b.type === "text" && text.trim() !== ""
59      ? [`[assistant]\n${text}`]
60      : [];
61  });
62}
63
64function render(
65  m: Message,
66  uses: ReadonlyMap<string, ToolUse>,
67  limit: number | undefined,
68): string[] {
69  if (m.role === "assistant") return [];
70  return m.content.flatMap((b) => {
71    if (b.type === "text") {
72      const text = textOf(b);
73      const trimmed = text.trimStart();
74      if (trimmed === "") return [];
75      const injected = trimmed.startsWith(REMINDER) ||
76        trimmed.startsWith(STOP_FEEDBACK);
77      return [`${injected ? "[context]" : "[user]"}\n${text}`];
78    }
79    if (b.type === "tool_result") {
80      const use = uses.get(String(b.tool_use_id));
81      return [[
82        `[tool ${use?.name ?? "unknown"}${b.is_error ? " (error)" : ""}]`,
83        `input: ${clip(JSON.stringify(use?.input ?? null), limit)}`,
84        `output:\n${clip(resultText(b.content), limit)}`,
85      ].join("\n")];
86    }
87    return [`[${b.type}]`];
88  });
89}
90
91// The prompt cache matches only a prefix that ends where a block ended in an
92// earlier request, so each earlier turn is its own block: the next judgment
93// appends one block and finds the previous breakpoint one block back.
94export function buildEvidence(
95  messages: readonly Message[],
96): { earlier: string[]; latest: string; text: string; latestChars: number } {
97  const uses = new Map<string, ToolUse>();
98  for (const m of messages) {
99    for (const b of m.content) {
100      if (b.type === "tool_use") {
101        uses.set(String(b.id), { name: String(b.name), input: b.input });
102      }
103    }
104  }
105  const start = latestTurnStart(messages);
106  const turns: string[][] = [];
107  for (const m of messages.slice(0, start)) {
108    if (turns.length === 0 || isPrompt(m)) turns.push([]);
109    turns.at(-1)?.push(
110      ...(m.role === "assistant"
111        ? renderAnswer(m)
112        : render(m, uses, EARLIER_CHARS)),
113    );
114  }
115  const earlier = [
116    `## Earlier turns (tool inputs and outputs truncated to ${EARLIER_CHARS} chars each; [user], [assistant] and [context] are whole)`,
117    ...turns.filter((t) => t.length > 0).map((t) => t.join("\n\n")),
118  ];
119  const latestText = messages.slice(start).flatMap((m) =>
120    render(m, uses, undefined)
121  ).join("\n\n");
122  const latest = ["## Latest turn (complete)", latestText].join("\n\n");
123  return {
124    earlier,
125    latest,
126    text: [...earlier, latest].join("\n\n"),
127    latestChars: latestText.length,
128  };
129}
130