SLOPSHOPPER

motive-mem

After every turn, a separate model reviews what changed against your repo's .claude/principles.md — intent, principle violations, band-aid fixes — and shows it…

panecommandtoaststatusmodelprocess
v0.1.2MITupdated 2026-10-16wjsekrud/motive-mem
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · motive-mem
│ ┃ motive-mem ✕ › fix the failing auth test and add an audit log call │ ┃ No reviews yet. They show up here when a │ ┃ turn that changed code ends. ⏺ Read(src/auth.ts) │ ┃ [ Review all uncommitted ] ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /motive-mem │ ⎿ motive-mem: Intent review is idle: this is not a git repository. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · motive-mem
No reviews yet. They show up here when a turn that changed code ends. [ Review all uncommitted ]
README

Motive-mem

한국어

A Claude Code mod that reviews intent, not lines. Each time a turn ends, a model other than the one that wrote the code checks what that turn changed against your repository's .claude/principles.md.

  • Intent match — does the diff match the request and Claude's report? Changes missing from the report, reports that claim more than happened.
  • Principle violations — did it break a principle your repository has settled (layers, single paths, "the one place", promises)?
  • Band-aid fixes — traces of routing around the structure to make a local problem go away (skipping the entry point, a second copy, changing test expectations …).

<img src="docs/panel.png" alt="The review panel after a turn: what the turn did, whether it matches intent, three suspected principle violations (P05, P06, P07) each with its file, line and code, where a person should look, the files the turn touched, and buttons to send the findings to Claude, review again or approve a finding as an exception">

The panel after a turn.

Inspired by Anthropic's Redesigning source control (Scion · Antique) — people review intent rather than lines, and the recurring job is an agent saying "no" when a change breaks a core principle.

Cost: every turn that changes code makes one extra model call on your account (default sonnet, medium effort; the principles file is prompt-cached). Turns that touch only comments or docs are skipped, and in a repository without a principles file nothing runs at all.

How it works

  1. When you send a message, the working tree is snapshotted with git stash create (the tree itself is untouched).
  2. When the answer ends, it snapshots again and takes only the diff in between. Comment- or docs-only changes are skipped.
  3. A separate model (default sonnet) gets only the principles, the request, Claude's last report and the diff — never the author's reasoning.
  4. The status line and a toast report the result; when there are findings, a panel opens with Send to Claude, Review again and Approve as exception. Approved exceptions are kept in .git/motive-mem/decisions/ and are not raised again.

It turns on only when the session folder is inside a git repository that has .claude/principles.md. Install it at user scope; it wakes up only where a principles file exists.

Install

Requires Claude Code with mods (plugin hooks modules). Built and tested on Claude Code 2.1.299 — the mod API is early access and may change between releases.

claude plugin marketplace add wjsekrud/motive-mem
claude plugin install motive-mem@motive-mem

Then, in a repository you want reviewed, create its principles file with /motive-mem:principles.

Command
/motive-memOpen the panel
/motive-mem allReview all uncommitted changes
/motive-mem pause · resumeStop · restart automatic review
/motive-mem:principlesCreate or revise the principles file (skill)

Settings

/plugin configure motive-mem@motive-mem

SettingDefault
languageenPanel, status line and review text — en or ko. Principles files can be in any language.
modelsonnetThe review model. opus judges hard cases better and costs more.
effortmediumHow hard the review model thinks.
maxDiffChars60000Past this, code files go in first and the rest are listed by name only.
openOnIssuetrueOpen the panel when there is a violation, a suspect, or a change missing from the report.

The principles file

Principles are dug out, not invented. The skill finds what people already decided — in CLAUDE.md, design docs, docstrings of code and tests, reverted history — shows it as a table for you to confirm, and only then writes the file. A growing principles file is itself the drift this mode exists to stop, so adding a principle needs evidence and removing one needs only that the evidence was wrong.

## P02 Order status changes only in orders/transitions.py
- Scope: orders/**, api/handlers/**, jobs/**
- Rule: only `transitions.apply(order, event)` changes `Order.status` — the audit log and webhooks hang off it.
- Signal: `order.status =` outside `transitions.py`; loosening `test_status_only_changes_through_apply`.
- Evidence: ARCHITECTURE.md "State transitions"; the 2026-03 hotfix that refunded twice (reverted).

Criteria and procedure: skills/principles/SKILL.md. Format: skills/principles/references/format.md.

Limitations

  • One model call per turn that changes code.
  • Edits to files that were never tracked are invisible; up to 30 new untracked files per turn.
  • A turn git cannot snapshot — another git command holding the index lock, a merge in progress, an intent-to-add entry — is not reviewed; the status line says so.
  • The same model family writes and reviews, so their blind spots can overlap.
  • The mod API is early access — if the mod stops loading after a Claude Code update, check for a newer version.

Development

See CLAUDE.md. To run from a clone, add the folder itself as a marketplace — the install is then the folder, so edits apply after /reload-plugins:

claude plugin marketplace add /path/to/Motive-mem
claude plugin install motive-mem@motive-mem

License

MIT

Source 4 files
hooks/register.tsx 570 lines
1// Intent review: when a turn ends, a separate model checks what that turn changed against the repository's
2// .claude/principles.md. It gets the request, the report, the diff and the principles — never the author's
3// (Claude's) reasoning. Results go to the status line, a toast and a panel.
4// The start and end of a turn are snapshotted with `git stash create` (the working tree is never touched),
5// and only the diff between them is reviewed.
6
7import { atom, read, update } from 'claude-code'
8import type { EngineInterface, Register } from 'claude-code'
9
10import type { Decision, FileChange, Intent, Review } from '../types'
11import {
12  BINARY,
13  PRINCIPLES_PATH,
14  buildPrompt,
15  cut,
16  fixPrompt,
17  forLog,
18  hasIssues,
19  kindOf,
20  latestById,
21  levelOf,
22  openFindings,
23  parseDiff,
24  parsePrinciples,
25  parseVerdict,
26  principleLabel,
27  readRecords,
28  recordName,
29  resolvePath,
30  reviewMarkdown,
31  scopeHits,
32  statusLine,
33  systemPrompt,
34  untrackedChunk,
35  writeRecord,
36  type LogFs,
37} from './core'
38import { WORDS, langOf, type Lang } from './text'
39
40type Engine = EngineInterface
41// gitDir is this work tree's; commonDir is shared by every work tree of the repository
42type Repo = { top: string; gitDir: string; commonDir: string }
43type Snap = { rev: string; untracked: string[] }
44
45const PANE = 'motive-mem'
46const KEEP = 40
47const FRESH_LIMIT = 30
48const FRESH_MAX_CHARS = 200_000
49
50const reviews = atom({ plugin: 'motive-mem', key: 'reviews' } as const, [])
51const cursor = atom({ plugin: 'motive-mem', key: 'cursor' } as const, -1)
52const isPaused = atom({ plugin: 'motive-mem', key: 'isPaused' } as const, false)
53
54// ---- git
55
56async function git($: Engine, repo: string, args: string[], stdin?: string) {
57  return $.process.run(['git', '-c', 'core.quotepath=off', '-C', repo, ...args], { timeoutMs: 30_000, stdin })
58}
59
60async function gitRepo($: Engine): Promise<Repo | undefined> {
61  const cwd = await $.session.cwd()
62  const found = await $.process
63    .run(['git', '-C', cwd, 'rev-parse', '--show-toplevel', '--absolute-git-dir', '--git-common-dir'])
64    .catch(() => undefined)
65  if (found === undefined || found.exitCode !== 0) return undefined
66  const [top, gitDir, common] = found.stdout.trim().split(/\r?\n/)
67  // The common dir comes relative to cwd when it is the work tree's own .git
68  return top && gitDir && common ? { top, gitDir, commonDir: resolvePath(cwd, common) } : undefined
69}
70
71// When the mode is on: a git repository that has a principles file
72async function repoOf($: Engine): Promise<Repo | undefined> {
73  const repo = await gitRepo($)
74  if (repo === undefined) return undefined
75  return (await $.fs.exists(`${repo.top}/${PRINCIPLES_PATH}`)) ? repo : undefined
76}
77
78// Why it is idle — the answer when a command is run
79async function whyOff($: Engine): Promise<string> {
80  const c = words().command
81  return (await gitRepo($)) === undefined ? c.notRepo : c.noPrinciples(PRINCIPLES_PATH)
82}
83
84const firstLine = (text: string) => text.trim().split(/\r?\n/)[0] ?? ''
85
86// The snapshot, or why there is none. `git stash create` fails while another git command holds the index lock
87// (an editor's `git status`, another session's snapshot) and while the index has unmerged or intent-to-add
88// entries. A failure is never taken for a clean tree — that would review the wrong diff: it is retried a few
89// times, then reported.
90async function snapshot($: Engine, repo: Repo): Promise<Snap | string> {
91  let failure = ''
92  for (let attempt = 0; attempt < 4; attempt++) {
93    if (attempt > 0) await $.clock.sleep(150 * attempt)
94    const stash = await git($, repo.top, ['stash', 'create'])
95    if (stash.exitCode !== 0) {
96      failure = firstLine(stash.stderr) || `git stash create: ${stash.exitCode}`
97      continue
98    }
99    // Empty output: nothing changed since HEAD
100    let rev = stash.stdout.trim()
101    if (rev === '') {
102      const head = await git($, repo.top, ['rev-parse', '--verify', '-q', 'HEAD'])
103      if (head.exitCode !== 0) return words().command.noHead
104      rev = head.stdout.trim()
105    }
106    const listed = await git($, repo.top, ['ls-files', '--others', '--exclude-standard', '-z'])
107    if (listed.exitCode !== 0) {
108      failure = firstLine(listed.stderr)
109      continue
110    }
111    const untracked = listed.stdout.split('\0').filter(Boolean)
112    // Cut at 4 MiB: the last path may be half of one
113    if (listed.isStdoutTruncated) untracked.pop()
114    return { rev, untracked }
115  }
116  return failure
117}
118
119async function changes(
120  $: Engine,
121  repo: Repo,
122  from: string,
123  to: string,
124  fresh: string[],
125): Promise<{ files: FileChange[]; diff: string }> {
126  // a/ and b/ whatever diff.noprefix, diff.mnemonicPrefix or diff.srcPrefix say — parseDiff reads them
127  const out = await git($, repo.top, [
128    'diff',
129    '--no-color',
130    '--no-ext-diff',
131    '--src-prefix=a/',
132    '--dst-prefix=b/',
133    '-M',
134    '-U3',
135    from,
136    to,
137  ])
138  let diff = out.exitCode === 0 ? out.stdout : ''
139  const files = parseDiff(diff)
140  if (out.isStdoutTruncated) {
141    // Past 4 MiB the output is cut: the last file's diff is partial and the ones after it are missing. Every
142    // changed file is still listed — as code, unless its name says otherwise — so none drops out unseen.
143    const last = files.at(-1)
144    if (last?.kind === 'comment') last.kind = 'code'
145    const known = new Set(files.map(f => f.path))
146    const names = await git($, repo.top, ['diff', '--name-only', '-z', '-M', from, to])
147    for (const path of names.stdout.split('\0').filter(Boolean)) {
148      if (known.has(path)) continue
149      files.push({ path, status: 'modified', added: 0, removed: 0, kind: kindOf(path, [], false), lines: [] })
150    }
151  }
152  for (const path of fresh.slice(0, FRESH_LIMIT)) {
153    const text = BINARY.test(path)
154      ? undefined
155      : await $.fs.read(`${repo.top}/${path}`).catch(() => undefined)
156    if (text === undefined || text.length > FRESH_MAX_CHARS || text.includes('\u0000')) {
157      files.push({ path, status: 'untracked', added: 0, removed: 0, kind: 'binary', lines: [] })
158      continue
159    }
160    const chunk = untrackedChunk(path, text)
161    diff += chunk
162    files.push(...parseDiff(chunk).map(file => ({ ...file, status: 'untracked' as const })))
163  }
164  return { files, diff }
165}
166
167// ---- logs (in .git — outside the work tree, so they never show up in the next turn's diff)
168
169// Every session in the repository reads and writes these. A write adds a record file of its own (writeRecord in
170// core.ts): nothing is read and written back, so sessions never overwrite each other and none waits on a lock.
171// Reviews belong to a work tree; approved exceptions hold in every work tree of the repository.
172type Log = { dir: string; legacy: string[] }
173
174const reviewLog = (repo: Repo): Log => ({
175  dir: `${repo.gitDir}/motive-mem/reviews`,
176  legacy: [`${repo.gitDir}/motive-mem/reviews.jsonl`],
177})
178const decisionLog = (repo: Repo): Log => ({
179  dir: `${repo.commonDir}/motive-mem/decisions`,
180  // Before 0.1.2 each work tree kept its own
181  legacy: [...new Set([`${repo.commonDir}/motive-mem/decisions.jsonl`, `${repo.gitDir}/motive-mem/decisions.jsonl`])],
182})
183const LOG_KEEP = 200
184
185// This session's mark in record names and review ids — another session's never matches it
186const owner = Math.random().toString(36).slice(2, 10) || 'x'
187let written = 0
188
189function logFs($: Engine): LogFs {
190  return {
191    list: async dir => (await $.fs.list(dir)).map(entry => ({ name: entry.name, size: entry.size })),
192    read: path => $.fs.read(path),
193    write: (path, text) => $.fs.write(path, text),
194  }
195}
196
197async function addRecord($: Engine, log: Log, value: unknown) {
198  await writeRecord(logFs($), log.dir, recordName(await $.clock.now(), owner, written++), value, LOG_KEEP)
199}
200
201async function readLog<T>($: Engine, log: Log, limit: number): Promise<T[]> {
202  return readRecords<T>(logFs($), log.dir, log.legacy, limit)
203}
204
205// A failed log write must not take the result with it: it is noted in the debug log
206async function logReview($: Engine, repo: Repo, review: Review) {
207  await addRecord($, reviewLog(repo), forLog(review, FRESH_LIMIT)).catch(err =>
208    $.ui.log(`motive-mem: could not write the review log: ${String(err)}`, { to: 'debug' }),
209  )
210}
211
212// ---- state
213
214async function put($: Engine, review: Review) {
215  await update($, reviews, list => [...list.filter(r => r.id !== review.id), review].slice(-KEEP))
216  await update($, cursor, () => -1)
217}
218
219async function replace($: Engine, review: Review) {
220  await update($, reviews, list => list.map(r => (r.id === review.id ? review : r)))
221}
222
223// ---- review (module variables start over on reload — the review list lives in $.state)
224
225type Config = {
226  model: string
227  effort: 'low' | 'medium' | 'high'
228  maxDiffChars: number
229  openOnIssue: boolean
230  lang: Lang
231}
232
233let config: Config = { model: 'sonnet', effort: 'medium', maxDiffChars: 60_000, openOnIssue: true, lang: 'en' }
234let pending: { repo: Repo; snap: Snap } | undefined
235let prompts: string[] = []
236let serial = 0
237
238function words() {
239  return WORDS[config.lang]
240}
241
242async function review(
243  $: Engine,
244  repo: Repo,
245  range: Review['range'],
246  intent: Intent,
247  origin: Review['origin'],
248) {
249  const { files, diff } = await changes($, repo, range.from, range.to, range.fresh)
250  if (files.length === 0) {
251    if (origin !== 'turn') $.ui.toast(words().command.nothing)
252    return
253  }
254  // Gone when this very turn deleted it: the deletion is still reviewed (and flagged as a principles change)
255  const principlesText = await $.fs.read(`${repo.top}/${PRINCIPLES_PATH}`).catch(() => '')
256  const hits = scopeHits(
257    parsePrinciples(principlesText),
258    files.filter(f => f.kind === 'code' || f.kind === 'test').map(f => f.path),
259  )
260  const level = levelOf(files)
261  const at = await $.clock.now()
262  const draft: Review = {
263    id: `${at}-${owner}-${serial++}`,
264    at,
265    origin,
266    status: level === 'trivial' ? 'skipped' : 'running',
267    level,
268    range,
269    files: files.map(({ lines: _lines, ...summary }) => summary),
270    principleDocs: files.filter(f => f.kind === 'principles').map(f => f.path),
271    hits,
272    intent,
273    model: config.model,
274    excepted: [],
275  }
276  await put($, draft)
277  $.ui.status(statusLine(draft, config.lang))
278  if (draft.principleDocs.length > 0) {
279    $.ui.toast(words().docsChangedToast(draft.principleDocs.join(', ')))
280  }
281  if (draft.status === 'skipped') {
282    await logReview($, repo, draft)
283    return
284  }
285
286  // From here on the draft is on screen as running: whatever happens, it ends as done or error — never stuck
287  let done: Review
288  try {
289    const decisions = await readLog<Decision>($, decisionLog(repo), 30)
290    const answer = await $.model.complete({
291      model: config.model,
292      effort: config.effort,
293      system: systemPrompt(config.lang),
294      prompt: buildPrompt({
295        principles: principlesText,
296        decisions,
297        intent,
298        files,
299        diff,
300        hits,
301        maxDiffChars: config.maxDiffChars,
302        lang: config.lang,
303      }),
304      maxTokens: 8000,
305      timeoutMs: 240_000,
306    })
307    if (!answer.isAnswered) {
308      const why =
309        answer.reason === 'api-error'
310          ? `api-error: ${answer.error}${answer.status === null ? '' : ` (${answer.status})`}`
311          : answer.reason
312      done = { ...draft, status: 'error', error: why }
313    } else {
314      const verdict = parseVerdict(answer.text)
315      done =
316        verdict === undefined
317          ? { ...draft, status: 'error', error: words().unreadable(cut(answer.text, 120)) }
318          : { ...draft, status: 'done', verdict }
319    }
320  } catch (err) {
321    done = { ...draft, status: 'error', error: String(err) }
322  }
323  await replace($, done)
324  $.ui.status(statusLine(done, config.lang))
325  if (hasIssues(done)) {
326    const first = openFindings(done)[0]?.finding
327    $.ui.toast(
328      first ? `${principleLabel(first.principle, config.lang)}: ${first.why}` : statusLine(done, config.lang),
329      { timeoutMs: 8000 },
330    )
331    if (config.openOnIssue) {
332      // Show this review: another one may have started — and finished — after it
333      const index = (await read($, reviews)).findIndex(r => r.id === done.id)
334      if (index >= 0) await update($, cursor, () => index)
335      void $.ui.open({ id: PANE, title: words().title })
336    }
337  }
338  await logReview($, repo, done)
339}
340
341function later($: Engine, work: () => Promise<void>) {
342  $.clock.after(0, () => {
343    work().catch(err => $.ui.log(`motive-mem: ${String(err)}`, { to: 'debug' }))
344  })
345}
346
347async function reviewAll($: Engine) {
348  const repo = await repoOf($)
349  if (repo === undefined) return whyOff($)
350  const head = await git($, repo.top, ['rev-parse', '--verify', '-q', 'HEAD'])
351  if (head.exitCode !== 0) return words().command.noHead
352  const now = await snapshot($, repo)
353  if (typeof now === 'string') return words().status.snapshotFailed(now)
354  const range = { from: head.stdout.trim(), to: now.rev, fresh: now.untracked }
355  later($, () => review($, repo, range, { prompts: [...prompts], answer: '', isAll: true }, 'all'))
356  return words().command.reviewingAll
357}
358
359export const register: Register = (on, options) => {
360  const maxDiffChars = Number(options.maxDiffChars)
361  config = {
362    model: typeof options.model === 'string' && options.model.trim() !== '' ? options.model.trim() : 'sonnet',
363    effort: options.effort === 'low' || options.effort === 'high' ? options.effort : 'medium',
364    maxDiffChars: Number.isFinite(maxDiffChars) && maxDiffChars >= 1000 ? maxDiffChars : 60_000,
365    openOnIssue: options.openOnIssue !== false,
366    lang: langOf(options.language),
367  }
368
369  on('session.start', async ($, e, next) => {
370    const started = await next(e)
371    const w = words()
372    await $.command.register({ name: 'motive-mem', description: w.command.description })
373    const repo = await repoOf($)
374    if (repo !== undefined && (await read($, reviews)).length === 0) {
375      const saved = latestById(await readLog<Review>($, reviewLog(repo), LOG_KEEP), KEEP)
376      if (saved.length > 0) await update($, reviews, () => saved)
377    }
378    // A review the previous environment was still running (it was reloaded) never finishes: let it be run again
379    if ((await read($, reviews)).some(r => r.status === 'running')) {
380      await update($, reviews, list =>
381        list.map(r => (r.status === 'running' ? { ...r, status: 'error' as const, error: w.interrupted } : r)),
382      )
383    }
384    if (repo !== undefined) {
385      const last = (await read($, reviews)).at(-1)
386      $.ui.status(
387        (await read($, isPaused))
388          ? `${w.title} · ${w.status.paused}`
389          : last
390            ? statusLine(last, config.lang)
391            : `${w.title} · ${w.status.on}`,
392      )
393    }
394    return started
395  })
396
397  on('turn.start', async ($, e, next) => {
398    // A subagent's or teammate's run belongs to the main turn, whose review covers what it changed
399    if (e.agentId !== undefined || (await read($, isPaused))) return next(e)
400    const repo = await repoOf($)
401    if (repo === undefined) {
402      pending = undefined
403      return next(e)
404    }
405    if (e.text.trim() !== '') prompts = [...prompts, e.text.trim()].slice(-3)
406    // Keep the start of a stopped (aborted) turn — the next turn's review covers both
407    if (pending === undefined || pending.repo.top !== repo.top) {
408      const snap = await snapshot($, repo).catch(err => String(err))
409      if (typeof snap === 'string') {
410        pending = undefined
411        $.ui.status(cut(`${words().title} · ${words().status.snapshotFailed(snap)}`, 160))
412      } else {
413        pending = { repo, snap }
414      }
415    }
416    return next(e)
417  })
418
419  on('turn.complete', async ($, e, next) => {
420    const done = await next(e)
421    if (e.agentId !== undefined || e.isAborted || pending === undefined) return done
422    const { repo, snap } = pending
423    pending = undefined
424    const intent: Intent = { prompts: [...prompts], answer: e.answer }
425    later($, async () => {
426      const end = await snapshot($, repo)
427      if (typeof end === 'string') {
428        $.ui.status(cut(`${words().title} · ${words().status.snapshotFailed(end)}`, 160))
429        return
430      }
431      const before = new Set(snap.untracked)
432      const fresh = end.untracked.filter(path => !before.has(path))
433      if (end.rev === snap.rev && fresh.length === 0) return
434      await review($, repo, { from: snap.rev, to: end.rev, fresh }, intent, 'turn')
435    })
436    return done
437  })
438
439  on('command.run', { command: 'motive-mem' }, async ($, e) => {
440    const w = words()
441    const arg = e.args.trim().toLowerCase()
442    if (arg === 'pause') {
443      await update($, isPaused, () => true)
444      pending = undefined
445      $.ui.status(`${w.title} · ${w.status.paused}`)
446      return { text: w.command.paused }
447    }
448    if (arg === 'resume') {
449      await update($, isPaused, () => false)
450      $.ui.status(`${w.title} · ${w.status.on}`)
451      return { text: w.command.resumed }
452    }
453    if (arg === 'all') return { text: await reviewAll($) }
454    if ((await repoOf($)) === undefined) return { text: await whyOff($) }
455    await $.ui.open({ id: PANE, title: w.title })
456    return { text: w.command.opened }
457  })
458
459  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
460    const { Box, Button, Markdown, Text } = $.ui.resolve(e)
461    const w = words()
462    const p = w.panel
463    const list = await read($, reviews)
464    const paused = await read($, isPaused)
465    if (list.length === 0) {
466      return (
467        <Box flexDirection="column">
468          <Text dimColor>{p.empty}</Text>
469          {paused && <Text color="warning">{p.pausedBanner}</Text>}
470          <Button key="all" label={p.reviewAll} hotkey="a" onPress={() => void reviewAll($)} />
471        </Box>
472      )
473    }
474    const at = await read($, cursor)
475    const index = at < 0 || at >= list.length ? list.length - 1 : at
476    const shown = list[index]
477    if (shown === undefined) return <Text dimColor>{p.notFound}</Text>
478    const open = openFindings(shown)
479    // Handlers read the state as it is when pressed, not as it was drawn: two presses before a redraw both count
480    const move = async (step: number) => {
481      const count = (await read($, reviews)).length
482      await update($, cursor, at => {
483        const from = at < 0 || at >= count ? count - 1 : at
484        return Math.min(count - 1, Math.max(0, from + step))
485      })
486    }
487
488    return (
489      <Box flexDirection="column" gap={1}>
490        {paused && <Text color="warning">{p.pausedBanner}</Text>}
491        <Markdown text={reviewMarkdown(shown, index, list.length, config.lang)} />
492        <Box flexDirection="row" flexWrap="wrap" columnGap={1}>
493          <Button key="prev" label={p.prev} hotkey="p" dimColor={index === 0} onPress={() => move(-1)} />
494          <Button
495            key="next"
496            label={p.next}
497            hotkey="n"
498            dimColor={index === list.length - 1}
499            onPress={() => move(1)}
500          />
501          {hasIssues(shown) && (
502            <Button
503              key="send"
504              label={p.send}
505              hotkey="c"
506              variant="primary"
507              onPress={() => void $.prompt.fill({ text: fixPrompt(shown, config.lang), mode: 'append' })}
508            />
509          )}
510          {shown.status !== 'running' && shown.level !== 'trivial' && (
511            <Button
512              key="retry"
513              label={p.retry}
514              hotkey="r"
515              onPress={() => {
516                later($, async () => {
517                  const repo = await repoOf($)
518                  if (repo) await review($, repo, shown.range, shown.intent, 'retry')
519                })
520              }}
521            />
522          )}
523          <Button key="all" label={p.uncommitted} hotkey="a" onPress={async () => $.ui.toast(await reviewAll($))} />
524        </Box>
525        {open.length > 0 && (
526          <Box flexDirection="column">
527            <Text dimColor>{p.exceptHint}</Text>
528            {open.slice(0, 9).map(({ finding, index: i }) => (
529              <Button
530                key={`except:${shown.id}:${i}`}
531                label={p.except(i + 1, principleLabel(finding.principle, config.lang), finding.file.split('/').pop() ?? '')}
532                // One digit only — the engine refuses the whole pane over a "10"
533                hotkey={i < 9 ? String(i + 1) : undefined}
534                dimColor
535                onPress={async () => {
536                  const repo = await repoOf($)
537                  if (repo === undefined) return
538                  let updated = undefined as Review | undefined
539                  await update($, reviews, list =>
540                    list.map(r => {
541                      if (r.id !== shown.id || r.excepted.includes(i)) return r
542                      updated = { ...r, excepted: [...r.excepted, i] }
543                      return updated
544                    }),
545                  )
546                  // Already approved by an earlier press
547                  if (updated === undefined) return
548                  const approved = updated
549                  $.ui.status(statusLine(approved, config.lang))
550                  const decision: Decision = {
551                    at: await $.clock.now(),
552                    principle: finding.principle,
553                    file: finding.file,
554                    why: finding.why,
555                  }
556                  // The decision, then the review again with the approval so a later session restores it approved.
557                  // Either one not saved is said.
558                  await addRecord($, decisionLog(repo), decision)
559                    .then(() => addRecord($, reviewLog(repo), forLog(approved, FRESH_LIMIT)))
560                    .catch(err => $.ui.toast(words().notSaved(String(err)), { timeoutMs: 8000 }))
561                }}
562              />
563            ))}
564          </Box>
565        )}
566      </Box>
567    )
568  })
569}
570
hooks/core.ts 681 lines
1// The pure part of intent review: reading the principles doc, splitting the diff, building the review
2// request, reading the answer, the panel text, and the locking of the shared logs (given a lock and a clock).
3// No `$` here, so `claude plugin test` checks it as is.
4
5import type {
6  Decision,
7  FileChange,
8  FileKind,
9  Finding,
10  Intent,
11  Level,
12  Principle,
13  Review,
14  Verdict,
15} from '../types'
16import { WORDS, type Lang } from './text'
17
18export const PRINCIPLES_PATH = '.claude/principles.md'
19
20const HASH_COMMENT = /\.(py|ps1|psm1|sh|toml|ya?ml|cfg|ini|spec)$/i
21const SLASH_COMMENT = /\.(m?[jt]sx?|c[jt]s|css|scss|c|h|cpp|hpp|cs|java|go|rs|swift|kt)$/i
22const CSS = /\.(css|scss)$/i
23const DOCS = /\.(md|txt|rst)$/i
24// Text files the build reads — a change to them is not a docs change
25const BUILD_TEXT = /(^|\/)(requirements[^/]*|constraints[^/]*|CMakeLists)\.txt$/i
26// Comments the toolchain reads: silencing a check or switching a build flag is not a comment-only change
27const DIRECTIVE =
28  /^(#!|\/\/\/|\/\/\s*(go:|\+build))|@ts-|eslint|prettier-ignore|istanbul ignore|c8 ignore|noqa|type:|pylint|mypy|pyright|nolint|clang-format|pragma|-\*-|#requires/i
29export const BINARY =
30  /\.(png|jpe?g|gif|webp|bmp|ico|pdf|ttf|otf|woff2?|pbf|mvt|zip|7z|gz|exe|dll|pyd|so|sqlite|db|bin|npy|npz)$/i
31const TEST = /(^|\/)(tests?\/|test_[^/]*$|[^/]*_test\.[^/]+$|[^/]*\.test\.[^/]+$)/i
32
33export function isPrincipleDoc(path: string): boolean {
34  return path === PRINCIPLES_PATH || path === 'CLAUDE.md' || path.endsWith('/CLAUDE.md') || path === 'AGENTS.md'
35}
36
37// ---- principles doc
38
39// The scope field, in either language the skill writes: `- Scope:` or `- 범위:`
40const SCOPE = /^\s*[-*]\s*(?:scope|범위)\s*:\s*(.+)$/i
41
42// The lines of a markdown file, each with whether it sits inside a ``` or ~~~ fence (a `#` there is not a heading)
43function markdownLines(text: string): { line: string; isFenced: boolean }[] {
44  let fence = ''
45  return text
46    .replace(/^/, '')
47    .split(/\r?\n/)
48    .map(line => {
49      const mark = /^\s*(`{3,}|~{3,})/.exec(line)?.[1]
50      if (mark !== undefined && (fence === '' || mark.startsWith(fence))) {
51        fence = fence === '' ? mark : ''
52        return { line, isFenced: true }
53      }
54      return { line, isFenced: fence !== '' }
55    })
56}
57
58export function parsePrinciples(text: string): Principle[] {
59  const out: Principle[] = []
60  let current: Principle | undefined
61  for (const { line, isFenced } of markdownLines(text)) {
62    if (isFenced) continue
63    const head = /^##\s+([A-Z]\d{1,3})\s+(.+?)\s*$/.exec(line)
64    if (head) {
65      current = { id: head[1] ?? '', title: head[2] ?? '', scope: [] }
66      out.push(current)
67      continue
68    }
69    if (/^#{1,2}\s/.test(line)) {
70      current = undefined
71      continue
72    }
73    const scope = SCOPE.exec(line)
74    if (scope && current) {
75      current.scope.push(
76        ...(scope[1] ?? '')
77          .split(',')
78          .map(part => part.replace(/`/g, '').trim())
79          .filter(Boolean),
80      )
81    }
82  }
83  return out
84}
85
86// Sections for people to settle among themselves — kept from the reviewer so an unanswered question
87// never becomes a criterion
88// — at any heading level, until the next heading of the same level or higher
89const NOT_FOR_REVIEWER = /^(#{1,6})\s+[*_]*\s*(open questions|needs confirmation|열린\s*질문|확인\s*필요)/i
90
91export function forReviewer(text: string): string {
92  const out: string[] = []
93  let cutLevel = 0
94  for (const { line, isFenced } of markdownLines(text)) {
95    const level = isFenced ? 0 : (/^(#{1,6})\s/.exec(line)?.[1]?.length ?? 0)
96    if (level > 0) {
97      if (cutLevel > 0 && level <= cutLevel) cutLevel = 0
98      if (cutLevel === 0 && NOT_FOR_REVIEWER.test(line)) cutLevel = level
99    }
100    if (cutLevel === 0) out.push(line)
101  }
102  return out.join('\n')
103}
104
105export function globToRegExp(glob: string): RegExp {
106  let source = ''
107  for (let i = 0; i < glob.length; i++) {
108    const c = glob.charAt(i)
109    if (c === '*' && glob[i + 1] === '*') {
110      // `**/` is zero or more whole folders; a trailing `**` is anything below
111      if (glob[i + 2] === '/') {
112        source += '(?:.*/)?'
113        i += 2
114      } else {
115        source += '.*'
116        i += 1
117      }
118    } else if (c === '*') {
119      source += '[^/]*'
120    } else if (c === '?') {
121      source += '[^/]'
122    } else {
123      source += c.replace(/[.+^${}()|[\]\\]/g, '\\$&')
124    }
125  }
126  return new RegExp(`^${source}$`)
127}
128
129export function scopeHits(principles: Principle[], paths: string[]): Record<string, string[]> {
130  const hits: Record<string, string[]> = {}
131  for (const principle of principles) {
132    const patterns = principle.scope.map(globToRegExp)
133    const matched = paths.filter(path => patterns.some(re => re.test(path)))
134    if (matched.length > 0) hits[principle.id] = matched
135  }
136  return hits
137}
138
139// ---- diff
140
141function headerPath(raw: string, prefix: string): string {
142  let path = raw.replace(/\t$/, '')
143  if (path === '/dev/null') return ''
144  if (path.startsWith('"') && path.endsWith('"')) path = path.slice(1, -1)
145  return path.startsWith(prefix) ? path.slice(prefix.length) : path
146}
147
148// A changed line that is only a comment. Leaning towards "no": a comment wrongly taken for code costs one review,
149// code wrongly taken for a comment skips the review.
150function isCommentLine(path: string, line: string): boolean {
151  if (DIRECTIVE.test(line)) return false
152  if (HASH_COMMENT.test(path)) return line.startsWith('#')
153  if (!SLASH_COMMENT.test(path)) return false
154  if (line.startsWith('//')) return true
155  // `/* … */ code` is code
156  if (line.startsWith('/*')) return !/\*\/\s*\S/.test(line)
157  // A block's middle or end line: `* text`, `*`, `*/` — not `*ptr = 1` or a CSS `* {`
158  return /^\*(\s|\/|$)/.test(line) && !(CSS.test(path) && /[{};]/.test(line))
159}
160
161export function kindOf(
162  path: string,
163  changed: string[],
164  isBinary: boolean,
165  more: { from?: string; wrapsCode?: boolean } = {},
166): FileKind {
167  if (isPrincipleDoc(path) || (more.from !== undefined && isPrincipleDoc(more.from))) return 'principles'
168  if (isBinary || BINARY.test(path)) return 'binary'
169  if (DOCS.test(path) && !BUILD_TEXT.test(path)) return 'docs'
170  if (TEST.test(path)) return 'test'
171  const body = changed.map(line => line.slice(1).trim()).filter(line => line !== '')
172  // No changed lines (a rename, a mode change) or a block comment opened around unchanged lines: code
173  if (body.length === 0 || (more.wrapsCode && SLASH_COMMENT.test(path))) return 'code'
174  return body.every(line => isCommentLine(path, line)) ? 'comment' : 'code'
175}
176
177export function parseDiff(diff: string): FileChange[] {
178  const out: FileChange[] = []
179  for (const chunk of diff.split(/^diff --git /m).slice(1)) {
180    const lines = chunk.split('\n')
181    const pair = /^a\/(.*) b\/(.*)$/.exec(lines[0] ?? '')
182    let from = pair?.[1] ?? ''
183    let to = pair?.[2] ?? ''
184    let status: FileChange['status'] = 'modified'
185    let isBinary = false
186    let isInHunk = false
187    let added = 0
188    let removed = 0
189    const changed: string[] = []
190    // A block comment a changed line opens (`/*` with no `*/` after it) that is still open at an unchanged line
191    // comments that code out — or, on the `-` side, back in
192    const open = { '+': false, '-': false }
193    let wrapsCode = false
194    for (const line of lines.slice(1)) {
195      if (!isInHunk) {
196        if (line.startsWith('--- ')) from = headerPath(line.slice(4), 'a/')
197        else if (line.startsWith('+++ ')) to = headerPath(line.slice(4), 'b/')
198        else if (line.startsWith('new file mode')) status = 'added'
199        else if (line.startsWith('deleted file mode')) status = 'deleted'
200        else if (line.startsWith('rename from ')) {
201          status = 'renamed'
202          from = line.slice('rename from '.length)
203        } else if (line.startsWith('rename to ')) to = line.slice('rename to '.length)
204        else if (line.startsWith('Binary files ')) isBinary = true
205        else if (line.startsWith('@@')) isInHunk = true
206        continue
207      }
208      if (line.startsWith('@@')) {
209        if (open['+'] || open['-']) wrapsCode = true
210        open['+'] = open['-'] = false
211        continue
212      }
213      const sign = line.charAt(0)
214      if (sign === '+' || sign === '-') {
215        if (sign === '+') added++
216        else removed++
217        changed.push(line)
218        const opens = line.lastIndexOf('/*')
219        const closes = line.lastIndexOf('*/')
220        if (opens > closes) open[sign] = true
221        else if (closes > opens) open[sign] = false
222      } else if (sign === ' ' && (open['+'] || open['-'])) {
223        wrapsCode = true
224      }
225    }
226    if (open['+'] || open['-']) wrapsCode = true
227    const path = status === 'deleted' ? from : to || from
228    if (path === '') continue
229    out.push({ path, status, added, removed, kind: kindOf(path, changed, isBinary, { from, wrapsCode }), lines: changed })
230  }
231  return out
232}
233
234export function untrackedChunk(path: string, text: string): string {
235  const body = text.replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n')
236  return [
237    `diff --git a/${path} b/${path}`,
238    'new file mode 100644',
239    '--- /dev/null',
240    `+++ b/${path}`,
241    `@@ -0,0 +1,${body.length} @@`,
242    ...body.map(line => `+${line}`),
243    '',
244  ].join('\n')
245}
246
247export function levelOf(files: { kind: FileKind }[]): Level {
248  if (files.some(file => file.kind === 'code')) return 'logic'
249  if (files.some(file => file.kind === 'test')) return 'tests'
250  return 'trivial'
251}
252
253// ---- review request (in English whatever the language; only the answer's sentences follow `lang`)
254
255const ANSWER_LANGUAGE: Record<Lang, string> = { en: 'English', ko: 'Korean' }
256
257// The `principle` a band-aid gets when no principle covers it. Older logs hold the Korean '땜질'.
258export const WORKAROUND = 'workaround'
259
260export function systemPrompt(lang: Lang): string {
261  return `You are this repository's "intent reviewer". This is not a line-by-line code review. You do not decide in the human's place — you narrow down where the human should look.
262
263Judge only three things.
2641. Intent match — does the diff match <request> and <author_report>? Of the changes the report does not mention, put in "unstated" only those outside the request's scope or that change other behavior — not details inside the requested change (choice of values, aliases, wording, names). Any entry in "unstated" opens a panel in front of the human — if you would add "not a big deal, but", leave it out. Check whether the report claims more than happened (passing checks presented as user confirmation, partial presented as done).
2652. Principle violations — only the principles written in <principles> count. Do not invent criteria the principles document does not state. Anything covered by the allowed exceptions in <principles> or by <approved_exceptions> is not a violation. A principle's scope is a hint of where it usually bites, not a boundary: a change outside it that does what the principle forbids still breaks it.
2663. Band-aid fixes — signs of routing around the structure to make a local problem go away: a write or sync that skips the single entry point, a second copy of a rule, formula or table that already lives in one place, a branch that fixes only one specific case, swallowing an exception to hide a symptom, changing test expectations or snapshots to make them pass, skipping checks (skip, xfail), lengthening waits, a flag for one particular task.
267
268What you do not do:
269- Style, naming or performance taste; proposals for a better design; suggestions to add defensive code or validation.
270- Hypothetical concerns ("this might … later"). Say only what the diff gives grounds for.
271- When unsure, lower "violation" to "suspect". If you cannot point to the diff line it rests on, do not say it.
272- When nothing is wrong, leave findings and unstated empty. An empty result is normal.
273- "attention" picks, from findings and unstated, only the places a human must open themselves. If both are empty, leave attention empty too.
274
275Answer with a single JSON object only (no code fence):
276{
277  "summary": "one sentence on what this change actually did",
278  "intent": "match" | "partial" | "mismatch",
279  "intent_note": "one or two sentences on how it differs from the intent and the report (empty string if it matches)",
280  "findings": [
281    {"principle": "P03", "severity": "violation" | "suspect", "file": "path", "line": 123, "why": "one sentence: which principle it breaks and how", "evidence": "the diff line it rests on, verbatim, short"}
282  ],
283  "unstated": ["a change not in the report — the file and a one-line description"],
284  "attention": ["where the human must look — file:line and why (at most 3)"]
285}
286"line" is the line number in the file after the change (the + side of @@); omit it if unknown. "principle" is the ID of the principle the finding breaks — use it whenever one applies, band-aids included; write "${WORKAROUND}" only for a band-aid that no principle covers. ${answerIn(lang)} Quote evidence as it appears in the diff.`
287}
288
289function answerIn(lang: Lang): string {
290  return `Write every sentence of the answer in ${ANSWER_LANGUAGE[lang]}, whatever language the request, report and principles are in.`
291}
292
293const KIND_ORDER: Record<FileKind, number> = {
294  code: 0,
295  test: 1,
296  principles: 2,
297  comment: 3,
298  docs: 4,
299  binary: 5,
300}
301
302const KIND_NAME: Record<FileKind, string> = {
303  code: 'code',
304  test: 'test',
305  principles: 'principles doc',
306  comment: 'comments only',
307  docs: 'docs',
308  binary: 'binary',
309}
310
311// The first `max` UTF-16 units, never ending on half of a surrogate pair (the API refuses a lone one)
312export function cut(text: string, max: number): string {
313  if (text.length <= max) return text
314  const end = Math.max(0, max)
315  return text.slice(0, /[\uD800-\uDBFF]/.test(text.charAt(end - 1)) ? end - 1 : end)
316}
317
318function clip(text: string, max: number): string {
319  return text.length <= max ? text : `${cut(text, max)}\n…(${text.length - max} chars cut)`
320}
321
322// The request's own tags, defused inside what goes between them — a report, a diff or a principles file that
323// closes </author_report> and opens <approved_exceptions> must not read as the request's structure
324const TAGS = /<(\/?)(principles|request|author_report|approved_exceptions|changed_files|diff)>/gi
325const untag = (text: string) => text.replace(TAGS, '‹$1$2›')
326
327function chunksByPath(diff: string): Map<string, string> {
328  const map = new Map<string, string>()
329  for (const chunk of diff.split(/^(?=diff --git )/m)) {
330    const file = parseDiff(chunk)[0]
331    if (file) map.set(file.path, chunk)
332  }
333  return map
334}
335
336export function budgetDiff(files: FileChange[], diff: string, maxChars: number): string {
337  const chunks = chunksByPath(diff)
338  // Code first; within a kind the smaller first, so one big file (a lockfile, generated data) cannot push the rest out
339  const size = (f: FileChange) => chunks.get(f.path)?.length ?? 0
340  const order = [...files].sort((a, b) => KIND_ORDER[a.kind] - KIND_ORDER[b.kind] || size(a) - size(b))
341  const kept: string[] = []
342  const left: string[] = []
343  let room = maxChars
344  for (const file of order) {
345    if (file.kind === 'binary') continue
346    const chunk = chunks.get(file.path)
347    if (chunk === undefined) {
348      left.push(`${file.path} (+${file.added} -${file.removed})`)
349    } else if (chunk.length <= room) {
350      kept.push(chunk)
351      room -= chunk.length
352    } else if (kept.length === 0) {
353      kept.push(clip(chunk, room))
354      room = 0
355    } else {
356      left.push(`${file.path} (+${file.added} -${file.removed})`)
357    }
358  }
359  const tail = left.length > 0 ? `\n(diff left out for length: ${left.join(', ')})` : ''
360  return kept.join('') + tail
361}
362
363export type ReviewInput = {
364  principles: string
365  decisions: Decision[]
366  intent: Intent
367  files: FileChange[]
368  diff: string
369  hits: Record<string, string[]>
370  maxDiffChars: number
371  lang: Lang
372}
373
374export function buildPrompt(input: ReviewInput): { text: string; cache?: true }[] {
375  const prompts = input.intent.prompts.length
376    ? input.intent.prompts.map((p, i) => `${i + 1}. ${clip(p, 2000)}`).join('\n')
377    : '(none)'
378  const decisions = input.decisions.length
379    ? untag(input.decisions.map(d => `- ${d.principle} ${d.file}: ${d.why}`).join('\n'))
380    : '(none)'
381  const byFile = new Map<string, string[]>()
382  for (const [id, paths] of Object.entries(input.hits)) {
383    for (const path of paths) byFile.set(path, [...(byFile.get(path) ?? []), id])
384  }
385  const files = input.files
386    .map(f => {
387      const ids = byFile.get(f.path)
388      const scope = ids ? ` [in scope of: ${ids.join(', ')}]` : ''
389      return `- ${f.path} (${KIND_NAME[f.kind]}, ${f.status}, +${f.added} -${f.removed})${scope}`
390    })
391    .join('\n')
392  const rest = [
393    `<request> (oldest first; the last one is this task)\n${untag(prompts)}\n</request>`,
394    `<author_report> (what Claude told the human when it finished)\n${untag(clip(input.intent.answer, 6000)) || (input.intent.isAll ? '(none — reviewing all uncommitted changes)' : '(none)')}\n</author_report>`,
395    `<approved_exceptions> (the human already approved these as exceptions — do not raise the same thing again)\n${decisions}\n</approved_exceptions>`,
396    `<changed_files>\n${untag(files)}\n</changed_files>`,
397    `<diff>\n${untag(budgetDiff(input.files, input.diff, input.maxDiffChars))}\n</diff>`,
398    answerIn(input.lang),
399  ].join('\n\n')
400  return [
401    { text: `<principles>\n${untag(forReviewer(input.principles))}\n</principles>`, cache: true },
402    { text: rest },
403  ]
404}
405
406// ---- reading the answer
407
408export function parseVerdict(text: string): Verdict | undefined {
409  const start = text.indexOf('{')
410  const end = text.lastIndexOf('}')
411  if (start < 0 || end <= start) return undefined
412  let raw: unknown
413  try {
414    raw = JSON.parse(text.slice(start, end + 1))
415  } catch {
416    return undefined
417  }
418  if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return undefined
419  const o = raw as Record<string, unknown>
420  // An answer that does not say match / partial / mismatch, or whose lists are not lists, is unreadable —
421  // never a clean pass
422  const intent = typeof o.intent === 'string' ? o.intent.trim().toLowerCase() : ''
423  if (intent !== 'match' && intent !== 'partial' && intent !== 'mismatch') return undefined
424  if (o.findings !== undefined && !Array.isArray(o.findings)) return undefined
425  // One line each: the panel shows these inside markdown
426  const str = (v: unknown) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim() : '')
427  const strs = (v: unknown) => (typeof v === 'string' ? [v] : Array.isArray(v) ? v : []).map(str).filter(Boolean)
428  const findings: Finding[] = (Array.isArray(o.findings) ? o.findings : []).flatMap(item => {
429    if (typeof item !== 'object' || item === null) return []
430    const f = item as Record<string, unknown>
431    const why = str(f.why) || str(f.reason) || str(f.description)
432    if (why === '') return []
433    const finding: Finding = {
434      principle: str(f.principle) || WORKAROUND,
435      severity: str(f.severity).toLowerCase() === 'violation' ? 'violation' : 'suspect',
436      file: str(f.file),
437      why,
438      evidence: str(f.evidence),
439    }
440    if (typeof f.line === 'number' && Number.isFinite(f.line)) finding.line = Math.round(f.line)
441    return [finding]
442  })
443  return {
444    summary: str(o.summary),
445    intent,
446    intentNote: str(o.intent_note),
447    findings,
448    unstated: strs(o.unstated),
449    attention: strs(o.attention).slice(0, 3),
450  }
451}
452
453// ---- panel, status line, and the text handed back to Claude
454
455export function openFindings(review: Review): { finding: Finding; index: number }[] {
456  return (review.verdict?.findings ?? [])
457    .map((finding, index) => ({ finding, index }))
458    .filter(({ index }) => !review.excepted.includes(index))
459}
460
461export function hasIssues(review: Review): boolean {
462  const v = review.verdict
463  return v !== undefined && (openFindings(review).length > 0 || v.unstated.length > 0 || v.intent !== 'match')
464}
465
466export function principleLabel(id: string, lang: Lang): string {
467  return id === WORKAROUND || id === '땜질' ? WORDS[lang].workaround : id
468}
469
470function tag(finding: Finding, lang: Lang): string {
471  return `[${principleLabel(finding.principle, lang)} ${WORDS[lang].severity[finding.severity]}]`
472}
473
474export function statusLine(review: Review, lang: Lang): string {
475  const w = WORDS[lang]
476  const s = w.status
477  if (review.status === 'running') return `${w.title} · ${s.running}`
478  if (review.status === 'error') return cut(`${w.title} · ${s.failed(review.error ?? '')}`.replace(/\s+/g, ' '), 120)
479  if (review.status === 'skipped') {
480    return review.principleDocs.length > 0
481      ? `${w.title} · ${s.docsChanged(review.principleDocs.join(', '))}`
482      : `${w.title} · ${s.trivial}`
483  }
484  const v = review.verdict
485  if (v === undefined) return w.title
486  const open = openFindings(review)
487  const violations = open.filter(x => x.finding.severity === 'violation').length
488  const suspects = open.length - violations
489  if (!hasIssues(review)) return `${w.title} ✓ ${w.intent[v.intent]} · ${s.noFindings}`
490  const parts: string[] = [w.intent[v.intent]]
491  if (violations > 0) parts.push(s.violations(violations))
492  if (suspects > 0) parts.push(s.suspects(suspects))
493  if (v.unstated.length > 0) parts.push(s.unstated(v.unstated.length))
494  return `${w.title} ⚠ ${parts.join(' · ')} — /motive-mem`
495}
496
497function clock(at: number): string {
498  const d = new Date(at)
499  const two = (n: number) => String(n).padStart(2, '0')
500  return `${two(d.getHours())}:${two(d.getMinutes())}`
501}
502
503function where(f: Finding): string {
504  return f.line === undefined ? f.file : `${f.file}:${f.line}`
505}
506
507// Inline code that holds backticks of its own
508function code(text: string): string {
509  const fence = '`'.repeat(Math.max(0, ...(text.match(/`+/g) ?? []).map(run => run.length)) + 1)
510  return fence.length > 1 ? `${fence} ${text} ${fence}` : `\`${text}\``
511}
512
513export function reviewMarkdown(review: Review, index: number, count: number, lang: Lang): string {
514  const w = WORDS[lang]
515  const p = w.panel
516  const out: string[] = []
517  out.push(
518    `**${p.header(w.origin[review.origin], index + 1, count)}** · ${clock(review.at)} · ${w.level[review.level]} · ${review.model}`,
519  )
520  out.push('')
521  if (review.principleDocs.length > 0) {
522    out.push(`> ${p.docsChanged(review.principleDocs.join(', '))}`)
523    out.push('')
524  }
525  if (review.status === 'running') out.push(`_${p.running}_`)
526  if (review.status === 'error') out.push(p.failed(review.error ?? p.unknown))
527  if (review.status === 'skipped') out.push(p.skipped)
528  const v = review.verdict
529  if (v !== undefined) {
530    out.push(`**${p.did}** ${v.summary || p.noSummary}`)
531    out.push('')
532    out.push(`**${w.intent[v.intent]}**${v.intentNote ? ` — ${v.intentNote}` : ''}`)
533    const open = openFindings(review)
534    if (open.length > 0) {
535      out.push('')
536      out.push(`**${p.findings}**`)
537      for (const { finding, index: i } of open) {
538        out.push(`${i + 1}. ${tag(finding, lang)} ${code(where(finding))} — ${finding.why}`)
539        if (finding.evidence) out.push(`   ${code(cut(finding.evidence, 160))}`)
540      }
541    }
542    if (review.excepted.length > 0) out.push(`\n_${p.excepted(review.excepted.map(i => i + 1))}_`)
543    if (v.unstated.length > 0) {
544      out.push('')
545      out.push(`**${p.unstated}**`)
546      for (const line of v.unstated) out.push(`- ${line}`)
547    }
548    if (v.attention.length > 0) {
549      out.push('')
550      out.push(`**${p.attention}**`)
551      for (const line of v.attention) out.push(`- ${line}`)
552    }
553    if (!hasIssues(review)) {
554      out.push('')
555      out.push(p.noFindings)
556    }
557  }
558  const shown = review.files.filter(f => f.kind !== 'binary').slice(0, 12)
559  if (shown.length > 0) {
560    out.push('')
561    out.push(
562      `**${p.files}** ${shown.map(f => `${f.path.split('/').pop()}(${w.kind[f.kind]})`).join(', ')}${review.files.length > shown.length ? p.more(review.files.length - shown.length) : ''}`,
563    )
564  }
565  const hit = Object.keys(review.hits)
566  if (hit.length > 0) out.push(`**${p.inScope}** ${hit.join(', ')}`)
567  return out.join('\n')
568}
569
570export function fixPrompt(review: Review, lang: Lang): string {
571  const v = review.verdict
572  if (v === undefined) return ''
573  const w = WORDS[lang]
574  const lines = [...w.fix.intro, '']
575  for (const { finding, index } of openFindings(review)) {
576    lines.push(`${index + 1}. ${tag(finding, lang)} ${where(finding)} — ${finding.why}`)
577  }
578  if (v.intent !== 'match') lines.push(`- ${w.fix.intent}: ${v.intentNote || w.intent[v.intent]}`)
579  for (const line of v.unstated) lines.push(`- ${w.fix.unstated}: ${line}`)
580  return lines.join('\n')
581}
582
583// ---- logs that several sessions write (.git/motive-mem)
584
585// Each write to a log is a file of its own — a record — and no record is ever written twice with content, so a
586// session cannot overwrite what another wrote, however their steps interleave or pause. There is no lock to wait
587// for, break or give up on. register.tsx passes $.fs in; the tests pass one that pauses.
588export type LogFs = {
589  list: (dir: string) => Promise<{ name: string; size: number }[]>
590  read: (path: string) => Promise<string>
591  write: (path: string, text: string) => Promise<void>
592}
593
594// <time>-<session>-<n>.json: names sort in time order and no two sessions make the same one
595const RECORD = /^\d{15}-[0-9a-z]+-\d+\.json$/
596
597export function recordName(at: number, owner: string, n: number): string {
598  return `${String(Math.max(0, Math.floor(at))).padStart(15, '0')}-${owner}-${n}.json`
599}
600
601// The records a log holds, oldest first. An empty one has been trimmed (or is still being written).
602function liveRecords(entries: { name: string; size: number }[]): string[] {
603  return entries
604    .filter(e => RECORD.test(e.name) && e.size > 0)
605    .map(e => e.name)
606    .sort()
607}
608
609// Writes one record; a failure rejects, so the caller can say it was not saved. Then trims the log to its last
610// `keep` records by emptying the older ones — $.fs cannot delete, and emptying writes the same thing whoever does
611// it, so two sessions trimming at once agree. A failed trim leaves the record saved.
612export async function writeRecord(fs: LogFs, dir: string, name: string, value: unknown, keep: number) {
613  await fs.write(`${dir}/${name}`, JSON.stringify(value))
614  try {
615    const live = liveRecords(await fs.list(dir))
616    for (const old of live.slice(0, Math.max(0, live.length - keep))) await fs.write(`${dir}/${old}`, '')
617  } catch {
618    // the next write trims
619  }
620}
621
622// The last `limit` values of a log, oldest first. The JSON-lines files the logs used to be (`legacy`) are read
623// only while the records fall short of `limit`. A record cut short or not yet written is skipped.
624export async function readRecords<T>(fs: LogFs, dir: string, legacy: string[], limit: number): Promise<T[]> {
625  const parse = (text: string): T[] => {
626    try {
627      return [JSON.parse(text) as T]
628    } catch {
629      return []
630    }
631  }
632  const names = liveRecords(await fs.list(dir).catch(() => [])).slice(-limit)
633  const records = (await Promise.all(names.map(name => fs.read(`${dir}/${name}`).catch(() => '')))).flatMap(parse)
634  if (records.length >= limit) return records
635  const old: T[] = []
636  for (const path of legacy) {
637    const text = await fs.read(path).catch(() => '')
638    old.push(...text.split('\n').filter(Boolean).flatMap(parse))
639  }
640  return [...old, ...records].slice(-limit)
641}
642
643// A path git printed relative to `base` (`../.git`), made absolute and without `.` or `..`; an absolute one as given
644export function resolvePath(base: string, path: string): string {
645  if (/^([a-z]:)?[\\/]/i.test(path)) return path
646  const parts = `${base}/${path}`.replace(/\\/g, '/').split('/')
647  const out: string[] = []
648  for (const part of parts) {
649    if (part === '..' && out.length > 1) out.pop()
650    else if (part !== '.' && (part !== '' || out.length === 0)) out.push(part)
651  }
652  return out.join('/')
653}
654
655// A review as the log keeps it: the request and the report clipped as the reviewer saw them, and only the new
656// files a retry would look at
657export function forLog(review: Review, freshLimit: number): Review {
658  return {
659    ...review,
660    range: { ...review.range, fresh: review.range.fresh.slice(0, freshLimit) },
661    intent: {
662      ...review.intent,
663      prompts: review.intent.prompts.map(p => cut(p, 2000)),
664      answer: cut(review.intent.answer, 6000),
665    },
666  }
667}
668
669// Reviews read back from the log, in time order. A review is logged when it ends and again with each approval: the
670// last record of an id wins, but approvals only ever add, so one session's record never drops another's.
671export function latestById(list: Review[], keep: number): Review[] {
672  const byId = new Map<string, Review>()
673  for (const review of list) {
674    const before = byId.get(review.id)
675    const excepted = before ? [...new Set([...before.excepted, ...review.excepted])] : review.excepted
676    byId.delete(review.id)
677    byId.set(review.id, { ...review, excepted })
678  }
679  return [...byId.values()].sort((a, b) => a.at - b.at).slice(-keep)
680}
681
hooks/text.ts 247 lines
1// What the plugin shows a person, in each language it speaks — chosen by the `language` option.
2// The reviewer's prompt is not here: it lives in core.ts, in English, and only its output language follows this.
3
4import type { FileKind, Level, Review, Verdict } from '../types'
5
6export type Lang = 'en' | 'ko'
7
8export function langOf(value: unknown): Lang {
9  return value === 'ko' ? 'ko' : 'en'
10}
11
12export type Words = {
13  title: string
14  intent: Record<Verdict['intent'], string>
15  level: Record<Level, string>
16  origin: Record<Review['origin'], string>
17  kind: Record<FileKind, string>
18  severity: Record<'violation' | 'suspect', string>
19  workaround: string
20  status: {
21    on: string
22    paused: string
23    running: string
24    failed: (error: string) => string
25    docsChanged: (docs: string) => string
26    trivial: string
27    noFindings: string
28    violations: (n: number) => string
29    suspects: (n: number) => string
30    unstated: (n: number) => string
31    snapshotFailed: (why: string) => string
32  }
33  panel: {
34    header: (origin: string, nth: number, count: number) => string
35    docsChanged: (docs: string) => string
36    running: string
37    failed: (error: string) => string
38    unknown: string
39    skipped: string
40    did: string
41    noSummary: string
42    findings: string
43    excepted: (numbers: number[]) => string
44    unstated: string
45    attention: string
46    noFindings: string
47    files: string
48    more: (n: number) => string
49    inScope: string
50    empty: string
51    pausedBanner: string
52    notFound: string
53    prev: string
54    next: string
55    send: string
56    retry: string
57    reviewAll: string
58    uncommitted: string
59    exceptHint: string
60    except: (nth: number, principle: string, file: string) => string
61  }
62  fix: { intro: string[]; intent: string; unstated: string }
63  command: {
64    description: string
65    notRepo: string
66    noPrinciples: (path: string) => string
67    nothing: string
68    noHead: string
69    reviewingAll: string
70    paused: string
71    resumed: string
72    opened: string
73  }
74  docsChangedToast: (docs: string) => string
75  unreadable: (text: string) => string
76  interrupted: string
77  notSaved: (error: string) => string
78}
79
80const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
81
82const en: Words = {
83  title: 'Intent review',
84  intent: { match: 'matches intent', partial: 'partly off intent', mismatch: 'off intent' },
85  level: { logic: 'logic change', tests: 'tests only', trivial: 'trivial change' },
86  origin: { turn: 'Turn', all: 'Uncommitted', retry: 'Re-run' },
87  kind: {
88    code: 'code',
89    test: 'test',
90    principles: 'principles doc',
91    comment: 'comments only',
92    docs: 'docs',
93    binary: 'binary',
94  },
95  severity: { violation: 'violation', suspect: 'suspect' },
96  workaround: 'workaround',
97  status: {
98    on: 'on',
99    paused: 'paused',
100    running: 'reviewing…',
101    failed: error => `failed: ${error}`,
102    docsChanged: docs => `principle docs changed (${docs}) — check them`,
103    trivial: 'trivial change only (comments, docs)',
104    noFindings: 'no findings',
105    violations: n => plural(n, 'violation'),
106    suspects: n => plural(n, 'suspect'),
107    unstated: n => `${n} not in report`,
108    snapshotFailed: why => `could not snapshot the work tree, this turn is not reviewed (${why})`,
109  },
110  panel: {
111    header: (origin, nth, count) => `${origin} review ${nth}/${count}`,
112    docsChanged: docs => `Principle docs changed: ${docs} — this changes the rules, check it yourself`,
113    running: 'Reviewing…',
114    failed: error => `Review failed: ${error}`,
115    unknown: 'unknown',
116    skipped: 'Only comments, docs or binaries changed — skipped the model review.',
117    did: 'What it did',
118    noSummary: '(no summary)',
119    findings: 'Findings',
120    excepted: numbers => `Approved as exceptions: ${numbers.map(n => `#${n}`).join(', ')}`,
121    unstated: 'Changed but not in the report',
122    attention: 'Where to look',
123    noFindings: 'No findings.',
124    files: 'Files',
125    more: n => ` and ${n} more`,
126    inScope: 'In scope of',
127    empty: 'No reviews yet. They show up here when a turn that changed code ends.',
128    pausedBanner: 'Automatic review paused — /motive-mem resume',
129    notFound: 'Review not found.',
130    prev: '◀ Prev',
131    next: 'Next ▶',
132    send: 'Send to Claude',
133    retry: 'Review again',
134    reviewAll: 'Review all uncommitted',
135    uncommitted: 'All uncommitted',
136    exceptHint: "Wrong finding? Approve it as an exception — later reviews won't raise the same thing again.",
137    except: (nth, principle, file) => `Approve #${nth} as exception (${principle} ${file})`,
138  },
139  fix: {
140    intro: [
141      'The intent review flagged the following in the last change. Fix it so the principles (.claude/principles.md) hold.',
142      "If you think a finding is wrong, don't change the code — say why it is wrong.",
143    ],
144    intent: 'Intent',
145    unstated: 'Changed but not in the report',
146  },
147  command: {
148    description: 'Open the intent review panel · all: review all uncommitted changes · pause / resume: stop or restart automatic review',
149    notRepo: 'Intent review is idle: this is not a git repository.',
150    noPrinciples: path => `Intent review is idle: no ${path}. To create one, run /motive-mem:principles`,
151    nothing: 'Nothing to review.',
152    noHead: 'Could not read HEAD.',
153    reviewingAll: 'Reviewing all uncommitted changes. The result shows in the status line and the panel.',
154    paused: 'Automatic review paused. To turn it back on: /motive-mem resume',
155    resumed: 'Automatic review is back on, from the next turn.',
156    opened: 'Opened the intent review panel.',
157  },
158  docsChangedToast: docs => `Principle docs changed: ${docs}`,
159  unreadable: text => `could not read the answer: ${text}`,
160  interrupted: `stopped before it finished — review it again`,
161  notSaved: error => `Could not save the approval: ${error}`,
162}
163
164const ko: Words = {
165  title: '의도 리뷰',
166  intent: { match: '의도 일치', partial: '의도 일부 어긋남', mismatch: '의도와 다름' },
167  level: { logic: '로직 변경', tests: '테스트만', trivial: '사소한 변경' },
168  origin: { turn: '턴', all: '미커밋 전체', retry: '다시 검토' },
169  kind: {
170    code: '코드',
171    test: '테스트',
172    principles: '원칙 문서',
173    comment: '주석만',
174    docs: '문서',
175    binary: '바이너리',
176  },
177  severity: { violation: '위반', suspect: '의심' },
178  workaround: '땜질',
179  status: {
180    on: '켜짐',
181    paused: '멈춤',
182    running: '검토 중…',
183    failed: error => `실패: ${error}`,
184    docsChanged: docs => `원칙 문서가 바뀜(${docs}) — 확인 필요`,
185    trivial: '사소한 변경만(주석·문서)',
186    noFindings: '지적 없음',
187    violations: n => `위반 ${n}`,
188    suspects: n => `의심 ${n}`,
189    unstated: n => `보고 밖 ${n}`,
190    snapshotFailed: why => `작업 트리를 찍지 못해 이번 턴은 리뷰하지 않음 (${why})`,
191  },
192  panel: {
193    header: (origin, nth, count) => `${origin} 리뷰 ${nth}/${count}`,
194    docsChanged: docs => `원칙 문서가 바뀌었다: ${docs} — 규칙이 바뀌는 변경이니 직접 확인할 것`,
195    running: '검토 중…',
196    failed: error => `리뷰 실패: ${error}`,
197    unknown: '알 수 없음',
198    skipped: '주석·문서·바이너리만 바뀌어 모델 리뷰를 건너뛰었다.',
199    did: '한 일',
200    noSummary: '(요약 없음)',
201    findings: '지적',
202    excepted: numbers => `예외로 승인함: ${numbers.join(', ')}번`,
203    unstated: '보고에 없던 변경',
204    attention: '사람이 볼 곳',
205    noFindings: '지적 없음.',
206    files: '파일',
207    more: n => ` 외 ${n}`,
208    inScope: '원칙 범위',
209    empty: '아직 리뷰가 없습니다. 코드를 바꾼 턴이 끝나면 여기에 나옵니다.',
210    pausedBanner: '자동 리뷰 멈춤 — /motive-mem resume',
211    notFound: '리뷰를 찾지 못했습니다.',
212    prev: '◀ 이전',
213    next: '다음 ▶',
214    send: 'Claude에게 전달',
215    retry: '다시 검토',
216    reviewAll: '미커밋 전체 검토',
217    uncommitted: '미커밋 전체',
218    exceptHint: '틀린 지적이면 예외로 승인 — 다음 리뷰부터 같은 건을 다시 짚지 않습니다.',
219    except: (nth, principle, file) => `${nth}번 예외 승인 (${principle} ${file})`,
220  },
221  fix: {
222    intro: [
223      '의도 리뷰가 방금 변경에서 아래를 짚었다. 원칙(.claude/principles.md)을 지키는 방향으로 고쳐 줘.',
224      '지적이 틀렸다고 보면 고치지 말고 왜 틀렸는지 말해 줘.',
225    ],
226    intent: '의도',
227    unstated: '보고에 없던 변경',
228  },
229  command: {
230    description: '의도 리뷰 패널 열기 · all: 미커밋 전체 검토 · pause / resume: 자동 리뷰 멈춤·재개',
231    notRepo: 'git 저장소가 아니라 의도 리뷰가 쉬고 있습니다.',
232    noPrinciples: path => `${path} 가 없어 의도 리뷰가 쉬고 있습니다. 원칙 파일을 만들려면 /motive-mem:principles`,
233    nothing: '검토할 변경이 없습니다.',
234    noHead: 'HEAD 를 읽지 못했습니다.',
235    reviewingAll: '미커밋 변경 전체를 검토합니다. 끝나면 상태 줄과 패널에 나옵니다.',
236    paused: '자동 리뷰를 멈췄습니다. 다시 켜려면 /motive-mem resume',
237    resumed: '자동 리뷰를 다시 켰습니다. 다음 턴부터 봅니다.',
238    opened: '의도 리뷰 패널을 열었습니다.',
239  },
240  docsChangedToast: docs => `원칙 문서가 바뀌었습니다: ${docs}`,
241  unreadable: text => `답을 읽지 못함: ${text}`,
242  interrupted: `끝나기 전에 멈춤 — 다시 검토할 것`,
243  notSaved: error => `예외 승인을 저장하지 못했습니다: ${error}`,
244}
245
246export const WORDS: Record<Lang, Words> = { en, ko }
247
types/index.d.ts 64 lines
1export type FileKind = 'code' | 'test' | 'comment' | 'docs' | 'binary' | 'principles'
2
3export type Level = 'logic' | 'tests' | 'trivial'
4
5export type FileStatus = 'added' | 'modified' | 'deleted' | 'renamed' | 'untracked'
6
7export type FileSummary = {
8  path: string
9  status: FileStatus
10  added: number
11  removed: number
12  kind: FileKind
13}
14
15export type FileChange = FileSummary & { lines: string[] }
16
17export type Principle = { id: string; title: string; scope: string[] }
18
19export type Finding = {
20  principle: string
21  severity: 'violation' | 'suspect'
22  file: string
23  line?: number
24  why: string
25  evidence: string
26}
27
28export type Verdict = {
29  summary: string
30  intent: 'match' | 'partial' | 'mismatch'
31  intentNote: string
32  findings: Finding[]
33  unstated: string[]
34  attention: string[]
35}
36
37export type Decision = { at: number; principle: string; file: string; why: string }
38
39// `isAll`: the review covers every uncommitted change, so there is no report to hold the diff to
40export type Intent = { prompts: string[]; answer: string; isAll?: boolean }
41
42export type Review = {
43  id: string
44  at: number
45  origin: 'turn' | 'all' | 'retry'
46  status: 'running' | 'done' | 'skipped' | 'error'
47  level: Level
48  range: { from: string; to: string; fresh: string[] }
49  files: FileSummary[]
50  principleDocs: string[]
51  hits: Record<string, string[]>
52  intent: Intent
53  model: string
54  verdict?: Verdict
55  error?: string
56  excepted: number[]
57}
58
59declare module 'claude-code' {
60  interface PluginState {
61    'motive-mem': { reviews: Review[]; cursor: number; isPaused: boolean }
62  }
63}
64