Memory that turns Claude into a counterpart: a local-first memory layer modeled on human memory. Wakes each session with what matters, remembers by meaning…

Agents are great. What you're missing is a counterpart.
Counterparts gives your AI assistant its own memory, modeled on human memory. It writes its memories itself, and they fade and grow the way yours do. It runs today with Claude Code.
You need bun 1.3 or newer, or Node 22.15 or newer. macOS and Linux; Windows not yet supported.
curl -fsSL https://bun.sh/install | bash # if you don't have bun
bun add -g counterparts
counterparts
With Node instead: npm install -g counterparts, then counterparts. Whichever runtime runs the setup is the one Claude Code's hooks and memory tools are wired to.
counterparts walks you through setup: your name and connecting Claude Code. No API keys. Then restart Claude Code and check it:
counterparts doctor
To remove it, run counterparts uninstall. Your memory is kept unless you ask for it to be deleted. The full walkthrough is in docs/QUICKSTART.md.

counterparts delete).People interested in giving an AI its own sense of self and building a relationship with it over time. Tinkerers, researchers, writers, and anyone who talks to an assistant every day and wishes it remembered.
It's not a work memory. It doesn't track your tasks, code conventions or project docs. Plenty of tools do that, including the memory built into ChatGPT and Claude.
Today's models are frozen, so memory is the only learning they do. Once a real memory works on top of a frozen model, the plan is to pair it with an open-weight model whose weights can change, so the AI can learn and grow, not just remember.
Once installed it runs on its own. A few commands are worth knowing:
counterparts dashboard # look at the memory in your browser
counterparts ask "..." # ask the memory a question
counterparts scope . --off # don't remember this directory
counterparts export # a copy of everything, encrypted by default
counterparts --help # the rest
Memory is on for every directory by default. The first session in a new directory asks whether you want it there.
Two pieces connect it to Claude Code. Hooks load a briefing at the start of each session and bring up related memories as you talk. A small MCP server gives the AI tools to save what it learned, write a journal entry, and look things up.
The core doesn't depend on Claude Code. Each part is its own module, with a CONTRACT.md describing what it does:
| module | what it does |
|---|---|
| store | One SQLite database, plus a rebuildable search cache and daily snapshots |
| encode | Filters what comes in: strips credentials, drops junk, scores what's new |
| remember | Takes what the AI writes during and at the end of a session |
| recall | Finds related memories as you talk |
| associate | Links memories that come up together |
| schemas | Beliefs about people and things, revised slowly |
| self | Identity, the journal, and the start-of-session briefing |
| prospective | Reminders for later, triggered by a date or a topic |
| sleep | Nightly housekeeping: fading, pruning, merging, promoting |
| physics | The math for strength and decay |
More: docs/ELI5.md (the whole system in plain words) and docs/module-map.md.
Early. It's been the author's daily memory since September 2026, on bun and macOS; Node (22.15+) and Linux pass a smoke test and an install run but have no daily user yet. Claude Desktop has no Linux build, so on Linux it is Claude Code only. Expect rough edges, and please open an issue when you hit one.
There are no API keys, and nothing leaves your machine except through Claude Code itself. Search by meaning runs on a small model on your machine, and a session that ends before it's written up is written up by the next session in that project.
That small model finds close paraphrases ("my doctor" finds a note about a physician), but not a description that never names the thing: "a pet that purrs" won't find a note about your cat. Exact words are strongest, and a short memory matches better than one padded with names and details.
Counterparts is the third version of a memory project. The earlier ones (claude-engram, engram, and bansai) were each used daily before the next was written. CONSTITUTION.md holds the principles.
MIT. Contributions are welcome; see CONTRIBUTING.md.
hooks/sidebar/hooks/full.tsx 31 lines1/**
2 * The plugin's own build's hooks module: the sidebar (`register.tsx`), the
3 * speak-first (`speak-first.tsx`) and the full sidebar's actions
4 * (`actions.tsx`: the Meet row, the dashboard link and line, the view and
5 * avatar switches) in one, since a plugin loads one hooks module
6 * (`hooks.json` "modules" takes one entry). The plugin directory's build
7 * names `register.tsx` alone, so none of the other two is in it.
8 *
9 * THE ONE SWITCH (2026-10-16): registering `actions.tsx` is what turns the
10 * full sidebar's pieces on (it sets `state.ts#run.full`); nothing else does.
11 */
12import type { Register } from 'claude-code'
13
14import { register as actions } from './actions'
15import { register as sidebar } from './register'
16import { register as speakFirst } from './speak-first'
17
18/**
19 * ORDER MATTERS: the hook registered first is the outer one on an event. The actions come first, and
20 * hook only `ui.message`, matched to their own clicks (`fill:…`), which they answer; the sidebar's
21 * `ui.message` beneath answers every other click without `next`, so it would swallow theirs. Then the
22 * sidebar, so its `command.run {command: 'counterparts'}` hook answers `/counterparts …` without `next`, and
23 * the speak-first's `command.run` observer beneath it never sees that command; the sidebar writes `$.state`
24 * `typedIn` instead, which the speak-first reads. Reordering would change who sees what on every shared event.
25 */
26export const register: Register = (on, options) => {
27 actions(on, options)
28 sidebar(on, options)
29 speakFirst(on, options)
30}
31hooks/sidebar/hooks/actions.tsx 213 lines1/**
2 * WHAT ONLY THE FULL PLUGIN'S SIDEBAR DOES (2026-10-16), a hooks module of its
3 * own beside `register.tsx`, like `speak-first.tsx`: `full.tsx` registers it,
4 * the plugin directory's build never loads it (its module is `register.tsx`
5 * alone), so none of this is in that build.
6 *
7 * The directory trim (2026-10-14) took everything that acts out of the shared
8 * sidebar. These come back in the full build only, each acting as little as it
9 * can:
10 *
11 * - "Meet your counterpart", at the top of the body while core says the
12 * first meeting is not done or skipped: a click puts `/counterparts:meet`
13 * in the prompt box (`$.prompt.fill`), and the person presses Enter. Only
14 * into an empty box: a draft stays as it is, and the row says so; so does
15 * a box that would not take it (a dialog up).
16 * Terminal only, like the next: on the desktop `$.prompt.fill` may refuse
17 * (`no_composer`), unmeasured, so there the footer says the commands.
18 * - The footer's Dashboard line, the same way: a click puts
19 * `/counterparts:dashboard` in the prompt box (it starts the dashboard, or
20 * opens the browser on one already serving this store).
21 * - COUNTERPARTS ↗ on the terminal, a `Link` to the dashboard: the address
22 * is core's (`sidebar.json`'s `dashboard`, `src/adapters/sidebar-status.ts`),
23 * never built here, and drawn only when it names this machine. The desktop
24 * draws a link that is not https as plain text, so there the title stays
25 * words and the Dashboard line is the way.
26 * - The view and avatar switches in the footer, store-only: a click on
27 * `view` closes the pane to quiet; on `avatar`, the fox or none
28 * (`register.tsx#setSwitch`: `$.store.set` of `view` / `brain`, as
29 * `/counterparts quiet` and `/counterparts avatar` do). The brain is not
30 * back.
31 *
32 * Nothing here runs a command, calls a tool or submits a prompt. The rows are
33 * lines of the body's surface module (`body.tsx`), clicked as every row is
34 * (the engine's Buttons invert under the pointer, NOTES), posted as
35 * `{ click: 'fill:…' }`; this module's one hook answers those, and is
36 * registered before the sidebar so it is the outer one on `ui.message` (the
37 * sidebar's answers every other click without passing it on).
38 */
39
40import type { Elements, EngineInterface, Register } from 'claude-code'
41
42import { canMeet } from './feed'
43import type { FullPane, TitleLink } from './pane'
44import { clip } from './sections'
45import type { Line, Seg } from './sections'
46import { FILL_NOTE_MS, quiet, run } from './state'
47import { P } from './theme'
48import { cells } from './width'
49import { footerLines } from './words'
50
51/** What a click puts in the prompt box, by the key its row posts. */
52export const FILLS: Readonly<Record<string, string>> = {
53 'fill:meet': '/counterparts:meet',
54 'fill:dash': '/counterparts:dashboard',
55}
56
57export const MEET_ROW = 'Meet your counterpart'
58
59/**
60 * Only the address core writes is drawn as a link (`sidebar-status.ts#dashboardUrl`): 127.0.0.1 on
61 * a port, 1 to 65535. Anything else in the file draws the plain title.
62 */
63const DASHBOARD_AT = /^http:\/\/127\.0\.0\.1:([1-9]\d{0,4})\/?$/
64
65function isDashboardAddress(href: string): boolean {
66 const m = DASHBOARD_AT.exec(href)
67 return m !== null && Number(m[1]) <= 65535
68}
69
70// ── the engine, through `$` (a click's command, put in the prompt box) ─────
71
72/** Why the box did not take it, drawn under the row that was clicked until FILL_NOTE_MS passes. */
73async function noteFor($: EngineInterface, key: string, text: string | null): Promise<void> {
74 run.fillNote = text === null ? null : { key, text, at: await $.clock.now() }
75 $.ui.invalidate('ui.render')
76 if (text !== null) $.clock.after(FILL_NOTE_MS + 50, () => $.ui.invalidate('ui.render'))
77}
78
79/**
80 * The command into the prompt box, for the person to send: only into an empty box (a slash command
81 * goes at the start of a prompt, and a draft is the person's). Never submitted from here. Appended,
82 * not replaced: on an empty box the same, and a draft typed between the read and the fill is never
83 * wiped (the box then holds more than the command, and the note says so).
84 */
85async function fillPrompt($: EngineInterface, key: string, command: string): Promise<void> {
86 const draftNote = `Your draft is in the prompt box: send or clear it, then click again (or type ${command}).`
87 const box = await $.prompt.read()
88 const draft = box.text.trim()
89 if (draft === command) return noteFor($, key, null)
90 if (draft !== '') return noteFor($, key, draftNote)
91 const r = await $.prompt.fill({ text: command, mode: 'append' })
92 if (r.isFilled) {
93 if (r.text.trim() !== command) return noteFor($, key, draftNote)
94 if (key === 'fill:meet') run.meetFilledIn = run.session
95 return noteFor($, key, null)
96 }
97 return noteFor($, key, r.refusal === 'dialog' ? 'A dialog is open: close it, then click again.' : `The prompt box did not take it: type ${command}`)
98}
99
100// ── the pane's pieces (no `$`) ──────────────────────────────────────────────
101
102/**
103 * Whether the sidebar shows "Meet your counterpart" (as v0.2's "Start the 5-minute intro"): core
104 * says the meeting never started (`not_started`), was put off (`later`), or was offered and not
105 * finished (`offered`). Not once a meeting has begun in this very session, for `not_started` or
106 * `offered`: its speak-first went out here (`firedIn`, the mark `speak-first.tsx` writes), or a click
107 * on the row put `/counterparts:meet` in the box here (`filledIn`). Never in a folder where the
108 * meeting can't keep anything (`canMeet`), and never for an unknown state.
109 */
110export function meetShows(meet: string, folderMode: string, firedIn: string | null, session: string, filledIn: string | null = null): boolean {
111 if (!canMeet(folderMode)) return false
112 const begunHere = session !== '' && (firedIn === session || filledIn === session)
113 if (meet === 'not_started' || meet === 'offered') return !begunHere
114 return meet === 'later'
115}
116
117/** COUNTERPARTS as a link to the dashboard: only to an address on this machine. */
118export function titleLink(els: Pick<Elements['terminal'], 'Link'>, href: string | null): TitleLink {
119 if (href === null || !isDashboardAddress(href)) return null
120 const { Link } = els
121 return (words: JSX.Element[]) => <Link href={href}>{words}</Link>
122}
123
124/** A note, word-wrapped to `w`, on the lines of the row it is about (a click on it is that row's). */
125function noteLines(note: string, w: number, key: string): Line[] {
126 const out: Line[] = []
127 let cur = ''
128 for (const word of note.split(/\s+/).filter(Boolean)) {
129 if (cur !== '' && [...`${cur} ${word}`].length > w) {
130 out.push({ segs: [{ t: clip(cur, w), c: P.accent2 }], key })
131 cur = word
132 } else cur = cur === '' ? word : `${cur} ${word}`
133 }
134 if (cur !== '') out.push({ segs: [{ t: clip(cur, w), c: P.accent2 }], key })
135 return out
136}
137
138/** The Meet row, a note under it when the box did not take the command, and a blank row. */
139export function meetLines(w: number, note: string | null): Line[] {
140 return [
141 { segs: [{ t: clip(MEET_ROW, w), c: P.accent, b: true }], key: 'fill:meet' },
142 ...(note === null ? [] : noteLines(note, w, 'fill:meet')),
143 { segs: [] },
144 ]
145}
146
147/** Pieces cut to `w` cells: a row wider than its box would wrap and move every row under it off its click. */
148function fitSegs(segs: readonly Seg[], w: number): Seg[] {
149 const out: Seg[] = []
150 let used = 0
151 for (const s of segs) {
152 if (used >= w) break
153 const t = cells(s.t) <= w - used ? s.t : clip(s.t, w - used)
154 out.push({ ...s, t })
155 used += cells(t)
156 }
157 return out
158}
159
160/**
161 * One switch: `view ● sidebar ○ quiet`, the one that is on lit; a click on the row turns it to the other.
162 * Narrower than that (an inline pane), the label goes first, then the words are cut.
163 */
164function switchLine(label: string, opts: readonly [string, string][], on: string, key: string, w: number): Line {
165 const dots: Seg[] = []
166 for (const [value, word] of opts) {
167 const lit = value === on
168 dots.push({ t: ' ', c: P.mid })
169 dots.push({ t: lit ? '●' : '○', c: lit ? P.accent : P.dim })
170 dots.push({ t: ` ${word}`, c: lit ? P.hi : P.dim })
171 }
172 const whole: Seg[] = [{ t: label, c: P.mid }, ...dots]
173 const width = (ss: readonly Seg[]): number => ss.reduce((n, s) => n + cells(s.t), 0)
174 return { segs: width(whole) <= w ? whole : fitSegs(dots.slice(1), w), key }
175}
176
177/**
178 * The full build's footer: the rule (a blank row on the desktop), the instructions as the
179 * directory's footer says them less the hide line (the view switch does it), and the intro only
180 * while `intro` (the meeting waits but the Meet row is not drawn: core's state unknown, a folder
181 * paused), the Dashboard line clickable, then the view and avatar switches.
182 */
183export function footLines(s: { fit: number; w: number; prose: boolean; paused: boolean; view: string; avatar: string; note: string | null; intro: boolean; fills: boolean }): Line[] {
184 const out: Line[] = [s.prose ? { segs: [] } : { segs: [{ t: '─'.repeat(s.w), c: P.faint }] }]
185 for (const l of footerLines(s.fit, s.paused, { intro: s.intro, fox: false, hide: false })) {
186 const segs: Seg[] = [...(l.label === '' ? [] : [{ t: l.label, c: P.mid }]), ...(l.how === '' ? [] : [{ t: l.how, c: P.hi }])]
187 const key = s.fills && l.of === FILLS['fill:dash'] ? 'fill:dash' : undefined
188 out.push(key === undefined ? { segs } : { segs, key })
189 }
190 if (s.note !== null) out.push(...noteLines(s.note, s.fit, 'fill:dash'))
191 out.push(switchLine('view', [['sidebar', 'sidebar'], ['quiet', 'quiet']], s.view === 'quiet' ? 'quiet' : 'sidebar', s.view === 'quiet' ? 'set:view:sidebar' : 'set:view:quiet', s.w))
192 out.push(switchLine('avatar', [['fox', 'animal'], ['off', 'off']], s.avatar === 'off' ? 'off' : 'fox', s.avatar === 'off' ? 'set:avatar:fox' : 'set:avatar:off', s.w))
193 return out
194}
195
196export const FULL_PANE: FullPane = { titleLink, meetShows, meetLines, footLines }
197
198// ── the hook ────────────────────────────────────────────────────────────────
199
200export const register: Register = on => {
201 // The pane draws these pieces from here on (`state.ts#run.full`): this registration is what turns them on.
202 run.full = FULL_PANE
203 run.fillNote = null
204 // A click on a row that puts a command in the prompt box. Answered here, never passed on.
205 on('ui.message', { data: { click: ['fill:meet', 'fill:dash'] } }, async ($, e) => {
206 const key = (e.data as { click?: unknown } | null)?.click
207 const command = typeof key === 'string' ? FILLS[key] : undefined
208 // Off the hook's own path: the fill goes through the other plugins' prompt.fill hooks.
209 if (typeof key === 'string' && command !== undefined) $.clock.after(0, () => quiet(fillPrompt($, key, command)))
210 return {}
211 })
212}
213hooks/sidebar/hooks/register.tsx 1526 lines1/**
2 * The Counterparts sidebar (v1, the directory trim of 2026-10-14): what
3 * memory is doing, in 35 columns. It shows; it does not act.
4 *
5 * The fox (or no avatar) above the title, the day and the count; then what
6 * was put in front of Claude for the last message (Memories, said in full;
7 * Subconscious, titles only), what this session saved, how often each
8 * mechanism fired today, and the last dream; then a footer of instructions:
9 * how to start the intro, open the dashboard, pause memory here, or hide the
10 * pane (`words.ts#footerLines`). Closed (`quiet`), it is only a dim tail under
11 * the prompt, ending with how to open it again. `/counterparts` opens it and
12 * sets the avatar and the theme. The design is the round-3 mockups Mike chose
13 * on 2026-10-10 (`~/counterparts-notes/mockups/2026-10-10-mod-round3/`);
14 * ../NOTES.md says where the build differs and why. The fuller v0.2 (the
15 * brain, the folder switch, the intro and dashboard buttons) is kept on the
16 * branch `sidebar-full-0.3.22`.
17 *
18 * Where things come from (no network, 2026-10-14):
19 * - the status file Counterparts writes for it (`sidebar.json` beside the
20 * configuration, next to `scopes.json`; `./status.ts`), read-only, on a
21 * timer while the pane shows: which memory wrote it (another one's
22 * numbers are never shown), day and count, times fired today, the last
23 * dream, the activity log's newest rows (a mechanism's firings, this
24 * session's rows on a resume) and the memories they name (opened in
25 * place). Core's own processes write it: the worker after each turn, the
26 * memory server after its tool calls and when the log moves;
27 * - the scope registry file the hooks read (`scopes.json` beside the
28 * configuration, read-only, `./scopes.ts`): where this folder stands, for
29 * the paused banner and the status line;
30 * - this session: the recall block the classic UserPromptSubmit hook
31 * injects (Memories, Subconscious), and `tool.call` on remember (or
32 * its old name note) / session_end (Saved) and on recall by id (`↗ opened`).
33 *
34 * No command is run, no tool is called, no process is started and nothing is
35 * fetched from here (the directory build's policy read, 2026-10-14), and
36 * nothing is a link: the footer says `/counterparts:dashboard`. The speak-first, which submits one prompt once per install, is
37 * `speak-first.tsx`, a hooks module of its own that only the full build
38 * carries. So is `actions.tsx` (2026-10-16), which gives the full build's pane
39 * the Meet row, the title's link to the dashboard and a footer of clickable
40 * rows (`state.ts#run.full`); with it unset, as in the directory's build, none
41 * of them is drawn and a `set:` click does nothing.
42 *
43 * The engine lets `$` pass only to functions declared at the top of this
44 * file, reads a `$.state` source only from an atom declared here, and reads
45 * the surface modules (`<Client module=…>`) off this file's source, so those
46 * live here: every function that touches the engine, the atoms, the hooks.
47 * Everything else is beside it, with no `$`. The shared core: `state.ts`
48 * (timings, `run`), `words.ts` (what the sidebar says), `status.ts` (the
49 * status file, read), `feed.ts` (the log's rows and the recall block, read), `sections.ts` (the body's
50 * sections, laid out), `mechanisms.ts`, `scopes.ts`, `theme.ts` (the colours).
51 * The views: `pane.tsx` (the pane's tree on every surface), `desktop.tsx` (the
52 * header), `fox.ts` with `fox-art.ts` and `cells.ts` (the fox), `width.ts`
53 * and `tail.ts`, and `body.tsx` (the body, a Client surface module).
54 */
55
56import { atom, read, update } from 'claude-code'
57import type { EngineInterface, Register } from 'claude-code'
58
59import type {
60 SidebarAvatar,
61 SidebarDream,
62 SidebarLatest,
63 SidebarMind,
64 SidebarRow,
65 SidebarSaved,
66 SidebarScope,
67 SidebarTheme,
68 SidebarToday,
69 SidebarView,
70} from '../types'
71import type { BodyProps } from './body'
72import { header } from './desktop'
73import {
74 RULES,
75 classify,
76 dateOf,
77 decisionFor,
78 firingIds,
79 firingTitle,
80 firstSentence,
81 mechFirings,
82 mechsOf,
83 openedIds,
84 otherStore,
85 ourTool,
86 parseRecallBlock,
87 parseGlance,
88 parseOnboardingMarker,
89 parseStoreMarker,
90 savedItems,
91 savedSince,
92 savesMemory,
93 surfacedIds,
94 titled,
95} from './feed'
96import type { DashDream, DashEvent, Firing, RecallBlock } from './feed'
97import { MECHS, mechById } from './mechanisms'
98import type { MechId } from './mechanisms'
99import {
100 IMAGE_COLS,
101 IMAGE_ROWS,
102 IMAGE_X0,
103 STAGE_COLS,
104 STAGE_MIN_PANE_ROWS,
105 TIER_ENV,
106 advance,
107 fineCells,
108 halfCells,
109 newDirector,
110 normDetail,
111 pickTier,
112 PNG_DIRS,
113 pngName,
114 runs,
115 stage,
116 stageRows,
117 stepKey,
118 trigger,
119} from './fox'
120import type { FoxDetail, FoxEvent, FoxTier, Step } from './fox'
121import { foxSvg } from './fox-svg'
122import { footer, footerRows, frame, pausedBanner, plainBody } from './pane'
123import type { PaneEls } from './pane'
124import { lookup, parentOf, parseRegistry, settingsHookConfig } from './scopes'
125import type { RegistryMode } from './scopes'
126import { layoutBody } from './sections'
127import type { Line } from './sections'
128import {
129 FILL_NOTE_MS,
130 FIRING_MS,
131 MEET_FLAG,
132 NAMES_NOTHING,
133 OPEN_COLUMNS,
134 POLL_IDLE_MS,
135 POLL_MS,
136 ROOMY_ROWS,
137 SCOPES_FILE_TTL_MS,
138 SCOPE_RECHECK_MS,
139 UNKNOWN_SCOPE,
140 quiet,
141 run,
142} from './state'
143import { NOT_CARRIED, STATUS_FILE, keepsBefore, memoryIn, parseStatus, rowsNamed, rowsSince } from './status'
144import type { Status } from './status'
145import { CLASSIC_HINT, NARROW_HINT, TAIL_HINT, TAIL_SPARE, narrowHint, quietTail } from './tail'
146import { P, SURFACE, applyTheme, normTheme } from './theme'
147import { cells } from './width'
148import {
149 bodyOf,
150 firedIn,
151 isAbsolutePath,
152 isPaused,
153 memoriesCount,
154 memoryMeta,
155 normAvatar,
156 normView,
157 resumeWords,
158 statusFor,
159 storedWords,
160 words,
161} from './words'
162
163// ── constants ───────────────────────────────────────────────────────────────
164
165const PANE = 'counterparts'
166const TITLE = 'Counterparts'
167
168// ── state (the contract: ../types/index.d.ts) ──────────────────────────────
169
170const pulseA = atom({ plugin: 'counterparts', key: 'pulse' } as const, null)
171const dashA = atom({ plugin: 'counterparts', key: 'dash' } as const, 'unknown')
172const mindA = atom({ plugin: 'counterparts', key: 'mind' } as const, null)
173const savedA = atom({ plugin: 'counterparts', key: 'saved' } as const, [])
174const todayA = atom({ plugin: 'counterparts', key: 'today' } as const, null)
175const dreamA = atom({ plugin: 'counterparts', key: 'dream' } as const, null)
176const openA = atom({ plugin: 'counterparts', key: 'open' } as const, null)
177const mechA = atom({ plugin: 'counterparts', key: 'mech' } as const, null)
178const focusA = atom({ plugin: 'counterparts', key: 'focus' } as const, null)
179const latestA = atom({ plugin: 'counterparts', key: 'latest' } as const, null)
180const firingA = atom({ plugin: 'counterparts', key: 'firing' } as const, null)
181const scopeA = atom({ plugin: 'counterparts', key: 'scope' } as const, UNKNOWN_SCOPE)
182const viewA = atom({ plugin: 'counterparts', key: 'view' } as const, 'sidebar')
183const brainA = atom({ plugin: 'counterparts', key: 'brain' } as const, 'fox')
184const themeA = atom({ plugin: 'counterparts', key: 'theme' } as const, 'tron')
185const placedA = atom({ plugin: 'counterparts', key: 'placed' } as const, false)
186/** The person ran `/counterparts …` in this session: written here, read by `speak-first.tsx` (which never sees it). */
187const typedInA = atom({ plugin: 'counterparts', key: 'typedIn' } as const, null)
188
189// ── the engine, through `$` ────────────────────────────────────────────────
190
191/**
192 * The status file, read as it stands (`status.ts`): found beside the
193 * registry (`scopesFile`, the hooks' own configuration's folder), read again
194 * only when its size or time changed, and kept for this module life. Null:
195 * not there (no session has written it yet), unreadable, or not a version
196 * this sidebar reads. Read only, no permission asked, and no network.
197 */
198async function readStatus($: EngineInterface): Promise<Status | null> {
199 const scopes = await scopesFile($, false)
200 if (scopes === null) return null
201 const file = `${parentOf(scopes)}/${STATUS_FILE}`
202 if (file !== run.statusFile) {
203 run.statusFile = file
204 run.statusStamp = ''
205 run.status = null
206 }
207 try {
208 if (!(await $.fs.exists(file))) {
209 run.statusStamp = ''
210 run.status = null
211 return null
212 }
213 const st = await $.fs.stat(file)
214 const stamp = `${String(st.size)}:${String(st.mtimeMs)}`
215 if (stamp === run.statusStamp && run.status !== null) return run.status
216 const text = await $.fs.read(file)
217 const parsed = typeof text === 'string' ? parseStatus(text) : null
218 // A file caught half-written (never by its writers, who rename a whole one in) or of another version:
219 // the last good one stands until the next read.
220 if (parsed === null) return run.status
221 run.statusStamp = stamp
222 // Two writers racing: an older file of the same store over a newer one is not shown (the log only grows),
223 // unless it is newer by more than a race makes it — a store put back (`keepsBefore`).
224 const before = run.status
225 if (keepsBefore(before, parsed)) return before
226 run.status = parsed
227 return parsed
228 } catch {
229 return run.status
230 }
231}
232
233/**
234 * WHICH STORE (core #459): the status file must be the store's this session's
235 * wake named. Both known and different: everything shown from it is dropped
236 * (the pulse, today's counts, the last dream) and nothing more is shown until
237 * it matches again; the Mechanisms section says so. Either unknown (no marker
238 * yet, an older core, a store with no id yet): carry on.
239 */
240async function storeMatches($: EngineInterface, s: Status): Promise<boolean> {
241 const other = otherStore(run.wakeStore, s.storeId)
242 if (other !== run.foreign) {
243 run.foreign = other
244 if (other) {
245 await update($, dashA, () => 'other')
246 await update($, pulseA, () => null)
247 await update($, todayA, () => null)
248 await update($, dreamA, () => null)
249 }
250 // Either way the next look takes all of it again, from the right store.
251 run.lastSeq = -1
252 }
253 return !other
254}
255
256async function refreshStatus($: EngineInterface): Promise<void> {
257 $.ui.status(statusFor(await read($, scopeA)))
258}
259
260/** The mechanisms new rows prove: the header's dot lights in the newest one's colour for a moment (`firing`). */
261async function fire($: EngineInterface, ids: readonly MechId[]): Promise<void> {
262 if (ids.length === 0) return
263 const now = await $.clock.now()
264 await update($, firingA, () => ({ ids: [...ids], at: now }))
265 $.clock.after(FIRING_MS + 100, () => $.ui.invalidate('ui.render'))
266}
267
268async function setLatest($: EngineInterface, text: string, mech: MechId, body?: string): Promise<void> {
269 await setLatestAt($, text, mech, await $.clock.now(), body)
270}
271
272async function setLatestAt($: EngineInterface, text: string, mech: MechId, at: number, body?: string): Promise<void> {
273 const next: SidebarLatest = body === undefined ? { text, mech, at } : { text, mech, at, body }
274 await update($, latestA, l => (l !== null && l.at > at ? l : next))
275}
276
277/** Day, count, and when the file was written. */
278async function showPulse($: EngineInterface, s: Status): Promise<void> {
279 const before = await read($, pulseA)
280 const p = s.pulse
281 if (before === null || before.day !== p.day || before.memories !== p.memories || before.lastSeq !== p.lastSeq || before.at !== s.writtenAt) {
282 await update($, pulseA, () => ({ day: p.day, memories: p.memories, lastSeq: p.lastSeq, at: s.writtenAt }))
283 }
284}
285
286/**
287 * Times each mechanism fired today, as the file counted them (`firedToday`,
288 * rows on the store's calendar day). A file written before this clock's
289 * midnight counts a day that is over: none yet today, until the next file.
290 */
291async function showToday($: EngineInterface, s: Status): Promise<void> {
292 const now = await $.clock.now()
293 const date = dateOf(now)
294 const counts: SidebarToday['counts'] = {}
295 const over = dateOf(s.writtenAt) !== date
296 for (const m of MECHS) {
297 const v = s.today?.counts[m.id]
298 counts[m.id] = typeof v === 'number' ? (over ? 0 : v) : m.notBuilt === true ? null : 0
299 }
300 const next: SidebarToday = { date: over || s.today === null ? date : s.today.date, counts, source: 'dashboard' as const }
301 const before = await read($, todayA)
302 if (before === null || JSON.stringify(before) !== JSON.stringify(next)) await update($, todayA, () => next)
303}
304
305/**
306 * The newest dream, in its own voice: its first sentence and what follows. No
307 * "what changed that night" counts (Mike, 2026-10-10): the room goes to the
308 * dream itself.
309 */
310async function showDream($: EngineInterface, s: Status): Promise<void> {
311 const d = s.dreams[0]
312 if (d === undefined || typeof d.journal !== 'string' || d.journal.trim() === '') {
313 if ((await read($, dreamA)) !== null) await update($, dreamA, () => null)
314 return
315 }
316 const atOf = rowsNamed(s, 'dream.journaled').find(e => e.subject === d.id)?.at ?? null
317 const { first, rest } = firstSentence(d.journal)
318 const next: SidebarDream = { id: d.id, at: atOf, date: d.date, first, rest }
319 const before = await read($, dreamA)
320 if (before === null || before.id !== next.id || before.at !== next.at || before.rest !== next.rest) {
321 await update($, dreamA, () => next)
322 }
323 // A dream newer than anything this session did is the newest thing (the tail).
324 const at = next.at
325 if (at !== null) {
326 const latest = await read($, latestA)
327 if (latest === null || latest.at < at) await setLatestAt($, words('dreamed', next.first), 'dreaming', at)
328 }
329}
330
331/**
332 * One look at the status file. A new one: the pulse, today's counts and the
333 * last dream as it says them; the rows newer than the last look's light the
334 * header's dot and move the fox. Says whether anything new arrived.
335 */
336async function poll($: EngineInterface): Promise<boolean> {
337 if (run.polling) return false
338 run.polling = true
339 try {
340 const s = await readStatus($)
341 if (s === null) {
342 // No file yet: the first session's memory server or its first turn writes one.
343 if ((await read($, dashA)) !== 'down') await update($, dashA, () => 'down')
344 return false
345 }
346 if (!(await storeMatches($, s))) return false
347 if ((await read($, dashA)) !== 'up') await update($, dashA, () => 'up')
348 // Every look, the same file or not: past this clock's midnight its counts are yesterday's.
349 await showToday($, s)
350 if (run.lastSeq >= 0 && s.pulse.lastSeq === run.lastSeq && (await read($, pulseA))?.at === s.writtenAt) return false
351 const first = run.lastSeq < 0
352 const events = first ? [] : rowsSince(s, run.lastSeq)
353 run.lastSeq = s.pulse.lastSeq
354 await showPulse($, s)
355 await showDream($, s)
356 if (!run.seeded) {
357 run.seeded = true
358 await seedSession($, s).catch(() => undefined)
359 }
360 // Memories still named by the words Claude was shown: their titles, now the turn's row is in.
361 const mind = await read($, mindA)
362 if (mind !== null && mind.surfaced.some(r => r.id === null)) await titleSurfaced($, s, mind.turn)
363 const rows = events.map(e => classify(e, run.session, run.startedAt)).filter((r): r is SidebarRow => r !== null)
364 const lit = [...new Set(rows.filter(r => r.who !== 'other').sort((a, b) => b.at - a.at).flatMap(mechsOf))]
365 await fire($, lit)
366 // The fox dreams while a dream runs (one begun, none ended since), in any session or at night.
367 const dreams = events.filter(e => e.name === 'dream.begun' || e.name === 'dream.journaled' || e.name === 'dream.changed' || e.name === 'dream.undone')
368 const lastDream = dreams.sort((a, b) => a.seq - b.seq).at(-1)
369 if (lastDream !== undefined) await foxEvent($, lastDream.name === 'dream.begun' ? 'dream' : 'dreamEnd')
370 // A save for this session the memory tools' own hook did not already write down (see `savedSince`).
371 if (run.saving === 0 && savedSince(events, run.session, stage.director?.saveAt ?? -Infinity, await $.clock.now())) await foxEvent($, 'note')
372 return first || events.length > 0
373 } catch {
374 return false
375 } finally {
376 run.polling = false
377 }
378}
379
380/** The pane is placed and the one shown: the only time the status file is read. */
381async function paneShown($: EngineInterface): Promise<boolean> {
382 try {
383 const pane = (await $.ui.panes()).find(p => p.id === PANE)
384 return pane !== undefined && pane.isShown && pane.isPlaced
385 } catch {
386 return false
387 }
388}
389
390/** Reads the status file while the pane shows, faster while things happen; stops when it doesn't (a drawing starts it again). */
391async function pollLoop($: EngineInterface): Promise<void> {
392 if ((await read($, viewA)) !== 'sidebar' || !(await paneShown($))) {
393 run.pollArmed = false
394 stopStage()
395 return
396 }
397 const moved = await poll($)
398 await refreshScope($)
399 run.quietPolls = moved ? 0 : run.quietPolls + 1
400 $.clock.after(run.quietPolls >= 4 ? POLL_IDLE_MS : POLL_MS, () => quiet(pollLoop($)))
401}
402
403function armPolling($: EngineInterface, delayMs: number): void {
404 if (run.pollArmed) return
405 run.pollArmed = true
406 $.clock.after(delayMs, () => quiet(pollLoop($)))
407}
408
409// ── this session's own: the recall block, the memory tools ─────────────────
410
411/**
412 * The recall block for the person's message: Memories (the "Came to mind"
413 * lane, said in full) and Subconscious (the "Quietly available" lane). The
414 * block names a surfaced memory by its gist only; its title comes from the
415 * turn's decision row (its `surfaced` ids) once the status file carries it,
416 * at the next look. Until then the gist stands: it is the text Claude was shown.
417 */
418async function onRecallBlock($: EngineInterface, block: RecallBlock): Promise<void> {
419 if (block.surfaced.length + block.footnotes.length === 0) return
420 const at = await $.clock.now()
421 const mind: SidebarMind = {
422 turn: block.turn,
423 at,
424 surfaced: block.surfaced.map(g => ({ id: null, title: g })),
425 footnotes: block.footnotes.map(f => ({ id: f.id, title: f.title })),
426 }
427 await update($, mindA, () => mind)
428 await update($, openA, o => (o !== null && (o.key.startsWith('mem:') || o.key.startsWith('sub:')) ? null : o))
429 const firstSurfaced = mind.surfaced[0]
430 const firstFoot = mind.footnotes[0]
431 if (firstSurfaced !== undefined) await setLatest($, words('remembered', firstSurfaced.title), 'retrieval')
432 else if (firstFoot !== undefined) await setLatest($, words('subconscious', firstFoot.title), 'retrieval')
433 await fire($, ['retrieval'])
434 await foxEvent($, 'came')
435 if (block.surfaced.length > 0 && run.status !== null && !run.foreign) await titleSurfaced($, run.status, block.turn)
436}
437
438/** The surfaced memories' ids and titles, from the turn's decision row in the status file, when it is there yet. */
439async function titleSurfaced($: EngineInterface, s: Status, turn: number): Promise<void> {
440 if (run.session === '') run.session = await $.session.id()
441 const row = decisionFor(rowsNamed(s, 'recall.decision', 40), run.session, turn)
442 if (row === undefined) return
443 const ids = surfacedIds(row)
444 const mind = await read($, mindA)
445 if (mind === null || mind.turn !== turn) return
446 const surfaced = mind.surfaced.map((r, i) => ({ id: ids[i] ?? r.id, title: memoryTitle(s, ids[i]) ?? r.title }))
447 await update($, mindA, m => (m === null || m.turn !== turn ? m : { ...m, surfaced }))
448 const first = surfaced[0]
449 const latest = await read($, latestA)
450 if (first !== undefined && latest !== null && latest.text.startsWith('remembered: ') && latest.at >= mind.at) {
451 await update($, latestA, l => (l === null ? l : { ...l, text: words('remembered', first.title) }))
452 }
453}
454
455/** A memory's title, from the status file, or null. */
456function memoryTitle(s: Status | null, id: string | null | undefined): string | null {
457 if (id === null || id === undefined) return null
458 const m = memoryIn(s, id)
459 return m !== null && m.title !== '' ? m.title : null
460}
461
462/**
463 * On the first look, when this module has seen nothing of the session yet (a
464 * resumed session, a pane opened after a reload that lost nothing but the
465 * module): Memories, Subconscious and Saved from the status file's rows for
466 * the session. The session is this one; a preview or a check may name another
467 * with `COUNTERPARTS_SIDEBAR_SESSION` (the term-loop shots do, since their
468 * session sends no message).
469 */
470async function seedSession($: EngineInterface, s: Status): Promise<void> {
471 const preview = ((await $.env.get('COUNTERPARTS_SIDEBAR_SESSION')) ?? '').trim()
472 // The pane can draw (and this run, once a module life) before session.start has named the session.
473 const session = preview !== '' ? preview : run.session !== '' ? run.session : await $.session.id().catch(() => '')
474 if (session === '') return
475 const [mind0, saved0] = await Promise.all([read($, mindA), read($, savedA)])
476 const ofSession = (e: DashEvent): boolean => e.detail?.some(d => (d.key === 'session' || d.key === 'actorId') && d.value === session) === true
477 if (mind0 === null) {
478 const decision = rowsNamed(s, 'recall.decision').filter(ofSession).find(e => classify(e)?.mechs.includes('retrieval') === true)
479 if (decision !== undefined) {
480 const surfaced = surfacedIds(decision)
481 let footnotes: string[] = []
482 try {
483 const list: unknown = JSON.parse(decision.detail?.find(d => d.key === 'footnotes')?.value ?? '[]')
484 if (Array.isArray(list)) footnotes = list.map(x => (x as { id?: unknown })?.id).filter((x): x is string => typeof x === 'string')
485 } catch {
486 footnotes = []
487 }
488 const ref = (id: string) => ({ id, title: memoryTitle(s, id) ?? id })
489 const turn = Number(decision.detail?.find(d => d.key === 'turn')?.value ?? 0)
490 const mind: SidebarMind = {
491 turn: Number.isFinite(turn) ? turn : 0,
492 at: decision.at,
493 surfaced: surfaced.map(ref),
494 footnotes: footnotes.map(ref),
495 }
496 if (mind.surfaced.length + mind.footnotes.length > 0) await update($, mindA, m => m ?? mind)
497 }
498 }
499 if (saved0.length === 0) {
500 const settles = rowsNamed(s, 'contradiction.settled')
501 const mine = rowsNamed(s, 'gate.deposit').filter(e => ofSession(e) && Number(e.detail?.find(d => d.key === 'accepted')?.value ?? 0) > 0)
502 const items = mine.slice(0, 12).map((e): SidebarSaved | null => {
503 const row = classify(e)
504 const id = row?.memory?.id ?? null
505 if (id === null) return null
506 const settle = settles.find(x => ofSession(x) && titled(x.detail?.find(d => d.key === 'holds')?.value).id === id && x.detail?.some(d => d.key === 'how' && d.value !== 'open') === true)
507 const over = settle === undefined ? null : titled(settle.detail?.find(d => d.key === 'over')?.value)
508 const title = memoryTitle(s, id) ?? row?.memory?.title ?? id
509 const replaces = over === null || over.id === null ? null : (memoryTitle(s, over.id) ?? over.title)
510 return { key: `seq:${String(e.seq)}`, id, title, at: e.at, replaces, replacesId: over?.id ?? null, kind: over === null ? 'new' : 'update' }
511 })
512 const list = items.filter((x): x is SidebarSaved => x !== null).sort((a, b) => b.at - a.at)
513 if (list.length > 0) await update($, savedA, sv => (sv.length === 0 ? list : sv))
514 }
515 // The newest of what was found, as the tail says it, unless something newer is known.
516 const [mind, saved] = await Promise.all([read($, mindA), read($, savedA)])
517 const said = mind?.surfaced[0] !== undefined ? words('remembered', mind.surfaced[0].title) : mind?.footnotes[0] !== undefined ? words('subconscious', mind.footnotes[0].title) : null
518 const first = saved[0]
519 if (first !== undefined && (mind === null || first.at > mind.at)) await setLatestAt($, storedWords(first.title), 'salience', first.at, bodyOf(first))
520 else if (mind !== null && said !== null) await setLatestAt($, said, 'retrieval', mind.at)
521}
522
523/** What a memory tool saved: "Saved this session", newest first; an update's old title from the status file when it has it. */
524async function onSaved($: EngineInterface, items: readonly SidebarSaved[]): Promise<void> {
525 if (items.length === 0) return
526 await update($, savedA, list => [...[...items].reverse(), ...list])
527 await foxEvent($, 'note')
528 const first = items[0]
529 if (first !== undefined) {
530 await setLatest($, items.length === 1 ? storedWords(first.title) : storedWords(first.title, items.length), 'salience', bodyOf(first))
531 }
532 await fire($, items.some(i => i.kind === 'update') ? ['salience', 'reconsolidation'] : ['salience'])
533 for (const it of items) {
534 const title = memoryTitle(run.foreign ? null : run.status, it.replacesId)
535 if (title === null) continue
536 await update($, savedA, list => list.map(x => (x.key === it.key ? { ...x, replaces: title } : x)))
537 }
538}
539
540/** A `recall` that opened memories by address: the footnotes it names get `↗ opened`. */
541async function onOpened($: EngineInterface, ids: readonly string[], handle: string | null): Promise<void> {
542 const mind = await read($, mindA)
543 if (mind === null) return
544 const hit = (f: { id: string | null; title: string }): boolean => (f.id !== null && ids.includes(f.id)) || (handle !== null && f.title.trim().toLowerCase() === handle.toLowerCase())
545 if (!mind.footnotes.some(hit) && !mind.surfaced.some(hit)) return
546 await update($, mindA, m =>
547 m === null ? m : { ...m, footnotes: m.footnotes.map(f => (hit(f) ? { ...f, opened: true } : f)), surfaced: m.surfaced.map(r => (hit(r) ? { ...r, opened: true } : r)) },
548 )
549 const named = mind.footnotes.find(hit) ?? mind.surfaced.find(hit)
550 if (named !== undefined) await setLatest($, words('opened', named.title), 'retrieval')
551}
552
553// ── a click in the body ────────────────────────────────────────────────────
554
555/**
556 * Opens a memory in place, every time, whatever its length: its title, text
557 * and kind from the status file (which carries the memories its rows name,
558 * each text's start). A click never opens the dashboard by itself (Mike,
559 * 2026-10-10): the layout shows up to 20 lines and ends a longer text, or one
560 * the file cut, with `more`, the one link to the memory's card there. One the
561 * file does not carry shows its title and that link. Clicked again, it closes.
562 */
563async function openMemory($: EngineInterface, key: string, id: string | null, fallback: string): Promise<void> {
564 const cur = await read($, openA)
565 if (cur !== null && cur.key === key) {
566 await update($, openA, () => null)
567 return
568 }
569 const at = await $.clock.now()
570 if (id === null) {
571 // Named only by the words Claude was shown (the turn's row not read yet): those words, in place.
572 await update($, openA, () => ({ key, id: null, status: 'ready' as const, title: fallback, text: '', meta: null, at }))
573 return
574 }
575 const s = run.foreign ? null : await readStatus($)
576 const m = memoryIn(s, id)
577 if (m === null) {
578 const gone = s !== null && id in s.memories
579 await update($, openA, () => ({ key, id, status: 'ready' as const, title: fallback, text: gone ? 'no longer in memory' : NOT_CARRIED, meta: null, at, cut: !gone }))
580 return
581 }
582 await update($, openA, () => ({ key, id, status: 'ready' as const, title: m.title || fallback, text: m.text.trim(), meta: memoryMeta(m), at, cut: m.cut }))
583}
584
585/**
586 * A mechanism in "Mechanisms today": what its recent firings were about, from
587 * its panel rows in the status file, grouped by what and when: the memories
588 * they name, with their titles, and for a dream's rows the dream's own changes
589 * (which name the memories its row only counts). A firing that names nothing
590 * is left out (`feed.ts#mechFirings`).
591 */
592async function openMech($: EngineInterface, id: MechId): Promise<void> {
593 const cur = await read($, mechA)
594 await update($, openA, o => (o !== null && o.key.startsWith('ev:') ? null : o))
595 if (cur !== null && cur.id === id) {
596 await update($, mechA, () => null)
597 return
598 }
599 const at = await $.clock.now()
600 const s = run.foreign ? null : await readStatus($)
601 if (s === null) {
602 await update($, mechA, () => ({ id, status: 'error' as const, events: [], at }))
603 return
604 }
605 const panel = s.panels[id] ?? []
606 const dreams = panel.some(e => e.name.startsWith('dream.')) ? s.dreams : []
607 let firings = mechFirings(panel, id, dreams, 8)
608 // The panel shows four lines, its repeats merged into one (Salience's deposits all narrate alike, so one
609 // memory). A mechanism that fired today and names fewer than three there reads the file's other rows too.
610 const want = Math.min(3, (await read($, todayA))?.counts[id] ?? 0)
611 if (firings.length < want) firings = deeperFirings(s, id, panel, dreams)
612 const titles: Record<string, string> = {}
613 for (const x of new Set(firings.flatMap(firingIds))) {
614 const t = memoryTitle(s, x)
615 if (t !== null) titles[x] = t
616 }
617 const events = firings.flatMap(f => {
618 const title = firingTitle(f, titles)
619 return title === null ? [] : [{ key: f.key, seq: f.seq, at: f.at, word: f.word, title, memoryId: f.memoryId, text: f.text }]
620 })
621 await update($, mechA, () => ({ id, status: 'ready' as const, events, at }))
622}
623
624/** A mechanism's firings from its panel's rows and the file's rows of its events: only when the panel named too few. */
625function deeperFirings(s: Status, id: MechId, panel: readonly DashEvent[], dreams: readonly DashDream[]): Firing[] {
626 const names = new Set(RULES.filter(r => r.mech === id && !NAMES_NOTHING.has(r.name)).map(r => r.name))
627 const seen = new Set<number>()
628 const rows = [...panel, ...s.events.filter(e => names.has(e.name))].filter(e => (seen.has(e.seq) ? false : (seen.add(e.seq), true)))
629 return mechFirings(rows, id, dreams, 8)
630}
631
632/** A click on a row of the body, by the key the layout gave it. */
633async function clickBody($: EngineInterface, key: string): Promise<void> {
634 // The full build's switches (`actions.tsx` draws them; never drawn in the directory's build, never acted on there).
635 if (key.startsWith('set:')) {
636 if (run.full !== null) await setSwitch($, key)
637 return
638 }
639 // A command for the prompt box: `actions.tsx`'s own hook answers it, outside this one.
640 if (key.startsWith('fill:')) return
641 // (The `more` that ends a cut text is plain words, with no link: a click on it is its row's.)
642 if (key.startsWith('head:')) {
643 const section = key.slice(5)
644 await update($, focusA, f => (f === section ? null : section))
645 return
646 }
647 if (key === 'dream' || key === 'glance') {
648 const at = await $.clock.now()
649 const cur = await read($, openA)
650 await update($, openA, () => (cur?.key === key ? null : { key, id: null, status: 'ready' as const, title: null, text: '', meta: null, at }))
651 return
652 }
653 if (key.startsWith('mech:')) {
654 const id = key.slice(5) as MechId
655 if (mechById(id) !== undefined && mechById(id)?.notBuilt !== true) await openMech($, id)
656 return
657 }
658 const mind = await read($, mindA)
659 if (key.startsWith('mem:') || key.startsWith('sub:')) {
660 const list = key.startsWith('mem:') ? mind?.surfaced : mind?.footnotes
661 const r = list?.[Number(key.slice(4))]
662 if (r !== undefined) await openMemory($, key, r.id, r.title)
663 return
664 }
665 if (key.startsWith('saved:')) {
666 const it = (await read($, savedA)).find(s => `saved:${s.key}` === key)
667 if (it !== undefined) await openMemory($, key, it.id, it.title)
668 return
669 }
670 if (key.startsWith('ev:')) {
671 const mech = await read($, mechA)
672 const ev = mech?.events.find(e => `ev:${e.key}` === key)
673 if (ev === undefined) return
674 if (ev.memoryId !== null) await openMemory($, key, ev.memoryId, ev.title)
675 else {
676 const cur = await read($, openA)
677 const at = await $.clock.now()
678 await update($, openA, () => (cur?.key === key ? null : { key, id: null, status: 'ready' as const, title: null, text: '', meta: null, at }))
679 }
680 return
681 }
682}
683
684// ── the folder's switch ────────────────────────────────────────────────────
685
686/** A file's text, or null when it is not there or can't be read. */
687async function readText($: EngineInterface, path: string): Promise<string | null> {
688 try {
689 if (!(await $.fs.exists(path))) return null
690 const text = await $.fs.read(path)
691 return typeof text === 'string' ? text : null
692 } catch {
693 return null
694 }
695}
696
697/**
698 * The registry this session's hooks read, found as they find it
699 * (`config-path.ts`): the wired hook's `--config` (the user's settings, then
700 * this folder's), else `COUNTERPARTS_CONFIG`, else
701 * `~/.counterparts/claude-code.json`; `scopes.json` beside it. Read-only, no
702 * permission asked. Found again after five minutes, or when asked to.
703 */
704async function scopesFile($: EngineInterface, fresh: boolean): Promise<string | null> {
705 const now = await $.clock.now()
706 if (!fresh && run.scopesFile !== null && now - run.scopesFileAt < SCOPES_FILE_TTL_MS) return run.scopesFile
707 const home = ((await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? '').trim()
708 const moved = ((await $.env.get('CLAUDE_CONFIG_DIR')) ?? '').trim()
709 const settings = [
710 ...(moved.length > 0 ? [`${moved}/settings.json`] : home.length > 0 ? [`${home}/.claude/settings.json`] : []),
711 ...(run.cwd.length > 0 ? [`${run.cwd}/.claude/settings.json`, `${run.cwd}/.claude/settings.local.json`] : []),
712 ]
713 let named: string | null = null
714 for (const file of settings) {
715 const text = await readText($, file)
716 const config = text === null ? undefined : settingsHookConfig(text)
717 if (typeof config === 'string') {
718 named = config
719 break
720 }
721 }
722 if (named === null) {
723 const env = ((await $.env.get('COUNTERPARTS_CONFIG')) ?? '').trim()
724 named = env.length > 0 ? env : home.length > 0 ? `${home}/.counterparts/claude-code.json` : null
725 }
726 // A named configuration that is not absolute is refused by the hooks too: nothing to read.
727 run.scopesFile = named !== null && isAbsolutePath(named) ? `${parentOf(named)}/scopes.json` : null
728 run.scopesFileAt = now
729 return run.scopesFile
730}
731
732/** `scopes.ts#canonicalScopePath`: the deepest existing ancestor realpathed, the rest kept. */
733async function canonicalPath($: EngineInterface, path: string): Promise<string> {
734 const known = run.canon.get(path)
735 if (known !== undefined) return known
736 let head = path.length > 1 ? path.replace(/[/\\]+$/, '') : path
737 const tail: string[] = []
738 for (let i = 0; i < 64; i += 1) {
739 let real: string | undefined
740 try {
741 real = (await $.fs.stat(head, { resolve: true })).realPath
742 } catch {
743 real = undefined
744 }
745 if (real !== undefined) {
746 if (tail.length === 0) {
747 if (run.canon.size > 200) run.canon.clear()
748 run.canon.set(path, real)
749 return real
750 }
751 return `${real.replace(/[/\\]+$/, '')}/${tail.join('/')}`
752 }
753 const parent = parentOf(head)
754 if (parent === head || parent.length === 0) break
755 tail.unshift(head.slice(parent.length).replace(/^[/\\]+/, ''))
756 head = parent
757 }
758 return path
759}
760
761/** Where this folder stands, from the registry file: null when it can't be read (no home folder, no folder, a read refused). */
762async function readScopeFile($: EngineInterface, fresh: boolean): Promise<SidebarScope | null> {
763 if (run.cwd.length === 0) return null
764 const file = await scopesFile($, fresh)
765 if (file === null) return null
766 let entries: Record<string, RegistryMode> = {}
767 try {
768 // Absent is ordinary: every folder is unset. Present and unparseable reads
769 // the same way, as the hooks read it (`scopes.ts#readScopes`).
770 if (await $.fs.exists(file)) entries = parseRegistry(String(await $.fs.read(file)))
771 } catch {
772 return null
773 }
774 const target = await canonicalPath($, run.cwd)
775 const list = await Promise.all(
776 Object.entries(entries).map(async ([key, mode]) => ({ key, mode, canonical: await canonicalPath($, key) })),
777 )
778 const v = lookup(list, target)
779 return { mode: v.mode, own: v.canonical !== null && v.canonical === target, setBy: v.matched, dir: target, error: null, busy: false, unread: null }
780}
781
782/**
783 * Reads this folder's registry entry and shows any change: at session start,
784 * on each status poll while the pane is drawn, once a minute otherwise, and
785 * on every `/counterparts`. A pause made in another session shows here within
786 * one of those. No tool is called and nothing is logged.
787 */
788async function refreshScope($: EngineInterface, fresh = false): Promise<void> {
789 // Before session.start (the band may draw first) there is no folder yet: the state stays as it is, not "unreadable".
790 if (run.scopeReading || run.cwd.length === 0) return
791 run.scopeReading = true
792 try {
793 const found = await readScopeFile($, fresh).catch(() => null)
794 const before = await read($, scopeA)
795 const next: SidebarScope = found ?? (before.mode === 'unknown' ? { ...before, unread: 'unreadable' } : before)
796 if (next.mode === before.mode && next.own === before.own && next.setBy === before.setBy && next.dir === before.dir && next.unread === before.unread && before.error === null) return
797 await update($, scopeA, () => next)
798 await refreshStatus($)
799 } finally {
800 run.scopeReading = false
801 }
802}
803
804// ── views and the avatar ─────────────────────────────────────────────
805
806/**
807 * Opens (or re-opens) the pane and asks for a fresh drawing of it. Measured
808 * live (v0.1): a pane closed by hand and opened again is drawn from the
809 * terminal's settled evaluation, so this module's render hook never runs and
810 * the fox, stopped at the close, would stay frozen.
811 */
812async function openPane($: EngineInterface): Promise<{ isPlaced: boolean }> {
813 await setView($, 'sidebar')
814 // The desktop asks for a narrower pane: its font fits a fifth more in a cell's width (Mike, 2026-10-13).
815 const opened = await $.ui.open({ id: PANE, title: TITLE, columns: run.surface === 'desktop' ? OPEN_COLUMNS - 4 : OPEN_COLUMNS })
816 await update($, placedA, () => opened.isPlaced)
817 $.ui.invalidate('ui.render')
818 return { isPlaced: opened.isPlaced }
819}
820
821/** Closes the pane for the quiet view: the tail draws again. */
822async function closeQuiet($: EngineInterface): Promise<void> {
823 await setView($, 'quiet')
824 stopStage()
825 await update($, placedA, () => false)
826 await $.ui.close({ id: PANE })
827 $.ui.invalidate('ui.render')
828}
829
830/** The view, for this session and (in `$.store`) the next. */
831async function setView($: EngineInterface, view: SidebarView): Promise<void> {
832 if ((await read($, viewA)) !== view) await update($, viewA, () => view)
833 await $.store.set('view', view)
834 if (view !== 'sidebar') stopStage()
835}
836
837/** The avatar, for every session (`$.store` `brain`, its old name): the fox or none. */
838async function setAvatar($: EngineInterface, mode: SidebarAvatar): Promise<void> {
839 await $.store.set('brain', mode)
840 if ((await read($, brainA)) !== mode) await update($, brainA, () => mode)
841 if (mode !== 'fox') stopStage()
842 $.ui.invalidate('ui.render')
843}
844
845/**
846 * A click on one of the full build's footer switches (2026-10-16): store-only, as `/counterparts quiet`,
847 * `/counterparts` and `/counterparts avatar animal|off` do it. `set:view:quiet` closes the pane to quiet.
848 */
849async function setSwitch($: EngineInterface, key: string): Promise<void> {
850 if (key === 'set:view:quiet') await closeQuiet($)
851 else if (key === 'set:view:sidebar') await openPane($)
852 else if (key === 'set:avatar:off') await setAvatar($, 'off')
853 else if (key === 'set:avatar:fox') await setAvatar($, 'fox')
854}
855
856/** The pane's colours, for every session (`$.store`): tron or cozy. The Pane hook applies it at each drawing. */
857async function setTheme($: EngineInterface, name: SidebarTheme): Promise<void> {
858 await $.store.set('theme', name)
859 if ((await read($, themeA)) !== name) await update($, themeA, () => name)
860}
861
862/**
863 * Opened without being asked: only where it docks as a sidebar, and only when
864 * the stored view is the sidebar. Measured live (v0.1): the band draws BEFORE
865 * `session.start` has read the stored view, so the view (and the theme) is
866 * read from the store here.
867 */
868async function openUnasked($: EngineInterface): Promise<void> {
869 const view = normView(await $.store.get('view'))
870 if ((await read($, viewA)) !== view) await update($, viewA, () => view)
871 const theme = normTheme(await $.store.get('theme'))
872 if ((await read($, themeA)) !== theme) await update($, themeA, () => theme)
873 if (view !== 'sidebar') return
874 const opened = await openPane($)
875 if (!opened.isPlaced && run.interactive) {
876 run.hint = true
877 $.ui.invalidate('ui.render')
878 }
879}
880
881/** A refused blit is a Raster gone or not mounted yet: ask for a fresh drawing, a few times at most until one is taken. */
882function redrawAfterRefusal($: EngineInterface): void {
883 if (run.redraws >= 3) return
884 run.redraws += 1
885 $.ui.invalidate('ui.render')
886}
887
888// ── the fox (fox.ts holds what it does and how each frame looks) ──
889
890function stopStage(): void {
891 stage.gen += 1
892 stage.live = false
893}
894
895/** Something real happened: the fox's moment for it plays now, if the stage is up (else the next drawing shows where it is). */
896async function foxEvent($: EngineInterface, ev: FoxEvent): Promise<void> {
897 const now = await $.clock.now()
898 stage.director ??= newDirector(now)
899 if (!trigger(stage.director, ev, now)) return
900 if (stage.live) {
901 stage.gen += 1
902 const gen = stage.gen
903 $.clock.after(0, () => quiet(stageStep($, gen)))
904 }
905}
906
907/**
908 * What is on screen next, then one wait until it changes: no timer runs in
909 * between (a still hold is one wait of 4–9 s). A change on a Raster or an
910 * Image is a blit; in sextants (Text) or on the desktop (an Svg) a redraw of
911 * the pane. A pane no longer shown stops it (the next drawing starts it). A
912 * refused blit stops it; an Image refused twice in a row because it draws
913 * its alt here leaves `auto` drawing sextants or half-blocks for the session. Any other
914 * refusal (not mounted yet, another size, the terminal not yet asked) is not
915 * counted: it says nothing about pictures.
916 */
917/** What the engine's blit refusal says when an Image draws its alt (Claude Code 2.1.300). */
918const ALT_REFUSAL = 'draws its alt'
919
920async function stageStep($: EngineInterface, gen: number): Promise<void> {
921 if (gen !== stage.gen || !stage.live) return
922 const now = await $.clock.now()
923 stage.director ??= newDirector(now)
924 const { step, next } = advance(stage.director, now)
925 const key = stepKey(step)
926 if (key !== stage.shown) {
927 if (!(await paneShown($))) {
928 stopStage()
929 return
930 }
931 if (gen !== stage.gen) return
932 stage.shown = key
933 const tier = stage.tier
934 if (tier === 'basic' || tier === 'image') {
935 const args =
936 tier === 'basic'
937 ? { requestId: PANE, key: 'stage', cells: halfCells(step), columns: STAGE_COLS, rows: stageRows('basic') }
938 : { requestId: PANE, key: 'stage', source: pngFile(step), columns: IMAGE_COLS, rows: IMAGE_ROWS }
939 // Not awaited: the next wait is set below at once, whatever the blit's answer.
940 quiet(
941 (async () => {
942 let r: Awaited<ReturnType<EngineInterface['ui']['blit']>>
943 try {
944 r = await $.ui.blit(args)
945 } catch {
946 if (gen === stage.gen) stopStage()
947 return
948 }
949 if (gen !== stage.gen) return
950 if (r.deny === undefined) {
951 run.redraws = 0
952 if (tier === 'image') stage.imageDenies = 0
953 return
954 }
955 if (tier === 'image' && r.deny.includes(ALT_REFUSAL)) {
956 stage.imageDenies += 1
957 if (stage.imageDenies >= 2) stage.noImages = true
958 }
959 stopStage()
960 redrawAfterRefusal($)
961 })(),
962 )
963 } else $.ui.invalidate('ui.render')
964 }
965 $.clock.after(Math.max(16, next - now), () => quiet(stageStep($, gen)))
966}
967
968/** Starts the stage's timer under a new generation, once its element is mounted. */
969function startStage($: EngineInterface): void {
970 if (stage.live) return
971 stage.gen += 1
972 stage.live = true
973 const gen = stage.gen
974 $.clock.after(0, () => quiet(stageStep($, gen)))
975}
976
977/**
978 * The desktop's pane, as wide as the person drags it (it keeps their width, not the one a plugin asks for;
979 * measured 2026-10-13): the fox shows down to this many columns, scaled to fit, where the terminal needs
980 * STAGE_COLS. `w` is the last drawing's width.
981 */
982const STAGE_MIN_PROSE_COLS = 22
983const prosePane = { w: STAGE_COLS }
984
985/** The Image's source for a step: the PNG file, which the terminal reads itself. */
986function pngFile(step: Step): { file: string; format: 'png' } {
987 return { file: `${stage.pngDir ?? ''}/${pngName(step)}`, format: 'png' }
988}
989
990/** The folder of the fox's PNGs under the plugin's, or null when neither place holds them. */
991async function findPngDir($: EngineInterface): Promise<string | null> {
992 const root = $.plugin.root.replace(/[/\\]+$/, '')
993 for (const rel of PNG_DIRS) {
994 const dir = `${root}/${rel}`
995 try {
996 if (await $.fs.exists(`${dir}/idle.png`)) return dir
997 } catch {
998 // not readable: the next place
999 }
1000 }
1001 return null
1002}
1003
1004/** A PNG's bytes (base64) for the desktop's Svg, read once from the plugin's folder; '' when it can't be. */
1005async function pngData($: EngineInterface, name: string): Promise<string> {
1006 const known = stage.pngData.get(name)
1007 if (known !== undefined) return known
1008 let data = ''
1009 if (stage.pngDir !== null) {
1010 try {
1011 data = (await $.fs.read(`${stage.pngDir}/${name}`, { as: 'bytes' })).base64
1012 } catch {
1013 data = ''
1014 }
1015 }
1016 stage.pngData.set(name, data)
1017 return data
1018}
1019
1020/** The stage's element in a tier, for the step on screen (`png`: the desktop's picture, base64). */
1021function stageElement(els: ReturnType<EngineInterface['ui']['resolve']>, tier: FoxTier, step: Step, png: string): JSX.Element {
1022 if (tier === 'basic' && 'Raster' in els) {
1023 const { Raster } = els
1024 return <Raster key="stage" columns={STAGE_COLS} rows={stageRows('basic')} cells={halfCells(step)} />
1025 }
1026 if (tier === 'image' && 'Image' in els) {
1027 const { Box, Image } = els
1028 return (
1029 <Box key="stage-box" flexDirection="row" paddingLeft={IMAGE_X0}>
1030 <Image key="stage" source={pngFile(step)} columns={IMAGE_COLS} rows={IMAGE_ROWS} alt="a small fox" />
1031 </Box>
1032 )
1033 }
1034 if (tier === 'svg' && 'Svg' in els) {
1035 const { Svg } = els
1036 const svg = foxSvg(step, png)
1037 // A pane dragged narrower than the fox: the fox scales down with it (about 7 px a cell on the desktop).
1038 const k = Math.min(1, (prosePane.w * 7) / svg.width)
1039 return <Svg key="stage" source={svg.source} alt="a small fox" width={Math.round(svg.width * k)} height={Math.round(svg.height * k)} />
1040 }
1041 // fine: each row as runs of one colour pair; a cell with no colour is the panel's.
1042 const { Box, Text } = els
1043 return (
1044 <Box key="stage" flexDirection="column" width={STAGE_COLS}>
1045 {fineCells(step).map((line, y) => (
1046 <Box key={`s${String(y)}`} flexDirection="row">
1047 {runs(line).map((r, i) => (
1048 <Text key={String(i)} {...(r.fg === null ? {} : { color: r.fg })} {...(r.bg === null ? {} : { backgroundColor: r.bg })}>
1049 {r.ch}
1050 </Text>
1051 ))}
1052 </Box>
1053 ))}
1054 </Box>
1055 )
1056}
1057
1058/** The fox's detail, for every session (`$.store` `avatarDetail`): auto, images, fine or basic. */
1059async function setDetail($: EngineInterface, detail: FoxDetail): Promise<void> {
1060 await $.store.set('avatarDetail', detail)
1061 stage.detail = detail
1062 stage.noImages = false
1063 stage.imageDenies = 0
1064 stopStage()
1065 stage.shown = ''
1066 $.ui.invalidate('ui.render')
1067}
1068
1069/** A drawing of the pane: the status file is read from here on, until the pane stops showing. */
1070function wake($: EngineInterface): void {
1071 if (run.hint) {
1072 run.hint = false
1073 $.ui.invalidate('ui.render')
1074 }
1075 armPolling($, run.lastSeq >= 0 ? POLL_MS : 0)
1076 if (!run.woke) {
1077 run.woke = true
1078 quiet(refreshScope($))
1079 }
1080 // Drawn, it is placed: the tail under the prompt stands down (written after the drawing, never during it).
1081 $.clock.after(0, () => {
1082 quiet(
1083 (async () => {
1084 if (!(await read($, placedA))) await update($, placedA, () => true)
1085 })(),
1086 )
1087 })
1088}
1089
1090/**
1091 * The body's lines, with no link on any of them (2026-10-14): the `more` that
1092 * ends a cut text is words, and a click on it is its row's. The rest is on the
1093 * dashboard, which `/counterparts:dashboard` opens (the footer says so).
1094 */
1095function plainLines(lines: readonly Line[]): Line[] {
1096 return lines.map(l => {
1097 if (l.link === undefined) return l
1098 const { link: _dropped, ...rest } = l
1099 return rest
1100 })
1101}
1102
1103// ── hooks ───────────────────────────────────────────────────────────────────
1104
1105export const register: Register = on => {
1106 on('session.start', async ($, e, next) => {
1107 run.interactive = e.isInteractive
1108 run.cwd = e.cwd
1109 run.session = await $.session.id()
1110 if (run.startedAt === 0) run.startedAt = await $.clock.now()
1111 await $.command.register({
1112 name: 'counterparts',
1113 description: 'Counterparts sidebar: open it, make it quiet, or set the avatar or the theme',
1114 argumentHint: '[quiet | avatar animal|off | avatar detail auto|images|fine|basic | theme tron|cozy | resume]',
1115 })
1116 // (A `claudeMemory` or `claudeMemorySwitch` left in the store by an older version is never read.)
1117 const [viewPref, brainPref, themePref, detailPref] = await Promise.all([
1118 $.store.get('view'),
1119 $.store.get('brain'),
1120 $.store.get('theme'),
1121 $.store.get('avatarDetail'),
1122 ])
1123 // A new module life's fox starts fresh: still, awake, trying pictures again where they may show.
1124 stage.director = null
1125 stage.noImages = false
1126 stage.imageDenies = 0
1127 stage.detail = normDetail(detailPref)
1128 // The PNGs ship as files beside the module (art/fox/): found once; none found, the terminal draws no pictures.
1129 stage.pngDir = await findPngDir($)
1130 stage.pngData.clear()
1131 if (stage.pngDir === null) stage.noImages = true
1132 // Pictures: tried, and the engine says. Where they can't show, whether the font draws sextants, read once (fox.ts).
1133 // (Each name spelled out: the engine lists the variables a module reads.)
1134 const envVals = await Promise.all([
1135 $.env.get('TERM_PROGRAM').catch(() => undefined),
1136 $.env.get('TERM').catch(() => undefined),
1137 $.env.get('KITTY_WINDOW_ID').catch(() => undefined),
1138 $.env.get('WEZTERM_EXECUTABLE').catch(() => undefined),
1139 ])
1140 stage.env = Object.fromEntries(TIER_ENV.map((k, i) => [k, envVals[i]]).filter(([, v]) => typeof v === 'string'))
1141 await update($, themeA, () => normTheme(themePref))
1142 await update($, viewA, () => normView(viewPref))
1143 await update($, brainA, () => normAvatar(brainPref))
1144 // Nothing is opened or drawn here, and the status file is not read. The pane
1145 // opens unasked from the first drawing of the band above the prompt, which
1146 // says whether this surface docks a pane; the fox and the status reads start
1147 // with the pane's own first drawing. One thing is read: where this folder
1148 // stands, so a session started in a paused folder says so at once.
1149 quiet(refreshStatus($))
1150 if (run.interactive) {
1151 // Where this folder stands, now and every few minutes.
1152 $.clock.after(0, () => quiet(refreshScope($)))
1153 run.scopeTimer?.cancel()
1154 run.scopeTimer = $.clock.every(SCOPE_RECHECK_MS, () => quiet(refreshScope($)))
1155 }
1156 return next(e)
1157 })
1158
1159 on('command.run', { command: 'counterparts' }, async ($, e) => {
1160 // This hook answers without `next`, so no hook beneath sees the command: the speak-first learns it from here.
1161 const kind = (e.origin as { kind?: string } | undefined)?.kind
1162 if (kind === 'composer' || kind === 'bridge') {
1163 if (run.session === '') run.session = await $.session.id()
1164 await update($, typedInA, () => run.session)
1165 }
1166 const [verb = '', arg = ''] = e.args.trim().split(/\s+/)
1167 await refreshScope($, true)
1168 // `strip` (dropped 2026-10-10) is quiet now: an older term-loop's put-back can still type it.
1169 if (verb === 'quiet' || verb === 'hide' || verb === 'rail' || verb === 'strip') {
1170 await closeQuiet($)
1171 return { text: 'Counterparts quiet: the newest thing shows dim after the line under the prompt. /counterparts opens the sidebar.' }
1172 }
1173 if (verb === 'avatar') {
1174 if (arg === 'detail') {
1175 const d = e.args.trim().split(/\s+/)[2] ?? ''
1176 if (d !== 'auto' && d !== 'images' && d !== 'fine' && d !== 'basic') {
1177 return { text: `counterparts avatar detail: auto, images, fine or basic (now ${stage.detail}, ${stage.tier === 'image' ? 'drawn as a picture' : stage.tier === 'fine' ? 'drawn in sextants' : stage.tier === 'svg' ? 'drawn as a drawing' : 'drawn in half-blocks'}).` }
1178 }
1179 await setDetail($, d)
1180 return {
1181 text:
1182 d === 'auto'
1183 ? 'The fox is drawn the best way this terminal shows: a picture, else sextants, else half-blocks.'
1184 : d === 'images'
1185 ? 'The fox is drawn as a picture (kitty, Ghostty); a terminal that cannot shows its name instead.'
1186 : d === 'fine'
1187 ? 'The fox is drawn in sextants (six pixels a cell), for a font that has them.'
1188 : 'The fox is drawn in half-blocks, which every terminal shows.',
1189 }
1190 }
1191 if (arg === 'animal' || arg === 'fox') {
1192 await setAvatar($, 'fox')
1193 return { text: 'The avatar is the fox: it sits still, now and then blinks or looks around, naps when nothing happens, and shows what memory is doing.' }
1194 }
1195 if (arg === 'off') {
1196 await setAvatar($, 'off')
1197 return { text: 'No avatar: the header is two lines.' }
1198 }
1199 return { text: 'counterparts avatar: animal or off; or detail auto, images, fine or basic.' }
1200 }hooks/sidebar/hooks/speak-first.tsx 194 lines1/**
2 * SPEAK FIRST, a hooks module of its own (moved out of `register.tsx`,
3 * 2026-10-14): once per store, at an interactive start, while the wake's
4 * onboarding marker says `not_started`, it submits MEET_PROMPT, which the
5 * engine runs once the session is idle, so Claude opens the first meeting.
6 *
7 * The plugin's own build lists it beside the sidebar (`hooks/hooks.json`,
8 * "modules"); the plugin directory's build lists only the sidebar, which then
9 * offers the meeting by its "Start the 5-minute intro" button alone. Neither
10 * module imports the other: they share pure helpers (`feed.ts`, `words.ts`,
11 * `state.ts`'s constants) and, through the engine, two things of the plugin's:
12 * - `$.state` `counterparts.scope`, where this folder stands, which the
13 * sidebar reads from the registry and this module only reads (alone, it
14 * stays unknown, and the speak-first never fires: it never acts on an
15 * unknown folder);
16 * - `$.store` MEET_FLAG, the once-per-install mark this module writes
17 * (`{ session, at }`, or `{ settled }` once core moved past not_started),
18 * which the sidebar reads to hide its button while this session's
19 * speak-first is the introduction.
20 *
21 * Never headless, never where the folder is paused, off, observer or unknown,
22 * never once the person has typed a prompt or run a slash command (or is
23 * typing one), and never over a binding mark. The mark is written before the
24 * submit, so a crash between them loses the trigger rather than repeating it.
25 * A speak-first still queued when the person's own prompt goes first is
26 * dropped: their prompt comes first, and core offers the meeting in that reply.
27 *
28 * KEYED TO THE STORE without a store id: core says `not_started` only for a
29 * store that never got past it (`start-fresh` resets it). So every known state
30 * past it is written over the mark as `{ settled }`, and a settled mark doesn't
31 * block the speak-first: a `not_started` after it is a new store, which gets
32 * its own first meeting.
33 */
34
35import { atom, read } from 'claude-code'
36import type { EngineInterface, Register } from 'claude-code'
37
38import type { SidebarMeet } from '../types'
39import { canMeet, parseOnboardingMarker } from './feed'
40import { MEET_FLAG, MEET_PROMPT, SCOPE_RECHECK_MS, UNKNOWN_SCOPE, quiet } from './state'
41import { firedIn } from './words'
42
43/** The sidebar's view of this folder (`register.tsx` writes it); read here, never written. */
44const scopeA = atom({ plugin: 'counterparts', key: 'scope' } as const, UNKNOWN_SCOPE)
45
46/**
47 * The session in which the person ran `/counterparts …` (the sidebar writes it: its command hook answers
48 * without passing the command on, so this module's `command.run` hook never sees that one).
49 */
50const typedInA = atom({ plugin: 'counterparts', key: 'typedIn' } as const, null)
51
52/** How often a start that could not decide yet (the folder or the marker not read) looks again, and for how long. */
53const RETRY_MS = 1000
54const RETRIES = 120
55
56/** What this module life knows. */
57const sf = {
58 interactive: false,
59 session: '',
60 /** Where the first meeting stands, from the wake's marker; unknown until one says. */
61 meet: 'unknown' as SidebarMeet,
62 /** The person sent a prompt of their own, or ran a slash command, this session. */
63 typed: false,
64 /**
65 * The person sent a PROMPT of their own, not only a command: only this drops a speak-first
66 * already queued, since only a prompt gets a reply where core can offer the meeting.
67 */
68 prompted: false,
69 /** The speak-first was considered this module life (it goes out at most once per install). */
70 tried: false,
71 /** This module life submitted the speak-first. */
72 spoke: false,
73 retry: null as { cancel: () => void } | null,
74}
75
76/** The marker's state, taken in: past not_started settles a binding mark (a new store's not_started speaks again). */
77async function takeMeet($: EngineInterface, meet: SidebarMeet): Promise<void> {
78 if (meet === 'unknown') return
79 sf.meet = meet
80 if (meet === 'not_started') return
81 const mark = (await $.store.get(MEET_FLAG)) as { settled?: unknown } | undefined
82 if (mark?.settled !== meet) await $.store.set(MEET_FLAG, { settled: meet, at: await $.clock.now() })
83}
84
85/** One look: speaks first when every condition holds, else waits for what is missing or stands down for good. */
86async function speakFirst($: EngineInterface): Promise<void> {
87 if (!sf.interactive || sf.tried) return
88 const scope = await read($, scopeA)
89 // Not read yet: a later look tries again.
90 if (scope.mode === 'unknown' && scope.unread === null) return
91 // No state yet: the wake's marker, when it comes, tries again (no marker at all: an older core, nothing).
92 if (sf.meet === 'unknown') return
93 sf.tried = true
94 stopRetry()
95 if (sf.session === '') sf.session = await $.session.id()
96 if ((await read($, typedInA)) === sf.session) sf.typed = true
97 if (sf.meet !== 'not_started' || sf.typed || !canMeet(scope.mode)) return
98 if (firedIn(await $.store.get(MEET_FLAG)) !== null) return
99 // The last looks, right before: no prompt sent or typed, no other session got there meanwhile.
100 if (sf.typed || (await read($, typedInA)) === sf.session || (await turnsSoFar($)) > 0) return
101 if ((await draftNow($)).trim() !== '') return
102 if (firedIn(await $.store.get(MEET_FLAG)) !== null) return
103 await $.store.set(MEET_FLAG, { session: sf.session, at: await $.clock.now() })
104 sf.spoke = true
105 // Not awaited inside a hook: the engine queues it until the session is idle.
106 $.clock.after(0, () => quiet($.prompt.submit({ text: MEET_PROMPT })))
107}
108
109async function turnsSoFar($: EngineInterface): Promise<number> {
110 try {
111 return await $.session.turns()
112 } catch {
113 return 1
114 }
115}
116
117async function draftNow($: EngineInterface): Promise<string> {
118 try {
119 return (await $.prompt.read()).text
120 } catch {
121 return ''
122 }
123}
124
125function stopRetry(): void {
126 sf.retry?.cancel()
127 sf.retry = null
128}
129
130export const register: Register = on => {
131 // (Each hook here carries a matcher: the sidebar's own hooks on these events carry none, and two of one
132 // plugin on one event with none are refused when both modules load as one.)
133 on('session.start', { isInteractive: true }, async ($, e, next) => {
134 sf.interactive = e.isInteractive
135 sf.session = await $.session.id()
136 if (sf.interactive && !sf.tried) {
137 // The sidebar reads where this folder stands as the session starts; look once it has, and again a
138 // few times while either that or the wake's marker is missing.
139 $.clock.after(0, () => quiet(speakFirst($)))
140 stopRetry()
141 let left = RETRIES
142 sf.retry = $.clock.every(RETRY_MS, () => {
143 left -= 1
144 if (sf.tried) stopRetry()
145 else if (left > 0) quiet(speakFirst($))
146 else {
147 // Still undecided after two minutes (the folder's state or the marker late): once a minute after,
148 // as the sidebar's own scope recheck used to carry it.
149 stopRetry()
150 sf.retry = $.clock.every(SCOPE_RECHECK_MS, () => (sf.tried ? stopRetry() : quiet(speakFirst($))))
151 }
152 })
153 }
154 return next(e)
155 })
156
157 // A slash command the person ran (any: /model, /counterparts…) counts as having spoken: no
158 // command starts a turn, so `session.turns()` would not see it.
159 // (`/counterparts …` never reaches here: the sidebar answers it without `next`, and says so in `typedIn`.)
160 on('command.run', { origin: { kind: /^(composer|bridge)$/ } }, async ($, e, next) => {
161 sf.typed = true
162 return next(e)
163 }).catch(($, e, next) => next(e))
164
165 // A prompt the person sent: the speak-first stands down for good in this session. If it was
166 // already queued behind it, it is dropped: their prompt comes first, and core offers the
167 // meeting in that reply instead.
168 on('prompt.submit', { origin: { kind: /^(composer|bridge|plugin)$/ } }, async ($, e, next) => {
169 const kind = e.origin.kind
170 if (kind === 'composer' || kind === 'bridge') sf.typed = sf.prompted = true
171 if (kind === 'plugin' && e.origin.name === 'counterparts' && e.text === MEET_PROMPT && sf.prompted && sf.spoke) {
172 return { drop: 'the person spoke first' }
173 }
174 return next(e)
175 }).catch(($, e, next) => next(e))
176
177 // The wake's onboarding marker: where the first meeting stands, then a look.
178 on('session.append', { door: 'hook-context', origin: { kind: 'hook', event: 'SessionStart' } }, async ($, e, next) => {
179 const stored = await next(e)
180 if (e.agentId !== undefined) return stored
181 try {
182 const text = e.message.content.map(b => (b.type === 'text' && typeof b.text === 'string' ? b.text : '')).join('\n')
183 const meet = parseOnboardingMarker(text)
184 if (meet !== null) {
185 await takeMeet($, meet)
186 $.clock.after(0, () => quiet(speakFirst($)))
187 }
188 } catch {
189 // the row is stored whatever this module made of it
190 }
191 return stored
192 }).catch(($, e, next) => next(e))
193}
194hooks/sidebar/hooks/feed.ts 900 lines1/**
2 * What the sidebar reads, turned into its own terms: the dashboard's event
3 * feed (which mechanisms each event proves, and whose it is), the recall block
4 * the classic UserPromptSubmit hook injects, a `recall` facts answer, the
5 * memory tools' calls this session, a dream, and a mechanism's recent firings.
6 * Pure: no `$`.
7 *
8 * WHICH EVENTS ARE A MECHANISM FIRING is the dashboard's table
9 * (`src/adapters/mechanism-evidence.ts`, MECHANISM_EVIDENCE): an event name,
10 * sometimes a condition on its payload, and the mechanism it proves. One event
11 * can prove several: a dream that merged near-copies and wrote a gist proves
12 * Dreaming, Interference, Consolidation and Gist. This file keeps a copy of
13 * the names and conditions, not an import — a hooks module reaches nothing
14 * outside its plugin folder but through `$`. The repository's bun test
15 * `test/sidebar-mechanism-drift.test.ts` fails when the copy and the table
16 * disagree.
17 */
18
19import type { SidebarMeet, SidebarOnboarding, SidebarRow, SidebarSaved } from '../types';
20import { MECHS, mechById } from './mechanisms';
21import type { MechId } from './mechanisms';
22import { cells, ellipsizeCells, headCells } from './width';
23
24/** One event the sidebar read (the contract's SidebarRow). */
25export type FeedRow = SidebarRow;
26
27/** One event as the dashboard's activity feed narrates it (the status file carries these rows). */
28export type DashEvent = {
29 seq: number;
30 at: number;
31 day?: number;
32 name: string;
33 text: string;
34 subject?: string | null;
35 detail?: readonly { key: string; value: string }[];
36};
37
38function detail(e: DashEvent, key: string): string | undefined {
39 return e.detail?.find(d => d.key === key)?.value;
40}
41function num(e: DashEvent, key: string): number {
42 const v = Number(detail(e, key));
43 return Number.isFinite(v) ? v : 0;
44}
45/**
46 * Of the memories a deposit or a turn names, the ones carrying a recorded
47 * feeling, with their feeling words (`detail.felt`, JSON `[{ id, words }]`,
48 * 2026-10-14). The status file's writer reads them off the store; a row
49 * without it carries none.
50 */
51export function feltOf(e: DashEvent): { id: string; words: string[] }[] {
52 try {
53 const list: unknown = JSON.parse(detail(e, 'felt') ?? '[]');
54 if (!Array.isArray(list)) return [];
55 return list.flatMap(x => {
56 if (x === null || typeof x !== 'object') return [];
57 const { id, words } = x as { id?: unknown; words?: unknown };
58 if (typeof id !== 'string' || !id.startsWith('mem_')) return [];
59 return [{ id, words: Array.isArray(words) ? words.filter((w): w is string => typeof w === 'string' && w !== '') : [] }];
60 });
61 } catch {
62 return [];
63 }
64}
65
66/** `"Title…" [mem_abc]` → the title and the id. */
67export function titled(value: string | null | undefined): { title: string | null; id: string | null } {
68 if (value === undefined || value === null) return { title: null, id: null };
69 const m = /^"([\s\S]*)"\s*\[([A-Za-z]+_[A-Za-z0-9]+)\]$/.exec(value.trim());
70 if (m !== null) return { title: m[1] ?? null, id: m[2] ?? null };
71 const bare = /\[([A-Za-z]+_[A-Za-z0-9]+)\]/.exec(value);
72 return { title: null, id: bare?.[1] ?? null };
73}
74
75type Rule = { name: string; mech: MechId; word: string; when?: (e: DashEvent) => boolean };
76
77/**
78 * The event names that prove a mechanism fired, in the dashboard's words. An
79 * event counts when any rule for its name holds. The FIRST that holds gives
80 * it its word and colour (`mech`); EVERY one that holds lights (`mechs`).
81 */
82export const RULES: readonly Rule[] = [
83 { name: 'gate.deposit', mech: 'salience', word: 'kept', when: e => num(e, 'accepted') > 0 },
84 { name: 'gate.chunk', mech: 'salience', word: 'kept', when: e => num(e, 'accepted') > 0 },
85 { name: 'recall.decision', mech: 'retrieval', word: 'recalled', when: e => num(e, 'surfacedCount') + num(e, 'footnoteCount') > 0 },
86 // Emotion (2026-10-14): a memory saved with a feeling, a turn that brought one
87 // carrying a feeling to mind (`felt`). The mood match, off by decision since
88 // 2026-10-10, still lights it the day it is back on.
89 { name: 'gate.deposit', mech: 'emotional', word: 'saved with a feeling', when: e => feltOf(e).length > 0 },
90 { name: 'recall.decision', mech: 'emotional', word: 'came to mind', when: e => feltOf(e).length > 0 },
91 { name: 'recall.decision', mech: 'emotional', word: 'brought closer', when: e => num(e, 'moodMatched') > 0 },
92 // A memory a link put in front of the model (2026-10-11, Group 4).
93 { name: 'recall.decision', mech: 'association', word: 'brought to mind by a link', when: e => num(e, 'linksReached') > 0 },
94 { name: 'mcp.recall', mech: 'retrieval', word: 'looked up' },
95 { name: 'recall.credit', mech: 'retrieval', word: 'strengthened', when: e => num(e, 'credited') > 0 },
96 // Links LAID, not rows rewritten (2026-10-11, Group 4): `deposited`.
97 { name: 'associate.flush', mech: 'association', word: 'linked', when: e => num(e, 'deposited') > 0 },
98 { name: 'prospective.plain', mech: 'prospective', word: 'reminded' },
99 { name: 'prospective.fire', mech: 'prospective', word: 'reminded' },
100 { name: 'band.transition', mech: 'decay', word: 'faded', when: e => detail(e, 'site') === 'decay' && detail(e, 'direction') !== 'up' },
101 // A rise at whatever site wrote it (only decay does), not the crossing into
102 // identity (counted as `band.promoted`) or a `recurve` (2026-10-20).
103 { name: 'band.transition', mech: 'consolidation', word: 'rose', when: e => detail(e, 'direction') === 'up' && detail(e, 'to') !== 'identity' && detail(e, 'cause') !== 'promoted' && detail(e, 'cause') !== 'recurve' },
104 { name: 'memory.pruned', mech: 'decay', word: 'let go' },
105 { name: 'sleep.cycle', mech: 'decay', word: 'faded', when: e => num(e, 'faded') > 0 },
106 { name: 'band.promoted', mech: 'consolidation', word: 'became core' },
107 { name: 'memory.merged', mech: 'consolidation', word: 'merged' },
108 { name: 'dream.journaled', mech: 'dreaming', word: 'dreamed' },
109 // The replay's faint trails, laid as the dream opens (2026-10-11, Group 4).
110 { name: 'dream.begun', mech: 'association', word: 'linked', when: e => num(e, 'replayLinks') > 0 },
111 // A change the dream made, or a core suggestion (`applied` counts both).
112 { name: 'dream.changed', mech: 'dreaming', word: 'dreamed', when: e => num(e, 'applied') > 0 || num(e, 'nominate-core') > 0 },
113 { name: 'dream.changed', mech: 'episodic-semantic', word: 'dreamed a pattern', when: e => num(e, 'gist') > 0 },
114 { name: 'dream.changed', mech: 'interference', word: 'merged in a dream', when: e => num(e, 'merge') > 0 },
115 { name: 'dream.changed', mech: 'consolidation', word: 'merged in a dream', when: e => num(e, 'merge') > 0 },
116 // A fold gathers what belongs together, as a merge does (2026-10-20).
117 { name: 'dream.changed', mech: 'interference', word: 'folded in a dream', when: e => num(e, 'fold') > 0 },
118 { name: 'dream.changed', mech: 'consolidation', word: 'folded in a dream', when: e => num(e, 'fold') > 0 },
119 { name: 'contradiction.flagged', mech: 'interference', word: 'flagged' },
120 // A new memory read as the newer state of an older one (Group 2, the slot detector).
121 { name: 'contradiction.proposed', mech: 'interference', word: 'noticed' },
122 // DECLARED settles are reconsolidation's; a confirmed slot (a detected door) is
123 // interference's; a dream merge's rows count as the merge (Group 2b, review 10 C6),
124 // a fold's as the fold (2026-10-20).
125 { name: 'contradiction.settled', mech: 'reconsolidation', word: 'settled', when: e => detail(e, 'source') !== 'slot' && detail(e, 'source') !== 'dream-merge' && detail(e, 'source') !== 'fold' },
126 { name: 'contradiction.settled', mech: 'interference', word: 'replaced', when: e => detail(e, 'source') === 'slot' },
127 { name: 'revision.pressure', mech: 'reconsolidation', word: 'weighed' },
128];
129
130/** The names worth asking the dashboard for one by one. */
131export const RULE_NAMES: readonly string[] = [...new Set(RULES.map(r => r.name))];
132
133/** The rules `e` proves, one a mechanism, the event's own first; none when it proves nothing. */
134export function provedBy(e: DashEvent): Rule[] {
135 const out: Rule[] = [];
136 for (const r of RULES) {
137 if (r.name !== e.name || (r.when !== undefined && !r.when(e))) continue;
138 if (!out.some(o => o.mech === r.mech)) out.push(r);
139 }
140 return out;
141}
142
143/** A row's mechanisms, its own first (a row from before rows carried `mechs`: its own alone). */
144export function mechsOf(r: SidebarRow): MechId[] {
145 return Array.isArray(r.mechs) && r.mechs.length > 0 ? r.mechs : [r.mech];
146}
147
148/**
149 * The events that belong to no session: the night's sleep and dreams, and
150 * what they settle (fading, merging, promoting). Everything else carries the
151 * session it happened in (`detail.session`), or is a session's boundary work.
152 */
153const NIGHT = new Set([
154 'dream.journaled', 'dream.changed', 'band.transition', 'memory.pruned', 'memory.merged',
155 'band.promoted', 'sleep.cycle', 'contradiction.flagged', 'contradiction.settled', 'revision.pressure',
156]);
157
158/** The titles a recall narration quotes (“…”). */
159export function quotedTitles(text: string): string[] {
160 return [...text.matchAll(/“([^”]+)”/g)].map(m => m[1] ?? '').filter(t => t.length > 0);
161}
162
163/**
164 * A dashboard event in the sidebar's terms, or null when it proves no
165 * mechanism. `session` is this session's id: its own events are `here`, the
166 * night's `night`, other sessions' `other` (they never light this header's dot).
167 *
168 * WHOSE IT IS. An event's `session` (or, for a settle a session made, its
169 * `actorId`) names it. A look-up (`mcp.recall`), a reminder
170 * (`prospective.*`) and a link flush (`associate.flush`) name none yet (a
171 * core follow-up: add `session` to those payloads, and the read below takes
172 * it): one of those from after this session began (`since`) is taken as this
173 * session's, one from before as another's.
174 */
175export function classify(e: DashEvent, session = '', since = 0): FeedRow | null {
176 const proved = provedBy(e);
177 const rule = proved[0];
178 if (rule === undefined) return null;
179 const m = mechById(rule.mech);
180 const short = m?.short ?? rule.mech;
181 // A settle or a revision a session made names it as its actor, not as `session`.
182 const bySession = detail(e, 'actor') === 'session';
183 const from = detail(e, 'session') ?? (bySession ? detail(e, 'actorId') : undefined);
184 const mine = session !== '';
185 const who: FeedRow['who'] =
186 NIGHT.has(e.name) && !bySession
187 ? 'night'
188 : from !== undefined
189 ? mine && from === session ? 'here' : 'other'
190 : e.at >= since ? 'here' : 'other';
191 // The memory it is about: a deposit's `memoryId`, a fade's or a promotion's subject, a settle's `over`.
192 const named = [detail(e, 'memoryId'), e.subject ?? undefined, detail(e, 'over'), detail(e, 'id'), detail(e, 'targetId')]
193 .map(titled)
194 .find(t => t.id !== null && t.id.startsWith('mem_'));
195 const dream = e.name.startsWith('dream.') && typeof e.subject === 'string' && /^drm_[A-Za-z0-9]+$/.test(e.subject) ? e.subject : undefined;
196 const base: FeedRow = {
197 id: `seq:${String(e.seq)}`,
198 mech: rule.mech,
199 mechs: proved.map(r => r.mech),
200 word: rule.word,
201 at: e.at,
202 text: e.text,
203 more: [],
204 who,
205 line: `${rule.word} · ${e.text}`,
206 ...(named === undefined || named.id === null ? {} : { memory: { id: named.id, title: named.title } }),
207 ...(dream === undefined ? {} : { dream }),
208 };
209 if (rule.name === 'gate.deposit' || rule.name === 'gate.chunk') {
210 const accepted = num(e, 'accepted');
211 const text = named?.title ?? (accepted > 1 ? `${String(accepted)} memories written down` : 'a memory');
212 return { ...base, text, line: `kept · ${text}`, ...(named?.id ? { twinIds: [`mem:${named.id}`] } : {}) };
213 }
214 if (rule.name === 'recall.decision') {
215 const turn = detail(e, 'turn');
216 const n = num(e, 'surfacedCount') + num(e, 'footnoteCount');
217 const said = n > 0 ? `${String(n)} came to mind` : `${String(num(e, 'moodMatched'))} brought closer by a matching mood`;
218 return {
219 ...base,
220 text: said,
221 more: quotedTitles(e.text),
222 line: said,
223 ...(from !== undefined && turn !== undefined ? { twinIds: [`turn:${from}:${turn}`] } : {}),
224 };
225 }
226 return base;
227}
228
229/** A recall decision's surfaced ids, strongest first (`detail.surfaced`, a JSON list of `{ id }`). */
230export function surfacedIds(e: DashEvent): string[] {
231 try {
232 const list: unknown = JSON.parse(detail(e, 'surfaced') ?? '[]');
233 if (!Array.isArray(list)) return [];
234 return list.map(x => (x !== null && typeof x === 'object' ? (x as { id?: unknown }).id : undefined)).filter((x): x is string => typeof x === 'string');
235 } catch {
236 return [];
237 }
238}
239
240/** The decision row for this session's turn `turn`, among a few of the newest. */
241export function decisionFor(events: readonly DashEvent[], session: string, turn: number): DashEvent | undefined {
242 return events.find(e => e.name === 'recall.decision' && detail(e, 'session') === session && Number(detail(e, 'turn')) === turn);
243}
244
245// ── times fired today, counted from the feed (a dashboard older than v0.2) ──
246
247/**
248 * Times each mechanism fired on the calendar day `date` among `rows`, as the
249 * dashboard counts `firedToday`: rows, not amounts; a dream's rows once.
250 * `start` is a count so far, so a poll's new rows add to it; `dreams` the
251 * dreams already counted, so a dream's second row adds nothing. The caller
252 * hands in each row once (the cold read stops at the seq the polls go on from).
253 */
254export function countToday(
255 rows: readonly SidebarRow[],
256 date: string,
257 dateOf: (at: number) => string,
258 start: Partial<Record<MechId, number | null>> = {},
259 dreams: readonly string[] = [],
260): { counts: Partial<Record<MechId, number | null>>; dreams: string[] } {
261 const counts: Partial<Record<MechId, number | null>> = { ...start };
262 for (const m of MECHS) if (counts[m.id] === undefined) counts[m.id] = m.notBuilt ? null : 0;
263 const seenDreams = new Set(dreams);
264 const fresh = new Map<string, Set<MechId>>();
265 for (const r of rows) {
266 if (dateOf(r.at) !== date) continue;
267 for (const m of mechsOf(r)) {
268 if (r.dream !== undefined) {
269 // One dream, one firing of each mechanism it proves: its journal and its changes rows are one.
270 const k = `${r.dream}:${m}`;
271 if (seenDreams.has(k)) continue;
272 const set = fresh.get(r.dream) ?? new Set<MechId>();
273 if (set.has(m)) continue;
274 set.add(m);
275 fresh.set(r.dream, set);
276 }
277 const c = counts[m];
278 if (typeof c === 'number') counts[m] = c + 1;
279 }
280 }
281 for (const [d, ms] of fresh) for (const m of ms) seenDreams.add(`${d}:${m}`);
282 return { counts, dreams: [...seenDreams] };
283}
284
285// ── a mechanism's recent firings (its panel's `activity`) ─────────────────
286
287/** A piece of a firing's sentence: plain words, or a memory (its id, and the title the row carried, maybe cut). */
288export type FiringPart = string | { id: string | null; title: string | null };
289
290/** One thing a firing was about, before its titles are read in full: what the opened mechanism lists. */
291export type Firing = {
292 /** Unique among the list: `<seq>.<n>`. */
293 key: string;
294 seq: number;
295 at: number;
296 /** The group's word (`faded`, `came to mind`, `merged in a dream`). */
297 word: string;
298 /** The sentence, a memory's title or a few words around two. */
299 parts: FiringPart[];
300 /** The memory a click opens in place; null opens `text` instead. */
301 memoryId: string | null;
302 /** What opening a firing that names no memory shows. */
303 text: string;
304};
305
306function idList(e: DashEvent, key: string): string[] {
307 try {
308 const list: unknown = JSON.parse(detail(e, key) ?? '[]');
309 if (!Array.isArray(list)) return [];
310 return list
311 .map(x => (typeof x === 'string' ? x : x !== null && typeof x === 'object' ? (x as { id?: unknown }).id : undefined))
312 .filter((x): x is string => typeof x === 'string' && x.startsWith('mem_'));
313 } catch {
314 return [];
315 }
316}
317
318/** Which of a dream's changes prove `mech`: merges for Interference and Consolidation, patterns for Gist. */
319const DREAM_ACTION: Partial<Record<MechId, string>> = { interference: 'merge', consolidation: 'merge', 'episodic-semantic': 'gist' };
320
321/**
322 * What each firing of `mech` among `events` was about, newest first: the
323 * memories it names, never its counts (Mike, 2026-10-10: "1 came to mind"
324 * says nothing). A firing that names nothing is left out:
325 * - a recall's decision: each memory that came to mind or sat in the
326 * footnotes (`surfaced`, `footnotes` ids); a credit: each memory it
327 * strengthened (`ids`);
328 * - Emotion's deposits and turns: only the memories that carry a feeling
329 * (`felt`), each as its title and its feeling words (`Title (curious)`);
330 * - a deposit, a fade, a rise, a promotion, a prune, a reminder: its memory;
331 * - a settle: which memory holds over which; revision pressure: which
332 * argued with which;
333 * - a dream: its journal's first sentence (Dreaming); its merges
334 * (Interference, Consolidation) and patterns (Gist) from the dreams'
335 * changes, which name memories the event row only counts;
336 * - left out, nothing to name: a look-up (`mcp.recall` counts what it
337 * opened), a link flush (`associate.flush` counts pairs), a turn a link
338 * reached recall on (`recall.decision`'s `linksReached` is a count), a
339 * dream's replay links (`dream.begun` counts them), a flagged
340 * contradiction (a pair id), a sleep cycle's fades (counts).
341 */
342export function mechFirings(events: readonly DashEvent[], mech: MechId, dreams: readonly DashDream[] = [], limit = 8): Firing[] {
343 const out: Firing[] = [];
344 const push = (e: DashEvent, word: string, parts: FiringPart[], memoryId: string | null, text = e.text): void => {
345 if (out.length < limit) out.push({ key: `${String(e.seq)}.${String(out.length)}`, seq: e.seq, at: e.at, word, parts, memoryId, text });
346 };
347 for (const e of [...events].sort((a, b) => b.seq - a.seq)) {
348 if (out.length >= limit) break;
349 const rule = provedBy(e).find(r => r.mech === mech);
350 if (rule === undefined) continue;
351 // A turn a link reached recall on counts only (2026-10-11): its row does not
352 // say WHICH shown memory the link brought, so naming them all would be wrong.
353 if (e.name === 'recall.decision' && mech === 'association') continue;
354 // Emotion names only the memories that carry a feeling, each with its words.
355 const felt = mech === 'emotional' ? feltOf(e) : [];
356 if (felt.length > 0) {
357 const quoted = quotedTitles(e.text);
358 const own = e.name === 'gate.deposit' ? classify(e)?.memory : undefined;
359 felt.forEach((f, i) => {
360 const title = own?.id === f.id ? own.title : quoted.length === felt.length ? (quoted[i] ?? null) : null;
361 push(e, rule.word, f.words.length > 0 ? [{ id: f.id, title }, ` (${f.words.join(', ')})`] : [{ id: f.id, title }], f.id);
362 });
363 continue;
364 }
365 if (e.name === 'recall.decision' || e.name === 'recall.credit') {
366 const ids = e.name === 'recall.decision' ? [...surfacedIds(e), ...idList(e, 'footnotes')] : idList(e, 'ids');
367 const quoted = quotedTitles(e.text);
368 const word = e.name === 'recall.decision' && rule.word === 'recalled' ? 'came to mind' : rule.word;
369 ids.forEach((id, i) => push(e, word, [{ id, title: quoted.length === ids.length ? (quoted[i] ?? null) : null }], id));
370 continue;
371 }
372 if (e.name === 'dream.journaled' || e.name === 'dream.changed') {
373 const d = dreams.find(x => x.id === e.subject);
374 if (d === undefined) continue;
375 if (e.name === 'dream.journaled') {
376 if (typeof d.journal !== 'string' || d.journal.trim() === '') continue;
377 push(e, rule.word, [firstSentence(d.journal).first], null, d.journal.replace(/\s+/g, ' ').trim());
378 continue;
379 }
380 const action = DREAM_ACTION[mech];
381 if (action === undefined) continue;
382 for (const c of d.changes ?? []) {
383 const m = c.action === action && c.undone !== true ? c.memories?.[0] : undefined;
384 if (m === undefined || m.confidential === true) continue;
385 push(e, rule.word, [{ id: m.id, title: m.text }], m.id);
386 }
387 continue;
388 }
389 if (e.name === 'contradiction.settled' || e.name === 'contradiction.proposed') {
390 const holds = titled(detail(e, 'holds'));
391 const over = titled(detail(e, 'over'));
392 if (holds.id === null || over.id === null) continue;
393 push(e, rule.word, [holds, e.name === 'contradiction.proposed' ? ' may be the newer state of ' : ' holds over ', over], holds.id);
394 continue;
395 }
396 if (e.name === 'revision.pressure') {
397 const target = titled(detail(e, 'targetId'));
398 const by = titled(detail(e, 'challengerId'));
399 if (target.id === null || by.id === null) continue;
400 push(e, rule.word, [by, ' argued with ', target], target.id);
401 continue;
402 }
403 if (e.name === 'mcp.recall' || e.name === 'associate.flush' || e.name === 'contradiction.flagged' || e.name === 'sleep.cycle') continue;
404 const row = classify(e);
405 if (row?.memory === undefined) continue;
406 push(e, rule.word, [{ id: row.memory.id, title: row.memory.title }], row.memory.id);
407 }
408 return out;
409}
410
411/** The ids a firing names, for reading their titles whole. */
412export function firingIds(f: Firing): string[] {
413 return f.parts.flatMap(p => (typeof p === 'string' || p.id === null ? [] : [p.id]));
414}
415
416/**
417 * A firing's sentence, with each memory's title read in full where it was
418 * (`titles`, by id), else the one the row carried; null when a memory has no
419 * title at all (it is left out rather than shown as an id).
420 */
421export function firingTitle(f: Firing, titles: Readonly<Record<string, string>>): string | null {
422 let s = '';
423 for (const p of f.parts) {
424 if (typeof p === 'string') {
425 s += p;
426 continue;
427 }
428 const t = (p.id === null ? undefined : titles[p.id]) ?? p.title;
429 if (t === null || t === '') return null;
430 s += t;
431 }
432 return s;
433}
434
435// ── the recall block ────────────────────────────────────────────────────────
436
437export type RecallBlock = { turn: number; surfaced: string[]; footnotes: { title: string; id: string | null }[] };
438
439/**
440 * The block `core/recall/render.ts` composes, found in any text that carries
441 * it (the engine wraps hook context in a system reminder). Null when absent
442 * or when it is the quiet turn's empty string. A surfaced line is the
443 * memory's gist, as Claude read it; a footnote line is its title and id.
444 */
445export function parseRecallBlock(text: string): RecallBlock | null {
446 const open = /<!--\s*counterparts:recall t=(\d+)\s*-->/.exec(text);
447 if (open === null) return null;
448 const rest = text.slice(open.index + open[0].length);
449 const end = rest.search(/<!--\s*counterparts:recall\/end/);
450 const body = end >= 0 ? rest.slice(0, end) : rest;
451 const surfaced: string[] = [];
452 const footnotes: { title: string; id: string | null }[] = [];
453 let lane: 'none' | 'surfaced' | 'footnote' = 'none';
454 for (const raw of body.split('\n')) {
455 const line = raw.trim();
456 if (line === 'Came to mind:') { lane = 'surfaced'; continue; }
457 if (line.startsWith('Quietly available')) { lane = 'footnote'; continue; }
458 if (!line.startsWith('- ')) continue;
459 const item = line.slice(2).trim();
460 if (lane === 'surfaced') surfaced.push(item);
461 else if (lane === 'footnote') {
462 // A footnote can lead with what it is to another memory ("Earlier (now [id]): ", "Unsettled — may be out of
463 // date, see [id]: ") and trail one ("(earlier: [id])", "(corrects [id])"): the title is what's between,
464 // the id the first one after the lead (the sidebar showed "Earlier (now ): … [mem_…]", 2026-10-13).
465 // The line is `[Linked: |Journal: ][standing lead: ]Title [id][ (pointers)]` (core/recall/render.ts), so the
466 // memory's own id is the one at the end, before any trailing pointers; the lead may also be "Corrected by
467 // [id]" or "Replaced by [id]", alone or joined with "; ", and may sit behind a Linked:/Journal: word.
468 const end = /^(.*)\s*\[([A-Za-z]+_[A-Za-z0-9]+)\](?:\s*\([^()]*\))?$/.exec(item);
469 const m = end ?? /^(.*?)\s*\[([A-Za-z]+_[A-Za-z0-9]+)\]/.exec(item);
470 const front = m === null ? item : (m[1] ?? '');
471 const frame = /^(?:(?:Linked|Journal):\s+)*/.exec(front)?.[0] ?? '';
472 const after = front.slice(frame.length);
473 const lead = /^(Earlier|Unsettled|Corrected by|Replaced by)\b[^:]*?\[[A-Za-z]+_[A-Za-z0-9]+\][^:]*:\s*/.exec(after);
474 const word = lead === null ? '' : `${(lead[1] ?? '').replace(/ by$/, '')}: `;
475 const title = `${frame}${word}${lead === null ? after : after.slice(lead[0].length)}`.trim();
476 footnotes.push({ title, id: m === null ? null : (m[2] ?? null) });
477 }
478 }
479 const turn = Number(open[1]);
480 return { turn: Number.isFinite(turn) ? turn : 0, surfaced, footnotes };
481}
482
483// ── the memory tools, as the model calls them ──────────────────────────────
484
485/** The two names the memory server's tools go by: the npm install's, the plugin's. */
486export const SERVER_SPELLINGS = ['counterparts', 'plugin_counterparts_counterparts'] as const;
487
488/** `mcp__counterparts__remember` → `{ server: 'counterparts', tool: 'remember' }`, ours only. */
489export function ourTool(name: string): { server: string; tool: string } | null {
490 for (const server of SERVER_SPELLINGS) {
491 const prefix = `mcp__${server}__`;
492 if (name.startsWith(prefix)) return { server, tool: name.slice(prefix.length) };
493 }
494 return null;
495}
496
497function firstLine(s: unknown, max = 240): string | null {
498 if (typeof s !== 'string') return null;
499 const line = s.trim().split('\n')[0] ?? '';
500 if (line.length === 0) return null;
501 return line.length > max ? `${line.slice(0, max - 1)}…` : line;
502}
503
504/** A tool result's JSON payload (the server sends it whole as text). */
505export function payloadOf(text: string | undefined): Record<string, unknown> | null {
506 if (typeof text !== 'string') return null;
507 try {
508 const v: unknown = JSON.parse(text);
509 return v !== null && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null;
510 } catch {
511 return null;
512 }
513}
514
515/** `remember` was `note` until 2026-10-10; the old name still answers, so both save. */
516const REMEMBER = new Set(['remember', 'note']);
517
518function memoryId(v: unknown): string | null {
519 return typeof v === 'string' && /^mem_[A-Za-z0-9]+$/.test(v.trim()) ? v.trim() : null;
520}
521
522/**
523 * What a memory tool call that answered without error saved, as "Saved this
524 * session" items in the order written; none for any other tool (a chapter
525 * included: a journal entry), and for a call that stored nothing. A `remember` (or old `note`) or a `session_end` entry with `updates`
526 * replaces that memory (unless `how: open`, which keeps both); its title is
527 * read later, from the dashboard.
528 */
529export function savedItems(tool: string, args: Record<string, unknown>, resultText: string | undefined, at: number, seq: number): SidebarSaved[] {
530 const ours = ourTool(tool);
531 if (ours === null) return [];
532 const p = payloadOf(resultText);
533 if (p !== null && p['stored'] === false) return [];
534 const item = (i: number, title: string, id: string | null, src: Record<string, unknown>): SidebarSaved => {
535 const settled = p?.['settled'] as { ok?: unknown; held?: unknown } | undefined;
536 const refused = REMEMBER.has(ours.tool) && settled !== undefined && (settled.ok === false || settled.held === true);
537 const replacesId = src['how'] === 'open' || refused ? null : memoryId(src['updates']);
538 const body = typeof src['text'] === 'string' ? src['text'].replace(/\s+/g, ' ').trim() : '';
539 return {
540 key: `live:${String(seq)}:${String(i)}`,
541 id,
542 title,
543 at,
544 replaces: null,
545 replacesId,
546 kind: replacesId === null ? 'new' : 'update',
547 ...(body === '' ? {} : { text: body }),
548 };
549 };
550 if (REMEMBER.has(ours.tool)) {
551 const title = firstLine(args['title']) ?? firstLine(args['text']) ?? 'a note';
552 return [item(0, title, memoryId(p?.['id']), args)];
553 }
554 // A chapter is a journal entry, not a memory saved: left out of Saved this session (Mike, 2026-10-10).
555 if (ours.tool === 'session_end') {
556 const list = Array.isArray(args['memories']) ? (args['memories'] as unknown[]) : [];
557 if (typeof p?.['deposited'] === 'number' && p['deposited'] === 0) return [];
558 return list.flatMap((m, i) => {
559 const rec = m !== null && typeof m === 'object' ? (m as Record<string, unknown>) : {};
560 const title = firstLine(rec['title']) ?? firstLine(rec['text']);
561 return title === null ? [] : [item(i, title, null, rec)];
562 });
563 }
564 return [];
565}
566
567/** A memory tool that saves (`remember`, the old `note`, `session_end`); a chapter is a journal entry. */
568export function savesMemory(tool: string): boolean {
569 return REMEMBER.has(tool) || tool === 'session_end';
570}
571
572/** A save older than this when the status file is next read (a pane hidden a while) is not played as new. */
573export const SAVE_FRESH_MS = 2 * 60000;
574
575/**
576 * Whether the status file's new rows hold a save for this session that the
577 * fox has not written down yet (2026-10-20): a `gate.deposit` naming the
578 * session, with `accepted` > 0, written after the last save the fox heard
579 * (`after`, `Director.saveAt`) and within SAVE_FRESH_MS of `now`.
580 *
581 * Every deposit comes through the memory tools (`session_end`, `remember`),
582 * and the `tool.call` hook hears the save as the call returns, after the
583 * call's rows were written: so those rows are older than `after`, and the
584 * same save does not write twice (a second call inside one notepad's run
585 * plays nothing more, and still moves `after`). What is left is a save that hook did not
586 * see (a reload mid-call, an answer it could not read). A burst read in two
587 * looks writes once: the first look's notepad is newer than the rest.
588 */
589export function savedSince(events: readonly DashEvent[], session: string, after: number, now: number): boolean {
590 if (session === '') return false;
591 return events.some(
592 e =>
593 e.name === 'gate.deposit' &&
594 e.at > after &&
595 now - e.at < SAVE_FRESH_MS &&
596 num(e, 'accepted') > 0 &&
597 e.detail?.some(d => (d.key === 'session' || d.key === 'actorId') && d.value === session) === true,
598 );
599}
600
601/** The ids a `recall` call opened by address: its `ids`, or a `handle` that is an id. */
602export function openedIds(tool: string, args: Record<string, unknown>): { ids: string[]; handle: string | null } {
603 const ours = ourTool(tool);
604 if (ours === null || ours.tool !== 'recall') return { ids: [], handle: null };
605 const ids = Array.isArray(args['ids']) ? (args['ids'] as unknown[]).map(memoryId).filter((x): x is string => x !== null) : [];
606 const handle = typeof args['handle'] === 'string' && args['handle'].trim().length > 0 ? args['handle'].trim() : null;
607 const asId = memoryId(handle);
608 return asId === null ? { ids, handle } : { ids: [...ids, asId], handle: null };
609}
610
611// ── a dream ────────────────────────────────────────────────────────────────
612
613/** A dream as the status file carries it, the part the sidebar reads. */
614export type DashDream = {
615 id: string;
616 date: string | null;
617 day: number;
618 state?: string;
619 journal: string | null;
620 counts?: Record<string, number>;
621 changes?: { action: string; said: string; undone?: boolean; memories?: { id: string; text: string; confidential?: boolean }[] }[];
622};
623
624/** The journal's first sentence, and what follows it. */
625export function firstSentence(journal: string): { first: string; rest: string } {
626 const text = journal.replace(/\s+/g, ' ').trim();
627 const m = /^(.+?[.!?])(?:["”’)]*)(?=\s|$)/.exec(text);
628 if (m === null) return { first: text, rest: '' };
629 const first = text.slice(0, m[0].length).trim();
630 return { first, rest: text.slice(m[0].length).trim() };
631}
632
633// ── dates ──────────────────────────────────────────────────────────────────
634
635/** `10-09` or `2025-10-09` as `Oct 9` (with the year when one is given). */
636export function shortDay(s: string): string {
637 const m = /^(?:(\d{4})-)?(\d{2})-(\d{2})$/.exec(s.trim());
638 if (m === null) return '';
639 const month = MONTHS[Number(m[2]) - 1];
640 if (month === undefined) return '';
641 return `${month} ${String(Number(m[3]))}${m[1] === undefined ? '' : ` ${m[1]}`}`;
642}
643
644// ── words and times ────────────────────────────────────────────────────────
645
646/** Word-wrap into lines of at most `w` terminal cells (a wide character counts two; a word longer than a line is cut). */
647export function wrap(text: string, w: number): string[] {
648 const out: string[] = [];
649 let line = '';
650 for (const word0 of text.split(/\s+/).filter(Boolean)) {
651 let word = word0;
652 while (cells(word) > w) {
653 if (line) { out.push(line); line = ''; }
654 const head = headCells(word, w) || (Array.from(word)[0] ?? '');
655 out.push(head);
656 word = word.slice(head.length);
657 }
658 if (!word) continue;
659 if ((line ? cells(line) + 1 : 0) + cells(word) > w) { out.push(line); line = word; }
660 else line = line ? `${line} ${word}` : word;
661 }
662 if (line) out.push(line);
663 return out;
664}
665
666/** A folder as a person says it: a home folder (`/Users/<name>`, `/home/<name>`) as `~`. */
667export function shortDir(dir: string | null): string {
668 if (dir === null) return 'this folder';
669 return dir.replace(/^\/(?:Users|home)\/[^/]+(?=\/|$)/, '~');
670}
671
672/** `s` cut to `w` terminal cells, with an ellipsis. */
673export function ellipsize(s: string, w: number): string {
674 return ellipsizeCells(s, w);
675}
676
677const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
678
679/** The local calendar day of `at`, `YYYY-MM-DD`. */
680export function dateOf(at: number): string {
681 const d = new Date(at);
682 return `${String(d.getFullYear())}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
683}
684
685/**
686 * The time a section's heading carries: `10:25`, `8:07` (a 12-hour clock with
687 * no am or pm, as the mockups have it: every time it shows is recent), or
688 * `Oct 9` before today (`Jan 5 2025` in another year).
689 */
690export function hm(at: number, now: number): string {
691 const d = new Date(at);
692 if (dateOf(at) !== dateOf(now)) return humanDay(dateOf(at), now);
693 const h = d.getHours() % 12;
694 return `${String(h === 0 ? 12 : h)}:${String(d.getMinutes()).padStart(2, '0')}`;
695}
696
697/** `2026-10-09` as `Oct 9`, or `Jan 5 2025` when it is not this year (by `now`). */
698export function humanDay(iso: string, now: number): string {
699 const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
700 const month = m === null ? undefined : MONTHS[Number(m[2]) - 1];
701 if (m === null || month === undefined) return iso;
702 const year = m[1] ?? '';
703 return `${month} ${String(Number(m[3]))}${year === dateOf(now).slice(0, 4) ? '' : ` ${year}`}`;
704}
705
706/** Words that, after `10-20`, make it a range of something rather than a day. */
707const RANGE_UNITS =
708 'lines?|cells?|columns?|cols?|rows?|items?|mins?|minutes?|secs?|seconds?|s|ms|hours?|hrs?|h|days?|weeks?|months?|years?|pages?|steps?|tests?|files?|words?|chars?|characters?|points?|pts?|px|k|x|times?|percent|people|memories|frames?|fps|of';
709
710/**
711 * A short date as the titles write it (`(10-09)`, `10-09: `, `… 10-09`),
712 * rewritten as `<year>-10-09` so the ISO rules below say it: two digits a
713 * side, a real month and day, standing alone. Not a date, so left as written:
714 * part of a longer number or name (`2026-10-09` itself, `#10-09`, `v10-09`,
715 * `0.10-09`, `10-09-2026`, `10-09.5`), a time (`10:09`, `10-09:30`), a range of something
716 * (`10-20 lines`, `10-20%`), an impossible day (`13-09`, `02-30`). The year
717 * is this one: a title's short date is recent, and none is shown for it.
718 */
719function isoShortDates(title: string, year: string): string {
720 if (!/\d{2}-\d{2}/.test(title)) return title;
721 const re = new RegExp(`(?<![\\p{L}\\p{N}_#./:$~-])(\\d{2})-(\\d{2})(?![\\p{L}\\p{N}_/%-])(?![.:]\\d)(?!\\s*(?:${RANGE_UNITS})\\b)`, 'gu');
722 return title.replace(re, (whole, mm: string, dd: string) => {
723 const m = Number(mm);
724 const d = Number(dd);
725 const days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1];
726 return days === undefined || d < 1 || d > days ? whole : `${year}-${mm}-${dd}`;
727 });
728}
729
730/**
731 * A title as the sidebar shows it (never the stored text): an ISO date that
732 * only says today is dropped with what holds it (`(2026-10-10)`,
733 * `2026-10-10: `, `, 2026-10-10)`), `on 2026-10-10` reads `today` and `on
734 * 2026-10-10 morning` `this morning`; any
735 * other ISO date is short and human, `Oct 9`, with the year only when it is
736 * not this one (`Jan 5 2025`). Mike, 2026-10-10. A short date (`(10-09)`,
737 * `10-09: `) reads the same way, as this year's (`isoShortDates`).
738 */
739export function humanDates(title: string, now: number): string {
740 const today = dateOf(now);
741 title = isoShortDates(title, today.slice(0, 4));
742 if (!/\d{4}-\d{2}-\d{2}/.test(title)) return title;
743 const t = today.replace(/-/g, '\\-');
744 const out = title
745 .replace(new RegExp(`\\s*\\(\\s*${t}\\s*\\)`, 'g'), '')
746 .replace(new RegExp(`^\\s*${t}\\s*[:·—–-]\\s*`), '')
747 .replace(new RegExp(`\\s*[:·—–-]\\s*${t}\\s*$`), '')
748 .replace(new RegExp(`\\s*[,;]\\s*${t}(?=\\s*\\))`, 'g'), '')
749 .replace(new RegExp(`\\(\\s*${t}\\s*[,;]\\s*`, 'g'), '(')
750 .replace(new RegExp(`\\b(?:on\\s+)?${t}\\s+(morning|afternoon|evening|night)\\b`, 'g'), 'this $1')
751 .replace(new RegExp(`\\b(?:on|dated)\\s+${t}\\b`, 'g'), 'today')
752 .replace(new RegExp(`\\b${t}\\b`, 'g'), 'today')
753 .replace(/\b(\d{4}-\d{2}-\d{2})\b/g, (_m, iso: string) => humanDay(iso, now))
754 .replace(/\s{2,}/g, ' ')
755 .trim();
756 return out === '' ? title : out;
757}
758
759// ── the first meeting: core's onboarding state ─────────────────────────────
760
761const MEET_STATES: readonly SidebarMeet[] = ['not_started', 'offered', 'later', 'done', 'skipped'];
762
763/** Not read, or read as nothing the sidebar knows: it does nothing about the meeting. */
764export const UNKNOWN_ONBOARDING: SidebarOnboarding = { meet: 'unknown', where: null, style: null };
765
766/**
767 * Core's first-meeting state as a JSON object (`{ meet, where, style }`), read
768 * strictly: anything but an object whose `meet` is one of the five states is
769 * unknown, so a core from before onboarding (a 404 page, an error body, a
770 * renamed field) never moves the sidebar.
771 */
772export function parseOnboarding(text: string): SidebarOnboarding {
773 let raw: unknown;
774 try {
775 raw = JSON.parse(text);
776 } catch {
777 return UNKNOWN_ONBOARDING;
778 }
779 if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return UNKNOWN_ONBOARDING;
780 const rec = raw as Record<string, unknown>;
781 const meet = rec['meet'];
782 if (typeof meet !== 'string' || !(MEET_STATES as readonly string[]).includes(meet)) return UNKNOWN_ONBOARDING;
783 const str = (v: unknown): string | null => (typeof v === 'string' && v.length > 0 ? v : null);
784 return { meet: meet as SidebarMeet, where: str(rec['where']), style: str(rec['style']) };
785}
786
787/**
788 * THE ONE PLACE THE WAKE'S MARKER IS SPELLED. Core writes it on its own line
789 * in every SessionStart wake (done included; `start-fresh` resets it to
790 * not_started): `<!-- counterparts:onboarding meet=<state> -->`. Since
791 * 2026-10-20 (core's ONE TAG, `adapters/store-id.ts`) it is a field of the
792 * wake's own head tag, `<!-- counterparts:wake meet=<state> store=st_…
793 * elements=… bytes=… -->`, or of `<!-- counterparts:session meet=<state> … -->`
794 * in front of a wake that has no head tag; all three forms are read, so this
795 * sidebar reads an older core's wake too. No marker: an older core, the
796 * state unknown. Change the text here if core's changes.
797 */
798export const ONBOARDING_MARKER =
799 /<!--\s*counterparts:(?:onboarding\s+meet=([a-z_]+)\s*|(?:wake|session)\s+(?:[a-z]+=[^\s>]+\s+)*meet=([a-z_]+)(?:\s[^>]*)?)-->/;
800
801/** The state the wake's marker names, or null: no marker, or a state the sidebar doesn't know. */
802export function parseOnboardingMarker(text: string): SidebarMeet | null {
803 const m = ONBOARDING_MARKER.exec(text);
804 const state = m?.[1] ?? m?.[2];
805 return state !== undefined && (MEET_STATES as readonly string[]).includes(state) ? (state as SidebarMeet) : null;
806}
807
808/**
809 * WHICH STORE (core #459, 2026-10-12): the wake carries
810 * `<!-- counterparts:store id=st_… -->` on its own line, and the status file
811 * names the store that wrote it (`storeId`). Two stores on one machine can
812 * share one configuration folder, so the sidebar shows the file's numbers only
813 * when the two agree; either unknown (no marker, an older core, a store whose
814 * id is not minted yet: null) is "can't tell", and it carries on. Since
815 * 2026-10-20 it is the `store=` field of the wake's head tag (or of the
816 * `counterparts:session` tag), read as the onboarding marker's `meet=` is.
817 */
818export const STORE_MARKER =
819 /<!--\s*counterparts:(?:store\s+id=(st_[0-9a-f]{16})\s*|(?:wake|session)\s+(?:[a-z]+=[^\s>]+\s+)*store=(st_[0-9a-f]{16})(?:\s[^>]*)?)-->/
820
821/** The store the wake names, or null. */
822export function parseStoreMarker(text: string): string | null {
823 const m = STORE_MARKER.exec(text)
824 return m?.[1] ?? m?.[2] ?? null
825}
826
827/** Whether a status file written by `dash`'s store belongs to another store than the wake's: only when both are known and differ. */
828export function otherStore(wake: string | null, dash: string | null): boolean {
829 return wake !== null && dash !== null && wake !== dash
830}
831
832/**
833 * A folder where a first meeting makes sense: Counterparts on by its own
834 * entry or a parent's, or unset (on by default). Not paused, off or
835 * observer (nothing new is kept there), and not unknown (never acted on as on).
836 */
837export function canMeet(folderMode: string): boolean {
838 return folderMode === 'on' || folderMode === 'unset';
839}
840
841// ── a glance before anything happens: the wake's own lines ─────────────────
842
843/** What the sidebar shows before the session has done anything: a heading and one short text. */
844export type Glance = { head: string; text: string }
845
846/**
847 * THE ONE PLACE THE WAKE'S GLANCE LINES ARE SPELLED (2026-10-15, Mike: show
848 * the first that has something, in this order). Core writes them in every
849 * SessionStart wake: `Last here: …` (handoff/last-here.ts), `Where I left off
850 * in this directory (…): …` (handoff/index.ts), the `Coming up:` heading
851 * (self/briefing.ts FRAMING.horizon) with `- <date> · <text>` items, and
852 * `Yesterday, <date>: …` (handoff/last-here.ts). Change these if core's change;
853 * a wake without them shows no glance, nothing else.
854 */
855const GLANCE_LAST = /^Last here:\s*(.+)$/m
856const GLANCE_LEFT_OFF = /^Where I left off in this directory \([^)]*\):\s*(.+)$/m
857const GLANCE_COMING = /^Coming up:\s*\n-\s*(.+)$/m
858// "Yesterday, Oct 15: …", or since 2026-10-16 at a session start "Yesterday: …" (its date on the `Now:` line).
859const GLANCE_YESTERDAY = /^Yesterday(?:, ([^:]+))?:\s*(.+)$/m
860/**
861 * A Coming up item's date, every way core's `datePrefix` (self/briefing.ts)
862 * writes it: `due D`, `was due D`, `due D, every May 14`, `[by ]L (due D…)`,
863 * `[by ]L (was due D…)`, `[by ]L (of H)`, `[by ]L` — then ` · `. The date it
864 * is about comes out alone: the due date where there is one, else the learned.
865 */
866// Each date whole (`2026-10-15`) or, since 2026-10-16, short in the wake's year (`Oct 15`).
867const COMING_DATE = /^(?:by\s+)?(?:(?:was due|due)\s+(?:yesterday,\s+)?(\d{4}-\d{2}-\d{2}|[A-Z][a-z]{2} \d{1,2})(?:,[^·]*)?|(\d{4}-\d{2}-\d{2}|[A-Z][a-z]{2} \d{1,2})(?:\s*\((was due|due|of)\s+(?:yesterday,\s+)?(\d{4}-\d{2}-\d{2}|[A-Z][a-z]{2} \d{1,2})[^)]*\))?)\s*·\s*/
868
869/** Memory, chapter and handoff ids, and the asides that only point at them: not for the person. */
870function forPerson(text: string): string {
871 return text
872 .replace(/\((?:earlier|the whole of it is|expand)[^)]*\)/gi, '')
873 .replace(/\[?\b(?:mem|epi|sch|ctr)_[0-9a-f]{6,}\b\]?,?/g, '')
874 .replace(/\(\s*\)/g, '')
875 .replace(/[;,]\s*(?=[;,.]|$)/g, '')
876 .replace(/\s+([.,;])/g, '$1')
877 .replace(/\s{2,}/g, ' ')
878 .trim()
879}
880
881/** The first glance line the wake has, in Mike's order: where things were left, what's coming up, yesterday. */
882export function parseGlance(text: string): Glance | null {
883 for (const re of [GLANCE_LAST, GLANCE_LEFT_OFF]) {
884 const m = re.exec(text)?.[1]
885 if (m !== undefined && forPerson(m).length > 0) return { head: 'Last here', text: forPerson(m) }
886 }
887 const coming = GLANCE_COMING.exec(text)?.[1]
888 if (coming !== undefined) {
889 const t = forPerson(coming.replace(COMING_DATE, (_m, lone?: string, learned?: string, word?: string, inner?: string) =>
890 `${lone ?? (word === 'of' ? learned : inner ?? learned) ?? ''} · `))
891 if (t.length > 0) return { head: 'Coming up', text: t }
892 }
893 const y = GLANCE_YESTERDAY.exec(text)
894 if (y !== null) {
895 const t = forPerson(y[2] ?? '').replace(/^[\s;,]*(?:and \d+ more)?[.;\s]*$/, '')
896 if (t.length > 0) return { head: y[1] === undefined ? 'Yesterday' : `Yesterday, ${y[1]}`, text: t }
897 }
898 return null
899}
900hooks/sidebar/hooks/pane.tsx 147 lines1/**
2 * The pane's tree, on every surface: the title (the header in `desktop.tsx`
3 * places it), a paused folder's banner, the body, and the footer of
4 * instructions. No `$`: the Pane hook in `register.tsx` reads the state and
5 * builds the body (its `Client` tag must stay in the hooks module's own
6 * source).
7 *
8 * v1 (the directory trim, 2026-10-14): nothing in the pane acts. No Button
9 * runs a command or calls a tool: the intro row, the folder switch and its
10 * confirm, and the view and avatar switches are gone; the footer says how to
11 * do each instead (`words.ts#footerLines`). Nothing is a link either
12 * (2026-10-14): COUNTERPARTS is its name, and the dashboard is
13 * `/counterparts:dashboard`, which the footer says.
14 *
15 * The full build (2026-10-16) puts some back, drawn from `actions.tsx`'s
16 * pieces (`FullPane`, below): COUNTERPARTS ↗ as a link on the terminal, and a
17 * footer the hooks module draws as body lines so its rows can be clicked.
18 */
19
20import type { Elements } from 'claude-code'
21
22import type { SidebarScope } from '../types'
23import { shortDir } from './feed'
24import { clip } from './sections'
25import type { Line } from './sections'
26import { P, bg } from './theme'
27import { RESUME_SAY, footerLines } from './words'
28import type { FooterShow } from './words'
29
30/** The constructors the pane draws with: every surface has these. */
31export type PaneEls = Pick<Elements['terminal'], 'Box' | 'Text'>
32
33/** What a title link wraps its words in, or null: the title is plain words. */
34export type TitleLink = ((words: JSX.Element[]) => JSX.Element) | null
35
36/**
37 * What only the full plugin's build adds to the pane (2026-10-16): `actions.tsx` holds it, and
38 * sets `state.ts#run.full` to it when `full.tsx` registers that file; the directory's build never
39 * loads it, so `run.full` stays null there and the pane draws none of it. Pure: no `$`. What a
40 * click on these does is `actions.tsx`'s own hook (a command put in the prompt box) or
41 * `register.tsx#setSwitch` (the stored view or avatar).
42 */
43export type FullPane = {
44 /** COUNTERPARTS as a link to the dashboard at `href` (core's status file says where), or null where it can't be one. */
45 titleLink: (els: Pick<Elements['terminal'], 'Link'>, href: string | null) => TitleLink
46 /** Whether "Meet your counterpart" shows: core's state, the folder, and this session's speak-first. */
47 meetShows: (meet: string, folderMode: string, firedIn: string | null, session: string, filledIn: string | null) => boolean
48 /** The Meet row (and a note under it), then a blank row: lines for the top of the body. */
49 meetLines: (w: number, note: string | null) => Line[]
50 /** The footer, in lines the body's surface module draws (so its rows can be clicked): its rule, the instructions, the switches. */
51 footLines: (s: { fit: number; w: number; prose: boolean; paused: boolean; view: string; avatar: string; note: string | null; intro: boolean; fills: boolean }) => Line[]
52}
53
54// ── the title, which the header places ──
55
56/**
57 * COUNTERPARTS, plain text (no link, 2026-10-14). `lead` puts a dot before it. With `link` (the full
58 * build, on the terminal, 2026-10-16) it is a link to the dashboard, with `↗` after it.
59 */
60export function titleButton(els: PaneEls, o: { lead: boolean; paused: boolean; dot: string | null; link?: TitleLink }): JSX.Element {
61 const { Box, Text } = els
62 const link = o.link ?? null
63 const words = [
64 ...(o.lead ? [<Text key="dot" color={o.dot ?? P.accentDim}>◉ </Text>] : []),
65 <Text key="name" color={o.paused ? P.dim : P.accent} bold>COUNTERPARTS</Text>,
66 ...(o.lead && link !== null ? [<Text key="arrow" color={P.accentDim}> ↗</Text>] : []),
67 ]
68 return (
69 <Box key="title" flexDirection="row">
70 <Text>{link === null ? words : link(words)}</Text>
71 </Box>
72 )
73}
74
75// ── under the header ──
76
77/** A paused (or off) folder says so before anything else in the pane: three rows, said, not pressed. */
78export function pausedBanner(els: PaneEls, scope: SidebarScope, w: number): JSX.Element[] {
79 const { Text } = els
80 const off = scope.mode === 'off'
81 const how = off
82 ? scope.own ? 'ask Claude to turn it back on' : `off by ${shortDir(scope.setBy)}`
83 : scope.own ? RESUME_SAY : `paused by ${shortDir(scope.setBy)}`
84 return [
85 <Text key="paused" color={P.accent2} bold>{clip(off ? '◌ Counterparts off here' : '⏸ Counterparts paused here', w)}</Text>,
86 <Text key="paused-how" color={P.accent2}>{clip(how, w)}</Text>,
87 <Text key="paused-gap"> </Text>,
88 ]
89}
90
91// ── the footer: how to do what the pane doesn't ──
92
93/** The footer's rows at `w` (`fit`: the cells its text may take, wider on a surface with its own font): a rule (or a blank) and the lines. */
94export function footerRows(fit: number, paused = false, show?: FooterShow): number {
95 return 1 + footerLines(fit, paused, show).length
96}
97
98export function footer(els: PaneEls, s: { w: number; fit: number; prose: boolean; paused: boolean; show?: FooterShow }): JSX.Element {
99 const { Box, Text } = els
100 const { w, fit, prose, paused, show } = s
101 return (
102 <Box key="footer" flexDirection="column" width={w}>
103 {prose ? <Text> </Text> : <Text color={P.faint}>{'─'.repeat(w)}</Text>}
104 {footerLines(fit, paused, show).map((l, i) => (
105 <Text key={`f${String(i)}`}>
106 <Text color={P.mid}>{l.label}</Text>
107 {l.how === '' ? null : <Text color={P.hi}>{l.how}</Text>}
108 </Text>
109 ))}
110 </Box>
111 )
112}
113
114/** The body on a surface with no Client modules (mobile, an editor): the same lines, not clickable. */
115export function plainBody(els: PaneEls, lines: readonly Line[]): JSX.Element {
116 const { Box, Text } = els
117 return (
118 <Box key="body" flexDirection="column">
119 {lines.map((l: Line, y: number) => (
120 <Text key={`b${String(y)}`} color={l.segs[0]?.c ?? P.text}>{l.segs.map(s => s.t).join('') || ' '}</Text>
121 ))}
122 </Box>
123 )
124}
125
126/**
127 * The pane's frame: the rows in a column, the panel's colour behind them, at least as tall as the pane.
128 * `top` (the fox's stage): rows above, the last of them (the stage) drawn edge to edge, outside the padding.
129 */
130export function frame(els: PaneEls, W: number, fill: number, rows: JSX.Element[], top: JSX.Element[] | null = null): JSX.Element {
131 const { Box } = els
132 if (top !== null && top.length > 0) {
133 return (
134 <Box flexDirection="column" width={W} minHeight={fill} {...bg(P.panel)}>
135 <Box key="stage-head" flexDirection="column" paddingX={1}>{top.slice(0, -1)}</Box>
136 {top[top.length - 1]}
137 <Box key="stage-rest" flexDirection="column" paddingX={1} flexGrow={1}>{rows}</Box>
138 </Box>
139 )
140 }
141 return (
142 <Box flexDirection="column" paddingX={1} width={W} minHeight={fill} {...bg(P.panel)}>
143 {rows}
144 </Box>
145 )
146}
147hooks/sidebar/hooks/sections.ts 634 lines1/**
2 * The pane's body, laid out as lines: Memories, Subconscious, Saved this
3 * session, Mechanisms today and Last Dream, at the
4 * pane's width, folded to its height. Pure: no `$`, no engine. The hooks
5 * module hands the result to the `Client` surface module (`./body.tsx`),
6 * which draws the lines and reads clicks by row.
7 *
8 * Lineage: the round-3 mockups Mike chose on 2026-10-10
9 * (`~/counterparts-notes/mockups/2026-10-10-mod-round3/compose/compose3.ts`):
10 * its palette, its heading (`Label ──── right`), its wrap and clip, its
11 * half-height bars and its fold ladder, with the round-3 decisions that
12 * override its PNGs (FEEDBACK-all.md): "Memories ──── 10:25" and
13 * "Subconscious ────" are two headings; each saved item starts with its stage
14 * dot on its first line only, wrapped lines back at the left edge.
15 *
16 * Mike's rules, everywhere: width is scarce, so no decoration that takes a
17 * column across many lines (no quote rules, gutters, hanging indents or
18 * bullets on list items); space goes to information, never to saying what
19 * isn't shown (no "+N more" line); a click opens an item in place, every
20 * time, and never opens the dashboard by itself (v0.2 polish, 2026-10-10).
21 */
22
23import type {
24 SidebarDream,
25 SidebarMechOpen,
26 SidebarMemoryRef,
27 SidebarMind,
28 SidebarOpen,
29 SidebarSaved,
30 SidebarToday,
31} from '../types'
32import { dateOf, hm, humanDates } from './feed'
33import type { Glance } from './feed'
34import { MECHS, STAGES, hex, stageOf } from './mechanisms'
35import type { MechId } from './mechanisms'
36import { STATUS_STALE_MS, agoWords } from './status'
37import { P } from './theme'
38import { cells, headCells } from './width'
39
40/** Bars a shade under the site's full stage colour. */
41const BAR_K = 0.84
42
43/**
44 * THE OPENED CAP: a click opens any item in place (Mike, 2026-10-10: "click
45 * = expand in place, same every time"), showing its text whole up to this
46 * many lines at the pane's width; longer, 20 lines, the last ending with a
47 * cyan `more` that opens that memory on the dashboard (`#memories?id=`).
48 * Twenty lines of 32 columns is about 600 characters, near the median
49 * memory (626, measured on 77 of the live store's newest, 2026-10-10).
50 */
51export const OPEN_MAX_LINES = 20
52
53/** The word that ends a cut opened text, a link to the rest: drawn cyan, no icon, on the same line. */
54export const MORE = 'more'
55
56/**
57 * Every item in Memories, Subconscious and Saved this session (and a
58 * mechanism's firing) takes up to this many lines: when they don't all fit,
59 * fewer show, never one cut shorter (Mike, 2026-10-10, replacing
60 * Subconscious's "one line, up to four").
61 */
62const ITEM_LINES = 3
63/**
64 * The most saved items the list draws (the seed reads as many): a long
65 * session's dozens would only lengthen the fold ladder, a step an item, and
66 * every drawing walks it.
67 */
68const SAVED_MAX = 12
69
70/**
71 * One run of a line. On a prose surface (BodyProps.prose) three more say how it is laid out rather than
72 * spelled with spaces: `cw`, a column that many cells wide; `fill` of `of`, a bar that share of a column `of` cells wide;
73 * `grow`, the space that pushes what follows to the edge.
74 */
75export type Seg = { t: string; c: string; b?: true; i?: true; cw?: number; fill?: number; of?: number; grow?: true }
76/**
77 * One row of the body: its pieces, and what a click on it names; `link`, a
78 * click from column `from` (0-based, in cells) to the row's end names
79 * another key instead (the `more` at the end of a cut text). The hooks
80 * module hands every row over without one (no links, 2026-10-14): `more` is
81 * words, the rest of the text is on the dashboard (`/counterparts:dashboard`).
82 */
83export type Line = { segs: Seg[]; key?: string; link?: { from: number; key: string } }
84
85const seg = (t: string, c: string, o: { b?: boolean; i?: boolean } = {}): Seg => ({ t, c, ...(o.b ? { b: true as const } : {}), ...(o.i ? { i: true as const } : {}) })
86const line = (segs: Seg[], key?: string): Line => (key === undefined ? { segs } : { segs, key })
87const BLANK: Line = { segs: [] }
88
89// ── text ───────────────────────────────────────────────────────────────────
90
91export const TRAIL = /[\s,;:·—–-]+$/
92
93/**
94 * Word wrap to `width` cells (the first line to `first`); past `maxLines`
95 * the last line ends at a word with `…`. A word longer than a line is cut.
96 */
97export function wrapN(text: string, width: number, maxLines = 99, first = width): string[] {
98 const words = text.split(/\s+/).filter(Boolean)
99 const lines: string[] = []
100 const room = (): number => Math.max(1, lines.length === 0 ? first : width)
101 let i = 0
102 while (i < words.length) {
103 const w = room()
104 if (lines.length === maxLines - 1) {
105 const rest = words.slice(i).join(' ')
106 if (cells(rest) <= w) {
107 lines.push(rest)
108 return lines
109 }
110 let s = ''
111 for (let j = i; j < words.length; j++) {
112 const t = s === '' ? (words[j] ?? '') : `${s} ${words[j] ?? ''}`
113 if (cells(`${t.replace(TRAIL, '')}…`) > w) break
114 s = t
115 }
116 if (s === '') s = headCells(words[i] ?? '', w - 1)
117 lines.push(`${s.replace(TRAIL, '')}…`)
118 return lines
119 }
120 let cur = words[i] ?? ''
121 if (cells(cur) > w) {
122 const head = headCells(cur, w)
123 lines.push(head)
124 words[i] = cur.slice(head.length)
125 continue
126 }
127 i += 1
128 while (i < words.length && cells(cur) + 1 + cells(words[i] ?? '') <= w) {
129 cur += ` ${words[i] ?? ''}`
130 i += 1
131 }
132 lines.push(cur)
133 }
134 return lines
135}
136
137/** One line: the whole text if it fits, else cut mid-word with `…`, so the line is used to its last cell. */
138export function clip(s: string, w: number): string {
139 if (cells(s) <= w) return s
140 let cut = headCells(s, Math.max(0, w - 1))
141 const next = s.slice(cut.length, cut.length + 1)
142 // a stub of one or two letters reads worse than nothing: end at the word before it
143 const sp = cut.lastIndexOf(' ')
144 if (next !== ' ' && sp > 0 && cells(cut) - sp - 1 <= 2) cut = cut.slice(0, sp)
145 return `${cut.replace(TRAIL, '')}…`
146}
147
148/** `Label ──── right`: the label bold, a faint rule, the right dim (folded: `right ›`, a little brighter). */
149export function heading(label: string, right: string, w: number, o: { folded?: boolean; key?: string } = {}): Line {
150 const r = o.folded === true ? `${right} ›`.trim() : right
151 const segs: Seg[] = [seg(label, P.head, { b: true })]
152 const ruleN = w - cells(label) - 1 - (r === '' ? 0 : cells(r) + 1)
153 if (ruleN >= 1) segs.push(seg(` ${'─'.repeat(ruleN)}`, P.faint))
154 if (r !== '') segs.push(seg(ruleN >= 1 ? ` ${r}` : ` ${r}`, o.folded === true ? P.mid : P.dim))
155 return line(segs, o.key)
156}
157
158/** Lines of plain text in one colour, each carrying the key. */
159function plain(texts: readonly string[], c: string, key?: string, o: { b?: boolean; i?: boolean } = {}): Line[] {
160 return texts.map(t => line([seg(t, c, o)], key))
161}
162
163// ── what the body is drawn from ──────────────────────────────────────────────
164
165export type BodyState = {
166 /** Text columns (the pane's body less its padding). */
167 w: number
168 /** Rows the body may take before the footer. */
169 rows: number
170 now: number
171 mind: SidebarMind | null
172 saved: readonly SidebarSaved[]
173 today: SidebarToday | null
174 dream: SidebarDream | null
175 open: SidebarOpen | null
176 mech: SidebarMechOpen | null
177 focus: string | null
178 dash: 'unknown' | 'up' | 'down' | 'other'
179 /** When the status file the numbers come from was written (null: none read): an old one says its age. */
180 statusAt?: number | null
181 /**
182 * A surface that sets text in its own font (the desktop): a blank row between items, and the chart's rows as
183 * a name column, a solid bar and a count at the edge, since padding with spaces lines nothing up there.
184 */
185 prose?: boolean
186 /** The pane's own text width in cells, when `w` was widened for a prose surface's narrower font (bars use it). */
187 cellsW?: number
188 /** The wake's first glance line (Last here, Coming up, Yesterday), or null. */
189 glance?: Glance | null
190}
191
192/** How far each section is folded: the ladder's knobs. */
193type Fold = {
194 /** Memories items shown (each whole, up to ITEM_LINES). */
195 memShow: number
196 /** An opened item's text, in lines. */
197 text: number
198 /** Subconscious items shown; 0 folds it to its heading. */
199 sub: number
200 savedShow: number
201 savedFolded: boolean
202 chartFolded: boolean
203 events: number
204 dreamLines: number
205 excerpt: number
206 dreamFolded: boolean
207 mindFolded: boolean
208 /** The glance (Last here, Coming up, Yesterday) left out: the first thing to give way. */
209 glanceOff: boolean
210}
211
212const FULL: Fold = {
213 memShow: 99, text: OPEN_MAX_LINES, sub: 4, savedShow: SAVED_MAX, savedFolded: false, chartFolded: false,
214 events: 6, dreamLines: 3, excerpt: OPEN_MAX_LINES, dreamFolded: false, mindFolded: false, glanceOff: false,
215}
216
217/** One fold of the ladder; `fold` when it folds a section to its heading. */
218type Step = { label: string; section: string; apply: (f: Fold) => Fold; fold: boolean }
219const step = (label: string, section: string, apply: (f: Fold) => Fold): Step => ({ label, section, apply, fold: label.endsWith('folded') })
220const savedTo = (n: number) => step(`saved shows ${String(n)}`, 'saved', f => ({ ...f, savedShow: Math.min(f.savedShow, n) }))
221const savedFold = step('saved folded', 'saved', f => ({ ...f, savedFolded: true }))
222const subTo = (n: number) => step(`subconscious ${String(n)}`, 'sub', f => ({ ...f, sub: Math.min(f.sub, n) }))
223const dreamTo = (n: number) => step(`dream ${String(n)} lines`, 'dream', f => ({ ...f, dreamLines: Math.min(f.dreamLines, n) }))
224const excerptTo = (n: number) => step(`dream excerpt ${String(n)} lines`, 'dream', f => ({ ...f, excerpt: Math.min(f.excerpt, n) }))
225const textTo = (n: number) => step(`opened text ${String(n)} lines`, 'open', f => ({ ...f, text: Math.min(f.text, n) }))
226const eventsTo = (n: number) => step(`events ${String(n)}`, 'chart', f => ({ ...f, events: Math.min(f.events, n) }))
227const memTo = (n: number) => step(`memories shows ${String(n)}`, 'mind', f => ({ ...f, memShow: Math.min(f.memShow, n) }))
228const chartFold = step('chart folded', 'chart', f => ({ ...f, chartFolded: true }))
229const mindFold = step('memories folded', 'mind', f => ({ ...f, mindFolded: true, sub: 0 }))
230const dreamFold = step('dream folded', 'dream', f => ({ ...f, dreamFolded: true }))
231const glanceGone = step('glance off', 'glance', f => ({ ...f, glanceOff: true }))
232/**
233 * Saved items, fewer one at a time (down to `to`), each keeping its two
234 * lines; `savedFold` then folds the section to its heading. Never one line each: Mike would rather read
235 * fewer titles whole than many cut short (his standing complaint about v0.1,
236 * restated for v0.2 on 2026-10-10), so how many fit is the room's to decide,
237 * not a cut.
238 */
239function savedFewer(n: number, to = 1): Step[] {
240 const out: Step[] = []
241 for (let k = n - 1; k >= Math.max(1, to); k--) out.push(savedTo(k))
242 return out
243}
244
245/** A mechanism's firings, fewer one at a time, each keeping its lines. */
246const EVENTS_DOWN = [eventsTo(5), eventsTo(4), eventsTo(3), eventsTo(2)]
247
248/**
249 * WHAT FOLDS FIRST, per what is open (compose3.ts's ladder, Mike approved
250 * its 160x48 result, less its "saved 1 line each" step): saved items go
251 * fewer, then the section folds to its heading; then the dream shortens, the
252 * subconscious shows fewer; the chart and the memories fold last. An opened
253 * item keeps its room longest: the rest folds around it.
254 */
255function ladders(s: BodyState): Readonly<Record<'default' | 'open' | 'mech' | 'dream', readonly Step[]>> {
256 const n = Math.min(s.saved.length, SAVED_MAX)
257 const saved = [...savedFewer(n), savedFold]
258 return {
259 default: [glanceGone, ...saved, dreamTo(2), subTo(3), subTo(2), dreamTo(1), subTo(1), memTo(2), subTo(0), memTo(1), chartFold, mindFold, dreamFold],
260 // An opened item's text is the last to give way (cut, it ends with `more`); the dream (two rows) folds
261 // before the chart (twelve).
262 open: [glanceGone, ...saved, dreamTo(1), subTo(1), subTo(0), dreamFold, chartFold, textTo(14), textTo(10), textTo(8), textTo(5)],
263 mech: [glanceGone, ...saved, dreamTo(1), mindFold, ...EVENTS_DOWN, dreamFold, eventsTo(1)],
264 // The dream the person opened keeps its words while the saved list goes down to two items; past that its
265 // excerpt shortens before the last two go (the round-3 160x48 frame: two saved, the dream's first sentence).
266 dream: [glanceGone, chartFold, ...savedFewer(n, 2), excerptTo(14), excerptTo(10), excerptTo(7), excerptTo(5), excerptTo(3), ...(n > 1 ? [savedTo(1)] : []), savedFold, subTo(1), subTo(0), mindFold],
267 }
268}
269
270// ── the sections ─────────────────────────────────────────────────────────────
271
272/**
273 * `text` wrapped to `w`, at most `max` lines. Cut, the last line ends at a
274 * word with `…` and, when `moreKey` names where the rest is, a cyan `more`
275 * on that same line (its cells a link to `moreKey`).
276 */
277function textLines(text: string, w: number, max: number, c: string, key: string, moreKey: string | null, o: { b?: boolean; i?: boolean } = {}, cut = false): Line[] {
278 const all = wrapN(text, w)
279 if (all.length <= max && !(cut && moreKey !== null)) return plain(all, c, key, o)
280 if (moreKey === null) return plain(wrapN(text, w, max), c, key, o)
281 const head = all.slice(0, Math.max(0, Math.min(all.length, max) - 1))
282 const room = w - cells(MORE) - 1
283 const last = wrapN(all.slice(head.length).join(' '), room, 1)[0] ?? ''
284 return [
285 ...plain(head, c, key, o),
286 { segs: [seg(last, c, o), seg(' ', c), seg(MORE, P.accent)], key, link: { from: cells(last) + 1, key: moreKey } },
287 ]
288}
289
290/**
291 * An opened memory in place: its title in full (bold, after `dot` on its
292 * first line when given), its text (up to the cap, then `more`), what it is,
293 * and `extra` lines (a saved update's `replaces …`).
294 */
295function opened(s: BodyState, key: string, fallbackTitle: string, f: Fold, dot?: Seg, extra: Line[] = []): Line[] {
296 const o = s.open
297 const title = humanDates(o?.title ?? fallbackTitle, s.now)
298 const out = wrapN(title, s.w, 4, dot === undefined ? s.w : s.w - cells(dot.t)).map((t, i) =>
299 line([...(i === 0 && dot !== undefined ? [dot] : []), seg(t, P.hi, { b: true })], key),
300 )
301 if (o === null || o.key !== key) return out
302 if (o.status === 'loading') return [...out, line([seg('opening…', P.dim)], key), ...extra]
303 if (o.status === 'error') return [...out, ...plain(wrapN(o.text || "couldn't read it", s.w, 2), P.dim, key), ...extra]
304 if (o.text !== '') out.push(...textLines(o.text, s.w, f.text, P.text, key, o.id === null ? null : `more:${o.id}`, {}, o.cut === true))
305 if (o.meta !== null) out.push(line([seg(o.meta, P.dim)], key))
306 out.push(...extra)
307 return out
308}
309
310function memories(s: BodyState, f: Fold): Line[] {
311 const m = s.mind
312 if (m === null || m.surfaced.length === 0) return []
313 const time = hm(m.at, s.now)
314 if (f.mindFolded && s.open?.key.startsWith('mem:') !== true) return [heading('Memories', time, s.w, { folded: true, key: 'head:mind' })]
315 const out: Line[] = [heading('Memories', time, s.w, { key: 'head:mind' })]
316 const openIdx = s.open?.key.startsWith('mem:') === true ? Number(s.open.key.slice(4)) : -1
317 m.surfaced.slice(0, Math.max(f.memShow, openIdx + 1, 1)).forEach((r, i) => {
318 const key = `mem:${String(i)}`
319 if (s.open?.key === key) out.push(...opened(s, key, r.title, f))
320 else out.push(...plain(wrapN(humanDates(r.title, s.now), s.w, ITEM_LINES), P.hi, key))
321 })
322 return out
323}
324
325/** A footnote's title, up to ITEM_LINES lines; `↗ opened` after it when Claude opened it, on its last line when it fits. */
326function subTitle(r: SidebarMemoryRef, key: string, w: number, now: number): Line[] {
327 const c = r.opened === true ? P.text : P.mid
328 const title = humanDates(r.title, now)
329 if (r.opened !== true) return plain(wrapN(title, w, ITEM_LINES), c, key)
330 const mark = [seg(' ', P.dim), seg('↗', P.accent), seg(' opened', P.dim)]
331 const markW = cells(' ↗ opened')
332 let ls = wrapN(title, w, ITEM_LINES)
333 const lastW = cells(ls[ls.length - 1] ?? '')
334 if (lastW + markW > w) {
335 if (ls.length < ITEM_LINES) return [...plain(ls, c, key), line(mark.slice(1), key)]
336 // the third line gives the mark its room
337 ls = [...ls.slice(0, -1), ...wrapN(wrapN(title, w).slice(ls.length - 1).join(' '), w - markW, 1)]
338 }
339 return ls.map((t, i) => line([seg(t, c), ...(i === ls.length - 1 ? mark : [])], key))
340}
341
342function subconscious(s: BodyState, f: Fold): Line[] {
343 const m = s.mind
344 if (m === null || m.footnotes.length === 0) return []
345 // The time goes here only when Memories, which carries it, is not drawn.
346 const time = m.surfaced.length === 0 ? hm(m.at, s.now) : ''
347 const openIdx = s.open?.key.startsWith('sub:') === true ? Number(s.open.key.slice(4)) : -1
348 const n = Math.min(m.footnotes.length, Math.max(f.sub, openIdx + 1))
349 if (n === 0) {
350 const right = time === '' ? String(m.footnotes.length) : `${String(m.footnotes.length)} · ${time}`
351 return [heading('Subconscious', right, s.w, { folded: true, key: 'head:mind' })]
352 }
353 const out: Line[] = [heading('Subconscious', time, s.w, { key: 'head:mind' })]
354 m.footnotes.slice(0, n).forEach((r, i) => {
355 const key = `sub:${String(i)}`
356 out.push(...(s.open?.key === key ? opened(s, key, r.title, f) : subTitle(r, key, s.w, s.now)))
357 })
358 return out
359}
360
361function stageDot(kind: SidebarSaved['kind']): string {
362 return hex(kind === 'new' ? STAGES.encoding.col : STAGES.transformation.col)
363}
364
365function saved(s: BodyState, f: Fold): Line[] {
366 // A chapter is a journal entry, not a saved memory (a state written by an earlier copy may hold one).
367 const list = s.saved.filter(it => (it.kind as string) !== 'chapter')
368 const n = list.length
369 if (n === 0) return []
370 if (f.savedFolded && s.open?.key.startsWith('saved:') !== true) return [heading('Saved this session', String(n), s.w, { folded: true, key: 'head:saved' })]
371 const out: Line[] = [heading('Saved this session', String(n), s.w, { key: 'head:saved' })]
372 // An opened item is never folded away: the list shows at least down to it.
373 const openIdx = list.findIndex(it => s.open?.key === `saved:${it.key}`)
374 for (const it of list.slice(0, Math.min(Math.max(f.savedShow, openIdx + 1), n))) {
375 const key = `saved:${it.key}`
376 if (s.open?.key === key) {
377 // What an update replaces shows only opened (Mike, 2026-10-10: no `replaces` line in the list).
378 const extra = it.kind === 'update' ? plain(wrapN(`replaces ${humanDates(it.replaces ?? 'an earlier memory', s.now)}`, s.w, 3), P.dim, key) : []
379 out.push(...opened(s, key, it.title, f, seg('● ', stageDot(it.kind)), extra))
380 } else {
381 // The stage dot on the first line only; wrapped lines go back to the left edge, up to three, one colour.
382 wrapN(humanDates(it.title, s.now), s.w, ITEM_LINES, s.w - 2).forEach((t, i) => {
383 out.push(line([...(i === 0 ? [seg('● ', stageDot(it.kind))] : []), seg(t, P.hi)], key))
384 })
385 }
386 }
387 return out
388}
389
390/**
391 * `▄▄▄▖`: a half-height bar in half-cell steps, at least one half. On a log
392 * scale (2026-10-15, Mike, lightly held): one mechanism firing 144 times left
393 * every other bar a sliver, so 1, 10 and 100 are now even steps; the count
394 * beside the bar says the number.
395 */
396export function bar(v: number, max: number, width: number): string {
397 const share = Math.log1p(Math.max(0, v)) / Math.log1p(Math.max(1, max))
398 const halves = Math.max(1, Math.round(share * width * 2))
399 return '▄'.repeat(Math.floor(halves / 2)) + (halves % 2 === 1 ? '▖' : '')
400}
401
402/** The Mechanisms section before any session has written the status file (`status.ts`). */
403export const WAITING = 'Waiting for the first session: memory writes what it did here after a turn.'
404
405/** What shows in place of another store's numbers. */
406export const OTHER_STORE = 'The status file is another memory’s.'
407
408function chart(s: BodyState, f: Fold): Line[] {
409 const t = s.today
410 if (t === null) {
411 if (s.dash === 'down') {
412 // No status file yet (a new install, before its first turn): calm, dim, nothing to do.
413 return [heading('Mechanisms today', '', s.w), ...plain(wrapN(WAITING, s.w), P.dim)]
414 }
415 if (s.dash === 'other') {
416 // The status file is another store's (core #459): none of its numbers here.
417 return [heading('Mechanisms today', '', s.w), ...plain(wrapN(OTHER_STORE, s.w), P.dim)]
418 }
419 return [heading('Mechanisms today', '', s.w), line([seg('reading…', P.dim)])]
420 }
421 const fired = MECHS.filter(m => (t.counts[m.id] ?? 0) > 0).length
422 if (f.chartFolded) return [heading('Mechanisms today', `${String(fired)} fired`, s.w, { folded: true, key: 'head:chart' })]
423 const NAME = 16
424 const CNT = 4
425 const barW = Math.max(4, (s.cellsW ?? s.w) - NAME - CNT)
426 const max = Math.max(1, ...MECHS.map(m => t.counts[m.id] ?? 0))
427 // A file no writer has refreshed in an hour (no session running its memory server): it says how old it is.
428 const old = s.statusAt !== null && s.statusAt !== undefined && s.now - s.statusAt > STATUS_STALE_MS
429 const out: Line[] = [heading('Mechanisms today', old ? agoWords(s.now - (s.statusAt ?? s.now)) : 'times fired', s.w, { key: 'head:chart' })]
430 for (const m of MECHS) {
431 const v = t.counts[m.id]
432 const key = `mech:${m.id}`
433 const picked = s.mech?.id === m.id
434 // Not built yet: not drawn until it is (the fox trial, 2026-10-12).
435 if (m.notBuilt === true) continue
436 if (v === null) {
437 out.push(line([seg(m.short.padEnd(NAME), P.dim), seg(clip('○ not built yet', s.w - NAME), P.dim)], key))
438 continue
439 }
440 const n = v ?? 0
441 const name = seg(clip(m.short, NAME - 1).padEnd(NAME), n === 0 ? P.dim : picked ? P.hi : P.text, { b: picked })
442 const b = n > 0 ? bar(n, max, barW) : ''
443 const cs = String(n)
444 const count = seg(cs, n === 0 ? P.dim : picked ? P.hi : P.mid)
445 if (s.prose === true) {
446 const len = cells(b)
447 out.push(line([{ ...name, t: name.t.trimEnd(), cw: NAME }, { t: '', c: hex(stageOf(m.id).col, BAR_K), fill: len, of: barW }, { t: '', c: P.dim, grow: true as const }, count], key))
448 } else {
449 const pad = Math.max(1, s.w - NAME - cells(b) - cs.length)
450 out.push(line([name, seg(b, hex(stageOf(m.id).col, BAR_K)), seg(' '.repeat(pad), P.dim), count], key))
451 }
452 if (picked) out.push(...mechEvents(s, f))
453 }
454 return out
455}
456
457/** The opened mechanism's recent firings, grouped under what happened and when (`faded at 8:07:`), each title a line. */
458function mechEvents(s: BodyState, f: Fold): Line[] {
459 const m = s.mech
460 if (m === null) return []
461 if (m.status === 'loading') return [line([seg('reading…', P.dim)], `mech:${m.id}`)]
462 if (m.status === 'error') return plain(wrapN('nothing to show yet: no status file', s.w), P.dim, `mech:${m.id}`)
463 if (m.events.length === 0) {
464 // Association's firings (link flushes) count the pairs they linked and name none yet: say what it does instead.
465 const said = m.id === 'association' ? "links memories used together; it doesn't record which yet" : 'nothing lately names a memory'
466 return plain(wrapN(said, s.w), P.dim, `mech:${m.id}`)
467 }
468 const out: Line[] = []
469 let last = ''
470 for (const e of m.events.slice(0, f.events)) {
471 const when = hm(e.at, s.now)
472 const head = `${e.word} ${when.includes(':') ? 'at ' : ''}${when}:`
473 if (head !== last) {
474 out.push(line([seg(clip(head, s.w), P.mid)], `mech:${m.id}`))
475 last = head
476 }
477 const key = `ev:${e.key}`
478 if (s.open?.key === key) {
479 if (e.memoryId === null) {
480 out.push(...plain(wrapN(humanDates(e.title, s.now), s.w, 4), P.hi, key, { b: true }))
481 const rest = e.text.startsWith(e.title) ? e.text.slice(e.title.length).trim() : e.text
482 if (rest !== '') out.push(...textLines(rest, s.w, f.text, P.text, key, null))
483 } else out.push(...opened(s, key, e.title, f))
484 } else {
485 // no dot or bullet between firings: a wrapped line a shade softer says where one ends
486 wrapN(humanDates(e.title, s.now), s.w, ITEM_LINES).forEach((t, i) => out.push(line([seg(t, i === 0 ? P.text : P.mid)], key)))
487 }
488 }
489 return out
490}
491
492function dream(s: BodyState, f: Fold): Line[] {
493 const d = s.dream
494 if (d === null) return []
495 // its journal row's time; failing that its date before today, and nothing for today (no made-up time)
496 const when = d.at !== null ? hm(d.at, s.now) : d.date !== null && d.date !== dateOf(s.now) ? hm(new Date(`${d.date}T12:00:00`).getTime(), s.now) : ''
497 if (f.dreamFolded) return [heading('Last Dream', when, s.w, { folded: true, key: 'head:dream' })]
498 const out: Line[] = [heading('Last Dream', when, s.w, { key: 'dream' })]
499 if (s.open?.key !== 'dream') return [...out, ...plain(wrapN(d.first, s.w, f.dreamLines), P.text, 'dream', { i: true })]
500 // Opened: the dream itself, as far as the room goes (no "what changed" counts: Mike, 2026-10-10).
501 const body = f.excerpt <= 3 || d.rest === '' ? d.first : `${d.first} ${d.rest}`
502 out.push(...plain(wrapN(body, s.w, f.excerpt), P.text, 'dream', { i: true }))
503 return out
504}
505
506const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
507
508/** A `Coming up` item's leading date in words: `Today · …`, `Tomorrow · …`, else `Oct 20 · …`.
509 * Core writes it whole (`2026-10-20`) or, since 2026-10-16, short in the wake's year (`Oct 20`). */
510export function leadDate(text: string, now: number): string {
511 const short = (ymd: string): string => {
512 const [, m, d] = ymd.split('-')
513 const name = MONTHS[Number(m) - 1]
514 return name === undefined ? ymd : `${name} ${String(Number(d))}`
515 }
516 const words = (said: string, day: string | null): string => {
517 if (day === dateOf(now) || said === short(dateOf(now))) return 'Today · '
518 if (day === dateOf(now + 86_400_000) || said === short(dateOf(now + 86_400_000))) return 'Tomorrow · '
519 return `${day === null ? said : short(day)} · `
520 }
521 return text
522 .replace(/^(\d{4}-\d{2}-\d{2}) · /, (_whole, day: string) => words(day, day))
523 .replace(/^([A-Z][a-z]{2} \d{1,2}) · /, (_whole, said: string) => words(said, null))
524}
525
526/** Lines the glance may take. */
527const GLANCE_LINES = 3
528
529/** Before anything happens: where things were left, what's coming up, or yesterday (the wake's own lines). */
530function glance(s: BodyState, f: Fold): Line[] {
531 const g = s.glance
532 const opened = s.open?.key === 'glance'
533 // Opened (a click, as the dream opens), it is the one opened text, and shortens only as an opened text does.
534 if (g === null || g === undefined || (f.glanceOff && !opened)) return []
535 return [heading(g.head, '', s.w, { key: 'glance' }), ...plain(wrapN(humanDates(leadDate(g.text, s.now), s.now), s.w, opened ? f.text : GLANCE_LINES), P.text, 'glance')]
536}
537
538// ── the ladder ───────────────────────────────────────────────────────────────
539
540function sectionsOf(s: BodyState, f: Fold): Line[][] {
541 return [memories(s, f), subconscious(s, f), saved(s, f), chart(s, f), dream(s, f), glance(s, f)].filter(x => x.length > 0)
542}
543
544function total(secs: readonly Line[][], gaps: boolean): number {
545 return secs.reduce((a, r) => a + r.length, 0) + (gaps ? Math.max(0, secs.length - 1) : 0)
546}
547
548/** An item's key: Memories, Subconscious and Saved rows (a mechanism's rows stay together). */
549const ITEM_KEY = /^(mem|sub|saved):/
550
551/** A blank row wherever one item ends and the next begins. */
552function spaced(sec: readonly Line[]): Line[] {
553 const out: Line[] = []
554 sec.forEach((l, i) => {
555 const prev = sec[i - 1]?.key
556 if (prev !== undefined && l.key !== undefined && prev !== l.key && ITEM_KEY.test(prev) && ITEM_KEY.test(l.key)) out.push(BLANK)
557 out.push(l)
558 })
559 return out
560}
561
562function joined(secs: readonly Line[][], gaps: boolean): Line[] {
563 const out: Line[] = []
564 secs.forEach((sec, i) => {
565 if (gaps && i > 0) out.push(BLANK)
566 out.push(...sec)
567 })
568 return out
569}
570
571/** Which ladder: what is open decides what keeps its room. */
572function ladderFor(s: BodyState): readonly Step[] {
573 const l = ladders(s)
574 if (s.mech !== null) return l.mech
575 if (s.open?.key === 'dream') return l.dream
576 if (s.open !== null) return l.open
577 return l.default
578}
579
580/**
581 * The body: the least folding that fits with a blank row between sections;
582 * failing that, without the blank rows; then any fold the last one made
583 * unnecessary is opened again, the most important first. A section the
584 * person opened from its folded heading (`focus`) is never folded to its
585 * heading again (it may still shorten). Past the ladder's end the body is as
586 * it stands and the pane scrolls.
587 */
588export function layoutBody(s: BodyState): { lines: Line[]; folds: string[] } {
589 // The focused section never folds to its heading, and shortens only after every other section has folded.
590 const mine = (st: Step): boolean => st.section === s.focus || (s.focus === 'mind' && st.section === 'sub')
591 const ladder = ladderFor(s).filter(st => !(mine(st) && (st.fold || st.label === 'subconscious 0')))
592 const steps = [...ladder.filter(st => !mine(st)), ...ladder.filter(mine)]
593 const build = (on: ReadonlySet<number>): Line[][] => {
594 const secs = sectionsOf(s, steps.reduce((f, st, i) => (on.has(i) ? st.apply(f) : f), FULL))
595 return s.prose === true ? secs.map(spaced) : secs
596 }
597 const fit = (gaps: boolean): { on: Set<number>; secs: Line[][] } | null => {
598 for (let k = 0; k <= steps.length; k++) {
599 let on = new Set(Array.from({ length: k }, (_, i) => i))
600 let secs = build(on)
601 if (total(secs, gaps) > s.rows) continue
602 for (let i = k - 2; i >= 0; i--) {
603 const less = new Set(on)
604 less.delete(i)
605 const b = build(less)
606 if (total(b, gaps) <= s.rows) {
607 on = less
608 secs = b
609 }
610 }
611 return { on, secs }
612 }
613 return null
614 }
615 for (const gaps of [true, false]) {
616 const got = fit(gaps)
617 if (got !== null) return { lines: joined(got.secs, gaps), folds: [...got.on].sort((a, b) => a - b).map(i => steps[i]?.label ?? '') }
618 }
619 const all = new Set(steps.map((_, i) => i))
620 return { lines: joined(build(all), false), folds: steps.map(st => st.label) }
621}
622
623/** The lines an item's text takes at width `w`. */
624export function openedLines(text: string, w: number): number {
625 return text === '' ? 0 : wrapN(text, w).length
626}
627
628/** For tests: the body's text, a line a string. */
629export function textOf(lines: readonly Line[]): string[] {
630 return lines.map(l => l.segs.map(x => x.t).join(''))
631}
632
633export type { MechId }
634hooks/sidebar/hooks/state.ts 143 lines1/**
2 * The sidebar's own state and timings (shared core, no drawing): the
3 * timings and limits the hooks keep, the first meeting's line and its
4 * once-only mark, the unknown folder, and `run`, what
5 * this module life knows (a reload starts it over; the host keeps `$.state`).
6 *
7 * The `$.state` atoms themselves stay in `register.tsx`: the engine's scan
8 * reads a `read($, x)` source only where `x` is an atom declared in the same
9 * file (NOTES, "The split").
10 */
11
12import type { SidebarScope, SidebarMeet } from '../types'
13import type { Glance } from './feed'
14import type { FullPane } from './pane'
15import type { Status } from './status'
16
17/** How long the line under a clicked item says why the prompt box did not take its command. */
18export const FILL_NOTE_MS = 8000
19
20/**
21 * Body columns the sidebar asks for: 34, which the dock draws 35 wide with its
22 * divider (measured in v0.1: `columns: 44` gave a dock 45 wide), the mockups'
23 * 35. The body is laid out to 32 text columns inside a column of padding each
24 * side.
25 */
26export const OPEN_COLUMNS = 34
27
28/** Rows of pane body from which the header gets a blank row above it (the mockups at 200x60 have one; at 160x48, not). */
29export const ROOMY_ROWS = 44
30
31/** The status file (`status.ts`) is read only while the pane is drawn: this often while things happen… */
32export const POLL_MS = 15000
33
34/** …and this often after four quiet reads in a row. */
35export const POLL_IDLE_MS = 30000
36
37/** How often the folder's registry is read again while no status poll reads it (the pane closed or not shown). */
38export const SCOPE_RECHECK_MS = 60000
39
40/** How long the registry's path, found from the settings, is trusted before it is looked up again. */
41export const SCOPES_FILE_TTL_MS = 5 * 60000
42
43export const FIRING_MS = 2600
44
45
46/**
47 * The speak-first's line (`speak-first.tsx`, a hooks module of its own): what it
48 * submits, once per install at the first idle start while core says
49 * `not_started`. Framed as the plugin's (not `asUser`): the model reads "The
50 * counterparts plugin sent a message: …", and core's wake carries the meeting's
51 * instructions. Claude Code shows this line to the person ("Prompt from the
52 * counterparts plugin"), so it reads as a sentence to them, and still tells the
53 * model to introduce itself (2026-10-12, owner's onboarding trial). Since the fox
54 * trial it is "Meet your new counterpart." (the owner: Claude already has a
55 * memory of its own), which core's wake names as this meeting. In any later
56 * session the person types `/counterparts:meet` (the sidebar's footer says so).
57 */
58export const MEET_PROMPT = 'Meet your new counterpart.'
59
60/**
61 * `$.store`: the speak-first went out (`{ session, at }`), never again while it is there; or
62 * `{ settled }` once core moved past not_started. Written and read by `speak-first.tsx`.
63 */
64export const MEET_FLAG = 'meetTriggered'
65
66// ── the unknown folder, and what this module life knows ──
67
68export const UNKNOWN_SCOPE: SidebarScope = { mode: 'unknown', own: false, setBy: null, dir: null, error: null, busy: false, unread: null }
69
70export const run = {
71 session: '',
72 /** Where the first meeting stands, from the wake's onboarding marker: the footer drops its intro line once done or skipped. */
73 meet: 'unknown' as SidebarMeet | 'unknown',
74 /** The wake's first glance line (Last here, Coming up, Yesterday): shown until the session has something of its own. */
75 glance: null as Glance | null,
76 interactive: false,
77 /** The first drawing's one-time work (a quiet scope read, if the start's found none) is done. */
78 woke: false,
79 /** A read of this folder's registry is on its way. */
80 scopeReading: false,
81 /** The folder this session started in (`session.start`'s `cwd`). */
82 cwd: '',
83 /** The registry the hooks read, and when (`$.clock`) that was found. */
84 scopesFile: null as string | null,
85 scopesFileAt: 0,
86 scopeTimer: null as { cancel: () => void } | null,
87 /** Canonical forms of paths that resolved whole (a folder's realpath rarely moves). */
88 canon: new Map<string, string>(),
89 /** Whether to open the pane unasked has been decided (from the first band drawing). */
90 placementDecided: false,
91 /** Whether this surface docks a pane (the fullscreen renderer), once the band or the hint has said. */
92 docks: undefined as boolean | undefined,
93 /** The surface the band above the prompt last drew on (the pane opens narrower on the desktop). */
94 surface: null as string | null,
95 polling: false,
96 /** A status read is scheduled or running. */
97 pollArmed: false,
98 quietPolls: 0,
99 /** The newest seq of the file last read (-1: none read yet): rows after it are new. */
100 lastSeq: -1,
101 /** The status file's path, its stamp when last read, and what it said (`status.ts`). */
102 statusFile: null as string | null,
103 statusStamp: '',
104 status: null as Status | null,
105 liveSeq: 0,
106 /** Memory tool calls (`savesMemory`) running now: the poll writes no notepad for their rows; the call's own return does. */
107 saving: 0,
108 /** An unasked pane this surface could not place yet: the tail says `/counterparts opens the sidebar` until it draws. */
109 hint: false,
110 /** When this session began: an event naming no session, from after it, is taken as this session's. */
111 startedAt: 0,
112 /** Fresh drawings asked for after refused blits since the last blit that was taken. */
113 redraws: 0,
114 /** The body's text width at the last drawing: what the expand threshold is measured at. */
115 bodyW: 32,
116 /** This session's rows were looked for in the status file (`seedSession`), once a module life. */
117 seeded: false,
118 /** The store this session's hooks opened, from the wake's `counterparts:store` marker; null until it says. */
119 wakeStore: null as string | null,
120 /** The status file is another store's: nothing of it is shown until it matches again. */
121 foreign: false,
122 /**
123 * THE FULL PLUGIN'S PIECES (2026-10-16): the Meet row, the title's link to the dashboard, the footer's
124 * clickable lines and switches. Set by `actions.tsx` when `full.tsx` registers it, the one place the full
125 * build turns them on; null in the plugin directory's build, which never loads that file and draws none.
126 */
127 full: null as FullPane | null,
128 /** Why the prompt box did not take a clicked item's command (`actions.tsx`): drawn under that item for FILL_NOTE_MS. */
129 fillNote: null as { key: string; text: string; at: number } | null,
130 /** The session in which a click on the Meet row put `/counterparts:meet` in the box: the meeting has begun there. */
131 meetFilledIn: null as string | null,
132}
133
134// ── small helpers ───────────────────────────────────────────────────────────
135
136/** Work left running on its own: a reload or the session's end may cut it off, and that is fine. */
137export function quiet(p: Promise<unknown>): void {
138 p.catch(() => undefined)
139}
140
141/** Event names whose rows name nothing (`feed.ts#mechFirings`) or need a dream read: not worth reading deeper. */
142export const NAMES_NOTHING = new Set(['mcp.recall', 'associate.flush', 'contradiction.flagged', 'sleep.cycle', 'dream.journaled', 'dream.changed'])
143hooks/sidebar/hooks/theme.ts 118 lines1/**
2 * Every colour the pane draws with, by theme (shared core, no drawing).
3 * `tron` is the round-3 mockups' palette, the sidebar's look since v0.2;
4 * `cozy` is the warm one proposed for the stage on 2026-10-12
5 * (`~/counterparts-notes/mockups/2026-10-12-stage/cozy-theme.md`): dark
6 * walnut, parchment text, leaf green and pumpkin. Neutral text everywhere;
7 * `accent` (tron's cyan) for what can be pressed or is lit, `accent2` (tron's
8 * amber) for a warning.
9 *
10 * Not here: the mechanisms' stage colours (`mechanisms.ts`, the site's own,
11 * on dots and bars) and the fox's own colours (`fox.ts`). A theme sets the
12 * panel and the text around them; they stay.
13 *
14 * `P` is the palette in use, the one every drawing reads: `applyTheme` copies
15 * a theme into it. The Pane hook applies the session's theme before each
16 * drawing, so a reload (which starts this module over, at tron) draws right.
17 */
18
19import type { SidebarTheme } from '../types'
20
21export type Palette = {
22 /**
23 * The pane's background. Measured: the engine draws a Raster's colours at
24 * 4 bits a channel, so a panel colour given to a Raster's cells comes out a
25 * shade off it (`fox.ts` gives its cells the terminal's default instead).
26 */
27 panel: string
28 /** The brightest text: an opened item's title, a switch that is on. */
29 hi: string
30 text: string
31 mid: string
32 /** Quiet text: times, counts, what is off. */
33 dim: string
34 /** Rules and empty bars. */
35 faint: string
36 /** Section headings. */
37 head: string
38 /** What can be pressed, or is lit (tron's cyan). */
39 accent: string
40 /** A warning: paused, off (tron's amber). */
41 accent2: string
42 /** The header's dot at rest and its `↗`. */
43 accentDim: string
44}
45
46/** The mockups' palette: neutral text, stage colours only on dots and bars. */
47export const tron: Palette = {
48 panel: '#05080c',
49 hi: '#dde3e9',
50 text: '#b3bcc5',
51 mid: '#8e98a2',
52 dim: '#66717c',
53 faint: '#1d262e',
54 head: '#c9d1d8',
55 accent: '#00e5ff',
56 accent2: '#ffb347',
57 accentDim: '#0b6f7c',
58}
59
60/** Warm wood and lamplight: dark walnut, parchment text, leaf green and pumpkin. */
61export const cozy: Palette = {
62 panel: '#1a120d',
63 hi: '#f7ead2',
64 text: '#dccab0',
65 mid: '#b49c80',
66 dim: '#8a7560',
67 faint: '#34261c',
68 head: '#efd9b6',
69 accent: '#9cc65f',
70 accent2: '#f0a04b',
71 accentDim: '#56713a',
72}
73
74export const THEMES: Readonly<Record<SidebarTheme, Palette>> = { tron, cozy }
75
76/**
77 * A surface that draws its own page (the desktop app, VS Code): Claude Code's
78 * theme keys, which follow the app's light or dark mode, and no panel of our
79 * own. Measured 2026-10-13 in the Desktop app's Code tab: on tron's black
80 * panel the app's native buttons (the title, the footer's switches) drew dark
81 * on dark, and the `─` rules, set in the app's proportional font, ran wider
82 * than the cells they were measured in and wrapped every heading.
83 */
84export const desk: Palette = {
85 panel: '',
86 hi: 'text',
87 text: 'text',
88 mid: 'inactive',
89 dim: 'inactive',
90 faint: 'subtle',
91 head: 'text',
92 accent: 'suggestion',
93 accent2: 'warning',
94 accentDim: 'inactive',
95}
96
97/** Whether the surface in use draws text in its own (proportional) font: no rules of `─`, no panel. */
98export const SURFACE = { prose: false }
99
100/** A stored theme: a name this version knows, else tron. */
101export function normTheme(v: unknown): SidebarTheme {
102 return v === 'cozy' ? 'cozy' : 'tron'
103}
104
105/** The palette in use (tron until a theme is applied). */
106export const P: Palette = { ...tron }
107
108/** Makes `name` the palette in use. */
109export function applyTheme(name: SidebarTheme, surface: string = 'terminal'): void {
110 SURFACE.prose = surface === 'desktop' || surface === 'vscode'
111 Object.assign(P, SURFACE.prose ? desk : THEMES[name])
112}
113
114/** A Box's background, only when the palette has one (a prose surface keeps the app's). */
115export function bg(c: string): { backgroundColor?: string } {
116 return c === '' ? {} : { backgroundColor: c }
117}
118hooks/sidebar/hooks/width.ts 70 lines1/**
2 * Terminal cells, not string length: a CJK character or an emoji takes two
3 * cells, a combining mark or a zero-width joiner none. The lists lay out rows
4 * by line, so a title that took more cells than counted would wrap on screen
5 * and shift every click row under it. Pure; shared by the hooks module's
6 * wrapping and the list surface module.
7 */
8
9/** The cells one code point takes. */
10export function charCells(cp: number): number {
11 if (cp < 0x20 || (cp >= 0x7f && cp < 0xa0)) return 0
12 if (
13 (cp >= 0x0300 && cp <= 0x036f) || // combining marks
14 (cp >= 0x200b && cp <= 0x200f) || // zero-width spaces and marks
15 cp === 0x2060 ||
16 (cp >= 0xfe00 && cp <= 0xfe0f) || // variation selectors
17 (cp >= 0x1f3fb && cp <= 0x1f3ff) // skin-tone modifiers
18 ) {
19 return 0
20 }
21 if (
22 (cp >= 0x1100 && cp <= 0x115f) || // Hangul Jamo
23 (cp >= 0x2e80 && cp <= 0x303e) || // CJK radicals, punctuation
24 (cp >= 0x3041 && cp <= 0x33ff) || // kana, CJK symbols
25 (cp >= 0x3400 && cp <= 0x4dbf) ||
26 (cp >= 0x4e00 && cp <= 0x9fff) ||
27 (cp >= 0xa000 && cp <= 0xa4cf) || // Yi
28 (cp >= 0xac00 && cp <= 0xd7a3) || // Hangul syllables
29 (cp >= 0xf900 && cp <= 0xfaff) ||
30 (cp >= 0xfe30 && cp <= 0xfe4f) ||
31 (cp >= 0xff00 && cp <= 0xff60) || // fullwidth forms
32 (cp >= 0xffe0 && cp <= 0xffe6) ||
33 (cp >= 0x1f000 && cp <= 0x1faff) || // emoji and pictographs
34 (cp >= 0x20000 && cp <= 0x3fffd)
35 ) {
36 return 2
37 }
38 return 1
39}
40
41/** The cells a string takes. */
42export function cells(s: string): number {
43 let n = 0
44 for (const ch of s) n += charCells(ch.codePointAt(0) ?? 0)
45 return n
46}
47
48/** The longest head of `s` that fits `w` cells. */
49export function headCells(s: string, w: number): string {
50 let n = 0
51 let out = ''
52 for (const ch of s) {
53 const c = charCells(ch.codePointAt(0) ?? 0)
54 if (n + c > w) break
55 n += c
56 out += ch
57 }
58 return out
59}
60
61/** `s` cut to `w` cells, an ellipsis standing for what was cut. */
62export function ellipsizeCells(s: string, w: number): string {
63 return cells(s) <= w ? s : `${headCells(s, Math.max(0, w - 1))}…`
64}
65
66/** `s` padded with spaces to `w` cells. */
67export function padCells(s: string, w: number): string {
68 return s + ' '.repeat(Math.max(0, w - cells(s)))
69}
70hooks/sidebar/hooks/words.ts 180 lines1/**
2 * What the sidebar says, worked out with no `$` (shared core, no drawing):
3 * the stored view and avatar read from any version, the status line, what
4 * `/counterparts resume` says, the footer's instructions, the tail's words
5 * for what happened, an opened memory's meta line, and the first meeting's
6 * once-only mark.
7 */
8
9import type { SidebarAvatar, SidebarSaved, SidebarScope, SidebarView } from '../types'
10import { shortDay, shortDir } from './feed'
11
12/** Nothing is remembered and nothing comes to mind: paused for now, or set off. */
13export function isPaused(mode: string): boolean {
14 return mode === 'paused' || mode === 'off'
15}
16
17/**
18 * A stored view, from any version: v0.1's `full` is the sidebar; its `quiet`
19 * (a narrow pane), `rail` and `hidden`, and v0.2's first `strip` (one line
20 * above the prompt, dropped 2026-10-10), are quiet (no pane, the tail). Read
21 * so, never written back: a v0.1 copy reading the same store keeps its word.
22 */
23export function normView(v: unknown): SidebarView {
24 return v === 'quiet' || v === 'rail' || v === 'hidden' || v === 'strip' ? 'quiet' : 'sidebar'
25}
26
27/**
28 * The avatar as stored: `off` stays; anything else is the fox, including the
29 * brain (`turning`, `still`) an older version stored, which v1 no longer draws.
30 */
31export function normAvatar(v: unknown): SidebarAvatar {
32 return v === 'off' ? 'off' : 'fox'
33}
34
35/**
36 * The status line: only a warning. A folder paused or off says so in every
37 * session there, whatever the view (`⚠ counterparts:` and amber are the
38 * engine's); the normal case has no status line at all (v0.2).
39 */
40export function statusFor(scope: SidebarScope): string | undefined {
41 if (!isPaused(scope.mode)) return undefined
42 const parts =
43 scope.mode === 'paused'
44 ? ['⏸ Counterparts memory paused in this folder', scope.own ? RESUME_SAY : `resume it in ${shortDir(scope.setBy)}`]
45 : ['◌ Counterparts memory off in this folder']
46 return parts.join(' · ')
47}
48
49/** An opt-in written in the environment: `1`, `true`, `yes` or `on`. */
50export function truthy(v: string | undefined): boolean {
51 return v !== undefined && /^(1|true|yes|on)$/i.test(v.trim())
52}
53
54/**
55 * The header's count, whole: `1000 memories` (13 cells, the header's text
56 * column widened by one for it). From 10,000, `10k+ memories`, still 13: the
57 * exact number is on the dashboard.
58 */
59export function memoriesCount(n: number): string {
60 return n >= 10000 ? `${String(Math.floor(n / 1000))}k+ memories` : `${String(n)} memories`
61}
62
63/** The newest thing in plain words, for the tail. */
64export function words(kind: 'remembered' | 'subconscious' | 'stored' | 'opened' | 'dreamed', what: string): string {
65 return `${kind}: ${what}`
66}
67
68/** What the tail says of a save: `Stored “title”` (the quotes keep a title's own `Answered:` from doubling the lead), or `Stored 2 memories, the first “title”`. */
69export function storedWords(title: string, count = 1): string {
70 return count > 1 ? `Stored ${String(count)} memories, the first “${title}”` : `Stored “${title}”`
71}
72
73/** What a save wrote beyond its title, for the tail; none when the title was cut from the text itself. */
74export function bodyOf(s: SidebarSaved): string | undefined {
75 return s.text === undefined || s.text.startsWith(s.title) ? undefined : s.text
76}
77
78/** The memory text an opened item shows, and the line saying what it is. */
79export function memoryMeta(d: { kind?: unknown; learnedOn?: unknown; journal?: unknown }): string | null {
80 const kind = d.journal === true ? 'journal' : typeof d.kind === 'string' ? d.kind : null
81 // `Oct 9`, with the year only when it is not this one.
82 const thisYear = String(new Date().getFullYear())
83 const learned = typeof d.learnedOn === 'string' ? shortDay(d.learnedOn.startsWith(`${thisYear}-`) ? d.learnedOn.slice(5) : d.learnedOn) : ''
84 if (kind === null) return null
85 return learned === '' ? kind : `${kind} · learned ${learned}`
86}
87
88/** The session a still-binding speak-first went out in, or null (none, or settled since: core moved past not_started). */
89export function firedIn(stored: unknown): string | null {
90 const session = (stored as { session?: unknown } | null | undefined)?.session
91 return typeof session === 'string' ? session : null
92}
93
94export function isAbsolutePath(path: string): boolean {
95 return path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path)
96}
97
98// ── pausing: said, not done (v1 trim, 2026-10-14) ───────────────────────────
99
100/** What to say to Claude to pause or resume memory in this folder: Claude calls Counterparts' `scope` tool. */
101export const PAUSE_SAY = 'say “pause memory here”'
102export const RESUME_SAY = 'say “resume memory here”'
103
104/**
105 * What `/counterparts resume` answers: the sidebar changes no setting, so it
106 * says where the folder stands and how to resume it.
107 */
108export function resumeWords(scope: SidebarScope): string {
109 if (scope.mode === 'unknown') return `Couldn't read this folder's setting. To resume memory here, ${RESUME_SAY} to Claude.`
110 const here = shortDir(scope.dir)
111 if (scope.mode === 'paused' && scope.own) return `Counterparts memory is paused in ${here}. To resume it, ${RESUME_SAY} to Claude.`
112 // Set by a folder above: resumed there (a session in that folder, or the npm install's console).
113 if (scope.mode === 'paused') {
114 const there = scope.setBy ?? '<that folder>'
115 return `Counterparts memory is paused here because ${shortDir(scope.setBy)} is paused. To resume, ${RESUME_SAY} to Claude in a session there, or, with the npm install, run \`counterparts scope ${shellQuote(there)} --resume\`.`
116 }
117 if (scope.mode === 'off') {
118 const where = scope.setBy ?? scope.dir ?? '<this folder>'
119 return `Counterparts memory is off in ${here}. To turn it back on, ask Claude in a session in ${shortDir(where)}, or, with the npm install, run \`counterparts scope ${shellQuote(where)} --on\`.`
120 }
121 return `Counterparts memory isn't paused in ${here}.`
122}
123
124/** A path as one shell word, as core's `scopes.ts#shellWord` writes it: plain, or in single quotes. */
125export function shellQuote(path: string): string {
126 return /^[A-Za-z0-9_./@%+=:,-]+$/.test(path) ? path : `'${path.replace(/'/g, "'\\''")}'`
127}
128
129/**
130 * The footer (v1 trim, 2026-10-14): how to do what the sidebar no longer does
131 * itself, a few words and a command each. One line, `label · command`, the
132 * labels shortened where a whole line won't fit in `w` cells (all four short
133 * ones fit the docked pane's 32); narrower still, the short label, then the
134 * command under it, indented.
135 */
136export const FOOTER_ITEMS: readonly { label: string; short: string; how: string }[] = [
137 { label: '5-minute intro', short: 'Intro', how: '/counterparts:meet' },
138 { label: 'Dashboard', short: 'Dash', how: '/counterparts:dashboard' },
139 { label: 'Pause here', short: 'Pause', how: PAUSE_SAY },
140 { label: 'Hide this', short: 'Hide', how: '/counterparts quiet' },
141]
142
143/** One footer line: its label part (dim) and its command part (bright); either may be empty. `of`: the item's command, on each of its lines. */
144export type FooterLine = { label: string; how: string; of: string }
145
146/** Where memory is paused or off, the pause line says how to resume instead. */
147const RESUME_ITEM = { label: 'Resume here', short: 'Resume', how: RESUME_SAY }
148
149/** For someone who'd rather not have the fox: shown while it is the avatar (Mike, 2026-10-15). */
150const NO_FOX_ITEM = { label: 'Hide the fox', short: 'Fox', how: '/counterparts avatar off' }
151
152/**
153 * Which optional lines the footer carries: the intro until the first meeting is done or skipped; the fox's line while it shows;
154 * the hide line unless `hide` is false (the full build's view switch does it, 2026-10-16).
155 */
156export type FooterShow = { intro: boolean; fox: boolean; hide?: boolean }
157
158/** The footer's lines at `w` cells; `paused`: this folder is paused or off. */
159export function footerLines(w: number, paused = false, show: FooterShow = { intro: true, fox: false }): FooterLine[] {
160 const base = paused ? FOOTER_ITEMS.map(it => (it.how === PAUSE_SAY ? RESUME_ITEM : it)) : FOOTER_ITEMS
161 const items = [
162 ...base.filter(it => (show.intro || it.how !== '/counterparts:meet') && (show.hide !== false || it.how !== '/counterparts quiet')),
163 ...(show.fox ? [NO_FOX_ITEM] : []),
164 ]
165 const fits = (label: string, how: string): boolean => [...`${label} · ${how}`].length <= w
166 // One set of labels for every line, so they read alike: the long ones only where all of them fit.
167 const long = items.every(it => fits(it.label, it.how))
168 const out: FooterLine[] = []
169 for (const it of items) {
170 const label = long ? it.label : it.short
171 if (fits(label, it.how)) out.push({ label: `${label} · `, how: it.how, of: it.how })
172 else {
173 // A command is never cut: indented where that fits, else at the margin (under 25 cells the longest wraps).
174 out.push({ label: it.short, how: '', of: it.how })
175 out.push({ label: [...it.how].length + 2 <= w ? ' ' : '', how: it.how, of: it.how })
176 }
177 }
178 return out
179}
180hooks/sidebar/hooks/body.tsx 74 lines1/**
2 * The pane's body as a `Client` surface module: the lines `./sections.ts`
3 * laid out, drawn as they are, and a click on one posted back to the hooks
4 * module by the key it carries (`{ click: 'mem:0' }`). Nothing here is a
5 * link (2026-10-14): the hooks module hands every row over with none, so the
6 * `more` that ends a cut text is plain words and a click on it is the row's.
7 *
8 * Why not Buttons: the engine inverts a Button under the pointer and the
9 * focus, so moving the mouse over a list lit row after row (v0.1, NOTES).
10 * Here nothing changes under a passing pointer; a click on any row of an item
11 * is a click on the item. No `$` here, and no state: what is open lives in
12 * the hooks module's `$.state`, which draws this again.
13 */
14import type { ClientModule, ClientSurface } from 'claude-code'
15
16import type { Line } from './sections'
17
18/** `prose`: the surface sets text in its own font (desktop): a heading's `─` rule becomes space that pushes the right part to the edge. */
19export type BodyProps = { lines: Line[]; prose?: boolean }
20
21const RULE = /^ ?─+$/
22
23const Body: ClientModule<BodyProps, never> = (props, surface: ClientSurface<never>) => {
24 const { Box, Text } = surface.elements
25 surface.onPointer(ev => {
26 if (ev.type !== 'down' || (ev.button !== undefined && ev.button !== 'left')) return
27 const l = props.lines[ev.y]
28 // a row's link (none is drawn now) would take the click from its column on
29 if (l?.link !== undefined && ev.x >= l.link.from) {
30 surface.post({ click: l.link.key })
31 return
32 }
33 if (l?.key !== undefined) surface.post({ click: l.key })
34 })
35 return (
36 <Box flexDirection="column">
37 {props.lines.map((l, y) =>
38 l.segs.length === 0 ? (
39 <Text key={`l${String(y)}`}> </Text>
40 ) : (
41 <Box key={`l${String(y)}`} flexDirection="row">
42 {l.segs.map((s, i) =>
43 props.prose === true && (s.grow === true || RULE.test(s.t)) ? (
44 <Box key={String(i)} flexGrow={1} />
45 ) : props.prose === true && s.fill !== undefined ? (
46 // a share of its column, drawn in half blocks clipped to that share: whatever width the app's
47 // font gives `▄`, the bar is the right length, half a row tall like the terminal's
48 <Box key={String(i)} width={s.of ?? s.fill} overflow="hidden">
49 {/* one row tall and clipped, no `wrap`: a truncating Text drew `…` at the bar's end */}
50 {s.fill > 0 ? (
51 <Box width={`${String(Math.round((100 * s.fill) / Math.max(1, s.of ?? s.fill)))}%`} height={1} overflow="hidden">
52 <Text color={s.c}>{'▄'.repeat(2 * (s.of ?? s.fill))}</Text>
53 </Box>
54 ) : null}
55 </Box>
56 ) : props.prose === true && s.cw !== undefined ? (
57 <Box key={String(i)} width={s.cw}>
58 <Text color={s.c} {...(s.b === true ? { bold: true } : {})}>{s.t}</Text>
59 </Box>
60 ) : (
61 <Text key={String(i)} color={s.c} {...(s.b === true ? { bold: true } : {})} {...(s.i === true ? { italic: true } : {})}>
62 {props.prose === true && i > 0 && RULE.test(l.segs[i - 1]?.t ?? '') ? s.t.replace(/^ /, '') : s.t}
63 </Text>
64 ),
65 )}
66 </Box>
67 ),
68 )}
69 </Box>
70 )
71}
72
73export default Body
74