Build Claude Code mods spec-first (interview → SPEC → approve → build → verify), and watch them come together in Mod Lab: a pane, band, status line and toasts…

Build Claude Code mods spec-first, change them the same way, and watch each one come together live.
The plugin has three parts:
| Part | Command | What it does |
|---|---|---|
| build (skill) | /mod-builder:build <idea> | Turns an idea into a working mod in five steps around one approval: interview for gaps, a SPEC.md you approve, a scaffold from one of five tested archetypes with logic first, verify (claude plugin validate, claude plugin test, tsc, a headless smoke test), then ship with a "What it reaches" README and a marketplace entry. |
| edit (skill) | /mod-builder:edit <mod> <change> | Changes an existing mod the same way: appends a dated change to its SPEC for one approval, bumps the version by semver, changes logic first, re-verifies and re-ships. It never re-scaffolds. |
| Mod Lab (mod) | /modlab | Tracks every mod in your mods folder through eight stages, live, on every surface a mod can draw on. |
Both skills build on Claude Code's built-in plugin-authoring skill for the API. They add house conventions, a UI-state checklist, 14 patterns and a list of 65 engine gotchas, each tagged by how it was verified.
M O D L A B ● B U I L D I N G
3 mods · 2 green · 1 building modsDir …/mod-builder/mods
MODS 1 2 3 4 5 6 7 8
▸ agent-dock ● ● ● ● ◐ ○ ○ ○ running tests · 7 of 12 0:07
inbox-zero ● ● ● ● ● ● ● ● 12 tests · clean 2:14
tab-namer ● ● ● ● ◌ ◌ ● ● files changed · re-run Validate 1:38
────────────────────────────────────────────────────────────────────────
agent-dock v0.1.0 · mods/agent-dock/
Docks every sub-agent's output beside the transcript.
1 Spec ━ 2 Scaffold ━ 3 Logic ━ 4 Register ━ 5 Validate ━ 6 Test ┅ 7 README ┄ 8 Share
ctrl+x tab (again: next tab), then V validate · T test · K types · O readme · J/P move · N new · D demo · esc to leave
[ Validate ] [ Test ] [ Type-check ] [ README ]
[ Next ] [ Prev ] [ New mod ] [ Demo ]
Reading the pane
MODS over the names and a stage number over each light. The number over the selected mod's failed (red), running (coral) or stale (gold) stage lights up. The track below repeats the numbers beside each stage name, so 5 is Validate.| Light | Meaning |
|---|---|
● | passed |
◐ | running |
✕ | failed |
○ | not done yet |
◌ | stale: it passed, but the code changed afterwards, or an edit started |
running tests · 7 of 12), and the time column shows the run's elapsed time.What Mod Lab uses
| Surface | What Mod Lab puts there |
|---|---|
| Pane beside the transcript | Stage lights per mod, judged from disk and exit codes; a detail panel with version, description, the numbered track, HOOKS, REACHES and gating hooks; an error box with [F] Fix with Claude; a "ready to share" box |
| Band above the prompt | Each running stage, with a 15-cell bar that fills on real progress: streamed test counts against the last run's total, otherwise stages passed of 8 |
| Status line | ◆ 3 mods · 1 building |
| Toasts and a native notification | When validate or test finishes, and when a mod is ready to share |
| Hotkey buttons | V T K O J P N D, and F on a failure; <kbd>ctrl</kbd>+<kbd>x</kbd> <kbd>tab</kbd> gives the pane the keyboard (a dim line says so) |
| Pre-filled prompts | [N] for a new mod; [F] for a fix request quoting the first failure |
| A model-callable tool | lab_report: the skills report each stage as they work, so the pane lights up live. The disk and exit codes always decide pass or fail. |
Stages, and what an edit asks for
| # | Stage | Passes when | During an edit, re-passes when |
|---|---|---|---|
| 1 | Spec | SPEC.md has no <placeholder> left | SPEC.md is saved again |
| 2 | Scaffold | plugin.json and hooks/hooks.json exist | stays green |
| 3 | Logic | a logic module and a *.test.ts exist | a logic or test file changes |
| 4 | Register | hooks/register.tsx exists | stays green |
| 5 | Validate | the last validate passed, with no code changed since | it runs again |
| 6 | Test | the last test run passed, with no code changed since | it runs again |
| 7 | README | it has "What it reaches" and no template comments | it's saved again |
| 8 | Share | the marketplace lists the mod | the marketplace lists the new version |
An edit starts a build generation with its first report. Every stage that passed before turns ◌, except Scaffold and Register, which stay green, and turns green again as the change redoes it. The generation ends, and "ready to share" fires again, when all eight are green.
Checks re-run themselves. At the end of each of Claude's turns (not a subagent's), Mod Lab rescans every mod. Edits from any tool count, Bash included. With autoRerun on (the default), it then re-runs what went stale: a stale Validate runs again, followed by Test if Validate passes and Test has run before; a stale Test alone runs again if Validate passed. Nothing runs mid-turn or on a timer.
The pane follows Claude's edits mid-turn. After each batch of Claude's tools, Mod Lab reads again the mods an Edit, Write or NotebookEdit changed in the folder it watches (a worktree a build reported included). After any other tool that isn't read-only (Bash, PowerShell, a subagent, an MCP tool), whose paths it can't read, it lists each folder's top, hooks/, tests/ and .claude-plugin/, and the marketplace beside them, and reads only the folders whose SPEC.md, README.md, .mcp.json, manifest or files there changed (every mod, when the marketplace did). A batch of only Read, Grep, Glob, WebFetch, WebSearch, TodoWrite, AskUserQuestion or lab_report calls looks at nothing. Such a change deeper down, or in types/, agents/, commands/ or skills/, shows at the next report, command or turn end. This only redraws the pane: no check runs from it. Where an organization manages Claude Code, plugins you install don't get this event, and the pane refreshes as before.
/modlab demo
A pretend mod, aurora, walks through every stage in 12 seconds. One test fails and Claude fixes it. Press D again to stop it. Nothing is written to disk.
Then start a real one, and change it later:
/mod-builder:build a band above the prompt showing the current git branch
/mod-builder:edit git-branch also show how many commits are unpushed
/modlab command | What it does |
|---|---|
/modlab | Open the pane; again to fold it to the status line. If the pane is open as a tab behind another, it comes to the front with the keyboard instead of folding |
/modlab demo | Play the demo |
/modlab <mod> | Open the pane on that mod (a pane behind another tab comes to the front) |
/modlab new <idea> | Put /mod-builder:build <idea> in the prompt box |
Typing /mod-builder:build or /mod-builder:edit opens Mod Lab too. A command you type opens the pane at any width. When Mod Lab opens it on its own (autoOpen, or when Claude starts a build you asked for in plain words), the window must be at least 144 columns wide, or 110 once you've opened Mod Lab yourself. Narrower than that, watch the status line.
Reaching the pane when other panes are open: ctrl+x tab shows the first tab and gives it the keyboard, each press after moves one tab right, and after the last tab the keyboard goes back to the prompt. Esc hands it back from any tab. A letter that is one of the pane's keys acts at once. To cycle without going through the first tab, bind pane:next and pane:previous (no default key) in ~/.claude/keybindings.json; it works while a pane holds the keyboard:
{"bindings":[{"context":"Pane","bindings":{"ctrl+x n":"pane:next","ctrl+x p":"pane:previous"}}]}
From GitHub:
/plugin install mod-builder --marketplace bankielewicz/mod-builder
Or from a local clone of https://github.com/bankielewicz/mod-builder, which is a folder marketplace:
claude plugin marketplace add ./mod-builder
/plugin install mod-builder@claudemod
Edits to the folder load with /reload-plugins. While developing: claude --plugin-dir plugins/mod-builder.
Each way of loading the plugin (--plugin-dir, or an installed copy) keeps its own store, and within it each mods folder keeps its own results. If you switch either one (another way of loading, or a /cd into another worktree), Validate and Test show ○ until you press V and T once. Results don't build up (0.2.30): at session start, Mod Lab deletes those of a mods folder that's gone, such as a removed worktree, and each scan drops a mod that's no longer in its folder. A folder it can't check, such as one it has no permission to read, keeps its results, and so does a folder that lists no mods at all. A drive that isn't mounted reads as gone.
| Option | Default | What it does |
|---|---|---|
modsDir | empty: the mods/ of the marketplace nearest the session's project root (where it started, or where /cd took it), else the one next to this plugin | The folder whose child folders Mod Lab tracks. Set, it always wins. Empty, a build that reports its folder (the build and edit skills do) is watched for the rest of the session, until a /cd moves the project root or the folder's marketplace is gone; only a marketplace's mods/ in the project's own git repository (its top folder or one of its worktrees, read from .git on disk) is taken, since Validate and Test run there; a nested clone or a copy, such as community mods kept in an ignored folder, is not. Before any report, it is the mods/ of the marketplace nearest the project root (then nearest the working directory), so a session in a git worktree watches that worktree's mods/; a /cd takes effect at the next scan, and Claude's own cd in Bash doesn't move it. In another repository with a .claude-plugin/marketplace.json, that is its mods/, and the pane says No mods yet. if it keeps its plugins elsewhere. Set it to pin one folder. |
autoOpen | false | Open Mod Lab when a skill reports a running stage, if the window is at least 144 columns wide (110 once you've opened Mod Lab yourself). Typing /mod-builder:build or /mod-builder:edit opens it whatever this is set to. |
autoRerun | true | At the end of each of Claude's turns, re-run stale checks: a stale Validate, then Test if Validate passes and Test has run before; a stale Test alone, if Validate passed |
testTimeoutMinutes | 3 | How long a Validate, Test or type-check may run before Mod Lab stops it and shows it as timed out (at most 10; fractions are fine). When Mod Lab loads, it clears checks a reload left shown as running. One still shown as running 30 s past this stops counting: V, T and K light again and the auto re-run goes on |
logging | normal | off: nothing. normal: errors, session start and check results. verbose: also reports, scans, processes and commands. debug: also expected misses (a folder or file not there yet), each mod's lights and process output. One file per session in ~/.claude/mod-builder-data/logs/, each line also in the debug log (claude --debug). |
/mod-builder config lists these with their current values and this session's log file; /mod-builder config <option> <value> changes one (for example /mod-builder config logging verbose). They're also in /config.
Mods are not sandboxed. They run with your access and skip Claude's permission prompts, so this table lists everything this one can touch. It is taken from claude plugin validate.
| Reach | Detail | ||
|---|---|---|---|
| Hooks | session.start, command.run{mod-builder} (gating, with .catch), command.run{modlab} (answers its own command; /modlab runs while Claude is working, 0.2.28), command.run{mod-builder:build} and command.run{mod-builder:edit} (gating, with .catch: open the pane, then run the skill), tool.call{mcp__mod-builder__lab_report}, classic.PostToolBatch (gating, with .catch: starts the mid-turn rescan and returns; validate notes it doesn't run for an installed plugin where an organization manages Claude Code), `classic.SessionStart{source=clear\ | resume\ | fork} (gating, with .catch, 0.2.28: after /clear, /resume and /branch writes the build's pinned folder back and rescans, detached; the same organization note applies), turn.complete, session.end, ui.close, ui.render{Pane modlab}, ui.render{AbovePrompt}` |
| Processes | claude plugin validate --json <mod> and npx -y -p typescript@5.6 tsc -p <mod> ($.process.run); claude plugin test <mod> streamed with $.process.spawn so the band fills on real progress (it falls back to $.process.run if the stream can't start). Only when you press V, T or K, when a skill reports a Validate or Test stage, or (with autoRerun) at the end of a turn for a mod whose checks went stale. Never on a timer. A check still running after testTimeoutMinutes is stopped (its child is killed) and shown as timed out. | ||
| Files | Reads under modsDir, the marketplace file beside it and its own plugin.json. When a build reports a folder, checks its marketplace file and reads .git in the folder above it and at or above the project root, to tell whether it is the project's own repository or a worktree of it. With modsDir empty and no build's folder kept, checks whether .claude-plugin/marketplace.json exists in the project root (the working directory when the root can't be read) and then each folder above it, stopping at the first found, at each scan. At session start, stats each mods folder its store has keys for ($.fs.stat, 0.2.30). Writes only its log, ~/.claude/mod-builder-data/logs/<date>-<session>.log, unless logging is off. | ||
| Prompt box | $.prompt.fill puts /mod-builder:build (N, or /modlab new <idea>) or a fix request (F) in the prompt box; it never submits | ||
| Notifications | $.ui.notify: a native notification when a mod is ready to share | ||
| Settings | Its own /config rows ($.config.list / $.config.set), when you run /mod-builder config <option> <value> | ||
| Environment | Reads HOME, USERPROFILE (to place the log file) | ||
| Session | Reads the project root (to find the mods folder when modsDir is empty, and to keep a build's folder until a /cd), the working directory (to name a mod's folder the way the session reads it, and to find the mods folder when the root can't be read) and the session id (to name the log file). Keeps the folder a build reported in its own session state. | ||
| Store | Its own $.store, one set of keys per mods folder: last results per mod, which mods were announced, and edit generations. At session start it lists its keys and deletes those of a folder that's gone, and the unkeyed ones from before 0.2.9 once replaced; each scan drops a mod no longer in its folder (0.2.30) | ||
| Network | None from the mod itself. The first Type-check makes npx download TypeScript. | ||
| Model calls | None | ||
| Tools it adds | lab_report, which records progress (with path, the folder being built in) and runs nothing beyond the Validate and Test above | ||
| Gating hooks | 7, all with .catch: /mod-builder (command), /mod-builder:build and /mod-builder:edit (they open the pane and always run the skill), lab_report, classic.PostToolBatch (passes every batch on), classic.SessionStart (passes it on), ui.close |
claude plugin validate plugins/mod-builder
claude plugin test plugins/mod-builder # 166 tests: logic and UI
bash plugins/mod-builder/skills/build/scripts/check-archetypes.sh # all five archetypes
hooks/mod-builder-logic.ts holds every rule. It has no $ calls and is unit-tested.hooks/register.tsx is the only file that calls $.skills/build/ and skills/edit/ are the two skills; edit reuses build's references and templates.SPEC.md is Mod Lab's own spec, written from the skill's template. Its Design section records how the pane follows the Claude Design mockups, and its Edits section covers build generations.design/ holds the Claude Design briefs: the repo README, its visuals (hero and feature strip), and the pane mockups (superseded, kept for history).CI tests it on Claude Code 2.1.296. 0.2.29's tests, archetype check, typecheck and -p live checks ran on 2.1.308; 0.2.30's tests, typecheck and -p live check ran on 2.1.309; 0.2.31's tests, archetype check and -p live check ran on 2.1.309, and validate --strict on 2.1.309 and 2.1.296; 0.2.32's archetype check and -p live check ran on 2.1.309; 0.2.33's and 0.2.34's checks and -p live checks ran on 2.1.310. Function hooks are early access, so the API may change between releases.
hooks/register.tsx 1969 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { ModView, Run, RunKind } from '../types'
5import * as Lab from './mod-builder-logic'
6
7/**
8 * Mod Lab: the showcase half of mod-builder. Every `$` call lives here; every
9 * rule it applies lives in mod-builder-logic.ts. The drawing follows the
10 * Claude Design mockups in design/ (frames 1a–5b).
11 *
12 * `/modlab` opens a pane of the mods under the mods folder, each with eight
13 * stage lights judged from disk and exit codes. Buttons run validate, test and
14 * tsc; the band, the status line, toasts and a notification report runs; the
15 * model's `lab_report` tool lights the stage it is working on; `/modlab demo`
16 * walks a pretend build through every state.
17 */
18
19const PANE = 'modlab'
20/** The pane as every open asks for it; bringing it to the front adds only `focus`. */
21const PANE_ARGS = { id: PANE, title: 'Mod Lab', columns: 80 }
22const TOOL = 'lab_report'
23const RESULTS_KEY = 'modlab:results'
24const DONE_KEY = 'modlab:done'
25const GENERATIONS_KEY = 'modlab:generations'
26/** Each names one set of a mods folder's records, `<prefix>:<modsDir>`; alone, the unkeyed set from before 0.2.9. */
27const STORE_PREFIXES = [RESULTS_KEY, DONE_KEY, GENERATIONS_KEY]
28const FRAME_MS = 250
29const NAME_COLUMN = 18
30const LABEL_COLUMN = 11
31const NARROW_TOAST = '◆ Mod Lab needs a wider window. Widen it, or watch the status line.'
32const SHOW_TEXT = 'Bringing Mod Lab to the front; it takes the keyboard if your prompt is empty (Esc gives it back).'
33const STILL_BEHIND_TOAST = 'Mod Lab is still behind another tab: ctrl+x tab, then again until it shows.'
34/** How long after asking for the front the pane is read again (#31). */
35const FRONT_CHECK_MS = 500
36
37/** The design's colour roles; `text` is the surface's own foreground. */
38const COLOR: Record<Lab.Tone, string | undefined> = {
39 accent: '#D97757',
40 success: '#7FB685',
41 warn: '#E0B15A',
42 error: '#E06C6C',
43 dim: '#8A8580',
44 text: undefined,
45}
46const BACKGROUND = '#1A1918'
47const HOVER = '#2C2A27'
48
49// One value on purpose: a scan's mods and the folder it judged them in are written together, so no
50// render, button, lab_report or re-run ever pairs one folder's rows with another's path. Don't split
51// it into two atoms (PR #57 review round 2; the "publishes its folder and its mods together" test).
52const judged = atom({ plugin: 'mod-builder', key: 'judged' } as const, { modsDir: null, views: [] })
53const selected = atom({ plugin: 'mod-builder', key: 'selected' } as const, null)
54const runs = atom({ plugin: 'mod-builder', key: 'runs' } as const, [])
55const reported = atom({ plugin: 'mod-builder', key: 'reported' } as const, {})
56const building = atom({ plugin: 'mod-builder', key: 'building' } as const, {})
57const frame = atom({ plugin: 'mod-builder', key: 'frame' } as const, { n: 0, now: 0 })
58const demoStartedAt = atom({ plugin: 'mod-builder', key: 'demoStartedAt' } as const, null)
59const readme = atom({ plugin: 'mod-builder', key: 'readme' } as const, null)
60const fresh = atom({ plugin: 'mod-builder', key: 'fresh' } as const, [])
61const hasWarnedNarrow = atom({ plugin: 'mod-builder', key: 'hasWarnedNarrow' } as const, false)
62// A copy of `pin` below, for a reload: written with `$.state.set` only, and read once at session start.
63const pinned = atom({ plugin: 'mod-builder', key: 'pinned' } as const, null)
64
65type Engine = EngineInterface
66type StoredResults = Record<string, Lab.Results>
67
68// Module state: options, timer handles, in-flight guards and write chains only.
69// A reload starts it afresh; what must survive lives in atoms and $.store.
70let configuredDir = ''
71let autoOpen = false
72let autoRerun = true
73/** A check's time limit in ms, from `testTimeoutMinutes`. */
74let runLimit = Lab.runLimitMsOf(undefined)
75let clock: Timer | null = null
76let lastTickMs = 0
77let scanning: Promise<void> | null = null
78// What the next pass reads, merged from the requests made during a scan (Change 0.2.24).
79let queuedScan: Lab.ScanRequest | null = null
80let isQueuedAnnounced = false
81// The folder a build reported with `path`, and the root it was reported under (#92). Module state, so the
82// lab_report hook sets it before its scan without a state read: a dispatch's first `get` fixes what all its
83// reads see (gotchas.md), and the #10 scan has to come first.
84let pin: Lab.Pin | null = null
85/** Set by session.start: a resumed startup fires classic.SessionStart before it (probed on 2.1.296 and 2.1.306, #119). */
86let hasStarted = false
87// The project root's repository (its common git folder), found once per root (PR #95 review follow-up).
88let rootRepo: { root: string; common: string | null } | null = null
89// Writes to the results and generations in $.store, in order (Change 0.2.8).
90let storeChain: Promise<void> = Promise.resolve()
91// What the last finished scan read; a scan swaps in its own once it has read every folder (Change 0.2.8).
92let factsByMod = new Map<string, Lab.FileFacts>()
93/** The folder and mods of the last scan that wrote its rows (`judged`): set with no await after that write. */
94let published: { modsDir: string; names: ReadonlySet<string> } | null = null
95/** The folder the last scan listed and its mod folders, in order: a pass reads only some mods while they match (Change 0.2.24). */
96let scannedFolders: { modsDir: string; names: readonly string[]; marketplaceMtime: number | null } | null = null
97/** Each mod folder's quick signature as last read, by its path, a folder that isn't a mod yet included (PR #109 review). */
98const folderSigs = new Map<string, string>()
99// Logging (Change 0.2.2): the level, this session's lines, its file once known, and writes in order.
100let logLevel: Lab.LogLevel = 'normal'
101let logBuffer: Lab.LogBuffer = Lab.EMPTY_LOG
102let logFile = ''
103let logChain: Promise<void> = Promise.resolve()
104let flushTimer: Timer | null = null
105let lastCaught: Record<string, string> = {}
106let writtenSig = ''
107let hasReportedWriteFailure = false
108
109// Every function that takes `$` is declared here, at the top of the file: the
110// engine follows `$` only into functions it can see at this level.
111
112// ── Logging ───────────────────────────────────────────────────────────────
113
114/**
115 * Records one line when the `logging` level allows it: into this session's
116 * buffer, the debug log, and the log file (at once for `normal` lines, else
117 * LOG_FLUSH_MS after the last). Logging never throws into Mod Lab.
118 */
119function logEvent($: Engine, level: Lab.LineLevel, site: string, message: string, context?: unknown): void {
120 if (!Lab.shouldLog(logLevel, level)) return
121 try {
122 const line = Lab.logLineOf(Date.now(), level, site, message, context)
123 logBuffer = Lab.pushLine(logBuffer, line)
124 $.ui.log(line, { to: 'debug' })
125 if (level === 'normal') {
126 flushTimer?.cancel()
127 flushTimer = null
128 void flushLog($)
129 } else scheduleFlush($)
130 } catch {
131 // A line that can't be recorded is dropped; Mod Lab carries on.
132 }
133}
134
135/** A caught error, logged where it was caught; `normal` unless the miss is expected. Repeats at one site are logged once. */
136function logCaught($: Engine, site: string, error: unknown, level: Lab.LineLevel = 'normal', context?: unknown): void {
137 const message = Lab.errorText(error)
138 if (level === 'normal') {
139 const seen = Lab.isNewCaught(lastCaught, site, message)
140 lastCaught = seen.last
141 if (!seen.isNew) return
142 }
143 logEvent($, level, site, message, context)
144}
145
146function scheduleFlush($: Engine): void {
147 if (flushTimer) return
148 try {
149 flushTimer = $.clock.after(Lab.LOG_FLUSH_MS, () => {
150 flushTimer = null
151 void flushLog($)
152 })
153 } catch {
154 flushTimer = null
155 }
156}
157
158/** Writes the buffer to this session's log file; writes run one at a time. A failed write is noted once in the debug log. */
159function flushLog($: Engine): Promise<void> {
160 logChain = logChain
161 .then(() => writeLog($))
162 .catch((error: unknown) => {
163 if (hasReportedWriteFailure) return
164 hasReportedWriteFailure = true
165 try {
166 $.ui.log(`mod-builder: could not write its log ${logFile}: ${Lab.errorText(error)}`, { to: 'debug' })
167 } catch {
168 // Nothing more can be done.
169 }
170 })
171 return logChain
172}
173
174async function writeLog($: Engine): Promise<void> {
175 if (logLevel === 'off' || (logBuffer.lines.length === 0 && logBuffer.dropped === 0)) return
176 if (!logFile) {
177 const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || ''
178 if (!home) return
179 // A session whose id can't be read gets its own name, never a file other sessions share.
180 const sessionId = await $.session.id().catch(() => `x${Date.now().toString(36)}`)
181 const file = Lab.logFileOf(home, Date.now(), sessionId)
182 // After a reload this module starts empty: continue the session's file rather than replace it.
183 // A file that exists but can't be read is left alone; the next flush tries again.
184 if (await $.fs.exists(file)) {
185 const earlier = String(await $.fs.read(file))
186 logBuffer = Lab.continueLog(earlier, logBuffer)
187 }
188 logFile = file
189 }
190 const text = Lab.logText(logBuffer)
191 const sig = `${logBuffer.dropped}:${logBuffer.lines.length}:${logBuffer.lines.at(-1) ?? ''}`
192 if (sig === writtenSig) return
193 await $.fs.write(logFile, text)
194 writtenSig = sig
195}
196
197/** The session's working directory, read at each use so a `/cd` is followed; null when it can't be read. */
198const cwdOf = ($: Engine): Promise<string | null> =>
199 $.session.cwd().catch((error: unknown) => (logCaught($, 'session.cwd', error), null))
200
201/** A folder's entries; none when it can't be listed, and then its path goes in `unlisted`, if given. */
202const list = ($: Engine, path: string, unlisted?: string[]): Promise<Lab.Entry[]> =>
203 $.fs
204 .list(path)
205 .then(entries => entries.map(({ name, kind, mtimeMs }) => ({ name, kind, mtimeMs })))
206 .catch((error: unknown) => {
207 logCaught($, 'fs.list', error, 'debug', { path })
208 unlisted?.push(path)
209 return []
210 })
211
212const readText = ($: Engine, path: string): Promise<string | null> =>
213 $.fs.read(path).catch((error: unknown) => {
214 logCaught($, 'fs.read', error, 'debug', { path })
215 return null
216 })
217
218const exists = ($: Engine, path: string): Promise<boolean> =>
219 $.fs.exists(path).catch((error: unknown) => {
220 logCaught($, 'fs.exists', error, 'debug', { path })
221 return false
222 })
223
224/** The mods folder of the plugin's own marketplace: `modsDir`'s default when the walk finds no marketplace above the root or the working directory. */
225const pluginModsDirOf = ($: Engine): string => `${$.plugin.root}/../../mods`
226
227/** The session's project root, which `/cd` and a worktree move change and a Bash `cd` doesn't (#92); null when it can't be read. */
228const rootOf = ($: Engine): Promise<string | null> =>
229 $.session.root().catch((error: unknown) => (logCaught($, 'session.root', error, 'debug'), null))
230
231/** Sets or clears the pin, with its copy in state for a reload: a write, never a read (see `pin`). An unchanged pin isn't written again. */
232async function setPin($: Engine, next: Lab.Pin | null): Promise<void> {
233 if (pin?.modsDir === next?.modsDir && pin?.root === next?.root) return
234 pin = next
235 await $.state.set({ plugin: 'mod-builder', key: 'pinned' }, next).catch((error: unknown) => logCaught($, 'state.set', error, 'normal', { key: 'pinned' }))
236}
237
238/** After /clear, /resume or /branch (#119): the pin's copy in state again, then a scan to list the mods again. */
239async function reseed($: Engine): Promise<void> {
240 if (pin) await $.state.set({ plugin: 'mod-builder', key: 'pinned' }, pin).catch((error: unknown) => logCaught($, 'state.set', error, 'normal', { key: 'pinned' }))
241 await scan($, false)
242}
243
244/** A folder's `.git`: a file (a worktree's pointer) is read; a directory is known by its `HEAD`. */
245async function dotGitOf($: Engine, folder: string): Promise<Lab.DotGit> {
246 const path = `${Lab.normalizePath(folder).replace(/\/$/, '')}/.git`
247 const text = await readText($, path)
248 if (text !== null) return { kind: 'file', text }
249 return (await exists($, `${path}/HEAD`)) ? { kind: 'dir' } : null
250}
251
252/**
253 * Whether a folder's `.git` is git's own: a worktree pointer must be named back by git's record of it
254 * (`.git/worktrees/<name>/gitdir`), so a hand-written pointer doesn't count (PR #95 review follow-up).
255 */
256async function isRecordedByGit($: Engine, folder: string, dotGit: Lab.DotGit): Promise<boolean> {
257 const link = Lab.worktreeLinkOf(folder, dotGit)
258 if (!link) return true
259 const text = await readText($, link.record)
260 return text !== null && Lab.isBackLinkTo(folder, link.record, text)
261}
262
263/** The common git folder of the repository the project root is in: the first `.git` at or above it, if git records it. */
264async function rootRepoOf($: Engine, root: string): Promise<string | null> {
265 if (rootRepo?.root === root) return rootRepo.common
266 let common: string | null = null
267 for (const folder of Lab.foldersUpFrom(root)) {
268 const dotGit = await dotGitOf($, folder)
269 if (!dotGit) continue
270 common = (await isRecordedByGit($, folder, dotGit)) ? Lab.gitCommonDirOf(folder, dotGit) : null
271 break
272 }
273 rootRepo = { root, common }
274 return common
275}
276
277/**
278 * The pin a report's folder makes, or why it makes none (PR #95 review): a set `modsDir`, `Lab.pinCheckOf`'s
279 * reasons, no marketplace file, or a folder above `mods/` that isn't the project's own repository or one of
280 * its worktrees (a nested clone or copy, such as community mods kept in an ignored folder).
281 */
282async function pinFor($: Engine, dir: string): Promise<{ pin: Lab.Pin } | { reason: string }> {
283 if (configuredDir) return { reason: 'the modsDir option is set' }
284 const check = Lab.pinCheckOf(dir, await rootOf($))
285 if ('reason' in check) return check
286 const folder = Lab.normalizePath(dir)
287 if (!(await exists($, check.marketplace))) return { reason: `no marketplace holds ${folder}` }
288 const home = Lab.parentOf(folder)
289 const dotGit = await dotGitOf($, home)
290 if (!(await isRecordedByGit($, home, dotGit))) return { reason: `${home} has a worktree pointer git has no record of` }
291 const isOurs = Lab.isSameRepo(Lab.gitCommonDirOf(home, dotGit), await rootRepoOf($, check.root))
292 if (!isOurs) return { reason: `${home} isn't the project's git repository or one of its worktrees` }
293 return { pin: { modsDir: folder, root: check.root } }
294}
295
296/**
297 * The marketplace file nearest `start`, the folder the walk starts in: candidates are probed
298 * nearest first and the first one found ends the walk (each probe is slow on /mnt/c).
299 */
300async function nearestMarketplace($: Engine, start: string | null): Promise<string[]> {
301 for (const path of start === null ? [] : Lab.marketplaceCandidatesOf(start)) {
302 if (await exists($, path)) return [path]
303 }
304 return []
305}
306
307/**
308 * The walk with no pin: the marketplace nearest the project root, read now so a `/cd` is followed and a
309 * Bash `cd` isn't (#92), else the one nearest the working directory (no root, or none above it: PR #95 review).
310 */
311async function walkOf($: Engine, root: string | null): Promise<{ cwd: string | null; existing: string[] }> {
312 const fromRoot = await nearestMarketplace($, root)
313 if (fromRoot.length) return { cwd: null, existing: fromRoot }
314 const cwd = await cwdOf($)
315 return { cwd, existing: await nearestMarketplace($, cwd) }
316}
317
318/**
319 * What `modsDir` means when it isn't set and no build's folder is pinned: the `mods/` of the marketplace
320 * `walkOf` finds (a worktree's own in a worktree), else the plugin's own.
321 */
322async function defaultModsDir($: Engine): Promise<string> {
323 const root = await rootOf($)
324 const { cwd, existing } = await walkOf($, root)
325 return Lab.watchedDirOf(null, root, '', cwd, existing, pluginModsDirOf($)).dir
326}
327
328/**
329 * The mods folder to watch now (#92): a build's pinned folder while the project root is the one it
330 * was pinned under, else a set `modsDir` (nothing is walked), else the walk `defaultModsDir` takes.
331 * A drawing reads it without dropping the pin: `$.state.set` is refused while a render draws, so the
332 * next read outside a render drops it.
333 */
334async function currentModsDir($: Engine, isDrawing = false): Promise<string> {
335 // A set modsDir decides alone: no root to read, and a pin stays for when it's cleared.
336 if (configuredDir) return Lab.normalizePath(configuredDir)
337 const held = pin
338 const root = await rootOf($)
339 // A kept pin whose marketplace is gone (a worktree removed after its PR merged) is dropped too (PR #95 review).
340 const kept = Lab.keptPinOf(held, root)
341 const live = kept && (await exists($, Lab.marketplaceFileOf(kept.modsDir))) ? kept : null
342 const { cwd, existing } = live ? { cwd: null, existing: [] } : await walkOf($, root)
343 const watched = Lab.watchedDirOf(live, root, '', cwd, existing, pluginModsDirOf($))
344 // A changed root or a gone marketplace dropped the pin, unless a report has pinned another folder meanwhile.
345 if (held && !watched.pin && pin === held && !isDrawing) await setPin($, null)
346 return watched.dir
347}
348
349/**
350 * The folder the pane shows: the one the last scan judged (kept in state, so it survives a
351 * reload), else the current one before any scan. What the pane's buttons act on.
352 */
353async function shownModsDir($: Engine, isDrawing = false): Promise<string> {
354 return (await read($, judged)).modsDir ?? currentModsDir($, isDrawing)
355}
356
357/** A folder of `at` that its listing `top` names, listed in turn; one it doesn't name reads as empty. A failed listing goes in `unlisted`. */
358function listIn($: Engine, at: string, top: readonly Lab.Entry[], folder: string, unlisted: string[]): Promise<Lab.Entry[]> {
359 return top.some(entry => entry.name === folder) ? list($, `${at}/${folder}`, unlisted) : Promise.resolve([])
360}
361
362/** The folders the quick signature reads besides the mod's own listing: the full read and the quick check list them here alike. */
363async function quickFoldersOf($: Engine, at: string, top: readonly Lab.Entry[], unlisted: string[]): Promise<Omit<Lab.QuickRead, 'top'>> {
364 const [manifestDir, hooks, tests] = await Promise.all([listIn($, at, top, '.claude-plugin', unlisted), listIn($, at, top, 'hooks', unlisted), listIn($, at, top, 'tests', unlisted)])
365 return { manifestDir, hooks, tests }
366}
367
368/** One mod folder's file facts, as a scan judges them; null when it isn't a mod. */
369async function modFactsOf($: Engine, modsDir: string, name: string, marketplace: string): Promise<Lab.FileFacts | null> {
370 const at = `${modsDir}/${name}`
371 const top = await list($, at)
372 const has = (entry: string): boolean => top.some(one => one.name === entry)
373 // A folder that can't be listed reads as empty, so the facts say which ones (a delete would look the same).
374 const unlisted: string[] = []
375 const [{ manifestDir, hooks, tests }, types, agents, commands, skills] = await Promise.all([
376 quickFoldersOf($, at, top, unlisted),
377 listIn($, at, top, 'types', unlisted),
378 listIn($, at, top, 'agents', unlisted),
379 listIn($, at, top, 'commands', unlisted),
380 listIn($, at, top, 'skills', unlisted),
381 ])
382 // The baseline the quick check after a tool batch compares, kept whether or not the folder is a mod yet (Codex 4296025357).
383 folderSigs.set(at, Lab.quickSigOf({ top, manifestDir, hooks, tests }))
384 // Their subfolders are walked too; the manifest folder's are not.
385 const codeFolders = { hooks, tests, types, agents, commands, skills }
386 const nested = await Promise.all(Object.entries(codeFolders).map(([folder, entries]) => nestedFiles($, at, folder, entries, unlisted)))
387 return Lab.factsOf({
388 name,
389 top,
390 manifestDir,
391 ...codeFolders,
392 nested: nested.flat(),
393 unlisted: unlisted.map(path => path.slice(at.length + 1)),
394 spec: has('SPEC.md') ? await readText($, `${at}/SPEC.md`) : null,
395 readme: has('README.md') ? await readText($, `${at}/README.md`) : null,
396 manifest: manifestDir.some(entry => entry.name === 'plugin.json') ? await readText($, `${at}/.claude-plugin/plugin.json`) : null,
397 marketplace,
398 })
399}
400
401/** The marketplace file beside a mods folder, or '' when there is none. */
402const marketplaceOf = async ($: Engine, modsDir: string): Promise<string> => (await readText($, `${modsDir}/../.claude-plugin/marketplace.json`)) ?? ''
403
404/**
405 * The files in `folder`'s subfolders (from its `entries`), up to `depth` levels down, named by
406 * their path from the mod folder `at`. Sibling folders are listed at once, since /mnt/c is slow;
407 * dot-folders and node_modules are skipped. A subfolder that can't be listed goes in `unlisted`.
408 */
409async function nestedFiles($: Engine, at: string, folder: string, entries: readonly Lab.Entry[], unlisted: string[], depth = 3): Promise<Lab.Entry[]> {
410 if (depth === 0) return []
411 const subfolders = entries.filter(entry => entry.kind === 'dir' && !entry.name.startsWith('.') && entry.name !== 'node_modules')
412 const found = await Promise.all(
413 subfolders.map(async sub => {
414 const path = `${folder}/${sub.name}`
415 const inner = await list($, `${at}/${path}`, unlisted)
416 const files = inner.filter(entry => entry.kind === 'file').map(entry => ({ ...entry, name: `${path}/${entry.name}` }))
417 return [...files, ...(await nestedFiles($, at, path, inner, unlisted, depth - 1))]
418 }),
419 )
420 return found.flat()
421}
422
423// ── Store ─────────────────────────────────────────────────────────────────
424
425/**
426 * The store key of one mods folder's records. One install serves every folder the working
427 * directory leads to, and $.store is shared between sessions, so a mod's name alone is not enough.
428 */
429const keyOf = (base: string, modsDir: string): string => `${base}:${modsDir}`
430
431/** The one folder Mod Lab watched before 0.2.9 (a set `modsDir`, else the plugin's own): its records were unkeyed. */
432const legacyDirOf = ($: Engine): string => Lab.normalizePath(configuredDir || pluginModsDirOf($))
433
434/** One folder's records under `base`; the folder the unkeyed set described reads that until it has its own. */
435async function storedOf($: Engine, base: string, modsDir: string): Promise<unknown> {
436 const own = await $.store.get(keyOf(base, modsDir))
437 if (own !== undefined || modsDir !== legacyDirOf($)) return own
438 return $.store.get(base)
439}
440
441const resultsOf = async ($: Engine, modsDir: string): Promise<StoredResults> =>
442 ((await storedOf($, RESULTS_KEY, modsDir)) ?? {}) as StoredResults
443
444/**
445 * The version and the logic and test files an edit starts from. `logicSig` is absent in records from before 0.2.21,
446 * and null when a folder under hooks/ or tests/ couldn't be listed then; either way the edit keeps the mtime rule.
447 */
448type Baseline = Omit<Lab.Edit, 'since'>
449/**
450 * When each mod's current edit started (a build generation), for mods being edited, and its baseline.
451 * `repeatedAt` is when a Spec running last repeated during the edit, and `repeatedFrom` the mod on disk
452 * then: the baseline of the next edit, should a scan that read the edit before the repeat end it.
453 */
454type Generation = Lab.Edit & { repeatedAt?: number; repeatedFrom?: Baseline }
455/** As stored: an older version wrote the bare start time. */
456type StoredGenerations = Record<string, number | Generation>
457const generationsFrom = (stored: StoredGenerations): Record<string, Generation> =>
458 Object.fromEntries(
459 Object.entries(stored).map(([mod, gen]) => [mod, typeof gen === 'number' ? { since: gen, fromVersion: null } : gen]),
460 )
461const generationsOf = async ($: Engine, modsDir: string): Promise<Record<string, Generation>> =>
462 generationsFrom(((await storedOf($, GENERATIONS_KEY, modsDir)) ?? {}) as StoredGenerations)
463/** Whether `latest` is still the generation `read` was: the same start, and no Spec running reported on it since. */
464const isSameGeneration = (latest: Generation | undefined, read: Generation | undefined): boolean =>
465 latest?.since === read?.since && latest?.repeatedAt === read?.repeatedAt
466
467/**
468 * Sets one folder's records under `base` to `change` of their current value. Updates run one at
469 * a time, each reading the key in its turn, so two callers never overwrite each other's change.
470 * This orders this session's writes only: $.store is one file per plugin, and a second session's
471 * write can still race. A failed update rejects for its caller; the next one runs regardless.
472 */
473function updateStore<T>($: Engine, base: string, modsDir: string, change: (current: T) => T): Promise<void> {
474 return enqueueStore(async () => {
475 await $.store.set(keyOf(base, modsDir), change(((await storedOf($, base, modsDir)) ?? {}) as T))
476 })
477}
478
479/** Runs `task` after every store write and delete this session queued before it; one that fails doesn't hold up the next. */
480function enqueueStore<T>(task: () => Promise<T>): Promise<T> {
481 const turn = storeChain.then(task)
482 // The caller handles the turn's failure; the chain itself never rejects, so no failure goes unhandled.
483 storeChain = turn.then(
484 () => undefined,
485 () => undefined,
486 )
487 return turn
488}
489
490/** Updates one folder's build generations, as `updateStore` does, from their current value. */
491function updateGenerations($: Engine, modsDir: string, change: (current: Record<string, Generation>) => Record<string, Generation>): Promise<void> {
492 return updateStore($, GENERATIONS_KEY, modsDir, (stored: StoredGenerations) => change(generationsFrom(stored)))
493}
494
495/**
496 * Deletes one key in turn with `updateStore`'s writes, so a write this session started for it lands first (#138), if
497 * `isStillGone` says so in that same turn (PR #146 review, finding 5). Resolves to whether it deleted the key.
498 */
499function deleteStore($: Engine, key: string, isStillGone: () => Promise<boolean>): Promise<boolean> {
500 return enqueueStore(async () => {
501 if (!(await isStillGone())) return false
502 await $.store.delete(key)
503 return true
504 })
505}
506
507/**
508 * Whether `$.fs.stat` says the folder is gone: the engine's ENOENT, and nothing else (#138). Any other rejection keeps
509 * it, with a debug line, so pruning a reworded message stopped isn't silent (PR #146 review, finding 6).
510 */
511const isFolderGone = ($: Engine, dir: string): Promise<boolean> =>
512 $.fs.stat(dir).then(
513 () => false,
514 (error: unknown) => {
515 const isGone = Lab.folderGone(Lab.errorText(error))
516 if (!isGone) logCaught($, 'store.prune', error, 'debug', { path: dir })
517 return isGone
518 },
519 )
520
521/**
522 * Change 0.2.30 (#138): deletes the keys of mods folders that are gone, and each unkeyed key from before 0.2.9 its own
523 * keyed record has replaced. A folder is gone only when `$.fs.stat` says ENOENT: one it can't check keeps its keys.
524 * Each delete is logged; a refused one is logged and skipped.
525 */
526async function pruneStore($: Engine): Promise<void> {
527 const keys = await $.store.keys()
528 const legacyDir = legacyDirOf($)
529 const folders = Lab.storeFoldersOf(keys, STORE_PREFIXES, legacyDir)
530 const isGone = await Promise.all(folders.map(dir => isFolderGone($, dir)))
531 const gone = folders.filter((_, at) => isGone[at])
532 for (const { key, why } of Lab.prunableKeys(keys, STORE_PREFIXES, gone, legacyDir)) {
533 // A key that goes with its gone folder is checked again in its turn: the folder may be back (finding 5).
534 const dir = Lab.storeFolderOf(key, STORE_PREFIXES) ?? legacyDir
535 const isStillGone = () => (gone.includes(dir) ? isFolderGone($, dir) : Promise.resolve(true))
536 await deleteStore($, key, isStillGone).then(
537 isDeleted => logEvent($, isDeleted ? 'normal' : 'verbose', 'store', isDeleted ? `deleted ${key} (${why})` : `kept ${key} (${dir} is back)`),
538 (error: unknown) => logCaught($, 'store.delete', error, 'normal', { key }),
539 )
540 }
541}
542
543// ── Scanning ──────────────────────────────────────────────────────────────
544
545/** Every mod read again: what every scan did before 0.2.24, and still does unless a tool batch asks for less. */
546const FULL_SCAN: Lab.ScanRequest = { isFull: true, isQuick: false, mods: [] }
547
548/**
549 * Reads the mod folders `request` names (every one, by default), judges them and redraws. Single-flight: a
550 * call during a scan merges its request into one more pass, and every caller waits until the passes end,
551 * so what it reads afterwards reflects the disk as of its call.
552 */
553function scan($: Engine, isAnnounced: boolean, request: Lab.ScanRequest = FULL_SCAN): Promise<void> {
554 if (scanning) {
555 queuedScan = Lab.mergeScanRequests(queuedScan, request)
556 isQueuedAnnounced ||= isAnnounced
557 return scanning
558 }
559 scanning = scanPasses($, isAnnounced, request).finally(() => {
560 scanning = null
561 })
562 return scanning
563}
564
565async function scanPasses($: Engine, isAnnounced: boolean, request: Lab.ScanRequest): Promise<void> {
566 let announce = isAnnounced
567 let next: Lab.ScanRequest | null = request
568 while (next) {
569 queuedScan = null
570 await scanOnce($, announce, next)
571 announce = isQueuedAnnounced
572 isQueuedAnnounced = false
573 next = queuedScan
574 }
575}
576
577/**
578 * The folders whose quick signature moved since they were last read (Change 0.2.24), mods or not yet mods (Codex
579 * 4296025357): four listings each, no file read and no nested walk. A listing that fails counts as moved: can't
580 * tell isn't unchanged.
581 */
582async function movedMods($: Engine, modsDir: string, names: readonly string[]): Promise<string[]> {
583 // Every folder at once, as nestedFiles lists siblings: /mnt/c is slow.
584 const isMoved = await Promise.all(names.map(name => hasMoved($, `${modsDir}/${name}`)))
585 return names.filter((_, at) => isMoved[at])
586}
587
588/** One folder's quick signature now differs from the one recorded when it was last read, or a listing failed. */
589async function hasMoved($: Engine, at: string): Promise<boolean> {
590 const unlisted: string[] = []
591 const top = await list($, at, unlisted)
592 const folders = await quickFoldersOf($, at, top, unlisted)
593 return unlisted.length > 0 || Lab.quickSigOf({ top, ...folders }) !== folderSigs.get(at)
594}
595
596/** The mtime of the marketplace file beside a mods folder, or null when it isn't there (Codex 4296025346): a stat, no read. */
597async function marketplaceMtimeOf($: Engine, modsDir: string): Promise<number | null> {
598 const file = Lab.marketplaceFileOf(modsDir)
599 const slash = file.lastIndexOf('/')
600 return (await list($, file.slice(0, slash))).find(entry => entry.name === file.slice(slash + 1))?.mtimeMs ?? null
601}
602
603async function scanOnce($: Engine, isAnnounced: boolean, request: Lab.ScanRequest): Promise<void> {
604 const scanStartedAt = Date.now()
605 const dir = await currentModsDir($)
606 const unlisted: string[] = []
607 const folders = (await list($, dir, unlisted)).filter(entry => entry.kind === 'dir' && !entry.name.startsWith('.'))
608 // A failed listing reads as empty: for a pass that reads only some mods, that isn't every mod gone, so it skips (PR #109 review).
609 if (!request.isFull && unlisted.length) return
610 const names = folders.map(folder => folder.name)
611 // Only some mods are read while the last scan listed the same folder and the same mods, and knows each one named.
612 const last = scannedFolders?.modsDir === dir ? scannedFolders : null
613 // Every listing pass stats the marketplace beside the folder; a moved one reads every mod, whose listing facts it holds (Codex 4296025346).
614 const marketplaceMtime = request.isFull || request.isQuick || last === null ? await marketplaceMtimeOf($, dir) : last.marketplaceMtime
615 const isFull =
616 request.isFull ||
617 last === null ||
618 last.names.join('\n') !== names.join('\n') ||
619 request.mods.some(name => !factsByMod.has(name)) ||
620 marketplaceMtime !== last.marketplaceMtime
621 const toRead = new Set(isFull ? names : [...request.mods, ...(request.isQuick ? await movedMods($, dir, names) : [])])
622 // A pass for some mods where nothing moved: no file is read and nothing is judged again.
623 if (!isFull && toRead.size === 0) return
624 const marketplace = await marketplaceOf($, dir)
625 const results = await resultsOf($, dir)
626 // As stored, for the drop below to compare against (#138); judged in the current shape.
627 const storedGenerations = ((await storedOf($, GENERATIONS_KEY, dir)) ?? {}) as StoredGenerations
628 const generations = generationsFrom(storedGenerations)
629 const cwd = await cwdOf($)
630 const inFlight = await liveRunsOf($)
631 const reports = Lab.liveReports(await read($, reported), await $.clock.now())
632 const found = new Map<string, Lab.FileFacts>()
633 // In the folder's order, so a pass that reads only some mods keeps the rows where they were.
634 for (const name of names) {
635 const facts = toRead.has(name) ? await modFactsOf($, dir, name, marketplace) : (factsByMod.get(name) ?? null)
636 if (facts) found.set(facts.name, facts)
637 }
638 factsByMod = found
639 scannedFolders = { modsDir: dir, names, marketplaceMtime }
640 // "Ready to share" marks are kept per folder: a same-named mod elsewhere didn't just turn green.
641 const freshIdOf = (name: string): string => `${dir}/${name}`
642 // A build that reported a mod before writing its folder gets a row of its own until the folder is found (#19).
643 const builds = Lab.liveReports((await read($, building))[dir] ?? {}, await $.clock.now())
644 const placeholders = Lab.placeholderNames(builds, [...found.keys()], dir)
645 // A mod no longer in the folder drops out of its records (#138), unless a build reported it before writing its folder.
646 // A listing that failed reads as no folders at all, so it drops nothing; nor does one with no mods in it, as a folder
647 // can be for a moment, mid-checkout (PR #146 review, finding 2).
648 const keep = unlisted.length === 0 && names.length > 0 ? [...names, ...placeholders] : null
649 if (keep) {
650 await dropGone($, RESULTS_KEY, dir, results, keep)
651 await dropGone($, GENERATIONS_KEY, dir, storedGenerations, keep)
652 }
653 const judge = (freshIds: readonly string[]): ModView[] => [
654 ...[...factsByMod.values()].map(facts =>
655 Lab.viewOf(
656 facts,
657 results[facts.name] ?? {},
658 inFlight.filter(one => one.mod === facts.name),
659 Lab.reportIn(reports[facts.name], dir),
660 freshIds.includes(freshIdOf(facts.name)),
661 generations[facts.name] ?? null,
662 Lab.displayPathOf(`${dir}/${facts.name}`, cwd),
663 ),
664 ),
665 ...placeholders.map(name =>
666 Lab.viewOf(
667 Lab.placeholderFacts(name),
668 {},
669 inFlight.filter(one => one.mod === name),
670 builds[name] ?? null,
671 false,
672 null,
673 Lab.displayPathOf(`${dir}/${name}`, cwd),
674 ),
675 ),
676 ]
677 const newlyGreen = await announceGreen($, judge([]), isAnnounced, dir, keep)
678 const marks = await read($, fresh)
679 const kept = Lab.freshIdsOf(marks, legacyDirOf($))
680 const freshIds = [...new Set([...kept, ...newlyGreen.map(freshIdOf)])]
681 // Written when a mod just turned green, or when bare marks from before 0.2.9 moved to their folder.
682 if (newlyGreen.length || kept.some((id, at) => id !== marks[at])) await update($, fresh, () => freshIds)
683 const next = judge(freshIds)
684 // An edit's generation ends when every stage is green again.
685 const finished = next.filter(view => Lab.isGreen(view.lights) && generations[view.name] !== undefined)
686 if (finished.length) {
687 // Drop only the generations this scan judged: one begun since stays. A Spec running reported on one
688 // since was read after this scan's reports, so the edit was finished when it came: it begins the next.
689 await updateGenerations($, dir, remaining => {
690 for (const view of finished) {
691 const [latest, read] = [remaining[view.name], generations[view.name]]
692 if (isSameGeneration(latest, read)) delete remaining[view.name]
693 else if (latest?.since === read?.since && latest?.repeatedAt !== undefined) {
694 // The repeat read the mod as it began; a record from 0.2.20 or earlier has only this scan's facts.
695 const facts = found.get(view.name)
696 remaining[view.name] = { since: latest.repeatedAt, ...(latest.repeatedFrom ?? { fromVersion: facts?.version ?? null, logicSig: facts?.logicSig }) }
697 }
698 }
699 return remaining
700 })
701 }
702 // A README open over another folder's list doesn't belong to this one; closed as the list changes.
703 const previous = (await read($, judged)).modsDir
704 if (previous !== null && previous !== dir) await update($, readme, () => null)
705 await update($, judged, () => ({ modsDir: dir, views: next }))
706 published = { modsDir: dir, names: new Set(next.map(view => view.name)) }
707 logEvent($, 'verbose', 'scan', `${folders.length} folders, ${next.length} mods in ${Date.now() - scanStartedAt}ms`, { modsDir: dir })
708 logEvent($, 'debug', 'scan.lights', 'lights per mod', Object.fromEntries(next.map(view => [view.name, view.lights.join(' ')])))
709 await update($, selected, current =>
710 current && (next.some(view => view.name === current) || current === Lab.DEMO_NAME) ? current : (next[0]?.name ?? null),
711 )
712 await refreshStatus($)
713}
714
715/**
716 * Drops the mods not in `keep` from one folder's records under `base`, when the scan's read of them (`read`) has any,
717 * through `updateStore`, from the value read in its turn (#138): only the entries still as `read`, so one written since
718 * the scan read them stays (PR #146 review, Codex 4362849420). A refused write is logged; the next scan tries again.
719 */
720async function dropGone($: Engine, base: string, modsDir: string, read: Readonly<Record<string, unknown>>, keep: readonly string[]): Promise<void> {
721 if (!Lab.withoutGone(read, keep)) return
722 await updateStore($, base, modsDir, (stored: Record<string, unknown>) => Lab.withoutGone(stored, keep, read) ?? stored).catch((error: unknown) =>
723 logCaught($, 'store.set', error, 'normal', { key: keyOf(base, modsDir) }),
724 )
725}
726
727/**
728 * The first time a mod turns all green at its current code: a toast and a
729 * notification (when announced). Returns the mods that just turned green. The marks of mods not in `keep`, when the
730 * scan's listing succeeded, go in the same write (#138): `done` isn't written through `updateStore`.
731 */
732async function announceGreen($: Engine, judged: readonly ModView[], isAnnounced: boolean, modsDir: string, keep: readonly string[] | null): Promise<string[]> {
733 const doneKey = keyOf(DONE_KEY, modsDir)
734 const stored = ((await storedOf($, DONE_KEY, modsDir)) ?? {}) as Record<string, number | string>
735 const kept = keep ? Lab.withoutGone(stored, keep) : null
736 const done = kept ?? stored
737 const newly: string[] = []
738 let isChanged = kept !== null
739 for (const view of judged) {
740 const stamp = factsByMod.get(view.name)?.codeSig ?? ''
741 if (!Lab.isGreen(view.lights) || done[view.name] === stamp) continue
742 done[view.name] = stamp
743 isChanged = true
744 if (!isAnnounced) continue
745 newly.push(view.name)
746 $.ui.toast(`✓ ${view.name} is ready to share`)
747 void $.ui.notify(`${view.name} is ready to share`, { title: 'Mod Lab' }).catch((error: unknown) => logCaught($, 'announceGreen.notify', error))
748 }
749 if (isChanged) {
750 await $.store.set(doneKey, done)
751 logEvent($, 'debug', 'store.set', doneKey)
752 }
753 return newly
754}
755
756/** Every mod drawn now: the demo first while it runs. */
757async function shownViews($: Engine): Promise<ModView[]> {
758 const started = await read($, demoStartedAt)
759 const all = (await read($, judged)).views
760 if (started === null) return all
761 const { now } = await read($, frame)
762 return [Lab.demoViewAt(Math.max(0, now - started)), ...all]
763}
764
765/** After a tool batch: read again the mods it changed in the watched folder, or after shell the ones whose stats moved (Change 0.2.24). */
766async function rescanAfter($: Engine, calls: readonly Lab.BatchCall[]): Promise<void> {
767 // A batch of read-only tools changed nothing: not even the watched folder is looked up (PR #109 review).
768 if (Lab.isReadOnlyBatch(calls)) return
769 const touch = Lab.batchTouch(calls, await currentModsDir($))
770 if (touch.mods.length === 0 && !touch.isQuick) return
771 // Announced, as a report's and the tick's scans are: announceGreen stamps a mod done before it checks the flag.
772 await scan($, true, { isFull: false, isQuick: touch.isQuick, mods: touch.mods })
773}
774
775async function refreshStatus($: Engine): Promise<void> {
776 $.ui.status(Lab.badgeOf(Lab.countsOf(await shownViews($))))
777}
778
779// ── The clock: runs only while something is live ─────────────────────────
780
781/**
782 * session.start fires once per fresh load of this module (claude-code.d.ts), and the runs atom
783 * outlives the module that wrote it. So at that moment no row has a live run: clear them all.
784 */
785async function clearLeftRuns($: Engine): Promise<void> {
786 if ((await read($, runs)).length) await update($, runs, () => [])
787}
788
789function startClock($: Engine): void {
790 if (clock) return
791 clock = $.clock.every(FRAME_MS, () => void tick($).catch((error: unknown) => logCaught($, 'tick', error)))
792}
793
794async function tick($: Engine): Promise<void> {
795 const now = await $.clock.now()
796 const previous = lastTickMs
797 lastTickMs = now
798 await update($, frame, current => ({ n: current.n + 1, now }))
799
800 const started = await read($, demoStartedAt)
801 if (started !== null) {
802 for (const text of Lab.demoToastsBetween(previous - started, now - started)) $.ui.toast(text)
803 const walk = Lab.demoWalkMs()
804 if (previous - started < walk && now - started >= walk) {
805 $.ui.toast(`✓ ${Lab.DEMO_NAME} (demo) is ready to share. That was a whole mod build`)
806 void $.ui.notify(`${Lab.DEMO_NAME} (demo) is ready to share`, { title: 'Mod Lab' }).catch((error: unknown) => logCaught($, 'tick.notify', error))
807 }
808 if (now - started >= Lab.demoLengthMs()) await stopDemo($)
809 }
810 await refreshStatus($)
811
812 // An orphan that aged out is dropped and the mods rescanned, so its stage stops reading running.
813 const all = await read($, runs)
814 const live = Lab.liveRuns(all, now, runLimit)
815 if (live.length < all.length) {
816 await update($, runs, rows => Lab.liveRuns(rows, now, runLimit))
817 void scan($, true).catch((error: unknown) => logCaught($, 'tick.scan', error))
818 }
819
820 // A placeholder whose running report expired has no folder for a later scan to correct, so rescan now (#19).
821 const allBuilds = await read($, building)
822 const shown = await read($, judged)
823 const builds = Lab.liveReports(allBuilds[shown.modsDir ?? ''] ?? {}, now)
824 if (shown.views.some(view => view.isPlaceholder && builds[view.name]?.status !== 'running')) {
825 void scan($, true).catch((error: unknown) => logCaught($, 'tick.scan', error))
826 }
827
828 // runs is read again here: a run may have started during the awaits above.
829 const isLive =
830 (await liveRunsOf($)).length > 0 ||
831 (await read($, demoStartedAt)) !== null ||
832 (await hasRunningReport($, now))
833 if (!isLive) {
834 clock?.cancel()
835 clock = null
836 // A run or report that started after those reads found the clock still set and didn't start one: start it again.
837 if ((await liveRunsOf($)).length || (await hasRunningReport($, now))) startClock($)
838 }
839}
840
841// ── Runs ──────────────────────────────────────────────────────────────────
842
843/** Records streamed test progress on the run in flight, which redraws the row and band. */
844async function noteProgress($: Engine, entry: Run, counts: { passed: number; failed: number }): Promise<void> {
845 await update($, runs, all => Lab.withProgress(all, entry, counts))
846}
847
848/** A check ended at its time limit; the message is its summary. */
849class RunTimeout extends Error {}
850
851/** The error a check ends with at its time limit: "timed out after 3 minutes". */
852const timeoutOf = (): RunTimeout => new RunTimeout(Lab.timeoutText(runLimit))
853
854/** The runs in flight: a row whose run a reload ended counts nowhere once it is past the time limit and the grace. */
855/** Whether any build still has a live running report, read now rather than from an earlier copy. */
856async function hasRunningReport($: Engine, now: number): Promise<boolean> {
857 const reports = [Lab.liveReports(await read($, reported), now), ...Object.values(await read($, building)).map(builds => Lab.liveReports(builds, now))]
858 return reports.some(all => Object.values(all).some(report => report.status === 'running'))
859}
860
861async function liveRunsOf($: Engine): Promise<Run[]> {
862 return Lab.liveRuns(await read($, runs), await $.clock.now(), runLimit)
863}
864
865/** Runs a check to the end. `$.process.run` kills one still going at the time limit and rejects: that is a RunTimeout. */
866async function runToEnd($: Engine, argv: readonly string[], dir: string): Promise<{ exitCode: number; output: string }> {
867 const startedAt = await $.clock.now()
868 const out = await $.process.run(argv, { cwd: dir, timeoutMs: runLimit }).catch(async (error: unknown) => {
869 // It also rejects when the command cannot start, which happens at once.
870 throw Lab.isOverLimit((await $.clock.now()) - startedAt, runLimit) ? timeoutOf() : error
871 })
872 const output = `${out.stdout}\n${out.stderr}`
873 logProcess($, argv, out.exitCode, (await $.clock.now()) - startedAt, output)
874 return { exitCode: out.exitCode, output }
875}
876
877/** A finished process: argv, exit code and duration at `verbose`; its output's tail at `debug`. */
878function logProcess($: Engine, argv: readonly string[], exitCode: number, durationMs: number, output: string): void {
879 logEvent($, 'verbose', 'process', `exit ${exitCode} after ${durationMs}ms`, { argv })
880 logEvent($, 'debug', 'process.output', argv.slice(0, 3).join(' '), { tail: Lab.outputTail(output) })
881}
882
883/**
884 * Runs validate or tsc to the end; streams test so the band fills on real
885 * progress. A stream that cannot start (it rejects its first pull) falls back
886 * to running the tests to the end. A stream still going at the time limit is
887 * stopped, which kills the child, and the run ends as a RunTimeout.
888 */
889async function execute($: Engine, entry: Run, dir: string): Promise<{ exitCode: number; output: string }> {
890 const argv = Lab.argvOf(entry.kind, dir)
891 if (entry.kind !== 'Test') return runToEnd($, argv, dir)
892 let kept = Lab.EMPTY_STREAM
893 let seen = 0
894 let hasStarted = false
895 let isTimedOut = false
896 let timer: Timer | null = null
897 const startedAt = Date.now()
898 try {
899 const stream = $.process.spawn({ argv, cwd: dir })
900 // One shot at the limit: a poll overshoots any limit that isn't a multiple of its period.
901 timer = $.clock.after(runLimit, () => {
902 isTimedOut = true
903 // A stream closed before its end rejects its result (claude-code.d.ts, HookStream); nothing reads it then.
904 stream.result.catch(() => undefined)
905 void stream.return?.(undefined as never)?.catch?.(() => undefined)
906 })
907 for await (const piece of stream) {
908 hasStarted = true
909 kept = Lab.streamPiece(kept, piece.text, piece.stream)
910 if (kept.passed + kept.failed !== seen) {
911 seen = kept.passed + kept.failed
912 await noteProgress($, entry, { passed: kept.passed, failed: kept.failed })
913 }
914 }
915 if (isTimedOut) throw timeoutOf()
916 const ended = await stream.result
917 const output = Lab.streamOutput(kept)
918 logProcess($, argv, ended.code ?? 1, Date.now() - startedAt, output)
919 return { exitCode: ended.code ?? 1, output }
920 } catch (error) {
921 if (isTimedOut) throw timeoutOf()
922 if (hasStarted) throw error
923 // Expected under `claude plugin test`, where process.spawn has no stub.
924 logCaught($, 'execute.spawn', error, 'verbose', { argv, fallback: 'process.run' })
925 return runToEnd($, argv, dir)
926 } finally {
927 timer?.cancel()
928 }
929}
930
931/** Whether a newer run took this run's row (it outlived the limit and the grace): then it must not start or save anything. */
932async function isSuperseded($: Engine, entry: Run): Promise<boolean> {
933 if (Lab.hasRun(await read($, runs), entry)) return false
934 logEvent($, 'normal', 'run', `${entry.mod} ${entry.kind} superseded`, { startedAt: entry.startedAt })
935 return true
936}
937
938/** Runs a check and judges it. One that throws fails: as timed out at its time limit, else as "could not run". */
939async function resultOfRun($: Engine, entry: Run, dir: string, stamp: number): Promise<Lab.RunResult> {
940 const { mod, kind, startedAt } = entry
941 try {
942 const { exitCode, output } = await execute($, entry, dir)
943 const endedAt = await $.clock.now()
944 return Lab.resultOf(kind, exitCode, output, stamp, endedAt - startedAt, endedAt)
945 } catch (error) {
946 const endedAt = await $.clock.now()
947 const summary = error instanceof RunTimeout ? error.message : 'could not run'
948 const result: Lab.RunResult = { kind, ok: false, stampMs: stamp, durationMs: endedAt - startedAt, atMs: endedAt, summary, errors: [String(error).slice(0, 200)] }
949 logCaught($, 'run', error, 'normal', { mod, kind })
950 return result
951 }
952}
953
954/**
955 * Runs one check of `mod` in `modsDir`, the folder its caller judged it in. Its evidence and its
956 * result stay with that folder, even if a /cd moves the scans it triggers elsewhere.
957 */
958async function run($: Engine, mod: string, kind: RunKind, modsDir: string): Promise<void> {
959 if ((await liveRunsOf($)).some(one => one.mod === mod && one.kind === kind)) return
960 const dir = `${modsDir}/${mod}`
961 const typesPath = `${dir}/.claude-plugin/types/tsconfig.json`
962 const hasTypes = kind !== 'Typecheck' || (await exists($, typesPath))
963 if (!hasTypes) {
964 $.ui.toast(`${mod}: type-check needs the engine's types. Load the mod once in a session (/reload-plugins), then press K`)
965 return
966 }
967 const startedAt = await $.clock.now()
968 const last = (await resultsOf($, modsDir))[mod]?.Test?.tests
969 const entry: Run = { mod, kind, startedAt, passed: 0, failed: 0, total: last ? last.passed + last.failed : null }
970 await update($, runs, all => [...all.filter(one => !(one.mod === mod && one.kind === kind)), entry])
971 // From here the row is this run's alone to remove: whatever throws, it goes.
972 let toast = ''
973 try {
974 startClock($)
975 await scan($, false)
976 if (await isSuperseded($, entry)) return
977
978 const facts = await modFactsOf($, modsDir, mod, await marketplaceOf($, modsDir))
979 const stamp = facts?.codeMtimeMs ?? startedAt
980 const codeSig = facts?.codeSig
981 let result = await resultOfRun($, entry, dir, stamp)
982 if (await isSuperseded($, entry)) return
983 if (codeSig !== undefined) result = { ...result, codeSig }
984 logEvent($, 'normal', 'run', `${mod} ${kind} ${result.ok ? 'passed' : 'failed'}`, { durationMs: result.durationMs, summary: result.summary })
985 // A refused write loses this result, but the run still ends and says how it went.
986 const resultsKey = keyOf(RESULTS_KEY, modsDir)
987 await updateStore($, RESULTS_KEY, modsDir, (stored: StoredResults) => ({ ...stored, [mod]: { ...stored[mod], [kind]: result } })).then(
988 () => logEvent($, 'debug', 'store.set', resultsKey, { mod, kind }),
989 (error: unknown) => logCaught($, 'store.set', error, 'normal', { key: resultsKey, mod, kind }),
990 )
991 // A newer run may have taken the row while the write waited its turn. Its later write wins the
992 // store, since the writes are chained, so this result is not the one to announce.
993 if (await isSuperseded($, entry)) return
994 toast = Lab.toastOfRun(mod, result)
995 } catch (error) {
996 // No result came of it (a scan or reading the mod threw): say so, and rescan below so the stage stops reading running.
997 logCaught($, 'run', error, 'normal', { mod, kind })
998 toast = Lab.toastOfRunError(mod, kind, error)
999 } finally {
1000 await update($, runs, all => all.filter(one => !(one.mod === mod && one.kind === kind && one.startedAt === startedAt)))
1001 }
1002 $.ui.toast(toast)
1003 await scan($, true)
1004}
1005
1006/**
1007 * After a turn: rescan (edits may have come from any tool, Bash included), then
1008 * re-run what went stale. Validate first; Test only if Validate passes.
1009 */
1010async function rerunStale($: Engine): Promise<void> {
1011 await scan($, true)
1012 if (!autoRerun) return
1013 // The folder these views were judged in, read with them: each run's scans may move elsewhere.
1014 const verdict = await read($, judged)
1015 const modsDir = verdict.modsDir ?? (await currentModsDir($))
1016 const inFlight = await liveRunsOf($)
1017 for (const view of verdict.views) {
1018 const plan = Lab.rerunPlanOf(view.lights, inFlight.some(one => one.mod === view.name))
1019 if (plan.includes('Validate')) await run($, view.name, 'Validate', modsDir)
1020 const validated = (await resultsOf($, modsDir))[view.name]?.Validate
1021 if (plan.includes('Test') && validated?.ok) await run($, view.name, 'Test', modsDir)
1022 }
1023}
1024
1025function runInBackground($: Engine, mod: string | null, kind: RunKind, modsDir: string): void {
1026 if (!mod || mod === Lab.DEMO_NAME) return
1027 void run($, mod, kind, modsDir).catch((error: unknown) => logCaught($, 'runInBackground', error, 'normal', { mod, kind }))
1028}
1029
1030// ── The pane ──────────────────────────────────────────────────────────────
1031
1032const isPaneOpen = async ($: Engine): Promise<boolean> => (await $.ui.panes()).some(pane => pane.id === PANE)
1033/** Open and drawn: an unasked open on a narrow terminal is open but waits undrawn, and the person's open seats it. */
1034const isPaneShown = async ($: Engine): Promise<boolean> => (await $.ui.panes()).some(pane => pane.id === PANE && pane.isPlaced)
1035
1036async function openPane($: Engine): Promise<void> {
1037 const opened = await $.ui.open(PANE_ARGS)
1038 if (!opened.isPlaced) $.ui.toast(NARROW_TOAST)
1039}
1040
1041/** What a bare /modlab does with the pane; `paneAction` counts a pane waiting undrawn as not listed. */
1042async function paneActionOf($: Engine): Promise<ReturnType<typeof Lab.paneAction>> {
1043 return Lab.paneAction(await $.ui.panes(), PANE)
1044}
1045
1046/**
1047 * Asks for a pane that is a tab behind another to the front, with the keyboard, for a person who asked to see it (#31).
1048 * The request goes out before the first await. A pane that is still a tab behind another afterwards is named in a toast.
1049 */
1050async function bringToFront($: Engine): Promise<void> {
1051 await $.ui.open({ ...PANE_ARGS, focus: true })
1052 $.clock.after(FRONT_CHECK_MS, () => void warnIfBehind($).catch((error: unknown) => logCaught($, 'modlab.front', error)))
1053}
1054
1055async function warnIfBehind($: Engine): Promise<void> {
1056 if ((await paneActionOf($)) === 'show') $.ui.toast(STILL_BEHIND_TOAST)
1057}
1058
1059/** An open for a command that names the pane: a tab behind another comes to the front, any other pane is opened as before. */
1060async function openOrFront($: Engine): Promise<void> {
1061 if ((await paneActionOf($)) === 'show') void bringToFront($).catch((error: unknown) => logCaught($, 'modlab.front', error))
1062 else await openPane($)
1063}
1064
1065/**
1066 * Opens the pane from the hook of the person's command, before it returns: an open after that is "unasked", and the
1067 * engine leaves it undrawn below 144 columns (#90).
1068 */
1069async function showPane($: Engine): Promise<void> {
1070 await clearNarrowWarning($)
1071 await openPane($)
1072}
1073
1074/**
1075 * Opens the pane for a typed build or edit skill, unless it is shown; a failure is logged and never stops the skill.
1076 * It starts no scan: the skill's first report scans, and one that joined a scan started here would wait out an extra
1077 * pass against its 10 s budget (PR #93 review, Codex).
1078 */
1079async function openForSkill($: Engine, command: string): Promise<void> {
1080 try {
1081 if (!(await isPaneShown($))) await showPane($)
1082 } catch (error) {
1083 logCaught($, 'command.skill', error, 'normal', { command })
1084 }
1085}
1086
1087/** Selects `name` in the pane, out of any README. */
1088async function selectMod($: Engine, name: string): Promise<void> {
1089 await update($, selected, () => name)
1090 await update($, readme, () => null)
1091}
1092
1093async function startDemo($: Engine): Promise<void> {
1094 const now = await $.clock.now()
1095 lastTickMs = now
1096 await update($, frame, current => ({ ...current, now }))
1097 await update($, demoStartedAt, () => now)
1098 await update($, selected, () => Lab.DEMO_NAME)
1099 await update($, readme, () => null)
1100 startClock($)
1101}
1102
1103async function stopDemo($: Engine): Promise<void> {
1104 await update($, demoStartedAt, () => null)
1105 await update($, selected, current => (current === Lab.DEMO_NAME ? null : current))
1106 await scan($, false)
1107}
1108
1109/** D starts the demo; D again while it runs stops it. */
1110async function toggleDemo($: Engine): Promise<void> {
1111 if ((await read($, demoStartedAt)) === null) await startDemo($)
1112 else await stopDemo($)
1113}
1114
1115async function showReadme($: Engine, mod: string | null, modsDir: string): Promise<void> {
1116 if (!mod || mod === Lab.DEMO_NAME) return
1117 const text = await readText($, `${modsDir}/${mod}/README.md`)
1118 if (text === null) {
1119 $.ui.toast(`${mod} has no README yet`)
1120 return
1121 }
1122 await update($, readme, () => ({ name: mod, text, isStale: factsByMod.get(mod)?.isReadmeStale ?? false }))
1123}
1124
1125async function moveSelection($: Engine, by: number): Promise<void> {
1126 const names = (await shownViews($)).map(view => view.name)
1127 if (!names.length) return
1128 const current = names.indexOf((await read($, selected)) ?? '')
1129 const nextAt = (Math.max(0, current) + by + names.length) % names.length
1130 await update($, selected, () => names[nextAt] ?? null)
1131 if (await read($, readme)) await showReadme($, names[nextAt] ?? null, await shownModsDir($))
1132}
1133
1134async function fillFix($: Engine, view: ModView, modsDir: string): Promise<void> {
1135 const failed = (await resultsOf($, modsDir))[view.name]?.Test?.tests?.failed ?? 1
1136 const path = Lab.displayPathOf(`${modsDir}/${view.name}`, await cwdOf($))
1137 await $.prompt.fill({ text: Lab.fixPromptOf(view.name, view.failedStage ?? 'Test', view.errors, failed, path) })
1138}
1139
1140async function warnNarrowOnce($: Engine): Promise<void> {
1141 if (await read($, hasWarnedNarrow)) return
1142 await update($, hasWarnedNarrow, () => true)
1143 $.ui.toast(NARROW_TOAST)
1144}
1145
1146async function clearNarrowWarning($: Engine): Promise<void> {
1147 if (await read($, hasWarnedNarrow)) await update($, hasWarnedNarrow, () => false)
1148}
1149
1150// ── Hooks ─────────────────────────────────────────────────────────────────
1151
1152// ── /mod-builder config ───────────────────────────────────────────────────
1153
1154/** `/mod-builder config [list]` lists the options; `/mod-builder config <option> <value>` changes one. */
1155async function configure($: Engine, words: string[]): Promise<string> {
1156 const command = Lab.parseConfigCommand(words)
1157 if (command.kind === 'error') return command.text
1158 if (command.kind === 'set') {
1159 const why = await setOption($, command.name, command.value)
1160 if (why) return `Could not change ${command.name}: ${why}`
1161 }
1162 // What `default` means is only needed while modsDir is empty, or when it is being set.
1163 const needsDefault = !configuredDir || (command.kind === 'set' && command.name === 'modsDir')
1164 const defaultDir = needsDefault ? await defaultModsDir($) : ''
1165 // A build's kept folder is what an empty modsDir watches now (#92).
1166 const kept = !configuredDir && pin ? Lab.keptPinOf(pin, await rootOf($)) : null
1167 const values: Lab.OptionValues = {
1168 logging: logLevel,
1169 autoRerun,
1170 autoOpen,
1171 modsDir: configuredDir,
1172 modsDirShown: Lab.shortPath(configuredDir ? Lab.normalizePath(configuredDir) : defaultDir),
1173 testTimeoutMinutes: Lab.limitMinutesOf(runLimit),
1174 ...(kept ? { pinnedShown: Lab.shortPath(kept.modsDir) } : {}),
1175 }
1176 // The set reloads the plugin rather than changing this module's values, so show the new one.
1177 if (command.kind === 'set') Object.assign(values, Lab.valuesAfterSet(command.name, command.value, defaultDir))
1178 const shown = (value: string | boolean | number): string =>
1179 typeof value === 'boolean' ? (value ? 'on' : 'off') : typeof value === 'number' ? String(value) : value || 'default'
1180 const head = command.kind === 'set' ? `${command.name} is now ${shown(command.value)}.\n` : ''
1181 return head + Lab.configListText(values, logFile)
1182}
1183
1184/**
1185 * Writes one option through this plugin's own `/config` row: '' once written, else why not.
1186 * Changing a plugin's options reloads it (types), which empties this module's log buffer, so
1187 * the line about the change is written to the file before the set.
1188 */
1189async function setOption($: Engine, name: Lab.OptionName, value: string | boolean | number): Promise<string> {
1190 // A plugin option's row is keyed `<plugin>.<field>`; its owner names the install, e.g.
1191 // `mod-builder@claudemod` or `mod-builder@inline` under --plugin-dir (seen live, 2026-10-13).
1192 const key = `${$.plugin.name}.${name}`
1193 const row = (await $.config.list()).find(r => r.key === key && Lab.isOwnRow((r.provider as { plugin?: string } | undefined)?.plugin, $.plugin.name))
1194 if (!row) return `no /config row ${key} in this session (headless sessions list no plugin options). Change it in /config, or /plugin → mod-builder → options.`
1195 logEvent($, 'normal', 'config', `${name} changing`, { value })
1196 await flushLog($)
1197 const result = await $.config.set({ key: row.key, value })
1198 // A refusal doesn't reload the plugin, so this module can still record it.
1199 if (result.deny) logEvent($, 'normal', 'config', `${name} change refused`, { value, reason: result.deny })
1200 return result.deny ?? ''hooks/mod-builder-logic.ts 1902 lines1/**
2 * Mod Lab's deterministic core: every rule that needs no `$`.
3 *
4 * register.tsx gathers facts from disk and process exit codes, hands them here,
5 * and draws what comes back. Nothing in this file reads the clock, the disk or
6 * the engine, so every rule is unit-tested in tests/mod-builder-logic.test.ts.
7 */
8
9import type { Gate, Light, ModView, Pin, Reach, Reported, Run, RunKind, Stage, Tone } from '../types'
10
11export type { Gate, Light, ModView, Pin, Reach, Reported, Run, RunKind, Stage, Tone }
12
13export const STAGES = [
14 'Spec',
15 'Scaffold',
16 'Logic',
17 'Register',
18 'Validate',
19 'Test',
20 'README',
21 'Share',
22] as const satisfies readonly Stage[]
23
24/** What register.tsx reads off disk for one mod folder. */
25export type FileFacts = {
26 name: string
27 hasSpec: boolean
28 /** SPEC.md still holds an unfilled `<placeholder>` outside code. */
29 specHasPlaceholder: boolean
30 hasManifest: boolean
31 hasHooksJson: boolean
32 /** hooks/ holds a module other than register.ts(x). */
33 hasLogic: boolean
34 /** tests/ holds at least one *.test.ts(x). */
35 hasTests: boolean
36 hasRegister: boolean
37 hasReadme: boolean
38 /** README.md has a "What it reaches" heading. */
39 readmeHasReaches: boolean
40 /** The marketplace beside the mods folder lists this mod. */
41 isListed: boolean
42 /**
43 * Newest mtime of what validate and test read: the manifest, hooks/, tests/, types/, agents/,
44 * commands/ and skills/ with their subfolders, and the root .mcp.json.
45 */
46 codeMtimeMs: number
47 /**
48 * A signature of every code file's path and mtime (the files `codeMtimeMs` covers, subfolders
49 * up to 3 deep): changes on an edit, an add, a delete, a rename or a move between folders.
50 */
51 codeSig: string
52 /** Oldest and newest mtime of anything in the folder, for the build span. */
53 firstMtimeMs: number
54 lastMtimeMs: number
55 /** From SPEC.md's slot table, when present. */
56 archetype: string | null
57 builtOn: string | null
58 /** From plugin.json, when present. */
59 version: string | null
60 description: string | null
61 /** README.md is older than the newest code. */
62 isReadmeStale: boolean
63 /** When SPEC.md, the newest logic or test file (subfolders included), and README.md were last saved (0 when absent). */
64 specMtimeMs: number
65 logicMtimeMs: number
66 readmeMtimeMs: number
67 /**
68 * The logic modules and test files (subfolders included) by path and mtime: a delete or a rename changes it,
69 * which no mtime shows. Null when a folder under hooks/ or tests/ couldn't be listed: what it holds is unknown.
70 */
71 logicSig: string | null
72 /** `quickSigOf` this read's listings: what the stats-only check after a Bash batch compares (Change 0.2.24). */
73 quickSig: string
74 /** The version the marketplace lists this mod at, when it does. */
75 listedVersion: string | null
76}
77
78export type ValidateReport = {
79 ok: boolean
80 hooks: string[]
81 calls: string[]
82 gates: Gate[]
83 errors: string[]
84 warnings: string[]
85}
86
87export type TestReport = {
88 ok: boolean
89 passed: number
90 failed: number
91 durationMs: number | null
92 failures: string[]
93}
94
95/** One finished run, kept in `$.store` per mod. */
96export type RunResult = {
97 kind: RunKind
98 ok: boolean
99 /** The mod's codeMtimeMs when the run started; newer code makes it stale. */
100 stampMs: number
101 /** The mod's codeSig when the run started; any difference makes it stale (older results lack it). */
102 codeSig?: string
103 /** One line for the row and the toast. */
104 summary: string
105 /** The first few error lines, for the detail panel and Fix with Claude. */
106 errors: string[]
107 /** How long the run took. */
108 durationMs?: number
109 /** When the run finished; judged against an edit's generation. */
110 atMs?: number
111 validate?: ValidateReport
112 /** Test counts, for "12 tests · clean" and the done line. */
113 tests?: { passed: number; failed: number }
114}
115
116export type Results = Partial<Record<RunKind, RunResult>>
117
118// ── Stages ────────────────────────────────────────────────────────────────
119
120/**
121 * An edit under way (a build generation): when it began, and the version and the logic and test files
122 * (`logicSig`) it began from. A `logicSig` that is absent or null leaves Logic to the mtime rule.
123 */
124export type Edit = { since: number; fromVersion: string | null; logicSig?: string | null }
125
126/**
127 * The eight lights of one mod, from the disk, the stored runs and what runs
128 * now. The disk and exit codes decide passed or failed; a report from the
129 * model only ever adds `running` (SPEC non-negotiable 2).
130 */
131export function lightsOf(
132 facts: FileFacts,
133 results: Results,
134 running: readonly RunKind[],
135 reported: Reported | null,
136 edit: Edit | null = null,
137): Light[] {
138 // During an edit, evidence older than the edit's start is stale:
139 // it passed before, and has to be redone for this change.
140 const sinceMs = edit?.since ?? null
141 const fromVersion = edit?.fromVersion ?? null
142 const fromLogicSig = edit?.logicSig ?? null
143 const isOld = (atMs: number): boolean => sinceMs !== null && atMs < sinceMs
144 const runLight = (kind: 'Validate' | 'Test'): Light => {
145 if (running.includes(kind)) return 'running'
146 const result = results[kind]
147 if (!result) return 'pending'
148 const isChanged = result.codeSig !== undefined ? result.codeSig !== facts.codeSig : result.stampMs < facts.codeMtimeMs
149 if (isChanged || isOld(result.atMs ?? 0)) return 'stale'
150 return result.ok ? 'passed' : 'failed'
151 }
152 const fileLight = (isDone: boolean, savedMs?: number): Light =>
153 !isDone ? 'pending' : savedMs !== undefined && isOld(savedMs) ? 'stale' : 'passed'
154 // A delete or a rename saves no file, so a logic or test file changed since the edit began counts too:
155 // Logic is then judged with no mtime, which is never old.
156 // A signature that couldn't be read, then or now, shows nothing either way.
157 const isLogicChanged = fromLogicSig !== null && facts.logicSig !== null && fromLogicSig !== facts.logicSig
158 // During an edit, Share needs a new version (not the one the edit started from) that the marketplace lists.
159 const isReShared =
160 sinceMs === null ||
161 (facts.listedVersion !== null && facts.listedVersion === facts.version && (fromVersion === null || facts.version !== fromVersion))
162
163 const lights: Light[] = [
164 fileLight(facts.hasSpec && !facts.specHasPlaceholder, facts.specMtimeMs),
165 fileLight(facts.hasManifest && facts.hasHooksJson),
166 fileLight(facts.hasLogic && facts.hasTests, isLogicChanged ? undefined : facts.logicMtimeMs),
167 fileLight(facts.hasRegister),
168 runLight('Validate'),
169 runLight('Test'),
170 fileLight(facts.hasReadme && facts.readmeHasReaches, facts.readmeMtimeMs),
171 !facts.isListed ? 'pending' : isReShared ? 'passed' : 'stale',
172 ]
173
174 // What the skill says it is doing now always shows, even on a stage that
175 // passed before. A report never passes a stage: the disk does.
176 if (reported?.status === 'running') {
177 const at = STAGES.indexOf(reported.stage)
178 if (lights[at] !== 'failed') lights[at] = 'running'
179 }
180 return lights
181}
182
183/**
184 * Whether a `Spec running` report starts a new build generation: the mod has
185 * been built before (its Spec stage already passed), so this is an edit.
186 */
187export function startsGeneration(report: Reported, lights: readonly Light[] | null): boolean {
188 return report.stage === 'Spec' && report.status === 'running' && lights !== null && lights[0] !== 'pending'
189}
190
191/** The first failed stage, else the first running, else the first not passed. */
192export function focusStageOf(lights: readonly Light[]): { stage: Stage; light: Light } | null {
193 for (const want of ['failed', 'running'] as const) {
194 const at = lights.indexOf(want)
195 if (at >= 0) return { stage: STAGES[at]!, light: want }
196 }
197 const at = lights.findIndex(light => light !== 'passed')
198 return at >= 0 ? { stage: STAGES[at]!, light: lights[at]! } : null
199}
200
201/** What a run in flight is doing, in a few words: `validating`, `running tests · 7 of 12`. */
202export function runningTextOf(run: Pick<Run, 'kind' | 'passed' | 'failed' | 'total'>): string {
203 if (run.kind === 'Validate') return 'validating'
204 if (run.kind === 'Typecheck') return 'type-checking'
205 const done = run.passed + run.failed
206 if (run.total) return `running tests · ${done} of ${run.total}`
207 return done ? `running tests · ${done} so far` : 'running tests'
208}
209
210/** `12 tests · clean`: the quiet status of a green mod. */
211export function cleanTextOf(results: Results): string {
212 const tests = results.Test?.tests
213 const count = tests ? plural(tests.passed, 'test') : 'tests'
214 return `${count} · ${results.Validate?.ok ? 'clean' : 'passing'}`
215}
216
217/** The row's one-line status and its tone, in the design's words. */
218export function statusOf(
219 lights: readonly Light[],
220 results: Results,
221 reported: Reported | null,
222 runs: readonly Run[],
223 isFresh: boolean,
224): { text: string; tone: Tone } {
225 const run = runs[0]
226 if (run) return { text: runningTextOf(run), tone: 'text' }
227 const focus = focusStageOf(lights)
228 if (!focus) return isFresh ? { text: 'ready to share', tone: 'success' } : { text: cleanTextOf(results), tone: 'dim' }
229 const { stage, light } = focus
230 if (light === 'failed') {
231 if (stage === 'Test') return { text: results.Test?.summary ?? 'tests failing', tone: 'error' }
232 return { text: `validate · ${results.Validate?.summary ?? 'failed'}`, tone: 'error' }
233 }
234 if (light === 'running') {
235 const note = reported?.stage === stage && reported.note ? reported.note : `${stage.toLowerCase()} in progress`
236 return { text: note, tone: 'text' }
237 }
238 if (light === 'stale') {
239 if (stage === 'Validate' || stage === 'Test') return { text: `files changed · re-run ${stage}`, tone: 'warn' }
240 if (stage === 'Share') return { text: 'edit · bump the version and re-list it', tone: 'warn' }
241 return { text: `edit · update ${stage} for this change`, tone: 'warn' }
242 }
243 return { text: `next: ${stage}`, tone: 'dim' }
244}
245
246/**
247 * What to re-run for a mod at the end of a turn: Validate when Validate or
248 * Test has gone stale (the code changed after they passed), then Test. Nothing
249 * while a run for that mod is already in flight.
250 */
251export function rerunPlanOf(lights: readonly Light[], isRunning: boolean): RunKind[] {
252 if (isRunning) return []
253 const validate = lights[STAGES.indexOf('Validate')]
254 const test = lights[STAGES.indexOf('Test')]
255 // A Validate that failed on the current code blocks Test; re-running it changes nothing.
256 if (validate === 'stale') return test === 'pending' ? ['Validate'] : ['Validate', 'Test']
257 if ((validate === 'passed' || validate === 'pending') && test === 'stale') return ['Test']
258 return []
259}
260
261/** Every light green. */
262export function isGreen(lights: readonly Light[]): boolean {
263 return lights.length === STAGES.length && lights.every(light => light === 'passed')
264}
265
266// ── Reading files ─────────────────────────────────────────────────────────
267
268/**
269 * The start of a line that ends a paragraph: a blank line, or one that opens an
270 * ATX heading, a list item or a block quote. `$` is the end of the input (no
271 * `m` flag). A heading or quote takes at most three spaces of indent, as in
272 * CommonMark; a list item takes any, since nested items sit deeper. Any `N.`
273 * counts as an item, though CommonMark lets only `1.` interrupt a paragraph.
274 */
275const BLOCK_BREAK = String.raw`(?:[ \t]*(?:\r?\n|$|[-*+][ \t]|\d{1,9}[.)][ \t])| {0,3}(?:#{1,6}(?:[ \t]|$)|>))`
276
277/**
278 * An escaped `\` or backtick, which opens no span, or an inline code span: it
279 * may wrap over lines, but not into another block (CommonMark).
280 */
281const ESCAPE_OR_SPAN = new RegExp(String.raw`\\[\\\x60]|\x60(?:[^\x60\n]|\n(?!${BLOCK_BREAK}))*\x60`, 'g')
282
283/**
284 * Whether a SPEC still holds a `<placeholder>`: an angle-bracketed phrase
285 * outside fenced code, inline code and HTML comments.
286 */
287export function hasPlaceholder(spec: string): boolean {
288 const prose = spec
289 .replace(/<!--[\s\S]*?-->/g, '')
290 .replace(/```[\s\S]*?```/g, '')
291 .replace(ESCAPE_OR_SPAN, m => (m.startsWith('\\') ? m : ''))
292 return /<(?![/!])[^<>\n]{1,120}>/.test(prose)
293}
294
295/**
296 * The SPEC's slot table as `slot → value`: rows of `| slot | kind | value | … |`,
297 * the slot cut at its first space or parenthesis, the value with code ticks dropped.
298 */
299export function slotsOf(spec: string): Record<string, string> {
300 const slots: Record<string, string> = {}
301 for (const line of spec.split('\n')) {
302 const cells = line.split('|').map(cell => cell.trim())
303 if (cells.length < 5 || !/^(REQUIRED|HOUSE|ARCH)/.test(cells[2] ?? '')) continue
304 const slot = (cells[1] ?? '').split(/[\s(]/)[0]!.toLowerCase()
305 const value = (cells[3] ?? '').replace(/`/g, '').trim()
306 if (slot && value) slots[slot] = value
307 }
308 return slots
309}
310
311/** Whether a README has its "What it reaches" heading. */
312export function hasReachesHeading(readme: string): boolean {
313 return /^#{1,6}\s+what it reaches\b/im.test(readme)
314}
315
316/** Whether a README is finished: the heading is there and no template `<!-- … -->` comment is left. */
317export function isReadmeDone(readme: string): boolean {
318 return hasReachesHeading(readme) && !/<!--/.test(readme)
319}
320
321type MarketplaceEntry = { name?: unknown; source?: unknown; version?: unknown }
322
323/** The marketplace entry for a mod: by name, or by a `…/<name>` source. Null when unlisted or unreadable. */
324export function findEntry(marketplace: string, name: string): MarketplaceEntry | null {
325 try {
326 const parsed = JSON.parse(marketplace) as { plugins?: MarketplaceEntry[] }
327 return (
328 (parsed.plugins ?? []).find(
329 plugin =>
330 plugin.name === name ||
331 (typeof plugin.source === 'string' && plugin.source.replace(/\/+$/, '').endsWith(`/${name}`)),
332 ) ?? null
333 )
334 } catch {
335 return null
336 }
337}
338
339/** The version a marketplace.json lists the mod at, or null when unlisted or unversioned. */
340export function listedVersionOf(marketplace: string, name: string): string | null {
341 const version = findEntry(marketplace, name)?.version
342 return typeof version === 'string' ? version : null
343}
344
345/** Whether a marketplace.json lists the mod by name or by a `…/<name>` source. */
346export function isListedIn(marketplace: string, name: string): boolean {
347 return findEntry(marketplace, name) !== null
348}
349
350/** Whether a hooks/ file name is a module other than the register entry. */
351export function isLogicModule(file: string): boolean {
352 return /\.(m|c)?(t|j)sx?$/.test(file) && !/^register\./.test(file) && !/\.d\.ts$/.test(file)
353}
354
355/** Whether a tests/ file name is one `claude plugin test` collects. */
356export function isTestFile(file: string): boolean {
357 return /\.test\.tsx?$/.test(file)
358}
359
360/** Whether a file, named by its path from the mod folder, is logic under hooks/ or a test under tests/, at any depth. Freshness only: existence stays top-level. */
361export function isLogicOrTestPath(path: string): boolean {
362 const base = path.slice(path.lastIndexOf('/') + 1)
363 if (path.startsWith('hooks/')) return isLogicModule(base)
364 return path.startsWith('tests/') && isTestFile(base)
365}
366
367// ── Parsing what the commands print ───────────────────────────────────────
368
369/** Splits on commas outside braces and parentheses. */
370export function splitTop(list: string): string[] {
371 const parts: string[] = []
372 let depth = 0
373 let part = ''
374 for (const char of list) {
375 if (char === '{' || char === '(') depth += 1
376 if (char === '}' || char === ')') depth = Math.max(0, depth - 1)
377 if (char === ',' && depth === 0) {
378 if (part.trim()) parts.push(part.trim())
379 part = ''
380 } else {
381 part += char
382 }
383 }
384 if (part.trim()) parts.push(part.trim())
385 return parts
386}
387
388type ValidateSection = {
389 errors?: { path?: string; message?: string }[]
390 warnings?: { path?: string; message?: string }[]
391 notes?: string[]
392 gatingHooks?: { hook?: string; hasCatch?: boolean }[]
393}
394
395type ValidateJson = {
396 success?: boolean
397 manifest?: ValidateSection
398 contents?: ValidateSection[]
399}
400
401/** `claude plugin validate --json` output (and its exit code) → a report. */
402export function parseValidate(stdout: string, exitCode: number): ValidateReport {
403 let json: ValidateJson
404 try {
405 json = JSON.parse(stdout.slice(Math.max(0, stdout.indexOf('{')))) as ValidateJson
406 } catch {
407 return { ok: false, hooks: [], calls: [], gates: [], errors: nonBlankLines(stdout).slice(0, 3), warnings: [] }
408 }
409 const sections = [json.manifest, ...(json.contents ?? [])].filter(
410 (section): section is ValidateSection => section !== undefined,
411 )
412 const hooks: string[] = []
413 const calls: string[] = []
414 const gates: Gate[] = []
415 const errors: string[] = []
416 const warnings: string[] = []
417 for (const section of sections) {
418 for (const note of section.notes ?? []) {
419 const hooked = note.match(/\bhooks: (.*)$/)
420 if (hooked) hooks.push(...splitTop(hooked[1]!))
421 const called = note.match(/\bcalls: (.*)$/)
422 if (called && called[1] !== 'nothing on $') {
423 calls.push(...splitTop(called[1]!).map(call => call.replace(/\s*\(via .*\)$/, '')))
424 }
425 }
426 for (const gate of section.gatingHooks ?? []) {
427 if (gate.hook) gates.push({ hook: gate.hook, hasCatch: gate.hasCatch === true })
428 }
429 for (const error of section.errors ?? []) errors.push(`${error.path ?? ''}: ${error.message ?? ''}`)
430 for (const warning of section.warnings ?? []) {
431 warnings.push(`${warning.path ?? ''}: ${warning.message ?? ''}`)
432 }
433 }
434 return {
435 ok: exitCode === 0 && json.success !== false,
436 hooks: [...new Set(hooks)],
437 calls: [...new Set(calls)],
438 gates,
439 errors,
440 warnings,
441 }
442}
443
444/** `claude plugin test` output (bun's reporter, with stderr) and its exit code → a report. */
445export function parseTest(output: string, exitCode: number): TestReport {
446 const count = (word: string): number =>
447 Number(output.match(new RegExp(`^\\s*(\\d+) ${word}\\s*$`, 'm'))?.[1] ?? 0)
448 const time = output.match(/^Ran \d+ tests? across .*\[(\d+(?:\.\d+)?)(ms|s)\]\s*$/m)
449 const durationMs = time ? Math.round(Number(time[1]) * (time[2] === 's' ? 1000 : 1)) : null
450 const lines = output.split('\n')
451 const failures: string[] = []
452 lines.forEach((line, at) => {
453 if (!line.startsWith('(fail) ')) return
454 failures.push(line.slice(7).replace(/\s*\[[\d.]+m?s\]$/, ''))
455 const detail = lines
456 .slice(at + 1, at + 3)
457 .map(next => next.trim())
458 .find(Boolean)
459 if (detail && !detail.startsWith('(')) failures.push(` ${detail}`)
460 })
461 // Exits before the runner starts (no tests, bad folder, corrupt manifest) print one stderr line and no `(fail)`.
462 if (exitCode !== 0 && !failures.length) failures.push(...nonBlankLines(output).slice(-3))
463 const failed = count('fail')
464 return {
465 ok: exitCode === 0 && failed === 0,
466 passed: count('pass'),
467 failed,
468 durationMs,
469 failures: failures.slice(0, 6),
470 }
471}
472
473/** `tsc -p` output → its error lines, each cut to `file(line,col): message`; none means clean. */
474export function parseTsc(stdout: string): string[] {
475 return stdout
476 .split('\n')
477 .filter(line => /error TS\d+/.test(line))
478 .map(line => line.replace(/^.*?([^/\\]+\.tsx?\(\d+,\d+\))/, '$1').trim())
479}
480
481
482/** A finished run's one-line summary. */
483export function summaryOfRun(
484 kind: RunKind,
485 ok: boolean,
486 detail: { validate?: ValidateReport; test?: TestReport; tscErrors?: readonly string[] },
487): string {
488 if (kind === 'Validate' && detail.validate) {
489 const v = detail.validate
490 if (!ok) return plural(Math.max(1, v.errors.length), 'problem')
491 const gates = v.gates.length ? ` · ${plural(v.gates.length, 'gate')}` : ''
492 return `clean · ${plural(v.hooks.length, 'hook')}${gates}`
493 }
494 if (kind === 'Test' && detail.test) {
495 const t = detail.test
496 if (!ok) return t.failed === 0 ? 'tests did not run' : `${plural(t.failed, 'test')} failing`
497 const time = t.durationMs === null ? '' : ` in ${(t.durationMs / 1000).toFixed(1)}s`
498 return `${plural(t.passed, 'test')} passed${time}`
499 }
500 if (kind === 'Typecheck') {
501 return ok ? 'types clean' : plural(Math.max(1, detail.tscErrors?.length ?? 0), 'type error')
502 }
503 return ok ? 'passed' : 'failed'
504}
505
506/** What a mod reaches, grouped from validate's `calls:` list. */
507export function reachesOf(calls: readonly string[]): Reach[] {
508 const of = (noun: string): string => {
509 const methods = calls.filter(call => call.startsWith(`$.${noun}.`)).map(call => call.slice(noun.length + 3))
510 return methods.length ? methods.join(', ') : 'none'
511 }
512 return [
513 { label: 'processes', value: of('process') },
514 { label: 'files', value: of('fs') },
515 { label: 'network', value: of('http') },
516 { label: 'model', value: of('model') },
517 { label: 'mcp', value: of('mcp') },
518 ]
519}
520
521// ── Text ──────────────────────────────────────────────────────────────────
522
523const plural = (n: number, word: string): string => `${n} ${word}${n === 1 ? '' : 's'}`
524const nonBlankLines = (text: string): string[] => text.split('\n').map(line => line.trim()).filter(Boolean)
525
526/** `0:42`, `12:05`, `3h`, `2d`; an empty string under a second. */
527export function durationOf(ms: number): string {
528 if (!(ms >= 1000)) return ''
529 const seconds = Math.floor(ms / 1000)
530 if (seconds < 3600) return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`
531 if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`
532 return `${Math.floor(seconds / 86400)}d`
533}
534
535/** Like durationOf, but `0:00` rather than empty: for clocks that must always show. */
536export function clockOf(ms: number): string {
537 return durationOf(ms) || '0:00'
538}
539
540export type Counts = { mods: number; green: number; building: number; failing: number; stale: number }
541
542export function countsOf(views: readonly ModView[]): Counts {
543 return {
544 mods: views.length,
545 green: views.filter(view => isGreen(view.lights)).length,
546 building: views.filter(view => view.lights.includes('running')).length,
547 failing: views.filter(view => view.lights.includes('failed')).length,
548 stale: views.filter(view => view.lights.includes('stale')).length,
549 }
550}
551
552/** The summary's parts, joined in the pane by a dim ` · `; counts of zero are left out. */
553export function summaryPartsOf(counts: Counts): string[] {
554 if (counts.mods === 0) return ['0 mods']
555 return [
556 plural(counts.mods, 'mod'),
557 counts.green ? `${counts.green} green` : '',
558 counts.building ? `${counts.building} building` : '',
559 counts.failing ? `${counts.failing} failing` : '',
560 counts.stale ? `${counts.stale} stale` : '',
561 ].filter(Boolean)
562}
563
564/** `3 mods · 2 green · 1 building`. */
565export function summaryOf(counts: Counts): string {
566 return counts.mods === 0 ? 'no mods yet' : summaryPartsOf(counts).join(' · ')
567}
568
569/** Letter-spaced text: `mod lab` → `M O D L A B`. */
570export function spaced(text: string): string {
571 return text
572 .toUpperCase()
573 .split(' ')
574 .map(word => word.split('').join(' '))
575 .join(' ')
576}
577
578/**
579 * The masthead's state word and its tone. While building, `dot` is the `●` that
580 * pulses on its own (the letters never move).
581 */
582export function mastheadOf(counts: Counts): { dot: boolean; word: string; tone: Tone } {
583 if (counts.building) return { dot: true, word: spaced('building'), tone: 'success' }
584 if (counts.failing) return { dot: false, word: spaced(`${counts.failing} failing`), tone: 'error' }
585 if (counts.mods && counts.green === counts.mods) return { dot: false, word: spaced('all green'), tone: 'success' }
586 return { dot: false, word: spaced('standing by'), tone: 'dim' }
587}
588
589/** The building `●` toggles dimColor every 4 ticks (1 Hz at 250 ms). */
590export function isPulseDim(frame: number): boolean {
591 return Math.floor(frame / 4) % 2 === 1
592}
593
594/** The status-line badge; undefined clears it (no mods). Plain text: the host does not colour it. */
595export function badgeOf(counts: Counts): string | undefined {
596 if (counts.mods === 0) return undefined
597 const head = `◆ ${plural(counts.mods, 'mod')}`
598 if (counts.building) return `${head} · ${counts.building} building`
599 if (counts.failing) return `${head} · ${counts.failing} failing`
600 if (counts.green === counts.mods) return `${head} · all green`
601 return `${head} · ${counts.mods - counts.green} in progress`
602}
603
604/** Under 34 columns nothing is drawn (and the too-narrow toast fires once). */
605export type Layout = 'full' | 'medium' | 'compact' | 'none'
606
607export function layoutOf(bodyColumns: number): Layout {
608 if (bodyColumns >= 60) return 'full'
609 if (bodyColumns >= 40) return 'medium'
610 if (bodyColumns >= 34) return 'compact'
611 return 'none'
612}
613
614/** One drawn cell run: a glyph or word with its colour role, bold and dimColor. */
615export type Mark = { text: string; tone: Tone; bold?: boolean; dim?: boolean }
616
617/** A light's glyph at an animation frame. Running cycles ◐ · ◐ dim · ○, all accent. */
618export function lightMarkOf(light: Light, frame = 0): Mark {
619 if (light === 'passed') return { text: '●', tone: 'success' }
620 if (light === 'failed') return { text: '✕', tone: 'error', bold: true }
621 if (light === 'stale') return { text: '◌', tone: 'warn' }
622 if (light === 'pending') return { text: '○', tone: 'dim' }
623 const at = frame % 3
624 return at === 1 ? { text: '◐', tone: 'accent', dim: true } : { text: at === 2 ? '○' : '◐', tone: 'accent', bold: true }
625}
626
627/**
628 * The column header above the lights: one stage number per light, at the
629 * lights' pitch of 2 (digit + space). The number over the selected mod's
630 * failed, else running, else stale stage lights up; the rest are dim. The detail panel's
631 * track carries the same numbers beside the stage names, as the key.
632 */
633export function columnsOf(lights: readonly Light[]): Mark[] {
634 const first = (light: Light): number => lights.indexOf(light)
635 const focus = [first('failed'), first('running'), first('stale')].find(at => at >= 0) ?? -1
636 const tone: Tone = lights[focus] === 'failed' ? 'error' : lights[focus] === 'stale' ? 'warn' : 'accent'
637 return STAGES.map((_, at) =>
638 at === focus ? { text: `${at + 1} `, tone, bold: true } : { text: `${at + 1} `, tone: 'dim' },
639 )
640}
641
642/**
643 * The pipeline track: each stage name in its light's colour, then its
644 * connector. After a passed stage whose next has started: `━` success. After
645 * a running stage: `┅ ━ ┄` by frame, accent. Otherwise `┄` dim.
646 */
647export function trackOf(lights: readonly Light[], frame = 0): { num: Mark; name: Mark; joint: Mark | null }[] {
648 return STAGES.map((stage, at) => {
649 const light = lights[at] ?? 'pending'
650 const next = lights[at + 1]
651 const name: Mark =
652 light === 'passed'
653 ? { text: stage, tone: 'success' }
654 : light === 'running'
655 ? { text: stage, tone: 'accent', bold: true }
656 : light === 'failed'
657 ? { text: stage, tone: 'error', bold: true }
658 : light === 'stale'
659 ? { text: stage, tone: 'warn' }
660 : { text: stage, tone: 'dim' }
661 const num: Mark = { text: `${at + 1} `, tone: 'dim', dim: true }
662 if (at === STAGES.length - 1) return { num, name, joint: null }
663 let joint: Mark = { text: ' ┄ ', tone: 'dim', dim: true }
664 if (light === 'running') joint = { text: ` ${['┅', '━', '┄'][frame % 3]} `, tone: 'accent' }
665 else if (light === 'passed' && next !== undefined && next !== 'pending') joint = { text: ' ━ ', tone: 'success' }
666 return { num, name, joint }
667 })
668}
669
670/** A 15-cell bar filled to `fraction` (0..1), for real progress only. */
671export function barOf(fraction: number, width = 15): { filled: string; empty: string } {
672 const cells = Math.max(0, Math.min(width, Math.round(width * fraction)))
673 return { filled: '━'.repeat(cells), empty: '░'.repeat(width - cells) }
674}
675
676/**
677 * The draft `[F] Fix with Claude` puts in the prompt box: plain words, the
678 * first failure quoted from the error box. `path` is the mod's folder as the
679 * session should read it (see `displayPathOf`).
680 */
681export function fixPromptOf(name: string, stage: Stage, errors: readonly string[], failedCount: number, path: string): string {
682 // A Test with no failing test never ran: the errors are the runner's own line, not a test.
683 const didNotRun = stage === 'Test' && failedCount === 0
684 const what = didNotRun
685 ? 'the Test run'
686 : stage === 'Test'
687 ? `the ${failedCount === 1 ? 'failing test' : `${failedCount} failing tests`}`
688 : `the ${stage} problem${failedCount === 1 ? '' : 's'}`
689 const [first, ...rest] = errors
690 const quoted = [` ✕ ${(first ?? '').trim()}`, ...rest.slice(0, 2).map(line => ` ${line.trim()}`)].join('\n')
691 // `in .. First failure` would read as the parent folder.
692 const where = path === '.' ? 'the current folder' : path
693 const note = didNotRun ? ' (the tests did not run)' : ''
694 return `Fix ${what} in ${where}${note}. First failure, from Mod Lab:\n${quoted}\nThen re-run ${stage}.`
695}
696
697/** The done box's one line: `ready to share · 8/8 stages · 12 tests · validate clean · 1 gate`. */
698export function doneLineOf(results: Results): string {
699 const parts = ['8/8 stages']
700 const tests = results.Test?.tests
701 if (tests) parts.push(plural(tests.passed, 'test'))
702 if (results.Validate?.ok) parts.push('validate clean')
703 const gates = results.Validate?.validate?.gates.length ?? 0
704 if (gates) parts.push(plural(gates, 'gate'))
705 return parts.join(' · ')
706}
707
708/**
709 * The view of one mod, from everything gathered. `path` is the mod's folder
710 * as shown in the detail header (see `displayPathOf`).
711 */
712export function viewOf(
713 facts: FileFacts,
714 results: Results,
715 runs: readonly Run[],
716 reported: Reported | null,
717 isFresh: boolean,
718 edit: Edit | null,
719 path: string,
720): ModView {
721 const lights = lightsOf(facts, results, runs.map(run => run.kind), reported, edit)
722 const { text, tone } = statusOf(lights, results, reported, runs, isFresh && isGreen(lights))
723 const validate = results.Validate?.validate
724 const focus = focusStageOf(lights)
725 const failedStage = focus?.light === 'failed' ? focus.stage : null
726 const failedRun = failedStage === 'Validate' || failedStage === 'Test' ? results[failedStage] : undefined
727 const last = [results.Validate, results.Test].filter((one): one is RunResult => one !== undefined)
728 const lastMs = last.reduce((longest, one) => Math.max(longest, one.durationMs ?? 0), 0)
729 const fresh = isFresh && isGreen(lights)
730 return {
731 name: facts.name,
732 lights,
733 status: text,
734 tone,
735 time: durationOf(lastMs),
736 isDemo: false,
737 isFresh: fresh,
738 version: facts.version,
739 description: facts.description,
740 path: `${path}/`,
741 isReadmeStale: facts.isReadmeStale,
742 doneLine: fresh ? doneLineOf(results) : null,
743 archetype: facts.archetype,
744 builtOn: facts.builtOn,
745 hooks: validate?.hooks ?? [],
746 reaches: validate ? reachesOf(validate.calls) : [],
747 gates: validate?.gates ?? [],
748 errors: failedRun?.errors ?? [],
749 failedStage,
750 // factsOf never returns facts without a manifest or SPEC, so these are the placeholder's (#19).
751 isPlaceholder: !facts.hasSpec && !facts.hasManifest,
752 }
753}
754
755// ── Demo ──────────────────────────────────────────────────────────────────
756
757/** One beat of the demo: from `atMs`, `stage` shows `light`, with what the row says. */
758export type Beat = { atMs: number; stage: Stage; light: Light; note?: string }
759
760/**
761 * The demo build of `aurora`: every stage runs then passes, Test fails once
762 * and Claude fixes it. Exactly 12 s, then it holds green for 3 s.
763 */
764export function demoTimeline(): Beat[] {
765 const beats: Beat[] = []
766 let at = 0
767 const step = (stage: Stage, runMs: number, light: Light, note: string): void => {
768 beats.push({ atMs: at, stage, light: 'running', note })
769 at += runMs
770 beats.push({ atMs: at, stage, light })
771 }
772 step('Spec', 1000, 'passed', 'writing SPEC.md')
773 step('Scaffold', 800, 'passed', 'scaffolding plugin.json')
774 step('Logic', 1400, 'passed', 'aurora-logic.ts + tests')
775 step('Register', 1000, 'passed', 'register.tsx')
776 step('Validate', 1300, 'passed', 'validating')
777 step('Test', 1300, 'failed', 'running tests')
778 at += 1600
779 step('Test', 1300, 'passed', 'Claude is fixing src/band.tsx')
780 step('README', 1300, 'passed', 'What it reaches')
781 step('Share', 1000, 'passed', 'marketplace entry')
782 return beats
783}
784
785export const DEMO_NAME = 'aurora'
786
787/** How long the demo holds green after its last beat, before the real state returns. */
788export const DEMO_HOLD_MS = 3000
789
790export function demoWalkMs(beats: readonly Beat[] = demoTimeline()): number {
791 return beats[beats.length - 1]?.atMs ?? 0
792}
793
794export function demoLengthMs(beats: readonly Beat[] = demoTimeline()): number {
795 return demoWalkMs(beats) + DEMO_HOLD_MS
796}
797
798/** While the demo runs, the summary row: `aurora is a demo · nothing is written to disk`, and `0:02 / 0:12`. */
799export function demoClockOf(elapsedMs: number, beats: readonly Beat[] = demoTimeline()): { now: string; total: string } {
800 const walk = demoWalkMs(beats)
801 return { now: clockOf(Math.min(elapsedMs, walk)), total: clockOf(walk) }
802}
803
804const DEMO_ERRORS = ['band steps aside when hasSurvey is true', 'expected 0 band rows, received 2', 'at test/band.test.ts:18:5']
805
806/** The line that replaces `[F] Fix with Claude` while the demo's test is failing. */
807export const DEMO_FIXING = 'Claude is fixing src/band.tsx'
808
809/** The demo mod as a view, `elapsedMs` into the demo. */
810export function demoViewAt(elapsedMs: number, beats: readonly Beat[] = demoTimeline()): ModView {
811 const lights: Light[] = STAGES.map(() => 'pending')
812 let current: Beat | undefined
813 for (const beat of beats) {
814 if (beat.atMs > elapsedMs) break
815 lights[STAGES.indexOf(beat.stage)] = beat.light
816 current = beat
817 }
818 const testFailed = lights[STAGES.indexOf('Test')] === 'failed'
819 const isDone = isGreen(lights)
820 let status: { text: string; tone: Tone }
821 if (isDone) status = { text: 'ready to share', tone: 'success' }
822 else if (current?.light === 'running') status = { text: current.note ?? 'running', tone: 'text' }
823 else if (testFailed) status = { text: '1 test failing', tone: 'error' }
824 else status = { text: `next: ${STAGES[lights.findIndex(light => light !== 'passed')] ?? 'Share'}`, tone: 'dim' }
825 const hasValidated = lights[STAGES.indexOf('Validate')] === 'passed'
826 const walk = demoWalkMs(beats)
827 return {
828 name: DEMO_NAME,
829 lights,
830 status: status.text,
831 tone: status.tone,
832 time: clockOf(Math.min(elapsedMs, walk)),
833 isDemo: true,
834 isFresh: isDone,
835 version: 'demo',
836 description: 'A pretend mod. Walks all 8 stages in 12 seconds.',
837 path: 'not written to disk',
838 isReadmeStale: false,
839 doneLine: isDone ? `${DEMO_NAME} walked all 8 stages in ${clockOf(walk)} · demo, nothing saved` : null,
840 archetype: 'band + command',
841 builtOn: null,
842 hooks: hasValidated ? ['session.start', 'command.run{command=aurora}', 'ui.render{component=AbovePrompt}'] : [],
843 reaches: hasValidated ? reachesOf(['$.clock.every', '$.ui.status']) : [],
844 gates: [],
845 errors: testFailed ? DEMO_ERRORS : [],
846 failedStage: testFailed ? 'Test' : null,
847 isPlaceholder: false,
848 }
849}
850
851// ── Gathering ─────────────────────────────────────────────────────────────
852
853/** A directory entry as `$.fs.list` gives it, cut to what Mod Lab reads. */
854export type Entry = { name: string; kind: 'file' | 'dir' | 'other'; mtimeMs: number }
855
856/** How many parts of a UNC path (`//server/share`) are its root. */
857const UNC_ROOT_PARTS = 2
858
859/** Resolves `.` and `..` segments in a `/`-separated path. */
860export function normalizePath(path: string): string {
861 const slashed = path.replace(/\\/g, '/')
862 const root = rootOf(slashed)
863 // A UNC path's server and share are part of its root: '..' stops above them, as at `/`.
864 const floor = root === '//' ? UNC_ROOT_PARTS : 0
865 const parts: string[] = []
866 for (const part of slashed.slice(root.length).split('/')) {
867 if (part === '' || part === '.') continue
868 if (part === '..') {
869 if (parts.length > floor && parts[parts.length - 1] !== '..') parts.pop()
870 else if (!root) parts.push('..')
871 } else {
872 parts.push(part)
873 }
874 }
875 return root + parts.join('/')
876}
877
878/** A `/`-separated path's root: `//` for a UNC path, `/`, a drive (`C:/`, upper case), or '' when it is relative. */
879function rootOf(slashed: string): string {
880 if (/^\/\/[^/]/.test(slashed)) return '//'
881 if (slashed.startsWith('/')) return '/'
882 return /^[A-Za-z]:(\/|$)/.test(slashed) ? `${slashed.charAt(0).toUpperCase()}:/` : ''
883}
884
885/**
886 * A path as the session reads it: relative to `cwd` when inside it
887 * (`mods/foo`), `.` when it is `cwd`, absolute otherwise, and absolute when
888 * the working directory couldn't be read (`cwd` null).
889 */
890export function displayPathOf(path: string, cwd: string | null): string {
891 const target = normalizePath(path)
892 if (cwd === null) return target
893 const root = normalizePath(cwd)
894 if (target === root) return '.'
895 // `normalizePath` keeps a trailing `/` only for the root itself: cwd `/` gives prefix `/`, not `//`.
896 const prefix = `${root.replace(/\/$/, '')}/`
897 return target.startsWith(prefix) ? target.slice(prefix.length) : target
898}
899
900/** Where a marketplace keeps its manifest, below its folder. */
901const MARKETPLACE_FILE = '/.claude-plugin/marketplace.json'
902
903/**
904 * The marketplace file `cwd` would have if it were a marketplace, then that of every folder above
905 * it, nearest first, down to its root: `/`, a drive (`C:/`) or a UNC share (`//server/share`).
906 * A relative `cwd` names no folder to walk, so it has none.
907 */
908export function marketplaceCandidatesOf(cwd: string): string[] {
909 return foldersUpFrom(cwd).map(folder => (folder.endsWith('/') ? folder + MARKETPLACE_FILE.slice(1) : folder + MARKETPLACE_FILE))
910}
911
912/** `path` and every folder above it, nearest first, down to its root; none for a relative path. */
913export function foldersUpFrom(path: string): string[] {
914 const normal = normalizePath(path)
915 const root = rootOf(normal)
916 if (!root) return []
917 const parts = normal.slice(root.length).split('/').filter(Boolean)
918 // A UNC path's server and share are its root folder; nothing sits above them.
919 const top = root === '//' ? Math.min(UNC_ROOT_PARTS, parts.length) : 0
920 const folders: string[] = []
921 for (let depth = parts.length; depth >= top; depth--) folders.push(root + parts.slice(0, depth).join('/'))
922 return folders
923}
924
925/**
926 * The mods folder: a set `modsDir` always wins. Otherwise the `mods/` of the nearest folder at or
927 * above `cwd` whose marketplace file is among `existing`, the way /mod-builder:build finds it, and
928 * `fallback` (the plugin's own) when `cwd` is unknown or no marketplace is above it.
929 */
930export function modsDirFor(configured: string, cwd: string | null, existing: readonly string[], fallback: string): string {
931 if (configured) return normalizePath(configured)
932 const found = cwd === null ? undefined : marketplaceCandidatesOf(cwd).find(candidate => existing.includes(candidate))
933 return found === undefined ? normalizePath(fallback) : `${found.slice(0, -MARKETPLACE_FILE.length)}/mods`
934}
935
936/** Where the marketplace walk starts (#92): the session's project root when known, which a Bash `cd` doesn't move, else `cwd`. */
937export function walkStartOf(root: string | null, cwd: string | null): string | null {
938 return root ?? cwd
939}
940
941/** A path to compare by: normalized, and lower-cased on a drive or UNC share, which Windows reads without case (PR #95 review). */
942function pathKey(path: string): string {
943 const normal = normalizePath(path)
944 const root = rootOf(normal)
945 return root === '/' || root === '' ? normal : normal.toLowerCase()
946}
947
948/** A build's pinned folder, while the project root is the one it was pinned under or can't be read now; else null (#92). */
949export function keptPinOf(pin: Pin | null, root: string | null): Pin | null {
950 if (!pin) return null
951 return root === null || pathKey(pin.root) === pathKey(root) ? pin : null
952}
953
954/**
955 * The report a row in `dir` shows: one made in that folder, or one with no folder (stored before 0.2.16).
956 * `reported` keeps one report per mod name, so a same-named mod in another folder must not light this row (PR #95 review).
957 */
958export function reportIn(report: Reported | undefined, dir: string): Reported | null {
959 if (!report) return null
960 return report.dir === undefined || report.dir === dir ? report : null
961}
962
963/** The marketplace file a mods folder belongs to: `<marketplace>/mods` → `<marketplace>/.claude-plugin/marketplace.json`. */
964export function marketplaceFileOf(modsDir: string): string {
965 const parent = parentOf(modsDir)
966 return parent.endsWith('/') ? parent + MARKETPLACE_FILE.slice(1) : parent + MARKETPLACE_FILE
967}
968
969/** The folder above `path`, normalized; a root is its own parent. */
970export function parentOf(path: string): string {
971 const dir = normalizePath(path)
972 const cut = dir.lastIndexOf('/')
973 return cut < rootOf(dir).length ? rootOf(dir) : dir.slice(0, cut)
974}
975
976/** A folder's `.git` as the disk has it: a directory (a repository's top), a file (a worktree's or submodule's pointer), or none. */
977export type DotGit = { kind: 'dir' } | { kind: 'file'; text: string } | null
978
979/**
980 * The common git folder of the repository `folder` is the top of (PR #95 review follow-up): `<folder>/.git`
981 * for a repository top; for a `.git` file, its `gitdir:` (resolved against `folder`) without a trailing
982 * `/worktrees/<name>`. A submodule's `gitdir` names its own repository's folder. Null with no `.git`.
983 */
984export function gitCommonDirOf(folder: string, dotGit: DotGit): string | null {
985 if (!dotGit) return null
986 if (dotGit.kind === 'dir') return `${normalizePath(folder).replace(/\/$/, '')}/.git`
987 const gitDir = gitDirNamedIn(folder, dotGit.text)
988 if (gitDir === null) return null
989 return /^(.*)\/worktrees\/[^/]+$/.exec(gitDir)?.[1] ?? gitDir
990}
991
992/** The git folder a `.git` file's `gitdir:` line names, resolved against `folder`; null without one. */
993function gitDirNamedIn(folder: string, text: string): string | null {
994 const line = /^gitdir:[ \t]*(.+?)[ \t]*$/m.exec(text.replace(/\r/g, ''))
995 if (!line) return null
996 const named = line[1]!.replace(/\\/g, '/')
997 return normalizePath(rootOf(named) ? named : `${normalizePath(folder).replace(/\/$/, '')}/${named}`)
998}
999
1000/**
1001 * Git's own record of the worktree whose `.git` file this is: `<gitdir>/gitdir`, when the gitdir is
1002 * `…/worktrees/<name>` (PR #95 review follow-up). Null for a repository top, a submodule or no `.git`.
1003 */
1004export function worktreeLinkOf(folder: string, dotGit: DotGit): { record: string } | null {
1005 if (dotGit?.kind !== 'file') return null
1006 const gitDir = gitDirNamedIn(folder, dotGit.text)
1007 return gitDir !== null && /\/worktrees\/[^/]+$/.test(gitDir) ? { record: `${gitDir}/gitdir` } : null
1008}
1009
1010/** Whether git's record (`record`, holding `text`) names `folder`'s `.git` back: absolute, or relative to the record's folder. */
1011export function isBackLinkTo(folder: string, record: string, text: string): boolean {
1012 const named = text.replace(/\r/g, '').trim().replace(/\\/g, '/')
1013 if (!named) return false
1014 const resolved = normalizePath(rootOf(named) ? named : `${parentOf(record)}/${named}`)
1015 return pathKey(resolved) === pathKey(`${normalizePath(folder).replace(/\/$/, '')}/.git`)
1016}
1017
1018/** Whether two common git folders are one repository's (Windows roots without case); an unknown one never is. */
1019export function isSameRepo(a: string | null, b: string | null): boolean {
1020 return a !== null && b !== null && pathKey(a) === pathKey(b)
1021}
1022
1023/**
1024 * Whether a reported folder may be pinned, as far as its name and the root tell (PR #95 review): a
1025 * readable root, and a folder named `mods`. The caller checks that its marketplace file exists and that
1026 * the folder above it is the project's own repository or one of its worktrees (`isSameRepo`), since
1027 * Validate and Test then run there. Gives the marketplace file and the normalized root, or why not.
1028 */
1029export function pinCheckOf(dir: string, root: string | null): { marketplace: string; root: string } | { reason: string } {
1030 if (root === null) return { reason: "the project root can't be read" }
1031 const folder = normalizePath(dir)
1032 if (folder.slice(folder.lastIndexOf('/') + 1) !== 'mods') return { reason: `${folder} isn't a marketplace's mods folder` }
1033 return { marketplace: marketplaceFileOf(folder), root: normalizePath(root) }
1034}
1035
1036/** A pin as state kept it, or null when it isn't one (no root, or not a pin at all). */
1037export function pinOf(value: unknown): Pin | null {
1038 const held = value as { modsDir?: unknown; root?: unknown } | null
1039 return held && typeof held.modsDir === 'string' && typeof held.root === 'string' ? { modsDir: held.modsDir, root: held.root } : null
1040}
1041
1042/**
1043 * The folder Mod Lab watches (#92): a set `modsDir`, else the pin `keptPinOf` keeps, else `modsDirFor`
1044 * walking from the root, or from `cwd` when no marketplace in `existing` is above the root (PR #95 review).
1045 * `pin` is the pin to keep: null when there was none or a changed root dropped it.
1046 */
1047export function watchedDirOf(
1048 pin: Pin | null,
1049 root: string | null,
1050 configured: string,
1051 cwd: string | null,
1052 existing: readonly string[],
1053 fallback: string,
1054): { dir: string; pin: Pin | null } {
1055 const kept = keptPinOf(pin, root)
1056 if (configured) return { dir: normalizePath(configured), pin: kept }
1057 if (kept) return { dir: kept.modsDir, pin: kept }
1058 const hasMarketplace = (start: string | null): boolean => start !== null && marketplaceCandidatesOf(start).some(path => existing.includes(path))
1059 const start = [root, cwd].find(hasMarketplace) ?? walkStartOf(root, cwd)
1060 return { dir: modsDirFor('', start, existing, fallback), pin: null }
1061}
1062
1063/**
1064 * "Ready to share" marks as `<modsDir>/<name>`. Before 0.2.9 a mark was the bare name, of a mod
1065 * in the one folder Mod Lab watched (`legacyDir`), so a bare one is read as that folder's.
1066 */
1067export function freshIdsOf(stored: readonly string[], legacyDir: string): string[] {
1068 return stored.map(id => (id.includes('/') ? id : `${legacyDir}/${id}`))
1069}
1070
1071/**
1072 * The mods folder a store key names after one of `prefixes` (`modlab:results:<dir>`), or null (#138). Read by the
1073 * prefix, not split on `:`: a prefix holds one already, and a Windows folder another.
1074 */
1075export function storeFolderOf(key: string, prefixes: readonly string[]): string | null {
1076 const prefix = prefixes.find(p => key.startsWith(`${p}:`) && key.length > p.length + 1)
1077 return prefix === undefined ? null : key.slice(prefix.length + 1)
1078}
1079
1080/**
1081 * Whether a `$.fs.stat` rejection says the folder is gone: the engine's own ending, `failed: ENOENT` (probed on
1082 * 2.1.309: the error has no code). Anything else, another mod's refusal or EACCES included, can't tell, so the folder stays.
1083 */
1084export function folderGone(message: string): boolean {
1085 return /\) failed: ENOENT$/.test(message) && !message.includes('refused by')
1086}
1087
1088/** The folders the store's keys name, each once, and the one the unkeyed keys from before 0.2.9 describe when one is there. */
1089export function storeFoldersOf(keys: readonly string[], prefixes: readonly string[], legacyDir: string): string[] {
1090 const keyed = keys.map(key => storeFolderOf(key, prefixes)).filter((dir): dir is string => dir !== null)
1091 const hasUnkeyed = keys.some(key => prefixes.includes(key))
1092 return [...new Set([...keyed, ...(hasUnkeyed ? [legacyDir] : [])])]
1093}
1094
1095/**
1096 * The keys to delete, each with why: those of a folder in `gone`, and each unkeyed key whose folder (`legacyDir`) is gone
1097 * or has its own keyed record under that prefix, which `storedOf` reads in its place. Keys of other prefixes stay.
1098 */
1099export function prunableKeys(keys: readonly string[], prefixes: readonly string[], gone: readonly string[], legacyDir: string): { key: string; why: string }[] {
1100 return keys.flatMap(key => {
1101 const dir = storeFolderOf(key, prefixes)
1102 if (dir !== null) return gone.includes(dir) ? [{ key, why: `${dir} is gone` }] : []
1103 if (!prefixes.includes(key)) return []
1104 if (gone.includes(legacyDir)) return [{ key, why: `${legacyDir} is gone` }]
1105 return keys.includes(`${key}:${legacyDir}`) ? [{ key, why: `${legacyDir} has its own record` }] : []
1106 })
1107}
1108
1109/**
1110 * A folder's record (results, done marks or generations) without the mods not in `keep`, or null when none goes (#138).
1111 * Given `read`, the record as a scan read it before `keep` could change, a name goes only while its entry is still the one
1112 * read: one written since (an edit's new generation, PR #146 review, Codex 4362849420) stays for the next scan to judge.
1113 */
1114export function withoutGone<T>(record: Readonly<Record<string, T>>, keep: readonly string[], read?: Readonly<Record<string, unknown>>): Record<string, T> | null {
1115 const isAsRead = (name: string, entry: T) => read === undefined || (name in read && JSON.stringify(read[name]) === JSON.stringify(entry))
1116 const kept = Object.entries(record).filter(([name, entry]) => keep.includes(name) || !isAsRead(name, entry))
1117 return kept.length === Object.keys(record).length ? null : Object.fromEntries(kept)
1118}
1119
1120/** The last two segments of a path, for the summary line: `…/ClaudeMod/mods`. */
1121export function shortPath(path: string): string {
1122 const parts = normalizePath(path).split('/').filter(Boolean)
1123 return parts.length <= 2 ? normalizePath(path) : `…/${parts.slice(-2).join('/')}`
1124}
1125
1126/** Everything read from one mod folder, before it is judged. */
1127export type FolderRead = {
1128 name: string
1129 top: readonly Entry[]
1130 manifestDir: readonly Entry[]
1131 hooks: readonly Entry[]
1132 tests: readonly Entry[]
1133 types: readonly Entry[]
1134 /** Top-level listings of agents/, commands/ and skills/, which validate reads. Optional: absent reads as empty. */
1135 agents?: readonly Entry[]
1136 commands?: readonly Entry[]
1137 skills?: readonly Entry[]
1138 /** Files in subfolders of hooks/, tests/, types/, agents/, commands/ and skills/, named by their path from the mod folder (`hooks/lib/parser.ts`). */
1139 nested?: readonly Entry[]
1140 /** Folders whose listing failed, by their path from the mod folder (`hooks/lib`): read as empty, though they may not be. */
1141 unlisted?: readonly string[]
1142 spec: string | null
1143 readme: string | null
1144 /** plugin.json's text, when present. */
1145 manifest: string | null
1146 marketplace: string
1147}
1148
1149/** `version` and `description` from a plugin.json's text. */
1150export function manifestOf(text: string | null): { version: string | null; description: string | null } {
1151 try {
1152 const parsed = JSON.parse(text ?? '') as { version?: unknown; description?: unknown }
1153 return {
1154 version: typeof parsed.version === 'string' ? parsed.version : null,
1155 description: typeof parsed.description === 'string' ? parsed.description : null,
1156 }
1157 } catch {
1158 return { version: null, description: null }
1159 }
1160}
1161
1162/** A short, order-independent hash of a list of strings (FNV-1a over the sorted list). */
1163export function signatureOf(items: readonly string[]): string {
1164 let h = 0x811c9dc5
1165 for (const ch of [...items].sort().join('\n')) {
1166 h ^= ch.codePointAt(0)!
1167 h = Math.imul(h, 0x01000193) >>> 0
1168 }
1169 return `${items.length}:${h.toString(36)}`
1170}
1171
1172/** One folder's reads → its facts. A folder with neither manifest nor SPEC is no mod: null. */
1173export function factsOf(read: FolderRead): FileFacts | null {
1174 const has = (list: readonly Entry[], name: string): boolean => list.some(entry => entry.name === name)
1175 const hasManifest = has(read.manifestDir, 'plugin.json')
1176 const hasSpec = read.spec !== null
1177 if (!hasManifest && !hasSpec) return null
1178 const manifest = read.manifestDir.filter(entry => entry.name === 'plugin.json')
1179 // Named by folder, so a file moved between folders without a new mtime still changes the signature.
1180 const inFolder = (folder: string, entries: readonly Entry[]): Entry[] =>
1181 entries.filter(entry => entry.kind === 'file').map(entry => ({ ...entry, name: `${folder}/${entry.name}` }))
1182 const sigOf = (entries: readonly Entry[]): string => signatureOf(entries.map(entry => `${entry.name}@${entry.mtimeMs}`))
1183 // The one file at the top that validate reads; the SPEC and README are read by neither validate nor test.
1184 const mcp = read.top.filter(entry => entry.kind === 'file' && entry.name === '.mcp.json')
1185 const nested = read.nested ?? []
1186 const code = [
1187 ...inFolder('.claude-plugin', manifest),
1188 ...inFolder('hooks', read.hooks),
1189 ...inFolder('tests', read.tests),
1190 ...inFolder('types', read.types),
1191 ...inFolder('agents', read.agents ?? []),
1192 ...inFolder('commands', read.commands ?? []),
1193 ...inFolder('skills', read.skills ?? []),
1194 ...mcp,
1195 ...nested.filter(entry => entry.kind === 'file'),
1196 ]
1197 const all = [...read.top.filter(entry => entry.kind === 'file'), ...code]
1198 const times = all.map(entry => entry.mtimeMs)
1199 const slots = read.spec ? slotsOf(read.spec) : {}
1200 const codeMtimeMs = Math.max(0, ...code.map(entry => entry.mtimeMs))types/index.d.ts 103 lines1// Mod Lab's state contract: every value it keeps in `$.state`, and the types
2// those values are made of. Self-contained by rule: no imports. hooks/mod-builder-logic.ts
3// and hooks/register.tsx import these types from here.
4
5export type Stage = 'Spec' | 'Scaffold' | 'Logic' | 'Register' | 'Validate' | 'Test' | 'README' | 'Share'
6
7/** A run Mod Lab starts itself, by button, by hotkey or after a `lab_report`. */
8export type RunKind = 'Validate' | 'Test' | 'Typecheck'
9
10export type Light = 'pending' | 'running' | 'passed' | 'failed' | 'stale'
11
12export type Tone = 'success' | 'accent' | 'error' | 'warn' | 'dim' | 'text'
13
14export type Gate = { hook: string; hasCatch: boolean }
15
16export type Reach = { label: string; value: string }
17
18/** What a `lab_report` call last said, before the disk confirms it. */
19export type Reported = {
20 stage: Stage
21 status: 'running' | 'passed' | 'failed'
22 note?: string
23 /** When this report arrived, for the band's timer. */
24 since: number
25 /** The mods folder the session was in when it reported: a placeholder row shows only there (#19). */
26 dir?: string
27}
28
29/** A build's mods folder, pinned for the session by a `lab_report` with `path`, and the project root it was pinned under (#92). */
30export type Pin = { modsDir: string; root: string }
31
32/** One mod as the pane, band and status line draw it. */
33export type ModView = {
34 name: string
35 lights: Light[]
36 status: string
37 tone: Tone
38 /** The time column: a run's elapsed time while it runs, else the last run's duration. */
39 time: string
40 isDemo: boolean
41 /** Went all green during this session: the row reads "ready to share" and the done box shows. */
42 isFresh: boolean
43 version: string | null
44 description: string | null
45 /** The mod's folder as the session read it at the last scan, with a trailing `/` (`mods/<name>/` under the default `modsDir`); the demo's is `not written to disk`. The detail header works it out again when it draws. */
46 path: string
47 /** README.md is older than the code it describes. */
48 isReadmeStale: boolean
49 /** The done box's line, when the mod is fresh. */
50 doneLine: string | null
51 archetype: string | null
52 builtOn: string | null
53 hooks: string[]
54 reaches: Reach[]
55 gates: Gate[]
56 errors: string[]
57 failedStage: Stage | null
58 /** Reported by a build before its folder exists: a row with no actions, until a scan finds the folder. */
59 isPlaceholder: boolean
60}
61
62/** A run in flight: which mod, which kind, since when, and how far it has got. */
63export type Run = {
64 mod: string
65 kind: RunKind
66 startedAt: number
67 /** Tests reported so far (streamed), and the total the last run had, when known. */
68 passed: number
69 failed: number
70 total: number | null
71}
72
73declare module 'claude-code' {
74 interface PluginState {
75 'mod-builder': {
76 /**
77 * The last scan's verdict, written as one value so no reader pairs one folder's rows with
78 * another's path: `views`, the mods on disk judged (the demo is not among them), and `modsDir`,
79 * the folder they were judged in, which the pane's buttons act on (null before the first scan).
80 */
81 judged: { modsDir: string | null; views: ModView[] }
82 /** The row the detail panel shows. */
83 selected: string | null
84 runs: Run[]
85 reported: Record<string, Reported>
86 /** Builds still running, per mods folder then mod name, for placeholder rows (see `withBuilding`). */
87 building: Record<string, Record<string, Reported>>
88 /** The animation clock: frame count and the time it last ticked. */
89 frame: { n: number; now: number }
90 /** When the demo started, or null when none runs. */
91 demoStartedAt: number | null
92 /** The README the pane shows in place of the list, or null. */
93 readme: { name: string; text: string; isStale: boolean } | null
94 /** Mods that went all green this session (newest code stamp), for "ready to share", as `<modsDir>/<name>`. */
95 fresh: string[]
96 /** The "too narrow" toast fired for the current narrow spell; reset once wide again. */
97 hasWarnedNarrow: boolean
98 /** The folder a build reported with `path`: watched until the project root changes (#92). */
99 pinned: Pin | null
100 }
101 }
102}
103