The memory pane: a side pane over a memory-kit home's memory, one tab per tier (obligations, scratchpad, commitments, rules, lessons, facts, keys, secrets)…

A Claude Code side pane (a function-hooks mod) over a memory-kit home's memory, one tab per tier (since 0.7.0, kit #43; it showed the obligations tier alone before). The Obligations tab is the pane as it was: memory/obligations.yaml, soonest expiry first. Built against Claude Code 2.1.296's plugin API (early access; the API moves between releases). The plugin keeps its id, obligations-pane@memory-kit, so a home updates it as before; the pane's title is "Memory".
[Obligations][N][C][R][L][F][K][S]
A tab row sits above the header. The open tab shows its full name, the others one letter, so the row fits a narrow pane; it wraps onto a second line when even that does not fit. Click a tab, or press its digit (1-8) while the pane has the keyboard. Obligations is the default.
| Tab | Source (in the memory directory) | Shows | Header count |
|---|---|---|---|
| O Obligations | obligations.yaml | as below ("What it shows") | N expired · M due ≤7d |
| N Next | the scratchpad tier, found as the lint finds it: see "The Next tab" below (kit #53) | the file's name, then current and staging, each under its heading; a row is its label, record, then ref (dim). Several files: each under its own name | 13/15 current · 4 staging, or 2 scratchpads · 9 current · 4 staging |
| C Commitments | commitments.yaml | trigger -> obligation, then actor -> owed_to, within … (dim). No file: "commitments tier not in use here". A commitments.yaml that holds a scratchpad (kit #30) says so and shows under Next | N commitments |
| R Rules | rules.yaml | numbered | 18/20 |
| L Lessons | lessons/index.yaml | the summary, newest learned first, its enforcement before it and the date after; the line links to lessons/<slug>.md (a file:// URL; where the terminal opens none, plain text). A chip row under the header filters: [all][hooked][linted][recognition] | N lessons, or 3/12 linted |
| F Facts | facts/*.yaml | grouped by subject (the file's name), each fact after its verified date; a fact not verified in 91 days (a quarter), or never, is dim | N facts · M subjects · K not verified in 91 days |
| K Keys | keys.yaml | per grant: subject, holder · scope, then the revoke step. A blank revoke is flagged "no revoke step (a finding)"; one containing [?] "revoke step unconfirmed" | N grants · F findings |
| S Secrets | secrets/README.md and the secrets/ listing | the README's three labelled lines (public key, master key location, spare deposited / where / verified), then the encrypted files by name and date. A spare NOT YET deposited or verified is flagged | N encrypted files |
$.store (keyed by the resolved home path), so a reload or a restart opens where the person left it.<file> unreadable: line N: <why> in its tab; a broken facts file is flagged under its subject while the other subjects show. Every tier goes through the obligations parser's own strict reader (parseMapLists in hooks/obligations.ts): the kit's one shape, a top-level key holding a list of flat maps (memory-kit/types/memory-*.ts). A missing file says no <file> here (<path>); Next, which has no fixed file, says no scratchpad tier in this home (<memory dir>)._fill in_), or no encrypted file beside the README turns the top of the tab into a red banner naming what is off. A home that keeps its secrets elsewhere (an OS key store) shows the banner: that is the home's debt, not the pane's to hide.urls/<name> is a link in every tab, by the same rule as obligations: struck through and grey when the file is missing or unusable.k / j) steps through the open tab's lines; a new tab starts at the top./obligations opens the pane on the Obligations tab; /memory-pane opens it on the open tab (not /memory: that is Claude Code's built-in memory command, and the harness refuses it).dormant/ (parked facts) and urls/ (they are links everywhere).The kit names no scratchpad file: the tier is memory/<name>.yaml (types/memory-scratchpad.ts), and semafor keeps its own at memory/vitruvius.yaml. The tab used to read scratchpad.yaml alone, so it said no scratchpad.yaml here where the lint read eight rows. It now finds the tier by the lint's own rule:
*.yaml at the top of the memory directory is a scratchpad, except rules.yaml, obligations.yaml and keys.yaml. commitments.yaml is one only when it holds current or staging and no commitments key (kit #30); the Commitments tab then says it is not in use. A link to a file counts, as the lint follows it.13/15 current · 4 staging); several add up (2 scratchpads · 9 current · 4 staging), since the cap is per file. A broken file among several is flagged under its name; the others show.lint_tree in lint/memory_lint.py; the pane's copy is scratchpadCandidates and scratchpadShaped in hooks/tiers.ts. The two cannot share code, so a change to one is a change to both. One difference: the lint asks PyYAML whether commitments.yaml holds a scratchpad, and the pane, which has no YAML library, reads its keys at column 0. A commitments.yaml that PyYAML cannot parse but that has current: at column 0 is therefore the lint's commitments error and the pane's scratchpad error, under Next.N expired · M due ≤7d, then the scroll position i/n. For example memory-kit 0.1.0-alpha.5 0 expired · 1 due ≤7d 1/6 (since 0.3.0, kit #4; it showed the date and time before).<home>/memory-kit/VERSION, the home's pinned kit, not the pane's own version. The home is the folder that holds the memory directory (for a memoryDir session that runs outside it), else <cwd>: the first of the two with a VERSION. Without one the slot is empty: never a guess.memory-kit 0.1.0-alpha.5 · alpha.6 out. A newer pre-release of the same version shows its pre-release part alone; a different major, minor or patch shows the whole version, as · 0.2.0 out (kit #7, see Release check).expires is before today.expires falls between today and today + 7 days, both ends included. Today is the local date, which the header no longer shows.expires (expired first), ties by since, then file order.…), so the task text starts on the first line.urls/<name> in the text becomes a dark-blue underlined link (OSC 8 in the terminal; Ghostty clicks it). Links cited only in check or ref trail the text.urls/<name> with no file, or with an unusable one, is drawn struck through and grey.memory/urls/veo-214, and cite urls/veo-214. The pane recognises no ticket patterns on purpose; see the kit lesson link-a-ticket-with-a-url-file (#6).owed_to (kit #29) reads actor -> owed_to: text, as tools/obligations-due.py prints it; the party owed is drawn as an actor is (bold, its own colour, 20 columns). A row without one reads actor text, as before.check and since are not shown, to keep rows light.─ rule across the pane, no frame): one line for the session's main agent: the name in 10 columns (longer names get 9 chars + …), a colour-coded model letter, and the context weight such as 127k/1M. The letters are F = Fable, O = Opus, S = Sonnet, H = Haiku, and a dim · when the model is unknown. One more line per live subagent or teammate follows, in the same name and model columns, then its context load (dimmed unless running). The load is the latest model step's input side: input, cache read and cache write tokens added together, output left out, as Claude Code computes the status line's used_percentage (since 0.6.0; output was added before). It reads 84k/1M when the agent runs on the main loop's model, whose window the session reports, and 84k alone otherwise: windows are never guessed. An agent with no step seen yet shows a dim · and no load. One more line per running workflow follows (since 0.6.0): its name in the name column, a ≡ where the model letter stands, the current phase, and agents done/started, for example pane-live… ≡ Finish 2/3. The line shows while one of the run's agents works and goes when the last finishes. $.agent.list() leaves a workflow's agents out, so the pane counts them itself: agent.spawn tags each with its run id (e.workflow.runId) and turn.complete names the one that finished. "Started" counts the agents started so far: a run announces no total.<config>/projects/<cwd slug>/<session id>/subagents/workflows/<run id>/journal.jsonl (the phase of its last started entry). That file is Claude Code's own and undocumented: when it cannot be read, the label of the latest started agent gives the phase by convention, the part before its first colon (Review:bugs -> Review); a label without a colon gives none.<session dir>/workflows/scripts/<name>-<run id>.js. A run started again from a saved script keeps the first run's file name, so it shows its run id.e.props.bodyColumns). The footer subtracts its padding (one column each side) and shows used/window only when the whole line fits, otherwise used alone. Its lines wrap rather than truncate, so at extreme widths a figure moves to the next row instead of getting an ellipsis.k and j hotkeys step one while the pane has the keyboard. They live on two Buttons inside a Box that is not displayed.no obligations file here (<path>). An empty list says no obligations. A file the parser rejects says obligations.yaml unreadable: line N: <why>.Width: the harness decides. Unasked, the pane opens docked only on a wide terminal (144 columns, 110 once asked), otherwise it waits. /obligations opens it at any width.
<memory dir>/obligations.yaml. The memory directory is, in order:kit_home pointer in <cwd>/memory-kit.conf: <home>/<memory_dir> of the home it names (since kit #18; see "A session outside its home"). It wins over the option.memoryDir option, when set. A relative path resolves against <cwd>. Absolute is POSIX (/...), a drive letter (C:\... or C:/...) or UNC (\\server\share), since 0.3.0 (kit #8); the same holds for memory_dir. For a lead session that runs outside its home (a team folder, a sibling repo).<cwd>/<memory_dir>, with memory_dir read from <cwd>/memory-kit.conf.<cwd>/memory.<cwd> is the directory the session started in, not where it is now (since 0.2.1, kit issue #3). A shell cd into another repo mid-session does not switch the ledger. The start directory is the session's root ($.session.root(), which a shell cd does not move) at the first session.start, kept in $.state, so a mod reload (which fires session.start again, with the directory the session is in by then) keeps it too; so does an install mid-session (kit #45). Only when no start was seen does the pane fall back to $.session.root(). A start folder without a memory-kit.conf takes the nearest one above it (kit #42, below).
Left empty, one install therefore serves every kit home. The value is stored in settings under pluginConfigs; set in the user's settings, it points every session on the machine at that one home. For a session that starts outside its home, use a kit_home pointer conf in its start folder instead (kit #18): the lint and the tools follow it too, so it no longer makes that folder look like a home.
memory-kit/types/memory-obligations.ts, a list of {obligation, actor, since, check, expires, ref}.memory/urls/<name> holds one URL on line 1 (memory-kit/types/memory-urls.ts). The pane reads these files and never writes them.hooks/obligations.ts. The mod environment has no bundler and no node_modules, so a YAML library is not an option.obligations: or obligations: [], and list items of flat key: value maps with double-quoted, single-quoted or plain scalars.obligations:, as yaml.safe_dump writes them, or be indented (since 0.3.0, kit #5). One file uses one indent throughout.''). Double quotes take YAML's escapes, \x, \u, \U and an escaped line end included. A plain null or ~ is empty.yaml.safe_dump(data, sort_keys=False) writes, with or without allow_unicode, parses to what PyYAML reads back. The test fixture is that real output (tests/fixtures/make-safe-dump.py).since or expires, or a missing obligation, actor or expires.types/memory-obligations.ts is in PROPOSED-types-doc.md, for upstream to apply.Since 0.3.0 (kit #7), the pane notices a newer kit release by itself.
$.http.fetch: https://codeberg.org/api/v1/repos/<owner>/<repo>/tags?limit=50. That is the newest 50 tags, newest first.mitselek/memory-kit unless the home's memory-kit.conf (the home whose VERSION the header shows) has an upstream: key. Its value is owner/repo on Codeberg, e.g. upstream: someone/memory-kit. Any other value, a full URL included, makes no request and writes one debug line.v<major>.<minor>.<patch> with an optional -alpha.N, -beta.N or -rc.N. They compare by semver precedence (alpha.10 > alpha.9, alpha < beta < rc < the release). Other tags are ignored.$.store under upstream (url -> { checkedAt, latest }). The store is the plugin's own and shared by every session, so ten open sessions make one request.$.http.fetch has no timeout of its own, so a request not answered in 10 s (on $.clock.after) is a failed check.debug log line and never draws an error. A failure counts as a check, so the next try comes 6 h later.checkUpdates: false makes no request at all and shows no note.UPGRADE.md, run by the home's assistant.kit_home (kit #18)User-scope options apply to every session on the machine. That covers memoryDir set in the user's settings, not only the home's own sessions. On the pepys desk a user-wide home made every session on the box drain the desk's spool, and six notifications were lost. Use a pointer conf instead: put this in the folder the session starts in:
kit_home: ../desk # absolute, or relative to this conf's own folder
memory-kit.conf counts (memory_dir, upstream:), with paths relative to that home, and so does its memory-kit/VERSION. Other keys left in the pointer conf are ignored.memoryDir option. Then the option, then the start folder itself. The option is normalized as a pointer is (kit #46).memory-kit.conf takes the nearest one above it, as git finds .git, so a session started in a subfolder or a git worktree of a home finds that home; a pointer conf found there is followed as if the session had started in its folder. The walk stops at the filesystem root. The pane says where it looked: "<start> has no memory-kit.conf; using the nearest one above it, in <folder>".session.start, which a shell cd does not move (kit #45): an install or enable mid-session fires session.start with the shell's folder after any cd, which had made a subfolder the home.kit_home: . is just the home.C:\ or C:/) or UNC. ~ is not expanded: write the path absolute or relative to the conf.memory-kit/VERSION shows memory-kit ? in the header and asks upstream nothing.memory-kit.conf that gives a top-level key twice, the start folder's or the one a pointer names, is the same kind of problem, shown the same way: "duplicate key 'memory_dir' on line 5 (first on line 3)". The pane had read the first memory_dir: and the lint the last, so the two read different memory directories; now neither picks.lint/kit_home.py). This plugin's copy of the rules is hooks/kit-home.ts, identical in all three plugins; lint/run-fixtures.sh fails when the copies differ.The pane never writes into the home: not obligations, not urls/, not any tier. Mihkel ruled on 2026-10-14 that it stays read-only for good, for every tab (kit #43). Resolving or advancing an obligation happens in the file, by whoever owns it. What the pane writes is its own: the release check's cache and the open tab per home, in the plugin's $.store.
From the kit (any home that vendors memory-kit at memory-kit/), in a terminal at the home's root:
claude plugin marketplace add ./memory-kit/adapters/claude-code
claude plugin install obligations-pane@memory-kit
A kit upgrade (subtree pull) does not update the installed plugin: the harness keeps its own copy from the install (kit #23). After a pull that changed it, claude plugin marketplace update memory-kit, claude plugin update obligations-pane@memory-kit, then /reload-plugins in a running session; tools/kit-update.py runs the first two itself when claude is on PATH (#37).
Scope. This installs at user scope: every session on the machine loads the plugin. What it does in a folder that is not a kit home, and the project-scope alternative: Install scope.
Optional: /plugin configure obligations-pane@memory-kit to set the footer's agent name. /obligations (on the Obligations tab) and /memory-pane (on the open tab) open the pane at any width.
Or for one session only: claude --plugin-dir ./memory-kit/adapters/claude-code/obligations-pane.
Options (userConfig):
agentName is the footer name of the main agent. Left empty, the footer uses the working directory's name. A home's own agent_name: in its memory-kit.conf wins over it (gh#4): plugin options are read from user settings only, so on a box with several homes each one names itself there.memoryDir points the pane at a home's memory directory (see Data source). Set user-wide, it applies to every session on the machine: prefer a kit_home pointer conf, which also wins over this option.autoOpen (default on) opens the pane at session start, but only where an obligations file exists.checkUpdates (default on) runs the release check (see Release check). Off, the pane makes no network request at all.One key in the home's memory-kit.conf is read besides memory_dir: upstream: owner/repo (see Release check). The lint ignores keys it does not know.
claude plugin validate .
claude plugin test . # tests/*.test.ts; no test reaches the network
python3 tests/fixtures/make-safe-dump.py # regenerates the yaml.safe_dump fixture (PyYAML)
tsc -p . # once Claude Code has laid .claude-plugin/types/ (gitignored)
tsc -p . needs the type declarations, which Claude Code writes into .claude-plugin/types/ when it loads the mod from a watched folder. Before that, type-check with a tsconfig kept outside the folder whose include names the claude-code.d.ts that the plugin-authoring skill writes, plus hooks, types and tests.
For live testing in a session, link a working copy into the session's dev-mods folder. Claude Code then asks once whether to enable hot reloading for that session:
ln -s <working copy>/obligations-pane ~/.claude/dev-mods/<session-id>/obligations-pane
The pane over the workshop's real memory/obligations.yaml at 56 columns on 2026-10-14 01:14 EEST, with one teammate running; the header line is redrawn in the 0.3.0 format. The capture is a text approximation of the drawn tree. Colours are not shown: the background is pastel ye
hooks/register.tsx 902 lines1// Memory pane (the obligations pane until kit #43): a side pane over the home's memory, one tab
2// per tier. The Obligations tab shows memory/obligations.yaml, soonest expiry first, as 0.6.0 did;
3// the other tabs are tiers.ts's views. Read-only for good (Mihkel, 2026-10-14): it never writes
4// into the home; the open tab is remembered in the plugin's own $.store.
5
6import { atom, read, update } from 'claude-code'
7import type { EngineInterface, Register } from 'claude-code'
8
9import type { ObligationRow, PaneAgent, PaneSnapshot, TierView, ViewChoice, ViewLine } from '../types'
10import { foundAboveNote, resolveKitHome } from './kit-home'
11import {
12 actorColor,
13 cachedCheck,
14 clampIndex,
15 confValue,
16 contextWeight,
17 FETCH_TIMEOUT_MS,
18 countsLabel,
19 countsOf,
20 DATE_FG,
21 EXPIRED_DATE_BG,
22 fitActor,
23 fitName,
24 fitWeight,
25 FOOTER_CHROME,
26 RULE_COLOR,
27 HEADER_BG,
28 HEADER_FG,
29 isAbsolutePath,
30 journalPhase,
31 labelPhase,
32 liveWorkflows,
33 projectSlug,
34 recordWorkflowDone,
35 recordWorkflowSpawn,
36 workflowNameOf,
37 workflowTail,
38 isFresh,
39 isoDate,
40 kitLabel,
41 kitVersionOf,
42 LINK_FG,
43 liveAgents,
44 MODEL_COLORS,
45 memoryDirOf,
46 selfName,
47 modelLetter,
48 newestRelease,
49 offsetFromZ,
50 PANE_BG,
51 parentDir,
52 parseObligations,
53 recordStep,
54 segmentsOf,
55 sortByExpires,
56 statusOf,
57 step,
58 subagentWeight,
59 tagNamesOf,
60 trailingLinksOf,
61 updateNote,
62 upstreamTagsUrl,
63 urlNamesIn,
64 urlNamesOf,
65 urlOfFile,
66 wheelStep,
67 WORKFLOW_FG,
68} from './obligations'
69import type { Segment } from './obligations'
70import {
71 choiceKey,
72 choiceOf,
73 commitmentsView,
74 DEFAULT_CHOICE,
75 factsView,
76 keysView,
77 LESSON_FILTERS,
78 lessonsView,
79 nextView,
80 NO_SCRATCHPAD,
81 rulesView,
82 scratchpadCandidates,
83 scratchpadShaped,
84 secretFiles,
85 secretsView,
86 TABS,
87} from './tiers'
88
89export const PANE = 'obligations'
90export const TITLE = 'Memory'
91export const REFRESH_MS = 20_000
92
93const snapshot = atom({ plugin: 'obligations-pane', key: 'snapshot' } as const, null)
94const index = atom({ plugin: 'obligations-pane', key: 'index' } as const, 0)
95const models = atom({ plugin: 'obligations-pane', key: 'models' } as const, {})
96const loads = atom({ plugin: 'obligations-pane', key: 'loads' } as const, {})
97const mainModel = atom({ plugin: 'obligations-pane', key: 'mainModel' } as const, '')
98const startCwd = atom({ plugin: 'obligations-pane', key: 'startCwd' } as const, '')
99const workflows = atom({ plugin: 'obligations-pane', key: 'workflows' } as const, {})
100const choice = atom({ plugin: 'obligations-pane', key: 'choice' } as const, DEFAULT_CHOICE)
101const choiceHome = atom({ plugin: 'obligations-pane', key: 'choiceHome' } as const, '')
102
103/** The pane's userConfig, trimmed. */
104export type Settings = { agentName: string; memoryDir: string; checkUpdates: boolean }
105
106/** A file's text, '' when it is missing or unreadable. */
107async function readOrEmpty($: EngineInterface, path: string): Promise<string> {
108 try {
109 return (await $.fs.exists(path)) ? await $.fs.read(path) : ''
110 } catch {
111 return ''
112 }
113}
114
115/**
116 * The memory directory: the memoryDir option when set, else <cwd>/<memory_dir> from
117 * <cwd>/memory-kit.conf, else <cwd>/memory. A relative path resolves against cwd; a Windows
118 * absolute one (C:\, C:/, UNC) does not (kit #8).
119 */
120function memoryRoot(cwd: string, conf: string, memoryDir: string): string {
121 const dir = memoryDir !== '' ? memoryDir : (memoryDirOf(conf) ?? 'memory')
122 return isAbsolutePath(dir) ? dir : `${cwd}/${dir}`
123}
124
125/** The $.store key holding every upstream's last check (url -> UpstreamCheck), shared across sessions. */
126const STORE_KEY = 'upstream'
127
128let zoneOffset: number | undefined
129
130/** Minutes east of UTC. The environment's own zone first; the host's `date +%z` when it says UTC. */
131async function offsetOf($: EngineInterface, now: number): Promise<number> {
132 const own = -new Date(now).getTimezoneOffset()
133 if (own !== 0) return own
134 if (zoneOffset !== undefined) return zoneOffset
135 try {
136 const { exitCode, stdout } = await $.process.run(['date', '+%z'], { timeoutMs: 2_000 })
137 zoneOffset = exitCode === 0 ? (offsetFromZ(stdout) ?? 0) : 0
138 } catch {
139 zoneOffset = 0
140 }
141 return zoneOffset
142}
143
144async function readObligations(
145 $: EngineInterface,
146 path: string,
147): Promise<Pick<PaneSnapshot, 'source' | 'error' | 'items'>> {
148 if (!(await $.fs.exists(path))) return { source: 'missing', error: '', items: [] }
149 let text: string
150 try {
151 text = await $.fs.read(path)
152 } catch (err) {
153 return { source: 'error', error: `cannot read: ${String(err)}`, items: [] }
154 }
155 const parsed = parseObligations(text)
156 if (parsed.kind === 'error') return { source: 'error', error: `line ${parsed.line}: ${parsed.message}`, items: [] }
157 return { source: 'ok', error: '', items: sortByExpires(parsed.items) }
158}
159
160async function resolveUrls($: EngineInterface, root: string, items: readonly ObligationRow[], tier: TierView | null) {
161 const urls: Record<string, string> = {}
162 const cited = tier?.kind === 'ok' ? urlNamesIn(tier.lines.flatMap(l => [l.text, l.note])) : []
163 const names = [...new Set([...items.flatMap(urlNamesOf), ...cited])].slice(0, 100)
164 for (const name of names) {
165 try {
166 const url = urlOfFile(await $.fs.read(`${root}/urls/${name}`))
167 if (url !== undefined) urls[name] = url
168 } catch {
169 // Missing urls/<name>: drawn as a dead reference. The pane never writes urls/.
170 }
171 }
172 return urls
173}
174
175let badUpstreamLogged = false
176
177/** A file's text, undefined when it is not there; a read that fails throws. */
178async function readIfThere($: EngineInterface, path: string): Promise<string | undefined> {
179 return (await $.fs.exists(path)) ? $.fs.read(path) : undefined
180}
181
182/** The most facts files one refresh reads: a home with more shows these, and says so in the count. */
183const MAX_FACT_FILES = 200
184
185/**
186 * The open tab's view (kit #43), read from the memory directory `root`. Only the open tab is read:
187 * a refresh reads one tier besides obligations, however many tabs there are. A tier that cannot be
188 * read is its own tab's message, never the other tabs' business.
189 */
190async function readTier($: EngineInterface, view: ViewChoice, root: string, today: string, offset: number): Promise<TierView | null> {
191 const missing = (file: string): TierView => ({ kind: 'missing', message: `no ${file} here (${root}/${file})` })
192 try {
193 switch (view.tab) {
194 case 'O':
195 return null
196 case 'N': {
197 // kit #53: the scratchpad tier is found as the lint finds it, not by a fixed name.
198 const noTier: TierView = { kind: 'missing', message: `${NO_SCRATCHPAD} (${root})` }
199 if (!(await $.fs.exists(root))) return noTier
200 const files: { name: string; text: string }[] = []
201 for (const e of await $.fs.list(root)) {
202 if (scratchpadCandidates([e.name]).length === 0) continue
203 // The lint follows a link to a file; a link is `other` in a listing, so ask where it leads.
204 const kind = e.kind === 'other' ? (await $.fs.stat(`${root}/${e.name}`)).kind : e.kind
205 if (kind !== 'file') continue
206 const text = await $.fs.read(`${root}/${e.name}`)
207 if (e.name !== 'commitments.yaml' || scratchpadShaped(text)) files.push({ name: e.name, text })
208 }
209 return files.length === 0 ? noTier : nextView(files)
210 }
211 case 'C':
212 return commitmentsView(await readIfThere($, `${root}/commitments.yaml`))
213 case 'R': {
214 const text = await readIfThere($, `${root}/rules.yaml`)
215 return text === undefined ? missing('rules.yaml') : rulesView(text)
216 }
217 case 'L': {
218 const text = await readIfThere($, `${root}/lessons/index.yaml`)
219 return text === undefined ? missing('lessons/index.yaml') : lessonsView(text, view.lessons, `${root}/lessons`)
220 }
221 case 'F': {
222 if (!(await $.fs.exists(`${root}/facts`))) return missing('facts/')
223 const names = (await $.fs.list(`${root}/facts`))
224 .filter(e => e.kind === 'file' && /\.ya?ml$/.test(e.name))
225 .map(e => e.name)
226 .sort()
227 const files: { name: string; text: string }[] = []
228 for (const name of names.slice(0, MAX_FACT_FILES)) files.push({ name, text: await $.fs.read(`${root}/facts/${name}`) })
229 const v = factsView(files, today)
230 return v.kind === 'ok' && names.length > MAX_FACT_FILES ? { ...v, count: `${v.count} · first ${MAX_FACT_FILES} of ${names.length} files` } : v
231 }
232 case 'K': {
233 const text = await readIfThere($, `${root}/keys.yaml`)
234 return text === undefined ? missing('keys.yaml') : keysView(text)
235 }
236 case 'S': {
237 // Names and dates only: the README and a listing, never an encrypted file's bytes.
238 const dir = `${root}/secrets`
239 const readme = await readIfThere($, `${dir}/README.md`)
240 const entries = (await $.fs.exists(dir)) ? await $.fs.list(dir) : []
241 return secretsView(readme, secretFiles(entries, ms => isoDate(ms, offset)))
242 }
243 }
244 } catch (err) {
245 return { kind: 'error', message: `cannot read: ${String(err)}` }
246 }
247}
248
249/**
250 * The open tab and lessons filter for `home`: what $.state holds when it is this home's, else
251 * what $.store remembers for the home (kit #43: it outlives a restart), else Obligations.
252 */
253async function choiceFor($: EngineInterface, home: string): Promise<ViewChoice> {
254 if ((await read($, choiceHome)) === home) return choiceOf(await read($, choice))
255 let stored: unknown
256 try {
257 stored = await $.store.get(choiceKey(home))
258 } catch {
259 // No store: the default tab.
260 }
261 const loaded = choiceOf(stored)
262 await $.state.set({ plugin: 'obligations-pane', key: 'choice' }, loaded)
263 await $.state.set({ plugin: 'obligations-pane', key: 'choiceHome' }, home)
264 return loaded
265}
266
267/**
268 * The release check's inputs (kit #4, #7): the home's memory-kit/VERSION, the tags URL to ask
269 * ('' when no check is made: checkUpdates off, no VERSION, or an unusable `upstream:`), and
270 * the newest release the shared cache knows for it. No request here.
271 *
272 * The home is the one that holds the memory directory (a memoryDir session runs outside it),
273 * else the cwd: the first with a memory-kit/VERSION. Its memory-kit.conf names `upstream:`.
274 */
275async function kitOf($: EngineInterface, cwd: string, root: string, checkUpdates: boolean, pointed?: string) {
276 let home = ''
277 let kitVersion = ''
278 // A pointed home (kit_home) is the only candidate; without its VERSION the slot says "?" (the
279 // pointer promised a kit home) and nothing is asked upstream.
280 if (pointed !== undefined && kitVersionOf(await readOrEmpty($, `${pointed}/memory-kit/VERSION`)) === undefined)
281 return { kitVersion: '?', upstreamUrl: '', latest: '' }
282 for (const candidate of pointed !== undefined ? [pointed] : [...new Set([parentDir(root), cwd])]) {
283 kitVersion = kitVersionOf(await readOrEmpty($, `${candidate}/memory-kit/VERSION`)) ?? ''
284 if (kitVersion !== '') {
285 home = candidate
286 break
287 }
288 }
289 if (!checkUpdates || kitVersion === '') return { kitVersion, upstreamUrl: '', latest: '' }
290 const upstream = confValue(await readOrEmpty($, `${home}/memory-kit.conf`), 'upstream')
291 const url = upstreamTagsUrl(upstream)
292 if (url === undefined) {
293 if (!badUpstreamLogged) $.ui.log(`obligations-pane: upstream check skipped: unusable upstream "${upstream}"`, { to: 'debug' })
294 badUpstreamLogged = true
295 return { kitVersion, upstreamUrl: '', latest: '' }
296 }
297 let latest = ''
298 try {
299 latest = cachedCheck(await $.store.get(STORE_KEY), url)?.latest ?? ''
300 } catch {
301 // No store: the check below fills it.
302 }
303 return { kitVersion, upstreamUrl: url, latest }
304}
305
306/** The folder the session started in: its root, which a shell cd does not move (kit #45); `cwd` if the engine gives none. */
307async function startFolder($: EngineInterface, cwd: string): Promise<string> {
308 try {
309 return (await $.session.root()) || cwd
310 } catch {
311 return cwd
312 }
313}
314
315/** Gathers everything the pane draws and writes it to state in one go. No network. */
316export async function refresh($: EngineInterface, settings: Settings): Promise<void> {
317 const { agentName, memoryDir, checkUpdates } = settings
318 const now = await $.clock.now()
319 // The home is where the session started (kit issue #3): a shell cd into another repo
320 // mid-session must not switch the ledger. Without a start seen (a plugin installed mid-session,
321 // kit #45), the session's root: a shell cd does not move it, as it moves $.session.cwd().
322 const cwd = (await read($, startCwd)) || (await $.session.root())
323 // kit #18: the start folder's memory-kit.conf may point at the home (kit_home:, one hop); kit
324 // #42: a start folder without one takes the nearest above it. A home so found wins over the
325 // user-scope memoryDir option, which applies to every session.
326 const found = await resolveKitHome(cwd, async p => ((await $.fs.exists(p)) ? $.fs.read(p) : undefined))
327 const pointed = !('problem' in found) && (found.pointer !== undefined || found.foundIn !== undefined) ? found.home : undefined
328 const home = pointed ?? cwd
329 const conf = await readOrEmpty($, `${home}/memory-kit.conf`)
330 const root = memoryRoot(home, conf, pointed !== undefined ? '' : memoryDir)
331 const path = 'problem' in found ? found.pointer : `${root}/obligations.yaml`
332 const ledger: Pick<PaneSnapshot, 'source' | 'error' | 'items'> =
333 'problem' in found ? { source: 'pointer', error: found.problem, items: [] } : await readObligations($, path)
334 const offsetMinutes = await offsetOf($, now)
335 // kit #43: the open tab, remembered per home; a conf problem (a broken pointer, kit #18, or a
336 // key given twice, kit #55) shows on every tab as it is.
337 const view = await choiceFor($, home)
338 const tier = 'problem' in found ? null : await readTier($, view, root, isoDate(now, offsetMinutes), offsetMinutes)
339 const urls = await resolveUrls($, root, ledger.items, tier)
340
341 let tokens: number | null = null
342 let window: number | null = null
343 try {
344 const { context } = await $.session.usage()
345 tokens = context.tokens ?? null
346 window = context.window
347 } catch {
348 // No usage yet (no session bound): the footer shows "-".
349 }
350 let model = ''
351 try {
352 model = await $.session.model()
353 } catch {
354 // Unknown model draws "?".
355 }
356 const known = await read($, models)
357 let agents: PaneAgent[] = []
358 try {
359 agents = (await $.agent.list()).map(a => ({
360 id: a.id,
361 name: a.name ?? a.teammateId?.split('@')[0] ?? a.description ?? a.type,
362 model: known[a.id] ?? '',
363 status: a.status,
364 }))
365 } catch {
366 // No agent list: the footer shows the main agent alone.
367 }
368
369 const value: PaneSnapshot = {
370 path,
371 ...ledger,
372 urls,
373 foundAbove: !('problem' in found) && found.foundIn !== undefined ? foundAboveNote(cwd, found.foundIn) : '',
374 home,
375 tab: view.tab,
376 tier,
377 ...('problem' in found ? { kitVersion: '', upstreamUrl: '', latest: '' } : await kitOf($, cwd, root, checkUpdates, pointed)),
378 now,
379 offsetMinutes,
380 self: { name: selfName(conf, agentName, cwd), model, tokens, window },
381 agents: liveAgents(agents),
382 }
383 await $.state.set({ plugin: 'obligations-pane', key: 'snapshot' }, value)
384}
385
386let lastWheelStep: number | undefined
387
388/** How many rows the open tab scrolls through: obligations, or the tab's lines. */
389function rowCount(snap: PaneSnapshot | null): number {
390 if (snap === null) return 0
391 const tier = snap.tier ?? null
392 return tier === null ? snap.items.length : tier.kind === 'ok' ? tier.lines.length : 0
393}
394
395/** One wheel event: at most one item, and nothing within the throttle of the last step. */
396async function wheel($: EngineInterface, by: number): Promise<void> {
397 const { delta, lastStep } = wheelStep(by, await $.clock.now(), lastWheelStep)
398 lastWheelStep = lastStep
399 if (delta === 0) return
400 const length = rowCount(await read($, snapshot))
401 await update($, index, i => step(i, delta, length))
402}
403
404/**
405 * A tab or filter chosen (kit #43): shown at once from the top, remembered for the home in
406 * $.store (never in the home's memory), then the tab is read.
407 */
408async function choose($: EngineInterface, settings: Settings, change: Partial<ViewChoice>): Promise<void> {
409 const before = choiceOf(await read($, choice))
410 const next = { ...before, ...change }
411 await $.state.set({ plugin: 'obligations-pane', key: 'choice' }, next)
412 if (next.tab !== before.tab || next.lessons !== before.lessons) await $.state.set({ plugin: 'obligations-pane', key: 'index' }, 0)
413 const home = (await read($, snapshot))?.home ?? ''
414 if (home !== '') {
415 await $.state.set({ plugin: 'obligations-pane', key: 'choiceHome' }, home)
416 try {
417 await $.store.set(choiceKey(home), next)
418 } catch (err) {
419 $.ui.log(`obligations-pane: the tab is not remembered: ${String(err)}`, { to: 'debug' })
420 }
421 }
422 await safeRefresh($, settings)
423}
424
425/**
426 * Asks upstream for its tags when the shared cache is older than 6 h, and records the newest
427 * release in $.store and the snapshot. Only reads: it never pulls. A failure is one debug line
428 * and keeps the last known result; it counts as a check, so the next try is 6 h later.
429 */
430async function checkUpstream($: EngineInterface): Promise<void> {
431 const url = (await read($, snapshot))?.upstreamUrl ?? ''
432 if (url === '') return
433 const now = await $.clock.now()
434 const stored = await $.store.get(STORE_KEY)
435 const cached = cachedCheck(stored, url)
436 if (cached !== undefined && isFresh(cached.checkedAt, now)) return
437
438 let latest = cached?.latest ?? ''
439 let timeout: { cancel: () => void } | undefined
440 try {
441 // A request that never settles would hold `checking` for good: it fails at 10 s instead.
442 const expired = new Promise<never>((_, reject) => {
443 timeout = $.clock.after(FETCH_TIMEOUT_MS, () => reject(new Error(`timed out after ${FETCH_TIMEOUT_MS / 1000} s`)))
444 })
445 const answer = await Promise.race([$.http.fetch(url, { headers: { accept: 'application/json' } }), expired])
446 const names = answer.ok ? tagNamesOf(answer.text) : undefined
447 if (names === undefined) throw new Error(answer.ok ? 'not a tags list' : `HTTP ${answer.status}`)
448 latest = newestRelease(names) ?? ''
449 } catch (err) {
450 $.ui.log(`obligations-pane: upstream check failed (${url}): ${String(err)}`, { to: 'debug' })
451 } finally {
452 timeout?.cancel()
453 }
454 const all = typeof stored === 'object' && stored !== null ? (stored as Record<string, unknown>) : {}
455 await $.store.set(STORE_KEY, { ...all, [url]: { checkedAt: now, latest } })
456 await update($, snapshot, s => (s === null || s.upstreamUrl !== url ? s : { ...s, latest }))
457}
458
459/** refresh, never throwing: a failure goes to the debug log and the last snapshot stays. */
460async function safeRefresh($: EngineInterface, settings: Settings): Promise<void> {
461 try {
462 await refresh($, settings)
463 } catch (err) {
464 $.ui.log(`obligations-pane: refresh failed: ${String(err)}`, { to: 'debug' })
465 }
466}
467
468let checking: Promise<void> | undefined
469
470/** checkUpstream, one at a time and never throwing. */
471async function safeCheck($: EngineInterface): Promise<void> {
472 if (checking !== undefined) return checking
473 checking = checkUpstream($).catch(err => $.ui.log(`obligations-pane: upstream check failed: ${String(err)}`, { to: 'debug' }))
474 try {
475 await checking
476 } finally {
477 checking = undefined
478 }
479}
480
481/** The local refresh, then the release check when one is due, not awaited: no hook waits on the network. */
482async function refreshAll($: EngineInterface, settings: Settings): Promise<void> {
483 await safeRefresh($, settings)
484 void safeCheck($)
485}
486
487/**
488 * The session's folder under Claude Code's projects directory, where it keeps each workflow run's
489 * journal and saved script (undocumented layout: any miss leaves the phase and name to fall back).
490 */
491async function sessionDir($: EngineInterface): Promise<string> {
492 const config = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${(await $.env.get('HOME')) ?? ''}/.claude`
493 const cwd = (await read($, startCwd)) || (await $.session.root())
494 return `${config}/projects/${projectSlug(cwd)}/${await $.session.id()}`
495}
496
497/** Reads each live run's phase (journal) and, until found, its name (saved script). Never throws. */
498async function refreshWorkflows($: EngineInterface): Promise<void> {
499 try {
500 const live = liveWorkflows(await read($, workflows))
501 if (live.length === 0) return
502 const dir = await sessionDir($)
503 let scripts: string[] | undefined
504 for (const [runId, run] of live) {
505 let phase = run.phase
506 try {
507 phase = journalPhase(await $.fs.read(`${dir}/subagents/workflows/${runId}/journal.jsonl`))
508 } catch {
509 // No journal (yet): the label fallback stands.
510 }
511 let name = run.name
512 if (name === '') {
513 try {
514 scripts ??= (await $.fs.list(`${dir}/workflows/scripts`)).map(entry => entry.name)
515 name = workflowNameOf(scripts, runId)
516 } catch {
517 scripts = []
518 }
519 }
520 if (phase !== run.phase || name !== run.name) {
521 await update($, workflows, w => (w[runId] === undefined ? w : { ...w, [runId]: { ...w[runId], phase, name } }))
522 }
523 }
524 } catch (err) {
525 $.ui.log(`obligations-pane: workflow refresh failed: ${String(err)}`, { to: 'debug' })
526 }
527}
528
529export const register: Register = (on, options) => {
530 const settings: Settings = {
531 agentName: typeof options.agentName === 'string' ? options.agentName.trim() : '',
532 memoryDir: typeof options.memoryDir === 'string' ? options.memoryDir.trim() : '',
533 checkUpdates: options.checkUpdates !== false,
534 }
535 const autoOpen = options.autoOpen !== false
536 let timer: { cancel: () => void } | undefined
537
538 on('session.start', async ($, e, next) => {
539 const started = await next(e)
540 // Kept in $.state, which outlives a reload: a reload fires session.start again with the
541 // directory the session is in by then, so only the first start sets it. That first start may
542 // be an install or enable mid-session, whose e.cwd is the shell's folder after any cd: the
543 // session's root is not moved by a cd (kit #45).
544 if ((await read($, startCwd)) === '') await $.state.set({ plugin: 'obligations-pane', key: 'startCwd' }, await startFolder($, e.cwd))
545 // A refused command is a debug line, never a skipped start: a refusal used to throw out of
546 // this hook, and the pane never opened (/memory, Claude Code's built-in, live on 2.1.303).
547 for (const command of [
548 { name: 'obligations', description: 'Open the memory pane on its Obligations tab (memory/obligations.yaml)' },
549 { name: 'memory-pane', description: 'Open the memory pane: one tab per memory tier' },
550 ]) {
551 try {
552 await $.command.register(command)
553 } catch (err) {
554 $.ui.log(`obligations-pane: /${command.name} not registered: ${String(err)}`, { to: 'debug' })
555 }
556 }
557 await safeRefresh($, settings)
558 timer?.cancel()
559 timer = $.clock.every(REFRESH_MS, () => void refreshAll($, settings))
560 const snap = await read($, snapshot)
561 if (autoOpen && snap?.source !== 'missing') void $.ui.open({ id: PANE, title: TITLE })
562 // After the pane is up, and not awaited: the release check may wait on the network.
563 void safeCheck($)
564 return started
565 })
566
567 on('command.run', { command: 'obligations' }, async $ => {
568 await choose($, settings, { tab: 'O' })
569 const opened = await $.ui.open({ id: PANE, title: TITLE })
570 return { text: opened.isPlaced ? 'Obligations pane opened.' : 'Obligations pane waits for a wider terminal.' }
571 })
572
573 on('command.run', { command: 'memory-pane' }, async $ => {
574 await safeRefresh($, settings)
575 const opened = await $.ui.open({ id: PANE, title: TITLE })
576 return { text: opened.isPlaced ? 'Memory pane opened.' : 'Memory pane waits for a wider terminal.' }
577 })
578
579 on('turn.complete', async ($, e, next) => {
580 const done = await next(e)
581 const agentId = e.agentId
582 if (agentId !== undefined) await update($, workflows, w => recordWorkflowDone(w, agentId))
583 await refreshAll($, settings)
584 await refreshWorkflows($)
585 return done
586 })
587
588 // agent.list() carries no model: remember what each spawn resolved to. An observer: if it
589 // fails, the spawn goes on (next(e) replays a call that already settled, runs it otherwise).
590 // Context load per subagent: the latest step's usage. Observe only: every chunk passes
591 // through, the result is returned unchanged, and a failure here never touches the step.
592 on('turn.step', async function* ($, e, next) {
593 const result = yield* next(e)
594 try {
595 const usage = result.usage
596 if (usage !== null) {
597 if (e.agentId === undefined) await $.state.set({ plugin: 'obligations-pane', key: 'mainModel' }, usage.model)
598 else await update($, loads, l => recordStep(l, e.agentId, usage))
599 }
600 } catch {
601 // A lost load figure is not worth a failed hook.
602 }
603 return result
604 })
605
606 on('agent.spawn', async ($, e, next) => {
607 const result = await next(e)
608 const id = result.agentId
609 if (result.deny === undefined && id !== undefined) {
610 await update($, models, m => ({ ...m, [id]: result.model }))
611 const runId = e.workflow?.runId
612 if (runId !== undefined && runId !== '') {
613 await update($, workflows, w => recordWorkflowSpawn(w, runId, id, e.description))
614 await refreshWorkflows($)
615 }
616 await safeRefresh($, settings)
617 }
618 return result
619 }).catch(($, e, next) => next(e))
620
621 // Mouse wheel (and scroll keys) over the pane: strictly one obligation per event, by e.by's
622 // sign, then 150 ms of ignored events (a trackpad burst is one item); clamped to the list.
623 // No next(e): the engine's window stays, so the header and footer stay fixed; the index
624 // write redraws the pane.
625 on('ui.scroll', { component: 'Pane', requestId: PANE }, async ($, e) => {
626 await wheel($, e.by)
627 return {}
628 }).catch(() => ({}))
629
630 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
631 const { Box, Text, Button, Link } = $.ui.resolve(e)
632 const snap = await read($, snapshot)
633 const at = await read($, index)
634 const agentLoads = await read($, loads)
635 const runs = liveWorkflows(await read($, workflows))
636 const mainId = await read($, mainModel)
637 const rows = e.props.scroll.bodyRows
638
639 if (snap === null) {
640 return (
641 <Box backgroundColor={PANE_BG} flexDirection="column" height={rows}>
642 <Text color={DATE_FG}>loading obligations…</Text>
643 </Box>
644 )
645 }
646
647 const today = isoDate(snap.now, snap.offsetMinutes)
648 const items = snap.items
649 // kit #43: the tab the person chose, at once; its view once a refresh has read it.
650 const view = choiceOf(await read($, choice))
651 const onO = view.tab === 'O'
652 const tier = !onO && snap.tab === view.tab ? (snap.tier ?? null) : null
653 const count = onO ? items.length : tier?.kind === 'ok' ? tier.lines.length : 0
654 const first = clampIndex(at, count)
655 const move = (delta: number) => () => update($, index, i => step(i, delta, count))
656 const pick = (change: Partial<ViewChoice>) => () => choose($, settings, change)
657
658 // The tab row (kit #43): the open tab by its full name, the others by one letter, so the row
659 // fits a narrow pane; it wraps when even that does not fit. Digits 1-8 pick a tab too.
660 const tabRow = (
661 <Box key="tabs" flexDirection="row" flexWrap="wrap" flexShrink={0} paddingX={1}>
662 {TABS.map(t =>
663 t.id === view.tab ? (
664 <Button key={`tab-${t.id}`} plain onPress={pick({ tab: t.id })}>
665 <Text bold color={HEADER_FG} backgroundColor={HEADER_BG}>
666 [{t.name}]
667 </Text>
668 </Button>
669 ) : (
670 <Button key={`tab-${t.id}`} plain onPress={pick({ tab: t.id })}>
671 <Text color={DATE_FG}>[{t.id}]</Text>
672 </Button>
673 ),
674 )}
675 <Box display="none">
676 {TABS.map((t, i) => (
677 <Button key={`tab-key-${t.id}`} plain hotkey={String(i + 1)} onPress={pick({ tab: t.id })}>
678 {t.id}
679 </Button>
680 ))}
681 </Box>
682 </Box>
683 )
684
685 // The lessons filter (kit #43): one chip per enforcement type, under the header.
686 const chips = view.tab === 'L' && (
687 <Box key="chips" flexDirection="row" flexWrap="wrap" flexShrink={0} paddingX={1}>
688 {LESSON_FILTERS.map(f => (
689 <Button key={`chip-${f}`} plain onPress={pick({ lessons: f })}>
690 {f === view.lessons ? (
691 <Text bold color={HEADER_FG} backgroundColor={HEADER_BG}>
692 [{f}]
693 </Text>
694 ) : (
695 <Text color={DATE_FG}>[{f}]</Text>
696 )}
697 </Button>
698 ))}
699 </Box>
700 )
701
702 // The header's middle: the obligations counts on O, the open tab's own count elsewhere.
703 const headerCount = onO ? (snap.source === 'ok' ? countsLabel(countsOf(items, today)) : '') : tier?.kind === 'ok' ? tier.count : ''
704
705 const header = (
706 <Box key="header" backgroundColor={HEADER_BG} flexDirection="row" justifyContent="space-between" paddingX={1} flexShrink={0}>
707 <Text color={HEADER_FG} bold wrap="truncate-end">
708 {/* `?? ''`: a snapshot a 0.2.x module wrote before a hot reload has neither field. */}
709 {[kitLabel(snap.kitVersion ?? '', updateNote(snap.kitVersion ?? '', snap.latest ?? '')), headerCount]
710 .filter(part => part !== '')
711 .join(' ')}
712 </Text>
713 {count > 1 && (
714 <Box flexDirection="row" flexShrink={0}>
715 <Text color={HEADER_FG}>
716 {first + 1}/{count}
717 </Text>
718 {/* Not drawn: they only carry the k / j hotkeys. The wheel scrolls (ui.scroll). */}
719 <Box display="none">
720 <Button key="up" plain hotkey="k" onPress={move(-1)}>
721 ▲
722 </Button>
723 <Button key="down" plain hotkey="j" onPress={move(1)}>
724 ▼
725 </Button>
726 </Box>
727 </Box>
728 )}
729 </Box>
730 )
731
732 const segment = (s: Segment, i: number) =>
733 s.kind === 'text' ? (
734 s.text
735 ) : s.kind === 'link' ? (
736 <Link key={`l${i}`} href={s.href}>
737 <Text color={LINK_FG} underline>
738 {s.name}
739 </Text>
740 </Link>
741 ) : (
742 <Text key={`d${i}`} color="#666666" strikethrough>
743 urls/{s.name}
744 </Text>
745 )
746
747 const row = (item: ObligationRow) => {
748 const status = statusOf(item, today)
749 const trailing = trailingLinksOf(item, snap.urls)
750 return (
751 <Box key={`row-${item.line}`} flexDirection="column" flexShrink={0} paddingX={1}>
752 <Text color={DATE_FG}>
753 <Text bold color={DATE_FG} {...(status === 'expired' ? { backgroundColor: EXPIRED_DATE_BG } : {})}>
754 {item.expires}
755 </Text>{' '}
756 <Text bold color={actorColor(item.actor)}>
757 {fitActor(item.actor)}
758 </Text>
759 {/* kit #29: 'actor -> owed_to:', as tools/obligations-due.py prints it. An array, not a
760 fragment: the engine refused a fragment here (Box inside an inline element). */}
761 {item.owed_to !== ''
762 ? [
763 ' -> ',
764 <Text key="owed" bold color={actorColor(item.owed_to)}>
765 {fitActor(item.owed_to)}
766 </Text>,
767 ':',
768 ]
769 : null}{' '}
770 {segmentsOf(item.obligation, snap.urls).map(segment)}
771 {trailing.map((s, i) => [' ', segment(s, 100 + i)])}
772 </Text>
773 </Box>
774 )
775 }
776
777 // kit #42: a home found above the start folder is said, so a surprising home is visible.
778 // `?? ''`: a snapshot an older module wrote before a hot reload has no such field.
779 const foundAbove = (snap.foundAbove ?? '') !== '' && (
780 <Text key="found-above" color={DATE_FG} dimColor wrap="wrap">
781 {snap.foundAbove}
782 </Text>
783 )
784
785 // One line of a tier tab (kit #43): a heading, or tag, text with its links, note and flag.
786 const tierLine = (l: ViewLine) => {
787 if (l.heading)
788 return (
789 <Box key={l.key} flexDirection="column" flexShrink={0} paddingX={1}>
790 <Text bold underline color={DATE_FG}>
791 {l.text}
792 {l.flag !== '' ? <Text color="#9e0000"> {l.flag}</Text> : null}
793 </Text>
794 </Box>
795 )
796 const text = segmentsOf(l.text, snap.urls).map(segment)
797 return (
798 <Box key={l.key} flexDirection="column" flexShrink={0} paddingX={1}>
799 <Text color={DATE_FG} dimColor={l.dim}>
800 {l.tag !== '' ? [<Text key="tag" bold color={view.tab === 'K' ? actorColor(l.tag) : DATE_FG}>{l.tag}</Text>, ' '] : null}
801 {l.href !== '' ? (
802 <Link key="file" href={l.href}>
803 <Text color={LINK_FG}>{l.text}</Text>
804 </Link>
805 ) : (
806 text
807 )}
808 {l.note !== '' ? <Text dimColor> {l.note}</Text> : null}
809 {l.flag !== '' ? <Text color="#9e0000"> {l.flag}</Text> : null}
810 </Text>
811 </Box>
812 )
813 }
814
815 const tierBody =
816 tier === null ? (
817 <Text color={DATE_FG}>reading…</Text>
818 ) : tier.kind === 'missing' ? (
819 <Text color={DATE_FG}>{tier.message}</Text>
820 ) : tier.kind === 'error' ? (
821 <Text color="#9e0000">{tier.message}</Text>
822 ) : (
823 [
824 tier.banner !== '' ? (
825 <Text key="banner" color="#9e0000" bold wrap="wrap">
826 {tier.banner}
827 </Text>
828 ) : null,
829 ...(tier.lines.length === 0 ? [<Text key="empty" color={DATE_FG}>nothing here yet</Text>] : tier.lines.slice(first).map(tierLine)),
830 ]
831 )
832
833 const body = !onO && snap.source !== 'pointer' ? (
834 tierBody
835 ) :
836 snap.source === 'missing' ? (
837 <Text color={DATE_FG}>no obligations file here ({snap.path})</Text>
838 ) : snap.source === 'pointer' ? (
839 <Text color="#9e0000">memory-kit.conf problem: {snap.error}</Text>
840 ) : snap.source === 'error' ? (
841 <Text color="#9e0000">obligations.yaml unreadable: {snap.error}</Text>
842 ) : items.length === 0 ? (
843 <Text color={DATE_FG}>no obligations</Text>
844 ) : (
845 items.slice(first).map(row)
846 )
847
848 const agentLine = (key: string, name: string, model: string, tail: string, dim: boolean) => {
849 const letter = modelLetter(model)
850 return (
851 // wrap, never truncate: the figure is the point of the line (fitWeight keeps it short).
852 <Text key={key} color={DATE_FG} dimColor={dim} wrap="wrap">
853 {fitName(name)}{' '}
854 <Text bold color={MODEL_COLORS[letter]} dimColor={letter === '·'}>
855 {letter}
856 </Text>
857 {tail !== '' ? ` ${fitWeight(tail, e.props.bodyColumns - FOOTER_CHROME)}` : ''}
858 </Text>
859 )
860 }
861
862 const footer = (
863 <Box key="footer" flexDirection="column" flexShrink={0}>
864 <Text key="rule" color={RULE_COLOR} wrap="truncate-end">
865 {'─'.repeat(Math.max(0, e.props.bodyColumns))}
866 </Text>
867 <Box key="lines" flexDirection="column" paddingX={1}>
868 {agentLine('self', snap.self.name, snap.self.model, contextWeight(snap.self.tokens ?? undefined, snap.self.window ?? undefined), false)}
869 {snap.agents.map(a => {
870 const load = agentLoads[a.id]
871 const model = load?.model ?? a.model
872 const weight = subagentWeight(load, mainId !== '' ? mainId : snap.self.model, snap.self.window)
873 return agentLine(`agent-${a.id}`, a.name, model, weight, a.status !== 'running')
874 })}
875 {runs.map(([runId, run]) => (
876 <Text key={`wf-${runId}`} color={DATE_FG} wrap="wrap">
877 {fitName(run.name !== '' ? run.name : runId)}{' '}
878 <Text bold color={WORKFLOW_FG}>
879 ≡
880 </Text>{' '}
881 {workflowTail(run.phase !== '' ? run.phase : labelPhase(run.label), run.done.length, run.started.length)}
882 </Text>
883 ))}
884 </Box>
885 </Box>
886 )
887
888 return (
889 <Box backgroundColor={PANE_BG} flexDirection="column" height={rows}>
890 {tabRow}
891 {header}
892 {chips}
893 <Box key="body" flexDirection="column" flexGrow={1} flexShrink={1} overflow="hidden" gap={1} paddingTop={1}>
894 {foundAbove}
895 {body}
896 </Box>
897 {footer}
898 </Box>
899 )
900 })
901}
902hooks/kit-home.ts 152 lines1// kit_home: a memory-kit.conf key naming the kit home (kit #18). Pure: the caller hands in how
2// to read a file.
3//
4// IDENTICAL in adapters/claude-code/{obligations-pane,watch,kit-update}/hooks/kit-home.ts: a
5// plugin loads only its own folder, so each carries a copy; lint/run-fixtures.sh fails when the
6// copies differ. The same rules for Python are lint/kit_home.py, with the same messages.
7//
8// A start folder without a memory-kit.conf takes the nearest one above it (kit #42), as git finds
9// .git: a session started in a subfolder or a worktree of a home finds that home. The walk stops at
10// the filesystem root; no conf anywhere leaves the start folder as the home, as before.
11//
12// If that memory-kit.conf says `kit_home: <path>` (absolute, or relative to that conf's folder),
13// the home is the folder it names: that home's conf, memory-kit/VERSION, memory
14// directory, update:/upstream: and watch_files count, and the pointer conf's other keys are
15// ignored (reported in `ignored`). One hop, never chained: the target's conf may not point on (a
16// loop is a chain too). `kit_home: .` is just the home. A target with no memory-kit.conf, and a
17// `~` path (not expanded), are problems said plainly, never a silent fall back.
18//
19// So is a memory-kit.conf that gives a top-level key twice (kit #55), the start folder's or the one
20// a pointer names: confValueOf and the plugins' confValue take the first copy and YAML the last,
21// so a conf with memory_dir: twice sent the memory pane and the lint to different directories.
22
23export const KIT_HOME_KEY = 'kit_home'
24
25/** `foundIn`: the folder above the start folder whose memory-kit.conf decided (kit #42); absent
26 * when the start folder's own did, or none did. */
27export type KitHome = { home: string; pointer?: string; ignored: string[]; foundIn?: string } | { problem: string; pointer: string }
28
29/** POSIX (/...), a drive letter (C:\ or C:/) or UNC (\\server\share). */
30export function isAbsolute(path: string): boolean {
31 return /^(\/|[A-Za-z]:[\\/]|\\\\)/.test(path)
32}
33
34/** `.` and `..` resolved, `/` as the separator, no trailing slash; a root (/, C:/, //server/share) kept. */
35export function normalizePath(path: string): string {
36 const unc = /^\\\\|^\/\//.test(path)
37 const drive = /^[A-Za-z]:[\\/]/.exec(path)?.[0].slice(0, 2)
38 const root = unc ? '//' : drive !== undefined ? `${drive}/` : path.startsWith('/') ? '/' : ''
39 const parts: string[] = []
40 for (const part of path.slice(unc ? 2 : drive !== undefined ? 3 : root.length).split(/[\\/]+/)) {
41 if (part === '' || part === '.') continue
42 if (part === '..' && parts.length > 0 && parts[parts.length - 1] !== '..') parts.pop()
43 else if (part !== '..' || root === '') parts.push(part)
44 }
45 return `${root}${parts.join('/')}` || '.'
46}
47
48/** `name` inside `dir`; a root (/, C:/) already ends in its separator. */
49const inside = (dir: string, name: string) => (dir.endsWith('/') ? `${dir}${name}` : `${dir}/${name}`)
50
51/** The folder above `path`, normalized; undefined at a root (/, C:/, //server/share). */
52export function parentOf(path: string): string | undefined {
53 const p = normalizePath(path)
54 if (p === '/' || /^[A-Za-z]:\/$/.test(p) || /^\/\/[^/]+(\/[^/]+)?$/.test(p)) return undefined
55 const cut = p.lastIndexOf('/')
56 if (cut === -1) return undefined
57 if (cut === 0) return '/'
58 const up = p.slice(0, cut)
59 return /^[A-Za-z]:$/.test(up) ? `${up}/` : up
60}
61
62const sameAs = (a: string, b: string) => {
63 const [x, y] = [normalizePath(a), normalizePath(b)]
64 return /^[A-Za-z]:\//.test(x) || x.startsWith('//') ? x.toLowerCase() === y.toLowerCase() : x === y
65}
66
67/** A top-level `key: value` of memory-kit.conf, a trailing comment and quotes stripped; '' when absent. */
68export function confValueOf(conf: string, key: string): string {
69 for (const line of conf.split(/\r?\n/)) {
70 if (!line.startsWith(`${key}:`)) continue
71 const raw = line.slice(key.length + 1)
72 const hash = raw.search(/\s#/)
73 return (hash === -1 ? raw : raw.slice(0, hash)).trim().replace(/^["']|["']$/g, '')
74 }
75 return ''
76}
77
78/** What a reader says when the folder it took for the home has no memory-kit.conf (kit #31): silence
79 * there looked the same as "nothing newer". lint/kit_home.py no_conf_notice says it alike. */
80export function noConfNotice(folder: string): string {
81 return `${normalizePath(folder)} has no memory-kit.conf, so it is not a kit home; if the home is elsewhere, put kit_home: <path> in a memory-kit.conf here`
82}
83
84/** What a reader says when the home came from a conf above the start folder (kit #42), so a
85 * surprising home is visible. lint/kit_home.py found_above_note says it alike. */
86export function foundAboveNote(start: string, foundIn: string): string {
87 return `${normalizePath(start)} has no memory-kit.conf; using the nearest one above it, in ${normalizePath(foundIn)}`
88}
89
90const topKeys = (conf: string) => conf.split(/\r?\n/).flatMap(line => /^([A-Za-z_][\w-]*):/.exec(line)?.[1] ?? [])
91
92/** The first top-level key a memory-kit.conf gives twice, its line and the first one's; undefined
93 * when it gives each once (kit #55). lint/kit_home.py repeated_key reads it alike. */
94export function repeatedKey(conf: string): { key: string; line: number; first: number } | undefined {
95 const seen = new Map<string, number>()
96 for (const [i, line] of conf.split(/\r?\n/).entries()) {
97 const key = /^([A-Za-z_][\w-]*):/.exec(line)?.[1]
98 if (key === undefined) continue
99 const first = seen.get(key)
100 if (first !== undefined) return { key, line: i + 1, first }
101 seen.set(key, i + 1)
102 }
103 return undefined
104}
105
106/** The problem a conf giving a top-level key twice is (kit #55); undefined when it gives each once.
107 * lint/kit_home.py repeated_key_problem says it alike. */
108export function repeatedKeyProblem(path: string, conf: string): string | undefined {
109 const twice = repeatedKey(conf)
110 if (twice === undefined) return undefined
111 return `${path}: duplicate key '${twice.key}' on line ${twice.line} (first on line ${twice.first}); the plugins would take the first and the lint the last, so keep only one`
112}
113
114/** The home for a start folder, by its memory-kit.conf's kit_home (see the head of this file). */
115export async function resolveKitHome(start: string, read: (path: string) => Promise<string | undefined>): Promise<KitHome> {
116 const begin = normalizePath(start)
117 let from: string | undefined = begin
118 let conf: string | undefined
119 for (; from !== undefined; from = parentOf(from)) {
120 try {
121 conf = await read(inside(from, 'memory-kit.conf'))
122 } catch (err) {
123 // A folder above that cannot be read (a network share refuses) ends the walk, as no conf would.
124 if (from === begin) throw err
125 break
126 }
127 if (conf !== undefined) break
128 }
129 if (from === undefined || conf === undefined) return { home: begin, ignored: [] }
130 const above = from === begin ? {} : { foundIn: from }
131 const pointer = inside(from, 'memory-kit.conf')
132 const twice = repeatedKeyProblem(pointer, conf)
133 if (twice !== undefined) return { pointer, problem: twice }
134 const raw = confValueOf(conf, KIT_HOME_KEY)
135 if (raw === '') return { home: from, ignored: [], ...above }
136 if (raw.startsWith('~'))
137 return { pointer, problem: `${pointer}: kit_home: ${raw} -- write it absolute or relative to this conf's folder (~ is not expanded)` }
138 const target = normalizePath(isAbsolute(raw) ? raw : inside(from, raw))
139 if (sameAs(target, from)) return { home: from, ignored: [], ...above }
140 const targetConf = await read(inside(target, 'memory-kit.conf'))
141 if (targetConf === undefined) return { pointer, problem: `${pointer}: kit_home: ${raw} -> ${target}: no memory-kit.conf there, so it is not a kit home` }
142 const targetTwice = repeatedKeyProblem(inside(target, 'memory-kit.conf'), targetConf)
143 if (targetTwice !== undefined) return { pointer, problem: targetTwice }
144 const onward = confValueOf(targetConf, KIT_HOME_KEY)
145 if (onward !== '' && !sameAs(isAbsolute(onward) ? onward : inside(target, onward), target))
146 return {
147 pointer,
148 problem: `${pointer}: kit_home: ${raw} -> ${target}, whose own conf points on (kit_home: ${onward}); a pointer is followed one hop, never chained`,
149 }
150 return { home: target, pointer, ignored: topKeys(conf).filter(k => k !== KIT_HOME_KEY), ...above }
151}
152hooks/obligations.ts 979 lines1// Pure logic of the obligations pane: no `$`, no I/O. Everything here is unit-tested.
2//
3// Shape of the data: memory-kit/types/memory-obligations.ts (obligations: [{obligation, actor,
4// owed_to, since, check, expires, ref}]). URL tier: memory-kit/types/memory-urls.ts
5// (memory/urls/<name>, one URL on line 1).
6
7import type { AgentLoad, ObligationRow, PaneAgent, WorkflowRun } from '../types'
8
9// ---------------------------------------------------------------------------------------------
10// Parsing: a small strict parser for exactly the obligations shape. The mod environment has no
11// node_modules and no bundler, so no YAML dependency. Anything outside the shape is an error
12// with a line number, never a silent guess.
13
14export type ParseResult =
15 | { kind: 'ok'; items: ObligationRow[] }
16 | { kind: 'error'; line: number; message: string }
17
18const KEYS = ['obligation', 'actor', 'owed_to', 'since', 'check', 'expires', 'ref'] as const
19const REQUIRED = ['obligation', 'actor', 'expires'] as const
20const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/
21
22class ParseError extends Error {
23 constructor(
24 readonly line: number,
25 message: string,
26 ) {
27 super(message)
28 }
29}
30
31/** Strips a trailing ` # comment` from a plain (unquoted) scalar. */
32function plainScalar(raw: string): string {
33 const hash = raw.search(/(^|\s)#/)
34 return (hash === -1 ? raw : raw.slice(0, hash)).trim()
35}
36
37const ESCAPES: Record<string, string> = {
38 '0': '\0', a: '\x07', b: '\b', t: '\t', n: '\n', v: '\v', f: '\f', r: '\r', e: '\x1b',
39 ' ': ' ', '"': '"', '/': '/', '\\': '\\', N: '\x85', _: '\xa0', L: '
', P: '
',
40}
41const HEX_ESCAPES: Record<string, number> = { x: 2, u: 4, U: 8 }
42
43/**
44 * Line folding inside a flow scalar: `text` holds the scalar's lines joined by '\n'. Each
45 * line is trimmed (the first only at its end, the last only at its start); one break
46 * becomes a space, each empty line between two lines a '\n'.
47 */
48function fold(lines: readonly string[]): string {
49 let out = ''
50 let empties = 0
51 lines.forEach((raw, i) => {
52 let line = i === 0 ? raw : raw.trimStart()
53 if (i < lines.length - 1) line = line.trimEnd()
54 if (i > 0 && line === '' && i < lines.length - 1) {
55 empties++
56 return
57 }
58 if (i > 0) out += empties > 0 ? '\n'.repeat(empties) : ' '
59 empties = 0
60 out += line
61 })
62 return out
63}
64
65/**
66 * One scalar value: double-quoted, single-quoted, or plain, as YAML reads it. `raw` is the
67 * value's first line and any continuation lines, joined by '\n' (yaml.safe_dump folds long
68 * values onto indented continuation lines). `null` and `~` written plain are empty.
69 */
70export function parseScalar(raw: string, line: number): string {
71 const text = raw.trim()
72 if (text.startsWith('"')) {
73 // The scalar's lines, escapes marked; folded once the closing quote is found.
74 const parts: string[] = []
75 let current = ''
76 let lineNo = line
77 for (let i = 1; i < text.length; i++) {
78 const c = text[i] ?? ''
79 if (c === '"') {
80 const rest = text.slice(i + 1).trim()
81 if (rest !== '' && !rest.startsWith('#')) throw new ParseError(lineNo, 'text after closing quote')
82 parts.push(current)
83 return foldQuoted(parts)
84 }
85 if (c === '\n') {
86 lineNo++
87 parts.push(current)
88 current = ''
89 continue
90 }
91 if (c === '\\') {
92 const n = text[++i] ?? ''
93 if (n === '\n') {
94 // Escaped break: the lines join with nothing between, the next line's indent dropped.
95 lineNo++
96 while (text[i + 1] === ' ') i++
97 continue
98 }
99 const width = HEX_ESCAPES[n]
100 if (width !== undefined) {
101 const hex = text.slice(i + 1, i + 1 + width)
102 if (!new RegExp(`^[0-9A-Fa-f]{${width}}$`).test(hex)) throw new ParseError(lineNo, `bad escape \\${n}${hex}`)
103 current += escapeMark(String.fromCodePoint(Number.parseInt(hex, 16)))
104 i += width
105 continue
106 }
107 const mapped = ESCAPES[n]
108 if (mapped === undefined) throw new ParseError(lineNo, `unsupported escape \\${n}`)
109 current += escapeMark(mapped)
110 continue
111 }
112 current += c
113 }
114 throw new ParseError(line, 'unterminated double-quoted string')
115 }
116 if (text.startsWith("'")) {
117 let out = ''
118 for (let i = 1; i < text.length; i++) {
119 const c = text[i]
120 if (c === "'") {
121 if (text[i + 1] === "'") {
122 out += "'"
123 i++
124 continue
125 }
126 const rest = text.slice(i + 1).trim()
127 if (rest !== '' && !rest.startsWith('#')) throw new ParseError(line + lineCount(text.slice(0, i)), 'text after closing quote')
128 return fold(out.split('\n'))
129 }
130 out += c
131 }
132 throw new ParseError(line, 'unterminated single-quoted string')
133 }
134 const lines = text.split('\n')
135 lines.forEach((l, i) => {
136 if (i < lines.length - 1 && plainScalar(l) !== l.trim()) throw new ParseError(line + i, 'a comment cannot continue onto the next line')
137 })
138 const plain = fold(lines.map(plainScalar))
139 if (/^[|>]/.test(plain)) throw new ParseError(line, 'block scalars (| or >) are not supported')
140 if (/^[[{&*!]/.test(plain)) throw new ParseError(line, `unsupported value: ${plain.slice(0, 20)}`)
141 if (plain === '~' || /^(null|Null|NULL)$/.test(plain)) return ''
142 return plain
143}
144
145function lineCount(text: string): number {
146 return text.split('\n').length - 1
147}
148
149// Escaped characters are content, never trimmed or folded: each is carried as a mark with
150// no whitespace in it (U+0000, the code point in hex, ';') until folding is done.
151const escapeMark = (c: string) => `\u0000${(c.codePointAt(0) ?? 0).toString(16)};`
152
153function foldQuoted(parts: readonly string[]): string {
154 return fold(parts).replace(/\u0000([0-9a-f]+);/g, (_, hex: string) => String.fromCodePoint(Number.parseInt(hex, 16)))
155}
156
157/**
158 * The entries of a one-line flow map (`{rule: "x", ref: ''}`), as a list item may be written: the
159 * kit's own fixtures do, and YAML allows it. Commas inside quotes are content; nested
160 * collections are not supported.
161 */
162function flowEntries(text: string, line: number): [string, string][] {
163 const hash = text.search(/\}\s*(#.*)?$/)
164 if (!text.startsWith('{') || hash === -1) throw new ParseError(line, 'a flow map must open and close on its line')
165 const inner = text.slice(1, hash)
166 const parts: string[] = []
167 let current = ''
168 let quote = ''
169 for (let i = 0; i < inner.length; i++) {
170 const c = inner[i] ?? ''
171 if (quote !== '') {
172 current += c
173 if (c === '\\' && quote === '"') current += inner[++i] ?? ''
174 else if (c === quote) {
175 if (quote === "'" && inner[i + 1] === "'") current += inner[++i] ?? ''
176 else quote = ''
177 }
178 continue
179 }
180 // A quote opens a value only where the value starts: `It's` in a plain value is content.
181 if ((c === '"' || c === "'") && /(^|[:,])\s*$/.test(current)) quote = c
182 if (c === '{' || c === '[') throw new ParseError(line, 'nested values are not supported')
183 if (c === ',') {
184 parts.push(current)
185 current = ''
186 continue
187 }
188 current += c
189 }
190 if (quote !== '') throw new ParseError(line, 'unterminated quoted string in a flow map')
191 parts.push(current)
192 return parts.filter(p => p.trim() !== '').map(p => {
193 const m = /^\s*([A-Za-z_][\w-]*):(\s+(.*))?$/.exec(p)
194 if (!m) throw new ParseError(line, `expected "key: value" in a flow map, got: ${p.trim().slice(0, 40)}`)
195 return [m[1] ?? '', parseScalar(m[3] ?? '', line)]
196 })
197}
198
199/** Splits `key: value` (value may be empty). */
200function keyValue(text: string, line: number): [string, string] {
201 const m = /^([A-Za-z_][\w-]*):(\s+(.*))?$/.exec(text)
202 if (!m) throw new ParseError(line, `expected "key: value", got: ${text.slice(0, 40)}`)
203 return [m[1] ?? '', m[3] ?? '']
204}
205
206/**
207 * Parses memory/obligations.yaml. Accepts: comments, blank lines, one top-level key
208 * `obligations:` holding a block list of flat maps (or `[]`), scalar values quoted or plain.
209 * The list items may sit at column 0 under the key, as yaml.safe_dump writes them, or be
210 * indented; a value may continue on lines indented deeper than its key (folded as YAML does).
211 * Every item records the 1-based line it starts on: file order for ties, and a stable row key.
212 */
213export function parseObligations(text: string): ParseResult {
214 const parsed = parseMapLists(text, OBLIGATIONS)
215 if (parsed.kind === 'error') return parsed
216 return {
217 kind: 'ok',
218 items: (parsed.lists.obligations ?? []).map(({ fields: f, line }) => ({
219 obligation: f.obligation ?? '',
220 actor: f.actor ?? '',
221 owed_to: f.owed_to ?? '',
222 since: f.since ?? '',
223 check: f.check ?? '',
224 expires: f.expires ?? '',
225 ref: f.ref ?? '',
226 line,
227 })),
228 }
229}
230
231const OBLIGATIONS: ListSpec = { tops: ['obligations'], keys: KEYS, required: REQUIRED, dates: ['since', 'expires'] }
232
233/**
234 * One tier file's shape for parseMapLists: its top-level keys, each holding a block list of
235 * flat maps (memory-kit/types/memory-*.ts), the keys an item may carry, those it must carry
236 * non-empty, and those that are ISO dates when set.
237 */
238export type ListSpec = {
239 tops: readonly string[]
240 keys: readonly string[]
241 required: readonly string[]
242 dates: readonly string[]
243}
244
245/** One parsed item: every key of its spec ('' when absent), and the 1-based line it starts on. */
246export type MapRow = { fields: Record<string, string>; line: number }
247
248export type ListsResult = { kind: 'ok'; lists: Record<string, MapRow[]> } | { kind: 'error'; line: number; message: string }
249
250/**
251 * Parses a tier file of the kit's one YAML shape: top-level keys, each a block list of flat maps
252 * (or `[]`), as parseObligations reads obligations.yaml (that is this, with its spec). Each top
253 * key may appear once, in any order; an absent one is an empty list. Anything outside the shape
254 * is an error with a line, never a guess.
255 */
256export function parseMapLists(text: string, spec: ListSpec): ListsResult {
257 try {
258 return { kind: 'ok', lists: parseOrThrow(text, spec) }
259 } catch (err) {
260 if (err instanceof ParseError) return { kind: 'error', line: err.line, message: err.message }
261 throw err
262 }
263}
264
265function parseOrThrow(text: string, spec: ListSpec): Record<string, MapRow[]> {
266 const lines = text.replace(/^\uFEFF/, '').split(/\r?\n/)
267 const lists: Record<string, MapRow[]> = Object.fromEntries(spec.tops.map(t => [t, []]))
268 const seen = new Set<string>()
269 let top: string | undefined
270 let isEmptyList = false
271 let itemIndent = -1
272 let keyIndent = -1
273 let current: MapRow | undefined
274 // The key whose value is still open: continuation lines join it until the next key or item.
275 let pending: { key: string; raw: string[]; line: number; blanks: number } | undefined
276 const firstTops = spec.tops.map(t => `"${t}:"`).join(' or ')
277
278 const flush = () => {
279 if (!pending) return
280 const { key, raw, line } = pending
281 pending = undefined
282 if (!current) throw new ParseError(line, 'key outside a list item')
283 if (!spec.keys.includes(key)) throw new ParseError(line, `unknown key "${key}"`)
284 if (current.fields[key] !== undefined) throw new ParseError(line, `duplicate key "${key}"`)
285 // A value that starts on the next line: the scalar is the continuation alone.
286 const value = raw[0]?.trim() === '' && raw.length > 1 ? raw.slice(1) : raw
287 current.fields[key] = parseScalar(value.join('\n'), line)
288 }
289
290 const close = () => {
291 flush()
292 if (!current || top === undefined) return
293 for (const key of spec.required) {
294 if (current.fields[key] === undefined || current.fields[key] === '') {
295 throw new ParseError(current.line, `item is missing "${key}"`)
296 }
297 }
298 for (const key of spec.dates) {
299 const v = current.fields[key]
300 if (v !== undefined && v !== '' && !ISO_DATE.test(v)) {
301 throw new ParseError(current.line, `"${key}" is not an ISO date (YYYY-MM-DD): ${v}`)
302 }
303 }
304 lists[top]?.push({ line: current.line, fields: Object.fromEntries(spec.keys.map(k => [k, current?.fields[k] ?? ''])) })
305 current = undefined
306 }
307
308 const openKey = (text: string, line: number) => {
309 flush()
310 const [key, value] = keyValue(text, line)
311 pending = { key, raw: [value], line, blanks: 0 }
312 }
313
314 /** Inside an open quoted value, every line is content, a '#' or a blank line included. */
315 const inOpenQuote = (): boolean => {
316 if (!pending) return false
317 const value = pending.raw.join('\n').trim()
318 if (value.startsWith("'")) return !/^'(?:[^']|'')*'/.test(value)
319 if (value.startsWith('"')) return !/^"(?:[^"\\]|\\[\s\S])*"/.test(value)
320 return false
321 }
322
323 lines.forEach((raw, i) => {
324 const line = i + 1
325 const blank = /^\s*(#.*)?$/.test(raw)
326 if (raw.includes('\t') && !inOpenQuote()) throw new ParseError(line, 'tab in indentation')
327 const indent = raw.length - raw.trimStart().length
328
329 // A continuation line: deeper than the open value's key, or anything inside an open quote.
330 if (pending && (inOpenQuote() || (!blank && indent > keyIndent))) {
331 if (raw.trim() === '') {
332 pending.blanks++
333 return
334 }
335 const quoted = /^\s*['"]/.test(pending.raw.join('\n'))
336 if (!quoted && /^[A-Za-z_][\w-]*:(\s|$)/.test(raw.trim())) {
337 throw new ParseError(line, 'key at inconsistent indent (nested values are not supported)')
338 }
339 for (; pending.blanks > 0; pending.blanks--) pending.raw.push('')
340 pending.raw.push(raw)
341 return
342 }
343 if (blank) {
344 if (pending && raw.trim() === '') pending.blanks++
345 return
346 }
347 if (pending) pending.blanks = 0
348 const body = raw.trim()
349 const isItem = body.startsWith('- ') || body === '-'
350
351 if (indent === 0 && !(isItem && top !== undefined && !isEmptyList)) {
352 if (isItem) {
353 if (top === undefined) throw new ParseError(line, `expected ${firstTops} first`)
354 throw new ParseError(line, `content after "${top}: []"`)
355 }
356 const [key, value] = keyValue(body, line)
357 if (top !== undefined && (!spec.tops.includes(key) || seen.has(key))) throw new ParseError(line, `unexpected top-level line: ${body.slice(0, 40)}`)
358 if (!spec.tops.includes(key)) throw new ParseError(line, `unknown top-level key "${key}"`)
359 close()
360 top = key
361 seen.add(key)
362 itemIndent = -1
363 keyIndent = -1
364 const v = plainScalar(value)
365 isEmptyList = v === '[]'
366 if (!isEmptyList && v !== '') throw new ParseError(line, `"${key}" must be a list`)
367 return
368 }
369 if (top === undefined) throw new ParseError(line, `expected ${firstTops} first`)
370 if (isEmptyList) throw new ParseError(line, `content after "${top}: []"`)
371
372 if (isItem) {
373 if (itemIndent === -1) itemIndent = indent
374 if (indent !== itemIndent) throw new ParseError(line, 'list item at inconsistent indent')
375 close()
376 current = { line, fields: {} }
377 const rest = body.slice(1).trimStart()
378 if (rest === '') return
379 if (rest.startsWith('{')) {
380 // One line holds the whole item; the next line starts another item or a top key.
381 for (const [key, value] of flowEntries(rest, line)) {
382 if (!spec.keys.includes(key)) throw new ParseError(line, `unknown key "${key}"`)
383 if (current.fields[key] !== undefined) throw new ParseError(line, `duplicate key "${key}"`)
384 current.fields[key] = value
385 }
386 return
387 }
388 const firstKeyIndent = indent + (body.length - rest.length)
389 if (keyIndent === -1) keyIndent = firstKeyIndent
390 else if (firstKeyIndent !== keyIndent) throw new ParseError(line, 'key at inconsistent indent')
391 openKey(rest, line)
392 return
393 }
394
395 if (!current) throw new ParseError(line, 'expected a list item ("- ")')
396 if (keyIndent === -1) {
397 if (indent <= itemIndent) throw new ParseError(line, 'key at inconsistent indent')
398 keyIndent = indent
399 }
400 if (indent !== keyIndent) throw new ParseError(line, 'key at inconsistent indent (nested values are not supported)')
401 openKey(body, line)
402 })
403
404 if (top === undefined) {
405 // A file holding only comments is an empty tier, not an error.
406 if (lines.every(l => /^\s*(#.*)?$/.test(l))) return lists
407 throw new ParseError(1, `expected ${firstTops}`)
408 }
409 close()
410 return lists
411}
412
413/** A top-level `key: value` of a kit home's memory-kit.conf, unquoted; undefined when absent or empty. */
414export function confValue(conf: string, key: string): string | undefined {
415 for (const raw of conf.split(/\r?\n/)) {
416 if (!raw.startsWith(`${key}:`)) continue
417 const v = plainScalar(raw.slice(key.length + 1)).replace(/^["']|["']$/g, '')
418 return v === '' ? undefined : v
419 }
420 return undefined
421}
422
423/**
424 * An absolute path: POSIX (/...), drive letter (C:\ or C:/) or UNC (\\server\share). The mod
425 * has no Node, so no path.isAbsolute (kit #8).
426 */
427export function isAbsolutePath(path: string): boolean {
428 return /^(\/|[A-Za-z]:[\\/]|\\\\)/.test(path)
429}
430
431/** The directory holding `path`, POSIX or Windows separators: '/' at the root, '.' for a bare name. */
432export function parentDir(path: string): string {
433 const trimmed = path.replace(/[\\/]+$/, '')
434 const cut = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'))
435 if (cut === -1) return '.'
436 return cut === 0 ? trimmed.slice(0, 1) : trimmed.slice(0, cut)
437}
438
439/** Reads `memory_dir:` from a kit home's memory-kit.conf; undefined when absent. */
440export function memoryDirOf(conf: string): string | undefined {
441 return confValue(conf, 'memory_dir')
442}
443
444/**
445 * The main agent's footer name (gh#4): the home's `agent_name:`, else the agentName option,
446 * else the folder's name. The home wins because plugin options are user-wide: a box with
447 * several homes needs each to name itself.
448 */
449export function selfName(conf: string, option: string, cwd: string): string {
450 return confValue(conf, 'agent_name') ?? (option || basename(cwd))
451}
452
453// ---------------------------------------------------------------------------------------------
454// The home's kit version (kit #4) and the upstream release check (kit #7).
455
456/** The version a home's memory-kit/VERSION names: line 1, trimmed; undefined when empty. */
457export function kitVersionOf(text: string): string | undefined {
458 const first = (text.split(/\r?\n/)[0] ?? '').trim()
459 return first === '' ? undefined : first
460}
461
462export type Release = { major: number; minor: number; patch: number; pre?: { kind: 'alpha' | 'beta' | 'rc'; n: number } }
463
464const NUM = '(0|[1-9]\\d*)'
465const RELEASE = new RegExp(`^v?${NUM}\\.${NUM}\\.${NUM}(?:-(alpha|beta|rc)\\.${NUM})?$`)
466
467/** A release tag or version: v<maj>.<min>.<patch>, optional -alpha.N, -beta.N or -rc.N; else undefined. */
468export function parseRelease(tag: string): Release | undefined {
469 const m = RELEASE.exec(tag.trim())
470 if (!m) return undefined
471 const core = { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]) }
472 return m[4] === undefined ? core : { ...core, pre: { kind: m[4] as 'alpha' | 'beta' | 'rc', n: Number(m[5]) } }
473}
474
475const PRE_ORDER = { alpha: 0, beta: 1, rc: 2 } as const
476
477/** Semver precedence: core numbers, then a release above its pre-releases, then alpha < beta < rc, then N. */
478export function compareRelease(a: Release, b: Release): number {
479 const core = a.major - b.major || a.minor - b.minor || a.patch - b.patch
480 if (core !== 0) return core
481 if (a.pre === undefined || b.pre === undefined) return (a.pre === undefined ? 1 : 0) - (b.pre === undefined ? 1 : 0)
482 return PRE_ORDER[a.pre.kind] - PRE_ORDER[b.pre.kind] || a.pre.n - b.pre.n
483}
484
485const versionText = (r: Release) =>
486 `${r.major}.${r.minor}.${r.patch}${r.pre === undefined ? '' : `-${r.pre.kind}.${r.pre.n}`}`
487
488/** The newest release among tag names, as a version without the `v`; undefined when none is a release. */
489export function newestRelease(names: readonly string[]): string | undefined {
490 let best: Release | undefined
491 for (const name of names) {
492 const r = parseRelease(name)
493 if (r !== undefined && (best === undefined || compareRelease(r, best) > 0)) best = r
494 }
495 return best === undefined ? undefined : versionText(best)
496}
497
498/**
499 * What the header adds when upstream is ahead: the pre-release alone (`alpha.6`) when the
500 * core is the same, else the whole version. '' when not newer, or either side is not a release.
501 */
502export function updateNote(local: string, latest: string): string {
503 const mine = parseRelease(local)
504 const theirs = parseRelease(latest)
505 if (mine === undefined || theirs === undefined || compareRelease(theirs, mine) <= 0) return ''
506 const sameCore = mine.major === theirs.major && mine.minor === theirs.minor && mine.patch === theirs.patch
507 return sameCore && theirs.pre !== undefined ? `${theirs.pre.kind}.${theirs.pre.n}` : versionText(theirs)
508}
509
510/** The header's version slot: `memory-kit <version>`, ` · <note> out` when upstream is ahead; '' without a version. */
511export function kitLabel(version: string, note: string): string {
512 if (version === '') return ''
513 return note === '' ? `memory-kit ${version}` : `memory-kit ${version} · ${note} out`
514}
515
516export const DEFAULT_UPSTREAM = 'mitselek/memory-kit'
517const REPO_PART = '[A-Za-z0-9_][A-Za-z0-9_.-]*'
518const OWNER_REPO = new RegExp(`^${REPO_PART}/${REPO_PART}$`)
519
520/**
521 * The tags API URL for memory-kit.conf's `upstream:` (owner/repo on Codeberg; the kit's own
522 * repository when absent). undefined for any other value: no request is made.
523 */
524export function upstreamTagsUrl(upstream: string | undefined): string | undefined {
525 const repo = upstream ?? DEFAULT_UPSTREAM
526 if (!OWNER_REPO.test(repo) || repo.split('/').some(p => /^\.+$/.test(p))) return undefined
527 return `https://codeberg.org/api/v1/repos/${repo}/tags?limit=50`
528}
529
530/** Tag names from a tags API answer (a JSON list of `{ name }`); undefined for anything else. */
531export function tagNamesOf(text: string): string[] | undefined {
532 let data: unknown
533 try {
534 data = JSON.parse(text)
535 } catch {
536 return undefined
537 }
538 if (!Array.isArray(data)) return undefined
539 const names: string[] = []
540 for (const tag of data) {
541 const name = (tag as { name?: unknown } | null)?.name
542 if (typeof name !== 'string') return undefined
543 names.push(name)
544 }
545 return names
546}
547
548/** A tags request not answered by then counts as a failed check: $.http.fetch has no timeout of its own. */
549export const FETCH_TIMEOUT_MS = 10_000
550
551/** At most one request per upstream in this long, across every session ($.store). */
552export const UPDATE_INTERVAL_MS = 6 * 3_600_000
553
554/** One upstream's last check: when, and the newest release then known ('' for none). */
555export type UpstreamCheck = { checkedAt: number; latest: string }
556
557/** A check made within the interval. A clock that went back makes it stale. */
558export function isFresh(checkedAt: number, now: number): boolean {
559 const age = now - checkedAt
560 return age >= 0 && age < UPDATE_INTERVAL_MS
561}
562
563/** The stored check for `url` from the store's `upstream` value (url -> check); undefined when absent or malformed. */
564export function cachedCheck(stored: unknown, url: string): UpstreamCheck | undefined {
565 if (typeof stored !== 'object' || stored === null) return undefined
566 const entry = (stored as Record<string, unknown>)[url] as Partial<UpstreamCheck> | undefined
567 if (typeof entry?.checkedAt !== 'number' || typeof entry.latest !== 'string') return undefined
568 return { checkedAt: entry.checkedAt, latest: entry.latest }
569}
570
571// ---------------------------------------------------------------------------------------------
572// Dates. The plugin environment's local time zone is not trusted: the offset is passed in.
573
574/** `YYYY-MM-DD` of an instant at a UTC offset (minutes east of UTC). */
575export function isoDate(now: number, offsetMinutes: number): string {
576 return new Date(now + offsetMinutes * 60_000).toISOString().slice(0, 10)
577}
578
579/** `YYYY-MM-DD HH:MM` of an instant at a UTC offset. */
580export function isoMinute(now: number, offsetMinutes: number): string {
581 return new Date(now + offsetMinutes * 60_000).toISOString().slice(0, 16).replace('T', ' ')
582}
583
584/** Adds whole days to an ISO date. */
585export function addDays(date: string, days: number): string {
586 const t = Date.parse(`${date}T00:00:00Z`)
587 return new Date(t + days * 86_400_000).toISOString().slice(0, 10)
588}
589
590/** Parses `date +%z` output (`+0300`, `-0530`) into minutes east of UTC. */
591export function offsetFromZ(z: string): number | undefined {
592 const m = /^([+-])(\d{2})(\d{2})$/.exec(z.trim())
593 if (!m) return undefined
594 const minutes = Number(m[2]) * 60 + Number(m[3])
595 return m[1] === '-' ? -minutes : minutes
596}
597
598// ---------------------------------------------------------------------------------------------
599// Ordering and counts.
600
601/** Soonest expiry first (so expired rows lead); ties by `since`, then file order. */
602export function sortByExpires(items: readonly ObligationRow[]): ObligationRow[] {
603 return [...items].sort(
604 (a, b) => a.expires.localeCompare(b.expires) || a.since.localeCompare(b.since) || a.line - b.line,
605 )
606}
607
608export type Status = 'expired' | 'due' | 'later'
609
610/** expired: expires before today. due: today .. today+7 inclusive. */
611export function statusOf(item: ObligationRow, today: string): Status {
612 if (item.expires < today) return 'expired'
613 if (item.expires <= addDays(today, 7)) return 'due'
614 return 'later'
615}
616
617export function countsOf(items: readonly ObligationRow[], today: string): { expired: number; due: number } {
618 let expired = 0
619 let due = 0
620 for (const item of items) {
621 const s = statusOf(item, today)
622 if (s === 'expired') expired++
623 else if (s === 'due') due++
624 }
625 return { expired, due }
626}
627
628export function countsLabel(c: { expired: number; due: number }): string {
629 return `${c.expired} expired · ${c.due} due ≤7d`
630}
631
632// ---------------------------------------------------------------------------------------------
633// Scrolling: an index into the sorted list, stepped one item at a time.
634
635export function clampIndex(index: number, length: number): number {
636 if (length <= 0 || !Number.isFinite(index)) return 0
637 return Math.min(Math.max(0, Math.trunc(index)), length - 1)
638}
639
640export function step(index: number, delta: number, length: number): number {
641 return clampIndex(clampIndex(index, length) + delta, length)
642}
643
644// ---------------------------------------------------------------------------------------------
645// Footer columns.
646
647export const NAME_WIDTH = 10
648export const ACTOR_WIDTH = 20
649
650/** At most `width` code points: longer is width-1 chars + "…". No padding. */
651export function capName(name: string, width: number): string {
652 const chars = Array.from(name.trim())
653 return chars.length > width ? chars.slice(0, width - 1).join('') + '…' : chars.join('')
654}
655
656/** Footer column: exactly 10 code points, capped as capName, shorter right-padded. */
657export function fitName(name: string, width = NAME_WIDTH): string {
658 const capped = capName(name, width)
659 return capped + ' '.repeat(width - Array.from(capped).length)
660}
661
662/** Row actor: capped at 20 so the task text starts on the first line. */
663export function fitActor(actor: string): string {
664 return capName(actor, ACTOR_WIDTH)
665}
666
667/** '·' (drawn dim) when the model is unknown: a question mark reads as an error. */
668export type ModelLetter = 'F' | 'O' | 'S' | 'H' | '·'
669
670export function modelLetter(model: string | undefined): ModelLetter {
671 const m = (model ?? '').toLowerCase()
672 if (m.includes('fable')) return 'F'
673 if (m.includes('opus')) return 'O'
674 if (m.includes('sonnet')) return 'S'
675 if (m.includes('haiku')) return 'H'
676 return '·'
677}
678
679export const MODEL_COLORS: Record<ModelLetter, string> = {
680 F: '#b0006a',
681 O: '#c24e00',
682 S: '#005fb8',
683 H: '#1b7a2e',
684 '·': '#666666',
685}
686
687/** 127k, 1M, 1.5M, 950. */
688export function formatTokens(n: number): string {
689 if (n >= 1_000_000) return `${Number((n / 1_000_000).toFixed(1))}M`
690 if (n >= 1_000) return `${Math.round(n / 1_000)}k`
691 return String(Math.round(n))
692}
693
694export function contextWeight(tokens: number | undefined, window: number | undefined): string {
695 const used = tokens === undefined ? '-' : formatTokens(tokens)
696 return window === undefined || window <= 0 ? used : `${used}/${formatTokens(window)}`
697}
698
699/** Live agents (anything not finished), oldest first as listed. */
700export function liveAgents(agents: readonly PaneAgent[]): PaneAgent[] {
701 return agents.filter(a => a.status !== 'completed' && a.status !== 'failed' && a.status !== 'killed')
702}
703
704// ---------------------------------------------------------------------------------------------
705// Colours. Pane background is a bright pastel; actor colours are saturated darks that read on it.
706
707export const PANE_BG = '#fff3b0'
708export const HEADER_BG = '#1f1b3a'
709export const HEADER_FG = '#fff3b0'
710export const DATE_FG = '#000000'
711export const EXPIRED_DATE_BG = '#ffb4a8'
712export const LINK_FG = '#00008b'
713export const MIHKEL_COLOR = '#d4006f'
714
715/** Saturated, dark enough for the pastel; no plain blue (links are dark blue), no Mihkel pink. */
716export const ACTOR_PALETTE = [
717 '#7b1fa2', // purple
718 '#00796b', // teal
719 '#b34700', // burnt orange
720 '#2e7d32', // green
721 '#5d4037', // brown
722 '#6a1b9a', // violet
723 '#00838f', // cyan-teal
724 '#9e2a2b', // brick
725 '#556b2f', // olive
726 '#8e24aa', // orchid
727] as const
728
729/** FNV-1a, 32-bit. Deterministic across sessions and machines. */
730export function hash(text: string): number {
731 let h = 0x811c9dc5
732 for (const ch of text) {
733 h ^= ch.codePointAt(0) ?? 0
734 h = Math.imul(h, 0x01000193) >>> 0
735 }
736 return h >>> 0
737}
738
739export function actorColor(actor: string): string {
740 const key = actor.trim().toLowerCase()
741 if (key === 'mihkel') return MIHKEL_COLOR
742 return ACTOR_PALETTE[hash(key) % ACTOR_PALETTE.length] ?? ACTOR_PALETTE[0]
743}
744
745// ---------------------------------------------------------------------------------------------
746// urls/<name> links.
747
748const URL_REF = /urls\/([a-z0-9][a-z0-9-]*)/g
749
750/** Every urls/<name> cited in a row's text, check or ref, each once, in order. */
751export function urlNamesOf(item: Pick<ObligationRow, 'obligation' | 'check' | 'ref'>): string[] {
752 return urlNamesIn([item.obligation, item.check, item.ref])
753}
754
755/** Every urls/<name> cited in these texts, each once, in order (a tab's lines, kit #43). */
756export function urlNamesIn(texts: readonly string[]): string[] {
757 const names: string[] = []
758 for (const text of texts) {
759 for (const m of text.matchAll(URL_REF)) {
760 const name = m[1] ?? ''
761 if (!names.includes(name)) names.push(name)
762 }
763 }
764 return names
765}
766
767/** The URL a memory/urls/<name> file holds: line 1, trimmed; undefined when unusable. */
768export function urlOfFile(text: string): string | undefined {
769 const first = (text.split(/\r?\n/)[0] ?? '').trim()
770 if (first === '' || /\s/.test(first) || first.length > 2048) return undefined
771 return first
772}
773
774export type Segment =
775 | { kind: 'text'; text: string }
776 | { kind: 'link'; name: string; href: string }
777 | { kind: 'dead'; name: string }
778
779/** Splits text at each urls/<name>, resolved against `urls` (name -> URL). */
780export function segmentsOf(text: string, urls: Readonly<Record<string, string>>): Segment[] {
781 const out: Segment[] = []
782 let at = 0
783 for (const m of text.matchAll(URL_REF)) {
784 const start = m.index ?? 0
785 if (start > at) out.push({ kind: 'text', text: text.slice(at, start) })
786 const name = m[1] ?? ''
787 const href = urls[name]
788 out.push(href === undefined ? { kind: 'dead', name } : { kind: 'link', name, href })
789 at = start + m[0].length
790 }
791 if (at < text.length) out.push({ kind: 'text', text: text.slice(at) })
792 return out
793}
794
795/** Links cited in check or ref but not in the obligation text: drawn after the text. */
796export function trailingLinksOf(item: ObligationRow, urls: Readonly<Record<string, string>>): Segment[] {
797 const inText = new Set(segmentsOf(item.obligation, {}).flatMap(s => (s.kind === 'text' ? [] : [s.name])))
798 return urlNamesOf(item)
799 .filter(name => !inText.has(name))
800 .map(name => {
801 const href = urls[name]
802 return href === undefined ? { kind: 'dead' as const, name } : { kind: 'link' as const, name, href }
803 })
804}
805
806/** Last path component; used as the default agent name. */
807export function basename(path: string): string {
808 const parts = path.split('/').filter(p => p !== '')
809 return parts[parts.length - 1] ?? path
810}
811
812// ---------------------------------------------------------------------------------------------
813// Subagent context load, from turn.step usage.
814
815/** The token counts one step reported (ModelUsage) and the model that answered. */
816export type StepUsage = {
817 input_tokens: number
818 output_tokens: number
819 cache_read_input_tokens: number
820 cache_creation_input_tokens: number
821 model: string
822}
823
824/**
825 * A loop's context load after a step: the request's input side (uncached, cache read and cache
826 * write), as Claude Code computes the status line's used_percentage. Output is left out (0.6.0).
827 */
828export function contextLoad(u: StepUsage): number {
829 return u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
830}
831
832/**
833 * Records a subagent's latest step (latest wins). The main loop (no agentId) and steps
834 * with no usage leave the map as it was: the main line has its own figures.
835 */
836export function recordStep(
837 loads: Readonly<Record<string, AgentLoad>>,
838 agentId: string | undefined,
839 usage: StepUsage | null,
840): Record<string, AgentLoad> {
841 if (agentId === undefined || usage === null) return { ...loads }
842 return { ...loads, [agentId]: { tokens: contextLoad(usage), model: usage.model } }
843}
844
845/**
846 * A subagent's load as the footer shows it: used/window when it runs on the main loop's
847 * model (whose window the session reports), the used figure alone otherwise, '' when unknown.
848 */
849export function subagentWeight(load: AgentLoad | undefined, mainModel: string, mainWindow: number | null): string {
850 if (load === undefined) return ''
851 const same = mainModel !== '' && load.model.trim().toLowerCase() === mainModel.trim().toLowerCase()
852 return contextWeight(load.tokens, same && mainWindow !== null ? mainWindow : undefined)
853}
854
855/** Columns the footer takes around its lines: paddingX 1 each side, as the body rows. */
856export const FOOTER_CHROME = 2
857
858export const RULE_COLOR = '#b8a24a'
859
860/** The workflow mark (≡) on a footer line, where an agent's model letter stands. */
861export const WORKFLOW_FG = '#1f1b3a'
862
863/**
864 * The figure a footer line can show in `available` columns: `used/window` when the whole line
865 * (name 10, space, letter, space, figure) fits, else `used` alone. Never cut inside the figure.
866 */
867export function fitWeight(weight: string, available: number): string {
868 if (weight === '' || NAME_WIDTH + 3 + Array.from(weight).length <= available) return weight
869 return weight.split('/')[0] ?? weight
870}
871
872/** After a wheel step, further ui.scroll events are ignored this long: one burst, one item. */
873export const WHEEL_THROTTLE_MS = 150
874
875/**
876 * One wheel event: the items to step (-1, 0 or 1, never |by|) and the new last-step time.
877 * An event within WHEEL_THROTTLE_MS after the last step is ignored.
878 */
879export function wheelStep(by: number, now: number, lastStep: number | undefined): { delta: number; lastStep: number | undefined } {
880 const gap = lastStep === undefined ? Infinity : now - lastStep
881 // A clock that went backwards (a reset) starts a fresh burst.
882 if (by === 0 || (gap >= 0 && gap < WHEEL_THROTTLE_MS)) return { delta: 0, lastStep }
883 return { delta: Math.sign(by), lastStep: now }
884}
885
886// ---------------------------------------------------------------------------------------------
887// Workflow runs. A workflow's agents are not in $.agent.list(): agent.spawn tags them with the
888// run id, turn.complete names the one that finished. The phase and the name are read from the
889// files Claude Code keeps for a run (undocumented, so a miss falls back, never fails).
890
891/** Runs kept at most; finished ones are dropped oldest first, live ones never. */
892export const MAX_RUNS = 20
893
894function emptyRun(): WorkflowRun {
895 return { name: '', phase: '', label: '', started: [], done: [] }
896}
897
898/** Drops the oldest finished runs while there are more than MAX_RUNS. Key order is start order. */
899function pruneRuns(runs: Record<string, WorkflowRun>): Record<string, WorkflowRun> {
900 const ids = Object.keys(runs)
901 let excess = ids.length - MAX_RUNS
902 if (excess <= 0) return runs
903 const out: Record<string, WorkflowRun> = {}
904 for (const id of ids) {
905 const run = runs[id]!
906 if (excess > 0 && run.done.length >= run.started.length) {
907 excess--
908 continue
909 }
910 out[id] = run
911 }
912 return out
913}
914
915/** Records a workflow agent's start: counted as started, its label the latest. */
916export function recordWorkflowSpawn(
917 runs: Readonly<Record<string, WorkflowRun>>,
918 runId: string,
919 agentId: string,
920 label: string,
921): Record<string, WorkflowRun> {
922 const run = runs[runId] ?? emptyRun()
923 if (run.started.includes(agentId)) return { ...runs }
924 return pruneRuns({ ...runs, [runId]: { ...run, label, started: [...run.started, agentId] } })
925}
926
927/** Records an agent's finish in the run that started it; any other agent changes nothing. */
928export function recordWorkflowDone(runs: Readonly<Record<string, WorkflowRun>>, agentId: string): Record<string, WorkflowRun> {
929 for (const [id, run] of Object.entries(runs)) {
930 if (run.started.includes(agentId) && !run.done.includes(agentId)) {
931 return { ...runs, [id]: { ...run, done: [...run.done, agentId] } }
932 }
933 }
934 return { ...runs }
935}
936
937/** Runs with an agent still working, in start order. */
938export function liveWorkflows(runs: Readonly<Record<string, WorkflowRun>>): Array<[string, WorkflowRun]> {
939 return Object.entries(runs).filter(([, run]) => run.done.length < run.started.length)
940}
941
942/** The label convention's phase: the part before the first colon ('' without one). */
943export function labelPhase(label: string): string {
944 const at = label.indexOf(':')
945 return at < 0 ? '' : label.slice(0, at).trim()
946}
947
948/** The phase of the last `started` entry in a run's journal.jsonl that names one; '' if none. */
949export function journalPhase(text: string): string {
950 let phase = ''
951 for (const line of text.split('\n')) {
952 if (!line.includes('"started"')) continue
953 try {
954 const entry = JSON.parse(line) as { type?: unknown; phase?: unknown }
955 if (entry.type === 'started' && typeof entry.phase === 'string' && entry.phase !== '') phase = entry.phase
956 } catch {
957 // A torn or foreign line: skip it.
958 }
959 }
960 return phase
961}
962
963/** The run's name from its saved script `<name>-<runId>.js`; '' when no file matches. */
964export function workflowNameOf(fileNames: readonly string[], runId: string): string {
965 const suffix = `-${runId}.js`
966 const file = fileNames.find(f => f.endsWith(suffix) && f.length > suffix.length)
967 return file === undefined ? '' : file.slice(0, -suffix.length)
968}
969
970/** Claude Code's folder name for a project: every character but a letter or digit becomes '-'. */
971export function projectSlug(cwd: string): string {
972 return cwd.replace(/[^A-Za-z0-9]/g, '-')
973}
974
975/** What a workflow line shows after the name: the phase (when known), then done/started. */
976export function workflowTail(phase: string, done: number, started: number): string {
977 return [phase, `${done}/${started}`].filter(p => p !== '').join(' ')
978}
979hooks/tiers.ts 371 lines1// The memory pane's tabs (kit #43): one read-only view per memory tier. Pure: no `$`, no I/O; the
2// caller reads the files and hands in their text. Shapes: memory-kit/types/memory-*.ts. Every
3// file goes through parseMapLists, the obligations parser's own, so a tier the parser rejects
4// shows its error in its own tab and the others keep working.
5
6import type { LessonFilter, TabId, TierView, ViewChoice, ViewLine } from '../types'
7import { addDays, parseMapLists } from './obligations'
8import type { ListSpec, MapRow } from './obligations'
9
10/** The tab row, in Mihkel's order (19.10.2026): from "act now" to "rarely visited". */
11export const TABS: readonly { id: TabId; name: string }[] = [
12 { id: 'O', name: 'Obligations' },
13 { id: 'N', name: 'Next' },
14 { id: 'C', name: 'Commitments' },
15 { id: 'R', name: 'Rules' },
16 { id: 'L', name: 'Lessons' },
17 { id: 'F', name: 'Facts' },
18 { id: 'K', name: 'Keys' },
19 { id: 'S', name: 'Secrets' },
20]
21
22export const LESSON_FILTERS: readonly LessonFilter[] = ['all', 'hooked', 'linted', 'recognition']
23
24export const DEFAULT_CHOICE: ViewChoice = { tab: 'O', lessons: 'all' }
25
26/** A stored choice, validated: anything unknown falls back to the default, field by field. */
27export function choiceOf(stored: unknown): ViewChoice {
28 const raw = (typeof stored === 'object' && stored !== null ? stored : {}) as { tab?: unknown; lessons?: unknown }
29 const tab = TABS.find(t => t.id === raw.tab)?.id ?? DEFAULT_CHOICE.tab
30 const lessons = LESSON_FILTERS.find(f => f === raw.lessons) ?? DEFAULT_CHOICE.lessons
31 return { tab, lessons }
32}
33
34/** The $.store key of a home's choice: one per resolved home path. */
35export const choiceKey = (home: string) => `view:${home}`
36
37// Caps the header counts against (memory-kit/types/caps.ts; a plugin loads only its own folder).
38export const CURRENT_CAP = 15
39export const RULES_CAP = 20
40/** A fact whose `verified` is older than this, or blank, is drawn dim: a quarter, as the weekly sweep ages them. */
41export const FACT_STALE_DAYS = 91
42
43const line = (key: string, text: string, more: Partial<Omit<ViewLine, 'key' | 'text'>> = {}): ViewLine => ({
44 key,
45 tag: '',
46 text,
47 note: '',
48 dim: false,
49 heading: false,
50 flag: '',
51 href: '',
52 ...more,
53})
54
55const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
56
57/** Parses one tier file, or the view that says why it cannot be shown. */
58function parsed(text: string, file: string, spec: ListSpec): Record<string, MapRow[]> | TierView {
59 const result = parseMapLists(text, spec)
60 return result.kind === 'ok' ? result.lists : { kind: 'error', message: `${file} unreadable: line ${result.line}: ${result.message}` }
61}
62
63const isView = (x: Record<string, MapRow[]> | TierView): x is TierView => 'kind' in x && typeof x.kind === 'string'
64
65// ---------------------------------------------------------------------------------------------
66// N: the scratchpad tier (memory/<name>.yaml), shown as "Next": S is Secrets.
67//
68// Found as the lint finds it (kit #53). The rule's twin is lint_tree and scratchpad_shaped in
69// lint/memory_lint.py; the two cannot share code, so a change to one is a change to both. Every
70// top-level *.yaml of the memory directory is a scratchpad unless it is rules, obligations or
71// keys, and commitments.yaml is one only when it holds current or staging and no commitments key
72// (kit #30). The lint reads every such file, so the tab shows every one, in the lint's order.
73
74const SCRATCHPAD: ListSpec = { tops: ['current', 'staging'], keys: ['label', 'record', 'ref'], required: ['record'], dates: [] }
75
76/** The other tiers' files at the top of the memory directory, by stem, as lint_tree names them. */
77const NOT_SCRATCHPAD = ['rules', 'obligations', 'keys']
78
79export const NO_SCRATCHPAD = 'no scratchpad tier in this home'
80
81/**
82 * The memory directory's file names that may be scratchpads, in the lint's order (Python sorts
83 * paths by code point, as a plain sort does). commitments.yaml is among them: its shape decides.
84 */
85export function scratchpadCandidates(names: readonly string[]): string[] {
86 return names.filter(n => n.endsWith('.yaml') && !NOT_SCRATCHPAD.includes(n.slice(0, -'.yaml'.length))).sort()
87}
88
89/**
90 * Whether a commitments.yaml is a scratchpad a home named so before the tier existed (kit #30):
91 * current or staging among its top-level keys, and no commitments key. The lint asks PyYAML; the
92 * pane has no YAML library, so it reads the keys at column 0, as its own parser does.
93 */
94export function scratchpadShaped(text: string): boolean {
95 const keys = text
96 .replace(/^\uFEFF/, '')
97 .split(/\r?\n/)
98 .map(l => /^([A-Za-z_][\w-]*)\s*:(\s|$)/.exec(l)?.[1])
99 return !keys.includes('commitments') && (keys.includes('current') || keys.includes('staging'))
100}
101
102/**
103 * `files`: each scratchpad's name and text, as scratchpadCandidates and scratchpadShaped chose
104 * them. One file is the tab as it was, under its name; several are grouped by file, as facts are
105 * by subject, and a broken one is flagged in its place while the others show.
106 */
107export function nextView(files: readonly { name: string; text: string }[]): TierView {
108 if (files.length === 0) return { kind: 'missing', message: NO_SCRATCHPAD }
109 const sorted = [...files].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
110 const lines: ViewLine[] = []
111 let current = 0
112 let staging = 0
113 let errors = 0
114 for (const file of sorted) {
115 const lists = parsed(file.text, file.name, SCRATCHPAD)
116 if (isView(lists)) {
117 if (files.length === 1) return lists
118 lines.push(line(`h-${file.name}`, file.name, { heading: true, flag: lists.kind === 'error' ? lists.message : '' }))
119 errors++
120 continue
121 }
122 const cur = lists.current ?? []
123 const stg = lists.staging ?? []
124 current += cur.length
125 staging += stg.length
126 const rows = (rows: MapRow[], section: string) =>
127 rows.map(r => line(`${file.name}-${section}-${r.line}`, r.fields.record ?? '', { tag: r.fields.label ?? '', note: r.fields.ref ?? '' }))
128 lines.push(
129 line(`h-${file.name}`, file.name, { heading: true }),
130 line(`h-${file.name}-current`, `current (${cur.length})`, { heading: true }),
131 ...rows(cur, 'current'),
132 line(`h-${file.name}-staging`, `staging (${stg.length})`, { heading: true }),
133 ...rows(stg, 'staging'),
134 )
135 }
136 // The cap is per file: a sum over several files has none to count against.
137 const parts = files.length === 1 ? [`${current}/${CURRENT_CAP} current`] : [`${files.length} scratchpads`, `${current} current`]
138 parts.push(`${staging} staging`)
139 if (errors > 0) parts.push(`${plural(errors, 'file')} unreadable`)
140 return { kind: 'ok', count: parts.join(' · '), banner: '', lines }
141}
142
143// ---------------------------------------------------------------------------------------------
144// C: commitments (memory/commitments.yaml), optional: a home opts in with the file (kit #30).
145
146const COMMITMENTS: ListSpec = {
147 tops: ['commitments'],
148 keys: ['trigger', 'obligation', 'actor', 'owed_to', 'within', 'ref'],
149 required: ['trigger', 'obligation'],
150 dates: [],
151}
152
153export const COMMITMENTS_UNUSED = 'commitments tier not in use here'
154
155export function commitmentsView(text: string | undefined): TierView {
156 if (text === undefined) return { kind: 'missing', message: COMMITMENTS_UNUSED }
157 // kit #30, #53: the lint reads such a file as a scratchpad, and so does the Next tab.
158 if (scratchpadShaped(text)) return { kind: 'missing', message: `${COMMITMENTS_UNUSED} (commitments.yaml holds a scratchpad: see Next)` }
159 const lists = parsed(text, 'commitments.yaml', COMMITMENTS)
160 if (isView(lists)) return lists
161 const rows = lists.commitments ?? []
162 return {
163 kind: 'ok',
164 count: plural(rows.length, 'commitment'),
165 banner: '',
166 lines: rows.map(({ fields: f, line: at }) => {
167 const parties = [f.actor, f.owed_to].filter(p => p !== '').join(' -> ')
168 const within = f.within === '' ? '' : `within ${f.within}`
169 return line(`c-${at}`, `${f.trigger} -> ${f.obligation}`, { note: [parties, within].filter(p => p !== '').join(', ') })
170 }),
171 }
172}
173
174// ---------------------------------------------------------------------------------------------
175// R: rules (memory/rules.yaml), numbered, counted against the cap.
176
177const RULES: ListSpec = { tops: ['rules'], keys: ['rule', 'ref'], required: ['rule'], dates: [] }
178
179export function rulesView(text: string): TierView {
180 const lists = parsed(text, 'rules.yaml', RULES)
181 if (isView(lists)) return lists
182 const rows = lists.rules ?? []
183 return {
184 kind: 'ok',
185 count: `${rows.length}/${RULES_CAP}`,
186 banner: '',
187 lines: rows.map((r, i) => line(`r-${r.line}`, r.fields.rule ?? '', { tag: `${i + 1}.` })),
188 }
189}
190
191// ---------------------------------------------------------------------------------------------
192// L: lessons, from the generated index (memory/lessons/index.yaml), newest first, filterable.
193
194const LESSONS: ListSpec = {
195 tops: ['lessons'],
196 keys: ['slug', 'summary', 'learned', 'ref', 'enforcement', 'trigger'],
197 required: ['slug', 'summary'],
198 dates: ['learned'],
199}
200
201/** A file:// URL for a local path, POSIX or Windows (C:/ gets the third slash). */
202export function fileUrl(path: string): string {
203 const p = path.replaceAll('\\', '/')
204 const abs = p.startsWith('/') ? p : `/${p}`
205 return `file://${abs.split('/').map(encodeURIComponent).join('/').replace(/^\/([A-Za-z])%3A/, '/$1:')}`
206}
207
208export function lessonsView(text: string, filter: LessonFilter, lessonsDir: string): TierView {
209 const lists = parsed(text, 'lessons/index.yaml', LESSONS)
210 if (isView(lists)) return lists
211 const all = [...(lists.lessons ?? [])].sort((a, b) => (b.fields.learned ?? '').localeCompare(a.fields.learned ?? '') || a.line - b.line)
212 const shown = filter === 'all' ? all : all.filter(r => r.fields.enforcement === filter)
213 return {
214 kind: 'ok',
215 count: filter === 'all' ? plural(all.length, 'lesson') : `${shown.length}/${all.length} ${filter}`,
216 banner: '',
217 lines: shown.map(({ fields: f, line: at }) =>
218 line(`l-${at}`, f.summary ?? '', { tag: f.enforcement ?? '', note: f.learned ?? '', href: fileUrl(`${lessonsDir}/${f.slug}.md`) }),
219 ),
220 }
221}
222
223// ---------------------------------------------------------------------------------------------
224// F: facts (memory/facts/<subject>.yaml), grouped by subject, stale ones dim.
225
226const FACTS: ListSpec = { tops: ['facts'], keys: ['fact', 'ref', 'refute', 'verified'], required: ['fact'], dates: ['verified'] }
227
228/** Whether a fact's `verified` is blank or older than FACT_STALE_DAYS before today. */
229export function isStale(verified: string, today: string): boolean {
230 return verified === '' || verified < addDays(today, -FACT_STALE_DAYS)
231}
232
233/** `files`: each facts file's name (`<subject>.yaml`) and text, in any order. */
234export function factsView(files: readonly { name: string; text: string }[], today: string): TierView {
235 const lines: ViewLine[] = []
236 let facts = 0
237 let stale = 0
238 const errors: string[] = []
239 for (const file of [...files].sort((a, b) => a.name.localeCompare(b.name))) {
240 const subject = file.name.replace(/\.ya?ml$/, '')
241 const lists = parsed(file.text, `facts/${file.name}`, FACTS)
242 if (isView(lists)) {
243 // One broken subject is said in its place; the other subjects still show.
244 lines.push(line(`h-${subject}`, subject, { heading: true, flag: lists.kind === 'error' ? lists.message : '' }))
245 errors.push(subject)
246 continue
247 }
248 const rows = lists.facts ?? []
249 lines.push(line(`h-${subject}`, `${subject} (${rows.length})`, { heading: true }))
250 for (const { fields: f, line: at } of rows) {
251 const old = isStale(f.verified ?? '', today)
252 facts++
253 if (old) stale++
254 lines.push(line(`f-${subject}-${at}`, f.fact ?? '', { tag: f.verified === '' ? 'never' : (f.verified ?? ''), dim: old }))
255 }
256 }
257 const parts = [plural(facts, 'fact'), plural(files.length - errors.length, 'subject')]
258 if (stale > 0) parts.push(`${stale} not verified in ${FACT_STALE_DAYS} days`)
259 if (errors.length > 0) parts.push(`${plural(errors.length, 'file')} unreadable`)
260 return { kind: 'ok', count: parts.join(' · '), banner: '', lines }
261}
262
263// ---------------------------------------------------------------------------------------------
264// K: keys (memory/keys.yaml): who can get in, and how it is shut off.
265
266const KEYS: ListSpec = {
267 tops: ['keys'],
268 keys: ['subject', 'holder', 'scope', 'granted', 'revoke', 'ref'],
269 required: ['subject'],
270 dates: ['granted'],
271}
272
273export function keysView(text: string): TierView {
274 const lists = parsed(text, 'keys.yaml', KEYS)
275 if (isView(lists)) return lists
276 const rows = lists.keys ?? []
277 let findings = 0
278 const lines = rows.map(({ fields: f, line: at }) => {
279 const blank = (f.revoke ?? '').trim() === ''
280 if (blank) findings++
281 const flag = blank ? 'no revoke step (a finding)' : (f.revoke ?? '').includes('[?]') ? 'revoke step unconfirmed [?]' : ''
282 return line(`k-${at}`, [f.holder, f.scope].filter(p => p !== '').join(' · '), {
283 tag: f.subject ?? '',
284 note: blank ? '' : `revoke: ${f.revoke}`,
285 flag,
286 })
287 })
288 const parts = [plural(rows.length, 'grant')]
289 if (findings > 0) parts.push(plural(findings, 'finding'))
290 return { kind: 'ok', count: parts.join(' · '), banner: '', lines }
291}
292
293// ---------------------------------------------------------------------------------------------
294// S: secrets (memory/secrets/): the README's three labelled lines and the encrypted files' names.
295// Never a value: the pane reads the README and a directory listing, never an encrypted file.
296
297/** What the skeleton's README says (memory-kit/skeleton/memory/secrets/README.md), unfilled = undefined. */
298export type SecretsReadme = {
299 publicKey?: string
300 masterKey?: string
301 deposited?: string
302 where?: string
303 verified?: string
304}
305
306/** A value still as the skeleton ships it (`_fill in_`, `_date or NOT YET_`), or absent. */
307const filled = (v: string | undefined) => (v === undefined || v === '' || /^_.*_$/.test(v) ? undefined : v)
308
309/** The three labelled lines; a label the README lacks or leaves as shipped is undefined. */
310export function secretsReadmeOf(text: string): SecretsReadme {
311 const out: SecretsReadme = {}
312 for (const raw of text.split(/\r?\n/)) {
313 const l = raw.trim()
314 let m = /^- \*\*Public key[^*]*:\*\*\s*(.*)$/.exec(l)
315 if (m) out.publicKey = filled(m[1]?.trim())
316 m = /^- \*\*Master key location[^*]*:\*\*\s*(.*)$/.exec(l)
317 if (m) out.masterKey = filled(m[1]?.trim())
318 m = /^- \*\*Spare deposited:\*\*\s*(.*?)\s*[—–-]+\s*\*\*where:\*\*\s*(.*?)\s*[—–-]+\s*\*\*verified:\*\*\s*(.*)$/.exec(l)
319 if (m) {
320 out.deposited = filled(m[1]?.trim())
321 out.where = filled(m[2]?.trim())
322 out.verified = filled(m[3]?.trim())
323 }
324 }
325 return out
326}
327
328const notYet = (v: string | undefined) => v === undefined || /not yet/i.test(v)
329
330/**
331 * `readme`: the README's text, undefined when there is none. `files`: the secrets folder's
332 * entries other than the README, by name and modification date; never their contents.
333 */
334export function secretsView(readme: string | undefined, files: readonly { name: string; modified: string }[]): TierView {
335 const off: string[] = []
336 if (readme === undefined) off.push('no secrets/README.md')
337 const r = readme === undefined ? {} : secretsReadmeOf(readme)
338 if (readme !== undefined) {
339 if (r.publicKey === undefined) off.push('public key not filled in')
340 if (r.masterKey === undefined) off.push('master key location not filled in')
341 }
342 if (files.length === 0) off.push('no encrypted file beside the README')
343 const lines: ViewLine[] = []
344 if (readme !== undefined) {
345 lines.push(line('s-pub', r.publicKey ?? '(not filled in)', { tag: 'public key' }))
346 lines.push(line('s-master', r.masterKey ?? '(not filled in)', { tag: 'master key at' }))
347 const spareFlags = [notYet(r.deposited) ? 'spare NOT YET deposited' : '', notYet(r.verified) ? 'spare NOT YET verified' : '']
348 lines.push(
349 line('s-spare', `deposited ${r.deposited ?? 'NOT YET'}, where ${r.where ?? '(not said)'}, verified ${r.verified ?? 'NOT YET'}`, {
350 tag: 'spare',
351 flag: spareFlags.filter(f => f !== '').join(', '),
352 }),
353 )
354 }
355 lines.push(line('h-files', `encrypted files (${files.length})`, { heading: true }))
356 for (const f of [...files].sort((a, b) => a.name.localeCompare(b.name))) lines.push(line(`s-${f.name}`, f.name, { note: f.modified }))
357 return {
358 kind: 'ok',
359 count: off.length > 0 ? 'not kit-compliant' : plural(files.length, 'encrypted file'),
360 banner: off.length > 0 ? `secrets tier not kit-compliant: ${off.join('; ')}` : '',
361 lines,
362 }
363}
364
365/** Secrets folder entries that count as encrypted files: not the README, not a dotfile, not a folder. */
366export function secretFiles(entries: readonly { name: string; kind: string; mtimeMs: number }[], dateOf: (ms: number) => string) {
367 return entries
368 .filter(e => e.kind === 'file' && e.name !== 'README.md' && !e.name.startsWith('.'))
369 .map(e => ({ name: e.name, modified: dateOf(e.mtimeMs) }))
370}
371types/index.d.ts 134 lines1// The memory pane's $.state contract (the obligations pane until kit #43). Self-contained: no imports.
2
3/** One obligation as parsed from memory/obligations.yaml, plus the line its item starts on. */
4export type ObligationRow = {
5 obligation: string
6 actor: string
7 /** Who is waiting (kit #29); '' on a row without one. */
8 owed_to: string
9 since: string
10 check: string
11 expires: string
12 ref: string
13 /** 1-based line of the item's "- " in the file: file order for ties, and the row key. */
14 line: number
15}
16
17/** The memory pane's tabs (kit #43): Obligations, Next (the scratchpad), Commitments, Rules,
18 * Lessons, Facts, Keys, Secrets. */
19export type TabId = 'O' | 'N' | 'C' | 'R' | 'L' | 'F' | 'K' | 'S'
20
21export type LessonFilter = 'all' | 'hooked' | 'linted' | 'recognition'
22
23/** What the pane remembers per home ($.store): the open tab and the lessons filter. */
24export type ViewChoice = { tab: TabId; lessons: LessonFilter }
25
26/** One line of a tab's body (every tab but Obligations, which keeps its own rows). */
27export type ViewLine = {
28 key: string
29 /** Drawn first, bold (a label, a number, a date, a subject); '' for none. */
30 tag: string
31 /** The line's text; every urls/<name> in it is a link. */
32 text: string
33 /** Drawn dim after the text (who, when, how to revoke); '' for none. */
34 note: string
35 /** The whole line drawn dim (a stale fact). */
36 dim: boolean
37 /** A group heading (a scratchpad section, a facts subject). */
38 heading: boolean
39 /** Drawn in red after the note: what is off with this line; '' for nothing. */
40 flag: string
41 /** The line links here (a lesson's file); '' for no link. */
42 href: string
43}
44
45/** A tab's body: its lines and the header's count, or one message in place of them. */
46export type TierView =
47 | { kind: 'ok'; count: string; lines: ViewLine[]; banner: string }
48 | { kind: 'missing'; message: string }
49 | { kind: 'error'; message: string }
50
51/** One live subagent or teammate as the footer lists it. */
52export type PaneAgent = {
53 id: string
54 name: string
55 /** Model id or alias as the spawn resolved it; '' when unknown. */
56 model: string
57 status: string
58}
59
60/** A subagent's context load from its latest model step, and the model that answered it. */
61export type AgentLoad = { tokens: number; model: string }
62
63/** Everything the pane draws, gathered by one refresh. Rendering does no I/O. */
64export type PaneSnapshot = {
65 /** Absolute path of the obligations file this snapshot read (or looked for). */
66 path: string
67 /** 'pointer': the start folder's memory-kit.conf names no usable home: its kit_home pointer is broken
68 * (kit #18), or it or the conf it names gives a key twice (kit #55). `error` says why, `path` is that conf. */
69 source: 'ok' | 'missing' | 'error' | 'pointer'
70 /** For source 'error': what went wrong, with the line when known. */
71 error: string
72 items: ObligationRow[]
73 /** urls/<name> -> URL, for every name the items cite that resolved. */
74 urls: Record<string, string>
75 /** kit #42: the note when the home came from a memory-kit.conf above the start folder; '' otherwise. */
76 foundAbove: string
77 /** The resolved home: the key the open tab is remembered by (kit #43). */
78 home: string
79 /** The tab this snapshot's `tier` was read for. */
80 tab: TabId
81 /** The open tab's view; null on the Obligations tab, which reads `items`. */
82 tier: TierView | null
83 /** Milliseconds since the epoch when the snapshot was taken. */
84 now: number
85 /** Local UTC offset in minutes east, for "today". */
86 offsetMinutes: number
87 /** The home's memory-kit/VERSION, line 1; '' when there is none (kit #4). */
88 kitVersion: string
89 /** The tags URL the release check asks; '' when none is made: checkUpdates off, no VERSION, or an unusable upstream (kit #7). */
90 upstreamUrl: string
91 /** The newest upstream release known for upstreamUrl, without the `v`; '' when none. */
92 latest: string
93 self: { name: string; model: string; tokens: number | null; window: number | null }
94 agents: PaneAgent[]
95}
96
97/** One workflow run as the footer tracks it, keyed by its run id (`wf_…`). */
98export type WorkflowRun = {
99 /** From the run's saved script `<name>-<runId>.js`; '' until found (the footer shows the run id). */
100 name: string
101 /** The phase the run's journal names for its latest started agent; '' when unread. */
102 phase: string
103 /** The label (agent description) of the run's latest started agent: the phase fallback. */
104 label: string
105 /** agentIds started, in order. */
106 started: string[]
107 /** agentIds finished (turn.complete), in order. */
108 done: string[]
109}
110
111declare module 'claude-code' {
112 interface PluginState {
113 'obligations-pane': {
114 snapshot: PaneSnapshot | null
115 /** Index of the first obligation shown (scroll position). */
116 index: number
117 /** agentId -> model, captured at agent.spawn (agent.list carries no model). */
118 models: Record<string, string>
119 /** agentId -> load of its latest turn.step (subagents only). */
120 loads: Record<string, AgentLoad>
121 /** The model id the main loop's latest step reported ('' before one). */
122 mainModel: string
123 /** The session's working directory at its first session.start: the home the pane reads. */
124 startCwd: string
125 /** runId -> run, from agent.spawn's `workflow` tag and turn.complete (workflow agents are not in agent.list). */
126 workflows: Record<string, WorkflowRun>
127 /** The open tab and the lessons filter (kit #43), loaded from $.store for `choiceHome`. */
128 choice: ViewChoice
129 /** The home whose stored choice `choice` holds; '' before the first refresh. */
130 choiceHome: string
131 }
132 }
133}
134