SLOPSHOPPER

katharsis

An output style that classifies each message by exchange type and shapes the reply to fit it: the answer first, a ceiling per type, reference codes that…

panebandrowscommandtoastprompt
★ 5v0.10.1MITupdated 2026-10-26OpenScribbler/Katharsis
A shopper browsing a rack in a slop shop
README

Katharsis

A Claude Code output style that classifies each message you send and shapes the reply to fit it.

License: MIT OpenSSF Scorecard

A status check, an approval, a bug report, and a request for a diagnosis each want a different reply. Claude Code answers all four with the same shape: a paragraph of narration, the answer somewhere in the middle, and an offer at the end. Katharsis makes the model classify your message into one of 11 exchange types before it writes, read a guidance file for that type, and shape the reply to it: what opens the reply, what stays out, and how long it may run.

A two-turn exchange about a rounding rule, answered by Claude Opus 5 under Claude Code's default style, left, and under Katharsis, right

Same two messages, same model, same sandbox repo, recorded in Claude Code 2.1.283 and sped up. The pricing tests expect half-up rounding that finance never confirmed, and the user asks: "should we change the code or the tests?" The default reply runs 423 words, opens with "Neither, yet", and ends by offering two more tasks. The Katharsis reply runs 438 words and opens with its recommendation: "Change the code to half-up, and treat it as provisional until finance answers." The user then says "go with what you recommend". The default spends 449 words on the work and opens with "Done, but I need to correct something I told you." The Katharsis reply runs 87 words and opens with "All 10 tests pass."

To see the same exchange on other models: Claude Opus 5.5 · Claude Sonnet 5 · Claude Fable 5.1 · Claude Fable 5. Every default reply ends its first turn with an offer of more work, and one Katharsis reply does, on Sonnet 5. Across both turns, Katharsis is shorter on Opus 5.5, Fable 5.1, and Fable 5, where it runs 224 words against 540, and longer on Sonnet 5, 498 words against 349. Every reply is stored verbatim in demo/captures/, and demo/ has the sandbox and the steps to reproduce them.

What changes in your replies

  • The answer opens the reply. Every type's guidance puts the finding, the result, or the state on the first line, and the reasoning after it.
  • The reply is sized to the ask. A four-word status check gets a sentence and the one next step. A request for a diagnosis gets room to argue. Each type carries its own ceiling, and a reply that runs long because the subject felt rich is the failure the ceilings exist to stop.
  • Every item you might refer back to carries a code. Findings, risks, actions taken, and next actions each get a code such as F1 or NA2, numbered continuously through the session, so "do NA2" and "more on F3" are complete instructions. Coded lines sit under the topic they belong to, and each fact appears once.
  • The model acts instead of asking. It makes every call that is cheap to undo and reports the result. A reply ends with a question only when a wrong answer would be expensive or reach past your machine and the model cannot infer your answer, with the options inside the question and a recommendation.
  • At the sketch richness level, a shape gets a sketch only when a list or a table cannot show it. When the point of a reply is nesting, branching logic, or what a change moves in an existing structure, the reply can show it as an inline text sketch of at most 12 lines: a call tree that branches, a directory tree with depth, pseudocode with conditions or loops, or a diff sketch. A linear sequence of steps is a numbered list, and values compared across items, such as what each file does, are a table. A yes, a number, or a go-ahead stays prose, and the answer line is always prose. Sketches are opt-in: at the default level, text, none of this applies.
  • The codes survive the session. A Stop hook records every coded item to a ledger on disk, and kref reads them back, so F3 still resolves after a context compaction or in the next session.

Install

/plugin marketplace add OpenScribbler/Katharsis
/plugin install katharsis@openscribbler

Then, in a Claude Code session:

/katharsis:setup

Setup does the one thing a plugin cannot do for itself. The style has the model run one script per turn, and at the rich richness level a second one to render a diagram or reserve and open a video; a question page you ask for runs the second script at any level. In default permission mode each Bash call prompts on first use in every session, so setup adds one entry per script to permissions.allow in ~/.claude/settings.json:

Bash(~/.claude/katharsis/scripts/katharsis-exchange-style.sh:*)
Bash(~/.claude/katharsis/scripts/katharsis-artifact.sh:*)

A video tool the model runs at rich is not covered by them: it runs as its own Bash call, under your permission prompt. The setup script writes nothing else outside ~/.claude/katharsis-data/. It also checks that Claude Code is 2.1.287 or later, the first version that loads mods without a flag, and prints the fix when it is older. The same script runs from a terminal as ~/.claude/katharsis/scripts/setup.sh, and --dry-run prints the change without writing it.

Setup's output ends with the diagram renderers (d2, mmdc) and video tools (vhs, ffmpeg, remotion) it finds, unless setup stops early on a settings file it cannot edit or a Claude Code too old. For each one missing, it prints an install command when the installer that command needs, such as brew, curl, go, or npm, is on your PATH, and names the missing installer otherwise. Remotion counts only as the Katharsis Remotion project in ~/.claude/katharsis-data/remotion/, which its install command creates with Remotion's packages and the browser it renders with, marking it ready only once the browser is in place; a global remotion command does not count. When vhs or ffmpeg is found, setup marks Remotion not needed and offers no command, because rich uses those first. Remotion needs a paid company license for an organization above its small-team threshold; see remotion.dev/license. The script installs nothing. /katharsis:setup runs an install command only after you say yes to that command, and hands a command that contains sudo, or one that fails for lack of permission, to you to run in a terminal outside Claude Code. Without a video tool, rich uses Claude Motion when the session offers it and the option is on, otherwise a rendered diagram, otherwise an inline sketch.

Last, pick the style. Open /config, choose Output style, and pick one of the two:

StyleWhat it is
katharsis:KatharsisThe style alone. Claude Code's built-in software-engineering instructions are dropped, which is the default for any custom output style.
katharsis:Katharsis codingThe same style with those built-in instructions kept.

The two share one body, and a test holds them identical below the frontmatter. /config saves the choice to .claude/settings.local.json in the current project. Until you pick one, the per-turn and Stop hooks stay silent and write nothing. The session-start hook runs regardless: it makes the symlink, creates the data directory, and prints one line asking for setup until setup has run.

Setup ends by offering /katharsis:rules-check, which you can also run at any time. It reads every instruction file Claude Code loads for the current project, listed by scripts/instruction-files.sh, and reports the rules that repeat the style, the rules that contradict it, and a count of the rest. Each duplicate and conflict comes with a suggested edit, and the skill changes a file only after you approve that edit. A file that reaches every project, such as ~/.claude/CLAUDE.md, needs its own yes.

Requirements

Claude Code 2.1.287 or later, bash, and python3. Only the routing script and the session-start hook are plain bash. Setup, the Stop hooks, and the Bash hooks need python3, so without it setup fails and the ledger is not written. kref needs Node.js 22.18 or later.

Mods

Katharsis is a mod: a plugin whose hooks module, a TypeScript file, Claude Code calls when events happen. Claude Code loads mods with no flag from 2.1.287 on, and Katharsis depends on it: hooks/register.ts carries the per-turn reminder, reading the active style from the settings the engine runs under and telling an untyped turn from the prompt's origin. On a Claude Code that doesn't load mods, no reminder reaches the model and the Stop hooks stay idle; the Bash hooks that save a file a call replaced unread still run. The module also draws the drawer. From the third turn, and every 15 turns after, it asks the model in a forked call to name the session in a few words, and stores the name in the session record. claude plugin test . runs the module's tests.

How it works

  1. You send a message. The prompt hook reads which output style is active and, when it is Katharsis, prints the classify-then-read instruction into the model's context along with the next free code numbers from the ledger. Claude Code names the active style itself on every turn, and this instruction is what keeps the classification step from fading over a long session. When the model changes to one that takes a different note, and after a compaction, the hook also attaches a short note for Fable, Opus, or Sonnet from styles/models/, correcting the leans Anthropic's prompting guide names for that model. A note named for the version, such as opus-5-5.md, would win over the family's note; none ships yet. After a compaction, the hook also lists each owed item the ledger still has open (next actions, your moves, waits, blocks, and questions, the oldest 12), with its body and a question's options and recommendation, each shortened to 200 characters, so the resumed turn does not depend on the summary's account of what was owed. When your message answers a question, such as Q3 a or Q3 x, the hook records the answer, which closes the question in the drawer. At the standard or autonomous autonomy level, the hook adds one line naming the level. At the sketch or rich richness level, it adds one line naming that level and attaches the sketch rules from styles/richness/sketches.md when the session has not had them, after a compaction, and when the level returns from text. With the Claude Motion option off, it adds one line at every richness level saying no reply uses Motion.
  2. The model classifies the message with the cue table in the style, then runs scripts/katharsis-exchange-style.sh <type>. The script prints the guidance file for that type, so running it is the read, and stamps the type for the Stop hook. It never classifies; that judgment stays with the model. An unknown type exits non-zero and prints the valid set.
  3. The model writes the reply under that file's Shape, Ceiling, and Verification sections.
  4. The Stop hooks run. One checks the stamp and, when a turn skipped the classification step, appends one JSON line to telemetry/gate-misses.jsonl with no message text. The script prints an === END: <type> === line after the guidance, and a stamped turn whose output lacks it, because a | head cut it short, is counted there as truncated. The second parses every coded item out of the reply and writes it to ledger/<project>/<session>.jsonl, and holds the reply once when it gives a code a different claim than the one on file with no E line naming that code. The third reads the finished reply and holds it once when it opens by narrating the intended action and buries the finding. The fourth checks the reply's claims against the session's tool results: tests, a build, plugin validation, a linter, or CI said to pass when the last run failed, ran before a later code edit, or never ran, in the reply or in a ticked checklist line of a PR body or commit, unless that line shows the check failing; a change the reply itself says it verified with nothing run after the last edit; and a count whose only source is grep -I, grep -c, or rg without -uu, which skip files or count lines instead of matches. A command counts as a run only where it is the command, so rg pytest is not a test run. When no command the hook knows ran but some command's output reads like a check's result, the hook says nothing. A failed command with several steps counts against a check only when the check's output shows a failure or the check is the last step. When two different commands for the same check ended differently, only a claim about all of them, such as "the tests pass", is judged. A checklist line in the file --body-file or git commit -F names is read only when that file has not changed since the call returned, and --replay reads no such file. A line count is not flagged when you asked for lines. When the count came from grep -r or rg searching one literal word under a folder and piped to wc -l, the hook first recounts that word in every file under the folder, binary and hidden ones included. If its number differs and the files grep or rg skipped account for the whole difference, the line names those files. If its number matches the reply's, skipped files are not reported. Otherwise, and at a symlink or special file, or past 5,000 files, 32 MiB, or 3 seconds, you get only the line about what the command skips. --replay never recounts. Each one appends a record to detections/<session>.jsonl and shows you one Katharsis check: line. None of these holds the reply.

A Bash call that replaces a file no earlier call in the session named (>, tee, cp, mv, dd of=) is checked around the call by the same script, as a PreToolUse and PostToolUse hook, so this check runs without the hooks module and in sessions where Katharsis is not the active style. Before the call it copies the file, a regular file up to 256 KiB found through any symlinks in its path, to a folder under the system temp directory that only you can open; if that folder or its parent is a symlink, belongs to someone else, or is open to anyone else, the hook does nothing. A file the same command first moves or copies elsewhere is not copied. After the call, when lines of the old content are gone, it saves that copy under clobbered/<session>/, readable only by you, appends a record that counts the lost lines and names the saved copy, shows you one line with the cp command that restores it, and tells the model the same in the call's result. A file the call left larger than 1 MiB is not compared. Once clobbered/ holds 64 MiB, it saves no new copy and says so; it never deletes one. If the first reply after the call says nothing about the loss and the file does not match its saved copy, the fourth Stop hook holds that reply once for one appended line per file naming the loss and that command. No later reply is held for that replacement. A reply written in answer to any Stop hook's hold, this one's included, is skipped, and the check falls to the next reply of the same turn, if one follows. When the reply or the two text blocks before it name a file not yet restored and say it was not there before, the reply is not held, since that line would contradict them; you get one Katharsis check: line with the restore command instead.

No hook ever asks for a reply to be written again. A hold asks only for the lines that were missing. For a drifted code, that is a line saying the code stands as on file, the corrected claim with an E line, or the new item under a fresh code. For a buried opening, it is the finding on its own line. For a replaced file, it is one line naming the loss and the saved copy. The reply you already read stands and only the added lines are new. A rule with no such repair records the reply and lets it through. Every hook exits 0 on every path where it cannot help, so a hook that fails costs you a ledger row, never a turn.

The exchange types

TypeThe message looks likeCeiling
factual-question"is X shipped?", "where does Y live?", "do these two rules conflict?"150 words
status-and-resume"how's it going?", "let's continue", a handoff file, "773 merged"250
approval"1. a", "go ahead", "sounds good", "go ahead, but hold off on the second part"250
thinking-out-loud"let's discuss", "does that make sense?", "can we do X?"350
diagnosis"why does this happen?", "is this bad practice?", "what do you think?"500
redirect"do it this way instead", "stop hedging", "I deleted it on purpose", "I didn't read that"250
broken-report"this reply is messed up", "the hook didn't fire", "I got 7, not 5"250
work-request"update the changelog", "run the tests", "open a PR for both fixes"400
canned-reviewA script-sent review prompt naming a diff and a method300
harness-probe"answer in one line", "reply with only the token, or NONE"the named form
defaultThree or more types, a greeting, a pasted fragment250

Ceilings count everything you read, coded items included, because a coded line costs the same reading time as a sentence. The first exemption is an agenda: when your message lists items, every item on it gets a line. The second, at the sketch or rich richness level, is a reply's sketches, up to 12 lines in all, under the rules in styles/richness/sketches.md. The styles/README.md has the shared rules, and each styles/<type>.md has that type's cues, shape, ambiguities, and worked examples.

Reference codes

Each code has one form:

F1 - **the claim** - the evidence, in the same sentence

F findings, A assumptions, R risks, C caveats, AT actions taken, V verified, NA next actions, B blocked, MV your move, W waiting, X excluded, S state, T-O trade-offs, E errata, Q questions. Numbers never restart within a session. The model may define a new code when none fits, and the ledger records it either way, because detection is by shape rather than by an allowlist.

kref

kref reads the ledger back. Inside Claude Code, bash mode runs it from the plugin's bin/, which Claude Code puts on PATH, and the model's whole reply to that turn is "Logged." Below, the ledger comes from a four-day session on this repo that reached F145 and Q85 across 225 coded items. The visible reply is a short demo turn in that session rather than one of its own replies. A chip recalls caveat C21 from an earlier reply, the band counts every code type, and the drawer searches and filters the whole ledger. Then kref F100 fetches a finding from two days earlier, and kref search symlink --short lists every item across the ledger that mentions symlinks.

A reply late in a long Katharsis session: hovering the C21 chip recalls an old caveat, the band shows 50 questions, the drawer searches and filters the whole ledger, and kref fetches F100 and then searches the ledger for symlink

! kref                  this session's items under headings such as Findings, each in full
! kref F3               one item
! kref F                every F item
! kref search keytab    every item whose title, body, or options mention "keytab"
! kref sessions         the sessions that ran in this folder or below it, newest first
! kref --short NA       titles only
! kref --chrono         every item in the order it was written, rather than by heading
! kref --html           the same result as an HTML page
! kref --json           the same result as one JSON document, for scripts

In full, each item shows its title, its whole body, and for a question every option on its own line and the recommendation after ->:

Q4  ship it today?
    the tag is ready but CI is slow
    a. ship now
    b. wait for CI
    -> b - the release has no deadline

Inside Claude Code, kref reads the session you run it from, together with the sessions it continued from a handoff file. A code that scope lacks comes back from the newest sessions that define it. In your own terminal it reads the newest session that ran in the folder you are in, and in a folder where none ran it lists the sessions below it and asks which to open. kref search looks across every session. The kref page documents the rules and the JSON format. kref needs Node.js 22.18 or later.

Your own terminal does not have the plugin's bin/ on PATH, so link the wrapper once:

ln -s ~/.claude/katharsis/bin/kref ~/.local/bin/

The drawer

On Claude Code 2.1.287 or later (see Mods), with a Katharsis style active, the same items are one click away inside Claude Code: from a code in a reply, or from /kdrawer before the first prompt and after /clear. The band, off by default because it shares the row above the prompt with other plugins, is a row there that names the code types the session has, such as ▸ Katharsis · k: open | use /kdrawer · F:3|C:1|AT:2|Q:1. To draw it, open /config, search for band, and turn on the Band above the prompt row (katharsis.band). While the band holds the focus, after ctrl+x tab or a click, k opens the drawer. Hover a type for its latest 10 titles, each led by the status mark its drawer row carries, then press a title to open that item in the drawer, or press the type or its list-all button to list every item of that type.

The Katharsis band above the prompt: the pointer hovers the NA label, which pops up its 2 titles, then presses it, and the drawer lists every next action

The pointer hovers the AT label, moves up into its popup, and presses the AT2 title, which opens AT2's card in the drawer

/kdrawer [query], a code in a reply, or the band's open button opens the drawer, which groups every item under its type's name (Findings, Caveats, Actions taken), with a search box, a filter menu, a Status menu, a Clear button that resets the search and the filter, and a View menu. View short lists titles only, full adds every body, and current lists what the rows under the latest reply list, in full: the codes it cites under Codes this turn, then every open item under Still open. Current follows each new reply and ignores Status. Settings swaps the list for Katharsis's own /config options, such as the autonomy level and the band, with a button per value and the current one marked. A press sets the same option as its /config row, saved to your user settings in ~/.claude/settings.json, and reloads the plugin; the drawer stays on settings. Each row shows the code, a mark, and the title: a grey ○ for an item still open or of a type that never closes, a green ✓ for one answered, settled, or done, and a red ✗ for one dismissed, dropped, or withdrawn. A yellow ! marks an open line an erratum corrected without restating it, whose title is the version the erratum replaced; its card, open or closed, carries ! Corrected by E1 and the erratum's body. The drawer opens on titles only; press a code to open that item as a card, a frame around its row and body. A resolved item's body opens with how it ended, such as ✓ Done in AT3 or ✗ Dropped by X2. The Status menu picks all, open, or resolved items and carries the key to

Source 7 files
hooks/register.ts 325 lines
1// register.ts: the Katharsis prompt hook. It runs wherever Claude Code loads
2// mods, as it does with no flag from 2.1.287 on, and adds the per-turn reminder: the
3// classify-then-read instruction, the inherited stamp on an untyped turn, the
4// model note, the owed items after a compaction, the autonomy level when it
5// is not guided, the richness level and the sketch rules when it is not text,
6// the Claude Motion off line when that option is off, and the next free code
7// numbers. The Stop hooks stay command hooks in hooks.json.
8//
9// The module never says "<style> output style is active": the engine attaches
10// that sentence itself on every turn of a custom style (an `output_style`
11// attachment, seen on 2.1.278), so a second copy only costs the model a
12// repeated line.
13//
14// It reads three things from the engine rather than from files:
15//
16// - Which output style is active. `$.settings.read()` answers the merge the
17//   engine runs under, `--settings` files and policy included, so the module
18//   agrees with the system prompt by construction.
19// - Whether the user typed this turn. `e.origin.kind` is the engine's own
20//   stamp for a task notification, a bash-mode result, and every delivery a
21//   peer session, a scheduled task, or a plugin makes; text markers catch a
22//   skill load and a compaction resume, which arrive from the composer.
23// - Which model runs the main loop, from `$.session.model()`.
24//
25// A hook that throws mid-turn passes the prompt through untouched, so a
26// broken turn costs one reminder and never blocks the prompt.
27//
28// State stays where the Stop hooks and kref read it: the data directory,
29// ~/.claude/katharsis-data (KATHARSIS_DATA overrides it for tests), holding
30// .active-<sid>, .exchange-state-<sid>, .exchange-last-<sid>, .model-<sid>,
31// .model-id-<sid>, .sketches-<sid> and ledger/chains/<sid>, in the formats the scripts write,
32// and it creates and touches sessions/<sid>.json, the session record
33// (session.ts).
34
35import type { EngineInterface, Register } from 'claude-code';
36import { answeredOf, closersOf, latestRound, openQuestions, readAnswers, recordAnswers } from './answers.ts';
37import { registerDrawer } from './drawer.tsx';
38import { nextFree, readRecord, recordPath, thread, threadItems, threadTexts, type Io } from './ledger.ts';
39import { KATHARSIS_STYLES, releaseOf, touched } from './session.ts';
40
41// Origins where a person typed the text, at a terminal, a bridge client, or
42// the -p command line. Every other origin is a turn nobody typed.
43const TYPED_ORIGINS = new Set(['composer', 'bridge', 'sdk']);
44
45// Untyped turns the origin cannot tell apart from a typed one.
46const TEXT_MARKERS: ReadonlyArray<readonly [string, string]> = [
47  ['<bash-input>', 'bash-input'],
48  ['<task-notification>', 'task-notification'],
49  ['<command-name>', 'skill'],
50  ['Base directory for this skill', 'skill'],
51  ['<local-command-stdout>', 'local-command'],
52  ['This session is being continued from a previous conversation', 'compaction-resume'],
53];
54
55// The owed-work codes a compaction-resume turn lists, and how many at most.
56// The oldest are kept: next actions start first item first, and the summary
57// is likeliest to have dropped what was owed longest.
58const OWED = ['NA', 'MV', 'W', 'B', 'Q'];
59const OWED_MAX = 12;
60
61const CLASSIFY_LINES = [
62  'Classify the user\'s message by exchange type and read the matching guidance file in ~/.claude/katharsis/styles/ before shaping the reply.',
63  'Before sending the reply, re-read what the user actually asked and run that guidance file\'s Verification section against your draft.',
64];
65
66export function turnKind(text: string, originKind: string): string {
67  if (!TYPED_ORIGINS.has(originKind)) return originKind;
68  for (const [marker, kind] of TEXT_MARKERS) {
69    if (text.includes(marker)) return kind;
70  }
71  return 'typed';
72}
73
74// The ledger's files through the engine's filesystem. drawer.tsx has its own
75// copy, since the engine never lets $ cross an import.
76function engineIo($: EngineInterface): Io {
77  return {
78    read: async (path) => ((await $.fs.exists(path)) ? String(await $.fs.read(path)) : null),
79    list: async (dir) => ((await $.fs.exists(dir)) ? $.fs.list(dir) : []),
80  };
81}
82
83// One part of an owed item, on one line and at most 200 characters.
84function clipLine(t: string): string {
85  const one = t.replace(/\s+/g, ' ').replace(/"/g, "'").trim();
86  return one.length > 200 ? `${one.slice(0, 199)}…` : one;
87}
88
89function isoNow(): string {
90  return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
91}
92
93// The session record after this prompt. cwd and branch are read only when
94// the record is new, so the git call runs once per session. The record is
95// read last, right before the write, so a title the turn.complete hook wrote
96// meanwhile survives. A record that exists but won't parse is left alone.
97async function touchRecord($: EngineInterface, io: Io, data: string, sid: string, home: string): Promise<void> {
98  const config = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`;
99  const root = $.plugin.root;
100  const release = releaseOf(
101    root,
102    await io.read(`${root}/.claude-plugin/plugin.json`),
103    await io.read(`${config}/plugins/installed_plugins.json`),
104  );
105  const parent = (await io.read(`${data}/ledger/chains/${sid}`))?.trim() ?? '';
106  let old = await readRecord(io, data, sid);
107  let cwd = '';
108  let branch = '';
109  if (!old) {
110    if ((await io.read(recordPath(data, sid))) !== null) return;
111    cwd = await $.session.cwd();
112    const git = await $.process.run(['git', 'branch', '--show-current'], { timeoutMs: 2000 }).catch(() => null);
113    if (git?.exitCode === 0) branch = git.stdout.trim();
114    old = await readRecord(io, data, sid);
115  }
116  const rec = touched(old, { id: sid, now: isoNow(), cwd, branch, parent, release });
117  await $.fs.write(recordPath(data, sid), `${JSON.stringify(rec, null, 2)}\n`);
118}
119
120export const register: Register = (on, options) => {
121  // The plugin's `autonomy` option (plugin.json userConfig). Options are fixed
122  // for one activation, and a change in /config reloads the module.
123  // The engine hands an unset or unknown value over as the default, guided,
124  // which is the test as written and adds no line.
125  const autonomy = options.autonomy === 'standard' || options.autonomy === 'autonomous' ? options.autonomy : '';
126  // The `richness` option, read the same way: the default, text, adds nothing.
127  const richness = options.richness === 'sketch' || options.richness === 'rich' ? options.richness : '';
128  // The `motion` option, a toggle that is on by default. Only an explicit off
129  // turns Claude Motion off, and its line goes out at every richness level,
130  // since a user can ask for an animation at any of them. The line stands on
131  // its own because at text the sketch rules are not attached.
132  const motionOff = options.motion === false;
133
134  on('prompt.submit', async ($, e, next) => {
135    const home = (await $.env.get('HOME')) ?? '';
136    const data = (await $.env.get('KATHARSIS_DATA')) ?? `${home}/.claude/katharsis-data`;
137    const sid = await $.session.id();
138    const marker = `${data}/.active${sid ? `-${sid}` : ''}`;
139
140    const settings = await $.settings.read();
141    const style = typeof settings.outputStyle === 'string' ? settings.outputStyle : '';
142
143    // A session that switched away from Katharsis drops its marker here, so
144    // the Stop hooks go idle on the same turn.
145    if (!KATHARSIS_STYLES.has(style)) {
146      await $.process.run(['rm', '-f', marker]);
147      return next(e);
148    }
149
150    await $.fs.write(marker, '');
151    const lines: string[] = [];
152
153    // The handoff chain link: a punt opening names a punt file, and that file
154    // names the session that wrote it. Recording new -> parent makes the pair
155    // one numbering space for kref and for the counter line below.
156    const punt = e.text.match(/\/tmp\/punt-[A-Za-z0-9]+\.md/)?.[0];
157    if (punt && sid && (await $.fs.exists(punt))) {
158      const text = String(await $.fs.read(punt));
159      const parent = text.match(/^Ledger parent:[ \t]*([A-Za-z0-9-]*)/m)?.[1];
160      if (parent && parent !== sid) {
161        await $.fs.write(`${data}/ledger/chains/${sid}`, `${parent}\n`);
162      }
163    }
164
165    // The session record, after the chain link so it carries the parent. A
166    // failure here costs the record one update and never the reminder.
167    const io = engineIo($);
168    if (sid) await touchRecord($, io, data, sid, home).catch(() => undefined);
169
170    // A turn nobody typed inherits the last typed message's type. That needs
171    // no judgment, so the module stamps it instead of asking the model to.
172    const kind = turnKind(e.text, e.origin.kind);
173    if (kind === 'typed') {
174      lines.push(...CLASSIFY_LINES);
175    } else {
176      const last = `${data}/.exchange-last${sid ? `-${sid}` : ''}`;
177      const stamp = `${data}/.exchange-state${sid ? `-${sid}` : ''}`;
178      let primary = '';
179      if (await $.fs.exists(last)) {
180        primary = String(await $.fs.read(last)).split('\t')[1]?.trim() ?? '';
181      }
182      if (primary) {
183        await $.fs.write(stamp, `${isoNow()}\t${primary}\tinherited\n`);
184        lines.push(
185          `Untyped turn (${kind}): it inherits \`${primary}\` from the last typed message, and the stamp is already made. Shape the reply to that type; do not run the script.`,
186        );
187      } else {
188        lines.push(
189          `Untyped turn (${kind}) with no earlier type in this session: treat it as \`status-and-resume\` and run the script with that type.`,
190        );
191      }
192    }
193
194    if (autonomy) {
195      lines.push(`Autonomy level: ${autonomy}. The style's "Autonomy level" section moves which calls are the user's.`);
196    }
197    // The sketch rules: styles/richness/sketches.md, at sketch or rich only, sent when
198    // the session's record does not name it, and again after a compaction,
199    // whose summary drops it, as the model note is. At text the record is
200    // cleared, so the rules go out again when the level comes back.
201    // A failed lookup costs the rules, never the lines above them.
202    if (richness) {
203      lines.push(`Richness level: ${richness}. The sketch rules the prompt hook attached from styles/richness/sketches.md apply to this turn.`);
204    }
205    try {
206      const state = `${data}/.sketches${sid ? `-${sid}` : ''}`;
207      const seen = (await $.fs.exists(state)) ? String(await $.fs.read(state)).trim() : '';
208      const rules = `${$.plugin.root}/styles/richness/sketches.md`;
209      if (!richness) {
210        if (seen) await $.process.run(['rm', '-f', state]);
211      } else if ((seen !== 'sketches' || kind === 'compaction-resume') && (await $.fs.exists(rules))) {
212        lines.push(String(await $.fs.read(rules)).trim());
213        await $.fs.write(state, 'sketches\n');
214      }
215    } catch {}
216    if (motionOff) {
217      lines.push('Claude Motion: off. No reply on this turn uses Motion, even one the user asks for; only a reply that declines an animation says the Claude Motion option in /config is off.');
218    }
219
220    // Answers to the latest Questions round, read from the message itself
221    // (answers.ts), so the open-questions line needs no model call. A reading
222    // the parser would have to guess goes to the model to confirm instead.
223    // A failed ledger read skips the lines built from it, never the rest.
224    const items = sid ? await threadItems(io, data, sid).catch(() => null) : [];
225    if (kind === 'typed' && sid && items) {
226      const round = latestRound(items);
227      if (round.length > 0) {
228        const asked = new Map(
229          items.filter((i) => i.prefix === 'Q').map((i) => [i.code.toUpperCase(), i.options.map((o) => o.key.toLowerCase())]),
230        );
231        const { answers, unclear } = readAnswers(e.text, round, asked);
232        await recordAnswers({ read: io.read, write: (p, s) => $.fs.write(p, s) }, data, sid, answers);
233        const dropped = answers.filter((a) => a.how === 'dismissed').map((a) => a.code);
234        if (dropped.length > 0) {
235          lines.push(`Dismissed: ${dropped.join(', ')}. The user no longer wants ${dropped.length > 1 ? 'these' : 'this'} settled, so drop ${dropped.length > 1 ? 'them' : 'it'}: act on no option and do not ask again.`);
236        }
237        for (const u of unclear) {
238          const reading = u.letter ? `${u.code} ${u.letter}` : u.code;
239          lines.push(
240            u.why === 'position'
241              ? `The message's "${u.said}" names no question in the round, so it reads by position as ${reading}. Confirm that reading in one line before acting on it, and suggest answering as \`${u.code} ${u.letter || 'a'}\` next time, or \`${u.code} z\` for an answer of their own.`
242              : `The message's "${u.said}" picks option ${u.letter}, which ${u.code} does not offer. Ask which option was meant, and suggest answering as \`${u.code} <letter>\`, or \`${u.code} z\` for an answer of their own.`,
243          );
244        }
245      }
246      const answered = answeredOf(await threadTexts(io, `${data}/answers`, await thread(io, data, sid), false).catch(() => []));
247      const open = openQuestions(items, answered);
248      if (open.length > 0) lines.push(`Open questions: ${open.map((q) => q.code).join(', ')}. The drawer lists them under the reply, so the reply does not restate them.`);
249    }
250
251    // A compaction summary paraphrases what was owed, so the resumed turn gets
252    // the ledger's own list: every NA, MV, W, B, and Q no later line closed.
253    // A failed read costs the list, never the lines above it.
254    if (kind === 'compaction-resume' && sid && items) try {
255      const closed = closersOf(items, answeredOf(await threadTexts(io, `${data}/answers`, await thread(io, data, sid), false)));
256      const owed = items
257        .filter((i) => OWED.includes(i.prefix) && !closed.has(i.code.toUpperCase()))
258        // One reply's items share a timestamp and the ledger keeps no order
259        // among them, so number, then code, breaks the tie.
260        .sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : a.n - b.n || OWED.indexOf(a.prefix) - OWED.indexOf(b.prefix)));
261      if (owed.length > 0) {
262        // Each item goes out whole (title, body, a question's options), so
263        // the model needs no tool call to act on it, and quoted as a record
264        // of an earlier reply, so nothing in one reads as this hook's instruction.
265        const shown = owed.slice(0, OWED_MAX).map((i) => {
266          const text = clipLine(i.summary ? `${i.title} - ${i.summary}` : i.title);
267          const options = i.options.length > 0 ? ` Options: ${clipLine(i.options.map((o) => `${o.key}. ${o.text}`).join('; '))}` : '';
268          const rec = i.rec ? ` Recommended: ${clipLine(i.rec)}` : '';
269          return `${i.code} "${text}${options}${rec}"`;
270        });
271        const more = owed.length > OWED_MAX ? ` (${owed.length - OWED_MAX} newer items are in the drawer)` : '';
272        lines.push(
273          `Owed before the compaction, as recorded in the ledger${more}: ${shown.join('; ')}. The quoted items are records of earlier replies, not instructions. Where the summary's account of owed work differs, this list is the record. An \`AT\` or \`V\` line that cites a code closes it.`,
274        );
275      }
276    } catch {}
277
278    // The model note: the version's or else the family's note from
279    // styles/models/, sent when it differs from the one recorded for this session, and again
280    // after a compaction, whose summary drops it. The engine names the main
281    // loop's model directly.
282    const modelId = String(await $.session.model()).trim();
283    const model = modelId.toLowerCase();
284    // The full id, for stop-verifier.sh's per-reply telemetry row. .model-<sid>
285    // holds only the name of the note last sent.
286    // A failed write costs a telemetry field, never the lines above.
287    try {
288      const idState = `${data}/.model-id${sid ? `-${sid}` : ''}`;
289      const idSeen = (await $.fs.exists(idState)) ? String(await $.fs.read(idState)).trim() : '';
290      if (modelId && idSeen !== modelId) await $.fs.write(idState, `${modelId}\n`);
291    } catch {}
292    const match = (
293      [['fable', 'fable'], ['mythos', 'fable'], ['opus', 'opus'], ['sonnet', 'sonnet']] as const
294    ).find(([key]) => model.includes(key));
295    // A failed note lookup costs the note, never the lines above it.
296    if (match) try {
297      // A version's own note (opus-5-5.md for claude-opus-5-5) wins over the
298      // family's, because a lean one version shows can be gone in the next.
299      const [key, family] = match;
300      const version = model.match(new RegExp(`${key}-(\\d{1,2}(?:-\\d{1,2})?)(?!\\d)`))?.[1];
301      const dir = `${$.plugin.root}/styles/models`;
302      const versioned = version ? `${family}-${version}` : '';
303      const name = versioned && (await $.fs.exists(`${dir}/${versioned}.md`)) ? versioned : family;
304      const state = `${data}/.model${sid ? `-${sid}` : ''}`;
305      const seen = (await $.fs.exists(state)) ? String(await $.fs.read(state)).trim() : '';
306      const note = `${dir}/${name}.md`;
307      if ((seen !== name || kind === 'compaction-resume') && (await $.fs.exists(note))) {
308        lines.push(String(await $.fs.read(note)).trim());
309        await $.fs.write(state, `${name}\n`);
310      }
311    } catch {}
312
313    // One line of counters from the ledger, so numbering survives compaction
314    // and handoffs.
315    const counters = items ? nextFree(items) : '';
316    if (counters) lines.push(counters);
317
318    return next({ ...e, context: [...(e.context ?? []), lines.join('\n')] });
319  }).catch(async ($, e, next) => next(e));
320
321  // The drawer (drawer.tsx): the pane, /kdrawer, the reply chips, and the
322  // band when its option is on.
323  registerDrawer(on, autonomy, options.band === true);
324};
325
hooks/answers.ts 291 lines
1// answers.ts: which questions are still open, decided without the model.
2//
3// The prompt hook (register.ts) reads each typed message for answers to the
4// latest Questions round and records them to answers/<sid>.jsonl in the data
5// directory, as the drawer's send button does for the answer it posts. The
6// drawer reads that file to draw the Still open row. No
7// model call is made: a replay over 1,226 real answers found the patterns
8// below catch the answers people type. A miss leaves the question listed
9// until it is answered again as `Q3 a` or a later line settles it; a
10// question never drops out of sight unsettled.
11//
12// An answer is a number, an optional separator, and a letter: `1. a`, `1a`,
13// `Q2: b`, `1a, 2b`, `1a 2b`, one per line, with anything after the letter
14// ignored. A token starts a line or follows a comma or semicolon, or follows
15// another token on the same line, so "I merged 2 a while ago" matches
16// nothing. A number with prose after it, "54. I fixed it in Jira", answers
17// that question in prose.
18//
19// The number resolves in this order:
20//   1. Q2 or q2 is always Q2.
21//   2. A bare number naming a question in the latest round is that question.
22//   3. Otherwise a bare number with a letter is a position in the round, and
23//      the model is asked to confirm that reading rather than act on a guess.
24//   4. A bare number past the round's length naming an earlier question is
25//      that question, when the letter is one it offers, `z`, or `x` and no
26//      word follows it: the drawer keeps an unanswered question listed, and
27//      "2 a" answers it there. A numbered prose line, "2. A file was found",
28//      never reaches that far back.
29// A letter the question does not offer is not guessed at either, except `z`,
30// which every question takes as "my own answer": the drawer's Still open
31// row says so, and `x`, which dismisses any question, even one offering an
32// option x. The words dismiss, dismissed, cancel, and canceled stand in for
33// the `x`. A dismissal needs nothing but a separator after it: "Q3 x - stale"
34// dismisses, and "Q3 x is undefined" answers in prose.
35
36export type Round = { code: string; options: string[] }[];
37export type Answer = { code: string; letter: string; how: 'code' | 'number' | 'prose' | 'own' | 'dismissed' };
38export type Unclear = { code: string; letter: string; said: string; why: 'position' | 'option' };
39
40const TOKEN = String.raw`(q?)(\d{1,3})\s*[.):=\-]?\s*(dismiss(?:ed)?|cancel(?:l?ed)?|[a-z])(?![a-z0-9]|-[a-z0-9])`;
41const LEAD = new RegExp(String.raw`^\s*` + TOKEN, 'iy');
42const CHAIN = new RegExp(String.raw`(?:\s*[,;]\s*|\s+)` + TOKEN, 'iy');
43const SEP = new RegExp(String.raw`[,;]\s*` + TOKEN, 'ig');
44const PROSE = /^\s*(q?)(\d{1,3})\s*[.):]\s+[a-z]{2,}/i;
45
46type Token = { explicit: boolean; n: number; letter: string; wordAfter: boolean; said: string };
47
48function tokensOf(msg: string): Token[] {
49  const out: Token[] = [];
50  const take = (m: RegExpExecArray, line: string) => {
51    const end = m.index + m[0].length;
52    const wordAfter = /^\s+[a-z]/i.test(line.slice(end));
53    out.push({
54      explicit: m[1] !== '',
55      n: Number(m[2]),
56      // "1. Cancel the build" is a sentence, not a dismissal.
57      letter: m[3]!.length > 1 ? (wordAfter ? '' : 'x') : m[3]!.toLowerCase(),
58      wordAfter,
59      said: m[0].replace(/^[\s,;]+/, ''),
60    });
61    return end;
62  };
63  for (const line of msg.split('\n')) {
64    let pos = 0;
65    LEAD.lastIndex = 0;
66    let m = LEAD.exec(line);
67    const led = m !== null;
68    while (m) {
69      pos = take(m, line);
70      CHAIN.lastIndex = pos;
71      m = CHAIN.exec(line);
72    }
73    SEP.lastIndex = pos;
74    for (let s = SEP.exec(line); s; s = SEP.exec(line)) take(s, line);
75    if (!led) {
76      const p = line.match(PROSE);
77      if (p) out.push({ explicit: p[1] !== '', n: Number(p[2]), letter: '', wordAfter: true, said: p[0].trim() });
78    }
79  }
80  return out;
81}
82
83// The answers a message gives to the latest round, and the readings it leaves
84// for the model to confirm. `asked` holds every question on record, so an
85// explicit code outside the round still resolves.
86export function readAnswers(msg: string, round: Round, asked: Map<string, string[]>): { answers: Answer[]; unclear: Unclear[] } {
87  const answers: Answer[] = [];
88  const unclear: Unclear[] = [];
89  const inRound = new Map(round.map((q) => [q.code, q.options]));
90  const seen = new Set<string>();
91  for (const t of tokensOf(msg)) {
92    let code = `Q${t.n}`;
93    let opts: string[] | undefined;
94    let how: Answer['how'] = t.explicit ? 'code' : 'number';
95    let far = false;
96    if (t.explicit) opts = asked.get(code);
97    else if (inRound.has(code)) opts = inRound.get(code);
98    else if (t.letter !== '' && t.n >= 1 && t.n <= round.length) {
99      // A numbered prose line is never read by position: "1. Fix the tests"
100      // is more often a list than an answer.
101      code = round[t.n - 1]!.code;
102      if (!seen.has(code)) unclear.push({ code, letter: t.letter, said: t.said, why: 'position' });
103      seen.add(code);
104      continue;
105    } else if (t.letter !== '') {
106      opts = asked.get(code);
107      far = true;
108    }
109    if (opts === undefined || seen.has(code)) continue;
110    if (far && (t.wordAfter || (!opts.includes(t.letter) && t.letter !== 'z' && t.letter !== 'x'))) continue;
111    seen.add(code);
112    if (t.letter === 'z' && !opts.includes('z')) {
113      answers.push({ code, letter: 'z', how: 'own' });
114    } else if (t.letter === 'x' && !t.wordAfter) {
115      answers.push({ code, letter: 'x', how: 'dismissed' });
116    } else if (t.letter === '' || (!opts.includes(t.letter) && t.wordAfter)) {
117      // "54. I fixed it in Jira": the letter is the first word of a prose answer.
118      answers.push({ code, letter: '', how: 'prose' });
119    } else if (opts.length > 0 && !opts.includes(t.letter)) {
120      unclear.push({ code, letter: t.letter, said: t.said, why: 'option' });
121    } else {
122      answers.push({ code, letter: t.letter, how });
123    }
124  }
125  return { answers, unclear };
126}
127
128// Appends a row per answer to answers/<sid>.jsonl. The prompt hook records
129// what a typed message answers, and the drawer what its send button posted,
130// because Claude Code runs none of a plugin's own prompt.submit hooks on a
131// prompt that plugin submits. $.fs has no append, so each write waits for the
132// one before it, and two answers recorded at once both land.
133let recording: Promise<unknown> = Promise.resolve();
134export function recordAnswers(
135  fs: { read(p: string): Promise<string | null>; write(p: string, s: string): Promise<unknown> },
136  data: string,
137  sid: string,
138  answers: Answer[],
139): Promise<void> {
140  if (answers.length === 0) return Promise.resolve();
141  const run = recording.then(async () => {
142    const file = `${data}/answers/${sid}.jsonl`;
143    const before = (await fs.read(file)) ?? '';
144    const ts = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
145    const rows = answers.map((a) => JSON.stringify({ ts, code: a.code, letter: a.letter, how: a.how }));
146    await fs.write(file, `${before}${rows.join('\n')}\n`);
147  });
148  recording = run.catch(() => {});
149  return run;
150}
151
152// Every question code an answers file's rows name, with the letter the
153// latest row for it gave.
154export function answeredOf(texts: string[]): Map<string, string> {
155  const out = new Map<string, string>();
156  for (const text of texts) {
157    for (const line of text.split('\n')) {
158      try {
159        const r = JSON.parse(line) as Record<string, unknown>;
160        if (typeof r.code === 'string') out.set(r.code.toUpperCase(), String(r.letter ?? ''));
161      } catch {
162        continue; // a blank or partial line
163      }
164    }
165  }
166  return out;
167}
168
169type Q = { code: string; prefix: string; n: number; ts: string; title: string; summary: string };
170
171// What closed a code: the answer letter, the line that cited it, or both.
172export type Closer = { letter: string; by: string; prefix: string; title: string };
173
174const CITE = /(?<![A-Za-z0-9-])[A-Z][A-Z-]{0,3}\d+(?!\d)/g;
175// A code span: a run of backticks, then text up to a run of the same length,
176// across a line break too, since a title and its body are one paragraph.
177const SPAN = /(?<!`)(`+)(?!`)([\s\S]*?[^`])\1(?!`)/g;
178
179// Every code a later coded line cites, with the citing items, oldest first.
180// A mention in the reply's prose is not on record, so only a coded line's
181// title and body count, and a code inside a code span is an example, such as
182// `kref Q4` or `Q3 a`, rather than a citation.
183export function citersOf<T extends Q>(items: T[]): Map<string, T[]> {
184  const byTs = [...items].sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : 0));
185  const ts = new Map(items.map((i) => [i.code.toUpperCase(), i.ts]));
186  const out = new Map<string, T[]>();
187  for (const j of byTs) {
188    for (const c of new Set(`${j.title}\n${j.summary}`.replace(SPAN, ' ').match(CITE) ?? [])) {
189      const at = ts.get(c);
190      if (at === undefined || c === j.code.toUpperCase() || j.ts <= at) continue;
191      out.set(c, [...(out.get(c) ?? []), j]);
192    }
193  }
194  return out;
195}
196
197// Which lines close each type: owed work, a block, a risk, and a question
198// close on the action or check that did it or the exclusion that dropped it,
199// and a question on an answer too. A caveat closes on the action or check
200// that lifted its limit. Only these lines count, so an erratum or a finding
201// that cites a code leaves it open. A finding closes only when an erratum
202// withdraws it, and the other types record something and never close.
203const DONE = (p: string) => p === 'AT' || p === 'V' || p === 'X';
204const CLOSES: Record<string, (p: string) => boolean> = {
205  Q: DONE,
206  NA: DONE,
207  MV: DONE,
208  W: DONE,
209  B: DONE,
210  R: DONE,
211  C: (p) => p === 'AT' || p === 'V',
212};
213
214// The types that can close at all.
215export const CLOSING = new Set(Object.keys(CLOSES));
216
217// A withdrawn finding is restated as `F3 - **Withdrawn: <why>** - (E1)`, and
218// the ledger keeps that restatement as the code's current line.
219const WITHDRAWN = /^Withdrawn:/i;
220const ERRATUM = /\((E\d+)\)\s*$/;
221
222// An exclusion line dismisses a question only while it is unanswered, and
223// only when it names the question rather than one option, as `Q16c` does.
224function keepsQuestion(key: string, x: Q, answered: ReadonlyMap<string, string>): boolean {
225  return answered.has(key) || new RegExp(`(?<![A-Za-z0-9-])${key}[a-z](?![A-Za-z])`).test(`${x.title}\n${x.summary}`);
226}
227
228// Every closed code and what closed it.
229export function closersOf(items: Q[], answered: ReadonlyMap<string, string>): Map<string, Closer> {
230  const citers = citersOf(items);
231  const out = new Map<string, Closer>();
232  for (const i of items) {
233    const key = i.code.toUpperCase();
234    if (i.prefix === 'F') {
235      if (!WITHDRAWN.test(i.title)) continue;
236      const e = `${i.title}\n${i.summary}`.trim().match(ERRATUM)?.[1] ?? '';
237      out.set(key, { letter: '', by: e, prefix: e ? 'E' : '', title: '' });
238      continue;
239    }
240    const closes = CLOSES[i.prefix];
241    if (!closes) continue;
242    const by = (citers.get(key) ?? []).find((j) => closes(j.prefix) && !(i.prefix === 'Q' && j.prefix === 'X' && keepsQuestion(key, j, answered)));
243    const letter = i.prefix === 'Q' ? (answered.get(key) ?? '') : '';
244    if (by || answered.has(key)) out.set(key, { letter, by: by?.code ?? '', prefix: by?.prefix ?? '', title: by?.title ?? '' });
245  }
246  return out;
247}
248
249// An erratum names its target in its title, `F3 as first written: <old>`, and
250// the corrected line should go out again under F3 in the same reply. When it
251// does not, the ledger still holds the wrong line as F3's current one. Every
252// code whose latest line is not newer than an erratum correcting it and does
253// not end citing it, with that erratum, the newest when several do. Stamps
254// are to the second, so a line from an earlier reply can share the
255// erratum's; only the citation tells a same-reply restatement apart.
256const FIRST_WRITTEN = /^([A-Z][A-Z-]{0,3}\d+) as first written/;
257export function correctionsOf<T extends Q>(items: T[]): Map<string, T> {
258  const latest = new Map(items.map((i) => [i.code.toUpperCase(), i]));
259  const out = new Map<string, T>();
260  for (const e of items) {
261    if (e.prefix !== 'E') continue;
262    const key = e.title.match(FIRST_WRITTEN)?.[1];
263    const line = key ? latest.get(key) : undefined;
264    if (!key || !line || line.ts > e.ts) continue;
265    if (new RegExp(`\\(${e.code}\\)\\W*$`, 'i').test(`${line.title}\n${line.summary}`.trim())) continue;
266    const old = out.get(key);
267    if (!old || e.ts > old.ts) out.set(key, e);
268  }
269  return out;
270}
271
272// The open questions, oldest first: every question on record that no answer
273// row names and no later action-taken, verification, or exclusion line cites.
274export function openQuestions<T extends Q>(items: T[], answered: ReadonlyMap<string, string>): T[] {
275  const closed = closersOf(items, answered);
276  return items
277    .filter((i) => i.prefix === 'Q' && !closed.has(i.code.toUpperCase()))
278    .sort((a, b) => a.n - b.n);
279}
280
281// The latest Questions round: the Q rows the newest reply with a round wrote,
282// which share that reply's timestamp.
283export function latestRound(items: (Q & { options: { key: string }[] })[]): Round {
284  const qs = items.filter((i) => i.prefix === 'Q');
285  const last = qs.reduce((m, i) => (i.ts > m ? i.ts : m), '');
286  return qs
287    .filter((i) => i.ts === last)
288    .sort((a, b) => a.n - b.n)
289    .map((i) => ({ code: i.code, options: i.options.map((o) => o.key.toLowerCase()) }));
290}
291
hooks/drawer.tsx 1611 lines
1// drawer.tsx: the Katharsis drawer. An optional one-row band above the prompt
2// names the code types this session has, each with a hover list of its titles;
3// its button, or /kdrawer [query], opens a pane that lists every item grouped by
4// type, searchable by text and filterable by type and by status. In a reply,
5// each code on record becomes a link that opens the pane at that code, and a
6// row of chips under the reply carries a hover card per code.
7//
8// It reads the ledger through ledger.ts (one handoff chain is one numbering
9// space, a later record for a code supersedes an earlier one), and only while
10// the output style is Katharsis. It reads the style from settings rather than
11// the .active-<sid> marker register.ts writes at each prompt, because the
12// marker is missing until the first prompt of a new, forked, or cleared
13// session. The render hooks draw from a cache that session start, the end of
14// each turn, and every pane open refresh. A reply or the band drawn while the
15// cache is empty, as after a reload or /clear, loads it first. The refresh at
16// session start registers /kdrawer before the first prompt.
17//
18// Every hook falls through to next(e) when it throws: the drawer may vanish,
19// but it never stands between the person and the session.
20
21import type { ConfigRow, ConfigValue, EngineInterface, On } from 'claude-code';
22import { answeredOf, citersOf, CLOSING, closersOf, correctionsOf, latestRound, openQuestions, readAnswers, recordAnswers, type Closer } from './answers.ts';
23import { codeOrder, readRecord, recordPath, thread, threadItems, threadTexts, type Io, type Item } from './ledger.ts';
24import { cleanTitle, KATHARSIS_STYLES, TITLE_PROMPT, wantsTitle, withTranscript } from './session.ts';
25import { agreement, suggestsStandard, type Agreement } from './suggest.ts';
26import type { KatharsisShow, KatharsisView } from '../types';
27
28const PANE = 'kdrawer';
29const TITLE = 'Katharsis';
30const TEAL = '#14B8A6';
31const CODE_RE = /(?<![A-Za-z0-9-])[A-Z][A-Z-]{0,3}\d+(?![A-Za-z0-9])/g;
32const CODE_ONLY = /^[A-Za-z][A-Za-z-]{0,3}\d+$/;
33// Inline links point here. The host is reserved and never resolves, and the
34// path spells the code out for a terminal that shows a link's target on hover.
35const LINK_BASE = 'https://katharsis.invalid/';
36const MARKDOWN_MAX = 10000;
37// Titles a band reveal lists at most, so it never outgrows a short band.
38const REVEAL_MAX = 10;
39// The Still open row: the types someone has to act on, the person's first,
40// and the newest codes it shows of each. Next actions and waits are the
41// model's to finish, so the pane's filter holds them instead.
42const STILL_OPEN = ['Q', 'MV', 'B', 'R'];
43const STILL_OPEN_SHOWN = 3;
44// Sessions that show the answer hint on the row itself; later ones show it
45// only in a question's hover card.
46const HINT_SESSIONS = 3;
47const SUGGEST_DISMISSED = 'autonomy-suggestion-dismissed';
48
49// Each code's name, singular then plural. D is retired but still appears in
50// older ledgers.
51const TYPES: [string, string, string][] = [
52  ['F', 'Finding', 'Findings'],
53  ['A', 'Assumption', 'Assumptions'],
54  ['R', 'Risk', 'Risks'],
55  ['C', 'Caveat', 'Caveats'],
56  ['AT', 'Action taken', 'Actions taken'],
57  ['V', 'Verification', 'Verified'],
58  ['NA', 'Next action', 'Next actions'],
59  ['B', 'Blocked', 'Blocked'],
60  ['MV', 'Your move', 'Your moves'],
61  ['W', 'Waiting', 'Waiting'],
62  ['X', 'Excluded', 'Excluded'],
63  ['S', 'State', 'State'],
64  ['T-O', 'Trade-off', 'Trade-offs'],
65  ['E', 'Erratum', 'Errata'],
66  ['Q', 'Question', 'Questions'],
67  ['D', 'Decision', 'Decisions'],
68];
69const SINGULAR = new Map(TYPES.map(([p, s]) => [p, s]));
70const PLURAL = new Map(TYPES.map(([p, , pl]) => [p, pl]));
71
72// "Finding 9" for F9; an invented code keeps its own spelling.
73export function nameOf(i: Item): string {
74  const s = SINGULAR.get(i.prefix);
75  return s ? `${s} ${i.n}` : i.code;
76}
77
78// A Button label is one line, so a long title is cut to fit.
79function clip(s: string, width: number): string {
80  return s.length <= width ? s : `${s.slice(0, width - 1)}…`;
81}
82
83// A menu row: the name on the left and the count flush right in `width` cells.
84// A name too long for the row is cut, so the row never wraps onto a second line.
85function menuRow(name: string, count: string, width: number): string {
86  const cut = clip(name, Math.max(2, width - count.length - 1));
87  return `${cut}${' '.repeat(Math.max(1, width - cut.length - count.length))}${count}`;
88}
89
90function groupName(p: string): string {
91  const pl = PLURAL.get(p);
92  return pl ? `${pl} (${p})` : p;
93}
94
95// Types sorted by the label the reader scans: the band shows codes, so it
96// sorts by code; the filter menu and the pane's groups show names, so they
97// sort by name.
98const alpha = (a: string, b: string) => a.localeCompare(b, 'en');
99function byCode(ps: string[]): string[] {
100  return [...ps].sort(alpha);
101}
102function byName(ps: string[]): string[] {
103  return [...ps].sort((a, b) => alpha(groupName(a), groupName(b)));
104}
105// The ledger's files through the engine's filesystem. register.ts has its own
106// copy, since the engine never lets $ cross an import.
107function engineIo($: EngineInterface): Io {
108  return {
109    read: async (path) => ((await $.fs.exists(path)) ? String(await $.fs.read(path)) : null),
110    list: async (dir) => ((await $.fs.exists(dir)) ? $.fs.list(dir) : []),
111  };
112}
113
114type Show = KatharsisShow;
115const SHOWS: Show[] = ['all', 'open', 'resolved'];
116
117// View short lists titles, full adds every body, current lists the latest
118// reply's two rows, Codes this turn and Still open, in full, and settings
119// swaps the list for Katharsis's own rows from /config.
120type View = KatharsisView;
121const VIEWS: { value: View; text: string }[] = [
122  { value: 'short', text: 'titles only' },
123  { value: 'full', text: 'every body' },
124  { value: 'current', text: 'this turn and still open' },
125  { value: 'settings', text: 'Katharsis options' },
126];
127
128type State = {
129  active: boolean;
130  loaded: boolean;
131  commandRegistered: boolean;
132  items: Item[];
133  query: string;
134  prefix: string;
135  // Which items the pane shows by status. It outlives a pane close, unlike
136  // the rest of the pane's state.
137  show: Show;
138  view: View;
139  selected: string;
140  // Each open question's picked letter and note in its card, until send,
141  // and the codes whose send is still out.
142  picks: Map<string, string>;
143  notes: Map<string, string>;
144  sending: Set<string>;
145  filterOpen: boolean;
146  statusOpen: boolean;
147  viewOpen: boolean;
148  paneOpen: boolean;
149  answered: Map<string, string>;
150  closed: Map<string, Closer>;
151  citedBy: Map<string, Item[]>;
152  // Codes an erratum corrected without restating them, with that erratum.
153  corrected: Map<string, Item>;
154  // Whether this session shows the answer hint on the Still open row.
155  hint: boolean;
156  // The last finished reply's text, which tells the latest reply block apart.
157  lastAnswer: string;
158  // A code list the pane shows alone: the still open codes.
159  only: string[];
160  // The autonomy level register() got, '' for guided.
161  level: string;
162  // Whether the band option is on, which register() got too.
163  band: boolean;
164  // Katharsis's /config rows, listed when the settings view opens.
165  options: ConfigRow[];
166  // The answers behind a suggestion to move to standard, checked once a
167  // session, and null when there is none to make. scan marks this session's
168  // check, so one still running when a reset starts another is ignored.
169  suggestion: Agreement | null;
170  scan: symbol | null;
171};
172
173export async function loadLedger($: EngineInterface): Promise<{ active: boolean; items: Item[] }> {
174  const home = (await $.env.get('HOME')) ?? '';
175  const data = (await $.env.get('KATHARSIS_DATA')) ?? `${home}/.claude/katharsis-data`;
176  const sid = await $.session.id();
177  const style = (await $.settings.read()).outputStyle;
178  if (!sid || typeof style !== 'string' || !KATHARSIS_STYLES.has(style)) return { active: false, items: [] };
179  return { active: true, items: await threadItems(engineIo($), data, sid) };
180}
181
182// Every question code an answer row names, with its letter, across the handoff chain.
183export async function loadAnswered($: EngineInterface): Promise<Map<string, string>> {
184  const home = (await $.env.get('HOME')) ?? '';
185  const data = (await $.env.get('KATHARSIS_DATA')) ?? `${home}/.claude/katharsis-data`;
186  const sid = await $.session.id();
187  if (!sid) return new Map();
188  const io = engineIo($);
189  return answeredOf(await threadTexts(io, `${data}/answers`, await thread(io, data, sid), false));
190}
191
192// The answer hint shows on the row in the first 3 sessions that drew it. The
193// file holds their ids, one per line, and deleting it starts the count over.
194async function hintHere($: EngineInterface, drawn: boolean, g: number): Promise<boolean> {
195  const home = (await $.env.get('HOME')) ?? '';
196  const data = (await $.env.get('KATHARSIS_DATA')) ?? `${home}/.claude/katharsis-data`;
197  const sid = await $.session.id();
198  if (!sid) return false;
199  const f = `${data}/hint-sessions`;
200  const ids = (await $.fs.exists(f)) ? String(await $.fs.read(f)).split('\n').filter(Boolean) : [];
201  if (ids.includes(sid)) return true;
202  if (!drawn || ids.length >= HINT_SESSIONS) return false;
203  // After a /clear, sid is the new session's and drawn was judged on the old
204  // one's questions, so an overtaken refresh spends no hint.
205  if (g !== generation) return false;
206  await $.fs.write(f, `${[...ids, sid].join('\n')}\n`);
207  return true;
208}
209
210// The suggestion to move from guided to standard, made only at guided and
211// only until the person dismisses it. The dismissal is a file in the data
212// directory, and deleting it brings the suggestion back. Another open session
213// can write it at any time, so it is checked again once the scan is done.
214async function suggestionHere($: EngineInterface): Promise<Agreement | null> {
215  if (S.level || (await suggestDismissed($))) return null;
216  const a = await agreement(engineIo($), await dataDir($));
217  return suggestsStandard(a) && !(await suggestDismissed($)) ? a : null;
218}
219
220// The settings view lists the rows /config draws for this plugin's options
221// and sets them as the person would there, so an option added to the manifest
222// shows up with no change here. A deny, from another plugin's hook or a lock,
223// is a toast, and the rows are listed again either way.
224async function listOptions($: EngineInterface): Promise<void> {
225  // A plugin's keys are `katharsis.<field>` however it was installed, while
226  // its owner reads katharsis@inline when it loads from a folder.
227  S.options = (await $.config.list()).filter((r) => r.key.startsWith('katharsis.'));
228  $.ui.invalidate('ui.render');
229}
230
231async function setOption($: EngineInterface, row: ConfigRow, value: ConfigValue): Promise<void> {
232  // The set reloads the module, so what restore reads is written first.
233  await Promise.all([
234    $.state.set(VIEW, S.view),
235    $.state.set(LAST_ANSWER, S.lastAnswer),
236    $.state.set(SHOW, S.show),
237  ]).catch(() => undefined);
238  const r = await $.config.set({ key: row.key, value }).catch((err: unknown) => ({ deny: err instanceof Error ? err.message : String(err) }));
239  if (r.deny !== undefined) $.ui.toast(`Katharsis could not change ${row.label}: ${r.deny}`);
240  await listOptions($);
241}
242
243// A change in the settings view reloads this module, which starts S over, so
244// the view, the last reply, and Status also go to the session's state, and
245// session start, which a reload raises again, puts them back. The drawer
246// itself stays up through a reload, so restore asks whether it is.
247const VIEW = { plugin: 'katharsis', key: 'view' } as const;
248const LAST_ANSWER = { plugin: 'katharsis', key: 'lastAnswer' } as const;
249const SHOW = { plugin: 'katharsis', key: 'show' } as const;
250
251function setView($: EngineInterface, v: View): void {
252  S.view = v;
253  void $.state.set(VIEW, v).catch(() => undefined);
254}
255
256async function restore($: EngineInterface): Promise<void> {
257  const g = generation;
258  const view = (await $.state.get(VIEW)).value;
259  const last = (await $.state.get(LAST_ANSWER)).value;
260  const show = (await $.state.get(SHOW)).value;
261  // A failed lookup leaves the drawer counted closed rather than losing the rest.
262  const open = (await $.ui.panes().catch(() => [])).some((p) => p.id === PANE && p.isPlaced);
263  // A /clear that overtook the reads already set the new session's values.
264  if (g !== generation) return;
265  if (view) S.view = view;
266  if (last !== undefined) S.lastAnswer = last;
267  if (show) S.show = show;
268  S.paneOpen = open;
269  if (S.view === 'settings') await listOptions($);
270  $.ui.invalidate('ui.render');
271}
272
273async function suggestDismissed($: EngineInterface): Promise<boolean> {
274  return $.fs.exists(`${await dataDir($)}/${SUGGEST_DISMISSED}`);
275}
276
277function fresh(): State {
278  return {
279    active: false,
280    loaded: false,
281    commandRegistered: false,
282    items: [],
283    query: '',
284    prefix: 'all',
285    show: 'all',
286    view: 'short',
287    selected: '',
288    picks: new Map(),
289    notes: new Map(),
290    sending: new Set(),
291    filterOpen: false,
292    statusOpen: false,
293    viewOpen: false,
294    paneOpen: false,
295    answered: new Map(),
296    closed: new Map(),
297    citedBy: new Map(),
298    corrected: new Map(),
299    hint: false,
300    lastAnswer: '',
301    only: [],
302    level: '',
303    band: false,
304    options: [],
305    suggestion: null,
306    scan: null,
307  };
308}
309
310// Module state: the render hooks read it, the press and input closures
311// mutate it and invalidate. A function that takes $ must be declared at the
312// top of the file (the engine checks where $ goes), hence module scope.
313const S: State = fresh();
314
315// A register() call or /clear empties the cache and moves the generation on,
316// so a refresh that began before it writes nothing, and a drawing after it
317// starts its own load rather than joining one that read the old session.
318let generation = 0;
319let loading: Promise<void> | null = null;
320function reset(): void {
321  generation += 1;
322  loading = null;
323}
324
325async function refresh($: EngineInterface): Promise<void> {
326  const g = generation;
327  const r = await loadLedger($);
328  const answered = r.active ? await loadAnswered($) : new Map();
329  const hint = r.active ? await hintHere($, openQuestions(r.items, answered).length > 0, g) : false;
330  // A suggestion another session dismissed goes at this session's next
331  // refresh. The scan reads every answers file, so it runs beside the
332  // refresh rather than inside it, and a failed scan just makes none.
333  const dropSuggestion = S.suggestion !== null && (await suggestDismissed($));
334  if (g !== generation) return;
335  S.active = r.active;
336  S.items = r.items;
337  S.answered = answered;
338  S.closed = closersOf(S.items, S.answered);
339  S.citedBy = citersOf(S.items);
340  S.corrected = correctionsOf(S.items);
341  S.hint = hint;
342  if (dropSuggestion) S.suggestion = null;
343  if (r.active && !S.scan) {
344    const scan = Symbol('scan');
345    S.scan = scan;
346    void suggestionHere($)
347      .then((a) => {
348        if (!a || S.scan !== scan || S.level) return;
349        S.suggestion = a;
350        $.ui.invalidate('ui.render');
351      })
352      .catch(() => undefined);
353  }
354  S.loaded = true;
355  // Marked before the await, so refreshes that overlap register it once.
356  if (S.active && !S.commandRegistered) {
357    S.commandRegistered = true;
358    try {
359      await $.command.register({
360        name: PANE,
361        description: 'Open the Katharsis drawer: every coded item this session, searchable',
362        argumentHint: '[query]',
363        immediate: true,
364      });
365    } catch (err) {
366      S.commandRegistered = false;
367      throw err;
368    }
369  }
370}
371
372// One load shared by every drawing that finds the cache empty, so the replies
373// on screen after a reload read the ledger and register /kdrawer once.
374function load($: EngineInterface): Promise<void> {
375  if (!loading) {
376    const p: Promise<void> = refresh($).finally(() => {
377      // A reset may have started a newer load meanwhile; that one stays shared.
378      if (loading === p) loading = null;
379    });
380    loading = p;
381  }
382  return loading;
383}
384
385async function redrawFresh($: EngineInterface): Promise<void> {
386  await refresh($);
387  $.ui.invalidate('ui.render');
388}
389
390function prefixes(): string[] {
391  return [...new Set(S.items.map((i) => i.prefix))];
392}
393
394// The Still open row's groups, in STILL_OPEN order, each type's unclosed
395// codes with the newest few shown and the rest counted, so nothing open
396// drops out of sight.
397function stillOpen(): { prefix: string; all: Item[]; shown: Item[] }[] {
398  return STILL_OPEN.map((p) => {
399    const all =
400      p === 'Q' ? openQuestions(S.items, S.answered) : ofPrefix(p).filter((i) => !S.closed.has(i.code.toUpperCase()));
401    return { prefix: p, all, shown: all.slice(-STILL_OPEN_SHOWN) };
402  }).filter((g) => g.all.length > 0);
403}
404
405// What View current lists: the codes the latest reply cites other than
406// questions, as its Codes this turn row names them, and every still open code.
407function current(): { turn: Item[]; open: Item[] } {
408  const byCodeMap = new Map(S.items.map((i) => [i.code.toUpperCase(), i]));
409  const turn = [...new Set((S.lastAnswer.match(CODE_RE) ?? []).map((c) => c.toUpperCase()))]
410    .map((c) => byCodeMap.get(c))
411    .filter((i): i is Item => i !== undefined && i.prefix !== 'Q');
412  return { turn: codeOrder(turn), open: stillOpen().flatMap((g) => g.all) };
413}
414
415// A dismissed code is a question answered `x`, an item an `X` line dropped,
416// or a finding an erratum withdrew.
417function dismissed(i: Item): boolean {
418  const c = S.closed.get(i.code.toUpperCase());
419  return c !== undefined && (c.letter === 'x' || c.prefix === 'X' || i.prefix === 'F');
420}
421
422function isClosed(i: Item): boolean {
423  return S.closed.has(i.code.toUpperCase());
424}
425
426// A row's status glyph: a circle for an item still open or of a type that
427// never closes, a check for one answered or closed, a cross for one dismissed
428// or dropped, and a bang for an open line an erratum corrected without
429// restating it, since its title is the wrong version. Every row has one, and
430// the Status menu carries the key.
431function glyph(i: Item): string {
432  if (!isClosed(i)) return S.corrected.has(i.code.toUpperCase()) ? '!' : '○';
433  return dismissed(i) ? '✗' : '✓';
434}
435
436// A check is green, a cross red, a bang yellow, and a circle grey, in a drawer
437// row, a band popup row, a card header, and the key.
438function paint(Text: ReturnType<EngineInterface['ui']['resolve']>['Text'], g: string) {
439  return g === '✓' ? <Text color="success">{g}</Text> : g === '✗' ? <Text color="error">{g}</Text> : g === '!' ? <Text color="warning">{g}</Text> : <Text dimColor>{g}</Text>;
440}
441
442
443// A card's closing line names how the item ended, with a verb for each way
444// and the line that did it: a question Answered, Settled, or Dismissed, owed
445// work Done, a block Cleared, a risk Retired, a caveat Lifted, anything an
446// exclusion Dropped, and a finding Withdrawn. The mark and verb are the head,
447// which alone takes the colour; the tail is information.
448const VERB: Record<string, string> = { Q: 'Settled by', NA: 'Done in', MV: 'Done in', W: 'Done in', B: 'Cleared by', R: 'Retired by', C: 'Lifted by' };
449
450function closing(i: Item): { head: string; tail: string } | null {
451  const c = S.closed.get(i.code.toUpperCase());
452  if (!c) return null;
453  const by = c.by ? `${c.by}${c.title ? `: ${c.title}` : ''}` : '';
454  if (i.prefix === 'F') return { head: '✗ Withdrawn', tail: c.by ? ` by ${c.by}` : '' };
455  if (c.letter === 'x') return { head: '✗ Dismissed', tail: '' };
456  if (S.answered.has(i.code.toUpperCase())) return { head: '✓ Answered', tail: `${c.letter ? ` ${c.letter}` : ''}${by ? ` · in ${by}` : ''}` };
457  if (c.prefix === 'X') return { head: '✗ Dropped by', tail: ` ${by}` };
458  return { head: `✓ ${VERB[i.prefix] ?? 'Resolved by'}`, tail: ` ${by}` };
459}
460
461// The closing line as one Text: the head in green or red, the tail plain.
462function closingLine(Text: ReturnType<EngineInterface['ui']['resolve']>['Text'], i: Item, key?: string) {
463  const c = closing(i);
464  if (!c) return null;
465  return (
466    <Text key={key} wrap="wrap">
467      <Text color={dismissed(i) ? 'error' : 'success'}>{c.head}</Text>
468      {c.tail}
469    </Text>
470  );
471}
472
473// The card of a line an erratum corrected without restating it leads with the
474// erratum, because the title above it is the version the erratum replaced.
475function correctionLine(Text: ReturnType<EngineInterface['ui']['resolve']>['Text'], i: Item, key?: string) {
476  const e = S.corrected.get(i.code.toUpperCase());
477  if (!e) return null;
478  return (
479    <Text key={key} wrap="wrap">
480      <Text color="warning">! Corrected by</Text>
481      {` ${e.code}${e.summary ? `: ${e.summary}` : ''}`}
482    </Text>
483  );
484}
485
486// A finding closes only when withdrawn, so its card lists the codes that cite it.
487function backlinks(i: Item): string {
488  const by = i.prefix === 'F' ? (S.citedBy.get(i.code.toUpperCase()) ?? []) : [];
489  return by.length > 0 ? `Cited by ${by.map((j) => j.code).join(' ')}` : '';
490}
491
492// What send posts for a question: the picked letter and the note after it,
493// or the note alone as an own answer (z). A dismissal puts a dash before its
494// note, because a word after x reads as prose.
495export function answerText(code: string, letter: string, note: string): string {
496  const n = note.trim();
497  if (letter === '') return n === '' ? '' : `${code} z ${n}`;
498  return n === '' ? `${code} ${letter}` : letter === 'x' ? `${code} x - ${n}` : `${code} ${letter} ${n}`;
499}
500
501// Send posts answers as the person's next message, one line per question,
502// and leaves the prompt box alone. A card's send posts its own question; the
503// queue's send posts every open question that holds a pick or a note. Claude
504// Code runs none of this plugin's prompt.submit hooks on a prompt the plugin
505// submits, so send records the answer rows the prompt hook would have. The
506// turn gets none of that hook's other lines (the classify reminder,
507// Dismissed, Open questions), and the style alone carries them. A note the
508// parser would read as other than its own answer stops the whole send.
509async function sendAnswers($: EngineInterface, codes: string[]): Promise<void> {
510  if (codes.length === 0 || codes.some((c) => S.sending.has(c))) return;
511  const held = codes.map((code) => {
512    const letter = S.picks.get(code) ?? '';
513    const note = S.notes.get(code) ?? '';
514    return { code, letter, note, text: answerText(code, letter, note) };
515  });
516  const empty = held.find((h) => h.text === '');
517  if (empty) {
518    $.ui.toast(`Pick an option or write your own answer to ${empty.code} first`);
519    return;
520  }
521  const text = held.map((h) => h.text).join('\n');
522  const asked = new Map(S.items.filter((i) => i.prefix === 'Q').map((i) => [i.code.toUpperCase(), i.options.map((o) => o.key.toLowerCase())]));
523  const round = latestRound(S.items);
524  const bad = held.find((h) => {
525    const read = readAnswers(h.text, round, asked);
526    return read.unclear.length > 0 || read.answers.length !== 1 || read.answers[0]!.code !== h.code || read.answers[0]!.letter !== (h.letter || 'z');
527  });
528  if (bad) {
529    $.ui.toast(`Katharsis would not read "${bad.text}" as one answer to ${bad.code}: reword the note`);
530    return;
531  }
532  // Each pick and note stays on its card while the send is out, so a failed
533  // send leaves the cards as the person last left them, edits included. The
534  // rows go under the session the send started in, in case a /clear lands
535  // while it is out.
536  const { picks, notes, sending } = S;
537  for (const c of codes) sending.add(c);
538  let sid: string | undefined;
539  let entered: string | undefined;
540  try {
541    sid = (await $.session.id()) ?? undefined;
542    const r = await $.prompt.submit({ text, asUser: true });
543    if (r.drop === undefined) entered = r.text;
544  } catch {}
545  for (const c of codes) sending.delete(c);
546  if (entered === undefined) {
547    $.ui.toast(`Katharsis could not send ${codes.join(' ')}: ${held.length === 1 ? `type ${text}` : 'type each answer on its own line'} and press Enter instead`);
548    return;
549  }
550  // A hook beneath may rewrite the prompt, so the rows record what entered.
551  // A failed write or redraw costs the rows, never the send. A pick or note
552  // changed while the send was out stays, in case the question stays open.
553  for (const h of held) {
554    if ((picks.get(h.code) ?? '') === h.letter) picks.delete(h.code);
555    if ((notes.get(h.code) ?? '') === h.note) notes.delete(h.code);
556  }
557  try {
558    if (sid) await recordAnswers({ read: engineIo($).read, write: (p, s) => $.fs.write(p, s) }, await dataDir($), sid, readAnswers(entered, round, asked).answers);
559    await refresh($);
560  } catch {}
561  $.ui.invalidate('ui.render');
562}
563
564function hintFor(code: string): string {
565  return `Ex: ${code} a or ${code} z <custom>`;
566}
567
568function ofPrefix(p: string): Item[] {
569  return S.items.filter((i) => i.prefix === p);
570}
571
572function haystack(i: Item): string {
573  return [i.code, nameOf(i), i.title, i.summary, ...i.options.map((o) => `${o.key}. ${o.text}`), i.rec]
574    .join('\n')
575    .toLowerCase();
576}
577
578// Status open keeps the types that can close and are not yet closed, and Status
579// resolved the closed ones, done and dropped alike.
580function shows(i: Item, show: Show = S.show): boolean {
581  if (show === 'open') return CLOSING.has(i.prefix) && !isClosed(i);
582  if (show === 'resolved') return isClosed(i);
583  return true;
584}
585
586// A query spelled as a code ("F1") finds that code alone, so F10 to F19 stay
587// out; anything else searches the text. A code asked for by name, the
588// selected one, or the still open list shows whatever Status says, since the
589// person went to it directly, and so does View current. Open items come
590// first within each type, in ledger order otherwise. A heading asks with
591// Status set to all.
592function visible(show: Show = S.show): Item[] {
593  const q = S.query.trim().toLowerCase();
594  const exact = CODE_ONLY.test(q);
595  const cur = S.view === 'current' ? current() : null;
596  const listed = cur ? new Set([...cur.turn, ...cur.open].map((i) => i.code)) : null;
597  return S.items
598    .filter(
599      (i) =>
600        (S.prefix === 'all' || i.prefix === S.prefix) &&
601        (S.only.length === 0 || S.only.includes(i.code)) &&
602        (!listed || listed.has(i.code)) &&
603        (q === '' || (exact ? i.code.toLowerCase() === q : haystack(i).includes(q))) &&
604        (exact || S.only.length > 0 || listed !== null || i.code === S.selected || shows(i, show)),
605    )
606    .sort((a, b) => Number(isClosed(a)) - Number(isClosed(b)));
607}
608
609// How many lines a wrapping row takes: `widths` laid left to right, `gap`
610// apart, in `room` cells.
611function lines(widths: number[], room: number, gap: number): number {
612  let n = 1;
613  let used = 0;
614  for (const w of widths) {
615    if (used > 0 && used + gap + w > room) {
616      n += 1;
617      used = w;
618    } else used += (used > 0 ? gap : 0) + w;
619  }
620  return n;
621}
622
623async function openPane($: EngineInterface, query?: string, only: string[] = []): Promise<string> {
624  if (query !== undefined) {
625    S.query = query;
626    S.prefix = 'all';
627    S.selected = CODE_ONLY.test(query.trim()) ? query.trim().toUpperCase() : '';
628  }
629  // Every open starts in the short view with the menus closed, except the
630  // still open codes, which open in full so their options show. Status keeps
631  // its last setting.
632  S.only = only;
633  setView($, only.length > 0 ? 'full' : 'short');
634  S.filterOpen = S.statusOpen = S.viewOpen = false;
635  const opened = await $.ui.open({ id: PANE, title: TITLE, focus: true, closeOnEscape: true });
636  S.paneOpen = opened.isPlaced;
637  return opened.isPlaced ? '' : `Katharsis drawer is waiting: ${opened.reason}`;
638}
639
640// The reply's text with every code on record turned into a link, skipping
641// fenced blocks and inline code spans, where a link would draw literally.
642export function linkify(text: string, items: Item[]): { text: string; hrefs: string[] } {
643  const hrefs = new Set<string>();
644  const byCode = new Map(items.map((i) => [i.code.toUpperCase(), i]));
645  const link = (seg: string) =>
646    seg.replace(CODE_RE, (c) => {
647      const item = byCode.get(c.toUpperCase());
648      if (!item) return c;
649      const href = `${LINK_BASE}${c}/${nameOf(item).toLowerCase().replace(/[^a-z0-9]+/g, '-')}`;
650      hrefs.add(href);
651      return `[${c}](${href})`;
652    });
653  let inFence = false;
654  const out = text.split('\n').map((line) => {
655    if (/^\s*(```|~~~)/.test(line)) {
656      inFence = !inFence;
657      return line;
658    }
659    if (inFence) return line;
660    return line
661      .split(/(`[^`]*`)/)
662      .map((seg) => (seg.startsWith('`') && seg.endsWith('`') && seg.length > 1 ? seg : link(seg)))
663      .join('');
664  });
665  return { text: out.join('\n'), hrefs: [...hrefs] };
666}
667
668function codeOfHref(href: string): string {
669  return href.startsWith(LINK_BASE) ? (href.slice(LINK_BASE.length).split('/')[0] ?? '') : '';
670}
671
672// Where Claude Code judges the terminal unable to show a link, it draws the
673// link's text and then its URL, so every linked code would read as
674// "F3 (https://katharsis.invalid/F3/finding)". This is that judgment from the
675// environment, as Claude Code 2.1.301 makes it: the supports-hyperlinks checks,
676// then its own list of terminals. The process's TTY and color checks and the
677// --no-hyperlink flags are out of reach and pass in an interactive session.
678const LINK_TERMINALS = ['ghostty', 'Hyper', 'kitty', 'alacritty', 'iTerm.app', 'iTerm2', 'WarpTerminal'];
679
680function version(v: string): { major: number; minor: number } {
681  const old = /^(\d{1,2})(\d{2})$/.exec(v);
682  if (/^\d{3,4}$/.test(v) && old) return { major: 0, minor: Number(old[1]) };
683  const [major = NaN, minor = NaN] = v.split('.').map((n) => parseInt(n, 10));
684  return { major, minor };
685}
686
687export function terminalShowsLinks(env: Record<string, string | undefined>): boolean {
688  const supports = () => {
689    if (env.NETLIFY) return true;
690    if (env.WT_SESSION !== undefined) return true;
691    if (env.CI || env.TEAMCITY_VERSION) return false;
692    const v = version(env.TERM_PROGRAM_VERSION ?? '');
693    switch (env.TERM_PROGRAM) {
694      case 'iTerm.app':
695        return v.major === 3 ? v.minor >= 1 : v.major > 3;
696      case 'WezTerm':
697        return v.major >= 20200620;
698      case 'vscode':
699        return v.major > 1 || (v.major === 1 && v.minor >= 72);
700      case 'ghostty':
701        return true;
702    }
703    if (env.VTE_VERSION) {
704      if (env.VTE_VERSION === '0.50.0') return false;
705      const vte = version(env.VTE_VERSION);
706      return vte.major > 0 || vte.minor >= 50;
707    }
708    return env.TERM === 'alacritty';
709  };
710  const force = env.FORCE_HYPERLINK;
711  if (force !== undefined) return force !== '' ? parseInt(force, 10) !== 0 : supports();
712  if (supports()) return true;
713  const program = env.TERM_PROGRAM ?? '';
714  if (LINK_TERMINALS.includes(program) || LINK_TERMINALS.includes(env.LC_TERMINAL ?? '')) return true;
715  if (env.TERMINAL_EMULATOR === 'JetBrains-JediTerm') return true;
716  if (program === 'tmux') {
717    const t = version(env.TERM_PROGRAM_VERSION ?? '');
718    if (t.major > 3 || (t.major === 3 && t.minor >= 4)) return true;
719  }
720  return env.TERM?.includes('kitty') ?? false;
721}
722
723let showsLinks: Promise<boolean> | null = null;
724
725// The environment holds for the process, so it is read once. Each name is
726// spelled out, since the engine lists the variables a module reads. A failed
727// read keeps the engine's drawing for that reply and is tried again next time,
728// since a cached guess of true would bring the URLs back.
729function linksShown($: EngineInterface): Promise<boolean> {
730  showsLinks ??= (async () =>
731    terminalShowsLinks({
732      FORCE_HYPERLINK: await $.env.get('FORCE_HYPERLINK'),
733      NETLIFY: await $.env.get('NETLIFY'),
734      WT_SESSION: await $.env.get('WT_SESSION'),
735      CI: await $.env.get('CI'),
736      TEAMCITY_VERSION: await $.env.get('TEAMCITY_VERSION'),
737      TERM_PROGRAM: await $.env.get('TERM_PROGRAM'),
738      TERM_PROGRAM_VERSION: await $.env.get('TERM_PROGRAM_VERSION'),
739      VTE_VERSION: await $.env.get('VTE_VERSION'),
740      TERM: await $.env.get('TERM'),
741      LC_TERMINAL: await $.env.get('LC_TERMINAL'),
742      TERMINAL_EMULATOR: await $.env.get('TERMINAL_EMULATOR'),
743    }))().catch(() => {
744      showsLinks = null;
745      return false;
746    });
747  return showsLinks;
748}
749
750// The session record's two late fields (session.ts). They live here because
751// the engine takes one hook per event from the plugin, and the drawer's
752// hooks below already hold classic.Stop and turn.complete.
753async function dataDir($: EngineInterface): Promise<string> {
754  const home = (await $.env.get('HOME')) ?? '';
755  return (await $.env.get('KATHARSIS_DATA')) ?? `${home}/.claude/katharsis-data`;
756}
757
758// The transcript's path arrives only with a classic hook's input.
759async function noteTranscript($: EngineInterface, sid: string, path: string): Promise<void> {
760  if (!sid || !path) return;
761  const data = await dataDir($);
762  const rec = await readRecord(engineIo($), data, sid);
763  const next = rec && withTranscript(rec, path, await $.fs.exists(path));
764  if (next) await $.fs.write(recordPath(data, sid), `${JSON.stringify(next, null, 2)}\n`);
765}
766
767async function titleSession($: EngineInterface): Promise<void> {
768  const sid = await $.session.id();
769  if (!sid) return;
770  const data = await dataDir($);
771  const io = engineIo($);
772  const rec = await readRecord(io, data, sid);
773  if (!rec || !wantsTitle(rec, await $.session.turns())) return;
774  const r = await $.model.fork({ prompt: TITLE_PROMPT });
775  const title = r.isAnswered ? cleanTitle(r.text) : '';
776  // Re-read, since the next prompt may have touched the record meanwhile.
777  const fresh = title ? await readRecord(io, data, sid) : null;
778  if (fresh) await $.fs.write(recordPath(data, sid), `${JSON.stringify({ ...fresh, title, titleSource: 'katharsis' }, null, 2)}\n`);
779}
780
781export function registerDrawer(on: On, level = '', band = false): void {
782  // A register() call starts clean: a hot reload re-runs it, and so does a
783  // change to the autonomy level or the band option in /config.
784  Object.assign(S, fresh(), { level, band });
785  reset();
786  showsLinks = null;
787
788  // After the Stop command hooks (ledger-stop.sh) have written this turn's rows.
789  on('classic.Stop', async ($, e, next) => {
790    const r = await next(e);
791    await noteTranscript($, e.session_id, e.transcript_path).catch(() => undefined);
792    await redrawFresh($);
793    return r;
794  }).catch(($, e, next) => next(e));
795
796  // A managed plugin can route classic.* past the user tier (sec-default
797  // does), so the Stop hook above may never run. turn.complete can fire
798  // before ledger-stop.sh writes, so it reloads now and twice more after.
799  on('turn.complete', async ($, e, next) => {
800    const r = await next(e);
801    if (e.agentId) return r;
802    // After the reply is out, so the title's fork never delays it.
803    if (!e.isAborted) void titleSession($).catch(() => undefined);
804    S.lastAnswer = typeof e.answer === 'string' ? e.answer : '';
805    void $.state.set(LAST_ANSWER, S.lastAnswer).catch(() => undefined);
806    await redrawFresh($);
807    $.clock.after(1500, () => void redrawFresh($));
808    $.clock.after(5000, () => void redrawFresh($));
809    return r;
810  }).catch(($, e, next) => next(e));
811
812  // Focus moving to anything but the menu or its button closes the menu: a
813  // click on a row, the search field, or another button.
814  on('ui.focus', { requestId: PANE }, ($, e, next) => {
815    if (S.filterOpen && e.element !== 'filter' && !e.element?.startsWith('filter-')) {
816      S.filterOpen = false;
817      $.ui.invalidate('ui.render');
818    }
819    if (S.statusOpen && e.element !== 'show' && !e.element?.startsWith('status-')) {
820      S.statusOpen = false;
821      $.ui.invalidate('ui.render');
822    }
823    if (S.viewOpen && e.element !== 'view' && !e.element?.startsWith('view-')) {
824      S.viewOpen = false;
825      $.ui.invalidate('ui.render');
826    }
827    return next(e);
828  }).catch(($, e, next) => next(e));
829
830  on('ui.close', async ($, e, next) => {
831    const r = await next(e);
832    if (e.id === PANE) {
833      S.paneOpen = false;
834      $.ui.invalidate('ui.render');
835    }
836    return r;
837  }).catch(($, e, next) => next(e));
838
839  on('session.start', async ($, e, next) => {
840    await restore($).catch(() => undefined);
841    await refresh($);
842    // Restore drew before refresh made the drawer active.
843    $.ui.invalidate('ui.render');
844    return next(e);
845  }).catch(($, e, next) => next(e));
846
847  // /clear goes on under a new session id with no session.start, so the
848  // cache still holds the old session's items. Emptying it makes the next
849  // turn's refresh, or the next reply's or band's drawing, load the new one.
850  // The command stays registered.
851  on('session.end', async ($, e, next) => {
852    const r = await next(e);
853    if (e.reason === 'clear') {
854      Object.assign(S, fresh(), { commandRegistered: S.commandRegistered, show: S.show, level: S.level, band: S.band });
855      void $.state.set(VIEW, S.view).catch(() => undefined);
856      void $.state.set(LAST_ANSWER, '').catch(() => undefined);
857      void $.state.set(SHOW, S.show).catch(() => undefined);
858      reset();
859      $.ui.invalidate('ui.render');
860    }
861    return r;
862  }).catch(($, e, next) => next(e));
863
864  on('command.run', { command: PANE }, async ($, e) => {
865    await refresh($);
866    if (!S.active) return { text: 'Katharsis is not active in this session.' };
867    const text = await openPane($, e.args.trim());
868    return text ? { text } : {};
869  }).catch(($, e, next) => next(e));
870
871  // The band, drawn only when the band option is on, since a row above the
872  // prompt competes with other plugins' rows there: the title in teal, an
873  // open button that k presses while the band holds the focus, the command's
874  // name, then one label per type present. A Button's label takes no color, so the
875  // title is text and the open button sits beside it. Hovering a label
876  // reveals that type's latest titles above the row. The reveal sits above
877  // the row so the row stays under the pointer while the band grows, and it
878  // joins the label's hover group, so the pointer can move up into it and
879  // press a title or the list-all button.
880  //
881  // Every reveal is one fixed height, so moving between labels never resizes
882  // the band, and the band never grows past maxRows, where the engine would
883  // make it scroll. Each label's box holds the pipe after it, so crossing a
884  // pipe keeps the pointer inside a group and the reveal never blinks.
885  // While the pane is open the reveals are left out: the pointer's last hover
886  // stays lit under the docked pane, and the surface left it half drawn.
887  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
888    if (!S.band || e.props.hasSurvey) return next(e);
889    if (!S.loaded) await load($);
890    if (!S.active) return next(e);
891    // Another plugin's band draws beneath this one rather than being replaced.
892    const below = await next(e);
893    const { Box, Text, Button } = $.ui.resolve(e);
894    const present = byCode(prefixes());
895    const most = Math.max(0, ...present.map((p) => ofPrefix(p).length));
896    // Border 2, header 1, band row 1; what is left holds titles, at most 10.
897    const listRows = Math.max(1, Math.min(REVEAL_MAX, most, e.props.maxRows - 4));
898    const revealHeight = listRows + 3;
899    const titleWidth = Math.max(10, e.props.bodyColumns - 4);
900    // The hint goes when the row would not fit, as beside a docked pane: a row
901    // too wide shrinks its Texts to nothing rather than cutting the tail.
902    const labels = present.map((p) => `${p}:${ofPrefix(p).length}`).join('|');
903    const hint = `▸ ${TITLE} · k: open | use /${PANE} · ${labels}`.length <= e.props.bodyColumns ? `| use /${PANE} ·` : '·';
904    const openType = (p: string, code = '') => {
905      S.query = code;
906      S.selected = code;
907      S.prefix = p;
908      void openPane($).then(() => $.ui.invalidate('ui.render'));
909    };
910    const band = (
911      <Box flexDirection="column">
912        {(S.paneOpen ? [] : present).map((p) => {
913          const items = ofPrefix(p);
914          const shown = items.slice(-listRows);
915          // The code cell fits the widest code shown, so every title starts in one column.
916          const codeWidth = Math.max(0, ...shown.map((i) => i.code.length));
917          return (
918            <Box
919              key={`reveal-${p}`}
920              display="none"
921              hover={{ scope: `kband-${p}`, display: 'flex' }}
922              flexDirection="column"
923              height={revealHeight}
924              overflow="hidden"
925              borderStyle="round"
926              paddingX={1}
927            >
928              <Box key={`reveal-head-${p}`} flexDirection="row" gap={2}>
929                <Text bold>{`${groupName(p)} · ${items.length}`}</Text>
930                {items.length > shown.length ? <Text dimColor>{`latest ${shown.length}`}</Text> : null}
931                <Button key={`reveal-all-${p}`} label={`list all ${items.length} ▸`} plain onPress={() => openType(p)} />
932              </Box>
933              {shown.map((i) => (
934                // The row leads with the glyph its drawer row carries.
935                <Box key={`reveal-row-${i.code}`} flexDirection="row">
936                  <Box key={`reveal-glyph-${i.code}`} width={2} flexShrink={0}>{paint(Text, glyph(i))}</Box>
937                  <Button
938                    key={`reveal-${i.code}`}
939                    label={clip(`${i.code.padEnd(codeWidth)}  ${i.title}`, titleWidth - 2)}
940                    plain
941                    onPress={() => openType(p, i.code)}
942                  />
943                </Box>
944              ))}
945            </Box>
946          );
947        })}
948        <Box key="band-row" flexDirection="row" gap={1} height={1} overflow="hidden">
949          <Box key="band-head" flexDirection="row" gap={1} flexShrink={0}>
950            <Text color={TEAL}>{`▸ ${TITLE}`}</Text>
951            <Text dimColor>·</Text>
952            <Button
953              key="open"
954              label="open"
955              hotkey="k"
956              plain
957              hover={{ scope: 'kband-open', underline: true }}
958              // An empty query, as /kdrawer with no argument sends, so a code
959              // the band opened last time does not stay listed past Status.
960              onPress={() => {
961                void openPane($, '').then(() => refresh($)).then(() => $.ui.invalidate('ui.render'));
962              }}
963            />
964            <Text dimColor>{hint}</Text>
965          </Box>
966          {present.length === 0 ? <Text dimColor>no codes yet</Text> : null}
967          <Box key="band-labels" flexDirection="row">
968            {present.map((p, k) => (
969              <Box key={`label-${p}`} flexDirection="row" flexShrink={0} hover={{ scope: `kband-${p}` }}>
970                <Button
971                  key={`band-${p}`}
972                  label={`${p}:${ofPrefix(p).length}`}
973                  plain
974                  dimColor
975                  hover={{ scope: `kband-${p}`, bold: true }}
976                  onPress={() => openType(p)}
977                />
978                {k < present.length - 1 ? <Text dimColor>|</Text> : null}
979              </Box>
980            ))}
981          </Box>
982        </Box>
983      </Box>
984    );
985    return below ? <Box flexDirection="column">{band}{below}</Box> : band;
986  }).catch(($, e, next) => next(e));
987
988  on('ui.render', { component: 'Pane', requestId: PANE }, ($, e, next) => {
989    if (!S.active) return next(e);
990    const T = $.ui.resolve(e);
991    const { Box, Text, Button } = T;
992    const redraw = () => $.ui.invalidate('ui.render');
993    const rows = visible();
994    const width = Math.max(20, e.props.bodyColumns);
995    const present = byName(prefixes());
996    const groups = byName([...new Set(rows.map((i) => i.prefix))]);
997    // The pane losing focus, a click in the transcript or the prompt, closes the menu.
998    if (!e.props.isFocused) S.filterOpen = S.statusOpen = S.viewOpen = false;
999    // Row 2 names the filter by its code when the full name would push the
1000    // View button onto a line of its own, as in a docked pane. A Button draws
1001    // as `[ label ]`, the controls sit 2 apart, and the row keeps 2 of padding.
1002    // Past that the row wraps, and the menu drops below its last line.
1003    const viewLabel = `View: ${S.view} ${S.viewOpen ? '▴' : '▾'}`;
1004    const full = S.view !== 'short';
1005    // The settings view hides search, Filter, Status, and Clear, which act on
1006    // the list it replaces, and leaves View as the way back.
1007    const settings = S.view === 'settings';
1008    // Status opens a menu of all, open, and resolved, with the key to the row
1009    // glyphs below them. Clear leaves it alone: Status is a standing
1010    // preference that outlives the pane, and Clear undoes one visit's search.
1011    const showLabel = `Status: ${S.show} ${S.statusOpen ? '▴' : '▾'}`;
1012    const named = S.only.length > 0 ? 'still open' : S.prefix === 'all' ? 'all types' : groupName(S.prefix);
1013    const controls = (filter: string) => [filter.length + 4, showLabel.length + 4, 'Clear'.length + 4, viewLabel.length + 4];
1014    const fits = lines(controls(`Filter: ${named} ▾`), width - 2, 2) === 1;
1015    const filterLabel = `Filter: ${fits ? named : S.only.length > 0 ? 'open' : S.prefix} ${S.filterOpen ? '▴' : '▾'}`;
1016    const menuTop = settings ? 1 : 1 + lines(controls(filterLabel), width - 2, 2);
1017    const menu = [
1018      { value: 'all', name: 'All types', n: S.items.length },
1019      ...present.map((p) => ({ value: p, name: groupName(p), n: ofPrefix(p).length })),
1020    ];
1021    // An inline pane's frame fits the tree, which a placed menu adds nothing
1022    // to, and stops at the rows the surface gave it. The tree grows to reach
1023    // an open menu's foot, and a menu taller than the room splits into columns.
1024    const inline = e.props.placement === 'inline';
1025    // Columns stop at what the drawer's width holds whole, and a menu still
1026    // taller than the room scrolls with the drawer.
1027    const longest = Math.max(...menu.map((f) => `● ${f.name} ${f.n}`.length));
1028    const room = inline ? Math.max(1, e.props.scroll.bodyRows - menuTop - 2) : menu.length;
1029    const across = Math.min(Math.ceil(menu.length / room), Math.max(1, Math.floor((width - 2) / (longest + 2))));
1030    const perColumn = Math.ceil(menu.length / across);
1031    // Recounted, so a split the width capped never leaves its last column empty.
1032    const columns = Math.ceil(menu.length / perColumn);
1033    // The menu reaches the Clear button's right edge, wider only for a long name.
1034    const reach = filterLabel.length + 4 + 2 + showLabel.length + 4 + 2 + 'Clear'.length + 4;
1035    const menuWidth = Math.min(width, Math.max(reach, columns * longest + (columns - 1) * 2 + 4));
1036    const cellWidth = Math.floor((menuWidth - 4 - (columns - 1) * 2) / columns);
1037    // The Status menu drops below the Status button, or from the left edge
1038    // when the button wrapped onto a line of its own.
1039    const statusMenu = SHOWS.map((s) => ({
1040      value: s,
1041      n: S.items.filter((i) => (S.prefix === 'all' || i.prefix === S.prefix) && shows(i, s)).length,
1042    }));
1043    const legend = [
1044      { g: '○', text: 'open, or never closes' },
1045      { g: '✓', text: 'answered, settled, or done' },
1046      { g: '✗', text: 'dismissed, dropped, or withdrawn' },
1047      { g: '!', text: 'corrected, title not restated' },
1048    ];
1049    const statusWidth = Math.min(width, Math.max(...legend.map((l) => l.text.length + 2), ...statusMenu.map((f) => `● ${f.value} ${f.n}`.length)) + 4);
1050    // A menu wider than the room right of the button shifts left to stay inside the drawer.
1051    // A legend line too long for the menu wraps by word, and each wrap adds a row.
1052    const legendRows = legend.reduce((n, l) => n + lines(l.text.split(' ').map((w) => w.length), statusWidth - 6, 1), 0);
1053    // The View menu hangs from the right edge, under the View button.
1054    const viewWidth = Math.min(width, Math.max(...VIEWS.map((v) => `● ${v.value}  ${v.text}`.length)) + 4);
1055    const menuFoot = menuTop + (S.filterOpen ? perColumn + 2 : S.statusOpen ? statusMenu.length + legendRows + 3 : S.viewOpen ? VIEWS.length + 2 : 0);
1056    const statusLeft = Math.max(0, Math.min(width - statusWidth, lines([filterLabel.length + 4, showLabel.length + 4], width - 2, 2) === 1 ? filterLabel.length + 4 + 2 : 0));
1057
1058    // An open question's card holds an answer until send posts it: an option
1059    // or dismiss picks a letter, pressing it again unpicks it, and the field
1060    // holds a note, or the own answer when nothing is picked. The line by
1061    // send shows the message it will post.
1062    const answerable = (i: Item) => i.prefix === 'Q' && !isClosed(i);
1063    const pick = (code: string, letter: string) => {
1064      if (S.picks.get(code) === letter) S.picks.delete(code);
1065      else S.picks.set(code, letter);
1066      redraw();
1067    };
1068    const option = (i: Item, o: Item['options'][number]) =>
1069      answerable(i) ? (
1070        <Box key={`opt-${i.code}-${o.key}`} flexDirection="row" alignItems="flex-start">
1071          <Box key={`opt-pick-box-${i.code}-${o.key}`} flexShrink={0} marginRight={1}>
1072            <Button
1073              key={`answer-${i.code}-${o.key}`}
1074              label={S.picks.get(i.code) === o.key ? `✓ ${o.key}` : o.key}
1075              variant={S.picks.get(i.code) === o.key ? 'primary' : undefined}
1076              onPress={() => pick(i.code, o.key)}
1077            />
1078          </Box>
1079          <Text wrap="wrap">{o.text}</Text>
1080        </Box>
1081      ) : (
1082        <Text key={`opt-${i.code}-${o.key}`} wrap="wrap">{`  ${o.key}. ${o.text}`}</Text>
1083      );
1084    const noteField = (i: Item) =>
1085      answerable(i) && 'Input' in T ? (
1086        <T.Input
1087          key={`note-${i.code}`}
1088          label={S.picks.has(i.code) ? 'Note' : 'Own answer'}
1089          placeholder={S.picks.has(i.code) ? 'optional, sent after the letter' : 'type it, then send'}
1090          value={S.notes.get(i.code) ?? ''}
1091          submitLabel="send"
1092          onInput={(v) => {
1093            S.notes.set(i.code, v);
1094            redraw();
1095          }}
1096          onSubmit={(v) => {
1097            S.notes.set(i.code, v);
1098            void sendAnswers($, [i.code]);
1099          }}
1100        />
1101      ) : null;
1102    const answerRow = (i: Item) => {
1103      if (!answerable(i)) return null;
1104      const text = answerText(i.code, S.picks.get(i.code) ?? '', S.notes.get(i.code) ?? '');
1105      return (
1106        <Box key={`answer-row-${i.code}`} flexDirection="row" flexWrap="wrap" columnGap={2}>
1107          <Button
1108            key={`answer-${i.code}-x`}
1109            label={S.picks.get(i.code) === 'x' ? '✓ dismiss' : 'dismiss'}
1110            variant={S.picks.get(i.code) === 'x' ? 'primary' : undefined}
1111            onPress={() => pick(i.code, 'x')}
1112          />
1113          <Button key={`send-${i.code}`} label="send" variant="primary" onPress={() => void sendAnswers($, [i.code])} />
1114          <Text key={`answer-preview-${i.code}`} dimColor wrap="wrap">{text === '' ? 'nothing picked yet' : `sends: ${text}`}</Text>
1115        </Box>
1116      );
1117    };
1118
1119    const body = (i: Item) => [
1120      closingLine(Text, i, `closed-${i.code}`),
1121      correctionLine(Text, i, `corrected-${i.code}`),
1122      backlinks(i) ? <Text key={`cited-${i.code}`} wrap="wrap" dimColor>{backlinks(i)}</Text> : null,
1123      i.summary ? <Text key={`sum-${i.code}`} wrap="wrap" dimColor={i.prefix === 'Q'}>{i.summary}</Text> : null,
1124      ...i.options.map((o) => option(i, o)),
1125      i.rec ? <Text key={`rec-${i.code}`} wrap="wrap"><Text bold>Recommended:</Text>{` ${i.rec}`}</Text> : null,
1126      noteField(i),
1127      answerRow(i),
1128    ];
1129
1130    // A row is a table line: the code, the status glyph, and the title, which
1131    // wraps in the cells left. Every row keeps the glyph cell, blank or not, so
1132    // every title starts in one column. The code cell fits the widest code
1133    // shown and its marker.
1134    const codeWidth = Math.max(0, ...rows.map((i) => i.code.length)) + 4;
1135    // A heading counts its type under the search and filters but not Status,
1136    // and for a type that closes, how many are open, so Status open never
1137    // reads "1 open of 1".
1138    const every = visible('all');
1139    const heading = (p: string) => {
1140      const of = every.filter((i) => i.prefix === p);
1141      const open = of.filter((i) => !isClosed(i)).length;
1142      return CLOSING.has(p) ? `${groupName(p)} · ${open} open of ${of.length}` : `${groupName(p)} · ${of.length}`;
1143    };
1144    // The code is a button: pressing it opens the item as a card, a frame
1145    // around the row and its body, and pressing it again closes the card.
1146    const entry = (i: Item) => {
1147      const open = S.selected === i.code;
1148      const line = (
1149        <Box key={`line-${i.code}`} flexDirection="row" alignItems="flex-start">
1150          <Box key={`cell-code-${i.code}`} width={codeWidth} flexShrink={0}>
1151            <Button
1152              key={`pick-${i.code}`}
1153              label={`${open ? '▾' : '▸'} ${i.code}`}
1154              plain
1155              hover={{ scope: `kref-${i.code}`, inverse: true }}
1156              onPress={() => {
1157                S.selected = open ? '' : i.code;
1158                S.filterOpen = S.statusOpen = S.viewOpen = false;
1159                redraw();
1160              }}
1161            />
1162          </Box>
1163          <Box key={`cell-status-${i.code}`} width={2} flexShrink={0}>
1164            {paint(Text, glyph(i))}
1165          </Box>
1166          <Box key={`cell-title-${i.code}`} flexGrow={1} flexShrink={1} minWidth={0}>
1167            <Text wrap="wrap">{i.title}</Text>
1168          </Box>
1169        </Box>
1170      );
1171      return (
1172        <Box key={`row-${i.code}`} flexDirection="column" marginTop={full ? 1 : 0}>
1173          {open ? (
1174            <Box
1175              key={`card-${i.code}`}
1176              flexDirection="column"
1177              borderStyle="round"
1178              backgroundColor="userMessageBackground"
1179              paddingX={1}
1180            >
1181              {line}
1182              {body(i)}
1183            </Box>
1184          ) : (
1185            line
1186          )}
1187          {!open && full ? (
1188            // The body starts under the title, past the code and glyph cells.
1189            <Box key={`body-${i.code}`} flexDirection="column" paddingLeft={codeWidth + 2}>
1190              {body(i)}
1191            </Box>
1192          ) : null}
1193        </Box>
1194      );
1195    };
1196
1197    // An option's row: its label, a button per value with the current one
1198    // marked, then the description /config shows under it. A locked row, or a
1199    // kind with no fixed values, shows its value and changes only in /config.
1200    const valueName = (v: ConfigValue) => (v === true ? 'on' : v === false ? 'off' : String(v));
hooks/ledger.ts 327 lines
1// ledger.ts: the one reader of the ledger's format. The drawer and the prompt
2// hook import it inside the engine, and a CLI under node can import it too,
3// so it holds no JSX, no enums and no engine calls, and every import it ever
4// takes spells its extension. Files arrive through an Io the caller builds on
5// whatever filesystem its runtime has.
6//
7// A handoff chain is one numbering space: ledger/chains/<sid> holds the
8// parent session's ID, and a session's thread is itself plus every ancestor.
9// A later record for a code supersedes an earlier one anywhere in the thread.
10
11export type Io = {
12  // The file's text, or null when it does not exist.
13  read(path: string): Promise<string | null>;
14  // The directory's entries, or none when it does not exist.
15  list(dir: string): Promise<{ name: string; kind: string }[]>;
16};
17
18export type Option = { key: string; text: string };
19export type Item = {
20  code: string;
21  prefix: string;
22  n: number;
23  known: boolean;
24  ts: string;
25  title: string;
26  summary: string;
27  options: Option[];
28  rec: string;
29  // The session that wrote the row, and the heading it sat under.
30  session: string;
31  section: string;
32  // The row's place in the files read, so items stamped in the same second
33  // keep the order the reply wrote them in.
34  seq: number;
35};
36
37// The stock prefixes in the order the next-free line lists them. D is
38// retired but still appears in older ledgers.
39export const ORDER = ['F', 'D', 'A', 'R', 'C', 'AT', 'V', 'NA', 'B', 'MV', 'W', 'X', 'S', 'T-O', 'E', 'Q'];
40
41const alpha = (a: string, b: string) => a.localeCompare(b, 'en');
42
43// Codes in a row, by type then number: A1, AT2, C1, F3, F10.
44export function codeOrder<T extends { prefix: string; n: number }>(xs: T[]): T[] {
45  return [...xs].sort((a, b) => alpha(a.prefix, b.prefix) || a.n - b.n);
46}
47
48// The session and every ancestor its chain file names, newest first.
49export async function thread(io: Io, data: string, sid: string): Promise<string[]> {
50  const ids: string[] = [];
51  let cur = sid;
52  while (cur && !ids.includes(cur) && ids.length < 20) {
53    ids.push(cur);
54    const link = await io.read(`${data}/ledger/chains/${cur}`);
55    if (link === null) break;
56    cur = link.trim();
57    if (!/^[\w-]+$/.test(cur)) break; // a link names a session, never a path
58  }
59  return ids;
60}
61
62// The text of every <id>.jsonl for the thread's ids, oldest session first, in
63// one directory or in each project directory under it. A session can span
64// two project directories, since rows written before the Stop hook keyed the
65// project on the transcript's directory sit under whichever cwd it saw.
66export async function threadTexts(io: Io, dir: string, ids: string[], nested: boolean): Promise<string[]> {
67  const dirs = nested
68    ? (await io.list(dir)).filter((d) => d.kind === 'dir' && d.name !== 'chains').map((d) => `${dir}/${d.name}`)
69    : [dir];
70  const texts: string[] = [];
71  for (const id of [...ids].reverse()) {
72    for (const d of dirs) {
73      const text = await io.read(`${d}/${id}.jsonl`);
74      if (text !== null) texts.push(text);
75    }
76  }
77  return texts;
78}
79
80function toItem(r: Record<string, unknown>): Item | undefined {
81  // A code and a timestamp are printed bare, so a row whose code or ts holds
82  // anything else, such as a terminal escape, is dropped or loses its ts.
83  if (typeof r.code !== 'string' || !/^[A-Z][A-Z-]*\d+$/i.test(r.code)) return undefined;
84  const options = Array.isArray(r.options)
85    ? r.options.map((o: Record<string, unknown>) => ({ key: String(o?.key ?? ''), text: String(o?.text ?? '') }))
86    : [];
87  return {
88    code: r.code,
89    prefix: String(r.prefix ?? ''),
90    n: Number(r.n ?? 0) || 0,
91    known: Boolean(r.known),
92    ts: typeof r.ts === 'string' && /^[\d:.TZ+-]+$/.test(r.ts) ? r.ts : '',
93    title: String(r.title ?? ''),
94    summary: String(r.summary ?? ''),
95    options,
96    rec: String(r.rec ?? ''),
97    session: String(r.session_id ?? ''),
98    section: String(r.section ?? ''),
99    seq: 0,
100  };
101}
102
103// The ledger files' rows as items: a later record for a code supersedes an
104// earlier one, and equal stamps fall to file order.
105export function itemsOf(texts: string[]): Item[] {
106  const latest = new Map<string, Item>();
107  let seq = 0;
108  for (const text of texts) {
109    for (const line of text.split('\n')) {
110      if (line.length > 1_000_000) continue; // a pathological row, never a real one
111      let item: Item | undefined;
112      try {
113        item = toItem(JSON.parse(line) as Record<string, unknown>);
114      } catch {
115        continue; // a blank or partial line
116      }
117      if (!item) continue;
118      item.seq = seq++;
119      const key = item.code.toUpperCase();
120      const old = latest.get(key);
121      if (!old || item.ts >= old.ts) latest.set(key, item);
122    }
123  }
124  return codeOrder([...latest.values()]);
125}
126
127// Every item in the session's thread.
128export async function threadItems(io: Io, data: string, sid: string): Promise<Item[]> {
129  return itemsOf(await threadTexts(io, `${data}/ledger`, await thread(io, data, sid), true));
130}
131
132// The line that tells the model where numbering resumes: the next free
133// number per prefix, stock prefixes in ORDER and invented ones after them.
134// Empty when the thread has no items.
135export function nextFree(items: Item[]): string {
136  const top = new Map<string, number>();
137  for (const i of items) {
138    if (i.prefix) top.set(i.prefix, Math.max(top.get(i.prefix) ?? 0, i.n));
139  }
140  if (top.size === 0) return '';
141  const keys = [
142    ...ORDER.filter((p) => top.has(p)),
143    ...[...top.keys()].filter((p) => !ORDER.includes(p)).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)),
144  ];
145  return `Katharsis codes continue, never restart. Next free: ${keys.map((p) => `${p}${(top.get(p) ?? 0) + 1}`).join('  ')}`;
146}
147
148// A session's record, katharsis-data/sessions/<id>.json. Only Katharsis's
149// hooks write it: the prompt hook creates and touches it, the Stop hook adds
150// the transcript, and turn.complete adds the title. kref reads it to name the
151// session. transcript is
152// the path Claude Code reported, and transcriptSeen says the file existed at
153// some Stop: a path never seen belongs to a session that saved nothing, and
154// a record with no path at all means the Stop hook never ran.
155export type Release = { version: string; commit?: string };
156export type SessionRecord = {
157  id: string;
158  parent?: string;
159  cwd: string;
160  branch?: string;
161  started: string;
162  updated: string;
163  title?: string;
164  titleSource?: string;
165  katharsis: Release[];
166  transcript?: string;
167  transcriptSeen?: boolean;
168};
169
170export function recordPath(data: string, sid: string): string {
171  return `${data}/sessions/${sid}.json`;
172}
173
174const RECORD_TEXT = ['parent', 'cwd', 'branch', 'started', 'updated', 'title', 'titleSource', 'transcript'];
175
176// The session's record, or null when it has none or the file is unreadable.
177// A text field holding anything but text is dropped, as if never written.
178export async function readRecord(io: Io, data: string, sid: string): Promise<SessionRecord | null> {
179  const text = await io.read(recordPath(data, sid));
180  if (text === null) return null;
181  try {
182    const r = JSON.parse(text) as Record<string, unknown>;
183    if (!r || typeof r !== 'object' || r.id !== sid) return null;
184    const out: Record<string, unknown> = { ...r, katharsis: Array.isArray(r.katharsis) ? r.katharsis : [] };
185    for (const k of RECORD_TEXT) if (k in out && typeof out[k] !== 'string') delete out[k];
186    return out as SessionRecord;
187  } catch {
188    return null;
189  }
190}
191
192// The section each stock prefix groups under.
193export const SECTIONS: Record<string, string> = {
194  F: 'Findings', D: 'Decisions', A: 'Assumptions', R: 'Risks', C: 'Caveats', AT: 'Actions Taken',
195  V: 'Verified', NA: 'Next Actions', B: 'Blocked', MV: 'Your Move', W: 'Waiting', X: 'Excluded',
196  S: 'State', 'T-O': 'Trade-offs', E: 'Errata', Q: 'Questions',
197};
198
199// The section an item groups under.
200export function sectionOf(i: Item): string {
201  return SECTIONS[i.prefix.toUpperCase()] ?? (i.section.trim() || 'Other codes');
202}
203
204// Items grouped by section: stock prefixes in ORDER, invented ones by the
205// heading they were written under, and questions last.
206export function sections(items: Item[]): { name: string; items: Item[] }[] {
207  const rank = (i: Item) => {
208    const p = i.prefix.toUpperCase();
209    if (p === 'Q') return 1000;
210    const k = ORDER.indexOf(p);
211    return k >= 0 ? k : 500;
212  };
213  const name = sectionOf;
214  const groups = new Map<string, { rank: number; items: Item[] }>();
215  for (const i of codeOrder(items)) {
216    const g = groups.get(name(i)) ?? { rank: rank(i), items: [] };
217    g.items.push(i);
218    groups.set(name(i), g);
219  }
220  return [...groups.entries()]
221    .sort(([a, x], [b, y]) => x.rank - y.rank || alpha(a, b))
222    .map(([n, g]) => ({ name: n, items: g.items }));
223}
224
225// Every session's ledger text, by session ID, across every project
226// directory.
227export async function ledgerTexts(io: Io, data: string): Promise<Map<string, string[]>> {
228  const out = new Map<string, string[]>();
229  const root = `${data}/ledger`;
230  for (const d of await io.list(root)) {
231    if (d.kind !== 'dir' || d.name === 'chains') continue;
232    for (const f of await io.list(`${root}/${d.name}`)) {
233      if (!f.name.endsWith('.jsonl')) continue;
234      const text = await io.read(`${root}/${d.name}/${f.name}`);
235      if (text === null) continue;
236      const id = f.name.slice(0, -'.jsonl'.length);
237      out.set(id, [...(out.get(id) ?? []), text]);
238    }
239  }
240  return out;
241}
242
243// What kref knows about a session, from its record or from Claude Code's
244// own files. updated is when it last prompted or replied, codes counts the
245// codes it defined itself.
246export type SessionInfo = {
247  id: string;
248  cwd?: string;
249  branch?: string;
250  title?: string;
251  titleSource?: string;
252  started?: string;
253  updated?: string;
254  codes: number;
255};
256
257export type Scope =
258  | { kind: 'all'; reason: '--all' }
259  | { kind: 'session'; reason: '--session' | 'CLAUDE_CODE_SESSION_ID' | 'cwd'; id: string; more: number }
260  | { kind: 'sessions'; reason: 'below-cwd'; sessions: SessionInfo[] }
261  | { kind: 'error'; code: 'not_found' | 'ambiguous_session' | 'usage'; message: string };
262
263export type ScopeInput = {
264  ref?: string; // --session
265  all?: boolean; // --all
266  env?: string; // CLAUDE_CODE_SESSION_ID
267  cwd: string;
268  home: string;
269  sessions: SessionInfo[];
270};
271
272export const SESSION_ID = /^[0-9a-f-]+$/i;
273export const LIST_CAP = 20;
274
275const newest = (a: SessionInfo, b: SessionInfo) => ((a.updated ?? '') < (b.updated ?? '') ? 1 : (a.updated ?? '') > (b.updated ?? '') ? -1 : 0);
276const trim = (p: string) => (p.length > 1 ? p.replace(/\/+$/, '') : p);
277
278// The scoping rules, first match wins: a flag, then the Claude Code session
279// kref runs inside, then the newest session that ran in exactly this folder
280// (never ~ or /), then a list of the newest sessions at or under it.
281export function scope(input: ScopeInput): Scope {
282  const sessions = [...input.sessions].sort(newest);
283  if (input.all) return { kind: 'all', reason: '--all' };
284  if (input.ref !== undefined) {
285    const ref = input.ref.trim();
286    if (ref === 'last') {
287      return sessions[0]
288        ? { kind: 'session', reason: '--session', id: sessions[0].id, more: 0 }
289        : { kind: 'error', code: 'not_found', message: 'the ledger has no sessions' };
290    }
291    if (!SESSION_ID.test(ref) || ref.length < 8) {
292      return { kind: 'error', code: 'usage', message: `--session takes a session ID, a prefix of 8 or more of its characters, or last` };
293    }
294    const hits = sessions.filter((s) => s.id.toLowerCase().startsWith(ref.toLowerCase()));
295    if (hits.length === 0) return { kind: 'error', code: 'not_found', message: `no session starts with ${ref}` };
296    if (hits.length > 1) return { kind: 'error', code: 'ambiguous_session', message: `${hits.length} sessions start with ${ref}` };
297    return { kind: 'session', reason: '--session', id: hits[0].id, more: 0 };
298  }
299  if (input.env && SESSION_ID.test(input.env)) {
300    return { kind: 'session', reason: 'CLAUDE_CODE_SESSION_ID', id: input.env, more: 0 };
301  }
302  const cwd = trim(input.cwd);
303  if (cwd !== trim(input.home) && cwd !== '/') {
304    const here = sessions.filter((s) => s.cwd !== undefined && trim(s.cwd) === cwd);
305    if (here.length > 0) return { kind: 'session', reason: 'cwd', id: here[0].id, more: here.length - 1 };
306  }
307  return { kind: 'sessions', reason: 'below-cwd', sessions: below(sessions, cwd).slice(0, LIST_CAP) };
308}
309
310// The sessions that ran at or under a folder, newest first.
311export function below(sessions: SessionInfo[], folder: string): SessionInfo[] {
312  const cwd = trim(folder);
313  return [...sessions].sort(newest).filter((s) => {
314    if (s.cwd === undefined) return false;
315    const c = trim(s.cwd);
316    return cwd === '/' || c === cwd || c.startsWith(`${cwd}/`);
317  });
318}
319
320// A literal, case-insensitive match on a code's title, body and question
321// options. No regex, so a pattern can't run away.
322export function search(items: Item[], text: string): Item[] {
323  const needle = text.toLowerCase();
324  const hit = (s: string) => s.toLowerCase().includes(needle);
325  return items.filter((i) => hit(i.title) || hit(i.summary) || i.options.some((o) => hit(o.text)));
326}
327
hooks/session.ts 90 lines
1// session.ts: how the session record changes, katharsis-data/sessions/<id>.json.
2// The engine loads one hooks module per plugin, takes one hook per event from
3// it, and never lets $ cross an import, so the hooks that write the record
4// live where their events already are: register.ts touches it on each
5// prompt, and drawer.tsx adds the transcript at Stop and the title at
6// turn.complete. This file holds what they share, with no engine calls, so
7// the CLI can import it under node.
8//
9// The record is created on the session's first Katharsis prompt and touched
10// on every one after, given the transcript's path at each Stop, and given a
11// title by a fork of the conversation after turn 3 and every 15 turns after
12// that. A session outside Katharsis gets no record.
13
14import type { Release, SessionRecord } from './ledger.ts';
15
16// The outputStyle values that mean Katharsis is on, by bare name and by the
17// plugin-qualified name the style picker writes.
18export const KATHARSIS_STYLES = new Set([
19  'Katharsis',
20  'katharsis:Katharsis',
21  'Katharsis coding',
22  'katharsis:Katharsis coding',
23]);
24
25export const TITLE_PROMPT =
26  'Name the work this session is doing in 3 to 6 words, as a gerund phrase such as "Researching the Katharsis CLI". Reply with the phrase alone: no classification, no punctuation at the end, no other text.';
27
28// The fork's reply as a title, or '' when it is not one: the first line,
29// without quotes, markdown or a closing period, at most 8 words.
30export function cleanTitle(text: string): string {
31  const line = text.split('\n').map((l) => l.trim()).find((l) => l) ?? '';
32  const t = line.replace(/^[#>*_`"'\s]+|[*_`"'.\s]+$/g, '').trim();
33  const words = t.split(/\s+/).filter(Boolean).length;
34  return words >= 1 && words <= 8 && t.length <= 80 ? t : '';
35}
36
37// Whether this turn asks the fork for a title: from turn 3 until one lands,
38// then every 15 turns so the title follows the work when it drifts.
39export function wantsTitle(rec: SessionRecord, turns: number): boolean {
40  return turns >= 3 && (!rec.title || (turns - 3) % 15 === 0);
41}
42
43// The running plugin's version from its plugin.json, and the commit Claude
44// Code installed it from when installed_plugins.json has an entry at this
45// root. A --plugin-dir checkout has no entry, so it gets the version alone.
46export function releaseOf(root: string, manifest: string | null, installed: string | null): Release | null {
47  let version = '';
48  try {
49    version = String(JSON.parse(manifest ?? '{}').version ?? '');
50  } catch {
51    return null;
52  }
53  if (!version) return null;
54  try {
55    const plugins = JSON.parse(installed ?? '{}').plugins ?? {};
56    const entries = Object.values(plugins).flat() as { installPath?: string; gitCommitSha?: string }[];
57    const commit = entries.find((p) => p.installPath === root)?.gitCommitSha;
58    if (commit) return { version, commit };
59  } catch {
60    // no install record to read the commit from
61  }
62  return { version };
63}
64
65// The record after a prompt: created when there was none, then the time, the
66// handoff parent, and a new release entry when a reinstall changed the plugin
67// mid-session. cwd and branch count only on creation.
68export function touched(
69  old: SessionRecord | null,
70  f: { id: string; now: string; cwd: string; branch: string; parent: string; release: Release | null },
71): SessionRecord {
72  const rec: SessionRecord = old
73    ? { ...old, katharsis: [...old.katharsis] }
74    : { id: f.id, cwd: f.cwd, ...(f.branch ? { branch: f.branch } : {}), started: f.now, updated: f.now, katharsis: [] };
75  rec.updated = f.now;
76  if (f.parent) rec.parent = f.parent;
77  const last = rec.katharsis[rec.katharsis.length - 1];
78  if (f.release && (last?.version !== f.release.version || last?.commit !== f.release.commit)) rec.katharsis.push(f.release);
79  return rec;
80}
81
82// The record after a Stop, or null when nothing changed. A path is marked
83// seen once the file exists and stays seen after cleanup deletes it, so a
84// session run with --no-session-persistence keeps a path never seen.
85export function withTranscript(rec: SessionRecord, path: string, exists: boolean): SessionRecord | null {
86  const seen = Boolean(rec.transcriptSeen) || exists;
87  if (rec.transcript === path && Boolean(rec.transcriptSeen) === seen) return null;
88  return { ...rec, transcript: path, ...(seen ? { transcriptSeen: true } : {}) };
89}
90
hooks/suggest.ts 88 lines
1// suggest.ts: the autonomy level a person's own answers support. Like
2// ledger.ts, it holds no JSX and no engine calls, and its imports spell their
3// extensions.
4//
5// At guided, the drawer suggests standard once the person has answered at
6// least SUGGEST_MIN questions that carried a recommendation and took it on at
7// least SUGGEST_RATE of them. A count gates it rather than time since
8// install: a month of light use holds too few answers to judge from, and a
9// week of heavy use holds plenty. The rate was set against the one history on
10// hand, 94 of 127 answers taken (74%), and 80% would never have suggested
11// standard to the person the level was built for.
12
13import { itemsOf, threadTexts, type Io } from './ledger.ts';
14
15export const SUGGEST_MIN = 50;
16export const SUGGEST_RATE = 0.7;
17
18export type Agreement = { answered: number; took: number };
19
20// The option letter a recommendation line opens with: "a - why", "**b**. why".
21// The letter must stand alone before a separator, so "A cleaner fix - b" and
22// "I'd take b" name no option.
23export function recLetter(rec: string): string {
24  return rec.trim().match(/^\**([a-z])\**(?=\s*(?:[-–—.):,]|$))/i)?.[1]?.toLowerCase() ?? '';
25}
26
27// The session and every ancestor its chain file names, newest first. Unlike
28// thread() it has no cap of 20, so every session of a long chain sees the
29// chain's questions and keys them alike.
30async function chainOf(io: Io, data: string, sid: string): Promise<string[]> {
31  const ids = [sid];
32  for (;;) {
33    const next = (await io.read(`${data}/ledger/chains/${ids[ids.length - 1]}`))?.trim() ?? '';
34    if (!/^[\w-]+$/.test(next) || ids.includes(next)) return ids;
35    ids.push(next);
36  }
37}
38
39// Every answered question that carried a recommendation, across every
40// session's answers file, and how many took it. A question is its code in
41// one handoff chain's numbering space, keyed by the chain's oldest session,
42// and its latest answer by stamp is the one that counts, whichever session of
43// the chain gave it, and on equal stamps the later session's answer wins.
44// Two sessions punted from one parent share that numbering space, so their
45// two Q8s count as one question: an undercount, never an overcount. A
46// dismissed question (x) counts for neither side; the person's own
47// answer, a prose answer, or another letter counts as answered and not taken.
48export async function agreement(io: Io, data: string): Promise<Agreement> {
49  const latest = new Map<string, { ts: string; depth: number; letter: string; own: boolean; rec: string }>();
50  for (const f of await io.list(`${data}/answers`)) {
51    if (f.kind !== 'file' || !f.name.endsWith('.jsonl')) continue;
52    const text = await io.read(`${data}/answers/${f.name}`);
53    if (text === null) continue;
54    const rows: { ts: string; code: string; letter: string; own: boolean }[] = [];
55    for (const line of text.split('\n')) {
56      try {
57        const r = JSON.parse(line) as Record<string, unknown>;
58        if (typeof r.code === 'string') rows.push({ ts: String(r.ts ?? ''), code: r.code.toUpperCase(), letter: String(r.letter ?? '').toLowerCase(), own: r.how === 'own' });
59      } catch {
60        continue; // a blank or partial line
61      }
62    }
63    if (rows.length === 0) continue;
64    const ids = await chainOf(io, data, f.name.slice(0, -'.jsonl'.length));
65    const root = ids[ids.length - 1];
66    const depth = ids.length - 1;
67    const items = new Map(itemsOf(await threadTexts(io, `${data}/ledger`, ids, true)).map((i) => [i.code.toUpperCase(), i]));
68    for (const r of rows) {
69      const q = items.get(r.code);
70      // A recommendation must name one of the question's options, so "I'd
71      // take b" reads as no recommendation rather than as option i.
72      const rec = q ? recLetter(q.rec) : '';
73      const offered = !q || q.options.length === 0 || q.options.some((o) => o.key.toLowerCase() === rec);
74      const key = `${root}:${r.code}`;
75      const old = latest.get(key);
76      const later = !old || r.ts > old.ts || (r.ts === old.ts && depth >= old.depth);
77      if (q?.prefix === 'Q' && later) latest.set(key, { ts: r.ts, depth, letter: r.letter, own: r.own, rec: offered ? rec : '' });
78    }
79  }
80  const counted = [...latest.values()].filter((a) => a.rec && a.letter !== 'x');
81  return { answered: counted.length, took: counted.filter((a) => a.letter === a.rec && !a.own).length };
82}
83
84// Whether the answers support moving from guided to standard.
85export function suggestsStandard(a: Agreement): boolean {
86  return a.answered >= SUGGEST_MIN && a.took / a.answered >= SUGGEST_RATE;
87}
88
types/index.d.ts 18 lines
1// The values Katharsis keeps in the session's state, which outlives a reload
2// of the plugin's code. A change in the drawer's settings view reloads it.
3export type KatharsisView = 'short' | 'full' | 'current' | 'settings';
4export type KatharsisShow = 'all' | 'open' | 'resolved';
5
6declare module 'claude-code' {
7  interface PluginState {
8    katharsis: {
9      // The drawer's view, so an open drawer comes back on the same one.
10      view: KatharsisView;
11      // The last finished reply's text, which tells the latest reply block apart.
12      lastAnswer: string;
13      // The drawer's Status, a standing preference.
14      show: KatharsisShow;
15    };
16  }
17}
18