SLOPSHOPPER

abofles-guide

Abo Fles guide and pane: the ๐Ÿงญ next line above the prompt box, and a pane with the guide, resume, spawns and an overrides editor (Save writes the CLAUDE.mdโ€ฆ

panebandcommandtoaststatusprocess
โ˜… 3v0.4.0MITupdated 2026-10-24Sajadh92/claude-plugins/plugins/abofles-guide
A shopper browsing a rack in a slop shop
Preview ยท a replayed session in a sandbox
claude ยท ~/work/app ยท abofles-guide
โ”‚ โ”ƒ Abo Fles โœ• โ€บ fix the failing auth test and add an audit log call โ”‚ โ”ƒ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ โ”ƒ โ”‚ fold:overrides โ”‚ โบ Read(src/auth.ts) โ”‚ โ”ƒ โ”‚ โ”‚ โŽฟ Read 6 lines โ”‚ โ”ƒ โ”‚ Pane data unreadable โ€” update both โ”‚ โบ Update(src/auth.ts) โ”‚ โ”ƒ โ”‚ abofles and abofles-guide โ”‚ โŽฟ Added 2 lines, removed 1 line โ”‚ โ”ƒ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โบ Bash(bun test) โ”‚ โŽฟ 3 pass, 1 fail โ”‚ โ”‚ โ— Done. refresh now rejects expired claims and logs an audit event. โ”‚ โ”‚ โœป Worked for 42s ยท done 4:20 PM โ”‚ โ”‚ โ€บ /abofles-pane โ”‚ โŽฟ abofles-guide: Abo Fles pane opened. โ”‚ โ”‚ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ€บ ? for shortcuts

Draws

Pane ยท Abo Fles
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ fold:overrides โ”‚ โ”‚ โ”‚ โ”‚ Pane data unreadable โ€” update both abofles and โ”‚ โ”‚ abofles-guide โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
README

abofles-guide

A band above the prompt box with the Abo Fles ๐Ÿงญ next line: what to do now, by priority, computed by the abofles plugin's hooks after every spawn, receipt and prompt (open FAIL / ATTENTION ยท judged question unasked ยท owner decisions open ยท partial/low reply not escalated ยท background agents running ยท context or memo hygiene ยท agent budget nearly out ยท the memo's Next). The same line is in every receipt (- \next\ โ†’ ๐Ÿงญ โ€ฆ) and resume block.

It draws a band with buttons and the pane below. It never spawns or blocks, and it never settles an item on your word: it runs no settle command. It runs two commands, both published by the abofles hooks: Undo (Claude's own last resolve) and the overrides editor's Save (scripts/overrides.py, which edits the ## abofles overrides block).

  • Use puts the top item's fill text in the prompt box as the next prompt (appended after a draft you already typed) and takes the band down. If the prompt box is not open it says so and keeps the band: use Copy.
  • Re-check (a ๐Ÿ”ด / ๐ŸŸ  / ๐ŸŸก top item that carries a re-check prompt) puts a verify-then-resolve prompt in the prompt box the same way: Claude checks the item, and resolves it only with evidence.
  • After Claude resolves an item the band shrinks to โœ“ resolved: โ€ฆ with Undo and Hide. Undo reopens Claude's last resolve (it runs the argv from guide.last_resolved in the project root and toasts the first line of its output) and stays offered until the next turn ends; the row does not depend on anything but that field. While it runs (up to 30 s) Undo is gone, so a second press cannot start a second run. Hide takes that row down (keyed by its timestamp; a newer resolve draws again).
  • Reopen by hand: /abofles:resume --reopen <n> (an owner decision), /abofles:status --unresolve <id> (a FAIL or an escalation). Exit code 3 from Undo toasts already open; any other failure toasts undo failed with the first line of the error and keeps the row, so Undo can be pressed again. Exit 0 and exit 3 clear the row.
  • Memo (when the context is within 50K of its next mark, or past the last one) puts /abofles:memo in the prompt box.
  • Copy puts the Use text on the clipboard.
  • Hide takes the band down. It is keyed on the ids of the items shown (plus the context mark when the memo is due), not on the emojis in the line: the band stays down while the same items are shown, even if their wording changes, and comes back when an item appears or goes, or when a newly crossed context mark makes the memo due again.

When nothing is open (every item โœ…) the band is hidden, except when the memo is due: then it shows just the meter and Memo. A dim second line, the meter, shows ctx 412K / 500K ยท task 3 spawns ยท $0.41 ยท budget 2 left ยท suggest Opus 5.5 ยท Medium (parts without data omitted). A toast fires once for each ๐Ÿ”ด item that was not toasted before (by item id), not on every refresh while the top stays red. Fields of the state file with the wrong type are ignored (a bad item is dropped, a bad task or ctx left out) rather than taking the band away. The โœ… suggestion in the band follows the memo's Now, which the abofles hook rewrites after every receipt. It needs abofles installed; without it the band stays empty.

The Abo Fles pane

A pane beside the transcript (the app docks it on the right) with one card per thing Abo Fles keeps for the session. The hooks write its data into the session's state file (pane) and this mod only draws it, in the look of the app's own side panels (Context, Changes, Environment): each card's header is its title with a chevron (โ€บ folded, โŒ„ open; a click folds it, and the folds are remembered across sessions) and a short summary at the right; numbers are label/value rows. In the pane every text wraps (nothing is cut, markdown marks are dropped); a long list shows its first rows and Show all N.

  • Guide: the ๐Ÿงญ items (the top one in full, two more, then Show all), the numbers as rows (Context, Task, Budget, Suggest) and the same buttons as the band (Use, Re-check, Memo, Copy, Hide, and Undo after Claude's resolve). A hidden card shows a Show button that brings it back; Memo is the primary button once nothing else is open. With Guide place = pane (the default) the band above the prompt box is empty while the pane is up.
  • Resume: Session, Memo and Away as rows, then Now, Next, Needs you (the first three, then Show all), Left, and Last receipts โ€” one short row each (1 Spawn ยท $0.28 ยท Saved 46%, the time at the right; Show details opens their done / check / open). What /abofles:resume prints (Resume place = pane, the default).
  • Spawns: Saved, Tokens and Open FAIL as rows; live agents (โ— side ยท ask, the start time at the right, the model under it); the history newest first, five rows then Show all: side ยท ask with the verdict (PASS / FAIL) at the right and a dim line under it (done ยท medium ยท sonnetยทmedium ยท 80K ยท $0.40 ยท saved 50%). The summary is 1 live ยท 3 spawns ยท $0.41. What /abofles:spawns prints (Spawns place = pane, the default).
  • Overrides: a short card โ€” a row per value a file sets (Receipt ยท short ยท this project), the count of the other lines โ€” and Edit overrides, which turns the pane into the editor page below. Always drawn.

Guide place, Resume place and Spawns place (pane | band / output) put each card in the pane or keep today's view; the cards that are not placed in the pane are not drawn.

Opening: the pane opens by itself once per session when the state has something placed in it, unless you closed it by hand (that is remembered across sessions, as is being open). Unasked, the app places it from 144 terminal columns, and from 110 once you have opened it yourself; on a narrower window it waits, and the band shows one row, Abo Fles ยท <top item>, with a Pane button that opens it at any width. /abofles-pane (the command this mod registers) opens the pane, or closes it when it is up. /abofles:pane is the abofles plugin's entry that points to it (the mod answers it too when the app routes it here); without this mod it prints the resume block and the spawn history as text.

How the abofles hook knows this mod is on (it then places the cards in the pane, else in the band/chat): the first abofles-guide@โ€ฆ key of ~/.claude/settings.json enabledPlugins decides (false = off); with no such key, a abofles-guide folder in ~/.claude/plugins/cache/*/ or in a folder of CLAUDE_CODE_PLUGIN_DIRS (env) turns it on.

The overrides editor

Edit overrides turns the pane into a page of its own (โ€น Back returns to the cards; the draft is kept); its groups are cards like the main page's. It edits the simple keys of the ## abofles overrides block (the table is in the abofles README):

  • Save to: This project (the project's CLAUDE.md, or .claude/CLAUDE.md when that is the file holding the block) or All projects (~/.claude/CLAUDE.md); the file is named under it. The project file wins over the user file when both set a key.
  • The keys in folding groups: Session (Main session, Session cap, Context marks, Break, Pace), Agents (Agents, Parallel, Agent budgets, Review gate, Questions), Output (Receipt, Guide, Resume, Language), Where it shows (Guide place, Resume place, Spawns place); a key the table adds later goes to More. Each group's summary says how many keys a file sets, or how many are edited.
  • Each key: a list for the keys with a fixed set of values (its first entry, default (<value>), removes the line), an input for numbers, texts and lists (the default as its placeholder), a dim one-line help, and a badge only when a file sets it (this project, all projects) or it is edited (edited). Agents and Receipt also offer custom value, which opens an input for N agents or savings N.
  • Other overrides (folded while the chosen file has none): a multi-line input for the other forms (cell, cap, tier, Reviewers, Workflow, Review lines) of the chosen file, one per line; lines of the other file are listed under it and edited there. Changing Save to drops the typed lines (they belong to one file).
  • Edits are kept as a draft; the page header and the main page's card say N unsaved.
  • Save runs the abofles plugin's scripts/overrides.py (the argv the hook publishes as pane.cmd.overrides) with the changes on stdin: it edits the block in place, adds new keys, removes the ones set to the default, and keeps everything else in the file as it was. It toasts Saved to <file>, the fields show the new values and the draft is cleared. A refused value (exit 2) toasts the first line of the error and keeps the draft.
  • Ask Claude to apply puts Apply in <file> \## abofles overrides\: - Key = value โ€ฆ (only the changed keys) in the prompt box instead, so Claude makes the edit. Discard edits (shown while there are edits) clears the draft.
  • If the file changed while you were editing (exit 3), Save toasts CLAUDE.md changed while saving โ€” reload the pane and save again and keeps the draft.

Commands the pane runs (Undo, Save) come from the state file and run only in the shape the abofles hook writes them: bash, the abofles plugin's scripts/py launcher, then memo.py, status.py or overrides.py from that same folder; anything else is dropped. They need bash on PATH (Git Bash on Windows), as the abofles hooks do.

Install: /plugin install abofles-guide@sajadh92 (after /plugin marketplace add <this repo>), or claude --plugin-dir plugins/abofles-guide. Validate: claude plugin validate plugins/abofles-guide. Turn the line off everywhere with - Guide = off in the project's ## abofles overrides.

Source 5 files
hooks/register.tsx 151 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import type { Guide } from '../types'
4import { renderPane } from './pane'
5import {
6  anyPane,
7  autoOpen,
8  closePane,
9  getDismissedTs,
10  getGuide,
11  getHiddenKey,
12  getPane,
13  getPaneOpen,
14  getRunning,
15  guideButtons,
16  hideKeyOf,
17  loadFolds,
18  openPane,
19  paneIsPlaced,
20  plain,
21  refresh,
22  setPaneOpen,
23  undoRow,
24  viewOf,
25} from './shared'
26
27// The abofles hooks (Python) compute the guide line after every spawn, receipt and prompt and keep it in the
28// session's state file as `guide.line`, next to `pane`, the data of the Abo Fles pane. This mod only draws them: the
29// band above the prompt, the pane (pane.tsx), and a toast when a new red item appears. It never spawns, blocks or
30// writes, and it never settles an item itself: Claude resolves, after a Re-check. The one command it runs is Undo,
31// the argv the hook publishes as `guide.last_resolved`. The state, its cleaning and the guide's buttons: shared.tsx.
32
33// /abofles:pane (the abofles plugin's own command file is the fallback when this mod is off) and its alias /abofles-pane:
34// open the pane, or close it when it is up. The reply is one short line.
35async function togglePane($: EngineInterface) {
36  if (await paneIsPlaced($)) {
37    await closePane($)
38    return { text: 'Abo Fles pane closed.' }
39  }
40  const r = await openPane($)
41  return { text: r.isPlaced ? 'Abo Fles pane opened.' : `Abo Fles pane is open but waits for room (${r.reason ?? 'no surface'}).` }
42}
43
44// `text` cut at a word end to at most `n` characters (code points), with โ€ฆ when cut: the opener row stays one line.
45function words(text: string, n: number): string {
46  const cs = Array.from(plain(text))
47  if (cs.length <= n) return cs.join('')
48  const cut = cs.slice(0, n - 1).join('')
49  const at = cut.lastIndexOf(' ')
50  return `${at > n / 2 ? cut.slice(0, at) : cut}โ€ฆ`
51}
52
53export const register: Register = on => {
54  on('session.start', async ($, e, next) => {
55    $.ui.status(undefined) // an entry an earlier build of this mod pinned: the band is enough
56    try {
57      await $.command.register({ name: 'abofles-pane', description: 'Open or close the Abo Fles pane (guide, resume, spawns, overrides)' })
58    } catch {
59      // the command file of the abofles plugin still answers /abofles:pane
60    }
61    await loadFolds($)
62    await refresh($)
63    await autoOpen($)
64    return next(e)
65  })
66
67  on('turn.complete', async ($, e, next) => {
68    const result = await next(e)
69    await refresh($)
70    return result
71  })
72
73  on('classic.Stop', async ($, e, next) => {
74    const result = await next(e)
75    await refresh($)
76    return result
77  }).catch(($, e, next) => next(e)) // a failed refresh must not change the Stop result
78
79  // The pane's live spawns: a subagent ended, or a tool (the Agent tool's spawn among them) ran.
80  on('classic.SubagentStop', async ($, e, next) => {
81    const result = await next(e)
82    await refresh($)
83    await autoOpen($)
84    return result
85  }).catch(($, e, next) => next(e))
86
87  on('classic.PostToolUse', async ($, e, next) => {
88    const result = await next(e)
89    await refresh($)
90    await autoOpen($)
91    return result
92  }).catch(($, e, next) => next(e))
93
94  // The person's command, by the name the engine gives a plugin's command file (`<plugin>:<name>`) and by the alias this mod registers.
95  on('command.run', { command: 'abofles:pane' }, $ => togglePane($)).catch(($, e, next) => next(e)) // a failure leaves the command file to answer
96  on('command.run', { command: 'abofles-pane' }, $ => togglePane($))
97
98  // The pane's id is 'abofles' (PANE_ID in shared.tsx), spelled out in the matchers so the scan reads them.
99  // Closed by the person (the mark or the key): it stays closed in the next session too.
100  on('ui.close', { id: 'abofles' }, async ($, e, next) => {
101    const result = await next(e)
102    if (e.origin.kind === 'person') await setPaneOpen($, false)
103    return result
104  }).catch(($, e, next) => next(e))
105
106  on('ui.render', { component: 'Pane', requestId: 'abofles' }, ($, e) => renderPane($, e))
107
108  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
109    if (e.props.hasSurvey) return next(e)
110    const g = await getGuide($)
111    const p = await getPane($)
112    const open = await getPaneOpen($) // a change redraws the band: the Pane button and the opener follow the pane
113    // Where the pane has something to show but is not drawn (a narrow terminal, or closed): the band is its opener.
114    const wants = anyPane(p)
115    const placed = wants ? await paneIsPlaced($) : false
116    const ui = $.ui.resolve(e)
117    const { Box, Button, Text } = ui
118    const openerRow = (g: Guide | null) => {
119      const top = g?.items?.[0]
120      const what = top ? `${top.p} ${words(top.text, 70)}` : g ? words(g.line.replace(/^\s*๐Ÿงญ\s*/, ''), 70) : ''
121      return (
122        <Box flexDirection="row" flexWrap="wrap" gap={1}>
123          <Text>{what ? `Abo Fles ยท ${what}` : 'Abo Fles'}</Text>
124          <Button key="pane" label="Pane" variant="secondary" onPress={() => openPane($)} />
125        </Box>
126      )
127    }
128    // The guide lives in the pane: the band stays empty while the pane is up, else one row that opens it.
129    if (p !== null && p.places.guide === 'pane') return placed ? next(e) : openerRow(g)
130    // Claude's last resolve (published by the hook until the Stop of the turn after it), unless the person hid that row.
131    const busy = (await getRunning($)) === true
132    const last = g?.last_resolved ?? null
133    if (g !== null && last !== null && last.ts !== (await getDismissedTs($))) {
134      return undoRow($, ui, g, last, busy)
135    }
136    // Hidden, or nothing open: the band is quiet, save for the opener of a pane that is not drawn (and was not closed by hand).
137    const quiet = () => (wants && !placed && open !== false ? openerRow(g) : next(e))
138    if (g === null || hideKeyOf(g) === (await getHiddenKey($))) return quiet()
139    const v = viewOf(g)
140    if (v.done && !v.memo) return quiet()
141    const paneButton = p !== null ? <Button key="pane" label="Pane" variant="secondary" onPress={() => openPane($)} /> : null
142    return (
143      <Box flexDirection="column">
144        {v.done ? null : <Text>{g.line.replace(/`/g, '')}</Text>}
145        {v.meter ? <Text dimColor>{v.meter}</Text> : null}
146        {guideButtons($, ui, g, v, false, paneButton)}
147      </Box>
148    )
149  })
150}
151
hooks/pane.tsx 261 lines
1import type { EngineInterface } from 'claude-code'
2
3import type { Guide, Pane, PaneLive, PaneRow, PaneSpawns } from '../types'
4import { overridesCard, overridesPage } from './editor'
5import { card, getDismissedTs, getFolds, getGuide, getHiddenKey, getPane, getPaneView, getRunning, guideButtons, hideKeyOf, isOpen, kv, limited, moreButton, plain, setFold, showGuide, undoRow, viewOf } from './shared'
6import type { Folds, RenderEvent, Ui } from './shared'
7
8// The "Abo Fles" pane: one card per thing the abofles hooks placed there (`pane.places`): Guide, Resume, Spawns, and always a
9// short Overrides card whose Edit button turns the pane into the overrides editor (editor.tsx). Native elements only; every text
10// wraps (nothing is cut), long lists show their first rows and a "Show all", and every card folds. The buttons are the band's.
11
12export const fmtTokens = (n: number): string => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}K` : String(n))
13export const fmtUsd = (x: number): string => (x > 0 && x < 0.005 ? '<$0.01' : `$${x.toFixed(2)}`)
14
15// `14:05`: when a live spawn started (its `ts`, epoch seconds, in local time), or `running` when the hook gave no start. A start time does not go stale between redraws.
16export function fmtStart(ts: number | null): string {
17  if (ts === null) return 'running'
18  const d = new Date(ts > 1e11 ? ts : ts * 1000)
19  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
20}
21
22const modelOf = (model: string, effort: string): string => (effort ? `${model || '?'}ยท${effort}` : model || '?')
23
24// The theme color of a priority emoji: red for ๐Ÿ”ด, amber for ๐ŸŸ ๐ŸŸก, green for โœ…; none for the rest.
25const toneOf = (p: string | undefined): string | undefined => (p === '๐Ÿ”ด' ? 'error' : p === '๐ŸŸ ' || p === '๐ŸŸก' ? 'warning' : p === 'โœ…' ? 'success' : undefined)
26
27// A small dim heading inside a card ("Needs you").
28function heading(ui: Ui, text: string) {
29  const { Text } = ui
30  return (
31    <Text size="caption" dimColor>
32      {text}
33    </Text>
34  )
35}
36
37// One section of a card: its heading, then its rows.
38function section(ui: Ui, title: string, rows: (JSX.Element | null)[]) {
39  const { Box } = ui
40  return (
41    <Box flexDirection="column">
42      {heading(ui, title)}
43      {rows}
44    </Box>
45  )
46}
47
48// A row with text that wraps on the left and a short aside (a time, a verdict) held at the right.
49function split(ui: Ui, left: JSX.Element, right: JSX.Element | null) {
50  const { Box } = ui
51  return (
52    <Box flexDirection="row" justifyContent="space-between" columnGap={1}>
53      <Box flexShrink={1}>{left}</Box>
54      {right}
55    </Box>
56  )
57}
58
59// ---- Guide
60
61// The guide's numbers as rows: context, the task's spawns and cost, its budget, the main-session suggestion.
62function meterRows(ui: Ui, g: Guide): JSX.Element[] {
63  const rows: JSX.Element[] = []
64  if (g.ctx) rows.push(kv(ui, 'Context', g.ctx.mark == null ? `${Math.round(g.ctx.tokens / 1000)}K` : `${Math.round(g.ctx.tokens / 1000)}K / ${g.ctx.mark}K`))
65  if (g.task) {
66    rows.push(kv(ui, 'Task', `${g.task.spawns} spawn${g.task.spawns === 1 ? '' : 's'} ยท $${g.task.usd.toFixed(2)}`))
67    if (g.task.left != null) rows.push(kv(ui, 'Budget', `${g.task.left} left`))
68  }
69  const main = g.main?.replace(/^\s*main:\s*/i, '').replace(/^suggest\s+/i, '').trim()
70  if (main) rows.push(kv(ui, 'Suggest', main))
71  return rows
72}
73
74function guideCard($: EngineInterface, ui: Ui, g: Guide, hidden: boolean, last: Guide['last_resolved'], busy: boolean, folds: Folds) {
75  const { Box, Button, Text } = ui
76  const v = viewOf(g)
77  const open = v.items.filter(i => i.p !== 'โœ…').length
78  const summary = v.done ? 'nothing open' : v.items.length > 0 ? `${open} open` : null
79  const rows: (JSX.Element | null)[] = []
80  if (last) rows.push(undoRow($, ui, g, last, busy, true))
81  if (hidden) {
82    rows.push(
83      <Box flexDirection="row" flexWrap="wrap" gap={1}>
84        <Text dimColor>Hidden until the list changes.</Text>
85        <Button key="show" label="Show" variant="secondary" onPress={() => showGuide($)} />
86      </Box>,
87    )
88  } else {
89    if (v.items.length > 0) {
90      // the top item in full, the others dim under it; each wraps
91      const [top, ...rest] = v.items
92      rows.push(
93        <Box flexDirection="column">
94          <Text>{`${top.p} ${plain(top.text)}`}</Text>
95          {limited($, ui, folds, 'guide', rest.map(it => <Text dimColor>{`${it.p} ${plain(it.text)}`}</Text>), 2)}
96        </Box>,
97      )
98    } else {
99      rows.push(<Text>{plain(g.line)}</Text>)
100    }
101    const meter = meterRows(ui, g)
102    if (meter.length > 0) rows.push(<Box flexDirection="column">{meter}</Box>)
103    if (!v.done || v.memo) rows.push(guideButtons($, ui, g, v, true))
104  }
105  return card($, ui, { id: 'guide', title: 'Guide', summary: hidden ? 'hidden' : summary, tone: hidden ? undefined : toneOf(v.top?.p), folds }, <Box flexDirection="column" rowGap={1}>{rows}</Box>)
106}
107
108// ---- Resume
109
110// The head line's parts the card shows as rows: `๐Ÿ“ Resume ยท memo 2026-10-21 17:40 ยท away 2 days ยท session 3f7416dd ยท now written โ€ฆ`.
111export function headParts(head: string): { memo: string | null; away: string | null; session: string | null } {
112  const parts = plain(head).split(' ยท ')
113  const find = (word: string) => parts.find(x => x.startsWith(`${word} `))?.slice(word.length + 1).trim() ?? null
114  return { memo: find('memo'), away: find('away'), session: find('session') }
115}
116
117// A receipt line of the journal as one short row: `10-22 07:19 ยท 1 Spawn ยท 319K Tokens ยท $0.28 ยท Saved 46% ($0.24) vs Opus 5.5 ยท done: โ€ฆ`
118// gives the time and `1 Spawn ยท $0.28 ยท Saved 46%`; `done`, `check` and `open` are its details. A line of another shape is kept whole.
119export function receiptOf(line: string): { time: string | null; head: string; details: string[] } {
120  const parts = plain(line).split(' ยท ')
121  const time = /^\d\d-\d\d \d\d:\d\d$/.test(parts[0] ?? '') ? (parts.shift() as string) : null
122  const at = parts.findIndex(x => /^[a-z]+:\s/i.test(x))
123  const stats = (at < 0 ? parts : parts.slice(0, at)).filter(x => !/Tokens$/.test(x)).map(x => x.replace(/\s*\(\$[\d.]+\)\s*vs\s+.*$/, '').replace(/\s+vs\s+.*$/, ''))
124  const details = at < 0 ? [] : parts.slice(at)
125  return stats.length > 0 ? { time, head: stats.join(' ยท '), details } : { time, head: details.shift() ?? '', details }
126}
127
128// A list row: the mark (`โ€ข`, `3.`) in a Text of its own beside the item, so a right-to-left item wraps and aligns by itself.
129function marked(ui: Ui, mark: string, text: string) {
130  const { Box, Text } = ui
131  return (
132    <Box flexDirection="row" alignItems="flex-start" columnGap={1}>
133      <Text dimColor>{mark}</Text>
134      <Box flexShrink={1}>
135        <Text>{plain(text)}</Text>
136      </Box>
137    </Box>
138  )
139}
140
141// The rows of a list: the item alone, or with a bullet when there are several.
142function listRows(ui: Ui, texts: string[]): JSX.Element[] {
143  const { Text } = ui
144  return texts.map(t => (texts.length > 1 ? marked(ui, 'โ€ข', t) : <Text>{plain(t)}</Text>))
145}
146
147function receiptRows($: EngineInterface, ui: Ui, lines: string[], folds: Folds): (JSX.Element | null)[] {
148  const { Box, Button, Text } = ui
149  const shown = isOpen(folds, 'more:receipts', false)
150  const rs = lines.map(receiptOf)
151  const rows: (JSX.Element | null)[] = rs.map(r => (
152    <Box flexDirection="column">
153      {split(ui, <Text>{r.head}</Text>, r.time ? <Text size="caption" tabular dimColor>{r.time}</Text> : null)}
154      {shown ? r.details.map(d => <Text size="caption" dimColor>{d}</Text>) : null}
155    </Box>
156  ))
157  if (rs.some(r => r.details.length > 0)) rows.push(<Button key="more:receipts" label={shown ? 'Hide details' : 'Show details'} plain dimColor onPress={() => setFold($, 'more:receipts', !shown)} />)
158  return rows
159}
160
161function resumeCard($: EngineInterface, ui: Ui, r: Pane['resume'], folds: Folds) {
162  const { Box, Text } = ui
163  if (r === null) return card($, ui, { id: 'resume', title: 'Resume', folds }, <Text dimColor>No memo yet โ€” run /abofles:memo</Text>)
164  const head = headParts(r.head) // not `h`: that name is the JSX factory
165  const parts: JSX.Element[] = []
166  const facts = [head.session ? kv(ui, 'Session', head.session) : null, head.memo ? kv(ui, 'Memo', head.memo) : null, head.away ? kv(ui, 'Away', head.away) : null].filter((x): x is JSX.Element => x !== null)
167  if (facts.length > 0) parts.push(<Box flexDirection="column">{facts}</Box>)
168  if (r.now.length > 0) parts.push(section(ui, 'Now', listRows(ui, r.now)))
169  if (r.next.length > 0) parts.push(section(ui, 'Next', listRows(ui, r.next)))
170  if (r.needs.length > 0) parts.push(section(ui, 'Needs you', limited($, ui, folds, 'needs', r.needs.map((n, i) => marked(ui, `${n.n ?? i + 1}.`, n.text)))))
171  if (r.left.length > 0) parts.push(section(ui, 'Left', limited($, ui, folds, 'left', listRows(ui, r.left))))
172  if (r.last.length > 0) parts.push(section(ui, 'Last receipts', receiptRows($, ui, r.last, folds)))
173  const summary = r.needs_open > 0 ? `${r.needs_open} need you` : head.memo ? `memo ${head.memo.replace(/^\d{4}-/, '')}` : null
174  return card($, ui, { id: 'resume', title: 'Resume', summary, tone: r.needs_open > 0 ? 'warning' : undefined, folds }, <Box flexDirection="column" rowGap={1}>{parts}</Box>)
175}
176
177// ---- Spawns
178
179// The second line of a history row: `done ยท medium ยท sonnetยทmedium ยท 80K ยท $0.40 ยท saved 50%`.
180export function historyDetail(r: PaneRow): string {
181  const saved = r.tokens && r.base_usd ? `saved ${Math.round(100 * (1 - (r.usd ?? 0) / r.base_usd))}%` : 'saved -'
182  return [r.status ?? '?', r.confidence ?? '?', modelOf(r.model, r.effort), r.tokens ? fmtTokens(r.tokens) : '-', r.usd !== null ? fmtUsd(r.usd) : '-', saved].join(' ยท ')
183}
184
185// The card's summary: `2 live ยท 3 spawns ยท $0.41`.
186export function spawnsSummary(s: PaneSpawns): string {
187  const t = s.totals
188  return [s.live.length > 0 ? `${s.live.length} live` : '', `${t.spawns} spawn${t.spawns === 1 ? '' : 's'}`, fmtUsd(t.usd)].filter(Boolean).join(' ยท ')
189}
190
191// The newest history rows the card shows before its "Show all".
192const HISTORY_ROWS = 5
193
194function liveRow(ui: Ui, l: PaneLive) {
195  const { Box, Text } = ui
196  return (
197    <Box flexDirection="column">
198      {split(ui, <Text>{`โ— ${[l.side || '?', plain(l.description)].filter(Boolean).join(' ยท ')}`}</Text>, <Text size="caption" tabular dimColor>{fmtStart(l.ts)}</Text>)}
199      <Text size="caption" dimColor>{modelOf(l.model, l.effort)}</Text>
200    </Box>
201  )
202}
203
204function historyRow(ui: Ui, r: PaneRow) {
205  const { Box, Text } = ui
206  const verdict = r.verdict ? <Text weight="semibold" color={/FAIL/i.test(r.verdict) ? 'error' : 'success'}>{r.verdict}</Text> : null
207  return (
208    <Box flexDirection="column">
209      {split(ui, <Text>{[r.side || '?', plain(r.description)].filter(Boolean).join(' ยท ')}</Text>, verdict)}
210      <Text size="caption" dimColor>{historyDetail(r)}</Text>
211    </Box>
212  )
213}
214
215function spawnsCard($: EngineInterface, ui: Ui, s: PaneSpawns, folds: Folds) {
216  const { Box, Text } = ui
217  if (s.live.length === 0 && s.rows.length === 0) return card($, ui, { id: 'spawns', title: 'Spawns', folds }, <Text dimColor>No spawns yet</Text>)
218  const t = s.totals
219  const parts: JSX.Element[] = [
220    <Box flexDirection="column">
221      {kv(ui, 'Saved', `${t.saved_pct}%`, t.saved_pct > 0 ? 'success' : undefined)}
222      {t.tokens > 0 ? kv(ui, 'Tokens', fmtTokens(t.tokens)) : null}
223      {t.open_fail > 0 ? kv(ui, 'Open FAIL', String(t.open_fail), 'error') : null}
224    </Box>,
225  ]
226  if (s.live.length > 0) parts.push(section(ui, 'Live', [<Box flexDirection="column" rowGap={1}>{s.live.map(l => liveRow(ui, l))}</Box>]))
227  if (s.rows.length > 0) {
228    // newest first; the rest behind Show all
229    const newest = [...s.rows].reverse()
230    const shown = isOpen(folds, 'more:history', false) ? newest : newest.slice(0, HISTORY_ROWS)
231    parts.push(section(ui, 'History', [<Box flexDirection="column" rowGap={1}>{shown.map(r => historyRow(ui, r))}</Box>, moreButton($, ui, folds, 'history', s.rows.length, HISTORY_ROWS)]))
232  }
233  return card($, ui, { id: 'spawns', title: 'Spawns', summary: spawnsSummary(s), folds }, <Box flexDirection="column" rowGap={1}>{parts}</Box>)
234}
235
236// ---- the pane
237
238export async function renderPane($: EngineInterface, e: RenderEvent) {
239  const ui = $.ui.resolve(e)
240  const { Box } = ui
241  const p = await getPane($)
242  const folds = await getFolds($)
243  if ((await getPaneView($)) === 'overrides') return overridesPage($, ui, p, folds)
244  const g = await getGuide($)
245  const cards: JSX.Element[] = []
246  if (p?.places.guide === 'pane' && g !== null) {
247    const hidden = hideKeyOf(g) === (await getHiddenKey($))
248    const last = g.last_resolved ?? null
249    const shownLast = last !== null && last.ts !== (await getDismissedTs($)) ? last : null
250    cards.push(guideCard($, ui, g, hidden, shownLast, (await getRunning($)) === true, folds))
251  }
252  if (p?.places.resume === 'pane') cards.push(resumeCard($, ui, p.resume, folds))
253  if (p?.places.spawns === 'pane') cards.push(spawnsCard($, ui, p.spawns, folds))
254  cards.push(await overridesCard($, ui, p, folds))
255  return (
256    <Box flexDirection="column" gap={1}>
257      {cards}
258    </Box>
259  )
260}
261
hooks/shared.tsx 580 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface } from 'claude-code'
3
4import type { Guide, GuideItem, Pane, PaneLive, PaneOverrideKey, PaneOverrides, PanePlaces, PaneResume, PaneRow, PaneSpawns, PaneTotals } from '../types'
5
6// What the band (register.tsx) and the pane (pane.tsx) share: the state atoms, the cleaning of the state file's
7// `guide` and `pane`, the refresh, and the guide's actions and buttons, so both places run the same code.
8const guide = atom({ plugin: 'abofles-guide', key: 'guide' } as const, null)
9// What Hide compares: the ids of the shown items (+ the memo mark when the memo is due), see hideKeyOf.
10const hiddenKey = atom({ plugin: 'abofles-guide', key: 'hiddenKey' } as const, null)
11
12// The `ts` of the last_resolved row the person hid: that row stays down, a newer resolve (other ts) draws again.
13const dismissedTs = atom({ plugin: 'abofles-guide', key: 'dismissedTs' } as const, null)
14// Set while Undo runs its command (up to 30 s): the button is gone, a second press is ignored.
15const running = atom({ plugin: 'abofles-guide', key: 'running' } as const, false)
16// The ids of the red items already toasted: a toast fires only for a red id not in it (kept across reloads).
17const toasted = atom({ plugin: 'abofles-guide', key: 'toasted' } as const, [] as string[])
18
19// The pane payload of the state file (null: older hooks, or none yet), see cleanPane.
20const pane = atom({ plugin: 'abofles-guide', key: 'pane' } as const, null)
21// true after the person or a command opened the pane, false after it was closed; null while undecided. Also kept in $.store.
22const paneOpen = atom({ plugin: 'abofles-guide', key: 'paneOpen' } as const, null)
23// true once this session tried the unasked open: it is tried once.
24const paneAuto = atom({ plugin: 'abofles-guide', key: 'paneAuto' } as const, false)
25// The overrides editor's unsaved values by override key ('' = back to the default), plus its own entries: '@scope' (project | user),
26// '@raw' (the lines of the complex forms as typed) and '@custom:<key>' (the custom value input of Agents / Receipt is open).
27const paneDraft = atom({ plugin: 'abofles-guide', key: 'paneDraft' } as const, {} as Record<string, string>)
28// true while the editor's Save runs its command (up to 30 s): a second press is ignored.
29const paneSaving = atom({ plugin: 'abofles-guide', key: 'paneSaving' } as const, false)
30// Which page the pane shows: the cards, or the overrides editor ('overrides').
31const paneView = atom({ plugin: 'abofles-guide', key: 'paneView' } as const, 'main' as 'main' | 'overrides')
32// Open (true) or folded (false) by id: a card ('guide'), an editor group ('g:Agents'), a long list ('more:needs'). Kept in $.store too.
33const paneFolds = atom({ plugin: 'abofles-guide', key: 'paneFolds' } as const, {} as Record<string, boolean>)
34
35// The atoms are read here alone: the state library's scan wants the reference and its read in one file.
36export function getGuide($: EngineInterface) {
37  return read($, guide)
38}
39export function getHiddenKey($: EngineInterface) {
40  return read($, hiddenKey)
41}
42export function getDismissedTs($: EngineInterface) {
43  return read($, dismissedTs)
44}
45export function getRunning($: EngineInterface) {
46  return read($, running)
47}
48export function getPane($: EngineInterface) {
49  return read($, pane)
50}
51export function getPaneOpen($: EngineInterface) {
52  return read($, paneOpen)
53}
54// The overrides editor's unsaved values: read, and change by a function of the current ones.
55export function getPaneDraft($: EngineInterface) {
56  return read($, paneDraft)
57}
58export function updatePaneDraft($: EngineInterface, fn: (cur: Record<string, string>) => Record<string, string>) {
59  return update($, paneDraft, cur => fn(cur ?? {}))
60}
61
62export function getPaneSaving($: EngineInterface) {
63  return read($, paneSaving)
64}
65
66export async function getPaneView($: EngineInterface): Promise<'main' | 'overrides'> {
67  return (await read($, paneView)) === 'overrides' ? 'overrides' : 'main'
68}
69export function setPaneView($: EngineInterface, view: 'main' | 'overrides') {
70  return update($, paneView, () => view)
71}
72
73export type Folds = Record<string, boolean>
74
75export async function getFolds($: EngineInterface): Promise<Folds> {
76  return (await read($, paneFolds)) ?? {}
77}
78
79// Is the card, group or list `id` open? Absent from the map: its default.
80export const isOpen = (folds: Folds, id: string, def = true): boolean => (typeof folds[id] === 'boolean' ? folds[id] : def)
81
82// Opens or folds one id, in the atom (the pane redraws) and in $.store (the next session finds it the same).
83export async function setFold($: EngineInterface, id: string, open: boolean) {
84  let next: Folds = {}
85  await update($, paneFolds, cur => (next = { ...(cur ?? {}), [id]: open }))
86  try {
87    await $.store.set('paneFolds', next)
88  } catch {
89    // no store: the session's atom is enough
90  }
91}
92
93// What an earlier session kept (booleans by id), loaded into the atom at the session start.
94export async function loadFolds($: EngineInterface) {
95  let stored: unknown
96  try {
97    stored = await $.store.get('paneFolds')
98  } catch {
99    stored = undefined
100  }
101  const folds: Folds = {}
102  if (isObj(stored)) for (const [k, v] of Object.entries(stored)) if (typeof v === 'boolean') folds[k] = v
103  await update($, paneFolds, () => folds)
104}
105
106// Takes the editor's "saving" flag; false when a Save already holds it. releaseSave gives it back.
107export async function claimSave($: EngineInterface): Promise<boolean> {
108  let was = false
109  await update($, paneSaving, cur => {
110    was = cur === true
111    return true
112  })
113  return !was
114}
115export function releaseSave($: EngineInterface) {
116  return update($, paneSaving, () => false)
117}
118
119export const PANE_ID = 'abofles'
120export const PANE_TITLE = 'Abo Fles'
121
122export type Ui = ReturnType<EngineInterface['ui']['resolve']>
123export type RenderEvent = Parameters<EngineInterface['ui']['resolve']>[0]
124
125// A line of a memo or a ledger as the cards draw it: control bytes and markdown marks (**bold**, `code`, __x__) dropped, spaces folded.
126export const plain = (text: string): string =>
127  text
128    .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, '') // terminal control bytes a memo line could carry
129    .replace(/\*\*|__|`/g, '')
130    .replace(/\s+/g, ' ')
131    .trim()
132
133// A card in the look of the desktop app's own side panels (Context, Changes, Environment): a rounded dim border; a header
134// row whose left part, the title and a chevron (โ€บ folded, โŒ„ open), is one plain button that folds the card, and whose right
135// part is a short summary (in `tone`, a theme key, or dim); the body only while the card is open. `id` names the fold (see isOpen).
136export function card($: EngineInterface, ui: Ui, c: { id: string; title: string; summary?: string | null; tone?: string; folds: Folds; def?: boolean }, body: JSX.Element | (JSX.Element | null)[]) {
137  const { Box, Button, Text } = ui
138  const open = isOpen(c.folds, c.id, c.def ?? true)
139  return (
140    <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1} rowGap={1}>
141      <Box flexDirection="row" justifyContent="space-between" alignItems="center" columnGap={1}>
142        <Button key={`fold:${c.id}`} plain onPress={() => setFold($, c.id, !open)}>
143          <Text weight="semibold">{c.title}</Text>
144          <Text dimColor>{open ? ' โŒ„' : ' โ€บ'}</Text>
145        </Button>
146        {c.summary ? (
147          <Box flexShrink={1}>
148            {c.tone ? <Text color={c.tone}>{c.summary}</Text> : <Text dimColor>{c.summary}</Text>}
149          </Box>
150        ) : null}
151      </Box>
152      {open ? body : null}
153    </Box>
154  )
155}
156
157// A row of the side panels: a label on the left and its value, dim (or in `tone`), held at the right.
158export function kv(ui: Ui, label: string, value: string, tone?: string) {
159  const { Box, Text } = ui
160  return (
161    <Box flexDirection="row" justifyContent="space-between" columnGap={1}>
162      <Box flexShrink={1}>
163        <Text>{label}</Text>
164      </Box>
165      {tone ? <Text color={tone}>{value}</Text> : <Text dimColor>{value}</Text>}
166    </Box>
167  )
168}
169
170// The "Show all N" / "Show less" button of a list longer than `limit` (id `more:<id>`, folded by default), or null.
171export function moreButton($: EngineInterface, ui: Ui, folds: Folds, id: string, total: number, limit: number) {
172  const { Button } = ui
173  if (total <= limit) return null
174  const all = isOpen(folds, `more:${id}`, false)
175  return <Button key={`more:${id}`} label={all ? 'Show less' : `Show all ${total}`} plain dimColor onPress={() => setFold($, `more:${id}`, !all)} />
176}
177
178// A long list: its first `limit` rows, then its moreButton.
179export function limited($: EngineInterface, ui: Ui, folds: Folds, id: string, rows: JSX.Element[], limit = 3): (JSX.Element | null)[] {
180  if (rows.length <= limit) return rows
181  return [...(isOpen(folds, `more:${id}`, false) ? rows : rows.slice(0, limit)), moreButton($, ui, folds, id, rows.length, limit)]
182}
183
184export const isStr = (v: unknown): v is string => typeof v === 'string'
185export const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
186export const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
187const argvOf = (v: unknown): string[] | null => (Array.isArray(v) && v.length > 0 && v.every(isStr) ? v : null)
188
189// An argv the hook published (Undo's `unresolve`, the editor's `cmd.overrides`) runs only in the shape script_cmd gives it: bash, the
190// abofles plugin's scripts/py launcher, then one of `scripts` from that same folder (forward slashes; Windows paths too). The state file
191// is the user's own, but anything that can write it must not get an arbitrary command run by a press. Any other argv is dropped.
192export function scriptArgv(v: unknown, scripts: readonly string[]): string[] | null {
193  const a = argvOf(v)
194  if (!a || a.length < 3 || !/^(?:.*\/)?bash(?:\.exe)?$/i.test(a[0])) return null
195  const m = /^(.*\/abofles(?:\/[^/]+)?\/scripts)\/py$/.exec(a[1])
196  if (!m || !scripts.some(name => a[2] === `${m[1]}/${name}`)) return null
197  return a
198}
199const strsOf = (v: unknown): string[] => (Array.isArray(v) ? v.filter(isStr) : [])
200const strOr = (v: unknown, d: string): string => (isStr(v) ? v : d)
201const numOrNull = (v: unknown): number | null => (isNum(v) ? v : null)
202const strOrNull = (v: unknown): string | null => (isStr(v) ? v : isNum(v) ? String(v) : null)
203
204// The id of an item: stable per underlying thing; a state file from before ids has none, so its text stands in.
205export const idOf = (it: GuideItem): string => it.id || it.text
206
207// One item from the state file, or null when it lacks a priority or text. Wrong-typed optional fields fall back.
208function cleanItem(v: unknown): GuideItem | null {
209  if (!isObj(v) || !isStr(v.p) || !isStr(v.text)) return null
210  const item: GuideItem = {
211    p: v.p,
212    text: v.text,
213    fill: isStr(v.fill) ? v.fill : '',
214    recheck: isStr(v.recheck) && v.recheck.trim() ? v.recheck : null,
215  }
216  if (isStr(v.id) && v.id) item.id = v.id
217  return item
218}
219
220// The guide from the state file with every field type-checked (older files lack the newer fields), or null.
221export function cleanGuide(raw: unknown): Guide | null {
222  if (!isObj(raw) || !isStr(raw.line) || !raw.line) return null
223  let ctx: Guide['ctx'] = null
224  if (isObj(raw.ctx) && isNum(raw.ctx.tokens) && (raw.ctx.mark == null || isNum(raw.ctx.mark))) {
225    ctx = { tokens: raw.ctx.tokens, mark: raw.ctx.mark ?? null }
226  }
227  let task: Guide['task'] = null
228  if (isObj(raw.task) && isNum(raw.task.spawns) && isNum(raw.task.usd)) {
229    task = {
230      spawns: raw.task.spawns,
231      usd: raw.task.usd,
232      budget: isNum(raw.task.budget) ? raw.task.budget : null,
233      left: isNum(raw.task.left) ? raw.task.left : null,
234    }
235  }
236  // Claude's last resolve, kept by the hook for Undo: needs its text, a ready argv and a timestamp.
237  let lastResolved: Guide['last_resolved'] = null
238  const lr = raw.last_resolved
239  if (isObj(lr) && isStr(lr.text) && isNum(lr.ts)) {
240    const unresolve = scriptArgv(lr.unresolve, ['memo.py', 'status.py'])
241    if (unresolve) lastResolved = { text: lr.text, unresolve, ts: lr.ts }
242  }
243  const items = Array.isArray(raw.items) ? raw.items.map(cleanItem).filter((i): i is GuideItem => i !== null) : []
244  return { line: raw.line, ts: isNum(raw.ts) ? raw.ts : 0, root: isStr(raw.root) ? raw.root : '', items, ctx, task, main: isStr(raw.main) ? raw.main : null, last_resolved: lastResolved }
245}
246
247// Where each thing shows; a missing or unknown place is today's view (guide in the band, resume and spawns in the output).
248function cleanPlaces(raw: unknown): PanePlaces {
249  const p = isObj(raw) ? raw : {}
250  return {
251    guide: p.guide === 'pane' ? 'pane' : 'band',
252    resume: p.resume === 'pane' ? 'pane' : 'output',
253    spawns: p.spawns === 'pane' ? 'pane' : 'output',
254  }
255}
256
257function cleanResume(raw: unknown): PaneResume | null {
258  if (!isObj(raw)) return null
259  const needs = Array.isArray(raw.needs)
260    ? raw.needs.filter(isObj).filter(n => isStr(n.text)).map(n => ({ n: numOrNull(n.n), text: n.text as string }))
261    : []
262  return { head: strOr(raw.head, ''), now: strsOf(raw.now), left: strsOf(raw.left), next: strsOf(raw.next), needs, needs_open: isNum(raw.needs_open) ? raw.needs_open : needs.length, last: strsOf(raw.last) }
263}
264
265function cleanLive(v: unknown): PaneLive | null {
266  if (!isObj(v)) return null
267  return { side: strOr(v.side, ''), model: strOr(v.model, ''), effort: strOr(v.effort, ''), description: strOr(v.description, ''), ts: numOrNull(v.ts) }
268}
269
270function cleanRow(v: unknown): PaneRow | null {
271  if (!isObj(v)) return null
272  return {
273    ts: numOrNull(v.ts),
274    side: strOr(v.side, ''),
275    model: strOr(v.model, ''),
276    effort: strOr(v.effort, ''),
277    topic: strOr(v.topic, ''),
278    tier: strOrNull(v.tier),
279    status: strOrNull(v.status),
280    confidence: strOrNull(v.confidence),
281    tokens: numOrNull(v.tokens),
282    usd: numOrNull(v.usd),
283    base_usd: numOrNull(v.base_usd),
284    description: strOr(v.description, ''),
285    verdict: strOrNull(v.verdict),
286    task: isStr(v.task) && v.task ? v.task : null,
287  }
288}
289
290function cleanSpawns(raw: unknown): PaneSpawns {
291  const s = isObj(raw) ? raw : {}
292  const live = Array.isArray(s.live) ? s.live.map(cleanLive).filter((r): r is PaneLive => r !== null) : []
293  const rows = Array.isArray(s.rows) ? s.rows.map(cleanRow).filter((r): r is PaneRow => r !== null) : []
294  const t = isObj(s.totals) ? s.totals : {}
295  const totals: PaneTotals = { spawns: isNum(t.spawns) ? t.spawns : rows.length, tokens: isNum(t.tokens) ? t.tokens : 0, usd: isNum(t.usd) ? t.usd : 0, base_usd: isNum(t.base_usd) ? t.base_usd : 0, saved_pct: isNum(t.saved_pct) ? t.saved_pct : 0, open_fail: isNum(t.open_fail) ? t.open_fail : 0 }
296  return { live, rows, totals }
297}
298
299function cleanOverrideKey(v: unknown): PaneOverrideKey | null {
300  if (!isObj(v) || !isStr(v.key) || !v.key) return null
301  return { key: v.key, kind: strOr(v.kind, 'text'), options: strsOf(v.options), value: strOr(v.value, ''), source: strOr(v.source, 'default'), default: strOr(v.default, '') }
302}
303
304function cleanOverrides(raw: unknown): PaneOverrides | null {
305  if (!isObj(raw)) return null
306  const f = isObj(raw.files) ? raw.files : {}
307  const keys = Array.isArray(raw.keys) ? raw.keys.map(cleanOverrideKey).filter((k): k is PaneOverrideKey => k !== null) : []
308  const lines = Array.isArray(raw.raw) ? raw.raw.filter(isObj).filter(r => isStr(r.line)).map(r => ({ line: r.line as string, source: strOr(r.source, '') })) : []
309  return { files: { project: strOr(f.project, ''), user: strOr(f.user, '') }, keys, raw: lines }
310}
311
312// The pane payload from the state file with every part type-checked, or null (no payload, or one of another version).
313// A malformed part is dropped and the rest kept; it never throws.
314export function cleanPane(raw: unknown): Pane | null {
315  try {
316    if (!isObj(raw) || raw.v !== 1) return null
317    const cmd = isObj(raw.cmd) ? raw.cmd : {}
318    return {
319      v: 1,
320      ts: isNum(raw.ts) ? raw.ts : 0,
321      root: strOr(raw.root, ''),
322      sid: strOr(raw.sid, ''),
323      places: cleanPlaces(raw.places),
324      resume: cleanResume(raw.resume),
325      spawns: cleanSpawns(raw.spawns),
326      overrides: cleanOverrides(raw.overrides),
327      cmd: { overrides: scriptArgv(cmd.overrides, ['overrides.py']) },
328    }
329  } catch {
330    return null
331  }
332}
333
334// The overrides the editor's script printed after a save: the pane's table follows at once, then the state file is read again (the script refreshed it).
335export async function applyOverrides($: EngineInterface, raw: unknown) {
336  const ov = cleanOverrides(raw)
337  if (ov) await update($, pane, cur => (cur ? { ...cur, overrides: ov } : cur))
338  await refresh($) // the script also rewrote the state file: a changed place (Guide place = band) shows at once
339}
340
341// Does any of the three things show in the pane?
342export const anyPane = (p: Pane | null): p is Pane => p !== null && (p.places.guide === 'pane' || p.places.resume === 'pane' || p.places.spawns === 'pane')
343
344// Takes the "running" flag; false when an Undo already holds it (a second press does nothing).
345async function claim($: EngineInterface): Promise<boolean> {
346  let wasRunning = false
347  await update($, running, cur => {
348    wasRunning = cur === true
349    return true
350  })
351  return !wasRunning
352}
353
354// Reads the session's state file: the guide and the pane. Toasts a new red item.
355export async function refresh($: EngineInterface) {
356  try {
357    const home = (await $.env.get('HOME')) ?? ''
358    const dir = (await $.env.get('ABOFLES_STATE_DIR')) ?? `${home}/.abofles/state`
359    const id = await $.session.id()
360    const text = await $.fs.read(`${dir}/${id}.json`)
361    const st = JSON.parse(text) as { guide?: unknown; pane?: unknown }
362    const nextPane = cleanPane(isObj(st) ? st.pane : null)
363    await update($, pane, () => nextPane)
364    const next = cleanGuide(isObj(st) ? st.guide : null)
365    if (!next) {
366      await update($, guide, () => null)
367      return
368    }
369    await update($, guide, () => next)
370    // Toast when a red item appears that was not toasted before (an old state file without items: the line itself).
371    const red = next.items.filter(i => i.p === '๐Ÿ”ด').map(idOf)
372    if (red.length === 0 && Array.from(keyOf(next.line))[0] === '๐Ÿ”ด') red.push(`line:${next.line}`)
373    const seen = await read($, toasted)
374    if (red.some(r => !seen.includes(r))) {
375      // code points, not UTF-16 units: an emoji is two units
376      $.ui.toast(Array.from(next.line).slice(0, 160).join(''))
377    }
378    if (red.length !== seen.length || red.some((r, n) => r !== seen[n])) await update($, toasted, () => red)
379  } catch {
380    // no state yet (abofles not installed, or no hook ran): draw nothing
381    await update($, guide, () => null)
382    await update($, pane, () => null)
383  }
384}
385
386// ---- the pane's open state
387
388// Keeps paneOpen in the atom (the band redraws on it) and in $.store (the next session honours it).
389export async function setPaneOpen($: EngineInterface, open: boolean) {
390  await update($, paneOpen, () => open)
391  try {
392    await $.store.set('paneOpen', open)
393  } catch {
394    // no store: the session's atom is enough
395  }
396}
397
398// What the store kept from an earlier session (true, false, or null: never decided), loaded into the atom.
399async function loadPaneOpen($: EngineInterface): Promise<boolean | null> {
400  let stored: unknown
401  try {
402    stored = await $.store.get('paneOpen')
403  } catch {
404    stored = undefined
405  }
406  const open = typeof stored === 'boolean' ? stored : null
407  await update($, paneOpen, () => open)
408  return open
409}
410
411// Opens the pane as asked (a command or a press): it is placed at any width.
412export async function openPane($: EngineInterface): Promise<{ isPlaced: boolean; reason?: string }> {
413  let result: { isPlaced: boolean; reason?: string }
414  try {
415    result = await $.ui.open({ id: PANE_ID, title: PANE_TITLE })
416  } catch (err) {
417    result = { isPlaced: false, reason: err instanceof Error ? err.message : String(err) }
418  }
419  await setPaneOpen($, true)
420  return result
421}
422
423// Closes the pane for good (the person's next session finds it closed too).
424export async function closePane($: EngineInterface) {
425  try {
426    await $.ui.close({ id: PANE_ID })
427  } catch {
428    // already gone
429  }
430  await setPaneOpen($, false)
431}
432
433// Is the pane open and drawn now?
434export async function paneIsPlaced($: EngineInterface): Promise<boolean> {
435  try {
436    return (await $.ui.panes()).some(p => p.id === PANE_ID && p.isPlaced)
437  } catch {
438    return false
439  }
440}
441
442// The unasked open: once per session, when the state has a pane payload with a place on the pane and the person
443// did not close it. Not placed (a narrow terminal): the band shows the opener.
444export async function autoOpen($: EngineInterface) {
445  const p = await read($, pane)
446  if (!anyPane(p) || (await read($, paneAuto)) === true) return
447  await update($, paneAuto, () => true)
448  if ((await loadPaneOpen($)) === false) return
449  try {
450    await $.ui.open({ id: PANE_ID, title: PANE_TITLE })
451  } catch {
452    // the band's opener stays
453  }
454}
455
456// ---- the guide: what both places draw and do
457
458// The memo is due when the context is within 50K tokens of its next mark, or past the last mark (mark null).
459export function needsMemo(ctx: Guide['ctx']): boolean {
460  if (!ctx) return false
461  return ctx.mark == null || ctx.mark * 1000 - ctx.tokens <= 50000
462}
463
464// The dim second line: `ctx 412K / 500K ยท task 3 spawns ยท $0.41 ยท budget 2 left ยท suggest Opus 5.5 ยท Medium`.
465export function meterOf(g: Guide): string {
466  const parts: string[] = []
467  if (g.ctx) parts.push(g.ctx.mark == null ? `ctx ${Math.round(g.ctx.tokens / 1000)}K` : `ctx ${Math.round(g.ctx.tokens / 1000)}K / ${g.ctx.mark}K`)
468  if (g.task) {
469    parts.push(`task ${g.task.spawns} spawns`, `$${g.task.usd.toFixed(2)}`)
470    if (g.task.left != null) parts.push(`budget ${g.task.left} left`)
471  }
472  const main = g.main?.replace(/^\s*main:\s*/i, '').trim()
473  if (main) parts.push(main)
474  return parts.join(' ยท ')
475}
476
477// The ladder's priorities in order (๐Ÿ”ด๐ŸŸก, โœ…, โ€ฆ): the fallback identity of a state file from before item ids.
478export function keyOf(line: string): string {
479  return (line.match(/[๐Ÿ”ด๐ŸŸ ๐ŸŸกโณ๐Ÿง ๐Ÿ’ฐโœ…]/gu) ?? []).join('') || line
480}
481
482// What Hide compares: the ids of the shown items, plus the memo mark when the memo is due. A hidden band comes back
483// when an item appears or goes, or when a newly crossed mark makes the memo due again; not when only wording changes.
484export function hideKeyOf(g: Guide): string {
485  const items = Array.isArray(g.items) ? g.items : []
486  const ids = items.length > 0 ? items.map(idOf).join('|') : keyOf(g.line)
487  return needsMemo(g.ctx ?? null) ? `${ids}|memo:${g.ctx?.mark ?? 'past'}` : ids
488}
489
490// The prompt the Use and Copy buttons hand over: the guide line as an instruction the assistant acts on.
491export function promptFor(line: string): string {
492  const body = line.replace(/^\s*๐Ÿงญ\s*/, '').trim()
493  return `abofles guide โ€” do this now, in order: ${body}`
494}
495
496// What the guide shows, worked out once: the items, the top one, whether nothing is open, and the texts the buttons hand over.
497export type GuideView = { items: GuideItem[]; top: GuideItem | undefined; done: boolean; memo: boolean; prompt: string; recheck: string | null; meter: string }
498
499export function viewOf(g: Guide): GuideView {
500  // A value an earlier build kept in $.state survives a reload: every newer field is optional here too.
501  const items = Array.isArray(g.items) ? g.items : []
502  const top = items[0]
503  // Nothing open: every item is โœ… (an old state file without items: the line's only priority is โœ…).
504  const done = items.length > 0 ? items.every(i => i.p === 'โœ…') : keyOf(g.line) === 'โœ…'
505  const recheck = !done && typeof top?.recheck === 'string' && top.recheck.trim() ? top.recheck : null
506  return { items, top, done, memo: needsMemo(g.ctx ?? null), prompt: top?.fill || promptFor(g.line), recheck, meter: meterOf(g) }
507}
508
509// Show: the hidden guide comes back at once (the pane's "Show" button).
510export async function showGuide($: EngineInterface) {
511  await update($, hiddenKey, () => null)
512}
513
514// Hide: the guide stays down until the shown items (or the memo mark) change.
515export async function hideGuide($: EngineInterface, g: Guide) {
516  await update($, hiddenKey, () => hideKeyOf(g))
517}
518
519// Put text into the prompt box; keep a draft the person already typed. Hides the guide once it is in.
520export async function fillPrompt($: EngineInterface, g: Guide, text: string) {
521  const draft = (await $.prompt.read()).text.trim()
522  const r = await $.prompt.fill({ text: draft ? `\n${text}` : text, mode: draft ? 'append' : 'replace' })
523  if (r.isFilled) await hideGuide($, g)
524  else $.ui.toast('Prompt box is not open โ€” use Copy')
525}
526
527export async function copyPrompt($: EngineInterface, text: string, surface: Parameters<EngineInterface['ui']['copy']>[0]['surface']) {
528  const r = await $.ui.copy({ text, surface })
529  $.ui.toast(r.isCopied ? 'Guide copied โ€” paste it in the prompt box' : `Copy failed (${r.reason})`)
530}
531
532// Undo: runs the argv the hook published as last_resolved (cwd = the project root), then reads the state again.
533export async function undoLast($: EngineInterface, g: Guide, last: NonNullable<Guide['last_resolved']>) {
534  if (!(await claim($))) return
535  try {
536    const r = await $.process.run(last.unresolve, g.root ? { cwd: g.root } : undefined)
537    if (r.exitCode === 0 || r.exitCode === 3) await update($, dismissedTs, () => last.ts) // a failed Undo keeps the row, so it can be retried
538    const first = (r.exitCode === 0 ? r.stdout : r.stderr || r.stdout).split('\n').find(l => l.trim()) ?? ''
539    if (r.exitCode === 0) $.ui.toast(first || 'Undone')
540    else if (r.exitCode === 3) $.ui.toast('Already open') // nothing changed
541    else $.ui.toast(`Undo failed โ€” ${first || `exit ${r.exitCode}`}`)
542    await refresh($)
543  } catch (err) {
544    $.ui.toast(`Undo failed โ€” ${err instanceof Error ? err.message : String(err)}`)
545  } finally {
546    await update($, running, () => false)
547  }
548}
549
550// The row "โœ“ resolved: โ€ฆ" with Undo (gone while an Undo runs) and Hide; the band and the pane's guide card both draw it.
551export function undoRow($: EngineInterface, ui: Ui, g: Guide, last: NonNullable<Guide['last_resolved']>, busy: boolean, inPane = false) {
552  const { Box, Button, Text } = ui
553  const look = inPane ? ({ variant: 'secondary' } as const) : {}
554  return (
555    <Box flexDirection="row" flexWrap="wrap" gap={1}>
556      <Text>{`โœ“ resolved: ${inPane ? plain(last.text) : Array.from(last.text).slice(0, 90).join('')}`}</Text>
557      {!busy ? <Button key="undo" label="Undo" {...look} onPress={() => undoLast($, g, last)} /> : null}
558      <Button key="undo-hide" label="Hide" {...look} onPress={() => update($, dismissedTs, () => last.ts)} />
559    </Box>
560  )
561}
562
563// The guide's buttons: Use, Re-check, Memo, Copy, Hide. In the pane Use is the primary button and the rest secondary.
564export function guideButtons($: EngineInterface, ui: Ui, g: Guide, v: GuideView, inPane = false, extra: unknown = null) {
565  const { Box, Button } = ui
566  const main = inPane ? ({ variant: 'primary' } as const) : {}
567  const look = inPane ? ({ variant: 'secondary' } as const) : {}
568  const memoLook = v.done && v.memo ? ({ variant: 'primary' } as const) : look // nothing else open: the memo is the next step
569  return (
570    <Box flexDirection="row" flexWrap="wrap" gap={1} marginTop={inPane ? 0 : 1}>
571      {v.done ? null : <Button key="use" label="Use" {...main} onPress={() => fillPrompt($, g, v.prompt)} />}
572      {v.recheck ? <Button key="recheck" label="Re-check" {...look} onPress={() => fillPrompt($, g, v.recheck as string)} /> : null}
573      {v.memo ? <Button key="memo" label="Memo" {...memoLook} onPress={() => fillPrompt($, g, '/abofles:memo')} /> : null}
574      {v.done ? null : <Button key="copy" label="Copy" {...look} onPress={press => copyPrompt($, v.prompt, press.surface)} />}
575      <Button key="hide" label="Hide" {...look} onPress={() => hideGuide($, g)} />
576      {extra as never}
577    </Box>
578  )
579}
580
hooks/editor.tsx 348 lines
1import type { EngineInterface } from 'claude-code'
2
3import type { Pane, PaneOverrideKey, PaneOverrides } from '../types'
4import { applyOverrides, card, claimSave, getPaneDraft, getPaneSaving, kv, plain, refresh, releaseSave, setPaneView, updatePaneDraft } from './shared'
5import type { Folds, Ui } from './shared'
6
7// The overrides of the Abo Fles pane, in two places. On the pane's main page, a short card: what is set (key = value, and in which
8// file) and an "Edit overrides" button. That button turns the pane into the editor page: the target file (scope), the simple keys in
9// groups (a Select for the keys with a fixed set of values, an Input for numbers, texts and lists; each with a one-line help and a badge
10// when a file sets it), the other forms as lines of one multi-line Input, and the buttons. Edits live in the paneDraft atom ('' = back
11// to the default) until Save runs the abofles plugin's overrides.py, which edits the `## abofles overrides` block of the chosen file and
12// prints the new table. Nothing is written by this mod itself.
13
14type Draft = Record<string, string>
15type Scope = 'project' | 'user'
16
17const SCOPE = '@scope'
18const RAW = '@raw'
19const CUSTOM = '@custom:'
20const DEFAULT_PICK = '@default' // the Select entries that are not a value of the key
21const CUSTOM_PICK = '@custom'
22
23// The keys that also take a value of their own: the Input a "custom value" pick opens, what it starts with and what it asks for.
24const CUSTOM_KEYS: Record<string, { start: string; hint: string }> = {
25  Agents: { start: '3', hint: 'N agents per task' },
26  Receipt: { start: 'savings 30', hint: 'savings N (percent)' },
27}
28
29// The editor's groups, in order, and each key's group and help line. A key the table adds later lands in "More", without help.
30const GROUPS = ['Session', 'Agents', 'Output', 'Where it shows', 'More'] as const
31const KEY_INFO: Record<string, { group: (typeof GROUPS)[number]; help: string }> = {
32  'Main session': { group: 'Session', help: 'The modelยทeffort you run on, e.g. opusยทhigh' },
33  'Session cap': { group: 'Session', help: 'Units per session before it stops to ask' },
34  'Context marks': { group: 'Session', help: 'Context sizes (K tokens) that ask for a memo, then /compact' },
35  Break: { group: 'Session', help: 'Minutes away before the resume shows again; off = never' },
36  Pace: { group: 'Session', help: 'fast: fewer stops, no Judge on small questions, short receipts' },
37  Agents: { group: 'Agents', help: 'ask once, size by tier (auto), N per task, or off' },
38  Parallel: { group: 'Agents', help: 'Background agents running at once' },
39  'Agent budgets': { group: 'Agents', help: 'Agents per tier T1, T2, T3, T4 under Agents = auto' },
40  'Review gate': { group: 'Agents', help: 'Holds the receipt while a required reviewer has not run' },
41  Questions: { group: 'Agents', help: 'judge: a Judge agent tries to answer before you are asked' },
42  Receipt: { group: 'Output', help: 'The receipt form; savings N prints it only when N% was saved' },
43  Guide: { group: 'Output', help: 'The ๐Ÿงญ next-step line' },
44  Resume: { group: 'Output', help: 'What the resume covers; off keeps it out of the chat' },
45  Language: { group: 'Output', help: 'The language owner questions are written in' },
46  'Guide place': { group: 'Where it shows', help: 'This pane, or the band above the prompt' },
47  'Resume place': { group: 'Where it shows', help: 'This pane, or printed in the chat' },
48  'Spawns place': { group: 'Where it shows', help: 'This pane, or printed in the chat' },
49}
50
51// Which file a value comes from, as the badge says it.
52const WHERE: Record<string, string> = { project: 'this project', user: 'all projects' }
53
54export const scopeOf = (d: Draft): Scope => (d[SCOPE] === 'user' ? 'user' : 'project')
55
56// The value as it would stand in the file: '' = no line (the default). A default value typed over a default is no line either.
57export const written = (k: PaneOverrideKey, v: string): string => {
58  const t = v.trim()
59  return t === '' || (k.source === 'default' && t === k.value) ? '' : t
60}
61
62const baseline = (k: PaneOverrideKey): string => written(k, k.value)
63
64const isChanged = (k: PaneOverrideKey, d: Draft): boolean => d[k.key] !== undefined && written(k, d[k.key]) !== baseline(k)
65
66export const changedKeys = (ov: PaneOverrides, d: Draft): PaneOverrideKey[] => ov.keys.filter(k => isChanged(k, d))
67
68const linesOf = (text: string): string[] => text.split('\n').map(l => l.replace(/^\s*-\s*/, '').trim()).filter(Boolean)
69const rawBase = (ov: PaneOverrides, scope: Scope): string[] => ov.raw.filter(r => r.source === scope).map(r => r.line)
70const rawLines = (ov: PaneOverrides, d: Draft, scope: Scope): string[] => (d[RAW] === undefined ? rawBase(ov, scope) : linesOf(d[RAW]))
71const rawChanged = (ov: PaneOverrides, d: Draft, scope: Scope): boolean => d[RAW] !== undefined && rawLines(ov, d, scope).join('\n') !== rawBase(ov, scope).join('\n')
72
73export const dirtyCount = (ov: PaneOverrides, d: Draft): number => changedKeys(ov, d).length + (rawChanged(ov, d, scopeOf(d)) ? 1 : 0)
74
75// The prompt "Ask Claude to apply" fills: only what changed, in the block's own `- Key = value` shape.
76export function askText(file: string, ov: PaneOverrides, d: Draft): string {
77  const parts = changedKeys(ov, d).map(k => {
78    const v = written(k, d[k.key])
79    return v === '' ? `- ${k.key} removed (back to the default)` : `- ${k.key} = ${v}`
80  })
81  const scope = scopeOf(d)
82  if (rawChanged(ov, d, scope)) {
83    const base = rawBase(ov, scope)
84    const now = rawLines(ov, d, scope)
85    parts.push(...now.filter(l => !base.includes(l)).map(l => `- ${l}`), ...base.filter(l => !now.includes(l)).map(l => `- remove: ${l}`))
86  }
87  return `Apply in ${file} \`## abofles overrides\`: ${parts.join(' ')}`
88}
89
90// A path as the card shows it: relative to the project, or with ~ for the home folder.
91function shortPath(path: string, root: string, home: string): string {
92  if (root && path.startsWith(`${root}/`)) return path.slice(root.length + 1)
93  if (home && path.startsWith(`${home}/`)) return `~${path.slice(home.length)}`
94  return path
95}
96
97const firstLine = (text: string): string => text.split('\n').find(l => l.trim()) ?? ''
98
99function setDraft($: EngineInterface, key: string, value: string, custom: boolean | null = null) {
100  return updatePaneDraft($, cur => {
101    const next: Draft = { ...cur, [key]: value }
102    if (custom === true) next[`${CUSTOM}${key}`] = '1'
103    if (custom === false) delete next[`${CUSTOM}${key}`]
104    return next
105  })
106}
107
108// Another scope is another file: the lines typed for the old one are dropped, so they are never written to the new one.
109function setScope($: EngineInterface, scope: Scope) {
110  return updatePaneDraft($, cur => {
111    if (scopeOf(cur) === scope) return cur
112    const next: Draft = { ...cur, [SCOPE]: scope }
113    delete next[RAW]
114    return next
115  })
116}
117
118// ---- the buttons
119
120async function save($: EngineInterface, p: Pane, ov: PaneOverrides, d: Draft, file: string) {
121  const argv = p.cmd.overrides
122  if (!argv) {
123    $.ui.toast('Update the abofles plugin to save here')
124    return
125  }
126  const scope = scopeOf(d)
127  const set: Record<string, string> = {}
128  for (const k of changedKeys(ov, d)) set[k.key] = written(k, d[k.key])
129  const body: { set: Record<string, string>; raw?: string[] } = { set }
130  if (rawChanged(ov, d, scope)) body.raw = rawLines(ov, d, scope)
131  if (Object.keys(set).length === 0 && body.raw === undefined) {
132    $.ui.toast('Nothing to save')
133    return
134  }
135  if (!(await claimSave($))) return
136  try {
137    const r = await $.process.run([...argv, 'set', '--scope', scope], { ...(p.root ? { cwd: p.root } : {}), stdin: JSON.stringify(body) })
138    if (r.exitCode !== 0) {
139      $.ui.toast(firstLine(r.stderr) || firstLine(r.stdout) || `Save failed (exit ${r.exitCode})`) // the draft stays
140      return
141    }
142    let again: unknown = null
143    try {
144      again = JSON.parse(r.stdout)
145    } catch {
146      // the file is written; the state file has the table
147    }
148    if (again !== null) await applyOverrides($, again)
149    else await refresh($)
150    await updatePaneDraft($, cur => (cur[SCOPE] ? { [SCOPE]: cur[SCOPE] } : {}))
151    $.ui.toast(`Saved to ${file}`)
152  } catch (err) {
153    $.ui.toast(`Save failed โ€” ${err instanceof Error ? err.message : String(err)}`)
154  } finally {
155    await releaseSave($)
156  }
157}
158
159async function askClaude($: EngineInterface, ov: PaneOverrides, d: Draft, file: string) {
160  if (dirtyCount(ov, d) === 0) {
161    $.ui.toast('Nothing changed to ask for')
162    return
163  }
164  const text = askText(file, ov, d)
165  const have = (await $.prompt.read()).text.trim()
166  const r = await $.prompt.fill({ text: have ? `\n${text}` : text, mode: have ? 'append' : 'replace' })
167  if (!r.isFilled) $.ui.toast('Prompt box is not open')
168}
169
170// ---- the editor page
171
172// One key: its control (named by its label), the custom value Input when open, then a dim help line and the badge.
173function field($: EngineInterface, ui: Ui, k: PaneOverrideKey, d: Draft) {
174  const { Box, Input, Select, Text } = ui
175  const help = KEY_INFO[k.key]?.help
176  const badge = isChanged(k, d) ? (
177    <Text size="caption" color="warning">
178      edited
179    </Text>
180  ) : WHERE[k.source] ? (
181    <Text size="caption" color="suggestion">
182      {WHERE[k.source]}
183    </Text>
184  ) : null
185  const meta =
186    help || badge ? (
187      <Box flexDirection="row" flexWrap="wrap" columnGap={1}>
188        {help ? (
189          <Text size="caption" dimColor>
190            {help}
191          </Text>
192        ) : null}
193        {badge}
194      </Box>
195    ) : null
196  const fallback = k.default ? `default ${k.default}` : 'none'
197  if (k.kind !== 'select') {
198    return (
199      <Box flexDirection="column">
200        <Input key={`in:${k.key}`} label={k.key} value={d[k.key] ?? k.value} placeholder={fallback} onInput={v => setDraft($, k.key, v)} onSubmit={v => setDraft($, k.key, v)} />
201        {meta}
202      </Box>
203    )
204  }
205  const custom = CUSTOM_KEYS[k.key]
206  const cur = written(k, d[k.key] ?? k.value)
207  const known = k.options.find(o => o.toLowerCase() === cur.toLowerCase())
208  const open = custom !== undefined && (d[`${CUSTOM}${k.key}`] !== undefined || (cur !== '' && known === undefined))
209  const pick = open ? CUSTOM_PICK : cur === '' ? DEFAULT_PICK : (known ?? cur)
210  const options = [
211    { value: DEFAULT_PICK, label: k.default ? `default (${k.default})` : 'default' },
212    ...k.options.map(o => ({ value: o })),
213    ...(custom ? [{ value: CUSTOM_PICK, label: 'custom value' }] : known === undefined && cur !== '' ? [{ value: cur }] : []),
214  ]
215  const onSelect = (v: string) => {
216    if (v === CUSTOM_PICK) return setDraft($, k.key, cur !== '' && known === undefined ? cur : custom?.start ?? '', true)
217    return setDraft($, k.key, v === DEFAULT_PICK ? '' : v, false)
218  }
219  return (
220    <Box flexDirection="column">
221      <Select key={`sel:${k.key}`} label={k.key} options={options} value={pick} onSelect={onSelect} />
222      {open ? <Input key={`custom:${k.key}`} label={`${k.key} value`} value={d[k.key] ?? k.value} placeholder={custom?.hint} onInput={v => setDraft($, k.key, v, true)} onSubmit={v => setDraft($, k.key, v, true)} /> : null}
223      {meta}
224    </Box>
225  )
226}
227
228// What the page and the short card both need: the draft, the file names, the counts.
229async function editorState($: EngineInterface, p: Pane, ov: PaneOverrides) {
230  const d = (await getPaneDraft($)) ?? {}
231  const home = (await $.env.get('HOME')) ?? ''
232  const scope = scopeOf(d)
233  const files = { project: shortPath(ov.files.project, p.root, home) || 'CLAUDE.md', user: shortPath(ov.files.user, p.root, home) || '~/.claude/CLAUDE.md' }
234  return { d, scope, files, file: files[scope], dirty: dirtyCount(ov, d) }
235}
236
237const unreadable = 'Pane data unreadable โ€” update both abofles and abofles-guide'
238
239// The page the pane turns into: Back, the target file, the groups of keys, the other forms, and Save / Ask Claude / Discard.
240export async function overridesPage($: EngineInterface, ui: Ui, p: Pane | null, folds: Folds) {
241  const { Box, Button, Input, Select, Text } = ui
242  const ov: PaneOverrides | null = p?.overrides ?? null
243  const back = (
244    <Button key="back" plain dimColor onPress={() => setPaneView($, 'main')}>
245      โ€น Back
246    </Button>
247  )
248  if (p === null || ov === null) {
249    return (
250      <Box flexDirection="column" gap={1}>
251        {back}
252        <Text dimColor>{unreadable}</Text>
253      </Box>
254    )
255  }
256  const { d, scope, files, file, dirty } = await editorState($, p, ov)
257  const saving = (await getPaneSaving($)) === true
258  const raw = rawLines(ov, d, scope)
259  const others = ov.raw.filter(r => r.source !== scope)
260  const groups = GROUPS.map(name => ({ name, keys: ov.keys.filter(k => (KEY_INFO[k.key]?.group ?? 'More') === name) })).filter(g => g.keys.length > 0)
261  const setIn = (keys: PaneOverrideKey[]): string | null => {
262    const edited = keys.filter(k => isChanged(k, d)).length
263    const set = keys.filter(k => WHERE[k.source]).length
264    return edited > 0 ? `${edited} edited` : set > 0 ? `${set} set` : null
265  }
266  const rawEdited = rawChanged(ov, d, scope)
267  return (
268    <Box flexDirection="column" gap={1}>
269      <Box flexDirection="row" justifyContent="space-between" alignItems="center" columnGap={1}>
270        {back}
271        <Box flexDirection="row" flexWrap="wrap" columnGap={1} flexShrink={1}>
272          <Text weight="semibold">Overrides</Text>
273          {dirty > 0 ? <Text color="warning">{`${dirty} unsaved`}</Text> : null}
274        </Box>
275      </Box>
276      <Box flexDirection="column">
277        <Select
278          key="scope"
279          label="Save to"
280          options={[
281            { value: 'project', label: 'This project' },
282            { value: 'user', label: 'All projects' },
283          ]}
284          value={scope}
285          onSelect={v => setScope($, v === 'user' ? 'user' : 'project')}
286        />
287        <Text size="caption" dimColor>{file}</Text>
288      </Box>
289      {groups.map(g => {
290        const summary = setIn(g.keys)
291        return card(
292          $,
293          ui,
294          { id: `g:${g.name}`, title: g.name, summary, tone: summary?.endsWith('edited') ? 'warning' : undefined, folds },
295          <Box flexDirection="column" rowGap={1}>{g.keys.map(k => field($, ui, k, d))}</Box>,
296        )
297      })}
298      {card(
299        $,
300        ui,
301        // folded while this file has none of these lines: they are the rare, free-form overrides
302        { id: 'g:Other', title: 'Other overrides', summary: rawEdited ? 'edited' : raw.length > 0 ? `${raw.length} line${raw.length === 1 ? '' : 's'}` : others.length > 0 ? `${others.length} in ${WHERE[others[0].source] ?? others[0].source}` : null, tone: rawEdited ? 'warning' : undefined, folds, def: raw.length > 0 || rawEdited },
303        <Box flexDirection="column">
304          <Text size="caption" dimColor>One per line: topic tiers, cells, reviewers, workflows โ€” e.g. Reviewers: Money = finance, tester</Text>
305          <Input key="raw" label="Lines" rows={Math.min(8, Math.max(2, raw.length + 1))} value={d[RAW] ?? rawBase(ov, scope).join('\n')} onInput={v => setDraft($, RAW, v)} onSubmit={v => setDraft($, RAW, v)} />
306          {others.map(r => (
307            <Text size="caption" dimColor>{`${r.line} โ€” in ${WHERE[r.source] ?? r.source}; switch Save to, to edit it`}</Text>
308          ))}
309        </Box>,
310      )}
311      <Box flexDirection="row" flexWrap="wrap" gap={1}>
312        {saving ? (
313          <Button key="save" label="Savingโ€ฆ" variant="secondary" onPress={() => undefined} />
314        ) : (
315          <Button key="save" label="Save" variant={dirty > 0 ? 'primary' : 'secondary'} onPress={() => save($, p, ov, d, file)} />
316        )}
317        <Button key="ask" label="Ask Claude to apply" variant="secondary" onPress={() => askClaude($, ov, d, file)} />
318        {dirty > 0 ? <Button key="reset" label="Discard edits" variant="secondary" onPress={() => updatePaneDraft($, cur => (cur[SCOPE] ? { [SCOPE]: cur[SCOPE] } : {}))} /> : null}
319      </Box>
320    </Box>
321  )
322}
323
324// The short card on the pane's main page: each value a file sets, the other lines' count, and "Edit overrides".
325export async function overridesCard($: EngineInterface, ui: Ui, p: Pane | null, folds: Folds) {
326  const { Box, Button, Text } = ui
327  const ov: PaneOverrides | null = p?.overrides ?? null
328  if (p === null || ov === null) return card($, ui, { id: 'overrides', title: 'Overrides', folds }, <Text dimColor>{unreadable}</Text>)
329  const { dirty } = await editorState($, p, ov)
330  const set = ov.keys.filter(k => WHERE[k.source])
331  // one row per value a file sets, as the app's panels read: the key, then the value and the file at the right
332  const rows: JSX.Element[] = set.map(k => kv(ui, k.key, `${plain(k.value)} ยท ${WHERE[k.source]}`))
333  if (ov.raw.length > 0) rows.push(kv(ui, 'Other lines', String(ov.raw.length)))
334  if (rows.length === 0) rows.push(<Text dimColor>All defaults</Text>)
335  const summary = dirty > 0 ? `${dirty} unsaved` : set.length > 0 ? `${set.length} set` : null
336  return card(
337    $,
338    ui,
339    { id: 'overrides', title: 'Overrides', summary, tone: dirty > 0 ? 'warning' : undefined, folds },
340    <Box flexDirection="column" rowGap={1}>
341      <Box flexDirection="column">{rows}</Box>
342      <Box flexDirection="row">
343        <Button key="edit-overrides" label="Edit overrides" variant="secondary" onPress={() => setPaneView($, 'overrides')} />
344      </Box>
345    </Box>,
346  )
347}
348
types/index.d.ts 115 lines
1export type GuideItem = {
2  id?: string // stable per underlying thing (fail:<agent>, dec:<n>, ctx:<mark>, โ€ฆ); absent in older state files: text stands in
3  p: string // the priority emoji (๐Ÿ”ด๐ŸŸ ๐ŸŸกโณ๐Ÿง ๐Ÿ’ฐโœ…)
4  text: string
5  fill: string // what Use puts in the prompt box and Copy copies
6  recheck?: string | null // ๐Ÿ”ด๐ŸŸ ๐ŸŸก items: the prompt Re-check puts in the prompt box (Claude verifies, then resolves)
7  // The hook still writes `resolve: null` and `unresolve: null` on every item; the band never reads them.
8}
9
10export type Guide = {
11  line: string
12  ts: number
13  root: string
14  items: GuideItem[]
15  ctx: { tokens: number; mark: number | null } | null // mark in K tokens; null: past the last mark
16  task: { spawns: number; usd: number; budget: number | null; left: number | null } | null
17  main: string | null // "suggest Opus 5.5 ยท Medium (now Fable 5.1 ยท Medium)"; null when the main session fits
18  // Claude's last resolve, kept by the hook until the Stop of the turn after it; null when nothing. Undo runs `unresolve` (cwd = root).
19  last_resolved: { text: string; unresolve: string[]; ts: number } | null
20}
21
22// ---- the Abo Fles pane: `pane` in the session's state file, written by the abofles hooks (v 1). Every part is optional to the mod:
23// cleanPane() drops what is malformed and keeps the rest; a state file from older hooks has no `pane` at all.
24
25export type PanePlaces = {
26  guide: 'pane' | 'band' // where the guide shows; old hooks: the band
27  resume: 'pane' | 'output' // where /abofles:resume shows; old hooks: the output
28  spawns: 'pane' | 'output' // where /abofles:bill shows; old hooks: the output
29}
30
31export type PaneResume = {
32  head: string
33  now: string[]
34  left: string[]
35  next: string[]
36  needs: { n: number | null; text: string }[] // the open decisions, numbered as the memo numbers them
37  needs_open: number
38  last: string[]
39}
40
41export type PaneLive = { side: string; model: string; effort: string; description: string; ts: number | null } // ts: epoch seconds
42
43export type PaneRow = {
44  ts: number | null
45  side: string
46  model: string
47  effort: string
48  topic: string
49  tier: string | null
50  status: string | null
51  confidence: string | null
52  tokens: number | null
53  usd: number | null
54  base_usd: number | null
55  description: string
56  verdict: string | null
57  task: string | null // the task the spawn belongs to; rows are grouped by it
58}
59
60export type PaneTotals = { spawns: number; tokens: number; usd: number; base_usd: number; saved_pct: number; open_fail: number }
61
62export type PaneSpawns = { live: PaneLive[]; rows: PaneRow[]; totals: PaneTotals } // rows: the last 30, oldest first
63
64export type PaneOverrideKey = { key: string; kind: string; options: string[]; value: string; source: string; default: string }
65
66export type PaneOverrides = {
67  files: { project: string; user: string }
68  keys: PaneOverrideKey[]
69  raw: { line: string; source: string }[] // override lines the table cannot show
70}
71
72export type Pane = {
73  v: 1
74  ts: number
75  root: string
76  sid: string
77  places: PanePlaces
78  resume: PaneResume | null // null: no memo yet
79  spawns: PaneSpawns
80  overrides: PaneOverrides | null
81  cmd: { overrides: string[] | null } // argv prefix of the script the overrides editor runs
82}
83
84declare module 'claude-code' {
85  interface PluginState {
86    // `hiddenKey`: the ids of the items shown when the person hid the band (Hide or Use), plus the memo mark when the
87    // memo was due; the band stays down while those are the same, and comes back when an item appears or goes.
88    // `dismissedTs`: the `ts` of the last_resolved row the person hid; that row stays down.
89    // `running`: true while an Undo command runs; its button is gone meanwhile.
90    // `toasted`: the ids of the red items already toasted; a toast fires only for a red id not in it.
91    // `pane`: the pane payload of the state file (null: older hooks, or none yet).
92    // `paneOpen`: true after the person or a command opened the pane, false after it was closed by hand or by the
93    // command, null while undecided; also kept in $.store under `paneOpen` so a new session honours it.
94    // `paneAuto`: true once this session tried the unasked open (once per session).
95    // `paneDraft`: unsaved values of the overrides editor, by override key (+ '@scope', '@raw', '@custom:<key>').
96    // `paneSaving`: true while the editor's Save runs its command.
97    // `paneView`: the page the pane shows: 'main' (the cards) or 'overrides' (the editor).
98    // `paneFolds`: open (true) or folded (false) by id: a card, an editor group (`g:<name>`), a long list (`more:<id>`); also in $.store.
99    'abofles-guide': {
100      guide: Guide | null
101      hiddenKey: string | null
102      dismissedTs: number | null
103      running: boolean
104      toasted: string[]
105      pane: Pane | null
106      paneOpen: boolean | null
107      paneAuto: boolean
108      paneDraft: Record<string, string>
109      paneSaving: boolean
110      paneView: 'main' | 'overrides'
111      paneFolds: Record<string, boolean>
112    }
113  }
114}
115