MoonlightCode for Claude Code: workflow phases, with Plan as a read-only boundary while Claude Code runs in auto mode

moonlightcode mod)A Claude Code plugin of function hooks that brings MoonlightCode into the session itself, without the daemon:
present_plan; you comment its lines and answer Approve, Ask for changes, or Reject. Claude Code's own plan mode is not used: it would leave auto mode.Design and test evidence: .bmad-output/spike-1-mod-findings.md.
From this repository's marketplace, for every session (function hooks are early access: the variable is needed):
claude plugin marketplace add titouanfreville/moonlight-ide-plugins --sparse .claude-plugin clients/claude-code
claude plugin install moonlightcode@moonlight
and in the env block of ~/.claude/settings.json: "CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1".
The MoonlightCode VS Code and JetBrains plugins do both for you: when no daemon can be started, they offer to install it (or run MoonlightCode: Install the Claude Code Plugin). They take the repository's marketplace, or the copy bundled in them when GitHub is out of reach. Installed this way, the mod also gates the sessions Anthropic's own Claude Code plugins start, which no launch flag of ours reaches.
The mod is the fallback, not a second gate. At session start it reads ~/.moonlight/control.json ($MOONLIGHT_HOME when set) and asks the daemon's /control/gating-status:
/phase, /ml-plan, present_plan or request_phase: the daemon's own mcp__moonlight__* verbs and the IDE panels are the way. The hint under the prompt says ☾ gated by the MoonlightCode daemon. The Review panel (/ml-review) still works.~/.moonlight, Claude Code's settings)./phase moves on./control/gating-status at session start (its hooks must be installed), then with the cheaper /control/health while it governs, 3 s each.The MoonlightCode VS Code and JetBrains panels show the sessions the mod governs beside the daemon's: their phase, a phase request waiting (Allow / Refuse), the plan to review. Decisions made there reach the mod through files under ~/.moonlight/mod/sessions/<id>/; see ../fallback-bridge.md.
To develop the mod, load the working copy instead:
CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude --plugin-dir ~/path/to/moonlight-ide-plugins/clients/claude-code/moonlight
To load it in every session, set it in the env block of ~/.claude/settings.json:
"CLAUDE_CODE_ENABLE_FUNCTION_HOOKS": "1",
"CLAUDE_CODE_PLUGIN_DIRS": "~/path/to/moonlight-ide-plugins/clients/claude-code/moonlight",
"CLAUDE_CODE_PLUGIN_DIR_WATCH": "1"
The same workflow as the MoonlightCode daemon (crates/domain/src/phase.rs). Claude Code runs in auto mode in every phase; the mod's policy is what differs.
| Phase | Project files | Notes (.ai/, .bmad-output/, .bmad/) | Next |
|---|---|---|---|
| ◐ Plan | read-only | writable | Auto |
| ● Auto | writable | writable | Test |
| ● Test | writable | writable | Review |
| ● Review | writable | writable | Commit |
| ■ Commit | read-only | read-only: everything frozen until you commit | Plan |
/tmp always is), and any other tool must be on the read-only allow-list. Jira tools are on it, writes included: filing tickets is planning work. Any other MCP tool asks the operator (Allow once, Allow for this session, Deny) instead of being refused; with no one to ask, it is refused.~/.moonlight, the project's .moonlight/, and Claude Code's settings (.claude/settings.json, .claude/settings.local.json, ~/.claude/settings.json), so an Auto session can't widen the next Plan. In Plan and Commit, Bash is refused while the effective sandbox has an allowWrite entry that opens one of them.gh, nx and the like need the network, local sockets and folders outside the project. The mod turns the sandbox off in the project's settings (enabled: false, allowUnsandboxedCommands: true) and back on for Plan and Commit. The gate's own files are then protected by reading the command: a redirect into them, or a writing program (mv, rm, sed -i, git checkout...) given them, is refused. Best effort: a script interpreter, or a command that hides the path, gets past it..claude/settings.local.json makes the gate refuse tools (with a toast) until it is fixed./phase, the hint, the pane), the agent finds a note about it at its next turn, and a pending request_phase is dropped.present_plan is a Plan tool: it is refused in the other phases. Approving a plan moves Plan to Auto.next is cyclic: after Commit, Plan starts the next unit of work. You may also jump to any phase.discovery, discover for Plan; implement, autoimplement, auto-implement for Auto.The phase is per project, shared by every session open on it. A session that sets a project to a read-only phase makes Bash read-only there for the other sessions too, since they share the project's sandbox settings.
Loading it turns the gate on for the session's project, in Plan: Bash runs under Claude Code's sandbox with the project read-only, and only the notes folders (.ai/, .bmad-output/, .bmad/) are writable. Type /phase auto to work normally.
The phase shows under the prompt, on the hint line: the current one as a badge (◐ PLAN yellow, ● AUTO green, ● TEST cyan, ● REVIEW blue, ■ COMMIT red), its rule in the same colour, then a dim · next: … that steps to the next phase, then Claude Code's own hint. /phase opens the Moonlight pane: the badge, then the five phases as dim words to jump to any. When the agent asks for a phase change, a band shows above the prompt with Approve (y) and Deny (n); otherwise nothing is drawn there.
The panes keep colour for state: the phase badge carries its phase's colour, the diff keeps Claude Code's own. The rest is plain or dim text. 🤖 marks what the AI reviewer found, with its severity as a word (high, medium, dim low); 💬 marks your comments, whose text hangs under them behind a ┃ rail.
The panes, the hint and the band draw on the terminal and desktop surfaces. The VS Code extension draws no mod UI today, so use the commands there.
| Command | What it does | ||||
|---|---|---|---|---|---|
/phase | Show the phase, its rule and the next one, and open the Moonlight pane | ||||
| `/phase plan\ | auto\ | test\ | review\ | commit` | Change the phase (aliases accepted) |
/phase next | Move to the next phase (Commit → Plan) | ||||
/phase approve · /phase deny | Answer the agent's request_phase | ||||
/ml-plan | Open or close the Plan panel, and print the plan with line numbers, its comments and its state | ||||
/ml-plan comment <line[-end]> <text> | Comment a line or a range of the plan; \n starts a new line | ||||
/ml-plan uncomment <id> | Remove a comment | ||||
/ml-plan approve [note] | Approve the plan: the phase moves to Auto, and the agent is told to implement it | ||||
/ml-plan refine <note> | Send the comments and the note back: the agent revises and presents the whole plan again | ||||
/ml-plan reject <reason> | Reject the plan: the agent stops | ||||
/ml-review | Open or close the Review panel, and list changed files and comments | ||||
/ml-review comment <path:line[-end]> <text> | Comment a line or a range of the current file; \n starts a new line | ||||
/ml-review uncomment <id> | Remove a comment | ||||
/ml-review submit [summary] | Send every comment to the agent as one message (the panel's Send review), then clear them | ||||
/ml-review accept | Close the review: the next one starts from here | ||||
/ml-review run [skill] | Run one review skill (the only attached one, else name any installed one; your list is left as it is) | ||||
/ml-review cancel | Free the panel from a review that will not answer | ||||
/ml-review attach <skill> · detach <skill> | Your own list of review skills to choose from at run time | ||||
/ml-review skills [reset] | The review skills offered, and the attached ones not installed; reset drops your own list | ||||
| `/ml-review scope session\ | head` | Review this session's changes, or everything since HEAD |
/ml-review rather than /review: /review is the alias of Claude Code's built-in /code-review.
In the Plan phase, the agent proposes a plan by calling mcp__moonlightcode__present_plan with the whole plan as Markdown (and an optional title). The tool answers at once and tells the agent to stop and wait; the verdict reaches it later as a [moonlight] prompt, which starts a turn. EnterPlanMode and ExitPlanMode are refused in Plan, with a pointer to present_plan: Claude Code's plan mode would leave auto mode.
~/.moonlight/mod/sessions/<session>/plan/v<N>.md. A new version starts with no comments.code and links through Markdown; code blocks highlighted in their fence's language, the fence shown only as that language. Table rows stay plain text, since a row drawn alone is not a table.+ before a line to comment it; click a second + to extend to a range; click the same single line again to clear. • marks a line with a comment, ✕ removes one. Type the comment, then Enter; end a line with \ to write several.present_plan again./ml-plan note goes with it.In VS Code, where no mod UI draws, use /ml-plan: it prints the plan with its line numbers to comment.
In the terminal's fullscreen layout, at least 110 columns wide, the panel docks on the right; elsewhere it shows above the prompt. Type /ml-review to open or close it. When it has focus, the arrow keys scroll, Tab walks the buttons, and Esc returns to the prompt.
r refreshes the list.+/-, green/red, syntax colours.s) forces one or the other.e), docked panel only: reopens the panel at the terminal's full width, like a modal. ⤡ Shrink goes back to the dock's normal width. A width you set by hand wins.+ in front of a line to comment it. Click a second + to extend to a range: every row between, removed, added and context lines alike, so a whole changed block takes one comment. Click the same single line again to clear. The line under the header shows the selection (src/f.ts:2-4 (+ removed 2-3)).▌ marks the selection, • a line with a comment.\ before Enter: it joins the draft shown above the field, and the next line without \ saves the comment. ✕ removes a comment.b goes back to the files view.s in the files view, Send in a file's header) sends every comment to the agent as one message: grouped by file, in line order, each with the lines it is about. The files view's Summary field adds an optional overall note; Enter there submits too. The review goes in as a prompt, so the agent starts on it at once, or as soon as its current turn ends. If the send fails, the comments come back.a in the files view, also in a file's header, or /ml-review accept), when no comment is pending: accepts the review. The agent is told all is good, the saved copies are dropped, and the next review shows only what the agent changes from then on.The mod has no review skill of its own: it attaches the ones you already use. A skill matches bare or under its plugin (bmad-method:bmad-code-review), and only the installed ones are offered.
Which skills are attached, first match wins:
/ml-review attach <skill> and detach <skill> keep your own list; /ml-review skills reset drops it.reviewSkills option, comma-separated. A team sets it for everyone in managed or shared settings: "pluginConfigs": { "moonlightcode": { "options": { "reviewSkills": "deep-review, bmad-code-review, code-review" } } }
bmad-code-review (BMAD) and code-review (Claude Code).i) in the files view. With one skill attached it runs it; with several it asks which. Or /ml-review run <skill>, or invoke an attached skill yourself as usual.moonlight-findings JSON block at the end, the format MoonlightCode's desktop panel reads. Only that skill's prompt gets it, not an attached skill it calls in turn. How the skill reviews is left to it.~/.moonlight/mod/sessions/<session>/baseline/, out of the agent's reach. A copy is named by its content, so the same content is stored once.sed -i, a formatter…) have no copy: switch to Since last commit to see them./clear. A session that ends otherwise keeps them for --resume; after a week without a heartbeat, the next session start removes them.v toggles): everything changed against HEAD. Untracked files count their lines as added (binary ones say so; past 200 untracked files the rest are listed uncounted). If the session's root is inside a git repository, the panel reviews that repository. Otherwise it looks for repositories up to 4 levels below the root, skipping node_modules, target, .venv, dist and build, and lists each one's changes under its folder name.Paths in comments start from the session root.
claude plugin validate .
CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude plugin test .
The mod protects its own folder from the agent in every phase. To let an agent edit it, the operator creates ~/.moonlight/mod/dev-unlock; the agent can't create that file. Plan still applies.
The backstop (hooks/backstop.sh) is a classic PreToolUse hook, registered in ~/.claude/settings.json. It is active only while ~/.moonlight/mod/governed exists. In that state, a session without a fresh heartbeat from the mod can only use read-only tools.
Colour never carries a meaning alone: each phase has its own symbol (◐ Plan, ▶ Auto, ✓ Test, ◎ Review, ■ Commit), each severity its mark (!!! high, !! medium, ! low), and change counts their + / -.
For colour blindness, turn on the colorBlind option: phases and change counts switch to the Okabe–Ito colours, which stay distinct for red-green and blue-yellow colour blindness.
"pluginConfigs": { "moonlightcode": { "options": { "colorBlind": true } } }
Diffs are drawn by Claude Code, in its theme: pick one of its colour-blind themes (/theme, "daltonized"). In the IDEs: VS Code has the moonlight.accessibility.colorBlind setting; JetBrains follows the IDE's own (Settings → Appearance → Accessibility, "Adjust colors for").
hooks/register.tsx 2665 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3import type { MoonlightcodePhaseRequest, MoonlightcodePlan, MoonlightcodeReviewView } from '../types'
4import {
5 anchorLabel,
6 anchorOf,
7 anchorOfRows,
8 continueDraft,
9 excerptOf,
10 excerptOfRows,
11 nextRowSelection,
12 type RowRange,
13 formatReview,
14 inRepo,
15 isInAnchor,
16 isSplit,
17 lineHunk,
18 parseChangedFiles,
19 parseFileDiff,
20 parseRepoDirs,
21 REPO_SEARCH_DEPTH,
22 REPO_SEARCH_SKIP,
23 toSplitRows,
24 baselineOf,
25 baselineStatus,
26 contentHash,
27 effectiveScope,
28 parseBaselineIndex,
29 parseNumstat,
30 type BaselineEntry,
31 type BaselineIndex,
32 type ChangedFile,
33 type DiffLine,
34 type Repo,
35 type ReviewScope,
36 type ReviewLayout,
37 counted,
38 untrackedCount,
39 UNTRACKED_COUNT_MAX,
40} from './review'
41import {
42 canSend,
43 drawable,
44 formatVerdict,
45 isTableRow,
46 parsePlan,
47 planExcerpt,
48 planSpan,
49 presentedAnswer,
50 type PlanComment,
51 type PlanLine,
52 type PlanVerdict,
53} from './plan'
54import { countColors, isColorBlindOption, PHASE_GLYPH, phaseBadge, phaseColor, severityLabel } from './palette'
55import { answer, BRIDGE_VERSION, type InboxEntry, parseInboxEntry, pendingEntries, type ReviewEntry, sessionTitleFrom, titleFromTranscript } from './bridge'
56import { controlUrl, countMisses, discoveryFile, type Governor, hooksInstalled, isHealthy, nextGovernor } from './daemon'
57import {
58 allowWriteBreach,
59 checkSandbox,
60 CLAUDE_PLAN_MODE_TOOLS,
61 gateFailure,
62 parseSettings,
63 allowsNotes,
64 allowsWrites,
65 DEFAULT_WRITABLE,
66 isAllowedInPlan,
67 writesGateFiles,
68 nextPhase,
69 notesFor,
70 phaseFromToken,
71 phaseLabel,
72 PHASES,
73 phaseRule,
74 isUnderAny,
75 mergeOwned,
76 ownedByAnyPhase,
77 newRootEntries,
78 parsePhase,
79 PROJECT_CONFIG_DIR,
80 PROJECT_SETTINGS,
81 projectKey,
82 sandboxListsFor,
83 type Phase,
84 type SandboxWriteLists,
85} from './policy'
86import {
87 DEFAULT_ATTACHED,
88 findingPlace,
89 findingsContract,
90 formatFinding,
91 installedSkills,
92 isAttached,
93 parseFindings,
94 parseSkillList,
95 sortFindings,
96 type TriagedFinding,
97} from './findings'
98
99// MoonlightCode for Claude Code. Everything that touches `$` lives in this one
100// file: the validator follows `$` only into functions declared in the same
101// module. Pure logic is in policy.ts, review.ts, findings.ts and plan.ts.
102//
103// The daemon's five phases: Plan → Auto → Test → Review → Commit → Plan.
104// In the read-only ones (Plan, Commit), project files stay read-only:
105// - Bash runs under Claude Code's own sandbox, configured here per phase;
106// - Edit / Write / NotebookEdit are checked against the notes folders (open
107// in Plan, frozen in Commit) and /tmp;
108// - any other tool runs only when it is on the read-only allow-list.
109// The phase is per project (Plan by default), since the sandbox config it
110// drives is per project too: ~/.moonlight/mod/projects/<root>/phase, which only this mod writes:
111// /phase (typed by the operator) or request_phase (the agent asks, the
112// operator approves). In every phase, the gate's own files (the mod,
113// ~/.moonlight, the project's .moonlight/) are never writable by the agent.
114// To develop the mod, its own folder is unlocked while
115// ~/.moonlight/mod/dev-unlock exists, a file only the operator can create.
116
117type $ = EngineInterface
118
119const OWNED_KEY = 'owned-sandbox-lists'
120const POLL_MS = 2000
121// The phase view: a band above the prompt where the surface draws one
122// (terminal, desktop), and this pane everywhere (VS Code and mobile have no band).
123const PANE = 'moonlight-phase'
124const SURFACES_WITHOUT_BAND: readonly string[] = ['vscode', 'mobile']
125const TOOL = 'request_phase'
126
127let root: string | undefined
128let appliedPhase: Phase | undefined
129let deniedEntries: readonly string[] = []
130// The notes folders, and the scratch folders (/tmp, TMPDIR) open in every phase.
131let noteRoots: string[] = []
132let scratchRoots: string[] = []
133let home: string | undefined
134let projectDir: string | undefined
135let modRoot: string | undefined
136// Who governs this session: the daemon (the mod stands by) or the mod. Unset
137// until session.start decides; the gate hooks govern unless it is 'daemon'.
138let governor: Governor | undefined
139let probing = false
140let missedProbes = 0
141let protectedRoots: string[] = []
142
143// What the band and the dialog draw from: written on change, read while drawing.
144const phaseState = atom({ plugin: 'moonlightcode', key: 'phase' } as const, 'plan' as Phase)
145
146// Each phase's badge and colour, on the hint line, the pane and the status.
147// The colour-blind mode (the `colorBlind` option): Okabe–Ito colours. The
148// symbols and marks that carry each meaning stay in every mode (palette.ts).
149let isColorBlind = false
150
151const phaseStyle = (phase: Phase): { badge: string; color: string } => ({
152 badge: phaseBadge(phase),
153 color: phaseColor(phase, isColorBlind),
154})
155const governorState = atom({ plugin: 'moonlightcode', key: 'governor' } as const, null as Governor | null)
156const pendingState = atom({ plugin: 'moonlightcode', key: 'pending' } as const, null)
157const mcpAllowedState = atom({ plugin: 'moonlightcode', key: 'mcpAllowed' } as const, [] as string[])
158const sessionTitleState = atom({ plugin: 'moonlightcode', key: 'sessionTitle' } as const, null as string | null)
159
160const MCP_ALLOW_ONCE = 'Allow once'
161const MCP_ALLOW_SESSION = 'Allow for this session'
162const MCP_DENY = 'Deny'
163
164// An MCP tool a read-only phase does not list: the operator decides, since only
165// they know what that server does. Their answer, a refusal when the dialog is
166// dismissed or there is no one to ask (a -p run).
167const askForMcpTool = async ($: $, tool: string, label: string): Promise<{ allowed: boolean; said: string }> => {
168 if ((await read($, mcpAllowedState)).includes(tool)) return { allowed: true, said: MCP_ALLOW_SESSION }
169 const said = await $.ui
170 .ask(`Moonlight (${label}) is read-only, and ${tool} is not on its read-only list. Let it run?`, {
171 header: 'MCP tool',
172 options: [MCP_ALLOW_ONCE, MCP_ALLOW_SESSION, MCP_DENY],
173 })
174 .catch(() => MCP_DENY)
175 if (said === MCP_ALLOW_SESSION) await update($, mcpAllowedState, list => [...(list ?? []), tool])
176 return { allowed: said === MCP_ALLOW_ONCE || said === MCP_ALLOW_SESSION, said }
177}
178
179let pending: MoonlightcodePhaseRequest | undefined
180
181const setPending = async ($: $, request: MoonlightcodePhaseRequest | undefined): Promise<void> => {
182 pending = request
183 await update($, pendingState, () => request ?? null)
184 void publishState($).catch(() => undefined)
185}
186
187// ---- Paths ----
188
189// A deny-list on spellings is best effort: compare without case, since a case
190// alias keeps its own spelling on a case-insensitive disk.
191const isUnderAnyFolded = (path: string, roots: readonly string[]): boolean =>
192 isUnderAny(path.toLowerCase(), roots.map(r => r.toLowerCase()))
193
194const isDevUnlocked = async ($: $): Promise<boolean> =>
195 home !== undefined && (await $.fs.exists(`${home}/.moonlight/mod/dev-unlock`))
196
197const listRoot = async ($: $, projectRoot: string): Promise<string[]> =>
198 (await $.fs.list(projectRoot)).map(entry => entry.name)
199
200const realPathOf = async ($: $, path: string): Promise<string | undefined> => {
201 const stat = await $.fs.stat(path, { resolve: true }).catch(() => undefined)
202 return stat?.realPath
203}
204
205// A notes folder that is a symlink could point into src/: it is skipped.
206const resolveNoteRoots = async ($: $, projectRoot: string): Promise<string[]> => {
207 const roots: string[] = []
208 for (const name of DEFAULT_WRITABLE) {
209 const path = `${projectRoot}/${name}`
210 const stat = await $.fs.stat(path).catch(() => undefined)
211 if (stat === undefined) roots.push(path)
212 else if (stat.isLink) $.ui.toast(`Moonlight: ${name} is a symlink, not writable in Plan`)
213 else roots.push(path)
214 }
215 return roots
216}
217
218const resolveScratchRoots = async ($: $): Promise<string[]> => {
219 const roots: string[] = []
220 for (const tmp of ['/tmp', await $.env.get('TMPDIR')]) {
221 if (tmp === undefined || tmp === '') continue
222 const real = await realPathOf($, tmp)
223 if (real !== undefined) roots.push(real)
224 }
225 return roots
226}
227
228// Where a write would land: the nearest existing ancestor's realPath plus the
229// segments that do not exist yet. Undefined when it cannot be told safely.
230const resolveTarget = async ($: $, path: string): Promise<string | undefined> => {
231 if (root === undefined) return undefined
232 let current = path.startsWith('/') ? path : `${root}/${path}`
233 const missing: string[] = []
234 while (current !== '' && current !== '/') {
235 const stat = await $.fs.stat(current, { resolve: true }).catch(() => undefined)
236 if (stat !== undefined) {
237 if (stat.realPath === undefined) return undefined
238 if (missing.some(s => s === '..' || s === '.')) return undefined
239 return [stat.realPath, ...missing].join('/')
240 }
241 const cut = current.lastIndexOf('/')
242 missing.unshift(current.slice(cut + 1))
243 current = current.slice(0, cut)
244 }
245 return undefined
246}
247
248// ---- Phase and sandbox ----
249
250// No project known yet reads as Plan, the safe default.
251const readPhase = async ($: $): Promise<Phase> =>
252 projectDir === undefined ? 'plan' : parsePhase(await $.fs.read(`${projectDir}/phase`).catch(() => undefined))
253
254const settingsPath = (projectRoot: string): string => `${projectRoot}/.claude/settings.local.json`
255
256// Per project: the store is the plugin's, shared by every session on the
257// machine, and one key for all let another project's lists stand for this
258// one's (its own stale entries then stayed, read as the user's).
259const ownedKey = (projectRoot: string): string => `${OWNED_KEY}:${projectKey(projectRoot)}`
260
261// Puts the mod's lists for this project in its settings, replacing what the mod
262// added last time and keeping the user's own entries. With no record for the
263// project, whatever a phase would have added here counts as the mod's.
264// `isOff`: shell commands run outside the sandbox (the writable phases).
265const writeSandboxLists = async (
266 $: $,
267 projectRoot: string,
268 owned: (entries: string[]) => SandboxWriteLists,
269 isOff = false,
270): Promise<SandboxWriteLists> => {
271 const path = settingsPath(projectRoot)
272 const text = await $.fs.read(path).catch(() => '{}')
273 const parsed = parseSettings(text)
274 if ('error' in parsed) {
275 // Thrown: the gate hooks' handlers then refuse every call they guard.
276 $.ui.toast(`Moonlight: ${path} cannot be read (${parsed.error}). Fix it: until then the gate refuses tools.`)
277 throw new Error(`${path}: ${parsed.error}`)
278 }
279 const settings = parsed.settings
280 const sandbox = (settings.sandbox ??= {})
281 sandbox.enabled = !isOff
282 sandbox.allowUnsandboxedCommands = isOff
283 const filesystem = (sandbox.filesystem ??= {})
284 const entries = await listRoot($, projectRoot)
285 const recorded = (await $.store.get(ownedKey(projectRoot))) as SandboxWriteLists | undefined
286 const previous = recorded ?? ownedByAnyPhase(DEFAULT_WRITABLE, entries)
287 const lists = owned(entries)
288 filesystem.denyWrite = mergeOwned(filesystem.denyWrite ?? [], previous.denyWrite, lists.denyWrite)
289 filesystem.allowWrite = mergeOwned(filesystem.allowWrite ?? [], previous.allowWrite, lists.allowWrite)
290 const next = `${JSON.stringify(settings, null, 2)}\n`
291 if (next !== text) await $.fs.write(path, next)
292 await $.store.set(ownedKey(projectRoot), lists)
293 return lists
294}
295
296const applySandbox = async ($: $, phase: Phase): Promise<void> => {
297 if (root === undefined) return
298 // The writable phases run shell commands outside the sandbox: gh, nx and the
299 // like need the network, sockets and folders outside the project, and the
300 // phase already lets the agent write. Plan and Commit keep it.
301 const owned = await writeSandboxLists($, root, entries => sandboxListsFor(phase, DEFAULT_WRITABLE, entries), allowsWrites(phase))
302 deniedEntries = owned.denyWrite
303 appliedPhase = phase
304 await update($, phaseState, () => phase)
305 // The hint line under the prompt shows the phase where it draws; the status
306 // only where it does not (the VS Code extension today), never both.
307 const surfaces = await $.session.surfaces().catch(() => [] as string[])
308 if (surfaces.some(s => SURFACES_WITHOUT_BAND.includes(s)))
309 $.ui.status(`Moonlight: ${phaseStyle(phase).badge.trim()} (${phaseRule(phase)})`)
310}
311
312const syncPhase = async ($: $): Promise<Phase> => {
313 const phase = await readPhase($)
314 if (phase !== appliedPhase) await applySandbox($, phase)
315 return phase
316}
317
318// Only the mod changes the phase: the agent's tools cannot write the file.
319const setPhase = async ($: $, to: Phase): Promise<Phase> => {
320 if (projectDir === undefined) return 'plan'
321 await $.fs.write(`${projectDir}/phase`, `${to}\n`)
322 return syncPhase($)
323}
324
325// Where things are, for the gate and the Review panel alike.
326const initPaths = async ($: $): Promise<void> => {
327 // The project root, not the cwd: a shell `cd` moves the cwd, not the root.
328 root = await realPathOf($, await $.session.root())
329 home = await $.env.get('HOME')
330 if (home !== undefined && root !== undefined) projectDir = `${home}/.moonlight/mod/projects/${projectKey(root)}`
331 modRoot = (await realPathOf($, $.plugin.root)) ?? $.plugin.root
332 protectedRoots = [modRoot]
333 if (home !== undefined) {
334 protectedRoots.push((await realPathOf($, `${home}/.moonlight`)) ?? `${home}/.moonlight`)
335 // Where the backstop is registered.
336 protectedRoots.push(`${home}/.claude/settings.json`)
337 }
338 if (root !== undefined) {
339 protectedRoots.push(`${root}/${PROJECT_CONFIG_DIR}`, ...PROJECT_SETTINGS.map(file => `${root}/${file}`))
340 noteRoots = await resolveNoteRoots($, root)
341 scratchRoots = await resolveScratchRoots($)
342 }
343}
344
345const initGate = async ($: $): Promise<void> => {
346 await initPaths($)
347 if (root !== undefined) await syncPhase($)
348}
349
350// ---- Daemon hand-over ----
351
352const PROBE_TIMEOUT_MS = 3000
353
354// Whether the MoonlightCode daemon governs Claude Code right now: it answers
355// on loopback and reports its hooks installed. Any doubt reads as no, so the
356// mod keeps the gate.
357// `watch`: the daemon is known to govern, so its health is enough (cheap); at
358// session start, its hooks must be installed too.
359const daemonGoverns = async ($: $, watch = false): Promise<boolean> => {
360 const file = discoveryFile(await $.env.get('HOME'), await $.env.get('MOONLIGHT_HOME'))
361 if (file === undefined || !(await $.fs.exists(file))) return false
362 const url = controlUrl(await $.fs.read(file))
363 if (url === undefined) return false
364 const answer = $.http
365 .fetch(`${url}/control/${watch ? 'health' : 'gating-status'}`)
366 .then(response => response.ok && (watch ? isHealthy(response.text) : hooksInstalled(response.text)))
367 .catch(() => false)
368 const late = $.clock.sleep(PROBE_TIMEOUT_MS).then(() => false)
369 return Promise.race([answer, late])
370}
371
372// Whether another session on this project is governed by the mod right now:
373// its state is published (only a governing mod publishes) and its heartbeat fresh.
374const projectGovernedElsewhere = async ($: $): Promise<boolean> => {
375 const sessions = await sessionsDir($)
376 if (sessions === undefined || root === undefined || !(await $.fs.exists(sessions))) return false
377 const me = await $.session.id()
378 const now = await $.clock.now()
379 for (const entry of await $.fs.list(sessions)) {
380 if (entry.kind !== 'dir' || entry.name === me) continue
381 try {
382 const lastBeat = await $.fs.stat(`${sessions}/${entry.name}/heartbeat`)
383 if (now - lastBeat.mtimeMs > HEARTBEAT_FRESH_MS) continue
384 const state = JSON.parse(await $.fs.read(`${sessions}/${entry.name}/state.json`)) as { root?: unknown }
385 if (state.root === root) return true
386 } catch {
387 // No heartbeat or no state: not a session the mod governs.
388 }
389 }
390 return false
391}
392
393// The backstop's own limit (hooks/backstop.sh): a fresher beat is a live mod.
394const HEARTBEAT_FRESH_MS = 10_000
395
396// While the daemon governs, the mod's own deny entries come out of the project's
397// sandbox (the gate's own files stay denied): leftovers from an earlier phase
398// would block the session the daemon governs.
399const releaseSandbox = async ($: $): Promise<void> => {
400 if (root === undefined) return
401 await writeSandboxLists($, root, entries => sandboxListsFor('auto', DEFAULT_WRITABLE, entries))
402}
403
404const setGovernor = async ($: $, to: Governor): Promise<void> => {
405 governor = to
406 await update($, governorState, () => to)
407}
408
409// While the daemon governs, the mod checks on it each tick, and takes the
410// session over once it has stopped (TAKEOVER_AFTER_MISSES probes in a row), in Plan: the stored phase is not trusted, since
411// the mod's sandbox did not guard it while the daemon governed. The operator
412// and the agent are told.
413const watchDaemon = async ($: $): Promise<void> => {
414 if (governor !== 'daemon' || probing) return
415 probing = true
416 try {
417 const governs = await daemonGoverns($, true).catch(() => false)
418 missedProbes = countMisses(missedProbes, governs)
419 if (nextGovernor(governor, governs, missedProbes) === 'daemon') return
420 await setGovernor($, 'mod')
421 await tryStart($, 'the gate', async () => {
422 await initPaths($)
423 // The phase is the project's: another live session the mod governs here
424 // has kept it guarded, so it stands; otherwise it is not trusted.
425 if (await projectGovernedElsewhere($)) await syncPhase($)
426 else await setPhase($, 'plan')
427 })
428 await startGoverned($)
429 const phase = await read($, phaseState)
430 $.ui.toast(`Moonlight: the daemon stopped governing; this session is now gated by the mod (${phaseLabel(phase)})`)
431 await tellModel(
432 $,
433 `[moonlight] The MoonlightCode daemon stopped answering: this session is now governed by the moonlightcode mod, ` +
434 `in the ${phaseLabel(phase)} phase (${phaseRule(phase)}). Use mcp__moonlightcode__request_phase and ` +
435 'mcp__moonlightcode__present_plan from now on, not the mcp__moonlight__ verbs.',
436 )
437 } finally {
438 probing = false
439 }
440}
441
442// ---- Write guard ----
443
444const denyWrite = (path: string, phase: Phase): { deny: string } => ({
445 deny:
446 phase === 'commit'
447 ? `Moonlight (Commit): ${path} cannot be written: the commit gate freezes everything until you commit, ` +
448 `${DEFAULT_WRITABLE.map(w => `${w}/`).join(', ')} included. Only /tmp stays writable. ` +
449 'Wait for the operator to commit, or ask with request_phase.'
450 : `Moonlight (${phaseLabel(phase)}): ${path} is a project file and ${phaseLabel(phase)} is read-only. ` +
451 `Write notes under ${DEFAULT_WRITABLE.map(w => `${w}/`).join(', ')} or /tmp, ` +
452 'then propose the plan.',
453})
454
455const guardSelf = async ($: $, path: string, target: string | undefined): Promise<{ deny: string } | undefined> => {
456 const asGiven = path.startsWith('/') ? path : root === undefined ? undefined : `${root}/${path}`
457 const candidates = [target, asGiven].filter((c): c is string => c !== undefined)
458 const unlocked = await isDevUnlocked($)
459 const roots = protectedRoots.filter(r => !(unlocked && r === modRoot))
460 if (!candidates.some(c => isUnderAnyFolded(c, roots))) return undefined
461 return {
462 deny:
463 `Moonlight: ${path} belongs to the gate itself (the mod, ~/.moonlight, ${PROJECT_CONFIG_DIR}/ or Claude Code's settings) ` +
464 'and is never writable by the agent, in any phase. Ask the operator.',
465 }
466}
467
468const guardWrite = async ($: $, path: string): Promise<{ deny: string } | undefined> => {
469 // The daemon's own hooks gate this session; the mod still keeps its own files
470 // out of the file tools' reach, since a takeover reads them.
471 if (governor === 'daemon') return guardSelf($, path, await resolveTarget($, path))
472 const phase = await syncPhase($)
473 const target = await resolveTarget($, path)
474 const self = await guardSelf($, path, target)
475 if (self !== undefined) return self
476 if (allowsWrites(phase)) return undefined
477 const open = allowsNotes(phase) ? [...noteRoots, ...scratchRoots] : scratchRoots
478 if (target === undefined || !isUnderAny(target, open)) return denyWrite(path, phase)
479 return undefined
480}
481
482// ---- Shell gate (Bash, Monitor) ----
483
484// Why a shell command must not run now, if it must not: the sandbox is not
485// safe, an allowWrite opens the gate's own files, or the deny list this mod
486// applied is not the one the engine runs under (fail closed).
487// Outside the sandbox, the gate's own files (the phase, the project settings)
488// are kept out of reach by reading the command: a write to them is refused.
489const gateFilesRefusal = (command: string, tool: string, phase: Phase): { deny: string } | undefined =>
490 writesGateFiles(command)
491 ? {
492 deny:
493 `Moonlight (${phaseLabel(phase)}): ${tool} refused, it would write the gate's own files ` +
494 '(.moonlight, .claude/settings). Only the operator changes the phase and the settings.',
495 }
496 : undefined
497
498const shellRefusal = async ($: $, tool: string, phase: Phase): Promise<{ deny: string } | undefined> => {
499 const settings = await $.settings.read()
500 const health = checkSandbox(settings)
501 if (!health.isSafe) return { deny: `Moonlight (${phase}): ${tool} refused, the sandbox is not safe: ${health.reason}.` }
502 const allowed = ((settings.sandbox as any)?.filesystem?.allowWrite ?? []) as unknown[]
503 const breach =
504 home !== undefined && root !== undefined
505 ? allowWriteBreach(Array.isArray(allowed) ? allowed : [], home, root, protectedRoots)
506 : undefined
507 if (breach !== undefined)
508 return {
509 deny:
510 `Moonlight (${phase}): ${tool} refused, the sandbox's allowWrite entry ${breach} opens the gate's own files. ` +
511 'Ask the operator to remove it from the settings.',
512 }
513 const effective = ((settings.sandbox as any)?.filesystem?.denyWrite ?? []) as string[]
514 const missing = deniedEntries.filter(entry => !effective.includes(entry))
515 if (appliedPhase !== phase || missing.length > 0)
516 return { deny: `Moonlight (${phase}): ${tool} refused, the deny list is not in force yet.` }
517 return undefined
518}
519
520// After a shell command in a read-only phase. The root stays writable to the
521// sandbox: any top-level entry the command created is denied from now on, and
522// the agent is told.
523const afterShell = async <R extends { deny?: string }>($: $, phase: Phase, ran: R): Promise<R> => {
524 if (allowsWrites(phase) || root === undefined || ran.deny !== undefined) return ran
525 const created = newRootEntries(await listRoot($, root), deniedEntries, notesFor(phase, DEFAULT_WRITABLE))
526 if (created.length === 0) return ran
527 await applySandbox($, phase)
528 const names = created.join(', ')
529 const label = phaseLabel(phase)
530 $.ui.toast(`Moonlight: ${label} — new top-level entry created: ${names}`)
531 return {
532 ...ran,
533 context: [
534 `Moonlight (${label}): this command created ${names} at the project root. ` +
535 `${label} is read-only (${phaseRule(phase)}): it is now write-denied and left for the operator to review. ` +
536 (allowsNotes(phase) ? `Write notes under ${DEFAULT_WRITABLE.map(w => `${w}/`).join(', ')} instead.` : 'Only /tmp stays writable.'),
537 ],
538 }
539}
540
541// ---- Heartbeat ----
542
543// The backstop (hooks/backstop.sh, a classic PreToolUse hook outside this mod)
544// denies writes for a session whose heartbeat is missing or stale: no mod
545// loaded means no gate, so fail closed.
546const beat = async ($: $): Promise<void> => {
547 if (home === undefined) return
548 const id = await $.session.id()
549 if (!SESSION_ID.test(id)) return
550 await $.fs.write(`${home}/.moonlight/mod/sessions/${id}/heartbeat`, `${await $.clock.now()}\n`)
551}
552
553const tick = async ($: $): Promise<void> => {
554 if (governor === 'daemon') await watchDaemon($)
555 else await syncPhase($)
556 await beat($)
557 if (governor === 'mod') {
558 await applyInbox($)
559 await refreshReview($)
560 await refreshTitle($)
561 await publishState($)
562 }
563}
564
565// The session's name, from its transcript every TITLE_REFRESH_TICKS ticks (and
566// at the first): Claude Code names a session after a turn or two, and the
567// operator may rename it at any time. Not left to the classic hooks: they do
568// not reach every session.
569const TITLE_REFRESH_TICKS = 15
570let titleTicks = 0
571let transcriptPath: string | undefined
572
573const refreshTitle = async ($: $): Promise<void> => {
574 titleTicks += 1
575 if (titleTicks % TITLE_REFRESH_TICKS !== 1) return
576 const path = await findTranscript($).catch(() => undefined)
577 if (path !== undefined) await noteTitle($, undefined, path).catch(() => undefined)
578}
579
580// Where Claude Code keeps this session's transcript: under its project folder,
581// named after the session; searched for once when the launch folder differs
582// from the root.
583const findTranscript = async ($: $): Promise<string | undefined> => {
584 if (transcriptPath !== undefined) return transcriptPath
585 const id = await $.session.id()
586 if (home === undefined || !SESSION_ID.test(id)) return undefined
587 const config = (await $.env.get('CLAUDE_CONFIG_DIR')) || `${home}/.claude`
588 const guess = root === undefined ? undefined : `${config}/projects/${projectKey(root)}/${id}.jsonl`
589 if (guess !== undefined && (await $.fs.exists(guess))) return (transcriptPath = guess)
590 const found = await $.process.run(['find', `${config}/projects`, '-maxdepth', '2', '-name', `${id}.jsonl`])
591 const first = found.stdout.split('\n').find(line => line.trim() !== '')
592 return first === undefined ? undefined : (transcriptPath = first.trim())
593}
594
595// The review the IDE shows: recomputed when a baseline was taken or a decision
596// applied, and every REVIEW_REFRESH_TICKS ticks for what changed otherwise
597// (a shell command, an edit outside the session). git runs only then.
598const REVIEW_REFRESH_TICKS = 5
599let reviewDirty = true
600let reviewTicks = 0
601let bridgeSkills: string[] = []
602
603const refreshReview = async ($: $): Promise<void> => {
604 reviewTicks += 1
605 if (!reviewDirty && reviewTicks % REVIEW_REFRESH_TICKS !== 0) return
606 reviewDirty = false
607 // A failed refresh keeps the last list: the phase and plan still publish.
608 await loadChangedFiles($).catch(() => undefined)
609 bridgeSkills = await runnableSkills($).then(r => r.runnable, () => bridgeSkills)
610}
611
612// ---- IDE bridge (bridge.ts) ----
613
614// The session's own folder, beside its heartbeat.
615const sessionFolder = async ($: $): Promise<{ dir: string; id: string } | undefined> => {
616 const sessions = await sessionsDir($)
617 const id = await $.session.id()
618 return sessions === undefined || !SESSION_ID.test(id) ? undefined : { dir: `${sessions}/${id}`, id }
619}
620
621let publishedState: string | undefined
622
623// What the IDE panels show, written while the mod governs and only when it
624// changed: the phase, the request waiting, the latest plan.
625const publishState = async ($: $): Promise<void> => {
626 if (governor !== 'mod') return
627 const at = await sessionFolder($)
628 if (at === undefined) return
629 const doc = await read($, planDocState)
630 const state = {
631 v: BRIDGE_VERSION,
632 sessionId: at.id,
633 root: root ?? null,
634 phase: await read($, phaseState),
635 title: await read($, sessionTitleState),
636 pending: pending === undefined ? null : { to: pending.to, reason: pending.reason },
637 plan: doc === null ? null : doc,
638 review: await reviewForIde($),
639 }
640 const key = JSON.stringify(state)
641 if (key === publishedState) return
642 await $.fs.write(`${at.dir}/state.json`, `${JSON.stringify({ ...state, updatedMs: await $.clock.now() })}\n`)
643 publishedState = key
644}
645
646// The session's name, as the IDE panels list it: Claude Code's own title once it
647// has one; until then the first line of the operator's first prompt, which is
648// what the title is made from anyway.
649// `transcript`: where Claude Code keeps the name it shows (the operator's rename,
650// else the one it generated); read with grep, since a transcript runs to megabytes.
651const noteTitle = async ($: $, title: string | undefined, transcript: string | undefined, prompt?: string): Promise<void> => {
652 let given = title?.trim() || undefined
653 if (given === undefined && transcript !== undefined && transcript !== '') {
654 const found = await $.process
655 .run(['grep', '-h', '-E', '"type":"(custom-title|ai-title)"', '--', transcript])
656 .catch(() => undefined)
657 given = found === undefined ? undefined : titleFromTranscript(found.stdout)
658 }
659 const named = sessionTitleFrom(given, prompt, await read($, sessionTitleState))
660 if (named === (await read($, sessionTitleState))) return
661 await update($, sessionTitleState, () => named)
662 await publishState($)
663}
664
665const reviewForIde = async ($: $) => {
666 const run = await read($, reviewRunState)
667 return {
668 scope: effectiveScope(await read($, reviewScopeState), await read($, reviewHasBaselinesState)),
669 files: (await read($, reviewFilesState)).map(f => ({
670 path: f.path,
671 absolute: `${f.repo}/${f.repoPath}`,
672 status: f.status,
673 added: f.added,
674 removed: f.removed,
675 ...(f.baseline !== undefined ? { baseline: f.baseline } : {}),
676 ...(f.skipped !== undefined ? { skipped: f.skipped } : {}),
677 })),
678 comments: await read($, reviewCommentsState),
679 findings: await read($, reviewFindingsState),
680 findingsStatus: await read($, reviewFindingsStatusState),
681 run: run === null ? null : { skill: run.skill },
682 skills: bridgeSkills,
683 }
684}
685
686// The operator's decisions from the IDE, oldest first, each answered in the
687// outbox; the IDE removes both files once it has read the answer.
688const applyInbox = async ($: $): Promise<void> => {
689 const at = await sessionFolder($)
690 if (at === undefined || !(await $.fs.exists(`${at.dir}/inbox`))) return
691 const names = async (dir: string) =>
692 (await $.fs.exists(dir)) ? (await $.fs.list(dir)).filter(e => e.kind === 'file').map(e => e.name) : []
693 const answered: { name: string; ok: boolean; message: string }[] = []
694 for (const name of pendingEntries(await names(`${at.dir}/inbox`), await names(`${at.dir}/outbox`))) {
695 try {
696 const entry = parseInboxEntry(await $.fs.read(`${at.dir}/inbox/${name}`))
697 answered.push({ name, ...('error' in entry ? { ok: false, message: entry.error } : await applyEntry($, entry)) })
698 } catch (error) {
699 answered.push({ name, ok: false, message: String(error) })
700 }
701 }
702 if (answered.length === 0) return
703 // The state first, the answers after: an IDE that reads its answer then the
704 // state must find the change it asked for already there.
705 reviewDirty = true
706 await refreshReview($)
707 await publishState($)
708 for (const a of answered) await $.fs.write(`${at.dir}/outbox/${a.name}`, answer(a.ok, a.message))
709}
710
711// One review decision, through the functions the Review panel calls.
712const applyReviewEntry = async ($: $, entry: ReviewEntry): Promise<{ ok: boolean; message: string }> => {
713 reviewDirty = true
714 switch (entry.kind) {
715 case 'review-comment': {
716 if (!(await read($, reviewFilesState)).some(f => f.path === entry.path))
717 return { ok: false, message: `${entry.path} is not among the files under review.` }
718 const id = `c${await $.clock.now()}`
719 const { kind: _kind, ...comment } = entry
720 await update($, reviewCommentsState, list => [...(list ?? []), { ...comment, id }])
721 return { ok: true, message: id }
722 }
723 case 'review-comment-edit': {
724 let found = false
725 await update($, reviewCommentsState, list =>
726 (list ?? []).map(c => (c.id === entry.id ? ((found = true), { ...c, body: entry.body }) : c)),
727 )
728 return found ? { ok: true, message: 'Comment updated.' } : { ok: false, message: 'No such comment: it was sent or removed.' }
729 }
730 case 'review-uncomment':
731 await removeReviewComment($, entry.id)
732 return { ok: true, message: 'Comment removed.' }
733 case 'review-submit': {
734 const message = await submitReview($, entry.summary)
735 return { ok: message.startsWith('Review submitted'), message }
736 }
737 case 'review-accept': {
738 const message = await acceptReview($)
739 return { ok: message.startsWith('Review accepted'), message }
740 }
741 case 'review-accept-file':
742 return acceptReviewFile($, entry.path)
743 case 'review-run': {
744 const { runnable } = await runnableSkills($)
745 if (!runnable.includes(entry.skill))
746 return { ok: false, message: `${entry.skill} is not a review skill this session can run (${runnable.join(', ') || 'none'}).` }
747 const message = await runReviewSkill($, entry.skill)
748 return { ok: (await read($, reviewRunState))?.skill === entry.skill, message }
749 }
750 case 'review-cancel':
751 await cancelAiReview($)
752 return { ok: true, message: 'AI review cancelled.' }
753 case 'review-scope':
754 await update($, reviewScopeState, () => entry.scope)
755 await loadChangedFiles($)
756 return { ok: true, message: `Review scope: ${entry.scope === 'session' ? 'changes made in this session' : 'changes since the last commit'}.` }
757 case 'finding': {
758 if (!(await read($, reviewFindingsState)).some(f => f.id === entry.id))
759 return { ok: false, message: 'No such finding: the review was sent or replaced.' }
760 await decideFinding($, entry.id, entry.decision)
761 if (entry.note !== undefined) await saveFindingNote($, entry.id, entry.note)
762 return { ok: true, message: 'Finding updated.' }
763 }
764 }
765}
766
767// One decision, through the functions the panes call.
768const applyEntry = async ($: $, entry: InboxEntry): Promise<{ ok: boolean; message: string }> => {
769 if (entry.kind !== 'phase' && entry.kind !== 'request' && entry.kind !== 'plan') return applyReviewEntry($, entry)
770 if (entry.kind === 'phase') {
771 const now = await operatorSetPhase($, entry.to)
772 $.ui.toast(`Moonlight: phase is now ${phaseLabel(now)} (set from the IDE)`)
773 return { ok: now === entry.to, message: `The phase is ${now}.` }
774 }
775 if (entry.kind === 'request') {
776 if (pending === undefined) return { ok: false, message: 'No phase request is waiting: it was answered already.' }
777 await decide($, entry.approve, entry.reason)
778 return { ok: true, message: entry.approve ? `The phase is ${await readPhase($)}.` : 'Denied: the agent was told.' }
779 }
780 const doc = await read($, planDocState)
781 if (doc === null || doc.version !== entry.version)
782 return { ok: false, message: `Plan v${entry.version} is not the current plan${doc !== null ? ` (v${doc.version} is)` : ''}.` }
783 if (doc.decided !== undefined) return { ok: false, message: `Plan v${doc.version} is already ${VERDICT_WORD[doc.decided]}.` }
784 const count = parsePlan(doc.markdown).length
785 const outside = entry.comments.find(c => c.start < 1 || c.end < c.start || c.end > count)
786 if (outside !== undefined) return { ok: false, message: `No such lines ${outside.start}-${outside.end}: the plan has ${count}.` }
787 for (const c of entry.comments) await addPlanComment($, c.start, c.end, c.body)
788 // A rejection's reason is its own text; any other note joins the panel's.
789 if (entry.verdict !== 'reject' && entry.note !== '')
790 await update($, planNoteState, current => [current.trim(), entry.note].filter(t => t !== '').join('\n\n'))
791 const message = await sendPlanVerdict($, entry.verdict, entry.verdict === 'reject' ? entry.note : undefined)
792 return { ok: (await read($, planDocState))?.decided === entry.verdict, message }
793}
794
795// ---- Phase control ----
796
797// A note the model reads at its next turn; starts none.
798const tellModel = async ($: $, text: string): Promise<void> => {
799 await $.session.append({ message: { type: 'user', content: [{ type: 'text', text }] } })
800}
801
802// A prompt the model acts on: a turn of its own, once the session is idle.
803const askModel = async ($: $, text: string): Promise<void> => {
804 await $.prompt.submit({ text })
805}
806
807// `reason`: why the operator denied it, when they said (the IDE asks).
808const decide = async ($: $, isApproved: boolean, reason?: string): Promise<void> => {
809 const request = pending
810 await setPending($, undefined)
811 if (request === undefined) return
812 if (!isApproved) {
813 $.ui.toast(`Moonlight: phase change to ${request.to} denied`)
814 const denied =
815 `[moonlight] The operator DENIED the phase change to ${request.to}` +
816 (reason !== undefined ? `: ${reason}` : '') +
817 '. Stay in the current phase.'
818 // The agent may be idle, waiting on this answer: a prompt wakes it.
819 void askModel($, denied).catch(() => tellModel($, denied))
820 return
821 }
822 const now = await setPhase($, request.to)
823 $.ui.toast(`Moonlight: phase is now ${phaseLabel(now)} (${phaseRule(now)})`)
824 const told = `[moonlight] The operator APPROVED the phase change. The phase is now ${now}: ${phaseRule(now)}.`
825 void askModel($, told).catch(() => tellModel($, told))
826}
827
828// The operator's own change (/phase, the hint, the pane): any pending request
829// is moot, and the agent learns the new rule at its next turn, from a note
830// that starts no turn of its own.
831const operatorSetPhase = async ($: $, to: Phase): Promise<Phase> => {
832 const before = await readPhase($)
833 await setPending($, undefined)
834 const now = await setPhase($, to)
835 if (now !== before)
836 await tellModel($, `[moonlight] The operator changed the phase to ${now}: ${phaseRule(now)}.`).catch(() => undefined)
837 return now
838}
839
840// Says where the pane stands: a surface may place no panes at all.
841// A pane that cannot open never fails what opened it (a request, a command).
842const openPhasePane = async ($: $, isFocused: boolean): Promise<string> => {
843 try {
844 const opened = await $.ui.open(isFocused ? { id: PANE, title: 'Moonlight', focus: true } : { id: PANE, title: 'Moonlight' })
845 return opened.isPlaced ? 'pane placed' : `pane not placed: ${opened.reason}`
846 } catch (error) {
847 return `pane not opened: ${String(error)}`
848 }
849}
850
851// ---- Review panel ----
852
853// A pane docked on the right in the terminal's fullscreen layout (inline
854// elsewhere): the changed files, then one file's diff where a click on a line
855// number anchors a comment (a second click extends it to a range).
856const REVIEW_PANE = 'moonlight-review'
857const reviewViewState = atom({ plugin: 'moonlightcode', key: 'reviewView' } as const, { kind: 'files' } as MoonlightcodeReviewView)
858const reviewFilesState = atom({ plugin: 'moonlightcode', key: 'reviewFiles' } as const, [])
859const reviewRowsState = atom({ plugin: 'moonlightcode', key: 'reviewRows' } as const, [])
860const reviewSelectionState = atom({ plugin: 'moonlightcode', key: 'reviewSelection' } as const, null)
861const reviewCommentsState = atom({ plugin: 'moonlightcode', key: 'reviewComments' } as const, [])
862// Why there is nothing to review, when it is not simply "no changes".
863const reviewProblemState = atom({ plugin: 'moonlightcode', key: 'reviewProblem' } as const, null)
864// Unified or side by side; `auto` picks side by side when the panel is wide enough.
865const reviewLayoutState = atom({ plugin: 'moonlightcode', key: 'reviewLayout' } as const, 'auto' as ReviewLayout)
866// Docked panel opened at the terminal's full width, like a modal.
867const reviewExpandedState = atom({ plugin: 'moonlightcode', key: 'reviewExpanded' } as const, false)
868// This session's changes (against baselines) or everything against HEAD.
869const reviewScopeState = atom({ plugin: 'moonlightcode', key: 'reviewScope' } as const, 'auto' as ReviewScope)
870const reviewHasBaselinesState = atom({ plugin: 'moonlightcode', key: 'reviewHasBaselines' } as const, false)
871// The lines of a comment being written, before its last one.
872const reviewDraftState = atom({ plugin: 'moonlightcode', key: 'reviewDraft' } as const, [] as string[])
873// The rows picked in the open file's diff; `reviewSelection` is their anchor.
874const reviewRowSelectionState = atom({ plugin: 'moonlightcode', key: 'reviewRowSelection' } as const, null as RowRange | null)
875// What an attached review skill found, with the operator's triage.
876const reviewFindingsState = atom({ plugin: 'moonlightcode', key: 'reviewFindings' } as const, [] as TriagedFinding[])
877const reviewFindingsStatusState = atom({ plugin: 'moonlightcode', key: 'reviewFindingsStatus' } as const, null as string | null)
878const reviewNoteForState = atom({ plugin: 'moonlightcode', key: 'reviewNoteFor' } as const, null as string | null)
879// One AI review at a time; only its skill's prompt gets the contract.
880const reviewRunState = atom(
881 { plugin: 'moonlightcode', key: 'reviewRun' } as const,
882 null as { skill: string; isPrompted: boolean; isFromPanel?: boolean; turnId?: string } | null,
883)
884
885// The prompt a panel run submits; `turn.start` knows the run's turn by it.
886const runPrompt = (skill: string): string => `Run the ${skill} skill to review my changes.`
887
888// The latest turn to start: where a skill started by hand runs.
889let lastTurnId: string | undefined
890const reviewPickingState = atom({ plugin: 'moonlightcode', key: 'reviewPicking' } as const, false)
891
892// Resolved on first use, so the panel works before or without the gate's init.
893let reviewRoot: string | undefined
894
895// The session's project root; the plugin test kit's engine has no `root()`,
896// so fall back to the cwd there.
897const sessionRoot = async ($: $): Promise<string> => {
898 try {
899 return await $.session.root()
900 } catch {
901 return await $.session.cwd()
902 }
903}
904
905const resolveReviewRoot = async ($: $): Promise<string | undefined> =>
906 (reviewRoot ??= root ?? (await realPathOf($, await sessionRoot($))))
907
908// Runs git in `cwd`, the session root by default.
909const git = async ($: $, args: readonly string[], cwd?: string): Promise<string> => {
910 const where = cwd ?? (await resolveReviewRoot($))
911 if (where === undefined) return ''
912 const ran = await $.process.run(['git', ...args], { cwd: where })
913 return ran.stdout
914}
915
916// ---- Baselines ----
917
918// Each file as it was before the agent first changed it this session, so a
919// review shows the agent's changes, git or not. Under ~/.moonlight, which the
920// agent cannot write. Dropped on Accept and on /clear; a session left without
921// either is swept once stale.
922const BASELINE_STALE_MS = 7 * 24 * 60 * 60 * 1000
923const SESSION_ID = /^[A-Za-z0-9_-]+$/
924
925// HOME is read here too, so the panel works before or without the gate's init.
926const sessionsDir = async ($: $): Promise<string | undefined> => {
927 const at = home ?? (await $.env.get('HOME').catch(() => undefined))
928 return at === undefined || at === '' ? undefined : `${at}/.moonlight/mod/sessions`
929}
930
931const baselineDir = async ($: $, sessionId?: string): Promise<string | undefined> => {
932 const sessions = await sessionsDir($)
933 if (sessions === undefined) return undefined
934 const id = sessionId ?? (await $.session.id())
935 return SESSION_ID.test(id) ? `${sessions}/${id}/baseline` : undefined
936}
937
938const readBaselineIndex = async ($: $): Promise<BaselineIndex> => {
939 const dir = await baselineDir($)
940 if (dir === undefined || !(await $.fs.exists(`${dir}/index.json`))) return {}
941 return parseBaselineIndex(await $.fs.read(`${dir}/index.json`))
942}
943
944// Called before an Edit, Write or NotebookEdit runs; only the first change of
945// a file is kept. A failure here never blocks the tool: that file then shows
946// against HEAD.
947// The file as it is now, as a baseline: a copy, `absent` when it does not
948// exist, or why it was not copied.
949const snapshotOf = async ($: $, dir: string, absolute: string): Promise<BaselineEntry> => {
950 if (!(await $.fs.exists(absolute))) return { kind: 'absent' }
951 const kept = baselineOf(await $.fs.read(absolute))
952 if ('reason' in kept) return { kind: 'skipped', reason: kept.reason }
953 const blob = `${dir}/blobs/${contentHash(kept.text)}`
954 if (!(await $.fs.exists(blob))) await $.fs.write(blob, kept.text)
955 return { kind: 'copy', blob }
956}
957
958const captureBaseline = async ($: $, path: string | undefined): Promise<void> => {
959 try {
960 const dir = await baselineDir($)
961 const at = await resolveReviewRoot($)
962 if (dir === undefined || at === undefined || path === undefined) return
963 const given = path.startsWith('/') ? path : `${at}/${path}`
964 // The root is a real path: so is the key, when the file exists.
965 const absolute = (await $.fs.exists(given)) ? ((await realPathOf($, given)) ?? given) : given
966 const index = await readBaselineIndex($)
967 if (index[absolute] !== undefined) return
968 const entry = await snapshotOf($, dir, absolute)
969 await $.fs.write(`${dir}/index.json`, JSON.stringify({ ...index, [absolute]: entry }))
970 reviewDirty = true
971 } catch (error) {
972 $.ui.toast(`Moonlight: no baseline for ${path}: ${String(error)}`)
973 }
974}
975
976// `$.fs` has no delete: `rm -r`, on a session's baseline folder only.
977const dropBaseline = async ($: $, sessionId?: string): Promise<void> => {
978 const dir = await baselineDir($, sessionId)
979 if (dir === undefined || !(await $.fs.exists(dir))) return
980 await $.process.run(['rm', '-r', '--', dir])
981}
982
983// Baselines of sessions whose heartbeat is older than a week: never accepted
984// nor cleared, and not coming back.
985const sweepStaleBaselines = async ($: $): Promise<void> => {
986 const sessions = await sessionsDir($)
987 if (sessions === undefined || !(await $.fs.exists(sessions))) return
988 const now = await $.clock.now()
989 const current = await $.session.id()
990 for (const entry of await $.fs.list(sessions)) {
991 if (entry.name === current || !SESSION_ID.test(entry.name)) continue
992 if (!(await $.fs.exists(`${sessions}/${entry.name}/baseline`))) continue
993 const heartbeat = `${sessions}/${entry.name}/heartbeat`
994 const seenAt = (await $.fs.exists(heartbeat)) ? (await $.fs.stat(heartbeat)).mtimeMs : 0
995 if (now - seenAt > BASELINE_STALE_MS) await dropBaseline($, entry.name)
996 }
997}
998
999// The files changed since their baselines, under the session root.
1000const baselineFiles = async ($: $, at: string): Promise<ChangedFile[]> => {
1001 const files: ChangedFile[] = []
1002 for (const [absolute, entry] of Object.entries(await readBaselineIndex($))) {
1003 if (!absolute.startsWith(`${at}/`)) continue
1004 const path = absolute.slice(at.length + 1)
1005 const isPresent = await $.fs.exists(absolute)
1006 const place = { path, repo: at, repoPath: path, status: baselineStatus(entry, isPresent) }
1007 if (entry.kind === 'skipped') {
1008 files.push({ ...place, added: 0, removed: 0, skipped: entry.reason })
1009 continue
1010 }
1011 const before = entry.kind === 'copy' ? entry.blob : '/dev/null'
1012 if (!isPresent && before === '/dev/null') continue
1013 const stat = parseNumstat(await git($, ['diff', '--no-index', '--numstat', '--', before, isPresent ? absolute : '/dev/null'], at))
1014 if (stat.added === 0 && stat.removed === 0) continue
1015 files.push({ ...place, ...stat, baseline: before })
1016 }
1017 return files.sort((a, b) => a.path.localeCompare(b.path))
1018}
1019
1020// The repositories to review: the one the root is in, else every one found in
1021// its subfolders (a session opened on a folder of projects).
1022const findRepos = async ($: $): Promise<Repo[]> => {
1023 const at = await resolveReviewRoot($)
1024 if (at === undefined) return []
1025 if ((await git($, ['rev-parse', '--is-inside-work-tree'])).trim() === 'true') {
1026 const top = (await git($, ['rev-parse', '--show-toplevel'])).trim()
1027 return [{ dir: top.startsWith('/') ? top : at, prefix: '' }]
1028 }
1029 const skip = REPO_SEARCH_SKIP.flatMap((name, i) => (i === 0 ? ['-name', name] : ['-o', '-name', name]))
1030 const found = await $.process.run(
1031 ['find', at, '-maxdepth', String(REPO_SEARCH_DEPTH), '(', ...skip, ')', '-prune', '-o', '-name', '.git', '-print', '-prune'],
1032 { cwd: at },
1033 )
1034 return parseRepoDirs(found.stdout, at)
1035}
1036
1037const loadChangedFiles = async ($: $): Promise<void> => {
1038 const at = await resolveReviewRoot($)
1039 const sinceBaselines = at === undefined ? [] : await baselineFiles($, at)
1040 const hasBaselines = Object.keys(await readBaselineIndex($)).length > 0
1041 await update($, reviewHasBaselinesState, () => hasBaselines)
1042 if (effectiveScope(await read($, reviewScopeState), hasBaselines) === 'session') {
1043 await update($, reviewProblemState, () => null)
1044 await update($, reviewFilesState, () => sinceBaselines)
1045 return
1046 }
1047 const repos = await findRepos($)
1048 await update($, reviewProblemState, () =>
1049 repos.length > 0
1050 ? null
1051 : `No git repository in ${reviewRoot ?? 'this project'} or its subfolders (${REPO_SEARCH_DEPTH} levels): nothing to diff against.`,
1052 )
1053 const files: ChangedFile[] = []
1054 for (const repo of repos) {
1055 const numstat = await git($, ['diff', '--numstat', 'HEAD'], repo.dir)
1056 const porcelain = await git($, ['status', '--porcelain', '--untracked-files=all'], repo.dir)
1057 const listed = parseChangedFiles(numstat, porcelain)
1058 // `git diff --numstat HEAD` leaves untracked files out: count their lines
1059 // as a diff from nothing, up to a cap.
1060 let counted = 0
1061 for (const file of listed) {
1062 if (file.status !== '??' || file.added !== 0 || file.removed !== 0) continue
1063 if (counted >= UNTRACKED_COUNT_MAX) {
1064 file.skipped = `not counted (over ${UNTRACKED_COUNT_MAX} untracked files)`
1065 continue
1066 }
1067 counted += 1
1068 Object.assign(file, untrackedCount(await git($, ['diff', '--no-index', '--numstat', '--', '/dev/null', file.path], repo.dir)))
1069 }
1070 files.push(...inRepo(listed, repo))
1071 }
1072 await update($, reviewFilesState, () => files)
1073}
1074
1075const diffAgainstHead = async ($: $, inside: string, cwd: string | undefined): Promise<string> => {
1076 const tracked = await git($, ['diff', 'HEAD', '--', inside], cwd)
1077 // An untracked file has no diff against HEAD: show it whole, as added.
1078 return tracked !== '' ? tracked : await git($, ['diff', '--no-index', '--', '/dev/null', inside], cwd)
1079}
1080
1081// Only a file under review: a finding names its file, and the model wrote it.
1082const openReviewFile = async ($: $, path: string): Promise<void> => {
1083 const file = (await read($, reviewFilesState)).find(f => f.path === path)
1084 if (file === undefined) {
1085 $.ui.toast(`Moonlight: ${path} is not among the files under review`)
1086 return
1087 }
1088 const cwd = file?.repo
1089 const inside = file?.repoPath ?? path
1090 const diff =
1091 file?.skipped !== undefined
1092 ? ''
1093 : file?.baseline !== undefined
1094 ? await git($, ['diff', '--no-index', '--', file.baseline, file.status === 'D' ? '/dev/null' : inside], cwd)
1095 : await diffAgainstHead($, inside, cwd)
1096 await update($, reviewRowsState, () => parseFileDiff(diff))
1097 await clearSelection($)
1098 await update($, reviewViewState, () => ({ kind: 'file', path }))
1099}
1100
1101const showReviewFiles = async ($: $): Promise<void> => {
1102 await clearSelection($)
1103 await update($, reviewViewState, () => ({ kind: 'files' }))
1104 await loadChangedFiles($)
1105}
1106
1107const clearSelection = async ($: $): Promise<void> => {
1108 await update($, reviewRowSelectionState, () => null)
1109 await update($, reviewSelectionState, () => null)
1110}
1111
1112// A click picks the row; a second one extends to every row between, removed,
1113// added and context alike. The anchor the comment gets follows from them.
1114// `index`: the row's place in the file's rows, as the render drew them (a
1115// state read hands back copies, so rows are not found by identity here).
1116const clickReviewLine = async ($: $, path: string, index: number): Promise<void> => {
1117 const rows = await read($, reviewRowsState)
1118 const row = rows[index]
1119 if (row === undefined || anchorOf(row) === undefined) return
1120 const range = nextRowSelection(await read($, reviewRowSelectionState), index)
1121 await update($, reviewRowSelectionState, () => range)
1122 await update($, reviewSelectionState, () => (range === null ? null : anchorOfRows(rows, path, range)))
1123 await update($, reviewDraftState, () => [])
1124}
1125
1126// The comment field's Enter: a line ending with `\` joins the draft, any
1127// other line ends the comment.
1128const submitCommentLine = async ($: $, value: string): Promise<void> => {
1129 const next = continueDraft(await read($, reviewDraftState), value)
1130 if ('draft' in next) {
1131 await update($, reviewDraftState, () => next.draft)
1132 return
1133 }
1134 await update($, reviewDraftState, () => [])
1135 await addReviewComment($, next.body)
1136}
1137
1138const addReviewComment = async ($: $, body: string): Promise<void> => {
1139 const text = body.trim()
1140 const anchor = await read($, reviewSelectionState)
1141 if (text === '' || anchor === null) return
1142 const id = `c${await $.clock.now()}`
1143 // The loaded rows are the open file's: from /ml-review comment on another
1144 // file, there is no excerpt.
1145 const view = await read($, reviewViewState)
1146 const picked = await read($, reviewRowSelectionState)
1147 const rows = await read($, reviewRowsState)
1148 const excerpt =
1149 view.kind !== 'file' || view.path !== anchor.path
1150 ? ''
1151 : picked !== null
1152 ? excerptOfRows(rows, picked)
1153 : excerptOf(rows, anchor)
1154 await update($, reviewCommentsState, list => [
1155 ...(list ?? []),
1156 { ...anchor, id, body: text, ...(excerpt !== '' ? { excerpt } : {}) },
1157 ])
1158 await clearSelection($)
1159}
1160
1161const removeReviewComment = async ($: $, id: string): Promise<void> => {
1162 await update($, reviewCommentsState, list => (list ?? []).filter(c => c.id !== id))
1163}
1164
1165// Every file under review, reviewed as it is now.
1166const rebaseAll = async ($: $): Promise<void> => {
1167 const dir = await baselineDir($)
1168 if (dir === undefined) return
1169 const index = await readBaselineIndex($)
1170 const next: BaselineIndex = {}
1171 for (const [absolute, entry] of Object.entries(index)) {
1172 // A file that could not be copied stays listed whatever happens: forgotten.
1173 if (entry.kind === 'skipped') continue
1174 const now = await snapshotOf($, dir, absolute)
1175 if (now.kind !== 'skipped') next[absolute] = now
1176 }
1177 await $.fs.write(`${dir}/index.json`, JSON.stringify(next))
1178}
1179
1180// Closes the review: every file's baseline becomes its current content, so the
1181// next review shows only what the agent changes from here, by any tool; stays
1182// on this session's changes, not HEAD's.
1183const acceptReview = async ($: $): Promise<string> => {
1184 const comments = await read($, reviewCommentsState)
1185 const kept = (await read($, reviewFindingsState)).filter(f => f.decision === 'keep')
1186 if (comments.length > 0 || kept.length > 0) {
1187 const pending = [
1188 ...(comments.length > 0 ? [counted(comments.length, 'comment')] : []),
1189 ...(kept.length > 0 ? [counted(kept.length, 'kept finding')] : []),
1190 ].join(' and ')
1191 const refused = `Not accepted: ${pending} pending. Send them, or remove or dismiss them first.`
1192 $.ui.toast(`Moonlight: ${refused}`)
1193 return refused
1194 }
1195 await update($, reviewFindingsState, () => [])
1196 await update($, reviewFindingsStatusState, () => null)
1197 await rebaseAll($)
1198 await update($, reviewScopeState, () => 'session')
1199 await clearSelection($)
1200 await update($, reviewDraftState, () => [])hooks/review.ts 367 lines1// Pure logic of the Review panel: diff lines, line selection, comments.
2// No `$` here, so it is unit-testable.
3
4export type DiffLineKind = 'context' | 'added' | 'removed' | 'hunk'
5
6// One row of a file's diff, as the panel draws it. `newLine` is the line in
7// the current file (comments anchor there, side After); a removed line has
8// only `oldLine` (side Before).
9export type DiffLine = {
10 kind: DiffLineKind
11 text: string
12 oldLine?: number
13 newLine?: number
14}
15
16// `path`: as shown and commented, relative to the session root (the repo's
17// folder first when the root holds several). `repo`: the repo's absolute
18// folder; `repoPath`: the path inside it, as git takes it. `baseline`: set when
19// the diff is against the file's baseline, not HEAD: the blob, or `/dev/null`;
20// `skipped`: why that file has no diff.
21export type ChangedFile = {
22 path: string
23 status: string
24 added: number
25 removed: number
26 repo: string
27 repoPath: string
28 baseline?: string
29 skipped?: string
30}
31
32// "1 comment", "3 comments": what a person reads, never "comment(s)".
33export const counted = (count: number, word: string): string => `${count} ${word}${count === 1 ? '' : 's'}`
34
35// ---- Baselines: each file as it was before the agent first changed it ----
36
37// Larger files, and binary ones, are not copied: the panel says why instead.
38export const BASELINE_MAX_BYTES = 1_000_000
39
40// `copy`: the blob holding the file as it was; `absent`: the file did not
41// exist (the agent created it); `skipped`: not copied, `reason` says why.
42export type BaselineEntry =
43 | { kind: 'copy'; blob: string }
44 | { kind: 'absent' }
45 | { kind: 'skipped'; reason: string }
46
47// By absolute path.
48export type BaselineIndex = Record<string, BaselineEntry>
49
50export const parseBaselineIndex = (text: string): BaselineIndex => {
51 try {
52 const parsed: unknown = JSON.parse(text)
53 return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as BaselineIndex) : {}
54 } catch {
55 return {}
56 }
57}
58
59// What to keep of a file about to change: its text, or why not.
60export const baselineOf = (text: string): { text: string } | { reason: string } =>
61 text.length > BASELINE_MAX_BYTES
62 ? { reason: `over ${BASELINE_MAX_BYTES / 1_000_000} MB` }
63 : text.includes('\u0000')
64 ? { reason: 'binary' }
65 : { text }
66
67// Names a blob by its content (cyrb53, 53 bits): the same content is stored once.
68export const contentHash = (text: string): string => {
69 let h1 = 0xdeadbeef
70 let h2 = 0x41c6ce57
71 for (let i = 0; i < text.length; i += 1) {
72 const code = text.charCodeAt(i)
73 h1 = Math.imul(h1 ^ code, 2654435761)
74 h2 = Math.imul(h2 ^ code, 1597334677)
75 }
76 h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
77 h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
78 return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, '0')
79}
80
81// A file's status against its baseline: created, deleted, or modified.
82export const baselineStatus = (entry: BaselineEntry, isPresent: boolean): string =>
83 entry.kind === 'absent' ? 'A' : isPresent ? 'M' : 'D'
84
85// The first `git diff --numstat` line's counts.
86export const parseNumstat = (numstat: string): { added: number; removed: number } => {
87 const [added = '0', removed = '0'] = (numstat.split('\n')[0] ?? '').split('\t')
88 return { added: Number(added) || 0, removed: Number(removed) || 0 }
89}
90
91// An untracked file's count, from `git diff --no-index --numstat /dev/null f`:
92// git prints `-` for a binary file, which is not "no lines".
93export const untrackedCount = (numstat: string): { added: number; removed: number } | { skipped: string } =>
94 /^-\t-\t/.test(numstat) ? { skipped: 'binary' } : parseNumstat(numstat)
95
96// Past this many untracked files, the rest are listed uncounted: one git call
97// each, on every refresh, would stall the panel (an un-ignored build folder).
98export const UNTRACKED_COUNT_MAX = 200
99
100// Which changes the panel shows: the agent's since the baselines (`session`),
101// or everything against HEAD; `auto` picks `session` once a baseline exists.
102export type ReviewScope = 'auto' | 'session' | 'head'
103
104export const effectiveScope = (scope: ReviewScope, hasBaselines: boolean): 'session' | 'head' =>
105 scope === 'auto' ? (hasBaselines ? 'session' : 'head') : scope
106
107// A git repository under the session root: its absolute folder, and its folder
108// relative to the root (`''` for the root itself).
109export type Repo = { dir: string; prefix: string }
110
111// How deep under the root to look for repositories, and what never to enter.
112export const REPO_SEARCH_DEPTH = 4
113export const REPO_SEARCH_SKIP = ['node_modules', 'target', '.venv', 'dist', 'build']
114
115// Parses `find` output (one `<dir>/.git` per line) into repos under `root`.
116export const parseRepoDirs = (found: string, root: string): Repo[] =>
117 found
118 .split('\n')
119 .map(line => line.trim())
120 .filter(line => line.endsWith('/.git'))
121 .map(line => line.slice(0, -'/.git'.length))
122 .filter(dir => dir === root || dir.startsWith(`${root}/`))
123 .map(dir => ({ dir, prefix: dir === root ? '' : dir.slice(root.length + 1) }))
124 .sort((a, b) => a.prefix.localeCompare(b.prefix))
125
126// Places one repo's changed files under the session root.
127export const inRepo = (files: readonly Omit<ChangedFile, 'repo' | 'repoPath'>[], repo: Repo): ChangedFile[] =>
128 files.map(file => ({
129 ...file,
130 path: repo.prefix === '' ? file.path : `${repo.prefix}/${file.path}`,
131 repo: repo.dir,
132 repoPath: file.path,
133 }))
134
135export type LineSide = 'before' | 'after'
136
137// A comment's anchor: a line range on one side of a file's diff.
138// `removed`: the old lines a range on the new side also covers.
139export type LineAnchor = {
140 path: string
141 side: LineSide
142 start: number
143 end: number
144 removed?: { start: number; end: number }
145}
146
147// `excerpt`: the commented lines as they were when the comment was written.
148export type ReviewComment = LineAnchor & { id: string; body: string; excerpt?: string }
149
150const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/
151
152// Parses one file's unified diff (`git diff` output) into drawable rows.
153// File headers (`diff --git`, `index`, `---`, `+++`) are skipped.
154export const parseFileDiff = (diff: string): DiffLine[] => {
155 const rows: DiffLine[] = []
156 let oldLine = 0
157 let newLine = 0
158 let isInHunk = false
159 for (const raw of diff.split('\n')) {
160 const header = HUNK_HEADER.exec(raw)
161 if (header !== null) {
162 oldLine = Number(header[1])
163 newLine = Number(header[2])
164 isInHunk = true
165 rows.push({ kind: 'hunk', text: raw })
166 continue
167 }
168 if (!isInHunk || raw.startsWith('\\')) continue
169 if (raw.startsWith('+')) rows.push({ kind: 'added', text: raw.slice(1), newLine: newLine++ })
170 else if (raw.startsWith('-')) rows.push({ kind: 'removed', text: raw.slice(1), oldLine: oldLine++ })
171 else if (raw.startsWith(' ') || raw === '')
172 rows.push({ kind: 'context', text: raw.slice(1), oldLine: oldLine++, newLine: newLine++ })
173 }
174 // A trailing newline in the diff text leaves one empty context row: drop it.
175 while (rows.length > 0 && rows[rows.length - 1]!.kind === 'context' && rows[rows.length - 1]!.text === '' && diff.endsWith('\n'))
176 rows.pop()
177 return rows
178}
179
180// Parses `git diff --numstat` plus `git status --porcelain` into the files list.
181export const parseChangedFiles = (numstat: string, porcelain: string): Omit<ChangedFile, 'repo' | 'repoPath'>[] => {
182 const stats = new Map<string, { added: number; removed: number }>()
183 for (const line of numstat.split('\n')) {
184 const [added, removed, path] = line.split('\t')
185 if (path === undefined) continue
186 stats.set(path, { added: Number(added) || 0, removed: Number(removed) || 0 })
187 }
188 const files: Omit<ChangedFile, 'repo' | 'repoPath'>[] = []
189 for (const line of porcelain.split('\n')) {
190 if (line.length < 4) continue
191 const status = line.slice(0, 2).trim() || 'M'
192 const path = line.slice(3).replace(/^"|"$/g, '').split(' -> ').pop()!
193 const stat = stats.get(path) ?? { added: 0, removed: 0 }
194 files.push({ path, status, ...stat })
195 }
196 return files.sort((a, b) => a.path.localeCompare(b.path))
197}
198
199// Where a row can be commented: the current file's line, else the old one.
200export const anchorOf = (row: DiffLine): { side: LineSide; line: number } | undefined =>
201 row.newLine !== undefined
202 ? { side: 'after', line: row.newLine }
203 : row.oldLine !== undefined
204 ? { side: 'before', line: row.oldLine }
205 : undefined
206
207// Line selection by clicks: a first click picks a line, a second click on the
208// same side extends it to a range, a click on a line already the whole range
209// clears it. A click on the other side starts over there.
210// The rows picked in the open file's diff, by index: a range may mix removed,
211// added and context lines, as a changed block does.
212export type RowRange = { from: number; to: number }
213
214// Click a row; a second click extends to a range; clicking the single picked
215// row again clears it; a click after a range starts over.
216export const nextRowSelection = (current: RowRange | null, clicked: number): RowRange | null => {
217 if (current === null || current.from !== current.to) return { from: clicked, to: clicked }
218 if (current.from === clicked) return null
219 return { from: Math.min(current.from, clicked), to: Math.max(current.from, clicked) }
220}
221
222// Where a comment on those rows anchors: on the current file's lines they
223// cover, the removed lines among them noted aside; on the old lines when
224// they are all removed ones.
225export const anchorOfRows = (rows: readonly DiffLine[], path: string, range: RowRange): LineAnchor | null => {
226 const picked = rows.slice(range.from, range.to + 1)
227 const after = picked.flatMap(r => (r.newLine === undefined ? [] : [r.newLine]))
228 const before = picked.flatMap(r => (r.kind === 'removed' && r.oldLine !== undefined ? [r.oldLine] : []))
229 if (after.length > 0) {
230 const anchor: LineAnchor = { path, side: 'after', start: Math.min(...after), end: Math.max(...after) }
231 return before.length > 0 ? { ...anchor, removed: { start: Math.min(...before), end: Math.max(...before) } } : anchor
232 }
233 return before.length > 0 ? { path, side: 'before', start: Math.min(...before), end: Math.max(...before) } : null
234}
235
236// The picked rows as diff text, so the agent sees what was commented.
237export const excerptOfRows = (rows: readonly DiffLine[], range: RowRange): string =>
238 rows
239 .slice(range.from, range.to + 1)
240 .filter(row => row.kind !== 'hunk')
241 .map(row => `${row.kind === 'added' ? '+' : row.kind === 'removed' ? '-' : ' '}${row.text}`)
242 .join('\n')
243
244// ---- Drawing rows with the engine's diff highlighter ----
245
246// Control characters a `Code` source may not hold (tab is allowed).
247const CONTROL = /[\u0000-\u0008\u000b-\u001f\u007f]/g
248
249// One row as a one-line unified-diff hunk, for a `Code` element with
250// `format: 'diff'`: the engine then draws that row's line numbers, marker,
251// add/remove colour and syntax highlighting, GitHub style.
252export const lineHunk = (row: DiffLine): string => {
253 const text = row.text.replace(CONTROL, '')
254 if (row.kind === 'added') return `@@ -${row.newLine! - 1},0 +${row.newLine},1 @@\n+${text}`
255 if (row.kind === 'removed') return `@@ -${row.oldLine},1 +${row.oldLine! - 1},0 @@\n-${text}`
256 return `@@ -${row.oldLine},1 +${row.newLine},1 @@\n ${text}`
257}
258
259// One row of the side-by-side view: the old file on the left, the new on
260// the right. A changed block pairs its removed lines with its added ones,
261// line by line, as GitHub's split view does; context lines sit on both sides.
262export type SplitRow =
263 | { kind: 'hunk'; text: string }
264 | { kind: 'pair'; left?: DiffLine; right?: DiffLine }
265
266export const toSplitRows = (rows: readonly DiffLine[]): SplitRow[] => {
267 const split: SplitRow[] = []
268 let removed: DiffLine[] = []
269 let added: DiffLine[] = []
270 const flush = (): void => {
271 for (let i = 0; i < Math.max(removed.length, added.length); i += 1)
272 split.push({ kind: 'pair', left: removed[i], right: added[i] })
273 removed = []
274 added = []
275 }
276 for (const row of rows) {
277 if (row.kind === 'removed') {
278 // A removed line after added ones starts a new changed block.
279 if (added.length > 0) flush()
280 removed.push(row)
281 } else if (row.kind === 'added') added.push(row)
282 else {
283 flush()
284 split.push(row.kind === 'hunk' ? { kind: 'hunk', text: row.text } : { kind: 'pair', left: row, right: row })
285 }
286 }
287 flush()
288 return split
289}
290
291// The side-by-side view only when each side keeps room for code.
292export const SPLIT_MIN_COLUMNS = 140
293
294export type ReviewLayout = 'auto' | 'unified' | 'split'
295
296export const isSplit = (layout: ReviewLayout, bodyColumns: number): boolean =>
297 layout === 'split' || (layout === 'auto' && bodyColumns >= SPLIT_MIN_COLUMNS)
298
299export const isInAnchor = (anchor: LineAnchor | null, path: string, side: LineSide, line: number): boolean =>
300 anchor !== null && anchor.path === path && anchor.side === side && line >= anchor.start && line <= anchor.end
301
302const span = (start: number, end: number): string => (start === end ? `${start}` : `${start}-${end}`)
303
304export const anchorLabel = (anchor: LineAnchor): string =>
305 `${anchor.path}:${span(anchor.start, anchor.end)}` +
306 (anchor.side === 'before' ? ' (removed)' : '') +
307 (anchor.removed !== undefined ? ` (+ removed ${span(anchor.removed.start, anchor.removed.end)})` : '')
308
309// A comment of several lines from a one-line field: a line ending with `\`
310// goes on to the next, as in a shell; the first line without it ends the
311// comment. Answers the draft so far, or the whole body.
312export const continueDraft = (draft: readonly string[], value: string): { draft: string[] } | { body: string } => {
313 const line = value.replace(/\s+$/, '')
314 if (line.endsWith('\\')) return { draft: [...draft, line.slice(0, -1).replace(/\s+$/, '')] }
315 return { body: [...draft, line].join('\n').trim() }
316}
317
318// The rows a selection covers, as text, so the agent sees what was commented.
319export const excerptOf = (rows: readonly DiffLine[], anchor: LineAnchor): string =>
320 rows
321 .filter(row => {
322 const at = anchorOf(row)
323 return at !== undefined && isInAnchor(anchor, anchor.path, at.side, at.line)
324 })
325 .map(row => `${row.kind === 'added' ? '+' : row.kind === 'removed' ? '-' : ' '}${row.text}`)
326 .join('\n')
327
328// The review as one message to the agent: an optional summary, then every
329// comment grouped by file, in line order, each with the lines it is about.
330// `findings`: the AI reviewer's findings the operator kept, already formatted;
331// they lead, worst first, with the operator's decision on each.
332export const formatReview = (
333 comments: readonly ReviewComment[],
334 summary: string,
335 findings: readonly string[] = [],
336): string => {
337 const byFile = new Map<string, ReviewComment[]>()
338 for (const comment of comments) byFile.set(comment.path, [...(byFile.get(comment.path) ?? []), comment])
339 const sections = [...byFile.entries()].map(([path, list]) => {
340 const items = [...list]
341 .sort((a, b) => a.start - b.start)
342 .map(c => {
343 const quote =
344 c.excerpt !== undefined && c.excerpt !== ''
345 ? `\n \`\`\`diff\n${c.excerpt.replace(/^/gm, ' ')}\n \`\`\``
346 : ''
347 // A body of several lines stays inside its list item.
348 return `- ${anchorLabel(c)}: ${c.body.replace(/\n/g, '\n ')}${quote}`
349 })
350 return [`### ${path}`, ...items].join('\n')
351 })
352 const parts = [
353 ...(findings.length > 0 ? [`${findings.length} finding(s) the operator kept from the AI review`] : []),
354 ...(comments.length > 0 ? [`${comments.length} comment(s) on ${byFile.size} file(s)`] : []),
355 ]
356 return [
357 `[moonlight] Code review from the operator: ${parts.join(', ')}.`,
358 'Address each item: change the code, or explain why not. A line marked "→ Operator" is their decision ' +
359 'about that finding and wins over the reviewer. Then summarize what you did, per item.',
360 ...(summary.trim() !== '' ? ['', `Summary: ${summary.trim()}`] : []),
361 ...(findings.length > 0 ? ['', '## Findings', ...findings] : []),
362 ...(comments.length > 0 && findings.length > 0 ? ['', '## Comments'] : []),
363 '',
364 ...sections,
365 ].join('\n')
366}
367hooks/plan.ts 122 lines1// Pure logic of the Plan panel: the plan's lines, comments on them, and the
2// messages to the agent. No `$` here, so it is unit-testable.
3
4export type PlanLineKind = 'heading' | 'bullet' | 'code' | 'fence' | 'blank' | 'text'
5
6// One line of the plan as the panel draws it. `line`: 1-based, as comments and
7// /ml-plan name it. `text`: the line as written. `level`: a heading's depth
8// (`#` count), a bullet's or a text line's nesting (2 spaces each, from 0).
9// `lang`: a code line's language, from its opening fence (```ts), and on the
10// opening fence itself; `opens`: the fence opens a block (else it closes one).
11export type PlanLine = { line: number; kind: PlanLineKind; text: string; level?: number; lang?: string; opens?: boolean }
12
13export type PlanVerdict = 'approve' | 'refine' | 'reject'
14
15// A comment on lines `start`-`end` of one plan version. `excerpt`: those lines
16// as they were when the comment was written.
17export type PlanComment = { id: string; start: number; end: number; body: string; excerpt?: string }
18
19const FENCE = /^\s*(```|~~~)/
20const HEADING = /^(#{1,6})\s+\S/
21const BULLET = /^(\s*)(?:[-*+]|\d+[.)])\s+\S/
22
23const linesOf = (markdown: string): string[] => {
24 const lines = markdown.replace(/\r\n?/g, '\n').split('\n')
25 // A final newline is not a line of its own.
26 if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop()
27 return lines
28}
29
30// A fence opens a code block and the next fence closes it: inside, every line
31// is code, `# x` included.
32export const parsePlan = (markdown: string): PlanLine[] => {
33 let isInFence = false
34 let lang = ''
35 const withLang = (l: PlanLine): PlanLine => (lang !== '' ? { ...l, lang } : l)
36 return linesOf(markdown).map((text, i): PlanLine => {
37 const line = i + 1
38 if (FENCE.test(text)) {
39 isInFence = !isInFence
40 if (!isInFence) return { line, kind: 'fence', text, opens: false }
41 lang = text.trim().replace(/^(```|~~~)/, '').trim().split(/\s+/)[0] ?? ''
42 return withLang({ line, kind: 'fence', text, opens: true })
43 }
44 if (isInFence) return withLang({ line, kind: 'code', text })
45 if (text.trim() === '') return { line, kind: 'blank', text }
46 const heading = HEADING.exec(text)
47 if (heading !== null) return { line, kind: 'heading', text, level: heading[1]!.length }
48 const bullet = BULLET.exec(text)
49 if (bullet !== null) return { line, kind: 'bullet', text, level: Math.floor(bullet[1]!.replace(/\t/g, ' ').length / 2) }
50 const indent = /^\s*/.exec(text)![0].replace(/\t/g, ' ').length
51 return indent >= 2 ? { line, kind: 'text', text, level: Math.floor(indent / 2) } : { line, kind: 'text', text }
52 })
53}
54
55// A line as the engine's Markdown and Code elements take it: no control
56// characters but tab, and within their 10000-character limit.
57export const drawable = (text: string): string =>
58 text.replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '').slice(0, 10_000)
59
60// A table row drawn alone is not a table: those lines stay plain text.
61export const isTableRow = (text: string): boolean => /^\s*\|/.test(text)
62
63// Lines `start` to `end` (1-based, inclusive) of the plan.
64export const planExcerpt = (markdown: string, start: number, end: number): string =>
65 linesOf(markdown)
66 .slice(Math.max(0, start - 1), Math.max(0, end))
67 .join('\n')
68
69export const planSpan = ({ start, end }: { start: number; end: number }): string =>
70 start === end ? `line ${start}` : `lines ${start}-${end}`
71
72// What present_plan answers the agent at once: the verdict comes later.
73export const presentedAnswer = (version: number): string =>
74 `[moonlight] Plan v${version} sent to the operator for review in the Plan panel. ` +
75 'Stop here and wait: do not start implementing, and do not call present_plan again until the operator answers. ' +
76 'The verdict arrives as a [moonlight] prompt: APPROVED (implement it), REFINEMENT (revise and present the whole ' +
77 'plan again) or REJECTED (stop). Tell the operator in one line that the plan is in the Plan panel, or that ' +
78 '`/ml-plan` shows it where no panel draws (the VS Code extension).'
79
80const commentItems = (comments: readonly PlanComment[]): string[] =>
81 [...comments]
82 .sort((a, b) => a.start - b.start || a.end - b.end)
83 .map(c => {
84 const quote =
85 c.excerpt !== undefined && c.excerpt !== '' ? `\n${c.excerpt.split('\n').map(l => ` > ${l}`).join('\n')}` : ''
86 return `- ${planSpan(c)}: ${c.body.replace(/\n/g, '\n ')}${quote}`
87 })
88
89// The operator's verdict as one prompt to the agent. `phase`: the phase once
90// the verdict applied (an approval moves Plan to Auto first).
91export const formatVerdict = (
92 verdict: PlanVerdict,
93 version: number,
94 comments: readonly PlanComment[],
95 note: string,
96 phase: string,
97): string => {
98 const said = note.trim()
99 if (verdict === 'approve')
100 return [
101 `[moonlight] Plan v${version} APPROVED by the operator. The phase is now ${phase}: implement the plan.`,
102 ...(said !== '' ? ['', `Operator note: ${said}`] : []),
103 ...(comments.length > 0 ? ['', 'Comments to keep in mind while implementing:', ...commentItems(comments)] : []),
104 ].join('\n')
105 if (verdict === 'refine')
106 return [
107 `[moonlight] The operator asks for a REFINEMENT of plan v${version}. Address every comment, then call ` +
108 'present_plan again with the whole revised plan (not only the changes). Do not start implementing.',
109 ...(said !== '' ? ['', `Operator note: ${said}`] : []),
110 ...(comments.length > 0 ? ['', 'Comments:', ...commentItems(comments)] : []),
111 ].join('\n')
112 return [
113 `[moonlight] Plan v${version} REJECTED by the operator. Stop: do not implement it, and do not present ` +
114 'another plan unless the operator asks for one.',
115 ...(said !== '' ? ['', `Reason: ${said}`] : []),
116 ].join('\n')
117}
118
119// A refinement must say what to change: a comment or a note.
120export const canSend = (verdict: PlanVerdict, comments: readonly PlanComment[], note: string): boolean =>
121 verdict !== 'refine' || comments.length > 0 || note.trim() !== ''
122hooks/palette.ts 54 lines1// How phases, diff counts and severities are drawn. Colour never carries a
2// meaning alone: each phase has its own symbol and each severity its own mark,
3// in every mode. The colour-blind mode swaps the colours for the Okabe–Ito
4// palette, which stays distinct for red-green and blue-yellow colour blindness
5// alike.
6
7import type { Phase } from './policy'
8
9export type Severity = 'high' | 'medium' | 'low'
10
11// One shape per phase: told apart without colour, and in a monochrome terminal.
12export const PHASE_GLYPH: Readonly<Record<Phase, string>> = {
13 plan: '◐',
14 auto: '▶',
15 test: '✓',
16 review: '◎',
17 commit: '■',
18}
19
20const STANDARD_PHASE: Readonly<Record<Phase, string>> = {
21 plan: 'yellow',
22 auto: 'green',
23 test: 'cyan',
24 review: 'blue',
25 commit: 'red',
26}
27
28// Okabe–Ito: orange, blue, sky blue, yellow, vermilion.
29const COLOR_BLIND_PHASE: Readonly<Record<Phase, string>> = {
30 plan: '#E69F00',
31 auto: '#0072B2',
32 test: '#56B4E9',
33 review: '#F0E442',
34 commit: '#D55E00',
35}
36
37export const phaseBadge = (phase: Phase): string => ` ${PHASE_GLYPH[phase]} ${phase.toUpperCase()} `
38
39export const phaseColor = (phase: Phase, isColorBlind: boolean): string =>
40 (isColorBlind ? COLOR_BLIND_PHASE : STANDARD_PHASE)[phase]
41
42// Lines added and removed: blue and orange in the colour-blind mode, as the
43// colour-blind diff themes do; the `+` and `-` say it in every mode.
44export const countColors = (isColorBlind: boolean): { added: string; removed: string } =>
45 isColorBlind ? { added: '#0072B2', removed: '#E69F00' } : { added: 'green', removed: 'red' }
46
47// A mark ahead of the word, so the worst stand out at a glance without colour.
48export const SEVERITY_MARK: Readonly<Record<Severity, string>> = { high: '!!!', medium: '!!', low: '!' }
49
50export const severityLabel = (severity: Severity): string => `${SEVERITY_MARK[severity]} ${severity}`
51
52// The plugin option, as settings give it: a boolean, or its text.
53export const isColorBlindOption = (value: unknown): boolean => value === true || value === 'true'
54hooks/bridge.ts 223 lines1// Pure logic of the file bridge between the mod and the MoonlightCode IDE
2// plugins (VS Code, JetBrains). No `$` here, so it is unit-testable.
3//
4// The mod cannot listen, so the two meet in files, per session, under
5// ~/.moonlight/mod/sessions/<id>/ (the gate refuses the agent there):
6// - state.json: what the IDE panels show, written by the mod while it governs;
7// - inbox/<entry>.json: one operator decision each, written by the IDE;
8// - outbox/<entry>.json: the mod's answer to it. An entry with an answer is
9// done; the IDE removes both files once it has read the answer.
10// The format is versioned: `v` changes when a reader would misread it.
11
12import { PHASES, type Phase } from './policy'
13import type { PlanVerdict } from './plan'
14
15export const BRIDGE_VERSION = 1
16
17export type BridgePlan = { version: number; title: string; markdown: string; decided?: PlanVerdict }
18
19export type BridgeState = {
20 v: number
21 sessionId: string
22 root: string | null
23 // The session's name for the panels; null until it has one.
24 title: string | null
25 phase: Phase
26 pending: { to: Phase; reason: string } | null
27 plan: BridgePlan | null
28 updatedMs: number
29}
30
31const TITLE_MAX = 80
32
33// The session's name as Claude Code keeps it in the transcript: the operator's
34// own (`/rename`, the IDE's rename) wins over the one Claude Code generated; the
35// latest of each counts. `lines`: the transcript's title entries.
36export const titleFromTranscript = (lines: string): string | undefined => {
37 let custom: string | undefined
38 let generated: string | undefined
39 for (const line of lines.split('\n')) {
40 if (line.trim() === '') continue
41 try {
42 const entry = JSON.parse(line) as { type?: unknown; customTitle?: unknown; aiTitle?: unknown }
43 if (entry.type === 'custom-title' && typeof entry.customTitle === 'string') custom = entry.customTitle
44 if (entry.type === 'ai-title' && typeof entry.aiTitle === 'string') generated = entry.aiTitle
45 } catch {
46 // A line cut short or not JSON names nothing.
47 }
48 }
49 return custom?.trim() || generated?.trim() || undefined
50}
51
52// The session's name: Claude Code's title once it has one; until then the one
53// already chosen, else the first line of the operator's first prompt. Commands
54// (`/phase`) and the mod's own prompts name nothing.
55export const sessionTitleFrom = (title: string | undefined, prompt: string | undefined, current: string | null): string | null => {
56 const clip = (s: string) => (s.length > TITLE_MAX ? `${s.slice(0, TITLE_MAX - 1).trimEnd()}…` : s)
57 const given = title?.trim()
58 if (given) return clip(given)
59 if (current !== null) return current
60 const line = prompt?.split('\n').map(l => l.trim()).find(l => l !== '')
61 if (line === undefined || line.startsWith('/') || line.startsWith('[moonlight]') || line.startsWith('The moonlightcode plugin')) return null
62 return clip(line)
63}
64
65export type PlanComment = { start: number; end: number; body: string }
66
67// A diff-line anchor, as the Review panel has it: 1-based lines of one side.
68export type ReviewAnchor = { path: string; side: 'before' | 'after'; start: number; end: number }
69
70export type ReviewEntry =
71 | ({ kind: 'review-comment'; body: string; excerpt?: string } & ReviewAnchor)
72 | { kind: 'review-comment-edit'; id: string; body: string }
73 | { kind: 'review-uncomment'; id: string }
74 | { kind: 'review-submit'; summary: string }
75 | { kind: 'review-accept' }
76 | { kind: 'review-accept-file'; path: string }
77 | { kind: 'review-run'; skill: string }
78 | { kind: 'review-cancel' }
79 | { kind: 'review-scope'; scope: 'session' | 'head' }
80 | { kind: 'finding'; id: string; decision: 'keep' | 'dismiss'; note?: string }
81
82export type InboxEntry =
83 | { kind: 'phase'; to: Phase }
84 | { kind: 'request'; approve: boolean; reason?: string }
85 | { kind: 'plan'; version: number; verdict: PlanVerdict; comments: PlanComment[]; note: string }
86 | ReviewEntry
87
88export type InboxAnswer = { v: number; ok: boolean; message: string }
89
90// An inbox entry's name: what the IDE writes, nothing that climbs or hides.
91export const ENTRY_FILE = /^[A-Za-z0-9_-]{1,64}\.json$/
92
93const VERDICTS: readonly string[] = ['approve', 'refine', 'reject']
94const MAX_TEXT = 20_000
95const MAX_COMMENTS = 200
96
97const text = (value: unknown): string | undefined =>
98 typeof value === 'string' && value.length <= MAX_TEXT ? value : undefined
99
100// An id or a name the IDE echoes back: one short word, nothing that climbs.
101const word = (value: unknown): string | undefined =>
102 typeof value === 'string' && /^[A-Za-z0-9_.:@-]{1,200}$/.test(value) ? value : undefined
103
104// A path as the review lists it: relative to the session root, never climbing.
105const reviewPath = (value: unknown): string | undefined =>
106 typeof value === 'string' && value !== '' && value.length <= 1000 && !value.startsWith('/') &&
107 !value.split('/').includes('..')
108 ? value
109 : undefined
110
111const parseReviewEntry = (e: Record<string, unknown>): ReviewEntry | { error: string } | undefined => {
112 switch (e.kind) {
113 case 'review-comment': {
114 const path = reviewPath(e.path)
115 const body = text(e.body)?.trim()
116 const excerpt = e.excerpt === undefined ? undefined : text(e.excerpt)
117 if (path === undefined) return { error: 'a comment needs the path of a file under review' }
118 if (e.side !== 'before' && e.side !== 'after') return { error: 'a comment side is before or after' }
119 if (!Number.isInteger(e.start) || !Number.isInteger(e.end) || (e.start as number) < 1 || (e.end as number) < (e.start as number))
120 return { error: 'a comment needs 1-based start and end lines' }
121 if (body === undefined || body === '') return { error: 'a comment needs a body' }
122 return {
123 kind: 'review-comment',
124 path,
125 side: e.side,
126 start: e.start as number,
127 end: e.end as number,
128 body,
129 ...(excerpt !== undefined && excerpt !== '' ? { excerpt } : {}),
130 }
131 }
132 case 'review-comment-edit': {
133 const id = word(e.id)
134 const body = text(e.body)?.trim()
135 return id === undefined || body === undefined || body === ''
136 ? { error: 'an edit needs the comment id and its new body' }
137 : { kind: 'review-comment-edit', id, body }
138 }
139 case 'review-uncomment': {
140 const id = word(e.id)
141 return id === undefined ? { error: 'needs the comment id' } : { kind: 'review-uncomment', id }
142 }
143 case 'review-submit': {
144 const summary = e.summary === undefined ? '' : text(e.summary)
145 return summary === undefined ? { error: 'the summary is not text, or too long' } : { kind: 'review-submit', summary: summary.trim() }
146 }
147 case 'review-accept':
148 return { kind: 'review-accept' }
149 case 'review-accept-file': {
150 const path = reviewPath(e.path)
151 return path === undefined ? { error: 'needs the path of a file under review' } : { kind: 'review-accept-file', path }
152 }
153 case 'review-run': {
154 const skill = word(e.skill)
155 return skill === undefined ? { error: 'needs the review skill to run' } : { kind: 'review-run', skill }
156 }
157 case 'review-cancel':
158 return { kind: 'review-cancel' }
159 case 'review-scope':
160 if (e.scope !== 'session' && e.scope !== 'head') return { error: 'a review scope is session or head' }
161 return { kind: 'review-scope', scope: e.scope }
162 case 'finding': {
163 const id = word(e.id)
164 const note = e.note === undefined ? undefined : text(e.note)
165 if (id === undefined) return { error: 'needs the finding id' }
166 if (e.decision !== 'keep' && e.decision !== 'dismiss') return { error: 'a finding is kept or dismissed' }
167 if (e.note !== undefined && note === undefined) return { error: 'the note is not text, or too long' }
168 return { kind: 'finding', id, decision: e.decision, ...(note !== undefined ? { note } : {}) }
169 }
170 default:
171 return undefined
172 }
173}
174
175// Reads one inbox entry. Anything malformed is an error the IDE is told about,
176// never a guess: these are operator decisions.
177export const parseInboxEntry = (raw: string): InboxEntry | { error: string } => {
178 let parsed: unknown
179 try {
180 parsed = JSON.parse(raw)
181 } catch {
182 return { error: 'not JSON' }
183 }
184 const e = (parsed ?? {}) as Record<string, unknown>
185 if (e.v !== BRIDGE_VERSION) return { error: `unsupported version ${String(e.v)} (the mod reads ${BRIDGE_VERSION})` }
186 switch (e.kind) {
187 case 'phase':
188 return PHASES.includes(e.to as Phase) ? { kind: 'phase', to: e.to as Phase } : { error: `unknown phase ${String(e.to)}` }
189 case 'request': {
190 if (typeof e.approve !== 'boolean') return { error: 'a request answer needs approve: true or false' }
191 const reason = text(e.reason)
192 return { kind: 'request', approve: e.approve, ...(reason !== undefined && reason.trim() !== '' ? { reason } : {}) }
193 }
194 case 'plan': {
195 if (!Number.isInteger(e.version) || (e.version as number) < 1) return { error: 'a plan answer needs its plan version' }
196 if (!VERDICTS.includes(String(e.verdict))) return { error: `unknown verdict ${String(e.verdict)}` }
197 const note = e.note === undefined ? '' : text(e.note)
198 if (note === undefined) return { error: 'the note is not text, or too long' }
199 const list = e.comments === undefined ? [] : e.comments
200 if (!Array.isArray(list) || list.length > MAX_COMMENTS) return { error: 'comments must be a list' }
201 const comments: PlanComment[] = []
202 for (const c of list) {
203 const k = (c ?? {}) as Record<string, unknown>
204 const body = text(k.body)
205 if (!Number.isInteger(k.start) || !Number.isInteger(k.end) || body === undefined || body.trim() === '')
206 return { error: 'each comment needs start, end and body' }
207 comments.push({ start: k.start as number, end: k.end as number, body: body.trim() })
208 }
209 return { kind: 'plan', version: e.version as number, verdict: e.verdict as PlanVerdict, comments, note: note.trim() }
210 }
211 default:
212 return parseReviewEntry(e) ?? { error: `unknown kind ${String(e.kind)}` }
213 }
214}
215
216// The entries still to apply: well-named, in the order they were written
217// (names sort by time: the IDE prefixes them with it), none already answered.
218export const pendingEntries = (inbox: readonly string[], answered: readonly string[]): string[] =>
219 inbox.filter(name => ENTRY_FILE.test(name) && !answered.includes(name)).sort()
220
221export const answer = (ok: boolean, message: string): string =>
222 `${JSON.stringify({ v: BRIDGE_VERSION, ok, message } satisfies InboxAnswer)}\n`
223hooks/daemon.ts 77 lines1// Pure logic of the hand-over with the MoonlightCode daemon. No `$` here, so
2// it is unit-testable.
3//
4// The mod is installed into Claude Code itself, so it loads in every session,
5// whoever launched it (a terminal, Anthropic's VS Code or JetBrains plugin).
6// When the daemon answers and its hooks are installed, the daemon governs and
7// the mod stands by; otherwise the mod governs. A session the mod governs
8// stays the mod's (never two gates with two phases); one on standby is taken
9// over as soon as the daemon stops governing.
10
11export type Governor = 'mod' | 'daemon'
12
13// Where the daemon publishes its port: `$MOONLIGHT_HOME/.moonlight/control.json`
14// when MOONLIGHT_HOME is absolute, else under the home directory (the rule the
15// IDE clients follow, moonlight-control-client/src/daemon.ts).
16export const discoveryFile = (home: string | undefined, override: string | undefined): string | undefined => {
17 const anchor = override !== undefined && override.startsWith('/') ? override : home
18 return anchor === undefined ? undefined : `${anchor}/.moonlight/control.json`
19}
20
21// The daemon's control API, from the discovery file: loopback only.
22export const controlUrl = (text: string): string | undefined => {
23 try {
24 const port = (JSON.parse(text) as { port?: unknown }).port
25 return Number.isInteger(port) && (port as number) > 0 && (port as number) < 65536
26 ? `http://127.0.0.1:${port as number}`
27 : undefined
28 } catch {
29 return undefined
30 }
31}
32
33// Whether the daemon's hooks gate Claude Code, from `/control/gating-status`:
34// at least one entry, every one installed. A daemon whose hooks are missing
35// governs nothing, so the mod keeps the gate.
36export const hooksInstalled = (text: string): boolean => {
37 try {
38 const entries = JSON.parse(text) as unknown
39 return (
40 Array.isArray(entries) &&
41 entries.length > 0 &&
42 entries.every(entry => (entry as { installed?: unknown } | null)?.installed === true)
43 )
44 } catch {
45 return false
46 }
47}
48
49// Probes in a row the daemon must miss before the mod takes a session over:
50// a daemon restart (a second or two) must not flip every open session.
51export const TAKEOVER_AFTER_MISSES = 3
52
53// Missed probes so far, after this one: a governing daemon resets the count.
54export const countMisses = (misses: number, daemonGoverns: boolean): number => (daemonGoverns ? 0 : misses + 1)
55
56// Whether `/control/health` answered as the daemon does: a cheap check, for
57// watching a daemon already known to govern (gating-status reads the hook
58// registrations, and can outlast a short timeout on a busy machine).
59export const isHealthy = (text: string): boolean => {
60 try {
61 return Number.isInteger((JSON.parse(text) as { api?: unknown }).api)
62 } catch {
63 return false
64 }
65}
66
67// Who governs from now on. The mod never hands a session back: its phase and
68// sandbox are in force, and a second gate would hold a second phase.
69// `misses`: probes missed in a row while the daemon governed (a session that
70// starts with no daemon is the mod's at once).
71export const nextGovernor = (current: Governor | undefined, daemonGoverns: boolean, misses = 0): Governor =>
72 current === 'mod'
73 ? 'mod'
74 : daemonGoverns || (current === 'daemon' && misses < TAKEOVER_AFTER_MISSES)
75 ? 'daemon'
76 : 'mod'
77hooks/policy.ts 249 lines1// Pure policy of the MoonlightCode gate. No `$` here, so it is unit-testable.
2
3// The daemon's workflow (crates/domain/src/phase.rs), in order. Plan and
4// Commit are read-only; Commit also freezes the notes folders, until the
5// operator commits. `next` is cyclic: Commit → Plan starts the next unit of work.
6export type Phase = 'plan' | 'auto' | 'test' | 'review' | 'commit'
7
8export const PHASES: readonly Phase[] = ['plan', 'auto', 'test', 'review', 'commit']
9
10export type SandboxWriteLists = {
11 denyWrite: readonly string[]
12 allowWrite: readonly string[]
13}
14
15export const DEFAULT_WRITABLE: readonly string[] = ['.ai', '.bmad-output', '.bmad']
16
17// A project's folder name under ~/.moonlight/mod/projects/, encoded the way
18// Claude Code names its own project folders (`/a/b.c` → `-a-b-c`).
19export const projectKey = (root: string): string => root.replace(/[^A-Za-z0-9]/g, '-')
20
21// Project files are writable.
22export const allowsWrites = (phase: Phase): boolean => phase === 'auto' || phase === 'test' || phase === 'review'
23
24// The notes folders are writable: every phase but the commit gate.
25export const allowsNotes = (phase: Phase): boolean => phase !== 'commit'
26
27export const nextPhase = (phase: Phase): Phase => PHASES[(PHASES.indexOf(phase) + 1) % PHASES.length]!
28
29// A phase as typed or requested, with the daemon's aliases; undefined for
30// anything else (`next` included: the caller resolves it against the current phase).
31export const phaseFromToken = (raw: string | undefined): Phase | undefined => {
32 const token = raw?.trim().toLowerCase()
33 if (token === 'plan' || token === 'discovery' || token === 'discover') return 'plan'
34 if (token === 'auto' || token === 'implement' || token === 'autoimplement' || token === 'auto-implement') return 'auto'
35 return token === 'test' || token === 'review' || token === 'commit' ? token : undefined
36}
37
38// The phase file: anything unreadable stays Plan, the safe default.
39export const parsePhase = (raw: string | undefined): Phase => phaseFromToken(raw) ?? 'plan'
40
41export const phaseLabel = (phase: Phase): string => phase.charAt(0).toUpperCase() + phase.slice(1)
42
43// What the phase allows, as the hint line, the pane and the messages say it.
44export const phaseRule = (phase: Phase): string =>
45 phase === 'plan' ? 'project read-only' : phase === 'commit' ? 'everything frozen until you commit' : 'project writable'
46
47// The notes folders open in this phase.
48export const notesFor = (phase: Phase, writable: readonly string[]): readonly string[] =>
49 allowsNotes(phase) ? writable : []
50
51// Paths are written to the project's .claude/settings.local.json, where `./x`
52// resolves under the project root.
53//
54// In the sandbox a denyWrite always wins over an allowWrite, however narrow the
55// allow is, so the root cannot be denied with the notes folders re-opened.
56// A read-only phase instead denies every top-level entry except the notes
57// folders it leaves open (none in Commit). The root itself stays writable: a
58// new top-level entry is caught after the call.
59//
60// The project's .moonlight/ holds the gate's own config: it is write-denied in
61// every phase, so an Auto session cannot widen the next Plan.
62export const PROJECT_CONFIG_DIR = '.moonlight'
63
64// Claude Code's project settings: they hold the sandbox lists the gate writes,
65// and hooks that would run outside it. Write-denied in every phase, so an Auto
66// session cannot widen the next Plan either.
67export const PROJECT_SETTINGS: readonly string[] = ['.claude/settings.json', '.claude/settings.local.json']
68
69export const sandboxListsFor = (
70 phase: Phase,
71 writable: readonly string[],
72 rootEntries: readonly string[],
73): SandboxWriteLists => {
74 const always = [`./${PROJECT_CONFIG_DIR}`, ...PROJECT_SETTINGS.map(file => `./${file}`)]
75 if (allowsWrites(phase)) return { denyWrite: always, allowWrite: [] }
76 const open = notesFor(phase, writable)
77 const entries = rootEntries.filter(name => !open.includes(name)).map(name => `./${name}`)
78 return { denyWrite: [...always, ...entries.filter(e => !always.includes(e))], allowWrite: [] }
79}
80
81// Everything a phase could have added for this root: what counts as the mod's
82// own when there is no record of what it added last.
83export const ownedByAnyPhase = (writable: readonly string[], rootEntries: readonly string[]): SandboxWriteLists => {
84 const lists = PHASES.map(phase => sandboxListsFor(phase, writable, rootEntries))
85 return {
86 denyWrite: [...new Set(lists.flatMap(l => l.denyWrite))],
87 allowWrite: [...new Set(lists.flatMap(l => l.allowWrite))],
88 }
89}
90
91// Top-level entries that appeared since the deny list was built.
92export const newRootEntries = (
93 rootEntries: readonly string[],
94 denied: readonly string[],
95 writable: readonly string[],
96): string[] =>
97 rootEntries.filter(name => !writable.includes(name) && !denied.includes(`./${name}`))
98
99// Replaces the entries this mod added last time with the new ones, keeping
100// whatever the user put there themselves.
101export const mergeOwned = (
102 existing: readonly string[],
103 previouslyOwned: readonly string[],
104 owned: readonly string[],
105): string[] => {
106 const kept = existing.filter(p => !previouslyOwned.includes(p))
107 return [...kept, ...owned.filter(p => !kept.includes(p))]
108}
109
110// In a read-only phase (Plan, Commit), a tool runs only when it is listed here. Everything else is
111// denied: unknown MCP tools (they run outside the sandbox), cross-session and
112// remote tools (another session could write for this one), schedulers.
113// Bash / Monitor / Edit / Write / NotebookEdit are listed because their own hooks gate them.
114const PLAN_ALLOWED_TOOLS: readonly string[] = [
115 'Read', 'Grep', 'Glob', 'LSP', 'WebFetch', 'WebSearch', 'ToolSearch',
116 'TodoWrite', 'AskUserQuestion', 'Skill', 'Agent', 'Task', 'TaskStop', 'Monitor',
117 'Bash', 'Edit', 'Write', 'NotebookEdit',
118 'mcp__moonlightcode__request_phase', 'mcp__moonlightcode__present_plan',
119]
120
121// Claude Code's own plan mode leaves auto mode: in Plan, plans go through
122// present_plan instead, so these are refused with a pointer to it.
123export const CLAUDE_PLAN_MODE_TOOLS: readonly string[] = ['EnterPlanMode', 'ExitPlanMode']
124
125// Read-only MCP tools, by exact name or by prefix (ending in `__` or `_`).
126const PLAN_ALLOWED_MCP: readonly string[] = [
127 'mcp__moonlight__phase_status', 'mcp__moonlight__request_phase',
128 'mcp__moonlight__present_plan', 'mcp__moonlight__report_blocked',
129 'mcp__codegraph__', 'mcp__context7__', 'mcp__exa__',
130 'mcp__github__get_', 'mcp__github__list_', 'mcp__github__search_',
131]
132
133// Jira is planning work, reading and filing tickets alike: it never touches the
134// code. Matched on the whole name, so a `jira` server's tools and Atlassian's
135// `getJiraIssue` / `createJiraIssue` both count, with the account lookup Jira
136// calls lean on. The daemon's classifier holds the same rule.
137export const isJiraTool = (tool: string): boolean =>
138 tool.startsWith('mcp__') && (/jira/i.test(tool) || tool.endsWith('__atlassianUserInfo'))
139
140export const isAllowedInPlan = (tool: string, extra: readonly string[] = []): boolean => {
141 if (PLAN_ALLOWED_TOOLS.includes(tool) || isJiraTool(tool)) return true
142 return [...PLAN_ALLOWED_MCP, ...extra].some(entry =>
143 entry.endsWith('_') ? tool.startsWith(entry) : tool === entry,
144 )
145}
146
147export const isUnder = (path: string, root: string): boolean =>
148 path === root || path.startsWith(root.endsWith('/') ? root : `${root}/`)
149
150export const isUnderAny = (path: string, roots: readonly string[]): boolean =>
151 roots.some(r => isUnder(path, r))
152
153export type SandboxHealth = { isSafe: true } | { isSafe: false; reason: string }
154
155// Whether a shell command, run outside the sandbox, would write the gate's own
156// files: a redirect into them, or a writing program given them. Best effort, on
157// the command's words: reading them, naming them in text, and what a script
158// interpreter does are not seen.
159const GATE_FILE = /\.moonlight\b|\.claude\/settings(\.local)?\.json/
160const GATE_REDIRECT = /(^|[^<>&0-9])>>?\s*['"]?[^\s'"|;&]*(\.moonlight\b|\.claude\/settings(\.local)?\.json)/
161// Programs that write the paths they are given.
162const WRITERS = ['tee', 'mv', 'cp', 'rm', 'rmdir', 'mkdir', 'touch', 'truncate', 'ln', 'chmod', 'chown', 'install', 'rsync', 'dd', 'patch']
163const GIT_WRITES = ['checkout', 'restore', 'rm', 'mv', 'clean']
164
165export const writesGateFiles = (command: string): boolean => {
166 if (GATE_REDIRECT.test(command)) return true
167 return command.split(/\n|;|&&|\|\||\|/).some(segment => {
168 if (!GATE_FILE.test(segment)) return false
169 // The program, past variable assignments and `sudo` / `env`.
170 const words = segment.trim().split(/\s+/).filter(w => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w))
171 while (words[0] === 'sudo' || words[0] === 'env') words.shift()
172 const program = (words[0] ?? '').replace(/^.*\//, '')
173 return (
174 WRITERS.includes(program) ||
175 (program === 'sed' && words.some(w => w.startsWith('-i'))) ||
176 (program === 'git' && GIT_WRITES.includes(words[1] ?? ''))
177 )
178 })
179}
180
181// Fail closed: Plan only trusts Bash when the sandbox cannot be bypassed.
182
183export const checkSandbox = (settings: Readonly<Record<string, unknown>>): SandboxHealth => {
184 const sandbox = (settings.sandbox ?? {}) as Record<string, unknown>
185 if (sandbox.enabled !== true) return { isSafe: false, reason: 'sandbox.enabled is not true' }
186 if (sandbox.allowUnsandboxedCommands !== false)
187 return { isSafe: false, reason: 'sandbox.allowUnsandboxedCommands is not false' }
188 const excluded = sandbox.excludedCommands
189 if (Array.isArray(excluded) && excluded.length > 0)
190 return { isSafe: false, reason: `sandbox.excludedCommands is set (${excluded.join(', ')})` }
191 const filesystem = (sandbox.filesystem ?? {}) as Record<string, unknown>
192 if (filesystem.disabled === true)
193 return { isSafe: false, reason: 'sandbox.filesystem.disabled is true' }
194 return { isSafe: true }
195}
196
197// The project's .claude/settings.local.json, as the gate edits it: an object
198// whose `sandbox.filesystem` lists are string arrays. Anything else is
199// refused, so the gate fails closed instead of writing over what it misreads.
200export const parseSettings = (text: string): { settings: Record<string, any> } | { error: string } => {
201 let parsed: unknown
202 try {
203 parsed = JSON.parse(text.trim() === '' ? '{}' : text)
204 } catch (error) {
205 return { error: `it is not valid JSON (${String(error)})` }
206 }
207 const isObject = (value: unknown): value is Record<string, unknown> =>
208 value !== null && typeof value === 'object' && !Array.isArray(value)
209 if (!isObject(parsed)) return { error: 'it is not a JSON object' }
210 const sandbox = parsed.sandbox
211 if (sandbox !== undefined && !isObject(sandbox)) return { error: '`sandbox` is not an object' }
212 const filesystem = sandbox?.filesystem
213 if (filesystem !== undefined && !isObject(filesystem)) return { error: '`sandbox.filesystem` is not an object' }
214 for (const key of ['denyWrite', 'allowWrite']) {
215 const list = filesystem?.[key]
216 if (list !== undefined && !(Array.isArray(list) && list.every(item => typeof item === 'string')))
217 return { error: `\`sandbox.filesystem.${key}\` is not a list of paths` }
218 }
219 return { settings: parsed }
220}
221
222// Why a gate hook that failed refuses its call: the engine skips a failed hook
223// that has no handler, which for a gate would let the call through.
224export const gateFailure = (failure: { kind: 'throw' | 'timeout'; message?: string }): string =>
225 'Moonlight: the gate could not check this call ' +
226 (failure.kind === 'timeout' ? '(it ran out of time)' : `(${failure.message ?? 'it failed'})`) +
227 ', so it is refused. Ask the operator.'
228
229// An `allowWrite` entry of the effective sandbox that opens a protected folder
230// (the entry lies under it, or holds it): with it, a sandboxed command could
231// write the gate's own files. `~` and `./` are expanded as the sandbox does.
232export const allowWriteBreach = (
233 allowWrite: readonly unknown[],
234 home: string,
235 projectRoot: string,
236 protectedRoots: readonly string[],
237): string | undefined =>
238 allowWrite
239 .filter((entry): entry is string => typeof entry === 'string')
240 .find(entry => {
241 const path = entry.startsWith('~')
242 ? `${home}${entry.slice(1)}`
243 : entry.startsWith('/')
244 ? entry
245 : `${projectRoot}/${entry.replace(/^\.\//, '')}`
246 const clean = path.length > 1 ? path.replace(/\/+$/, '') : path
247 return protectedRoots.some(r => isUnder(clean, r) || isUnder(r, clean))
248 })
249hooks/findings.ts 165 lines1// Pure logic of review findings: attaching an existing review skill, reading
2// what it found, and the operator's triage. No `$` here, so it is unit-testable.
3//
4// The output contract is the one `moonlight-review` and the desktop panel use
5// (packaging/skills/moonlight-review/SKILL.md): one fenced `moonlight-findings`
6// JSON block, last in the answer.
7
8export type Severity = 'high' | 'medium' | 'low'
9export type Route = 'patch' | 'decision' | 'defer'
10
11export type Finding = {
12 key: string
13 severity: Severity
14 route: Route
15 owner: string[]
16 file: string
17 line: number
18 summary: string
19 detail: string
20 fix?: string
21}
22
23// A finding plus the operator's call on it: kept (sent with the review, with
24// the note as the decision) or dismissed (dropped from this pass).
25export type TriagedFinding = Finding & { id: string; decision: 'keep' | 'dismiss'; note?: string }
26
27export type FindingsReport = { findings: Finding[]; notes: string; lanesFailed: string[] }
28
29// Review skills attached when neither the plugin option nor the operator says
30// otherwise: BMAD's and Claude Code's. A team adds its own through the
31// `reviewSkills` option (plugin.json), not here.
32export const DEFAULT_ATTACHED = ['bmad-code-review', 'code-review']
33
34// The `reviewSkills` option: names separated by commas or spaces.
35export const parseSkillList = (text: unknown): string[] | undefined => {
36 if (typeof text !== 'string') return undefined
37 const names = text.split(/[\s,]+/).filter(name => name !== '')
38 return names.length > 0 ? [...new Set(names)] : undefined
39}
40
41// The attached skills the session can run, by the names its commands list
42// (`plugin:name` or bare); with no list to go by, all of them.
43export const installedSkills = (attached: readonly string[], commands: readonly string[] | undefined): string[] =>
44 commands === undefined ? [...attached] : attached.filter(skill => commands.some(name => isAttached(name, [skill])))
45
46// A skill matches by its name, bare or under its plugin (`plugin:name`).
47export const isAttached = (skill: string, attached: readonly string[]): boolean =>
48 attached.some(name => skill === name || skill.endsWith(`:${name}`))
49
50const SEVERITIES: readonly string[] = ['high', 'medium', 'low']
51const ROUTES: readonly string[] = ['patch', 'decision', 'defer']
52
53const FENCE = '```moonlight-findings'
54
55// Reads the last findings block of an answer. A block that is missing or does
56// not parse is an error, never an empty review: a failed review must not read
57// as a clean one.
58export const parseFindings = (answer: string): FindingsReport | { error: string } => {
59 const start = answer.lastIndexOf(FENCE)
60 if (start < 0) return { error: 'no moonlight-findings block in the answer' }
61 const body = answer.slice(start + FENCE.length)
62 const end = body.indexOf('```')
63 if (end < 0) return { error: 'the moonlight-findings block is not closed' }
64 let parsed: unknown
65 try {
66 parsed = JSON.parse(body.slice(0, end))
67 } catch (error) {
68 return { error: `the moonlight-findings block is not JSON: ${String(error)}` }
69 }
70 const root = (parsed ?? {}) as { findings?: unknown; coverage?: { notes?: unknown; lanes_failed?: unknown } }
71 if (!Array.isArray(root.findings)) return { error: 'the moonlight-findings block has no findings array' }
72 const findings: Finding[] = []
73 for (const [i, raw] of root.findings.entries()) {
74 const f = (raw ?? {}) as Record<string, unknown>
75 if (!SEVERITIES.includes(String(f.severity))) return { error: `finding ${i + 1}: unknown severity ${String(f.severity)}` }
76 if (typeof f.file !== 'string' || typeof f.summary !== 'string' || !Number.isInteger(f.line))
77 return { error: `finding ${i + 1}: needs file, line and summary` }
78 findings.push({
79 key: typeof f.key === 'string' && f.key !== '' ? f.key : `F${i + 1}`,
80 severity: f.severity as Severity,
81 route: ROUTES.includes(String(f.route)) ? (f.route as Route) : 'decision',
82 owner: Array.isArray(f.owner) ? f.owner.map(String) : [],
83 file: f.file,
84 line: f.line as number,
85 summary: f.summary,
86 detail: typeof f.detail === 'string' ? f.detail : '',
87 ...(typeof f.fix === 'string' && f.fix !== '' ? { fix: f.fix } : {}),
88 })
89 }
90 const coverage = root.coverage ?? {}
91 return {
92 findings: sortFindings(findings),
93 notes: typeof coverage.notes === 'string' ? coverage.notes : '',
94 lanesFailed: Array.isArray(coverage.lanes_failed) ? coverage.lanes_failed.map(String) : [],
95 }
96}
97
98const RANK: Record<Severity, number> = { high: 0, medium: 1, low: 2 }
99
100// Worst first, then by place: the order a reviewer wants to read.
101export const sortFindings = <F extends Finding>(findings: readonly F[]): F[] =>
102 [...findings].sort(
103 (a, b) => RANK[a.severity] - RANK[b.severity] || a.file.localeCompare(b.file) || a.line - b.line,
104 )
105
106// What the review covers, for the skill: each file with the copy it is to be
107// diffed against, or the repo to diff against HEAD.
108export type ScopeFile = { path: string; baseline?: string; status: string }
109
110// A path as one shell word, for the commands the contract hands the skill.
111export const shellQuote = (text: string): string => `'${text.replace(/'/g, `'\\''`)}'`
112
113// Appended to an attached skill's prompt: what to review and how to answer.
114// It leaves how the skill reviews alone.
115export const findingsContract = (root: string, scope: 'session' | 'head', files: readonly ScopeFile[]): string => {
116 const list = files.map(f => {
117 if (f.baseline === undefined) return `- ${f.path} (${f.status}; diff against HEAD in its repository)`
118 return f.baseline === '/dev/null'
119 ? `- ${f.path} (created this session: all of it is new)`
120 : `- ${f.path} (before this session: ${f.baseline}; diff with \`git diff --no-index -- ${shellQuote(f.baseline)} ${shellQuote(`${root}/${f.path}`)}\`)`
121 })
122 return [
123 '',
124 '---',
125 '[moonlight] The operator reviews your findings in the MoonlightCode Review panel. Two additions to this review:',
126 '',
127 `1. Scope. Review these files under ${root} (${scope === 'session' ? "this session's changes, against the copies saved before the session changed them" : 'everything changed against HEAD'}):`,
128 ...(list.length > 0 ? list : ['- (no changed files: say so in coverage.notes)']),
129 '',
130 '2. Output. Run the review exactly as this skill says, then end your answer with ONE fenced block, nothing after it:',
131 '',
132 '```moonlight-findings',
133 '{ "coverage": { "notes": "what was or was not checked" },',
134 ' "findings": [ { "key": "H1", "severity": "high|medium|low", "route": "patch|decision|defer",',
135 ' "owner": ["who raised it"], "file": "path as listed above", "line": 12,',
136 ' "summary": "one line, read as a claim", "detail": "why it is true, where it is reachable from", "fix": "optional" } ] }',
137 '```',
138 '',
139 '`line` is 1-based in the file as it is now. Emit the block even with no findings: an empty array is a result.',
140 '',
141 'If the skill runs in the background or in a subagent, it only gets what you pass it: pass it this scope, and',
142 'write the block yourself in the answer where you report its results, with every finding it returned.',
143 ].join('\n')
144}
145
146// Where a finding is, short enough for a button in a docked panel: the last
147// two segments of its path. A button does not shrink, so a long path would
148// push the rest of its row out of sight.
149export const findingPlace = (file: string, line: number): string => `${file.split('/').slice(-2).join('/')}:${line}`
150
151// The marker of the operator's decision belongs to the operator alone: the
152// reviewer's text (the model's) cannot carry it.
153const OPERATOR_MARK = '→'
154const asReviewer = (text: string): string => text.replaceAll(OPERATOR_MARK, '->')
155
156// A kept finding as the agent reads it, the operator's note labelled as theirs.
157export const formatFinding = (f: TriagedFinding): string => {
158 const lines = [`- ${f.file}:${f.line} [${f.severity}, ${f.route}] ${asReviewer(f.summary)}`]
159 if (f.detail !== '') lines.push(...f.detail.split('\n').map(l => ` ${asReviewer(l)}`))
160 if (f.fix !== undefined)
161 lines.push(...asReviewer(f.fix).split('\n').map((l, i) => (i === 0 ? ` Suggested fix: ${l}` : ` ${l}`)))
162 if (f.note !== undefined) lines.push(...f.note.split('\n').map(l => ` ${OPERATOR_MARK} Operator: ${l}`))
163 return lines.join('\n')
164}
165types/index.d.ts 109 lines1export type MoonlightcodePhase = 'plan' | 'auto' | 'test' | 'review' | 'commit'
2
3export type MoonlightcodePhaseRequest = { to: MoonlightcodePhase; reason: string }
4
5export type MoonlightcodeReviewView = { kind: 'files' } | { kind: 'file'; path: string }
6
7export type MoonlightcodeChangedFile = {
8 path: string
9 status: string
10 added: number
11 removed: number
12 repo: string
13 repoPath: string
14 baseline?: string
15 skipped?: string
16}
17
18export type MoonlightcodeDiffLine = {
19 kind: 'context' | 'added' | 'removed' | 'hunk'
20 text: string
21 oldLine?: number
22 newLine?: number
23}
24
25export type MoonlightcodeLineAnchor = {
26 path: string
27 side: 'before' | 'after'
28 start: number
29 end: number
30 removed?: { start: number; end: number }
31}
32
33export type MoonlightcodeReviewComment = MoonlightcodeLineAnchor & { id: string; body: string; excerpt?: string }
34
35export type MoonlightcodeTriagedFinding = {
36 id: string
37 key: string
38 severity: 'high' | 'medium' | 'low'
39 route: 'patch' | 'decision' | 'defer'
40 owner: string[]
41 file: string
42 line: number
43 summary: string
44 detail: string
45 fix?: string
46 decision: 'keep' | 'dismiss'
47 note?: string
48}
49
50// One version of the agent's plan, as present_plan gave it. `decided`: the
51// operator's verdict on it, once sent.
52export type MoonlightcodePlan = {
53 version: number
54 title: string
55 markdown: string
56 decided?: 'approve' | 'refine' | 'reject'
57}
58
59export type MoonlightcodePlanComment = { id: string; start: number; end: number; body: string; excerpt?: string }
60
61declare module 'claude-code' {
62 interface PluginState {
63 moonlightcode: {
64 phase: MoonlightcodePhase
65 // Who governs the session: the daemon (the mod stands by) or the mod;
66 // null until session.start decides.
67 governor: 'mod' | 'daemon' | null
68 // MCP tools the operator allowed for the rest of the session in a
69 // read-only phase.
70 mcpAllowed: string[]
71 // The session's name for the IDE panels: Claude Code's title, else the
72 // first line of the operator's first prompt.
73 sessionTitle: string | null
74 pending: MoonlightcodePhaseRequest | null
75 reviewView: MoonlightcodeReviewView
76 reviewFiles: MoonlightcodeChangedFile[]
77 reviewRows: MoonlightcodeDiffLine[]
78 reviewSelection: MoonlightcodeLineAnchor | null
79 reviewComments: MoonlightcodeReviewComment[]
80 reviewProblem: string | null
81 reviewLayout: 'auto' | 'unified' | 'split'
82 reviewExpanded: boolean
83 reviewScope: 'auto' | 'session' | 'head'
84 reviewHasBaselines: boolean
85 reviewDraft: string[]
86 reviewRowSelection: { from: number; to: number } | null
87 reviewFindings: MoonlightcodeTriagedFinding[]
88 // What the last AI review said of its own coverage, or why it failed.
89 reviewFindingsStatus: string | null
90 // The finding whose note is being written.
91 reviewNoteFor: string | null
92 // The one AI review running: its skill, whether its prompt got the
93 // contract, and the turn it runs in (its end ends the run).
94 reviewRun: { skill: string; isPrompted: boolean; isFromPanel?: boolean; turnId?: string } | null
95 // The skill picker of "Run AI review" is open.
96 reviewPicking: boolean
97 // The plan under review (the latest version), its comments, the lines
98 // picked (0-based rows), a comment being written, the overall note, and
99 // whether Reject is asking for its reason.
100 planDoc: MoonlightcodePlan | null
101 planComments: MoonlightcodePlanComment[]
102 planRowSelection: { from: number; to: number } | null
103 planDraft: string[]
104 planNote: string
105 planRejecting: boolean
106 }
107 }
108}
109