SLOPSHOPPER

verinoda-live

Verinoda in Claude Code: the Verinoda MCP server's tools listed in front of the model with a one-paragraph call rule, the code index kept fresh while Claude…

paneguardcommandstatusprompttool
★ 1v0.8.1Apache-2.0updated 2026-10-25Verinoda-Labs/verinoda-symbiosis/claude-mods/verinoda-live
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · verinoda-live
│ ┃ İyileştirme ✕ › fix the failing auth test and add an audit log call │ ┃ İnceleniyor… Claude listeyi hazırlıyor; │ ┃ hiçbir şey değiştirilmiyor. ⏺ 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 │ │ › /verinoda-improve │ ⎿ verinoda-live: looking at it; the list will appear in the pane, │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · İyileştirme
İnceleniyor… Claude listeyi hazırlıyor; hiçbir şey değiştirilmiyor.
Pane · Verinoda
? Bu projede Verinoda index'i yok Proje klasöründe çalıştır: verinoda init, sonra verinoda update
README

verinoda-live: a Claude Code mod for Verinoda

A function-hooks plugin ("mod") for Claude Code that puts the Verinoda MCP server's tools in front of the model with a one-paragraph call rule, keeps a Verinoda index fresh while Claude edits, and can check each edit for names that do not exist. It finds the project (the nearest folder at or above the session's with a .verinoda index; never a home folder or a drive root unless the settings name it) and the CLI (verinoda on PATH, outside the project) by itself; /config overrides both (root, cli), turns the check after edits on (check), the file cards of a compaction off (compactCards) and the mascot's motion off (motion).

What it does

featurehowdefault
Tools in frontmcp__verinoda__analyze, project_query and run_tool are placed in the model's tool list, not behind ToolSearch (a tool the model must look up first is not called: 0 of 286 study sessions with the tools deferred, 51 of 63 with a tool listed in front; the ToolSearch turn costs a model call of its own). Their descriptions stay the server's.on
The call ruleWhile the Verinoda MCP server is connected (its tools are in the request), one paragraph in the system prompt (section verinoda-live:rule, about 630 characters): on a question that asks why something is the way it is, when or in which commit it changed, or what a change affects, the first tool call is analyze with the question, Grep, Read and git after it; its output is a lead, so confirm with one git or grep check before stating "no such change", "first added in" or why something changed; statically_verified and primary_source_verified claims are verified, strong_inference and below are not. A softer rule with a way out ("a question one grep answers needs no call") got no call in 39 of 39 headless sessions of the D186 re-run; this wording, with the reminder fix below and the server's matching description, got 6 of 6 in probes and 37 of 39 in the re-run, analyze first every time (D186, benchmarks/results/claims-rerun-2026-10-13/). The mod also takes the three pinned names out of the engine's reminder of tools behind ToolSearch, which is composed before the pins apply and said a direct call would fail.on
Re-index after editsEdit / Write / NotebookEdit inside ROOT mark the file; at the end of the main loop's turn one verinoda update --fast runs (subagent turns do not start one). A scripted session (claude -p, the Agent SDK) starts none, nor the graph watch after it: its end waits for that update. In the D193 bench such sessions ended 4.8 s after their last message at the median, against 0.4 s without it; in the own-repository study's Part B, on a loaded machine, 68.3 s (1.9 s without Verinoda). Their edits wait for /verinoda-update, and an analyze refreshes a changed tree itself, at once or in the background. A failed update keeps its files for /verinoda-update. Only in a project the person opened (the session's own folder), named in the settings, or trusted with verinoda trust: a .verinoda found in an ancestor they never opened runs nothing, the pane says so, and /verinoda-update names the command that allows it.on
Graph stateAfter --fast the graph is rebuilt in the background; the status line says text fresh · graph pending… until verinoda graph-state reports no build holding the lock and no file changed since the latest snapshot, then fresh ✓. A graph left behind with no build coming (files changed outside Claude's edit tools) is named, and /verinoda-update takes it in. Edits made while the build runs wait for it and are indexed when it ends. A scripted session never looks at the graph: its state reads graph state unknown (D193).on
File cards when compacting (setting compactCards)When Claude Code compacts the conversation (/compact, or the auto-compact window), the mod collects the files the main conversation read or edited under the project the person allowed, else under the folder the session was opened in (a card needs no index; never a home folder or a drive root; edited ones first, then the latest reads, at most 40; none under .verinoda), runs verinoda card on them (at most 20 s) and adds the cards to what the summarizer is told, after any /compact <focus>: one line per file (path and length, what it is for, its top-level definitions, its imports; an image's size), and the request to keep the cards instead of the files' text. A later turn reads again what it needs. A CLI that is missing, older (no card), slow or failing leaves the compaction exactly as Claude Code's own; a subagent's compaction gets no cards, nor a folder with a verinoda inside it. In the person's sessions a compaction cycle touched 67 files at the median; 40 cards of a real cycle took 0.67 s and 7,834 characters (D189).on
Check after edits (`/verinoda-check on\off, setting check`)After each Edit / Write of a Python, Java or Kotlin file inside ROOT, verinoda check --diff (falling back to the file itself without git) reads the changed lines; names on them that do not exist in the project or its environment are told to the model in one line with the edit's result (as a PostToolUse note), with the nearest real names. Nothing is said when nothing is absent. A cached check takes about 3 s, never more than 60 s, and never fails the edit. The pane shows the last check (k toggles). A choice made with /verinoda-check is kept and wins in a terminal; a scripted session (claude -p, the Agent SDK) takes the setting as given.off
/verinoda-improve [what to look at] paneA vague request ("make this better") becomes a list the person can recognise their wish in. The command asks Claude to look and change nothing; Claude hands the mod a ranked list through improve_propose; a second Turkish pane (İyileştirme) shows it in three groups (possible problems with file:line evidence, functional improvements, matters of taste) with nothing selected, the seven best ranked first and the rest folded. The person marks each item (u apply, k keep, c check first for a suspected problem), may add items of their own, and sends with g; only then does Claude work, on what was chosen, and report each outcome through improve_report. A suspicion is never drawn as a fact (kanıtsız, tahmin), an item without a decision is never read as rejected, and every change that was not on the list is reported. Nothing of it runs, and neither tool is listed to the model, before the command (or the improveOffer setting: one line in the system prompt that offers the list instead of guessing). A scripted session gets none of it. No Verinoda index is needed and nothing is stored.command only
/verinoda-panel paneIn Turkish (technical nouns kept): the index state as glyph + words + colour with the one action that applies (u), the check after edits as a two-way control (k), and a purple Claude mascot with glasses in the room left over, animated like Claude Code's own (it blinks and shuffles its feet; while Verinoda works it reads, a glint sweeping its lenses; hooks/mascot.tsx, drawn by the surface as a Client, so frames repaint only its region; still on surfaces without Client) (hidden inline, below 24 columns or when the content needs the rows).-

Nothing runs from the repository

A cloned repository can ship a verinoda.exe at its root, a .venv/ with one inside, or a .verinoda/ folder of its own. The mod runs none of them (D186 §4.6):

  • verinoda is resolved once at session start by walking PATH (with PATHEXT on Windows) and taking the first program found in a folder that is not inside the project, so an activated project .venv first on PATH is skipped; a cli setting that points into the project, or to a network share, is refused the same way. Without one outside the project nothing runs at all, not even trust --list: the status line says verinoda not found on PATH outside the project · set cli, the pane says it in Turkish, and /verinoda-update answers the same (a bare name handed to the child would be resolved through the same PATH, to the project's own program). The mod needs no python of its own: the graph's state comes from verinoda graph-state --json.
  • Every run has the user's home folder as its working directory (a drive root without one), never the repository, because Windows searches a child's working directory before PATH and whether $.process.run does is unverified; --repo names the project.
  • update --fast, graph-state and check run only where the person chose the index: the folder they opened, the one their settings name, or one verinoda trust --list knows (read once per session, through the CLI). A .verinoda in an ancestor they never opened is shown as güvenilmiyor and runs nothing.

hooks/features.test.ts puts a fake verinoda.exe in the project root and in its .venv, names both first on PATH, and checks that every process the mod runs is the one outside the project, from the home folder; with no other on PATH it checks that nothing runs, not even the trust list, and that the pane names the cli setting.

What was measured, and what went (D186)

The 0.6 mod had an auto-context mode (nudge: an instruction to start with verinoda analyze; search: verinoda query results attached to the prompt), a commit review after each git command that moved HEAD, assist features (located files injected, coupled-file notes, locate and coupled tools, a gate on the first search), a session-start warm-up of the checker, and the check after edits on by default. They are gone because the measurements gave no reason to keep them:

  • nudge: on 57 questions over corpora of 37-226 files (benchmarks/results/agent-compare-2026-10-02/) the same facts at 16 % fewer input tokens; on 51 questions over ten real repositories (benchmarks/results/agent-compare-realworld-2026-10-02/) the same facts at 1.14x input tokens: the saving did not replicate. On a 27,078-file repository and on seL4 (agent-compare-big-2026-10-02/, agent-compare-sel4-2026-10-02/) the agent used Verinoda in 0 of 206 nudged sessions. In the false-claims study (D185) the nudge fired once per session, 875 characters, telling the model to run the CLI while the guide said to use the server.
  • search: 5-6 facts fewer on the small corpora (207 against 212) at 1.29x output.
  • assist (inject, coupled, tool, prompt, gate): development-set numbers only (benchmarks/agent_compare/DESIGN_ASSIST.md); the confirmatory run has no result file, and gate denied the model's own first search.
  • commit review: a guard on every shell command that mentioned git, reading HEAD before and after; no study measured a gain.
  • check after edits: on 30 coding tasks (benchmarks/results/agent-compare-guard-2026-10-02/, 60 real sessions) it fired 0 times in 65 edits; on SWE-bench Lite (D184) it found an absent name in 3 of 99 calls, none acted on, at about $0.009 per session. It works (a deliberate removed name is caught and the model told), so it stays, off.
  • the warm-up: a check --stdin at every session start to build the checker's name index, for a check that rarely runs.

What replaces their delivery role is the tools in front and the call rule: in one headless session on the study's fastapi copy the model called analyze at its first tool call, confirmed the lead with git show and cited the commit that states the reason (546dc8b), where two sessions without the rule asserted the history gives none (D186 spec §3; one session each, an observation, not a scored measure). What freshness itself is worth is measured in benchmarks/results/agent-compare-stale-2026-10-02/: on projects under 300 files analyze refreshes a stale index by itself; on the larger ones a stale index cost about a fifth more input tokens, and the fresh one the mod keeps brought that back.

Developing it

The live copy Claude Code hot-reloads is the session's dev-mods folder; this folder is its versioned source. Load it from here in a terminal with claude --plugin-dir <this repository>/claude-mods/verinoda-live.

  • claude plugin validate <folder>: what the module hooks and calls, and anything the engine would refuse.
  • claude plugin test <folder>: hooks/register.test.ts (re-index and graph watcher), hooks/features.test.ts (the tools in front and the call rule, nothing run from the repository, the trust gate, the check after edits, the settings, the project, robustness, the pane on terminal and desktop), hooks/check.test.ts (the check after edits and its note), hooks/improve.test.ts (the improvement list: the proposed list and its first sight, decisions, the three prompts, reports, the wired command, tools and pane; hooks/improve.ts is its pure part and hooks/improve-pane.tsx its pane and hooks) and hooks/mascot.test.ts.
  • Type-check: after the engine has loaded the mod once it writes .claude-plugin/types/ and a tsconfig.json; then tsc -p <folder>. Both are generated and not kept here.

The 2026-10-02 version was reviewed by three independent lenses (API, state and failure paths, Windows and real-use edge cases) with two skeptics per finding; the 13 upheld findings are fixed and covered by tests.

Note: the pane's command is /verinoda-panel, not /verinoda: the Verinoda agent skill (~/.claude/skills/verinoda, installed by verinoda install) owns /verinoda, and a skill of that name takes the slash before a plugin command.

The pane was redesigned from a user-eyes evaluation (a first-time Turkish speaker, an all-day user, a terminal and accessibility specialist), two mascot designs and one synthesized spec; the tests mount it on the terminal and desktop surfaces, check every state's words, the hotkeys shown, and when the mascot appears.

Source 6 files
hooks/register.tsx 855 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { CheckInfo, ImproveState, IndexKind, IndexState, Notice } from '../types'
5import { CARD_CHARS, CARD_TIMEOUT_MS, cardInstructions, touchedFiles } from './cards'
6import { IMPROVE_SPECS, initialImprove, reviewPrompt, undoSend } from './improve'
7import { COMMAND as IMPROVE_COMMAND, endOfTurn, improveSections, mod as improveMod, registerImprove } from './improve-pane'
8import { frameRows, MASCOT_HEIGHT, MASCOT_WIDTH } from './mascot'
9import type { MascotProps, Mood } from './mascot'
10
11const PANE = 'verinoda'
12const GRAPH_POLL_MS = 1_000
13const GRAPH_WAIT_MS = 10 * 60_000
14// Unlocked yet behind this long: no build is coming (files changed outside Claude's edit tools).
15const GRAPH_STALL_MS = 15_000
16// The host's longest wait for a process (10 min). `verinoda update` itself waits up to 600 s for the build lock, so
17// the mod never starts one while its own background build holds it (reindex defers to the watcher instead).
18const UPDATE_TIMEOUT_MS = 600_000
19const TRUST_TIMEOUT_MS = 20_000
20const NOTICE_MS = 6_000
21const EDIT_TOOLS = ['Edit', 'Write', 'NotebookEdit'] as const
22// the Verinoda MCP server's tools, as the model names them; the three of its core profile are listed in front
23const MCP_TOOL_PREFIX = 'mcp__verinoda__'
24const MCP_CORE_TOOLS = ['mcp__verinoda__analyze', 'mcp__verinoda__project_query', 'mcp__verinoda__run_tool'] as const
25
26// After each edit of a file `verinoda check` reads (Python, Java, Kotlin), the names the edited lines use that do not
27// exist in the project or its environment are told to the model with the edit's result. Off unless asked (D186 §4.4):
28// 0 notes in 65 edits of the guard study, an absent name in 3 of 99 SWE-bench calls and none acted on. A cached check
29// takes about 3 s; the edit never waits longer than CHECK_TIMEOUT_MS for it.
30const CHECKABLE = /\.(py|pyi|java|kt|kts)$/i
31const CHECK_TIMEOUT_MS = 60_000
32const CHECK_NOTE_MAX = 8
33
34// The call rule (D186 §4.6), a section of the system prompt while the Verinoda MCP server is connected. The tools in
35// front alone did not make the model call them, and neither did a rule with a way out ("call analyze once ... a question
36// one grep answers needs no call"): in the D186 re-run the model called no Verinoda tool in 39 of 39 headless sessions
37// (first tool Grep in 38), the one session that rule was first tried on notwithstanding. This wording names the first
38// tool call and gives no way out; with the engine's reminder of deferred tools corrected (below) and the server's analyze
39// description saying the same, probes of six re-run tasks got the call in 5 of 6 (the miss a when-question the model
40// answered with `git log -S`, rightly); the earlier wording 0 of 39, this one without the two companions 3 of 6. The one
41// own check it asks for costs about one model call on history questions and is priced in the design's cost model.
42export const RULE_SECTION = 'verinoda-live:rule'
43export const CALL_RULE =
44  'Your first tool call on a question that asks why something is the way it is, when or in which commit it changed, or ' +
45  'what a change affects is `mcp__verinoda__analyze` with the question; Grep, Read and git come after it. It is in your ' +
46  'tool list, not behind ToolSearch. It answers from the git history and the code graph with a verdict, claims and leads ' +
47  'that carry file:line and commit hashes; `statically_verified` and `primary_source_verified` claims are verified, ' +
48  "`strong_inference` and below are not. Confirm its lead with one git or grep check of your own before stating 'no " +
49  "such change', 'first added in' or why something changed."
50
51const CHECKING: IndexState = { kind: 'checking', n: 0, waiting: false, since: null, at: null, error: '' }
52
53// Session state the drawing reads (declared in ../types); the check setting is also kept in $.store across sessions.
54const status = atom({ plugin: 'verinoda-live', key: 'status' } as const, '')
55const idx = atom({ plugin: 'verinoda-live', key: 'idx' } as const, CHECKING)
56const notice = atom({ plugin: 'verinoda-live', key: 'notice' } as const, null as Notice | null)
57const check = atom({ plugin: 'verinoda-live', key: 'check' } as const, false)
58const lastCheck = atom({ plugin: 'verinoda-live', key: 'lastCheck' } as const, null as CheckInfo | null)
59// the improvement list's state (D175); ./improve-pane.tsx declares the same source, because the scan reads an atom where it is used
60const improve = atom({ plugin: 'verinoda-live', key: 'improve' } as const, initialImprove())
61
62// Where Verinoda runs from, settled at session start (D186 §4.6: nothing the mod runs comes from the opened repository).
63// `cli` is the program: the setting's path when it lies outside the project, else what PATH names outside the project,
64// else nothing (''), and then nothing runs: the child inherits this PATH, so a bare name handed to it would be the
65// project's own program when that is the only one (an activated .venv with no install outside). `cwd` is the working
66// directory of every run: the user's home (a drive root without one), never the repository, because Windows searches a
67// child's working directory before PATH and whether $.process.run does is unverified; `--repo` names the project. The
68// settings' `python` went with the python probe (`verinoda graph-state`).
69const cfg = { cli: '', cwd: '', check: false, motion: true, cards: true }
70
71// Module state: a reload starts it over, which only forgets edits not yet indexed.
72const live = {
73  root: undefined as string | undefined,
74  cwd: '',
75  missingCli: '', // the name PATH had no program for outside the project; '' once one is found (or the settings name one)
76  isAllowed: false, // a program was found, and the root is the session's folder, the settings' one, or trusted with `verinoda trust`
77  isInteractive: true, // false in a scripted session (claude -p, the SDK): nothing is started that its end would wait for (D193)
78  pending: new Set<string>(),
79  isChecking: true, // the session-start look at the graph has not answered yet
80  isRunning: false,
81  runningCount: 0,
82  isGraphBehind: false,
83  graphSince: null as number | null,
84  graphFiles: 0,
85  stalledBehind: 0, // files the graph is behind on with no build coming; /verinoda-update takes them in
86  noGraph: false, // a .verinoda folder without a graph (`verinoda init` without `update`): nothing to be fresh
87  isSlow: false,
88  isUnknown: false,
89  failed: null as { n: number; error: string } | null,
90  freshAt: null as number | null,
91}
92
93export function norm(p: string): string {
94  return p.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
95}
96
97// slashes made forward, case kept: a case-sensitive file system finds a folder only as it is spelled
98const slashes = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '')
99
100export function isCheckable(path: string): boolean {
101  return CHECKABLE.test(path)
102}
103
104type CheckSite = { at?: string; path?: string; expr?: string; name?: string; verdict?: string; message?: string;
105  nearest?: { name?: string }[] }
106
107// A file under the project, relative to it, slashes forward and case kept (it is shown and passed on as spelled).
108function relPath(root: string, file: string): string {
109  const r = root.replace(/\\/g, '/').replace(/\/+$/, '')
110  return file.replace(/\\/g, '/').slice(r.length + 1)
111}
112
113function badSites(report: { sites?: CheckSite[] }, rel: string): CheckSite[] {
114  return (report.sites ?? []).filter(s =>
115    (s.verdict === 'absent' || s.verdict === 'mismatch') && norm(s.path ?? '') === norm(rel))
116}
117
118// The note the model reads after an edit, one line: the edited file's sites `verinoda check` found absent or mismatched
119// (an unknown is not checked, so it is never reported), each with the nearest real names; undefined when there are none,
120// which is nearly always (D186 §4.4), so a note is rare and short.
121export function checkNote(root: string, file: string, report: { sites?: CheckSite[] }, cli: string): string | undefined {
122  const rel = relPath(root, file)
123  const bad = badSites(report, rel)
124  if (bad.length === 0) return undefined
125  const sites = bad.slice(0, CHECK_NOTE_MAX).map(s => {
126    const near = (s.nearest ?? []).map(n => n.name).filter(Boolean).slice(0, 3)
127    return `${s.at ?? rel} ${s.expr ?? s.name ?? ''}: ${s.message ?? s.verdict}${near.length ? ` (nearest: ${near.join(', ')})` : ''}`
128  })
129  const more = bad.length > CHECK_NOTE_MAX ? ` (+${bad.length - CHECK_NOTE_MAX} more: ${cli} check --diff --repo ${root})` : ''
130  const what = bad.length === 1 ? 'a name that does' : `${bad.length} names that do`
131  return `[Verinoda check] The lines you changed in ${rel} use ${what} not exist in this project or its environment ` +
132    `(a static check; runtime-made names are never reported): ${sites.join('; ')}${more}`
133}
134
135// Work left running after a hook returns (a re-index, the graph watcher): a reload or the end of the session aborts
136// its $ calls, which is no error of the person's, so the rejection is dropped here.
137function background(work: Promise<unknown>): void {
138  work.catch(() => undefined)
139}
140
141function plural(n: number): string {
142  return `${n} file${n === 1 ? '' : 's'}`
143}
144
145function isInside(path: string, root: string): boolean {
146  const p = norm(path)
147  const r = norm(root)
148  return p === r || p.startsWith(`${r}/`)
149}
150
151// Is the Verinoda MCP server connected? The request's tool list names its tools; a `.mcp.json` would only say it is
152// configured. No index is needed: the server indexes the project it was set up for.
153export function isServerConnected(tools: readonly string[] | undefined): boolean {
154  return (tools ?? []).some(t => t.startsWith(MCP_TOOL_PREFIX))
155}
156
157// The index state from the module's fields, as the pane reads it and as the status line says it (in English, as the
158// slash commands do). The first matching rule wins: a running update over a failure, a failure over waiting edits.
159export function indexState(): { state: IndexState; line: string } {
160  const base = { waiting: false, since: null, at: live.freshAt, error: '' }
161  const at = (kind: IndexKind, n: number, line: string, extra: Partial<IndexState> = {}) =>
162    ({ state: { ...base, kind, n, ...extra }, line })
163  if (live.root === undefined) return at('noindex', 0, `no .verinoda index at or above ${live.cwd}`)
164  // before the trust gate: without the CLI the trust list cannot be read, so trust is unknown, not refused
165  if (live.missingCli !== '') {
166    return at('nocli', 0, `${live.missingCli} not found on PATH outside the project · set \`cli\``, { error: live.missingCli })
167  }
168  if (!live.isAllowed) return at('untrusted', 0, `index at ${live.root} not trusted · verinoda trust ${live.root}`, { error: live.root })
169  if (live.isRunning) return at('updating', live.runningCount, `updating (${plural(live.runningCount)})…`)
170  if (live.noGraph) return at('noindex', 0, `index folder at ${live.root} has no graph · verinoda update`, { error: live.root })
171  if (live.failed !== null) {
172    return at('failed', live.failed.n, `update failed · ${plural(live.failed.n)} kept for /verinoda-update`, { error: live.failed.error })
173  }
174  if (live.pending.size > 0) return at('pending', live.pending.size, `${plural(live.pending.size)} pending`, { waiting: live.isGraphBehind })
175  if (live.isGraphBehind) return at('graph', live.graphFiles, 'text fresh · graph pending…', { since: live.graphSince })
176  if (live.stalledBehind > 0) return at('behind', live.stalledBehind, `graph behind ${plural(live.stalledBehind)} · /verinoda-update`)
177  if (live.isSlow) return at('slow', 0, 'graph build still running (10 min+)')
178  if (live.isUnknown) return at('unknown', 0, 'graph state unknown')
179  if (live.isChecking) return at('checking', 0, 'checking…')
180  return at('fresh', 0, 'fresh ✓')
181}
182
183function publish($: EngineInterface): void {
184  const { state, line } = indexState()
185  $.ui.status(live.root === undefined ? undefined : `Verinoda: ${line}`)
186  // the pane's copy is best effort: a write refused after the module unloaded is dropped
187  update($, status, () => line).catch(() => undefined)
188  update($, idx, () => state).catch(() => undefined)
189}
190
191async function setCheck($: EngineInterface, value: boolean): Promise<void> {
192  await update($, check, () => value)
193  await $.store.set('check', value)
194}
195
196// The check after edits starts from the setting (`userConfig.check`, off unless set); what the person chose last with
197// /verinoda-check is kept in the store and wins. A scripted session (`claude -p`, the Agent SDK) has nobody at the
198// keyboard, so what was chosen there is not read: it takes the settings (`pluginConfigs`) as they are given. (The store
199// is shared by every session that loads the mod and rewritten by each at its end: a choice made once in a terminal
200// would otherwise reach the arms of a study that never asked for it, and did.)
201async function loadSettings($: EngineInterface, isInteractive: boolean): Promise<void> {
202  const stored = isInteractive ? await $.store.get('check') : undefined
203  await update($, check, () => (typeof stored === 'boolean' ? stored : cfg.check))
204}
205
206// Every run of the CLI: the resolved program, the user's home as the working directory, the project named with --repo.
207// Without a program nothing is run (the gates on `live.isAllowed` never ask; every caller takes the rejection as a run
208// that failed): a bare name must never reach $.process.run, whose child would resolve it through this process's PATH.
209function runCli($: EngineInterface, args: string[], timeoutMs?: number) {
210  if (cfg.cli === '') return Promise.reject(new Error('verinoda not found on PATH outside the project; set `cli`'))
211  return $.process.run([cfg.cli, ...args], { cwd: cfg.cwd, ...(timeoutMs === undefined ? {} : { timeoutMs }) })
212}
213
214// `check --diff` reads the lines changed against HEAD (and new files whole); a project without git, or a diff the
215// CLI cannot read, falls back to the edited file whole. Exit 3 (something absent) and 4 (something not checked) are
216// answers too. Whatever happens, the edit itself has already gone through.
217async function runCheck($: EngineInterface, root: string, file: string): Promise<{ sites?: CheckSite[] } | undefined> {
218  for (const args of [['check', '--diff', '--json', '--repo', root], ['check', file, '--json', '--repo', root]]) {
219    try {
220      const { exitCode, stdout } = await runCli($, args, CHECK_TIMEOUT_MS)
221      if (exitCode !== 0 && exitCode !== 3 && exitCode !== 4) continue
222      const report = JSON.parse(stdout) as { sites?: CheckSite[] }
223      if (typeof report === 'object' && report !== null) return report
224    } catch {
225      return undefined // a timeout or a CLI that will not start: the second command would wait as long
226    }
227  }
228  return undefined
229}
230
231async function checkEdit($: EngineInterface, root: string, file: string): Promise<string | undefined> {
232  const report = await runCheck($, root, file)
233  const note = report === undefined ? undefined : checkNote(root, file, report, cfg.cli)
234  const at = await $.clock.now()
235  const rel = relPath(root, file)
236  const n = report === undefined ? 0 : badSites(report, rel).length
237  await update($, lastCheck, () => ({ file: rel, n, ok: report !== undefined, at }))
238  return note
239}
240
241type GraphState = { locked: boolean; behind: number; state?: string }
242
243// `update --fast` takes the text in at once and rebuilds the graph in a background `verinoda update`. The graph has
244// caught up when no build holds the lock and no file changed since the latest snapshot (the background build records
245// it); the lock alone misses a build that has not taken it yet. `verinoda graph-state` answers both (D186: the CLI's
246// own subcommand; the mod used to run a python of its own for this, `-c` with the repository as its working directory,
247// which put the repository first on sys.path).
248async function graphState($: EngineInterface, root: string): Promise<GraphState | undefined> {
249  try {
250    const { exitCode, stdout } = await runCli($, ['graph-state', '--repo', root, '--json'])
251    if (exitCode !== 0) return undefined
252    const d = JSON.parse(stdout) as Partial<GraphState>
253    if (typeof d.locked !== 'boolean' || typeof d.behind !== 'number') return undefined
254    return { locked: d.locked, behind: d.behind, ...(typeof d.state === 'string' ? { state: d.state } : {}) }
255  } catch {
256    return undefined
257  }
258}
259
260// One look at the graph (session start, or the pane's "check again"): fresh, a build to watch, or behind.
261async function checkGraph($: EngineInterface): Promise<void> {
262  const root = live.root
263  if (root === undefined || !live.isAllowed || live.isRunning || live.isGraphBehind) return
264  live.isChecking = true
265  live.isUnknown = false
266  live.isSlow = false
267  publish($)
268  const state = await graphState($, root)
269  live.isChecking = false
270  live.noGraph = state?.state === 'no_index'
271  if (state === undefined) live.isUnknown = true
272  else if (live.noGraph) { /* an index folder with no graph yet: said as such, never as fresh */ }
273  else if (state.locked) background(watchGraph($, root, state.behind))
274  else if (state.behind > 0) live.stalledBehind = state.behind
275  else live.freshAt = await $.clock.now()
276  publish($)
277}
278
279// One watcher at a time; a later update while it runs only keeps it going.
280async function watchGraph($: EngineInterface, root: string, files: number): Promise<void> {
281  if (live.isGraphBehind) return
282  live.isGraphBehind = true
283  live.graphFiles = files
284  live.stalledBehind = 0
285  live.isSlow = false
286  live.isUnknown = false
287  const started = await $.clock.now()
288  live.graphSince = started
289  publish($)
290  let idleSince: number | undefined // first poll that saw no build running while behind
291  try {
292    while ((await $.clock.now()) - started < GRAPH_WAIT_MS) {
293      await $.clock.sleep(GRAPH_POLL_MS)
294      if (live.isRunning) {
295        idleSince = undefined
296        continue
297      }
298      const state = await graphState($, root)
299      if (state === undefined) {
300        live.isUnknown = true
301        return
302      }
303      const now = await $.clock.now()
304      if (state.locked || state.behind === 0) idleSince = undefined
305      else idleSince ??= now
306      const isStalled = idleSince !== undefined && now - idleSince >= GRAPH_STALL_MS
307      if (state.behind === 0 || isStalled) {
308        live.stalledBehind = isStalled ? state.behind : 0
309        if (!isStalled) live.freshAt = now
310        return
311      }
312    }
313    live.isSlow = true
314  } finally {
315    live.isGraphBehind = false
316    live.graphSince = null
317    publish($)
318    if (live.pending.size > 0 && !live.isRunning) background(reindex($)) // edits made while the build ran
319  }
320}
321
322async function exists($: EngineInterface, path: string): Promise<boolean> {
323  return (await $.fs.stat(path).catch(() => undefined)) !== undefined
324}
325
326// The project: the folder the settings name, else the nearest one at or above the session's with a .verinoda index.
327async function findRoot($: EngineInterface, named: string, cwd: string): Promise<string | undefined> {
328  if (named !== '') return (await exists($, `${slashes(named)}/.verinoda`)) ? slashes(named) : undefined
329  // a home folder or a drive root is never taken for a project unless the settings name it (Verinoda's own first
330  // scan refuses them too): every edit anywhere under it would re-index it
331  const homes = new Set<string>()
332  const profile = await $.env.get('USERPROFILE').catch(() => undefined)
333  const home = await $.env.get('HOME').catch(() => undefined)
334  for (const h of [profile, home]) if (h) homes.add(norm(h))
335  let dir = slashes(cwd)
336  for (let i = 0; i < 40 && dir !== ''; i++) {
337    const isTooWide = homes.has(norm(dir)) || /^[A-Za-z]:$/.test(dir) || dir === ''
338    if (!isTooWide && (await exists($, `${dir}/.verinoda`))) return dir
339    const up = dir.replace(/\/[^/]*$/, '')
340    if (up === dir || /^[A-Za-z]:$/.test(dir)) break
341    dir = up
342  }
343  return undefined
344}
345
346// A home folder or a drive root: never a project (findRoot), never the folder a compaction's file cards are made in.
347async function isWide($: EngineInterface, dir: string): Promise<boolean> {
348  const d = norm(dir)
349  const profile = await $.env.get('USERPROFILE').catch(() => undefined)
350  const home = await $.env.get('HOME').catch(() => undefined)
351  return d === '' || /^[a-z]:$/.test(d) || [profile, home].some(h => h !== undefined && h !== '' && norm(h) === d)
352}
353
354// The user's home, where every run of the CLI starts; without one (neither variable set), the drive root, which is
355// outside any project the mod would take (findRoot refuses drive roots).
356async function homeFolder($: EngineInterface, root: string): Promise<string> {
357  const profile = await $.env.get('USERPROFILE').catch(() => undefined)
358  const home = await $.env.get('HOME').catch(() => undefined)
359  for (const v of [profile, home]) if (typeof v === 'string' && v.trim() !== '') return slashes(v.trim())
360  const drive = /^[A-Za-z]:/.exec(root)
361  return drive === null ? '/' : `${drive[0]}/`
362}
363
364// The program as PATH names it, outside the project: the first folder of PATH that is not inside the root and holds
365// it (with a PATHEXT extension on Windows); undefined when none does. Nothing is run to find it (`where` would itself
366// be a program found by the child's own search), and the project's own .venv on PATH (an activated one) is skipped.
367async function fromPath($: EngineInterface, name: string, root: string): Promise<string | undefined> {
368  const path = await $.env.get('PATH').catch(() => undefined)
369  if (typeof path !== 'string' || path === '') return undefined
370  const isWindows = /^[A-Za-z]:/.test(root)
371  const pathext = isWindows ? await $.env.get('PATHEXT').catch(() => undefined) : undefined
372  const exts = isWindows
373    ? (typeof pathext === 'string' && pathext !== '' ? pathext : '.EXE;.CMD;.BAT').split(';').map(x => x.trim().toLowerCase()).filter(Boolean)
374    : ['']
375  for (const entry of path.split(isWindows ? ';' : ':')) {
376    const dir = slashes(entry.trim().replace(/^"|"$/g, ''))
377    if (dir === '' || isInside(dir, root)) continue
378    for (const ext of exts) {
379      const candidate = `${dir}/${name}${ext}`
380      const found = await $.fs.stat(candidate).catch(() => undefined)
381      if (found !== undefined && found.kind !== 'dir') return candidate
382    }
383  }
384  return undefined
385}
386
387// The program and the working directory of every run (D186 §4.6: the mod never runs anything from the opened
388// repository, not even a `.venv` it ships). A `cli` setting is taken when it is a bare name (looked up on PATH like the
389// default) or a path outside the root; a path inside the root, or on a network share, is refused like a found one. A
390// name PATH has no program for outside the root leaves no program at all (`nocli`): the OS would find the one inside.
391async function resolveTools($: EngineInterface, root: string, options: Record<string, unknown>): Promise<void> {
392  cfg.cwd = await homeFolder($, root)
393  live.missingCli = ''
394  const given = typeof options.cli === 'string' ? slashes(options.cli.trim()) : ''
395  const isPath = /[/\\]/.test(given)
396  if (given !== '' && isPath && !isInside(given, root) && !given.startsWith('//')) {
397    cfg.cli = given
398    return
399  }
400  const name = given !== '' && !isPath ? given : 'verinoda'
401  cfg.cli = (await fromPath($, name, root)) ?? ''
402  if (cfg.cli === '') live.missingCli = name
403}
404
405// Is the root a project the person trusted (`verinoda trust`)? The list is read through the CLI (its file lives in the
406// user's config dir), once per session; a list that cannot be read trusts nothing.
407async function isTrusted($: EngineInterface, root: string): Promise<boolean> {
408  try {
409    const { exitCode, stdout } = await runCli($, ['trust', '--list', '--json'], TRUST_TIMEOUT_MS)
410    if (exitCode !== 0) return false
411    const d = JSON.parse(stdout) as { trusted?: { path?: unknown; subfolders?: unknown }[] }
412    const key = norm(root)
413    return (Array.isArray(d.trusted) ? d.trusted : []).some(e => {
414      if (typeof e.path !== 'string') return false
415      const p = norm(e.path)
416      // with `subfolders` every folder below counts, except one under a .verinoda folder (reference checkouts live there)
417      return key === p || (e.subfolders === true && key.startsWith(`${p}/`) && !key.slice(p.length + 1).split('/').includes('.verinoda'))
418    })
419  } catch {
420    return false
421  }
422}
423
424// What a re-index came to: `text` is the command's answer (English, as before); `code` lets the pane say it.
425type Outcome = {
426  code: 'noindex' | 'nocli' | 'untrusted' | 'running' | 'graph-fresh' | 'fresh' | 'waiting' | 'updated' | 'failed'
427  n: number
428  text: string
429}
430
431async function reindex($: EngineInterface): Promise<Outcome> {
432  const { root, pending } = live
433  if (root === undefined) return { code: 'noindex', n: 0, text: `no .verinoda index at or above ${live.cwd}` }
434  if (live.missingCli !== '') {
435    return { code: 'nocli', n: 0, text: `${live.missingCli} was not found on PATH outside the project, and a program inside it ` +
436      '(its .venv, say) is never run: set `cli` in the plugin settings to one outside, or install verinoda on PATH' }
437  }
438  if (!live.isAllowed) {
439    return { code: 'untrusted', n: 0, text: `the index at ${root} is in a folder above the session's that is not trusted: ` +
440      `run \`verinoda trust ${root}\` or start Claude Code in it` }
441  }
442  if (live.isRunning) return { code: 'running', n: live.runningCount, text: 'an update is already running' }
443  if (pending.size === 0 && live.isGraphBehind) {
444    return { code: 'graph-fresh', n: 0, text: 'text index fresh; the graph is still being rebuilt' }
445  }
446  if (pending.size === 0 && live.stalledBehind === 0 && live.failed === null && !live.noGraph) {
447    // a scripted session never looked at the graph (D193): what it knows is only that none of its edits waits
448    return { code: 'fresh', n: 0, text: live.isInteractive ? 'index already fresh' : 'no edit of this session waits to be indexed' }
449  }
450  if (live.isGraphBehind) {
451    // the background build holds the lock; `update` would wait for it, so the files wait instead
452    publish($)
453    return { code: 'waiting', n: pending.size, text: `waiting for the graph build; ${plural(pending.size)} will be indexed when it ends` }
454  }
455
456  live.isRunning = true
457  const files = [...pending]
458  const stalled = live.stalledBehind
459  const count = files.length || stalled || live.failed?.n || 0
460  live.runningCount = count
461  pending.clear()
462  live.stalledBehind = 0
463  live.noGraph = false // the update builds the graph; a failure is said by `failed`
464  live.failed = null
465  live.isSlow = false
466  live.isUnknown = false
467  const fail = (error: string) => {
468    files.forEach(f => live.pending.add(f))
469    live.stalledBehind = Math.max(live.stalledBehind, stalled)
470    live.failed = { n: count, error }
471  }
472  publish($)
473  try {
474    const { exitCode, stderr } = await runCli($, ['update', '--fast', '--repo', root], UPDATE_TIMEOUT_MS)
475    if (exitCode !== 0) {
476      fail(`çıkış ${exitCode}: ${stderr.trim().split('\n').pop()?.slice(0, 160) ?? ''}`)
477      return { code: 'failed', n: count, text: `update failed (exit ${exitCode}): ${stderr.slice(0, 300)}` }
478    }
479    live.isRunning = false
480    if (live.isInteractive) background(watchGraph($, root, count))
481    else live.isUnknown = true // nothing watches the build in a scripted session (D193)
482    return { code: 'updated', n: count, text: `text index updated (${plural(count)}); the graph is rebuilt in the background` }
483  } catch (err) {
484    fail(String(err).slice(0, 160))
485    return { code: 'failed', n: count, text: `update failed: ${String(err)}` }
486  } finally {
487    live.isRunning = false
488    publish($)
489  }
490}
491
492const NOTICE_TEXT: Record<Outcome['code'], (n: number) => Notice> = {
493  noindex: () => ({ text: 'Bu projede index yok', tone: 'err' }),
494  nocli: () => ({ text: 'verinoda bulunamadı · `cli` ayarı', tone: 'err' }),
495  untrusted: () => ({ text: 'Klasöre güvenilmiyor · verinoda trust', tone: 'err' }),
496  running: n => ({ text: `Zaten güncelleniyor (${n} dosya)`, tone: 'ok' }),
497  'graph-fresh': () => ({ text: 'Metin güncel · graph hâlâ kuruluyor', tone: 'ok' }),
498  fresh: () => ({ text: 'Index zaten güncel', tone: 'ok' }),
499  waiting: n => ({ text: `Graph bitince ${n} dosya eklenecek`, tone: 'ok' }),
500  updated: n => ({ text: `Güncellendi (${n} dosya) · graph arka planda kuruluyor`, tone: 'ok' }),
501  failed: () => ({ text: 'Güncelleme başarısız · ayrıntı yukarıda', tone: 'err' }),
502}
503
504// The pane's update button: run it, and say what happened under the button for a few seconds.
505async function updateFromPane($: EngineInterface): Promise<void> {
506  const outcome = await reindex($)
507  const said = NOTICE_TEXT[outcome.code](outcome.n)
508  await update($, notice, () => said)
509  await $.clock.sleep(NOTICE_MS)
510  await update($, notice, n => (n === said ? null : n))
511}
512
513async function recheckFromPane($: EngineInterface): Promise<void> {
514  await update($, notice, () => ({ text: 'Kontrol ediliyor…', tone: 'ok' }))
515  await checkGraph($)
516  await update($, notice, () => null)
517}
518
519async function registerImproveTools($: EngineInterface): Promise<void> {
520  for (const spec of IMPROVE_SPECS) {
521    await $.tool.register({ name: spec.name, description: spec.description, inputSchema: spec.inputSchema as unknown as Record<string, unknown> })
522  }
523}
524
525export function settingCommand(arg: string, current: boolean): boolean | undefined {
526  const a = arg.trim().toLowerCase()
527  if (a === '') return !current
528  if (a === 'on' || a === 'açık' || a === 'ac' || a === 'aç') return true
529  if (a === 'off' || a === 'kapalı' || a === 'kapat') return false
530  return undefined
531}
532
533// ---- the pane's words, pictures and layout (pure: tested without the engine) ----------------------------------
534
535export function hhmm(ms: number | null): string {
536  if (ms === null) return '--:--'
537  const d = new Date(ms)
538  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
539}
540
541export type Tone = 'ok' | 'busy' | 'warn' | 'err' | 'idle'
542export const TONE_COLOR: Record<Tone, string> = { ok: 'green', busy: 'cyan', warn: 'yellow', err: 'red', idle: 'gray' }
543export type Action = 'update' | 'retry' | 'recheck'
544
545// Every state as a glyph, words and a tone; the glyph and words carry the meaning, the colour only reinforces it.
546export function describeIndex(s: IndexState): { head: string; tone: Tone; details: string[]; action: Action | null } {
547  switch (s.kind) {
548    case 'checking': return { head: '◌ Kontrol ediliyor…', tone: 'idle', details: [], action: null }
549    case 'fresh': return { head: '✓ Index güncel', tone: 'ok', details: [s.at === null ? 'bu oturumda değişiklik yok' : `son kontrol ${hhmm(s.at)}`], action: null }
550    case 'pending':
551      return s.waiting
552        ? { head: `● ${s.n} dosya bekliyor`, tone: 'warn', details: ['graph bitince eklenecek'], action: null }
553        : { head: `● ${s.n} dosya bekliyor`, tone: 'warn', details: ['tur bitince kendiliğinden güncellenir'], action: 'update' }
554    case 'updating': return { head: `◐ Güncelleniyor · ${s.n} dosya`, tone: 'busy', details: [], action: null }
555    case 'graph':
556      return { head: s.n > 0 ? `◐ Graph kuruluyor · ${s.n} dosya` : '◐ Graph kuruluyor', tone: 'busy',
557        details: [`${hhmm(s.since)}'den beri · genelde 2-4 dk`, 'Metin araması şimdiden güncel'], action: null }
558    case 'behind': return { head: `▲ Graph ${s.n} dosya geride`, tone: 'warn', details: ["Claude'un dışında değişen dosyalar"], action: 'update' }
559    case 'slow': return { head: "▲ Graph kurulumu 10 dk'yı geçti", tone: 'warn', details: [], action: 'recheck' }
560    case 'failed': return { head: `✗ Güncelleme başarısız · ${s.n} dosya bekletiliyor`, tone: 'err', details: [s.error], action: 'retry' }
561    case 'unknown': return { head: '? Graph durumu okunamadı', tone: 'idle', details: [], action: 'recheck' }
562    case 'noindex': return { head: "? Bu projede Verinoda index'i yok", tone: 'idle', details: ['Proje klasöründe çalıştır:', 'verinoda init, sonra verinoda update'], action: null }
563    case 'nocli':
564      return { head: '▲ verinoda bulunamadı · `cli` ayarı', tone: 'warn',
565        details: [`PATH'te projenin dışında ${s.error} yok`, "projenin kendi .venv'indeki asla çalıştırılmaz", '/config ile `cli` ayarına dışarıdaki yolunu yaz'], action: null }
566    case 'untrusted':
567      return { head: "▲ Üstteki klasörün index'ine güvenilmiyor", tone: 'warn',
568        details: [s.error, `izin için: verinoda trust ${s.error}`, "ya da Claude Code'u o klasörde başlat"], action: null }
569  }
570}
571
572export const ACTION_LABEL: Record<Action, string> = { update: 'Şimdi güncelle', retry: 'Tekrar dene', recheck: 'Tekrar kontrol et' }
573export const CHECK_HINT = "Python/Java/Kotlin düzenlemesindeki var olmayan isimler Claude'a söylenir"
574
575export function checkLine(c: CheckInfo | null): { text: string; tone: Tone } | null {
576  if (c === null) return null
577  if (!c.ok) return { text: `Son kontrol çalışmadı: ${c.file} (düzenleme yapıldı)`, tone: 'warn' }
578  if (c.n === 0) return { text: `Son kontrol: ${c.file} · temiz`, tone: 'idle' }
579  return { text: `Son kontrol: ${c.file} · ${c.n} isim bulunamadı, Claude'a söylendi`, tone: 'warn' }
580}
581
582// The mascot (./mascot.tsx) is drawn by the surface as a `Client`, animated there; a surface without `Client`
583// (VS Code, mobile) gets its first frame, still.
584const ANIMATED_SURFACES = ['terminal', 'desktop']
585const MOOD: Record<Tone, Mood> = { ok: 'idle', idle: 'idle', busy: 'busy', warn: 'warn', err: 'err' }
586
587export function mascotCaption(s: IndexState): { text: string; tone: Tone } {
588  if (s.kind === 'failed') return { text: 'Bir şey ters gitti', tone: 'err' }
589  if (s.kind === 'untrusted') return { text: 'İzin bekliyor', tone: 'warn' }
590  if (s.kind === 'nocli') return { text: 'Ayar bekliyor', tone: 'warn' }
591  if (s.kind === 'pending' || s.kind === 'behind' || s.kind === 'slow') return { text: 'Güncelleme bekliyor', tone: 'warn' }
592  if (s.kind === 'updating' || s.kind === 'graph' || s.kind === 'checking') return { text: 'Kodu okuyorum…', tone: 'busy' }
593  if (s.kind === 'noindex') return { text: 'Index yok', tone: 'idle' }
594  return { text: 'Her şey güncel', tone: 'idle' }
595}
596
597// Rows a line takes at this width (a wrapped line may take several).
598export function rowsOf(text: string, columns: number): number {
599  return Math.max(1, Math.ceil(text.length / Math.max(1, columns)))
600}
601
602export const register: Register = (on, options) => {
603  registerImprove(on)
604
605  on('session.start', async ($, e, next) => {
606    live.cwd = await $.session.cwd()
607    cfg.check = options.check === true
608    cfg.motion = options.motion !== false
609    cfg.cards = options.compactCards !== false
610    const named = typeof options.root === 'string' ? options.root.trim() : ''
611    live.root = await findRoot($, named, live.cwd)
612    live.isAllowed = false
613    if (live.root !== undefined) {
614      await resolveTools($, live.root, options)
615      // the index is used where the person chose it: the folder they opened, the one their settings name, or one they
616      // trusted with `verinoda trust`; a .verinoda in an ancestor they never opened is not, so a hostile repository's
617      // index can make the mod run nothing (D186 §4.6). Without a program outside the project not even the trust list
618      // is read.
619      live.isAllowed = live.missingCli === '' && (named !== '' || norm(live.root) === norm(live.cwd) || (await isTrusted($, live.root)))
620    } else if (!(await isWide($, live.cwd))) {
621      // no index anywhere: nothing is re-indexed or checked, but a compaction's file cards need none (D189), only the CLI,
622      // found as ever outside the folder the session was opened in
623      await resolveTools($, live.cwd, options)
624    }
625    live.isInteractive = e.isInteractive !== false
626    await loadSettings($, live.isInteractive)
627    // the improvement list (D175): its command is always there, its tools only for a person and when a list is in play or offered
628    improveMod.interactive = live.isInteractive
629    improveMod.offered = options.improveOffer === true
630    await $.command.register(IMPROVE_COMMAND)
631    if (improveMod.interactive && (improveMod.offered || (await read($, improve)).phase !== 'idle')) await registerImproveTools($)
632    await $.command.register({ name: 'verinoda-update', description: 'Re-index the files edited this session now.' })
633    await $.command.register({ name: 'verinoda-check', description: 'Check each edit of Python/Java/Kotlin code for names that do not exist: on, off, or toggle.' })
634    // not plain `verinoda`: the Verinoda agent skill of that name takes `/verinoda` first
635    await $.command.register({ name: 'verinoda-panel', description: 'Open the Verinoda pane: index state and the check setting.' })
636    // the look at the graph is the pane's, and a scripted session has none (D193): its state is unknown, never fresh
637    live.isChecking = live.isInteractive
638    live.isUnknown = !live.isInteractive
639    publish($)
640    if (live.isInteractive) background(checkGraph($))
641    return next(e)
642  })
643
644  // The server's core tools are first-class: their schemas in the prompt's list, not behind ToolSearch, where the agent
645  // studies found a tool that must first be looked up is not called (0 of 286 sessions with the tools deferred; `locate`
646  // listed in front was called in 51 of 63), and the ToolSearch turn that loads them costs a model call (D186). In this
647  // build a plugin's or a server's tool is deferred unless a hook says not. The descriptions stay the server's.
648  on('tool.describe', { tool: [...MCP_CORE_TOOLS] }, ($, e) => ({ description: e.description, isDeferred: false }))
649
650  // The engine's reminder of the tools behind ToolSearch is composed before the tool.describe answers apply (Claude Code
651  // 2.1.296): it names the three pinned tools too and says a direct call fails, which is false for them; asked, the model
652  // listed them as both in front and deferred. Their names are taken out; the rest of the reminder stands.
653  on('prompt.attachment', { type: 'deferred_tools_delta' }, async ($, e, next) => {
654    const out = await next(e)
655    if (out.text === null) return out
656    const pinned = new Set<string>(MCP_CORE_TOOLS)
657    const lines = out.text.split('\n').filter(l => !pinned.has(l.trim()))
658      .map(l => l.replace(/\bmcp__verinoda__(analyze|project_query|run_tool)\b,?\s?/g, ''))
659    return { text: lines.join('\n') }
660  })
661
662  // The call rule rides the system prompt while the server is connected; the improvement list's offer (D175) with it.
663  on('prompt.compose', async ($, e, next) => {
664    const out = await next(e)
665    const sections = improveSections(out.sections)
666    if (!isServerConnected(e.tools)) return sections === out.sections ? out : { sections }
667    return { sections: [...sections, { id: RULE_SECTION, text: CALL_RULE, scope: 'session' as const }] }
668  })
669
670  // D189: the summary of a compaction keeps one card per file the conversation read or edited (Verinoda reads them
671  // from the files now) instead of the files' text; the main conversation only. The cards are made in the project the
672  // person allowed, else in the folder the session was opened in: a card reads only files the conversation read
673  // already and needs no index, so a project the settings name elsewhere, or a folder with no index, still gets them;
674  // never a home folder or a drive root, never with a CLI inside the folder. A CLI that is missing, older (no `card`),
675  // slow or failing leaves the compaction exactly as it would have run.
676  on('session.compact', async ($, e, next) => {
677    if (e.agentId !== undefined || !cfg.cards || cfg.cli === '') return next(e)
678    const bases = [live.isAllowed ? live.root : undefined, (await isWide($, live.cwd)) ? undefined : live.cwd]
679    for (const base of bases) {
680      if (base === undefined || isInside(cfg.cli, base)) continue
681      const files = touchedFiles(e.messages, base)
682      if (files.length === 0) continue
683      try {
684        const { exitCode, stdout } = await runCli($, ['card', '--repo', base, '--max-chars', String(CARD_CHARS), '--', ...files],
685          CARD_TIMEOUT_MS)
686        if (exitCode === 0 && stdout.trim() !== '') return next({ ...e, instructions: cardInstructions(e.instructions, stdout) })
687      } catch {
688        // no card: the compaction runs as Claude Code's own
689      }
690      return next(e)
691    }
692    return next(e)
693  })
694
695  on('tool.call', { tool: EDIT_TOOLS }, async ($, e, next) => {
696    const ran = await next(e)
697    const root = live.root
698    if (root === undefined || !live.isAllowed || ran.deny !== undefined || ran.isError === true) return ran
699
700    const path = e.tool === 'NotebookEdit' ? e.notebook_path : e.tool === 'Edit' || e.tool === 'Write' ? e.file_path : undefined
701    const file = path === undefined ? '' : norm(path)
702    if (!file.startsWith(`${norm(root)}/`) || file.includes('/.verinoda/')) return ran
703    live.pending.add(file)
704    publish($)
705    if (path === undefined || !isCheckable(path) || !(await read($, check))) return ran
706    // the edit has gone through: nothing the check does may change that
707    const note = await checkEdit($, root, path.replace(/\\/g, '/')).catch(() => undefined)
708    return note === undefined ? ran : { ...ran, context: [...(ran.context ?? []), note] }
709  })
710
711  // One re-index per turn, not per edit; left running so the turn ends at once. Not in a scripted session (D193): its
712  // end waits for a process the mod still runs. In the D193 bench the server closed and the process exited only once this
713  // update had ended, 4.8 s after the last message at the median against 0.4 s without it; in the own-repository study's
714  // Part B, on a loaded machine, a median 68.3 s. Nobody reads the pane there, and an analyze refreshes a changed tree
715  // itself, at once or in the background. /verinoda-update still runs.
716  on('turn.complete', async ($, e, next) => {
717    const improving = await read($, improve)
718    if (e.agentId === undefined && improving.turn !== null && e.turnId === improving.turn) await update($, improve, endOfTurn)
719    // the improvement review waits for the command's own turn to end: a submit from the command's hook is refused by the host
720    if (e.agentId === undefined && improving.queue === 'review') {
721      await update($, improve, (s: ImproveState) => ({ ...s, queue: '' as const, expect: 'review' as const, turn: null, note: '' as const }))
722      const failed = () => update($, improve, (s: ImproveState) => (s.expect === 'review' ? undoSend(s, 'review') : s))
723      background($.prompt.submit({ text: reviewPrompt(improving.subject), asUser: true }).then(r => (r.drop === undefined ? undefined : failed()), failed))
724    }
725    if (e.agentId === undefined && live.isInteractive && live.pending.size > 0 && !live.isRunning) background(reindex($))
726    return next(e)
727  })
728
729  on('command.run', { command: 'verinoda-update' }, async $ => ({ text: (await reindex($)).text }))
730
731  on('command.run', { command: 'verinoda-check' }, async ($, e) => {
732    const value = settingCommand(e.args, await read($, check))
733    if (value === undefined) return { text: 'usage: /verinoda-check [on|off]' }
734    await setCheck($, value)
735    return { text: `check after edits ${value ? 'on' : 'off'}` }
736  })
737
738  on('command.run', { command: 'verinoda-panel' }, async $ => {
739    await $.ui.open({ id: PANE, title: 'Verinoda', focus: true })
740    return { text: 'Verinoda pane opened.' }
741  })
742
743  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
744    const { Box, Button, Text } = $.ui.resolve(e)
745    const s = await read($, idx)
746    const said = await read($, notice)
747    const isCheck = await read($, check)
748    const lastChk = await read($, lastCheck)
749
750    const columns = Math.max(20, e.props.bodyColumns ?? 48)
751    const isInline = e.props.placement === 'inline'
752    const bodyRows = e.props.scroll?.bodyRows ?? 0
753    const tone = (t: Tone) => TONE_COLOR[t]
754    let used = 0 // rows the content takes, counted while the tree is built, to know what is left for the mascot
755    const count = (text: string) => { used += rowsOf(text, columns) }
756
757    // 1 · the index
758    const ix = describeIndex(s)
759    const action = ix.action
760    const indexBlock = (
761      <Box key="index" flexDirection="column">
762        <Text bold color={tone(ix.tone)} wrap="wrap">{ix.head}</Text>
763        {!isInline && ix.details.map((d, i) => <Text key={`d${i}`} dimColor wrap="truncate">{`  ${d}`}</Text>)}
764        {action !== null && (
765          <Button key="update" label={ACTION_LABEL[action]} hotkey="u" variant={action === 'recheck' ? 'secondary' : 'primary'}
766            onPress={() => background(action === 'recheck' ? recheckFromPane($) : updateFromPane($))} />
767        )}
768        {said !== null && (
769          <Text key="notice" color={said.tone === 'err' ? 'red' : said.tone === 'warn' ? 'yellow' : undefined}
770            dimColor={said.tone === 'ok'} wrap="truncate">{`  ${said.text}`}</Text>
771        )}
772      </Box>
773    )
774    count(ix.head)
775    if (!isInline) used += ix.details.length
776    if (action !== null) used += 1
777    if (said !== null) used += 1
778
779    // nothing runs in these three states, so a setting would do nothing and is not drawn
780    if (s.kind === 'noindex' || s.kind === 'nocli' || s.kind === 'untrusted') return <Box flexDirection="column">{indexBlock}</Box>
781
782    // 2 · the check after edits: a two-option control; k always flips it; the last check under it
783    const lastLine = checkLine(lastChk)
784    const checkEl = (
785      <Box key="check" flexDirection="column">
786        <Box flexDirection={columns < 40 ? 'column' : 'row'} columnGap={1}>
787          <Text bold={!isInline}>{isInline ? 'Kontrol' : 'Kod kontrolü'}</Text>
788          <Button key="check-on" label={isCheck ? '● Açık' : 'Açık'} hotkey={isCheck ? undefined : 'k'}
789            variant={isCheck ? 'primary' : 'secondary'} onPress={() => (isCheck ? undefined : setCheck($, true))} />
790          <Button key="check-off" label={isCheck ? 'Kapalı' : '● Kapalı'} hotkey={isCheck ? 'k' : undefined}
791            variant={isCheck ? 'secondary' : 'primary'} onPress={() => (isCheck ? setCheck($, false) : undefined)} />
792        </Box>
793        {!isInline && <Text dimColor wrap="wrap">{CHECK_HINT}</Text>}
794        {lastLine !== null && (
795          <Text key="check-last" dimColor={lastLine.tone === 'idle'} color={lastLine.tone === 'warn' ? 'yellow' : undefined}
796            wrap="truncate">{lastLine.text}</Text>
797        )}
798      </Box>
799    )
800    if (!isInline) {
801      used += 2 + (columns < 40 ? 2 : 0) // the row (stacked when narrow) and the gap above it
802      count(CHECK_HINT)
803      if (lastLine !== null) used += 1
804    }
805
806    if (isInline) {
807      return (
808        <Box flexDirection="column">
809          {indexBlock}
810          <Box flexDirection="row" columnGap={2} flexWrap="wrap">{checkEl}</Box>
811        </Box>
812      )
813    }
814
815    // 3 · footer: only the keys that exist in this drawing
816    const keys = [action !== null ? 'u güncelle' : '', 'k kontrol'].filter(Boolean)
817    const footer = e.props.isFocused ? keys.join(' · ') : 'Kısayollar için ctrl+x tab'
818    used += 2 // the footer and the gap above it
819
820    // 4 · the mascot, only in the room left over: never cropped, never pushing content
821    const spare = bodyRows - used
822    const caption = mascotCaption(s)
823    const showMascot = columns >= 24 && spare >= MASCOT_HEIGHT + 3
824    const mascotProps: MascotProps = {
825      mood: MOOD[caption.tone], caption: caption.text, captionColor: tone(caption.tone), captionDim: caption.tone === 'idle',
826    }
827    const { Client } = $.ui.resolve(e) as { Client?: (props: Record<string, unknown>) => JSX.Element }
828    const mascot = !showMascot ? null : (
829      <Box key="mascot" flexDirection="column" alignItems="center" marginTop={Math.max(0, spare - MASCOT_HEIGHT - 3)}>
830        {Client !== undefined && cfg.motion && ANIMATED_SURFACES.includes(e.surface)
831          ? <Client key="mascot-client" module="./mascot.tsx" props={mascotProps} width={MASCOT_WIDTH} height={MASCOT_HEIGHT + 1} />
832          : (
833            <Box flexDirection="column" width={MASCOT_WIDTH}>
834              {frameRows(0, mascotProps.mood).map((row, i) => (
835                <Text key={`m${i}`} wrap="truncate">
836                  {row.map(([text, c], j) => (c === null ? text : <Text key={`m${i}-${j}`} color={c}>{text}</Text>))}
837                </Text>
838              ))}
839              <Text color={mascotProps.captionColor} dimColor={mascotProps.captionDim} wrap="truncate">{caption.text}</Text>
840            </Box>
841          )}
842      </Box>
843    )
844
845    return (
846      <Box flexDirection="column" rowGap={1}>
847        {indexBlock}
848        {checkEl}
849        {mascot}
850        <Text dimColor wrap="truncate">{footer}</Text>
851      </Box>
852    )
853  })
854}
855
hooks/cards.ts 52 lines
1// File cards for the compaction (D189): which files a conversation read or edited, and what the summarizer is told.
2// Pure: no `$`; register.tsx runs `verinoda card` and passes the cards on (session.compact).
3//
4// A long session reads its whole history again with every request; the compaction is what makes it small again,
5// and what its summary keeps of a file is the model's memory of it. Verinoda reads each file the conversation touched
6// (its path and length, what it is for, its top-level definitions, its imports) and the summarizer is asked to keep
7// that one line instead of the file's text; a later turn reads again what it needs. In the person's sessions a
8// compaction cycle touched 67 files at the median (93 at the 90th percentile, under the 967k window); 40 cards of a
9// real cycle took 0.67 s to make and 7,834 characters.
10
11export const CARD_FILES = 40
12export const CARD_CHARS = 8000
13export const CARD_TIMEOUT_MS = 20_000
14
15const FILE_TOOLS: Readonly<Record<string, string>> = {
16  Read: 'file_path', Edit: 'file_path', MultiEdit: 'file_path', Write: 'file_path', NotebookEdit: 'notebook_path',
17}
18
19export type ToolUse = { tool: string; input: Readonly<Record<string, unknown>> }
20export type Message = { toolUses?: readonly ToolUse[] }
21
22// The files the messages read or edited under `root`, repository-relative (slashes forward, case kept): the edited
23// ones first, then the read ones, each newest first, none under a `.verinoda` folder or climbing out with `..`, at most
24// `max`. A path the model gave is only matched against the root here; `verinoda card` judges it again before reading.
25export function touchedFiles(messages: readonly Message[], root: string, max = CARD_FILES): string[] {
26  const base = root.replace(/\\/g, '/').replace(/\/+$/, '')
27  const prefix = `${base.toLowerCase()}/`
28  const edited: string[] = []
29  const read: string[] = []
30  for (const message of [...messages].reverse()) {
31    for (const u of [...(message.toolUses ?? [])].reverse()) {
32      const key = FILE_TOOLS[u.tool]
33      const raw = key === undefined ? undefined : u.input[key]
34      if (typeof raw !== 'string') continue
35      const p = raw.replace(/\\/g, '/')
36      if (!p.toLowerCase().startsWith(prefix)) continue
37      const rel = p.slice(prefix.length)
38      if (rel === '' || rel.split('/').some(s => s === '..' || s === '.' || s.toLowerCase() === '.verinoda')) continue
39      ;(u.tool === 'Read' ? read : edited).push(rel)
40    }
41  }
42  return [...new Set([...edited, ...read])].slice(0, max)
43}
44
45export const CARDS_HEAD = "Verinoda's cards of the files this conversation read or edited, read from the files on disk now. " +
46  'In the summary keep each of these files as its card, not its contents; a later turn reads again what it needs:'
47
48// What the summarizer is told: what it was told already (a `/compact <focus>`, another plugin's) first, then the cards.
49export function cardInstructions(existing: string | undefined, cards: string): string {
50  return [existing?.trim() ?? '', `${CARDS_HEAD}\n${cards.trim()}`].filter(s => s !== '').join('\n\n')
51}
52
hooks/improve.ts 483 lines
1// The improvement checklist pane (D175), the part that needs no `$`: a proposed list is validated and stored, the
2// person's decisions, what may be sent, what the first sight shows, a report of outcomes applied, the three prompts,
3// the two tools and the pane's words. ./improve-pane.tsx wires it to the engine.
4import type { ImproveDecision, ImproveGroup, ImproveItem, ImproveState, ImproveStatus } from '../types'
5
6export const IMPROVE_PANE = 'verinoda-improve'
7export const IMPROVE_PROPOSE = 'mcp__verinoda-live__improve_propose'
8export const IMPROVE_REPORT = 'mcp__verinoda-live__improve_report'
9
10const TITLE_MAX = 120
11const TEXT_MAX = 600
12const EVIDENCE_MAX = 6
13const EVIDENCE_CHARS = 160
14const ITEMS_MAX = 30
15const SUBJECT_MAX = 80
16const EXTRA_MAX = 20
17const EXTRA_CHARS = 300
18export const OWN_MAX = 10
19export const OWN_CHARS = 300
20export const FIRST_SIGHT = 7
21export const FALLBACK_SUBJECT = 'bu konuşma'
22
23const MODEL_GROUPS = ['problem', 'improvement', 'taste'] as const
24const ID_FORM = /^[A-Za-z0-9_-]{1,16}$/
25const OWN_ID_FORM = /^u\d+$/
26
27export function initialImprove(): ImproveState {
28  return {
29    phase: 'idle', subject: '', items: [], open: null, unfolded: [], extra: [], draft: '', ownSeq: 0, expect: '', queue: '', turn: null, note: '',
30  }
31}
32
33// ---- the list and its parts --------------------------------------------------------------------------------------
34
35// The list holds what has no outcome yet or is waiting for one; the results hold the rest. An item is in one of them.
36export const isInList = (i: ImproveItem): boolean => i.outcome === null || i.outcome.status === 'waiting'
37export const isResult = (i: ImproveItem): boolean => !isInList(i)
38export const isSendable = (i: ImproveItem): boolean => (i.decision === 'apply' || i.decision === 'check') && i.outcome === null
39export const isOwn = (i: ImproveItem): boolean => i.group === 'own'
40export const isWaiting = (i: ImproveItem): boolean => i.outcome?.status === 'waiting'
41export const isUnreported = (i: ImproveItem): boolean => i.outcome?.status === 'unreported'
42
43export const listItems = (s: ImproveState): ImproveItem[] => s.items.filter(isInList)
44export const resultItems = (s: ImproveState): ImproveItem[] => s.items.filter(isResult)
45export const sendableItems = (s: ImproveState): ImproveItem[] => s.items.filter(isSendable)
46export const ownItems = (s: ImproveState): ImproveItem[] => s.items.filter(isOwn)
47export const modelItems = (s: ImproveState): ImproveItem[] => s.items.filter(i => !isOwn(i))
48
49// A text cut to `max` characters, trimmed; a cut ends in an ellipsis.
50export function clip(text: string, max: number): string {
51  const t = text.trim()
52  return t.length <= max ? t : `${t.slice(0, max - 1).trimEnd()}…`
53}
54
55function strings(value: unknown, max: number, chars: number): string[] {
56  if (!Array.isArray(value)) return []
57  const out: string[] = []
58  for (const v of value) {
59    if (typeof v !== 'string' || v.trim() === '') continue
60    out.push(clip(v, chars))
61    if (out.length === max) break
62  }
63  return out
64}
65
66// ---- a proposed list ---------------------------------------------------------------------------------------------
67
68export type Proposal = { subject?: unknown; items?: unknown }
69
70export type Replaced = { n: number; decided: number }
71
72export type Proposed =
73  | { error: string }
74  | { state: ImproveState; replaced: Replaced | null; counts: { problem: number; improvement: number; taste: number } }
75
76const refused = (what: string) => ({ error: `verinoda improve: ${what}; nothing was shown` })
77
78// Validated whole or not at all: the first failure is the answer. The person's own items that were not sent stay.
79export function proposeList(state: ImproveState, input: Proposal, what: string): Proposed {
80  const raw = input.items
81  if (!Array.isArray(raw) || raw.length < 1 || raw.length > ITEMS_MAX) return refused(`items must be a list of 1 to ${ITEMS_MAX} objects`)
82  const seen = new Set<string>()
83  const items: ImproveItem[] = []
84  for (let n = 0; n < raw.length; n++) {
85    const r = raw[n] as Record<string, unknown> | null
86    const at = `item ${n + 1}`
87    if (typeof r !== 'object' || r === null || Array.isArray(r)) return refused(`${at} is not an object`)
88    const id = typeof r.id === 'string' ? r.id.trim() : ''
89    if (id === '' || !ID_FORM.test(id) || OWN_ID_FORM.test(id)) {
90      return refused(`${at} has an id that is empty or not 1 to 16 letters, digits, - or _ (u and digits are kept for the user's own items)`)
91    }
92    if (seen.has(id)) return refused(`id ${id} is used twice`)
93    seen.add(id)
94    if (!MODEL_GROUPS.includes(r.group as never)) return refused(`item ${id} has a group that is not problem, improvement or taste`)
95    const text = (k: string, max: number): string | undefined => {
96      const v = r[k]
97      return typeof v === 'string' && v.trim() !== '' ? clip(v, max) : undefined
98    }
99    const title = text('title', TITLE_MAX)
100    const observation = text('observation', TEXT_MAX)
101    const why = text('why', TEXT_MAX)
102    const change = text('change', TEXT_MAX)
103    for (const [k, v] of [['title', title], ['observation', observation], ['why', why], ['change', change]] as const) {
104      if (v === undefined) return refused(`item ${id} needs a non-empty ${k}`)
105    }
106    items.push({
107      id, group: r.group as ImproveGroup, title: title ?? '', observation: observation ?? '', why: why ?? '', change: change ?? '',
108      cost: typeof r.cost === 'string' ? clip(r.cost, TEXT_MAX) : '', evidence: strings(r.evidence, EVIDENCE_MAX, EVIDENCE_CHARS),
109      seen: r.seen === true, verified: false, checked: '', decision: 'none', sentAs: null, outcome: null,
110    })
111  }
112  const subject = clip(typeof input.subject === 'string' ? input.subject : '', SUBJECT_MAX) || clip(what, SUBJECT_MAX) || FALLBACK_SUBJECT
113  const old = modelItems(state).filter(isInList)
114  const replaced = old.length === 0 ? null : { n: old.length, decided: old.filter(i => i.decision !== 'none').length }
115  const kept = ownItems(state).filter(isSendable)
116  const own = kept.filter(i => i.outcome === null)
117  const counts = { problem: 0, improvement: 0, taste: 0 }
118  for (const i of items) counts[i.group as keyof typeof counts]++
119  return {
120    state: { ...state, phase: 'choosing', subject, items: [...items, ...own], open: null, unfolded: [], extra: [], queue: '', note: '' },
121    replaced, counts,
122  }
123}
124
125export function proposeAnswer(p: { counts: { problem: number; improvement: number; taste: number }; replaced: Replaced | null }, isPlaced: boolean): string {
126  const n = p.counts.problem + p.counts.improvement + p.counts.taste
127  const tail = p.replaced === null ? '' : ` The earlier list (${p.replaced.n} items, ${p.replaced.decided} decisions) was replaced.`
128  return (isPlaced
129    ? `Shown to the user: ${n} items (${p.counts.problem} possible problems, ${p.counts.improvement} improvements, ${p.counts.taste} matters of taste). ` +
130      'Stop here: change nothing and wait for their selection, which arrives as a message.'
131    : `The list is stored (${n} items) but the pane is not on screen. Tell the user to run /verinoda-improve to see it. Change nothing meanwhile.`) + tail
132}
133
134// ---- decisions ---------------------------------------------------------------------------------------------------
135
136export function canCheck(i: ImproveItem): boolean {
137  return i.group === 'problem' && !i.verified
138}
139
140// Pressing the decision an item has clears it. `check` is for a suspected problem that no check confirmed yet; an own item
141// is `apply` from the start and keeps it.
142export function decide(state: ImproveState, id: string, decision: Exclude<ImproveDecision, 'none'>): ImproveState {
143  const i = state.items.find(x => x.id === id)
144  if (i === undefined || !isInList(i) || isOwn(i) || isWaiting(i)) return state
145  if (decision === 'check' && !canCheck(i)) return state
146  const next: ImproveDecision = i.decision === decision ? 'none' : decision
147  return { ...state, items: state.items.map(x => (x.id === id ? { ...x, decision: next } : x)) }
148}
149
150export function addOwn(state: ImproveState, text: string): ImproveState {
151  const t = clip(text, OWN_CHARS)
152  if (t === '' || ownItems(state).filter(isInList).length >= OWN_MAX) return { ...state, draft: '' }
153  const seq = state.ownSeq + 1
154  const item: ImproveItem = {
155    id: `u${seq}`, group: 'own', title: t, observation: '', why: '', change: '', cost: '', evidence: [], seen: true,
156    verified: false, checked: '', decision: 'apply', sentAs: null, outcome: null,
157  }
158  return { ...state, items: [...state.items, item], ownSeq: seq, draft: '' }
159}
160
161export function removeOwn(state: ImproveState, id: string): ImproveState {
162  const i = state.items.find(x => x.id === id)
163  if (i === undefined || !isOwn(i) || !isInList(i) || isWaiting(i)) return state
164  return { ...state, items: state.items.filter(x => x.id !== id), open: state.open === id ? null : state.open }
165}
166
167export const toggleOpen = (state: ImproveState, id: string): ImproveState => ({ ...state, open: state.open === id ? null : id })
168export const unfold = (state: ImproveState, group: ImproveGroup): ImproveState =>
169  state.unfolded.includes(group) ? state : { ...state, unfolded: [...state.unfolded, group] }
170
171// ---- what the first sight shows ----------------------------------------------------------------------------------
172
173// Of the list's model items the seven best ranked, and besides them any item with a decision, any verified one and the open
174// one. A group that was unfolded shows whole. The person's own items are always shown (their own group is small by design).
175export function visibleIds(state: ImproveState): Set<string> {
176  const list = listItems(state)
177  const out = new Set<string>()
178  list.filter(i => !isOwn(i)).forEach((i, rank) => {
179    if (rank < FIRST_SIGHT || i.decision !== 'none' || i.verified || i.id === state.open || state.unfolded.includes(i.group)) out.add(i.id)
180  })
181  for (const i of list) if (isOwn(i)) out.add(i.id)
182  return out
183}
184
185export type RowView = { id: string; mark: string; title: string; suffix: string; waiting: boolean }
186export type GroupView = { group: ImproveGroup; label: string; rows: RowView[]; more: number }
187
188const GROUP_LABEL: Record<ImproveGroup, string> = {
189  problem: 'Olası sorunlar', improvement: 'İşlevsel iyileştirmeler', taste: 'Estetik seçenekler', own: 'Sizin eklediğiniz',
190}
191const MARK: Record<ImproveDecision, string> = { none: '[ ]', apply: '[✓]', keep: '[–]', check: '[?]' }
192
193export function rowSuffix(i: ImproveItem): string {
194  if (i.verified) return ' (doğrulandı)'
195  if (i.group === 'problem' && i.evidence.length === 0) return ' (kanıtsız)'
196  if (i.group === 'taste' && !i.seen) return ' (tahmin)'
197  return ''
198}
199
200export function groupViews(state: ImproveState): GroupView[] {
201  const shown = visibleIds(state)
202  const list = listItems(state)
203  const views: GroupView[] = []
204  for (const group of ['problem', 'improvement', 'taste', 'own'] as const) {
205    const all = list.filter(i => i.group === group)
206    if (all.length === 0) continue
207    const rows = all.filter(i => shown.has(i.id)).map(i => ({
208      id: i.id, mark: MARK[i.decision], title: i.title, suffix: rowSuffix(i), waiting: isWaiting(i),
209    }))
210    views.push({ group, label: GROUP_LABEL[group], rows, more: all.length - rows.length })
211  }
212  return views
213}
214
215export function countsLine(state: ImproveState): string {
216  const list = listItems(state)
217  if (list.length === 0) return ''
218  const send = sendableItems(state)
219  const parts = [
220    `${list.length} madde`,
221    ...([[send.filter(i => i.decision === 'apply').length, 'uygula'], [send.filter(i => i.decision === 'check').length, 'kontrol'],
222      [list.filter(i => i.decision === 'keep').length, 'kalsın']] as const).filter(([n]) => n > 0).map(([n, w]) => `${n} ${w}`),
223  ]
224  return parts.join(' · ')
225}
226
227export const RESULT_WORDS: Record<Exclude<ImproveStatus, 'waiting'>, string> = {
228  applied: '✓ Uygulandı', partial: '◐ Kısmen uygulandı', failed: '✗ Uygulanamadı',
229  not_confirmed: '○ İncelendi: sorun doğrulanmadı', unreported: '? Sonuç bildirilmedi',
230}
231
232export const WORDS = {
233  idle: 'Liste yok. /verinoda-improve [neye bakılsın] ile başlatın.',
234  notSent: 'İstek gönderilemedi.',
235  reviewing: 'İnceleniyor… Claude listeyi hazırlıyor; hiçbir şey değiştirilmiyor.',
236  noList: 'Liste henüz gelmedi. Claude bir soru sormuş olabilir: yanıtlayın ya da /verinoda-improve ile yeniden başlatın.',
237  sent: 'Seçimleriniz gönderildi; sonuçlar burada görünecek.',
238  needOne: 'Göndermek için en az bir madde seçin.',
239  mobileOwn: 'Kendi maddenizi eklemek için terminali ya da masaüstünü kullanın.',
240  unfocused: 'Seçmek için ctrl+x tab',
241  results: 'Sonuçlar',
242  extra: 'Listede olmayan değişiklikler',
243  own: 'Kendi maddeniz',
244  noEvidence: 'Kanıt verilmedi',
245  waiting: ' … bekleniyor',
246}
247
248// ---- sending and what comes back ---------------------------------------------------------------------------------
249
250// Every sendable item gets `sentAs` (its decision) and the outcome waiting; its decision, and so its mark, stays.
251export function markSent(state: ImproveState): ImproveState {
252  return {
253    ...state, phase: 'sent', expect: 'selection', turn: null, note: '',
254    items: state.items.map(i => (isSendable(i)
255      ? { ...i, sentAs: i.decision === 'check' ? 'check' as const : 'apply' as const, outcome: { status: 'waiting' as const, note: '', evidence: [] } }
256      : i)),
257  }
258}
259
260// The person stops waiting, or the mod's own turn ended: what is still waiting is unreported, and the list can be marked again.
261export function unreport(state: ImproveState): ImproveState {
262  return {
263    ...state, phase: 'choosing',
264    items: state.items.map(i => (isWaiting(i) ? { ...i, outcome: { status: 'unreported' as const, note: '', evidence: [] } } : i)),
265  }
266}
267
268// A prompt that did not enter: the state before the press, so that the same marks can be sent again.
269export function undoSend(state: ImproveState, kind: 'review' | 'selection' | 'report'): ImproveState {
270  const base = { ...state, expect: '' as const, queue: '' as const, note: 'not-sent' as const }
271  if (kind === 'review') return { ...base, phase: 'idle' }
272  if (kind === 'selection') {
273    return { ...base, phase: 'choosing', items: state.items.map(i => (isWaiting(i) ? { ...i, sentAs: null, outcome: null } : i)) }
274  }
275  return {
276    ...base, phase: 'choosing',
277    items: state.items.map(i => (isWaiting(i) ? { ...i, outcome: { status: 'unreported' as const, note: '', evidence: [] } } : i)),
278  }
279}
280
281export function askReport(state: ImproveState): ImproveState {
282  return {
283    ...state, phase: 'sent', expect: 'report', turn: null, note: '',
284    items: state.items.map(i => (isUnreported(i) ? { ...i, outcome: { status: 'waiting' as const, note: '', evidence: [] } } : i)),
285  }
286}
287
288export function startReview(state: ImproveState, what: string): ImproveState {
289  return {
290    ...state, phase: 'reviewing', subject: what, items: ownItems(state).filter(isSendable), open: null, unfolded: [], extra: [],
291    expect: '', queue: 'review', turn: null, note: '',
292  }
293}
294
295export type Report = { outcomes?: unknown; extra_changes?: unknown }
296const REPORT_STATUSES = ['applied', 'partial', 'failed', 'confirmed', 'not_confirmed'] as const
297const FITS: Record<'apply' | 'check', readonly string[]> = { apply: ['applied', 'partial', 'failed'], check: ['confirmed', 'not_confirmed'] }
298
299export type Reported = { error: string } | { state: ImproveState; answer: string }
300
301// A call with any invalid outcome records nothing.
302export function applyReport(state: ImproveState, input: Report): Reported {
303  const fail = (what: string) => ({ error: `verinoda improve: ${what}` })
304  const raw = input.outcomes
305  if (!Array.isArray(raw) || raw.length < 1 || raw.some(o => typeof o !== 'object' || o === null || Array.isArray(o))) {
306    return fail('outcomes must list at least one item; nothing was recorded')
307  }
308  const outs = raw as Record<string, unknown>[]
309  const ids = outs.map(o => (typeof o.id === 'string' ? o.id.trim() : ''))
310  const twice = ids.find((id, n) => ids.indexOf(id) !== n)
311  if (twice !== undefined) return fail(`item ${twice} is reported twice`)
312  const byId = new Map(state.items.map(i => [i.id, i]))
313  for (const id of ids) {
314    const i = byId.get(id)
315    if (i === undefined || !(isWaiting(i) || isUnreported(i))) return fail(`no item ${id} is waiting for an outcome`)
316  }
317  for (const [n, o] of outs.entries()) {
318    const i = byId.get(ids[n] ?? '') as ImproveItem
319    const sent = i.sentAs ?? 'apply'
320    if (!REPORT_STATUSES.includes(o.status as never) || !FITS[sent].includes(o.status as string)) {
321      return fail(`item ${i.id} was sent to ${sent}; its outcome is one of ${FITS[sent].join(sent === 'apply' ? ', ' : ' or ').replace(/, ([a-z_]+)$/, ' or $1')}`)
322    }
323  }
324  for (const [n, o] of outs.entries()) {
325    if (typeof o.note !== 'string' || o.note.trim() === '') return fail(`item ${ids[n]} needs a note the user can read`)
326  }
327  const items = state.items.map(i => {
328    const n = ids.indexOf(i.id)
329    if (n < 0) return i
330    const o = outs[n] as Record<string, unknown>
331    const note = clip(o.note as string, TEXT_MAX)
332    const evidence = strings(o.evidence, EVIDENCE_MAX, EVIDENCE_CHARS)
333    if (o.status === 'confirmed') {
334      const change = typeof o.change === 'string' && o.change.trim() !== '' ? clip(o.change, TEXT_MAX) : i.change
335      return {
336        ...i, verified: true, checked: note, outcome: null, decision: 'none' as const, sentAs: null, change,
337        evidence: [...i.evidence, ...evidence].slice(0, EVIDENCE_MAX),
338      }
339    }
340    return { ...i, outcome: { status: o.status as ImproveStatus, note, evidence } }
341  })
342  const extra = [...state.extra, ...strings(input.extra_changes, EXTRA_MAX, EXTRA_CHARS)].slice(0, EXTRA_MAX)
343  const waiting = items.filter(isWaiting)
344  const next: ImproveState = { ...state, items, extra, phase: state.phase === 'sent' && waiting.length === 0 ? 'choosing' : state.phase }
345  const still = waiting.length > 0 ? ` Still waiting for: ${waiting.map(i => i.id).join(', ')}.` : ''
346  return { state: next, answer: `Recorded: ${outs.length} outcomes.${still}` }
347}
348
349// ---- the three prompts -------------------------------------------------------------------------------------------
350
351export function reviewPrompt(what: string): string {
352  const w = what.trim()
353  return [
354    'Make a list of what could be changed here so that I can choose. Do not change anything yet.',
355    `What to look at: ${w === '' ? 'what we have been working on in this conversation. If that is not clear, ask me one question first.' : w}`,
356    '',
357    'Look at it first: read the code, and if it has a rendered view you can look at, look at it. Then call',
358    `${IMPROVE_PROPOSE} with the items, ranked, the most worth doing first. Do not pad the list. Then stop and`,
359    'wait for my selection.',
360  ].join('\n')
361}
362
363export function selectionPrompt(state: ImproveState): string {
364  const send = sendableItems(state)
365  const line = (i: ImproveItem, withChange: boolean) =>
366    isOwn(i) ? `- [${i.id}] ${i.title} (my own item)` : `- [${i.id}] ${i.title}${withChange ? `: ${i.change}` : ''}`
367  const section = (head: string, items: ImproveItem[], withChange: boolean) =>
368    items.length === 0 ? [] : [head, ...items.map(i => line(i, withChange)), '']
369  const keep = listItems(state).filter(i => i.decision === 'keep' && !isOwn(i))
370  return [
371    `My decisions on the improvement list (${state.subject}):`,
372    '',
373    ...section('Apply these:', send.filter(i => i.decision === 'apply'), true),
374    ...section('Check these first (investigate only; change nothing for them):', send.filter(i => i.decision === 'check'), false),
375    ...section('Keep these as they are (do not change them, also not as a side effect):', keep, false),
376    'Everything else stays as it is. You may make the small auxiliary changes an item needs. If one would add behaviour, change',
377    'behaviour I did not choose, or cost something, tell me before you do it. When you are done or cannot go on, call',
378    `${IMPROVE_REPORT} with one outcome for each item to apply or to check, and list under extra_changes any`,
379    'change that was not on the list.',
380  ].join('\n')
381}
382
383export function reportPrompt(ids: string[]): string {
384  return [
385    `Report the outcome of the items I sent that you have not reported yet (${ids.join(', ')}) with ${IMPROVE_REPORT}.`,
386    'Change nothing else.',
387  ].join('\n')
388}
389
390// A turn belongs to the mod when its text starts with the first line of the prompt that was submitted.
391export function firstLine(prompt: string): string {
392  return (prompt.split('\n')[0] ?? '').trim()
393}
394
395export function expectedLine(state: ImproveState): string {
396  if (state.expect === 'review') return firstLine(reviewPrompt(''))
397  if (state.expect === 'selection') return firstLine(selectionPrompt(state))
398  if (state.expect === 'report') return firstLine(reportPrompt(state.items.filter(isWaiting).map(i => i.id)))
399  return ''
400}
401
402// ---- the tools ---------------------------------------------------------------------------------------------------
403
404export const IMPROVE_SPECS = [
405  {
406    name: 'improve_propose',
407    description:
408      'Show the user a list of what could be changed, in the Verinoda pane, so that they choose. Call it only when the user asked ' +
409      'for improvement options or a review list, in words or with /verinoda-improve; never on your own initiative. Before calling, ' +
410      'look at the code or the screen in question and change nothing. Rank the items, the most worth doing first, and do not pad ' +
411      'the list. Each item is one change the user can say yes or no to. `group`: `problem` is a possible bug, inconsistency or ' +
412      'unexpected behaviour (give `evidence`, the file:line you read); `improvement` is usability, readability, performance or ' +
413      'upkeep; `taste` is look, tone, density, colour or layout, a preference and not a defect (set `seen` to true only if you ' +
414      'judged it from a rendered view or a screenshot). `title` says the change in one concrete line (not "improve the hierarchy" ' +
415      'but "make Save the only primary button"); `observation` is what is there now; `why` is why it may matter; `change` is ' +
416      'exactly what you would do and what stays as it is; `cost` is what it costs or risks, if anything. After the call, stop: ' +
417      'change nothing and wait for the user\'s selection, which arrives as a message.',
418    inputSchema: {
419      type: 'object',
420      properties: {
421        subject: { type: 'string', description: 'What was looked at, in a few words: a file, a screen, a module' },
422        items: {
423          type: 'array', minItems: 1, maxItems: 30,
424          items: {
425            type: 'object',
426            properties: {
427              id: { type: 'string', description: 'Short and unique in this list: i1, i2, ...' },
428              group: { enum: ['problem', 'improvement', 'taste'] },
429              title: { type: 'string' },
430              observation: { type: 'string' },
431              why: { type: 'string' },
432              change: { type: 'string' },
433              cost: { type: 'string' },
434              evidence: { type: 'array', items: { type: 'string' } },
435              seen: { type: 'boolean' },
436            },
437            required: ['id', 'group', 'title', 'observation', 'why', 'change'],
438          },
439        },
440      },
441      required: ['subject', 'items'],
442    },
443  },
444  {
445    name: 'improve_report',
446    description:
447      'Report what happened to each item the user sent from the Verinoda pane, once you are done or cannot go on. One outcome per ' +
448      'item id you were given. For an item to apply: `applied` (done as described), `partial` (say what is missing) or `failed` ' +
449      '(say why). For an item to check first: `confirmed` (the problem is real; put the fix you propose in `change` and do not ' +
450      'apply it) or `not_confirmed` (you looked and found nothing that needs a change). `note` is one or two sentences the user ' +
451      'reads; `evidence` is what shows it: the check you ran and its result, a file:line. List under `extra_changes` every change ' +
452      'you made that was not on the list.',
453    inputSchema: {
454      type: 'object',
455      properties: {
456        outcomes: {
457          type: 'array', minItems: 1,
458          items: {
459            type: 'object',
460            properties: {
461              id: { type: 'string' },
462              status: { enum: ['applied', 'partial', 'failed', 'confirmed', 'not_confirmed'] },
463              note: { type: 'string' },
464              change: { type: 'string' },
465              evidence: { type: 'array', items: { type: 'string' } },
466            },
467            required: ['id', 'status', 'note'],
468          },
469        },
470        extra_changes: { type: 'array', items: { type: 'string' } },
471      },
472      required: ['outcomes'],
473    },
474  },
475] as const
476
477// The one line the system prompt carries when `improveOffer` is on.
478export const OFFER_SECTION =
479  'When the user asks for something to be better, nicer, cleaner or of higher quality without saying what should change, do ' +
480  'not guess and do not start editing. Offer in one line to list what could be changed so that they choose: ' +
481  '`/verinoda-improve` opens the list, and they may add what to look at. If they ask for the list in words, look first, then ' +
482  `call \`${IMPROVE_PROPOSE}\`. A request that says what to change is not vague: do it.`
483
hooks/improve-pane.tsx 306 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3
4import type { ImproveGroup, ImproveItem, ImproveState } from '../types'
5import {
6  addOwn, applyReport, askReport, canCheck, countsLine, decide, expectedLine, groupViews, IMPROVE_PANE, IMPROVE_PROPOSE, IMPROVE_REPORT,
7  IMPROVE_SPECS, initialImprove, isInList, isUnreported, isWaiting, listItems, markSent, modelItems, OFFER_SECTION, OWN_MAX,
8  proposeAnswer, proposeList, removeOwn, reportPrompt, resultItems, RESULT_WORDS, selectionPrompt, sendableItems,
9  startReview, toggleOpen, undoSend, unfold, unreport, WORDS, ownItems,
10} from './improve'
11import type { Proposal, Report } from './improve'
12
13// One key of the session's state holds all of it (declared in ../types); a reload keeps it. The feature is why this file
14// exists apart from register.tsx: its drawing and hooks are a module of their own that `register` calls once (D175).
15export const improve = atom({ plugin: 'verinoda-live', key: 'improve' } as const, initialImprove())
16
17export const COMMAND = {
18  name: 'verinoda-improve',
19  description: 'List what could be changed here and choose what to apply; nothing changes until you choose.',
20  argumentHint: '[what to look at]',
21}
22const TITLE = 'İyileştirme'
23const PANE_ROWS = 16
24
25// The session's interactivity, kept from `session.start` as everywhere in this mod: nobody at the keyboard gets none of it.
26export const mod = { interactive: false, offered: false }
27
28// Work left running after a hook returns: a rejection after the module unloaded is no error of the person's.
29function background(work: Promise<unknown>): void {
30  work.catch(() => undefined)
31}
32
33const patch = ($: EngineInterface, fn: (s: ImproveState) => ImproveState) => update($, improve, fn).then(() => undefined)
34
35async function registerTools($: EngineInterface): Promise<void> {
36  for (const spec of IMPROVE_SPECS) {
37    await $.tool.register({ name: spec.name, description: spec.description, inputSchema: spec.inputSchema as unknown as Record<string, unknown> })
38  }
39}
40
41const openPane = ($: EngineInterface) => $.ui.open({ id: IMPROVE_PANE, title: TITLE, focus: true, rows: PANE_ROWS })
42
43// A prompt the mod submits is the person's own decision, read bare by the model. Never awaited by a press (the turn may not be
44// able to start until the handler returns); one that did not enter puts the state back as it was. (The review prompt is
45// submitted from register.tsx, from turn.complete: the host refuses a submit from a command's hook.)
46function submit($: EngineInterface, kind: 'selection' | 'report', text: string): void {
47  const back = () => patch($, s => (s.expect === kind ? undoSend(s, kind) : s))
48  background($.prompt.submit({ text, asUser: true }).then(r => (r.drop === undefined ? undefined : back()), back))
49}
50
51// The turn the mod's own prompt started has ended, or was interrupted.
52export function endOfTurn(s: ImproveState): ImproveState {
53  const base = { ...s, turn: null }
54  if (s.phase === 'sent') return unreport(base)
55  if (s.phase === 'reviewing') return { ...base, note: 'no-list' }
56  return base
57}
58
59// The three events `register.tsx` already hooks without a matcher (a second such hook is refused) reach this feature through
60// what is exported here; `$` is never passed across an import, so the few lines that need it stay in `register.tsx`.
61export function improveSections(sections: readonly { id: string; text: string; scope: 'session' | 'shared' }[]) {
62  if (!mod.offered || !mod.interactive) return sections
63  return [...sections, { id: 'verinoda-live:improve', text: OFFER_SECTION, scope: 'session' as const }]
64}
65
66export function registerImprove(on: On): void {
67  // First-class, as the Verinoda server's core tools are (MCP_CORE_TOOLS in register.tsx): a tool the model must look up
68  // first is not called.
69  on('tool.describe', { tool: [IMPROVE_PROPOSE, IMPROVE_REPORT] }, ($, e) => {
70    const spec = IMPROVE_SPECS.find(s => `mcp__verinoda-live__${s.name}` === e.tool)
71    return { description: spec?.description ?? e.description, isDeferred: false }
72  })
73
74  on('command.run', { command: COMMAND.name }, async ($, e) => {
75    if (!mod.interactive) return { text: 'verinoda improve needs a person to choose: it does nothing in a scripted session' }
76    const what = e.args.trim()
77    const s = await read($, improve)
78    const size = listItems(s).length
79    if (s.phase === 'sent') {
80      await openPane($)
81      return { text: 'a selection is being applied; its outcomes will show in the pane' }
82    }
83    if (s.phase === 'choosing' && what === '' && (size > 0 || s.items.some(isUnreported))) {
84      await openPane($)
85      return { text: `improvement list opened (${size} items)` }
86    }
87    // the list this replaces: told only when the person had decided something in it
88    const old = modelItems(s).filter(isInList)
89    const replaced = old.some(i => i.decision !== 'none') ? ` (the earlier list of ${old.length} items was replaced)` : ''
90    await registerTools($)
91    await patch($, x => startReview(x, what))
92    await openPane($)
93    // the review prompt goes out when this command's own turn ends (register.tsx): the host refuses a submit from here
94    return { text: `looking at it; the list will appear in the pane, and nothing is changed until you choose${replaced}` }
95  })
96
97  on('tool.call', { tool: IMPROVE_PROPOSE }, async ($, e) => {
98    if (!mod.interactive) return { result: 'verinoda improve: nobody is at the keyboard to choose; ask in text instead' }
99    const s = await read($, improve)
100    if (s.phase === 'sent') {
101      return { result: 'verinoda improve: a selection is being applied; report its outcomes with improve_report before proposing a new list' }
102    }
103    const p = proposeList(s, e as unknown as Proposal, s.phase === 'reviewing' ? s.subject : '')
104    if ('error' in p) return { result: p.error }
105    await patch($, () => p.state)
106    const opened = await openPane($)
107    return { result: proposeAnswer(p, opened.isPlaced) }
108  })
109
110  on('tool.call', { tool: IMPROVE_REPORT }, async ($, e) => {
111    const s = await read($, improve)
112    const r = applyReport(s, e as unknown as Report)
113    if ('error' in r) return { result: r.error }
114    await patch($, () => r.state)
115    return { result: r.answer }
116  })
117
118  // Which turn is the mod's own: the one whose text starts with the first line of the prompt that was submitted.
119  on('turn.start', async ($, e, next) => {
120    const s = await read($, improve)
121    if (s.expect !== '' && e.text.trim().startsWith(expectedLine(s))) await patch($, x => ({ ...x, turn: e.turnId, expect: '' }))
122    return next(e)
123  })
124
125  // `/clear` ends the conversation without a `session.start` after it, so the list of the old one goes.
126  on('session.end', async ($, e, next) => {
127    if (e.reason === 'clear') await patch($, initialImprove)
128    return next(e)
129  })
130
131  on('ui.render', { component: 'Pane', requestId: IMPROVE_PANE }, async ($, e) => {
132    const { Box, Button, Text, Input } = $.ui.resolve(e) as ReturnType<typeof $.ui.resolve> & { Input?: unknown }
133    const InputEl = Input as ((props: Record<string, unknown>) => JSX.Element) | undefined
134    const s = await read($, improve)
135    const columns = Math.max(20, e.props.bodyColumns ?? 48)
136    const isNarrow = columns < 40
137
138    if (s.phase === 'idle') {
139      return (
140        <Box flexDirection="column">
141          <Text wrap="wrap">{WORDS.idle}</Text>
142          {s.note === 'not-sent' && <Text key="not-sent" color="yellow" wrap="wrap">{WORDS.notSent}</Text>}
143        </Box>
144      )
145    }
146    if (s.phase === 'reviewing') {
147      return (
148        <Box flexDirection="column">
149          <Text wrap="wrap">{s.note === 'no-list' ? WORDS.noList : WORDS.reviewing}</Text>
150          {s.note === 'not-sent' && <Text key="not-sent" color="yellow" wrap="wrap">{WORDS.notSent}</Text>}
151        </Box>
152      )
153    }
154
155    const isSent = s.phase === 'sent'
156    const results = resultItems(s)
157    const views = groupViews(s)
158    const sendN = sendableItems(s).length
159    const counts = countsLine(s)
160    const openItem = s.items.find(i => i.id === s.open && isInList(i))
161
162    const detail = (i: ImproveItem) => {
163      const line = (k: string, label: string, text: string) => <Text key={k} wrap="wrap">{`    ${label}: ${text}`}</Text>
164      if (i.group === 'own') {
165        return (
166          <Box key={`open-${i.id}`} flexDirection="column">
167            {!isSent && !isWaiting(i) && <Button key="act-remove" label="Kaldır" variant="secondary" onPress={() => background(patch($, x => removeOwn(x, i.id)))} />}
168          </Box>
169        )
170      }
171      const evidence = i.evidence.length > 0 ? i.evidence.join(', ') : i.group === 'problem' ? WORDS.noEvidence : ''
172      const pick = (d: 'apply' | 'keep' | 'check', label: string, hotkey: string) => (
173        <Button key={`act-${d}`} label={`${i.decision === d ? '● ' : ''}${label}`} hotkey={hotkey}
174          variant={i.decision === d ? 'primary' : 'secondary'} onPress={() => background(patch($, x => decide(x, i.id, d)))} />
175      )
176      return (
177        <Box key={`open-${i.id}`} flexDirection="column">
178          {line('obs', 'Gözlem', i.observation)}
179          {line('why', 'Neden', i.why)}
180          {line('chg', 'Öneri', i.change)}
181          {i.cost !== '' && line('cost', 'Bedel', i.cost)}
182          {evidence !== '' && line('evd', 'Kanıt', evidence)}
183          {i.verified && line('chk', 'İnceleme', i.checked)}
184          {!isSent && (
185            <Box flexDirection={isNarrow ? 'column' : 'row'} columnGap={1}>
186              {pick('apply', 'Uygula', 'u')}
187              {pick('keep', 'Kalsın', 'k')}
188              {canCheck(i) && pick('check', 'Önce kontrol et', 'c')}
189            </Box>
190          )}
191        </Box>
192      )
193    }
194
195    const resultBlock = results.length === 0 ? null : (
196      <Box key="results" flexDirection="column">
197        <Text bold>{WORDS.results}</Text>
198        {results.map(i => {
199          const status = (i.outcome?.status ?? 'unreported') as keyof typeof RESULT_WORDS
200          const tone = status === 'applied' ? 'green' : status === 'failed' ? 'red' : status === 'not_confirmed' ? undefined : 'yellow'
201          return (
202            <Box key={`res-${i.id}`} flexDirection="column">
203              <Text color={tone} dimColor={status === 'not_confirmed'} wrap="wrap">{`  ${RESULT_WORDS[status]} · ${i.title}`}</Text>
204              {i.outcome !== null && i.outcome.note !== '' && <Text key="note" wrap="wrap">{`      ${i.outcome.note}`}</Text>}
205              {i.outcome !== null && i.outcome.evidence.length > 0 && <Text key="evd" dimColor wrap="wrap">{`      ${i.outcome.evidence.join(', ')}`}</Text>}
206            </Box>
207          )
208        })}
209        {!isSent && results.some(isUnreported) && (
210          <Button key="ask-report" label="Sonucu iste" variant="secondary"
211            onPress={() => background(askFor($))} />
212        )}
213      </Box>
214    )
215
216    const extraBlock = s.extra.length === 0 ? null : (
217      <Box key="extra" flexDirection="column">
218        <Text bold>{WORDS.extra}</Text>
219        {s.extra.map((x, n) => <Text key={`extra-${n}`} wrap="wrap">{`  · ${x}`}</Text>)}
220      </Box>
221    )
222
223    const groupBlock = (g: { group: ImproveGroup; label: string; rows: { id: string; mark: string; title: string; suffix: string; waiting: boolean }[]; more: number }) => (
224      <Box key={`group-${g.group}`} flexDirection="column">
225        <Text bold>{g.label}</Text>
226        {g.rows.map(r => (
227          <Box key={`row-${r.id}`} flexDirection="column">
228            {isSent
229              ? <Text key={`item-${r.id}`} wrap="wrap">{`  ${r.mark} ${r.title}${r.suffix}${r.waiting ? WORDS.waiting : ''}`}</Text>
230              : <Button key={`item-${r.id}`} plain label={`${r.mark} ${r.title}${r.suffix}`} onPress={() => background(patch($, x => toggleOpen(x, r.id)))} />}
231            {openItem !== undefined && openItem.id === r.id && detail(openItem)}
232          </Box>
233        ))}
234        {!isSent && g.more > 0 && g.group !== 'own' && (
235          <Button key={`more-${g.group}`} plain label={`${g.more} madde daha`} onPress={() => background(patch($, x => unfold(x, g.group)))} />
236        )}
237      </Box>
238    )
239
240    const ownCount = ownItems(s).filter(isInList).length
241    let ownEl = null
242    if (!isSent && ownCount < OWN_MAX) {
243      ownEl = e.surface === 'mobile' || InputEl === undefined
244        ? <Text key="own-mobile" dimColor wrap="wrap">{WORDS.mobileOwn}</Text>
245        : (
246          <InputEl key="own" label={WORDS.own} submitLabel="ekle" value={s.draft}
247            onInput={(v: string) => background(patch($, x => ({ ...x, draft: v })))}
248            onSubmit={(v: string) => background(patch($, x => addOwn(x, v)))} />
249        )
250    }
251
252    const sendEl = isSent
253      ? (
254        <Box key="sent" flexDirection="column">
255          <Text wrap="wrap">{WORDS.sent}</Text>
256          <Button key="stop-waiting" label="Beklemeyi bırak" variant="secondary"
257            onPress={() => background(patch($, x => ({ ...unreport(x), expect: '', turn: null, note: '' })))} />
258        </Box>
259      )
260      : sendN > 0
261        ? <Button key="send" label={`Gönder (${sendN})`} hotkey="g" variant="primary" onPress={() => background(sendSelection($))} />
262        : <Text key="need-one" dimColor wrap="wrap">{WORDS.needOne}</Text>
263
264    const keys = isSent ? [] : [sendN > 0 ? 'g gönder' : '', views.some(v => v.rows.length > 0) ? 'tab gezin · enter aç' : ''].filter(Boolean)
265    const footer = e.props.isFocused ? keys.join(' · ') : WORDS.unfocused
266
267    return (
268      <Box flexDirection="column" rowGap={1}>
269        <Box key="head" flexDirection="column">
270          <Text bold wrap="wrap">{`İyileştirme: ${s.subject}`}</Text>
271          {counts !== '' && <Text dimColor wrap="wrap">{counts}</Text>}
272        </Box>
273        {s.note === 'not-sent' && <Text key="not-sent" color="yellow" wrap="wrap">{WORDS.notSent}</Text>}
274        {resultBlock}
275        {extraBlock}
276        {views.map(groupBlock)}
277        {ownEl}
278        {sendEl}
279        {footer !== '' && <Text key="footer" dimColor wrap="wrap">{footer}</Text>}
280      </Box>
281    )
282  })
283}
284
285// Press handlers kept beside the drawing: both read the list as it is when pressed, mark it and then raise the prompt.
286async function sendSelection($: EngineInterface): Promise<void> {
287  let text = ''
288  await patch($, s => {
289    if (s.phase !== 'choosing' || sendableItems(s).length === 0) return s
290    text = selectionPrompt(s)
291    return markSent(s)
292  })
293  if (text !== '') submit($, 'selection', text)
294}
295
296async function askFor($: EngineInterface): Promise<void> {
297  let text = ''
298  await patch($, s => {
299    const ids = s.items.filter(isUnreported).map(i => i.id)
300    if (s.phase !== 'choosing' || ids.length === 0) return s
301    text = reportPrompt(ids)
302    return askReport(s)
303  })
304  if (text !== '') submit($, 'report', text)
305}
306
hooks/mascot.tsx 91 lines
1import type { ClientModule } from 'claude-code'
2
3// Claude's mascot in purple, reading the code through its glasses: 20 x 8, block glyphs only (single cells in
4// Cascadia Mono), every body cell a full block so the background never shows through the face. Animated the way
5// Claude Code's mascot is: it blinks every few seconds and shuffles its feet; while Verinoda works (`busy`) it reads,
6// a glint sweeping across its lenses, its feet and arms quicker. Drawn by the surface (a `Client`), so a frame
7// repaints only this region: no render pass, no hook.
8
9export type Mood = 'idle' | 'busy' | 'warn' | 'err'
10export type MascotProps = { mood: Mood; caption: string; captionColor: string; captionDim: boolean }
11export type Segment = readonly [string, string | null] // text, colour (null: uncoloured padding)
12
13const HEAD = '#a78bfa'
14const BODY = '#8b5cf6'
15const SIDE = '#7c3aed'
16const FRAME = '#5b21b6'
17const LENS = '#1e1b4b'
18const GLINT = '#f5f3ff'
19const BLUSH = '#f0abfc'
20const MOUTH = '#4c1d95'
21const BELLY = '#6d28d9'
22
23export const MASCOT_WIDTH = 20
24export const MASCOT_HEIGHT = 8
25export const TICK_MS = 120
26
27const BLINK_EVERY_MS = 4_200 // a blink at the end of each cycle
28const BLINK_MS = 160
29const STEP_MS: Record<Mood, number> = { idle: 840, busy: 240, warn: 840, err: 840 }
30const SWEEP_MS = 360 // busy: the glint moves one cell along the lens
31
32// One lens on the glasses row: five cells, the glint at `at` (0-4), the rest dark; closed, the lid in head colour.
33function lens(at: number, isClosed: boolean): Segment[] {
34  if (isClosed) return [['█████', HEAD]]
35  return [0, 1, 2, 3, 4].map(i => (i === at ? ['█', GLINT] : ['█', LENS]) as Segment)
36}
37
38// The frame `t` ms into the animation for this mood, as rows of coloured segments, every row 20 cells.
39export function frameRows(t: number, mood: Mood): Segment[][] {
40  const isBlink = t % BLINK_EVERY_MS >= BLINK_EVERY_MS - BLINK_MS
41  const step = Math.floor(t / STEP_MS[mood]) % 2
42  const glint = mood === 'busy' ? Math.floor(t / SWEEP_MS) % 5 : 0
43  const arms: [string, string] = mood === 'busy' && step === 1 ? ['▝█', '█▘'] : ['▐█', '█▌']
44  const feet = step === 0 ? '▀▀ ▀▀    ▀▀ ▀▀' : '▀▀  ▀▀  ▀▀  ▀▀'
45  return [
46    [['   ', null], ['▄▄▄▄▄▄▄▄▄▄▄▄▄▄', HEAD], ['   ', null]],
47    [['  ', null], ['████████████████', HEAD], ['  ', null]],
48    [[' ', null], ['─', SIDE], ['█', FRAME], ...lens(glint, isBlink), ['████', FRAME], ...lens(glint, isBlink), ['█', FRAME], ['─', SIDE], [' ', null]],
49    [['  ', null], ['█', FRAME], ['█████', isBlink ? HEAD : LENS], ['████', HEAD], ['█████', isBlink ? HEAD : LENS], ['█', FRAME], ['  ', null]],
50    [['  ', null], ['█', HEAD], ['██', BLUSH], ['████', HEAD], ['██', MOUTH], ['████', HEAD], ['██', BLUSH], ['█', HEAD], ['  ', null]],
51    [[arms[0], SIDE], ['████████████████', BODY], [arms[1], SIDE]],
52    [['  ', null], ['████████████████', BELLY], ['  ', null]],
53    [['   ', null], [feet, SIDE], ['   ', null]],
54  ]
55}
56
57// While busy the caption's dots cycle ("Kodu okuyorum.", "..", "..."); otherwise it is shown as given.
58export function captionAt(t: number, mood: Mood, caption: string): string {
59  if (mood !== 'busy') return caption
60  const base = caption.replace(/[.…]+$/, '')
61  return base + '.'.repeat(1 + (Math.floor(t / 400) % 3))
62}
63
64type State = { t: number }
65
66const Mascot: ClientModule<MascotProps, State> = (props, surface) => {
67  const { Box, Text } = surface.elements
68  if (surface.state === undefined) {
69    // one clock for the instance's life: started on the first call, never again
70    let t = 0
71    surface.every(TICK_MS, () => {
72      t += TICK_MS
73      surface.setState({ t })
74    })
75    surface.setState({ t: 0 })
76  }
77  const t = surface.state?.t ?? 0
78  return (
79    <Box flexDirection="column" alignItems="center">
80      {frameRows(t, props.mood).map((row, i) => (
81        <Text key={`r${i}`} wrap="truncate">
82          {row.map(([text, color], j) => (color === null ? text : <Text key={`r${i}s${j}`} color={color}>{text}</Text>))}
83        </Text>
84      ))}
85      <Text color={props.captionColor} dimColor={props.captionDim} wrap="truncate">{captionAt(t, props.mood, props.caption)}</Text>
86    </Box>
87  )
88}
89
90export default Mascot
91
types/index.d.ts 100 lines
1// What the verinoda-live pane draws from, held by the host for the session (the check setting is also kept in the
2// mod's store across sessions).
3
4// The index as the pane shows it; every kind has a glyph and words, colour only reinforces them.
5export type IndexKind =
6  | 'checking' // the session-start check is running
7  | 'fresh' // nothing waiting, no build running
8  | 'pending' // edits waiting for the end of the turn (or for a running graph build: `waiting`)
9  | 'updating' // `verinoda update --fast` is running
10  | 'graph' // the text is in; the graph is rebuilt in the background (2-4 min on this repository)
11  | 'behind' // the graph is behind with no build coming (files changed outside Claude's edit tools)
12  | 'slow' // the watcher gave up after 10 minutes
13  | 'failed' // the last update failed; its files are kept
14  | 'unknown' // the graph state could not be read
15  | 'noindex' // no .verinoda in the project
16  | 'nocli' // no verinoda on PATH outside the project (and no `cli` setting naming one): nothing runs (D186)
17  | 'untrusted' // the .verinoda found is in an ancestor the person did not open or trust: nothing runs (D186)
18
19export type IndexState = {
20  kind: IndexKind
21  n: number // files the state is about (pending, updating, graph, behind, failed)
22  waiting: boolean // pending while a graph build runs: they go in when it ends
23  since: number | null // ms: when the graph build started (graph)
24  at: number | null // ms: when the index was last seen fresh in this session
25  error: string // failed: the first line of the CLI's error; untrusted: the folder with the index; nocli: the name looked for
26}
27
28export type Notice = { text: string; tone: 'ok' | 'warn' | 'err' }
29
30// The last check of an edit (`verinoda check`): what the model was told, for the pane.
31export type CheckInfo = {
32  file: string // the edited file, relative to the project
33  n: number // names reported absent or mismatched on the edited lines
34  ok: boolean // false: the check could not run (the edit went through all the same)
35  at: number // ms
36}
37
38// The improvement checklist pane (D175): one list the model proposed and the person marks, then what came of it.
39export type ImproveGroup = 'problem' | 'improvement' | 'taste' | 'own'
40export type ImproveDecision = 'none' | 'apply' | 'keep' | 'check'
41export type ImproveStatus = 'waiting' | 'applied' | 'partial' | 'failed' | 'not_confirmed' | 'unreported'
42
43export type ImproveItem = {
44  id: string // the model's id, or u1, u2, ... for the person's own
45  group: ImproveGroup
46  title: string // an own item: the person's text
47  observation: string
48  why: string
49  change: string
50  cost: string // '' when none was given
51  evidence: string[]
52  seen: boolean // taste: judged from a rendered view
53  verified: boolean // a check confirmed it
54  checked: string // the note of the check that confirmed it, else ''
55  decision: ImproveDecision // an own item: always 'apply'
56  sentAs: 'apply' | 'check' | null // what it was last sent as
57  outcome: { status: ImproveStatus; note: string; evidence: string[] } | null
58}
59
60export type ImproveState = {
61  phase: 'idle' | 'reviewing' | 'choosing' | 'sent'
62  subject: string
63  items: ImproveItem[] // the model's in rank order, then the person's own
64  open: string | null // the item whose details are shown
65  unfolded: ImproveGroup[] // groups whose folded items were opened
66  extra: string[] // changes the model reported that were not on the list
67  draft: string // what the own-item field holds
68  ownSeq: number // the last number given to an own item; never reused in a session
69  expect: '' | 'review' | 'selection' | 'report' // the prompt that was submitted and whose turn has not started
70  queue: '' | 'review' // the review prompt waits for the command's own turn to end: the host refuses a submit from a command's hook
71  turn: string | null // the id of the mod's own turn in flight
72  note: '' | 'no-list' | 'not-sent'
73}
74
75declare module 'claude-code' {
76  // The tools the mod registers (the improvement list's), so a `tool.call` hook can name them and read their arguments.
77  interface McpToolInputs {
78    'mcp__verinoda-live__improve_propose': {
79      subject: string
80      items: { id: string; group: 'problem' | 'improvement' | 'taste'; title: string; observation: string; why: string;
81        change: string; cost?: string; evidence?: string[]; seen?: boolean }[]
82    }
83    'mcp__verinoda-live__improve_report': {
84      outcomes: { id: string; status: 'applied' | 'partial' | 'failed' | 'confirmed' | 'not_confirmed'; note: string; change?: string; evidence?: string[] }[]
85      extra_changes?: string[]
86    }
87  }
88
89  interface PluginState {
90    'verinoda-live': {
91      status: string
92      idx: IndexState
93      notice: Notice | null
94      check: boolean // check every edit of a Python, Java or Kotlin file (off unless the setting or /verinoda-check turns it on)
95      lastCheck: CheckInfo | null
96      improve: ImproveState // the improvement checklist pane's whole state
97    }
98  }
99}
100