SLOPSHOPPER

fog-map

Exploration map: the repository as a tree under fog, cleared where Claude read, marked where it edited, made a file or hit an error, with what the edits may…

paneguardcommandtoaststatusprocess
★ 1v0.1.7MITupdated 2026-10-24simota/claude-mods/mods/fog-map
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · fog-map
│ ┃ 探索マップ ✕ › fix the failing auth test and add an audit log╭──────────────────╮ │ ┃ 🗺 探索率 100% ████████████████████ 読 0 … │ fog-map │ │ ┃ app · feat/auth-refresh ⏺ Read(src/auth.ts) │ 🗺 新しい区域を開拓: │ │ ┃ ▾ src/ ⎿ Read 6 lines │ src/ │ │ ┃ ✚ audit.ts +6 −0 新規 ⏺ Update(src/auth.ts) ╰──────────────────╯ │ ┃ ● auth.ts +2 −1 ⎿ Added 2 lines, removed 1 line ╭───────────────╮ │ ┃ ✚ cache.ts +8 −0 新規 ★ ⏺ Bash(bun test) │ fog-map │ │ ┃ ░ 未踏 ○ 読んだ ● 編集 ✚ 新規 ✗ エラー ⎿ 3 pass, 1 fail │ 🗺 探索率 100% │ │ ┃ ★ 直前 │ 到達 │ │ ● Done. refresh now rejects expired claims and logs╰───────────────╯ │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /map │ ⎿ fog-map: 🗺 探索率 100% · 2/2 │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · 探索マップ
🗺 探索率 100% ████████████████████ 読 0 · 編 3 · ✗ 0 / 2 app · feat/auth-refresh ▾ src/ ✚ audit.ts +6 −0 新規 ● auth.ts +2 −1 ✚ cache.ts +8 −0 新規 ★ ░ 未踏 ○ 読んだ ● 編集 ✚ 新規 ✗ エラー ★ 直前
README

claude-mods

English | 日本語

Personal Claude Code mods (function-hook plugins), published as one marketplace.

ModWhat it does
agent-paneLive pane of the session's subagents: running ones with elapsed time, finished ones with result and duration
done-gateFlags unverified edits, stops repeated failing commands, and blocks git --no-verify
sandbox-lensTallies sandbox denials seen in Bash output and reports them with /sandbox-report
todo-agentCollects #TODO(agent) follow-ups from Claude's replies into a per-project list with a /todos pane.
tool-rowRedraws finished tool-call rows in the terminal as one compact line with a Nerd Font icon, Gruvbox colors and a short stat
image-previewThumbnails of the images a session writes, reads or generates: under the tool's row in the terminal, and in an /images pane
self-auditAfter each turn, a cached fork of the conversation audits Claude's own reply against the CLAUDE.md reporting rules and flags violations above the prompt
browser-camLive pane of the browser Claude drives: the latest screenshot from Claude in Chrome, the page URL and the recent actions
prompt-coachHolds back a typed prompt that looks ambiguous (no done-condition, unclear target) and offers guesses at what it meant, sending it as is, or adding one; on by default
loopbackFeeds what self-audit, done-gate and sandbox-lens found back to Claude beside the next prompt, instead of only showing it to the person, skipping rules hit-rate found mostly wrong; off by default
zukanError book: catches the errors Bash commands hit across sessions and repos, records what got past each one, and when one comes back tells Claude and the person how it was fixed last time
pr-lampThe current branch's pull request as a lamp: checks, review, unresolved threads and what is left before a merge, in the status line and a /pr pane; red checks and new review comments go to Claude beside the next prompt
fog-mapExploration map: the repository as a tree under fog, cleared where Claude read and marked where it edited, made a file or hit an error, with the importers an edit may have broken unseen; /map
assertion-guardCatches edits that weaken tests to pass: assertions removed, expectations loosened or rewritten, tests skipped, errors swallowed; asks Claude for the reason beside the edit
negative-spaceWhen an edit adds authorization, validation or error handling, lists the refusal and boundary-value tests no test touched this session covers; /negative-space
mutation-tap/mutate runs a mutation test limited to the lines changed since HEAD and lists the mutants the tests did not catch
perf-delta/perf compares a benchmark before and after (a saved baseline, or a git ref in a temporary worktree): median time, peak memory, spread, and whether the change beats the noise
port-lanternThe dev servers the session started: URL, port, whether each still listens, and their latest log lines, in the status line and /ports
artifact-shelfA shelf of what sessions made (CSV, PDF, HTML, video, patches…), tied to the call and request that made each; /shelf searches by kind, word and time
side-effect-ledgerA ledger of what a git diff never shows (push, publish, deploy, PRs, API writes, messages) with outcome, how to undo, and whether the undo was checked; /ledger
visual-diffCompares browser screenshots of the same URL and size before and after an edit: side by side, a map of changed cells, regions, and the edits in between; /vdiff
journey-traceRecords Claude's browser actions and the expected states as a replayable recipe; /journey md for a bug report, /journey e2e for a Playwright draft
hit-rateGives each finding of done-gate, assertion-guard, self-audit and zukan a later verdict from what the session did next, keeps each rule's precision across sessions, and names the rules loopback stops feeding; /hit-rate; off by default
token-lensChecks an element's actual colours, spacing and type against the project's design tokens and lists off-token values with the nearest token; /token-lens <selector>
kachiWhen a check you broke turns green after a real fix, the band above the prompt sweeps green once with a short click, and the result row keeps the score: how many tries, how long it stayed red. Silent the rest of the time, but for one dim line under a check's first red
cross-checkA second opinion from Codex in one press: the band above the prompt reviews the current diff with codex exec in its read-only sandbox, shows the top finding and the count, and puts the findings into the prompt for Claude to fix when asked; /codex lists them
ci-rehearsalCI before the push, in one press: the band above the prompt runs the push workflows locally with runthrough, shows the failing job and step with the count, and puts the failures and their log tails into the prompt for Claude to fix when asked; /ci lists every job
stack-dockThe repository's devrouter stack in one press: the band above the prompt says whether it is unset, stopped or up, starts it with devrouter up, shows each service's URL and health in the status line and /stack, and puts doctor's findings and the failing logs into the prompt for Claude to fix when asked

Install

At the prompt of a terminal session:

/plugin install <mod> --marketplace simota/claude-mods

From a shell:

claude plugin install <mod> --marketplace simota/claude-mods

This repository is private: installing needs read access on GitHub and a git credential for github.com on the machine (an SSH key, or gh auth login then gh auth setup-git).

Usage

Options are set with /plugin configure <mod>@simota-mods in a session, or from a shell:

echo '{"enabled":"true"}' | claude plugin configure <mod>@simota-mods --values-stdin

A change made with /plugin configure reloads the mod; one made from a shell applies after a restart. Bands above the prompt stack: each mod draws its row above what the others draw.

agent-pane

  • /agent-pane opens the pane: running subagents first with elapsed time, then finished ones with ✓/✗ and duration; a background run that was stopped shows ■ 停止. A background run that left the roster without a result shows ? 結果不明; a teammate or remote launch shows ↗ 起動済み(追跡外).
  • In a fullscreen terminal the pane opens by itself once per session, on the first Agent call (a reload does not reopen it).
  • The status line shows agents: N running while any run.

done-gate

Works on its own, no command:

  • A turn that edited files without a passing test, lint, typecheck or build afterwards leaves a band: 未検証の変更があります. It stays until a check succeeds or 閉じる is pressed; 検証させる puts in the prompt an ask for Claude to run the checks the edits touch and fix what fails, for you to send, as every band's ask does (the band stays until a check passes). Only the program a command runs counts (ls build, npm ci are not checks), and only when its exit status is the command's: the check is last, or only && follows it (npm test | tail does not count).
  • The second identical failure of the same Bash command tells Claude to stop retrying and diagnose the root cause (again after the command has succeeded in between).
  • Any git command with --no-verify (or a prefix of it from --no-ver), and git commit -n / -nm, is denied, also inside subshells, $(…), backticks, bash -c "…", eval and wrappers such as sudo/timeout. The value of an option (-m "…"), a comment or a heredoc never triggers it. So is a git command that moves its hooks for the run (-c core.hooksPath=…, --config-env core.hooksPath=…) or carries a hook manager's off switch in its environment (HUSKY=0, LEFTHOOK=0, pre-commit's SKIP=…), or moves the hooks through config in its environment (GIT_CONFIG_KEY_n=core.hooksPath, GIT_CONFIG_PARAMETERS). ANSI-C quoting ($'--no-\x76erify'), env -S "…", bash -c -- '…' and a shell reading its script from stdin (bash <<< '…', a heredoc, echo '…' | sh) are read through. It is a best-effort guard: git aliases (git ci -n), a hook path written into config beforehand and an environment exported by an earlier command are not detected.

sandbox-lens

  • /sandbox-report lists the sandbox denials seen in Bash output, for this session and all time: denied hosts and paths, counts, last seen, an example command, and which setting would allow each.
  • /sandbox-report reset clears the record.
  • Hints only: it never changes sandbox settings. A loopback or private address keeps its port in the hint (127.0.0.1:3000), since an entry without a port opens every port.
  • A <sandbox_violations> block, and Operation not permitted lines a program printed about itself, are read. For a command that succeeded or was interrupted, the block is taken from where the engine puts it, apart from the command's own output, so one inside a shown file or page is ignored even when it ends the output. A failed command keeps only its error text: the block that ends it (before an agent-proxy note) is read, and there a block the command printed itself cannot be told from the harness's. Credentials in the example command (tokens, passwords, Authorization/Cookie and other credential headers such as X-API-Key, URL userinfo, keys in env assignments including run-together names such as PGPASSWORD, known key shapes) are masked. Each section shows the top 10; when the record is full (200), the least recently seen entry gives way.

todo-agent

  • Lines starting with #TODO(agent): <action> (after an optional quote or list bullet) in Claude's main-loop replies are collected per project (repo root or cwd). A mention inside a sentence, a table or inline code is not a TODO; subagent replies are ignored.
  • /todos opens the pane of this project's open items, each with a 完了 button.
  • /todos all lists every project's open items as text, marked as stored data.
  • The status line shows TODO(agent): N while the project has open items.

tool-row

Finished tool calls are drawn as one compact line with a Nerd Font icon: Edit/Write path +A −D, Read with line count, Bash (red on error), Agent, web and MCP calls. The result block under a compacted row is hidden, so a call is one line; an errored result stays. A row another mod decorated (an image-preview thumbnail) is left as it is, result included. Runs Claude Code folds into one count line (Read 3 files, ran 2 shell commands) stay folded. Terminal only.

OptionDefault
compacttrueOff leaves every row and result as Claude Code draws them

image-preview

  • Images a session writes, reads, or that a Bash command produces (png, jpg, jpeg, webp, gif) get a thumbnail under that tool's row in the terminal (kitty graphics: Ghostty, kitty).
  • /images opens a pane, newest first; h/l step through them.
  • Non-PNG files are converted with macOS sips after the tool result has gone back, so tool calls never wait on it. Converted files live in a private cache ($TMPDIR or ~/.cache), newest 50 kept. A killed session's folder is removed by a later session's start once a day untouched; a running session touches its own every hour (again after a plugin reload), so it is kept while idle, though not across a day the machine sleeps.
  • A Bash command and its output are searched for image paths in time linear in their length, before the result goes back. A path split at spaces (/tmp/a b/x.jpg) joins at most 8 preceding pieces and 4096 characters; the first 64 paths named are read, and of those the first 4 that exist are shown.
OptionDefault
inlinetrueThumbnail under the tool row
maxRows12Rows a thumbnail may take, 1 to 60

self-audit

After each reply of at least minChars characters, one tool-less fork of the conversation (served mostly from the prompt cache), given the reply itself as quoted data, checks it against the CLAUDE.md rules: claims done without evidence, first line not the result, unverified assertions, bypassed checks, scope inflation. Only violations of the five rules whose quote is found in the reply are kept (a made-up quote or rule is dropped); the quote is compared past markdown marks, bullets, curly quotes, case, spacing and a closing full stop, and one shortened with … is found piece by piece. Violations show in red above the prompt, in one row (the first and how many); 詳細 or /self-audit opens the pane with quotes and the fork's token use. Results belong to the latest reply only: when it was not audited, the pane says why.

OptionDefault
enabledtrue
minChars200Shorter replies are not audited

Cost: one extra request per turn on the session's model, plus the reply text (up to 12,000 characters) as uncached input; a cold cache (after 5 minutes idle or a model switch) resends the whole conversation.

browser-cam

  • While Claude drives a browser (Claude in Chrome, Claude Browser, or a remote device's browser), a pane shows the latest screenshot, the page title and URL, and the last 8 actions with ✓/✗. The URL comes only from the navigate call or the tab tools' own header, never from page text. Text typed or filled in is shown as its length only (type ‹7文字›, counted up to 10,000), since the field may be a password; a URL's secrets (token parameters, userinfo, key-shaped parts) are masked.
  • /cam toggles the pane; in a fullscreen terminal it opens by itself once per session, on the first browser call. Screenshots are decoded only while the pane is open, and written to a private per-session folder that is removed at session end. A killed session's folder is removed by a later session's start once a day untouched; a running session touches its own every hour (again after a plugin reload), so it is kept while idle, though not across a day the machine sleeps.
  • The desktop app shows the title and URL, a caption and the actions, without the picture.
OptionDefault
autoOpentrueOpen on the first browser call (fullscreen terminal)

prompt-coach

On by default (enabled: false turns it off). A typed prompt that looks ambiguous (no done-condition and an unclear target, or only evaluative words like いい感じ) is held back, and a band shows what is missing with up to three guesses at what it meant (judged along the lines of the clarify skill: the likeliest reading first, each a different deliverable with a checkable done-condition):

  • a / b / d: a guess goes into the prompt to edit and send (not held again)
  • s: このまま送る sends it unchanged
  • e: 補足して送る puts it back with 完了条件: to fill in (not held again)
  • q: 閉じる puts it back in the prompt

Typing another prompt instead sends that one and puts the held text back into the prompt. The held text is never lost: when a send fails or is dropped beneath, or putting words back fails, it stays held with its band (unless another prompt was held since) and its words are shown in a toast; a prompt still held at /clear goes straight back into the box, and one held when the session quits comes back at this project's next interactive session start. Words go into an empty box as they are, and are appended after a draft typed meanwhile on a line of their own, never over it.

Slash commands, prompts under 12 or over 1500 characters, prompts with any attachment or an @ mention, prompts sent by a plugin, and prompts typed while a turn runs are not judged. A timeout or error sends the prompt unchanged; the same text is not held twice (within the last 50 judged). Sending can wait up to timeoutMs.

OptionDefault
enabledtrue
modelclaude-haiku-5-5Judging model (alias or id)
timeoutMs3000500 to 3000

loopback

Off by default. When on, the new findings of the detector mods are attached to the next prompt typed at an idle prompt, as context only the model reads, so the correction does not wait for the person to retype it:

  • self-audit: the violations of the latest audited reply
  • done-gate: edits with no passing check after them (again after a check passed and new edits were left unverified; 閉じる on its band takes the flag down, and nothing is fed)
  • sandbox-lens: denials seen this session, each once

Each finding goes back once per session, marked as data that may be wrong for Claude to check before acting. A toast says how many went back and from where. Slash commands, hidden prompts, prompts sent by a plugin and prompts typed while a turn runs carry nothing. A detector that is not installed contributes nothing.

With hit-rate on, the rules it muted are not fed (sandbox-lens denials never are muted).

  • /loopback shows what was fed last and the self-audit repeat rate: of the rules fed back, how many self-audit flagged again on the next audited reply (all sessions). The rate is what the design is judged by (.genius/decisions/loopback.md). It also names the rules hit-rate muted.
OptionDefault
enabledfalse

Cost: the findings ride as extra input on the prompt they are attached to (each quote clipped to 300 characters, at most 12 findings).

zukan

An error book, kept across sessions and repos. When a Bash command fails, the error line is caught and numbered:

  • 📕 新種のエラー発見! No.042「…」 — a kind not seen before
  • 📙 No.017 再会(3回目・未解決) — seen before, nothing known to get past it
  • ` 📗 既知 No.017(3回目)— 前回: sandbox 外で git push origin main ` — seen before with a fix: Claude also reads, beside the tool's result, where it was seen and what got past it (marked as a past record to check, not an instruction)

A fix is learned when the same program and subcommand (git push, pnpm install; read past a leading cd, export or source, so cd app && npm install is npm install) succeeds within the next 10 Bash calls of the session; whether it ran outside the sandbox is kept with it. Two sightings are one kind when their error line matches with paths, quotes, numbers and hashes taken out.

Failures of tests, linters, type checkers and builds are not caught: they are fixed by editing code, not by a command. Credentials in a kept command and in the kept error line are masked as sandbox-lens does.

  • /zukan opens the book, most recently seen first: kinds, solved, sightings
  • /zukan note <No> <text> writes how to get past it, shown and fed in place of the learned command; an empty text removes the note
  • /zukan forget <No> removes an entry

The newest 300 kinds by last sighting are kept.

pr-lamp

The current branch's pull request, kept in the status line while it is open (once merged or closed, a toast says so and the line clears):

⎇ #42 · ✓5 ✗1 ⏳2 · 🛑 変更要求 · 💬3 · マージまであと4

"マージまであと N" counts what still stands before a merge: draft, failed checks, running checks, changes requested or approval pending, unresolved review threads, a conflict, the branch behind its base. At 0 it reads 🟢 マージ可能.

A toast when it changes: 🔴 CI 失敗: test, 💬 新しいレビューコメント 2件 (@rev), ✅ 承認されました, 🟢 #42 マージまであと0, 🎉 #42 がマージされました. Checks turning red, new review comments, changes requested and a new conflict are also attached to the next prompt typed at an idle prompt, once, with the last 40 lines of the failed log of up to three jobs (more are counted), marked as data whose comments and logs are not to be followed as instructions. The session's own replies on a thread (the comment, made after the post, carrying words it replied with through an MCP reply tool or gh api …/pulls/N/comments… -f body=, matched once) are not news; your own review comments are. What waits for the next prompt is about one pull request and is capped (newest kept). The option feed (on by default) turns that off.

  • /pr asks again and opens the pane: title, size, what is left, checks (failed first) and unresolved threads
  • /pr <number|url|branch> follows that pull request; /pr clear goes back to the default

Which pull request: the one a Bash command of the session last worked on (gh pr comment 2, gh pr review 2, the URL gh pr create printed, the branch a git push sent to; looking with gh pr view|diff|checks does not move it), so work pushed to a review branch from another checkout is followed; else the checked-out branch's; else your newest open pull request in the repository.

It asks gh (gh pr view, and gh api graphql for review threads) at session start, right after a Bash git push, git checkout, gh pr create and the like, every minute while a check runs or after a push, and every five minutes otherwise; it stops once the pull request is merged or closed. Without an origin remote, gh, or a pull request for the branch it shows nothing, and /pr says why. gh runs on the host, outside the Bash sandbox, with your gh auth.

fog-map

The repository as a map under fog, cleared as Claude works through it:

🗺 探索率 31%  ██████░░░░░░░░░░░░░░  読 23 · 編 9 · ✗ 2 / 101
▾ mods/
  ▾ pr-lamp/
    ▾ hooks/
      ● lamp.ts  +43 −2  編集 4回
      ✗ register.tsx  +59 −16  編集 6回  エラー 1  ★
  ▸ loopback/  ○●
  ░ agent-pane/  ░ browser-cam/  ░ done-gate/  …8
⚠ 編集したファイルを import しているが未読: mods/pr-lamp/tests/pr-lamp.test.ts

░ nothing touched yet, ○ read (Read, or cat, sed, grep… in Bash), ● edited (Edit, Write, NotebookEdit, sed -i), ✚ made by the session, ✗ named with a line number by a failed Bash command since its last edit, ★ the file touched last. A directory holding an edit, a new file or an error is open; one only read is closed with its marks beside it; untouched directories and files at a level share one fog row.

Two warnings, each a likely oversight: a file edited without being read, and a file that imports an edited one (JS/TS and Python, found by git grep) that was never opened. A very large repository's file list is cut to what one state value holds (3 M characters of paths), so it is still mapped, partly.

  • /map opens the pane
  • The status line shows 🗺 31% · ●9 · ✗2 · ⚠1 only while there is an error or a warning, and clears otherwise
  • A toast at 25, 50, 75 and 100% explored, and when an edit first reaches a new area (🗺 新しい区域を開拓: mods/zukan/)

The map is the session's, subagents' calls included; files outside the repository are not mapped. Explored is touched files over git ls-files, read again after a checkout, pull, mv or rm. Outside a git repository only the edit count is shown. A failed command's output is read once, in time linear in its length, before its result goes back.

assertion-guard

On each Edit, Write or MultiEdit it diffs the whole file before and after the call, so an assertion moved within the file is no removal, and one only reformatted (spaces around punctuation, a closing ; or ,, and '…' for "…" in languages that read them alike) is no rewrite; a change inside a string still is. In test files (by name, or a Rust file with a test module anywhere in it) it flags assertions removed or commented out, a strict matcher turned weak (toEqual → toBeDefined, assertEqual → assertTrue, toThrow(X) → toThrow()), an assertion now about a literal (expect(true).toBe(true)), the same assertion now expecting another value or the opposite (toBe → not.toBe), and tests skipped or focused (it.skip, @pytest.mark.skip, #[ignore], t.Skip). In any file but prose (.md, .txt, .rst, .adoc) it flags errors newly swallowed (catch {}, .catch(() => undefined), except: pass, || true); one named in a comment (// or || true, a doc block, /* … */, # …) is not.

Findings ride beside the edit's re

Source 3 files
hooks/register.tsx 215 lines
1import { atom, derive, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { FogFile, FogRepo } from '../types'
5import {
6  areaOf,
7  bar,
8  bashTouches,
9  capFiles,
10  countsOf,
11  editChange,
12  errorPaths,
13  importPattern,
14  inRepo,
15  milestoneOf,
16  rowsOf,
17  statusOf,
18  treeOf,
19  warningsOf,
20  withEdit,
21  withError,
22  withRead,
23} from './fog'
24
25const PANE = 'fog-map'
26const TITLE = '探索マップ'
27
28const repo = atom({ plugin: 'fog-map', key: 'repo' } as const, null as FogRepo | null)
29const touched = atom({ plugin: 'fog-map', key: 'touched' } as const, {} as Record<string, FogFile>)
30const focus = atom({ plugin: 'fog-map', key: 'focus' } as const, null as string | null)
31const importers = atom({ plugin: 'fog-map', key: 'importers' } as const, {} as Record<string, string[]>)
32const areas = atom({ plugin: 'fog-map', key: 'areas' } as const, [] as string[])
33const milestone = atom({ plugin: 'fog-map', key: 'milestone' } as const, 0)
34// Built from the file list once each time it changes, not on every call or every draw.
35const tracked = derive([repo], known => new Set(known?.files ?? []))
36const tree = derive([repo], known => treeOf(known?.files ?? []))
37
38const EDIT_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit'])
39// Commands after which the repository's file list is read again.
40const RESHAPES = /\bgit\s+(?:checkout|switch|pull|merge|rebase|mv|rm|stash)\b|\b(?:mv|rm|cp)\s/
41
42async function git($: EngineInterface, cwd: string, argv: string[]): Promise<string | undefined> {
43  const ran = await $.process.run(['git', ...argv], { cwd, timeoutMs: 15_000 }).catch(() => undefined)
44  return ran?.exitCode === 0 ? ran.stdout : undefined
45}
46
47/** The repository the session works in and its files; null outside a git repository. */
48async function loadRepo($: EngineInterface): Promise<void> {
49  const root = (await $.session.repo())?.root
50  if (root === undefined) {
51    await update($, repo, () => null)
52    return
53  }
54  const [listed, branch] = await Promise.all([git($, root, ['ls-files', '-z']), git($, root, ['branch', '--show-current'])])
55  const files = capFiles((listed ?? '').split('\0').filter(Boolean).slice(0, 50_000))
56  const name = root.split('/').filter(Boolean).pop() ?? root
57  await update($, repo, () => ({ root, name, branch: branch?.trim() || 'detached', files }))
58}
59
60/** The repository's root, else the session's directory: paths outside it are not mapped. */
61async function placeOf($: EngineInterface): Promise<{ root: string; cwd: string; files: Set<string> }> {
62  const known = await read($, repo)
63  const cwd = await $.session.cwd()
64  return { root: known?.root ?? cwd, cwd, files: new Set(known?.files ?? []) }
65}
66
67/** Finds, once per edited file, the files importing it (JS/TS and Python, by git grep). */
68async function findImporters($: EngineInterface, path: string): Promise<void> {
69  if ((await read($, importers))[path] !== undefined) return
70  const known = await read($, repo)
71  const pattern = importPattern(path)
72  if (known === null || pattern === undefined) return
73  const out = await git($, known.root, ['grep', '-l', '-E', pattern])
74  const list = (out ?? '').split('\n').filter(line => line !== '' && line !== path).slice(0, 50)
75  await update($, importers, all => ({ ...all, [path]: list }))
76}
77
78/** Marks what a call did, then redraws the status line and announces what is worth a toast. */
79async function mark($: EngineInterface, change: (all: Record<string, FogFile>) => Record<string, FogFile>, last: string | undefined): Promise<void> {
80  const before = await read($, touched)
81  const after = await update($, touched, change)
82  if (last !== undefined) await update($, focus, () => last)
83
84  const known = await read($, repo)
85  const counts = countsOf(after, known?.files ?? [], await read($, tracked))
86  const warnings = warningsOf(after, await read($, importers))
87  $.ui.status(statusOf(counts, warnings.length, known !== null))
88
89  const notes: string[] = []
90  const reached = milestoneOf(await read($, milestone), counts.percent)
91  if (known !== null && reached !== undefined) {
92    await update($, milestone, () => reached)
93    notes.push(`🗺 探索率 ${reached}% 到達`)
94  }
95  const newlyEdited = Object.keys(after).filter(path => (after[path]?.edits ?? 0) > 0 && (before[path]?.edits ?? 0) === 0)
96  const seen = await read($, areas)
97  const fresh = [...new Set(newlyEdited.map(areaOf))].filter(area => !seen.includes(area))
98  if (fresh.length > 0) {
99    await update($, areas, list => [...list, ...fresh])
100    notes.push(`🗺 新しい区域を開拓: ${fresh.join(' ')}`)
101  }
102  if (notes.length > 0) $.ui.toast(notes.join(' · '))
103}
104
105export const register: Register = on => {
106  on('session.start', async ($, e, next) => {
107    await $.command.register({ name: 'map', description: '探索マップを開く: Claude が読んだ・編集したファイルを、未踏の場所を霧にして表示' })
108    const started = await next(e)
109    await loadRepo($).catch(() => undefined)
110    await mark($, all => all, undefined)
111    return started
112  })
113
114  on('tool.call', async ($, e, next) => {
115    const tool = String(e.tool)
116    const input = e as unknown as Record<string, unknown>
117    const isEdit = EDIT_TOOLS.has(tool)
118    if (tool !== 'Read' && tool !== 'Bash' && !isEdit) return next(e)
119
120    const place = await placeOf($)
121    const target = typeof input.file_path === 'string' ? input.file_path : typeof input.notebook_path === 'string' ? input.notebook_path : undefined
122    const path = target === undefined ? undefined : inRepo(target, place.root, place.cwd)
123    // Asked before a Write runs: whether it makes a new file, and what it writes over, so its
124    // lines count as a diff stat would rather than as the whole file added.
125    const before = tool === 'Write' && path !== undefined ? await $.fs.read(`${place.root}/${path}`).catch(() => undefined) : undefined
126    const isNew = tool === 'Write' && path !== undefined && before === undefined
127      ? (await $.fs.stat(`${place.root}/${path}`).catch(() => undefined)) === undefined
128      : false
129
130    const ran = await next(e)
131    if (ran.deny !== undefined) return ran
132    const at = await $.clock.now()
133
134    if (tool === 'Read' && path !== undefined && ran.isError !== true) {
135      await mark($, all => ({ ...all, [path]: withRead(all[path], at) }), path)
136    } else if (isEdit && path !== undefined && ran.isError !== true) {
137      const change =
138        tool === 'Edit'
139          ? editChange(String(input.old_string ?? ''), String(input.new_string ?? ''))
140          : tool === 'Write'
141            ? editChange(typeof before === 'string' ? before : '', String(input.content ?? ''))
142            : editChange('', String(input.new_source ?? ''))
143      await mark($, all => ({ ...all, [path]: withEdit(all[path], { ...change, isNew }, at) }), path)
144      if (isNew) await update($, repo, old => (old === null ? old : { ...old, files: [...old.files, path] }))
145      void findImporters($, path).catch(() => undefined)
146    } else if (tool === 'Bash') {
147      const command = String(input.command ?? '')
148      const known = (word: string, cwd: string) => {
149        const one = inRepo(word, place.root, cwd)
150        return one !== undefined && place.files.has(one) ? one : undefined
151      }
152      const { reads, edits } = bashTouches(command, place.cwd, known)
153      const failed = ran.isError === true ? errorPaths(ran.text ?? '').flatMap(word => known(word, place.cwd) ?? []) : []
154      if (reads.length + edits.length + failed.length > 0) {
155        await mark(
156          $,
157          all => {
158            const marked = { ...all }
159            for (const one of reads) marked[one] = withRead(marked[one], at)
160            for (const one of edits) marked[one] = withEdit(marked[one], { added: 0, removed: 0 }, at)
161            for (const one of failed) marked[one] = withError(marked[one], at)
162            return marked
163          },
164          [...edits, ...reads, ...failed].at(-1),
165        )
166      }
167      if (ran.isError !== true && RESHAPES.test(command)) await loadRepo($).catch(() => undefined)
168    }
169    return ran
170  }).catch(($, e, next) => next(e)) // an observer: a failure here never changes the call
171
172  on('command.run', { command: 'map' }, async $ => {
173    await $.ui.open({ id: PANE, title: TITLE })
174    const known = await read($, repo)
175    const counts = countsOf(await read($, touched), known?.files ?? [], await read($, tracked))
176    return { text: known === null ? `🗺 git リポジトリの外です(編集 ${counts.edited})` : `🗺 探索率 ${counts.percent}% · ${counts.touched}/${counts.total}` }
177  })
178
179  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
180    const { Box, Text } = $.ui.resolve(e)
181    const known = await read($, repo)
182    const all = await read($, touched)
183    const counts = countsOf(all, known?.files ?? [], await read($, tracked))
184    const warnings = warningsOf(all, await read($, importers))
185    const width = Math.max(30, e.props.bodyColumns - 2)
186    const rows = rowsOf(known?.files ?? [], all, await read($, focus), width, await read($, tree))
187    // The pane's own rows, not the screen's: a docked pane shares the screen.
188    const room = Math.max(3, e.props.scroll.bodyRows - 5 - Math.min(3, warnings.length))
189    const color = { error: 'red', new: 'green', edit: 'yellow', 'focus-dir': 'cyan' } as Record<string, string>
190
191    return (
192      <Box flexDirection="column">
193        <Text bold wrap="truncate-end">
194          {known === null
195            ? `🗺 リポジトリの外 · 編 ${counts.edited}`
196            : `🗺 探索率 ${counts.percent}%  ${bar(counts.percent, 20)}  読 ${counts.read} · 編 ${counts.edited} · ✗ ${counts.errors} / ${counts.total}`}
197        </Text>
198        {known !== null && <Text dimColor>{`${known.name} · ${known.branch}`}</Text>}
199        {rows.length === 0 && <Text dimColor>まだどこにも踏み込んでいません。Claude がファイルを読むと霧が晴れていきます。</Text>}
200        {rows.slice(0, room).map((row, index) => (
201          <Text key={`row-${index}`} wrap="truncate-end" color={color[row.kind]} dimColor={row.kind === 'fog'} bold={row.kind === 'dir' || row.kind === 'focus-dir'}>
202            {`${'  '.repeat(row.depth)}${row.text}`}
203          </Text>
204        ))}
205        {rows.length > room && <Text dimColor>{`…ほか ${rows.length - room} 行`}</Text>}
206        {warnings.slice(0, 3).map((note, index) => (
207          <Text key={`warn-${index}`} color="yellow" wrap="truncate-end">{`⚠ ${note}`}</Text>
208        ))}
209        {warnings.length > 3 && <Text dimColor>{`⚠ ほか ${warnings.length - 3} 件`}</Text>}
210        <Text dimColor>░ 未踏  ○ 読んだ  ● 編集  ✚ 新規  ✗ エラー  ★ 直前</Text>
211      </Box>
212    )
213  })
214}
215
hooks/fog.ts 405 lines
1// The map, pure: where a tool call landed in the repository, what it did there, and the
2// tree drawn from it — fog where nothing was touched, marks where something was.
3
4import type { FogFile } from '../types'
5
6export const MILESTONES = [25, 50, 75, 100]
7/** Programs whose file arguments a Bash command reads. */
8const READERS = new Set(['cat', 'sed', 'head', 'tail', 'less', 'more', 'bat', 'nl', 'grep', 'rg', 'awk', 'wc', 'diff', 'cmp', 'jq'])
9
10export const blank = (at: number): FogFile => ({ reads: 0, edits: 0, added: 0, removed: 0, errors: 0, isNew: false, at })
11
12/** A path as the repository names it, or undefined when it lies outside. */
13// Trailing slashes off, by a loop: `/\/+$/` tries from every slash of a long run.
14function trimSlashes(path: string): string {
15  let end = path.length
16  while (end > 0 && path.charCodeAt(end - 1) === 47) end -= 1
17  return path.slice(0, end)
18}
19
20// No path is longer: a `cd` past it is not followed, so a chain of them is not read on forever.
21const PATH_MAX = 4096
22
23export function inRepo(path: string, root: string, cwd: string): string | undefined {
24  const full = path.startsWith('/') ? path : `${trimSlashes(cwd)}/${path}`
25  const parts: string[] = []
26  for (const part of full.split('/')) {
27    if (part === '' || part === '.') continue
28    if (part === '..') parts.pop()
29    else parts.push(part)
30  }
31  const clean = `/${parts.join('/')}`
32  const base = trimSlashes(root)
33  return clean.startsWith(`${base}/`) ? clean.slice(base.length + 1) : undefined
34}
35
36export function withRead(file: FogFile | undefined, at: number): FogFile {
37  const one = file ?? blank(at)
38  return { ...one, reads: one.reads + 1, at }
39}
40
41/** An edit's mark: its lines added and removed, and the errors it answers cleared. */
42export function withEdit(file: FogFile | undefined, change: { added: number; removed: number; isNew?: boolean }, at: number): FogFile {
43  const one = file ?? blank(at)
44  return {
45    ...one,
46    edits: one.edits + 1,
47    added: one.added + change.added,
48    removed: one.removed + change.removed,
49    errors: 0,
50    isNew: one.isNew || change.isNew === true,
51    at,
52  }
53}
54
55export function withError(file: FogFile | undefined, at: number): FogFile {
56  const one = file ?? blank(at)
57  return { ...one, errors: one.errors + 1, at }
58}
59
60/**
61 * The lines a change adds and removes, as a diff stat counts them: lines of the new text
62 * not matched by an equal line of the old, and the old ones left unmatched.
63 */
64export function editChange(oldText: string, newText: string): { added: number; removed: number } {
65  const left = new Map<string, number>()
66  for (const line of oldText === '' ? [] : oldText.split('\n')) left.set(line, (left.get(line) ?? 0) + 1)
67  let added = 0
68  for (const line of newText === '' ? [] : newText.split('\n')) {
69    const count = left.get(line) ?? 0
70    if (count > 0) left.set(line, count - 1)
71    else added += 1
72  }
73  const removed = [...left.values()].reduce((sum, n) => sum + n, 0)
74  return { added, removed }
75}
76
77/** The words of a Bash command, quotes taken off; a best-effort split, not a shell. */
78const words = (part: string): string[] => part.trim().split(/\s+/).map(word => word.replace(/^['"]|['"]$/g, ''))
79
80/**
81 * What a Bash command reads and edits among the given paths: `cat a`, `sed -n 1,9p a`,
82 * `sed -i … a`. A `cd` moves where the parts after it resolve (`cd mods && cat a.ts`);
83 * one into a place it cannot follow (`cd -`, `cd $DIR`) stops it reading further parts.
84 */
85export function bashTouches(
86  command: string,
87  cwd: string,
88  isKnown: (word: string, cwd: string) => string | undefined,
89): { reads: string[]; edits: string[] } {
90  const reads = new Set<string>()
91  const edits = new Set<string>()
92  // Fold only each new cd operand, not the whole growing path again. Materialize
93  // the directory only when a reader needs it; no cd leaves the original cwd as is.
94  let directory: string[] | undefined
95  let directoryLength = 0
96  for (const part of command.split(/&&|\|\||;|\||\n/)) {
97    const [program = '', ...rest] = words(part)
98    if (program === 'cd') {
99      const to = rest[0]
100      // Once the directory is unknown, no later part was followed anyway.
101      if (to === undefined || to === '-' || to.startsWith('~') || to.includes('$')) break
102      const path = to.startsWith('/') || directory !== undefined ? to : `${trimSlashes(cwd)}/${to}`
103      if (directory === undefined || to.startsWith('/')) {
104        directory = []
105        directoryLength = 0
106      }
107      for (const segment of path.split('/')) {
108        if (segment === '' || segment === '.') continue
109        if (segment === '..') {
110          const removed = directory.pop()
111          if (removed !== undefined) directoryLength -= removed.length + 1
112        } else {
113          directory.push(segment)
114          directoryLength += segment.length + 1
115        }
116      }
117      if (Math.max(1, directoryLength) > PATH_MAX) break
118      continue
119    }
120    const name = program.slice(program.lastIndexOf('/') + 1)
121    if (!READERS.has(name)) continue
122    const currentDirectory = directory === undefined ? cwd : `/${directory.join('/')}`
123    const isInPlace = name === 'sed' && rest.some(word => /^-[a-zA-Z]*i/.test(word) || word === '--in-place')
124    for (const word of rest) {
125      if (word.startsWith('-')) continue
126      const path = isKnown(word, currentDirectory)
127      if (path !== undefined) (isInPlace ? edits : reads).add(path)
128    }
129  }
130  return { reads: [...reads], edits: [...edits] }
131}
132
133const PATH_WORD = /[\w.@~+/-]+/g
134const LINE_MARK = /:\d+|\(\d+,\d+\)/y
135const EXTENSION = /^[A-Za-z]\w*$/
136
137/**
138 * Paths a failed command's output names with a line (`a.ts:12`, `a.ts(12,5)`), as candidates.
139 * Linear: each word is read once and only its last dot is tried, the dot a path's extension
140 * must follow; a regex trying every dot of a long word took seconds on a minified line.
141 */
142export function errorPaths(output: string): string[] {
143  const found = new Set<string>()
144  let taken = 0 // where the last mark ended: a path never starts inside one (`a.ts:12.b.ts:3`)
145  for (const word of output.matchAll(PATH_WORD)) {
146    const end = word.index + word[0].length
147    LINE_MARK.lastIndex = end
148    const mark = LINE_MARK.exec(output)
149    if (mark === null) continue
150    const path = output.slice(Math.max(word.index, taken), end)
151    const dot = path.lastIndexOf('.')
152    if (dot < 1 || !EXTENSION.test(path.slice(dot + 1))) continue
153    found.add(path)
154    taken = end + mark[0].length
155  }
156  return [...found]
157}
158
159/**
160 * The `git grep -E` pattern for a file's importers, or undefined for a language it does not
161 * read. POSIX classes only: the git macOS ships matches nothing for `\s`, `\w` or `\b` there.
162 */
163export function importPattern(path: string): string | undefined {
164  const name = path.slice(path.lastIndexOf('/') + 1)
165  const dot = name.lastIndexOf('.')
166  const ext = dot > 0 ? name.slice(dot + 1) : ''
167  const stem = (dot > 0 ? name.slice(0, dot) : name).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
168  if (['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs'].includes(ext)) {
169    return String.raw`(from|import|require\()[[:space:]]*\(?['"][^'"]*[/.]${stem}(\.[a-z]+)?['"]`
170  }
171  if (ext === 'py') {
172    // `from pkg.x import y`, `from .x import y`, `import pkg.x`, `import x as y`, `import a, x`.
173    const tail = String.raw`([[:space:],]|$)`
174    return String.raw`^[[:space:]]*(from[[:space:]]+([[:alnum:]_.]*\.)?${stem}${tail}|import[[:space:]]+([[:alnum:]_.,[:space:]]*[[:space:],.])?${stem}${tail})`
175  }
176  return undefined
177}
178
179export type Counts = { read: number; edited: number; errors: number; touched: number; total: number; percent: number }
180
181/** `tracked` is `new Set(files)` from a cache, when there is one: the list is not read again. */
182export function countsOf(touched: Readonly<Record<string, FogFile>>, files: readonly string[], tracked: ReadonlySet<string> = new Set(files)): Counts {
183  const all = Object.entries(touched)
184  const inside = all.filter(([path]) => tracked.has(path) || touched[path]?.isNew === true)
185  const total = tracked.size + all.filter(([path, one]) => one.isNew && !tracked.has(path)).length
186  return {
187    read: all.filter(([, one]) => one.reads > 0 && one.edits === 0).length,
188    edited: all.filter(([, one]) => one.edits > 0).length,
189    errors: all.filter(([, one]) => one.errors > 0).length,
190    touched: inside.length,
191    total,
192    percent: total === 0 ? 0 : Math.floor((inside.length / total) * 100),
193  }
194}
195
196/** The milestone a new percentage crosses, if any. */
197export function milestoneOf(previous: number, percent: number): number | undefined {
198  return MILESTONES.filter(one => one > previous && percent >= one).at(-1)
199}
200
201/** The area a path belongs to, announced the first time it is edited: `mods/zukan/`. */
202export function areaOf(path: string): string {
203  const parts = path.split('/')
204  return parts.length >= 3 ? `${parts[0]}/${parts[1]}/` : parts.length === 2 ? `${parts[0]}/` : './'
205}
206
207/** Files that import an edited one and were never opened: what an edit may have broken unseen. */
208export function warningsOf(touched: Readonly<Record<string, FogFile>>, importers: Readonly<Record<string, string[]>>): string[] {
209  const notes: string[] = []
210  for (const [path, one] of Object.entries(touched)) {
211    if (one.edits > 0 && one.reads === 0 && !one.isNew) notes.push(`編集したのに一度も読んでいない: ${path}`)
212  }
213  const unseen = new Set<string>()
214  for (const [edited, list] of Object.entries(importers)) {
215    if ((touched[edited]?.edits ?? 0) === 0) continue
216    for (const importer of list) {
217      const one = touched[importer]
218      if (one === undefined || (one.reads === 0 && one.edits === 0)) unseen.add(importer)
219    }
220  }
221  for (const path of [...unseen].sort()) notes.push(`編集したファイルを import しているが未読: ${path}`)
222  return notes
223}
224
225export const markOf = (one: FogFile): string => (one.errors > 0 ? '✗' : one.isNew ? '✚' : one.edits > 0 ? '●' : '○')
226
227/** The status line entry, only while there is something to look at: an error or a warning. The map and its share stay in `/map`. */
228export function statusOf(counts: Counts, warnings: number, hasRepo: boolean): string | undefined {
229  if (counts.errors === 0 && warnings === 0) return undefined
230  const parts = [hasRepo ? `🗺 ${counts.percent}%` : '🗺', `●${counts.edited}`]
231  if (counts.errors > 0) parts.push(`✗${counts.errors}`)
232  if (warnings > 0) parts.push(`⚠${warnings}`)
233  return parts.join(' · ')
234}
235
236export function bar(percent: number, width = 24): string {
237  const full = Math.round((Math.min(100, Math.max(0, percent)) / 100) * width)
238  return `${'█'.repeat(full)}${'░'.repeat(width - full)}`
239}
240
241/** One row of the drawn tree. */
242export type Row = { depth: number; text: string; kind: 'fog' | 'read' | 'edit' | 'new' | 'error' | 'dir' | 'focus-dir' }
243
244export type Node = { name: string; dirs: Map<string, Node>; files: string[] }
245
246/** The paths as a tree of folders, each name once. */
247export function treeOf(paths: Iterable<string>): Node {
248  const root: Node = { name: '', dirs: new Map(), files: [] }
249  for (const path of new Set(paths)) {
250    const parts = path.split('/')
251    let node = root
252    for (const part of parts.slice(0, -1)) {
253      let next = node.dirs.get(part)
254      if (next === undefined) {
255        next = { name: part, dirs: new Map(), files: [] }
256        node.dirs.set(part, next)
257      }
258      node = next
259    }
260    node.files.push(parts.at(-1) ?? path)
261  }
262  return root
263}
264
265function hasPath(tree: Node, path: string): boolean {
266  const parts = path.split('/')
267  let node: Node | undefined = tree
268  for (const part of parts.slice(0, -1)) node = node?.dirs.get(part)
269  return node !== undefined && node.files.includes(parts.at(-1) ?? path)
270}
271
272/**
273 * `base` with `paths` it lacks added, as treeOf would have placed them after its own. The
274 * folders on their way are copied, so `base`, kept in a cache, is never changed.
275 */
276function withPaths(base: Node, paths: readonly string[]): Node {
277  const root: Node = { ...base, dirs: new Map(base.dirs), files: [...base.files] }
278  const copied = new Set<Node>([root])
279  for (const path of paths) {
280    const parts = path.split('/')
281    let node = root
282    for (const part of parts.slice(0, -1)) {
283      const found = node.dirs.get(part)
284      let next: Node
285      if (found === undefined) next = { name: part, dirs: new Map(), files: [] }
286      else if (copied.has(found)) next = found
287      else next = { ...found, dirs: new Map(found.dirs), files: [...found.files] }
288      copied.add(next)
289      node.dirs.set(part, next)
290      node = next
291    }
292    const name = parts.at(-1) ?? path
293    if (!node.files.includes(name)) node.files.push(name)
294  }
295  return root
296}
297
298const signed = (one: FogFile): string => (one.edits > 0 ? `+${one.added} −${one.removed}` : '')
299
300/**
301 * The tree as rows: a directory holding an edit, a new file or an error is open; one only
302 * read is closed with its marks beside it; untouched directories and files at a level are
303 * one fog row. The ★ goes on the file touched last.
304 */
305export function rowsOf(
306  files: readonly string[],
307  touched: Readonly<Record<string, FogFile>>,
308  focus: string | null,
309  width: number,
310  tree?: Node,
311): Row[] {
312  const rows: Row[] = []
313  // `tree` is treeOf(files) from a cache: only the touched paths it lacks are added, on a copy.
314  const root = tree === undefined ? treeOf([...files, ...Object.keys(touched)]) : withPaths(tree, Object.keys(touched).filter(path => !hasPath(tree, path)))
315
316  // Each folder's marks are gathered once: an open folder's are not gathered again for each level
317  // above it, and a folder holding no touched path is never read through.
318  const holding = new Set<string>()
319  for (const path of Object.keys(touched)) {
320    for (let at = path.indexOf('/'); at >= 0; at = path.indexOf('/', at + 1)) holding.add(path.slice(0, at + 1))
321  }
322  const gathered = new Map<Node, FogFile[]>()
323  const marksUnder = (node: Node, prefix: string): FogFile[] => {
324    if (prefix !== '' && !holding.has(prefix)) return []
325    const known = gathered.get(node)
326    if (known !== undefined) return known
327    const marks = [
328      ...node.files.flatMap(name => (touched[`${prefix}${name}`] ? [touched[`${prefix}${name}`] as FogFile] : [])),
329      ...[...node.dirs.values()].flatMap(dir => marksUnder(dir, `${prefix}${dir.name}/`)),
330    ]
331    gathered.set(node, marks)
332    return marks
333  }
334
335  const walk = (node: Node, prefix: string, depth: number) => {
336    const fog: string[] = []
337    for (const dir of [...node.dirs.values()].sort((a, b) => a.name.localeCompare(b.name))) {
338      const path = `${prefix}${dir.name}/`
339      const marks = marksUnder(dir, path)
340      if (marks.length === 0) {
341        fog.push(`${dir.name}/`)
342        continue
343      }
344      const isOpen = marks.some(one => one.edits > 0 || one.errors > 0 || one.isNew)
345      const hasFocus = focus !== null && focus.startsWith(path)
346      if (!isOpen) {
347        rows.push({ depth, text: `▸ ${dir.name}/  ${marks.map(markOf).join('')}`, kind: hasFocus ? 'focus-dir' : 'dir' })
348        continue
349      }
350      rows.push({ depth, text: `▾ ${dir.name}/`, kind: hasFocus ? 'focus-dir' : 'dir' })
351      walk(dir, path, depth + 1)
352    }
353    for (const name of [...node.files].sort()) {
354      const path = `${prefix}${name}`
355      const one = touched[path]
356      if (one === undefined) {
357        fog.push(name)
358        continue
359      }
360      const details = [
361        signed(one),
362        one.edits > 1 ? `編集 ${one.edits}回` : '',
363        one.isNew ? '新規' : '',
364        one.errors > 0 ? `エラー ${one.errors}` : '',
365        path === focus ? '★' : '',
366      ].filter(Boolean)
367      const kind = one.errors > 0 ? 'error' : one.isNew ? 'new' : one.edits > 0 ? 'edit' : 'read'
368      rows.push({ depth, text: `${markOf(one)} ${name}${details.length > 0 ? `  ${details.join('  ')}` : ''}`, kind })
369    }
370    if (fog.length > 0) {
371      const room = Math.max(10, width - depth * 2)
372      let line = ''
373      let shown = 0
374      for (const name of fog) {
375        const next = `${line}${line === '' ? '' : '  '}░ ${name}`
376        if (next.length > room - 6 && line !== '') break
377        line = next
378        shown += 1
379      }
380      rows.push({ depth, text: shown < fog.length ? `${line}  …${fog.length - shown}` : line, kind: 'fog' })
381    }
382  }
383
384  walk(root, '', 0)
385  return rows
386}
387
388// The repository's files are kept in one state value, which the engine holds to 4,194,304
389// characters of JSON: past this the list is cut, so the write is never refused and the
390// repository never taken for none.
391export const MAX_FILES_CHARS = 3_000_000
392
393/** The files a state value can hold, in the order git lists them. */
394export function capFiles(files: readonly string[]): string[] {
395  const kept: string[] = []
396  let size = 2
397  for (const file of files) {
398    const next = JSON.stringify(file).length + 1
399    if (size + next > MAX_FILES_CHARS) break
400    size += next
401    kept.push(file)
402  }
403  return kept
404}
405
types/index.d.ts 43 lines
1/** What the session did to one file of the repository. */
2export type FogFile = {
3  /** Times it was read (Read, or a reader such as cat or sed in Bash). */
4  reads: number
5  /** Times it was edited (Edit, Write, NotebookEdit, sed -i). */
6  edits: number
7  /** Lines added and removed by those edits, as the edits' own text counts them. */
8  added: number
9  removed: number
10  /** Errors a failed Bash command named it in since it was last edited. */
11  errors: number
12  /** Made by this session: it did not exist before the first write. */
13  isNew: boolean
14  /** When it was last touched. */
15  at: number
16}
17
18/** The repository the map is of. */
19export type FogRepo = {
20  root: string
21  name: string
22  branch: string
23  /** Its files, repository-relative, as `git ls-files` lists them. */
24  files: string[]
25}
26
27declare module 'claude-code' {
28  interface PluginState {
29    'fog-map': {
30      repo: FogRepo | null
31      /** Repository-relative path to what the session did to it. */
32      touched: Record<string, FogFile>
33      /** The file touched last: the map's ★. */
34      focus: string | null
35      /** Edited file to the files that import it, as git grep found them. */
36      importers: Record<string, string[]>
37      /** Areas already announced, and the highest milestone reached (percent). */
38      areas: string[]
39      milestone: number
40    }
41  }
42}
43