SLOPSHOPPER

repro

Holds a Claude Code research session to its records: refuses an edit to a frozen plan, says when a manuscript or a run has no ledger behind it, and shows what…

panebandguardcommandstatusprompt
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · repro
│ ┃ Research projects ✕ › fix the failing auth test and add an audit log call │ ┃ 1–0 of 0 · Enter to pick · Esc to close │ ⏺ Read(src/auth.ts) │ ⎿ 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 │ │ › /repro-status │ ⎿ repro: 0 research projects. ↑ and ↓ to move, Enter to pick, Esc │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Research projects
1–0 of 0 · Enter to pick · Esc to close
README

repro

A Claude Code mod for research sessions. The reproducible-science plugin's hooks speak when a number enters a manuscript unbound or a frozen plan changes, refuse an edit to a frozen plan, and act only in a project that already keeps a ledger or a plan. This closes the other half: it works in a project that keeps neither yet.

It is a plugin of function hooks. That API is early access and changes between Claude Code releases, so this ships beside the reproducible-science plugin and not inside it: a build that cannot load it still loads the plugin.

What it does

Refuses an edit to a frozen fileAn Edit or Write to a file with a freeze record (.prereg/<name>.json beside it: a plan or an amendment), or to a PREREG.md carrying a freeze digest, is denied, with the instruction to record a note with prereg log or a change with prereg amend. The file is matched where it lands as well as by the name the edit gives: a symbolic link to a frozen plan, or prereg.md on a disk that ignores case, is refused too. A hard link to a frozen plan is not matched, because the mod's file interface reports no device or inode. An amendment still in draft has no record and is edited freely.
Notes a manuscript with no ledgerThe first edit to a .tex, .Rmd, .qmd or .typ with no .results/ ledger above it goes through, and the model is told no number in the file is bound to a run.
Notes an analysis with no ledgerThe same, once per project, when a command runs an analysis.
Notes a downloaded sourceAfter curl or wget saves a PDF, the model is told the address to record as url: in the claims file, so citations fetch can retrieve the same bytes for a reader.
Puts the gates in the system promptSeal before a run, claim before a number, freeze before a confirmatory analysis, with the state of the project's records as of the last turn.
Shows the stateOne dim row above the prompt, refreshed at the end of each turn, with one field per tool and one for re-runs of the declared commands.
WarnsThe pinned line under the prompt appears only when something is wrong, a few words per problem.
/repro-statusThe same readout on demand, with the sealed files hashed. Instant, and no model turn.
/repro-verifyChecks every pinned quotation of the working project against its source, which takes minutes on a large project, and keeps the count for the readout.
/repro-hide, /repro-showHides the readout above the prompt, and shows it again. A warning still appears while it is hidden.

The status row

study · prereg: 1/1 frozen · results: 3/3 runs sealed, 4 claims bound · citations: 120/120 quotes found · repro: 34/34 checks verified

Above the prompt each field is drawn on a row of its own. prereg is frozen plans over all plans, or none drafted.

results is the runs recorded after inputs were sealed, over all runs, then the claims bound to a run with results claim. A run recorded before anything was sealed lowers the first number: 2/3 runs sealed. A run whose id begins smoke_, prefreeze_, test_ or dryrun_ is a test run and is left out of the row, because it is recorded before a plan is frozen and nothing may be claimed from it.

citations is the last full check by /repro-verify, and before one has run it is the count pinned: citations: 120 pinned, not verified. Checking quotations takes minutes on a large project, so the row never runs it. A check that does not finish in a minute marks its own field not read (timed out) and leaves the others standing. A tool that is not on PATH is run as repro <tool>, which is how uv tool install reproducible-science without --with-executables-from leaves it, and a field whose tool cannot be run either way reads not installed.

repro is the checks claims verify verified over all the manifest declares, one per assertion: the claims alone, which is the fast check. The manifest is the repro.yaml at the project's top or above it, which is the one claims verify reads without being given a path. A manifest under another name or in a subfolder (paper/repro.yaml) is not found, and a project with none reads repro: no manifest. Claims are counted on the results row, where results claim makes them:

repro: 56/56 checks verified repro: 55/56 checks verified repro: 6/6 checks verified, 1 broken pin

A pinned file that changed is named because the assertions read from it still verify, against a file that is not the declared one. Where claims verify does not print a line for every assertion and some did not verify, the field gives the tool's own words: repro: 1 mismatch, 33 verified. The check takes under a second on a manifest of 56 assertions, so it runs with the others at the end of each turn.

A manifest that declares commands under regenerations adds a second repro row, for the re-runs of those commands that repro reproduce has recorded in .repro/reproductions.jsonl:

repro: 7/7 reproduced, last 13 Oct repro: 5/7 reproduced, 2 stale since 13 Oct → repro reproduce repro: 0/7 reproduced → repro reproduce

The numbers count declared commands, not assertions. A command is reproduced where repro stale calls it current: a recorded re-run that reproduced ran today's command over the files now on disk, and the same holds for every command upstream. A command repro stale calls stale or undetermined is counted under that word, and a command never re-run only lowers the first number. The date is the day the latest of the re-runs compared against started, in the machine's time zone, and in CI follows it where that re-run's entry carries a witness. The row is read from repro stale --format json, which executes nothing and takes about as long as claims verify, and it is not run for a manifest with no regenerations, which draws no row. Neither does a record of re-runs with a line repro stale cannot read.

A row whose tool has a next step still to take names the command that takes it, directly after the row:

citations: none pinned → citations pin repro: no manifest → repro manifest init

prereg: none drafted points at prereg new, an unfrozen draft at prereg freeze, a missing ledger at results init, a ledger with no runs at results seal, a manifest with no claims at adding some, and declared commands not all reproduced at repro reproduce. A project with none of the four set up shows one hint, repro init, which creates all four. A row with something to report carries no hint.

The warnings, each on the pinned line as repro: ...:

1 plan edited after freezea frozen PREREG.md no longer matches its digest
ledger truncated, edited, corruptthe chain does not verify
ledger rewritten after timestampa timestamp proof contradicts the chain
2 sealed files changedafter /repro-status, which hashes the sealed files
16 runs, nothing sealedruns are recorded and no input was sealed
3 runs, no plan frozenruns are recorded and no plan is frozen
1 number mismatcheda number in the manuscript disagrees with the artifact repro.yaml binds it to
1 quotation mismatchedthe same, for a quote assertion
2 claims mismatchedthe same, where the kind could not be read off claims verify's lines
1 quotation not foundafter /repro-verify: a pinned quotation is not in its source
1 claim on test runsa manuscript number is bound to a run named as a test run

An assertion or a quotation that is unchecked, and a claim offering no evidence, are counted in the row and draw no warning.

The working project

A session started in one folder often edits files in another, so the project is read off the paths the tools touch: the nearest directory above a touched file that holds a .results/ ledger, a claims/ directory, a PREREG.md or a paper/ directory.

/repro-status the working project's state /repro-status <part of a name> set the working project, among the folders beside the session's /repro-status pick choose one from a list /repro-status list print them /repro-status auto go back to following the files

The model can set it too, through the set_project tool the mod registers.

Install

/plugin marketplace add elliottower/reproducible-science /plugin install repro@reproducible-science

It needs the results, prereg and citations commands on PATH, and repro for the fourth and fifth fields.

Develop

claude plugin validate packages/repro/mod claude plugin test packages/repro/mod

The tests stand in for the engine and need no network or account. The mod tests job of this repository's CI installs the Claude Code pinned in .github/mod-tests and runs both commands.

Source 2 files
hooks/register.ts 1093 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4/** What `prereg freeze` once wrote into a plan. Its presence makes a plan frozen in place. */
5const FROZEN = /^\*\*Plan sha256:\*\*[ \t]*`[0-9a-f]{64}`/m
6
7/**
8 * Where `prereg freeze` records a file frozen whole: `.prereg/<name>.json` beside it. A plan and
9 * each of its amendments has one, and a file with one is never written to again.
10 */
11const recordOf = (path: string) => `${parent(path)}/.prereg/${path.replace(/^.*\//, '')}.json`
12
13const PLAN = 'PREREG.md'
14const LEDGER = '.results/ledger.jsonl'
15const MANIFEST = 'repro.yaml'
16
17/**
18 * What a row reads while its tool has a next step still to take, and the command that takes it.
19 * A row matching none of these carries no hint.
20 */
21const HINTS: [state: RegExp, next: string][] = [
22  [/prereg: none drafted$/, 'prereg new'],
23  [/prereg: 0\/\d+ frozen$/, 'prereg freeze'],
24  [/^results: no ledger$/, 'results init'],
25  [/^results: 0 runs, 0 claims bound$/, 'results seal'],
26  [/^citations: none pinned$/, 'citations pin'],
27  [/^repro: no manifest$/, 'repro manifest init'],
28  [/^repro: no claims declared$/, 'add claims to repro.yaml'],
29  // Fewer commands reproduced than declared: the two numbers differ.
30  [/^repro: (\d+)\/(?!\1 )\d+ reproduced/, 'repro reproduce'],
31]
32/** The rows of a project with nothing set up, which `repro init` starts in one command. */
33const NOTHING = [/prereg: none drafted$/, /^results: no ledger$/, /^citations: none pinned$/, /^repro: no manifest$/]
34const MANUSCRIPT = /\.(tex|rmd|qmd|typ)$/i
35
36/** Programs that run an analysis, matched on a command's first three words. */
37const RUNNERS = new Set([
38  'python', 'python3', 'uv', 'Rscript', 'julia', 'make', 'snakemake', 'nextflow', 'papermill',
39  'jupyter', 'quarto', 'modal', 'sbatch', 'srun',
40])
41
42const GATES = `# Research records (reproducible-science)
43
44This project keeps machine-checkable records, and three steps are not taken without one:
45
461. Before a run whose output a paper will report: \`results seal\` the inputs, then \`results run\`. With no ledger in the repository, \`results init\` comes first.
472. Before a number goes into a manuscript: \`results claim\` binds the sentence to the run that produced it.
483. Before a confirmatory analysis runs: \`prereg freeze\` the plan. A frozen plan or amendment is never edited; a note is recorded with \`prereg log\` and a change to the plan with \`prereg amend\`.
49
50A quotation is pinned with \`citations pin\` before the sentence quoting it is written.
51A gate is skipped only with the user's approval or a reason written into the notebook or the commit message, and the user is told in the same turn.`
52
53const parent = (path: string) => path.replace(/\/[^/]*$/, '')
54const dirOf = (path: string) => (path.includes('/') ? parent(path) : '.')
55
56/** The nearest `name` at or above `dir`, or undefined. Stops at the filesystem root. */
57async function above($: EngineInterface, dir: string, name: string) {
58  for (let at = dir; ; at = parent(at)) {
59    if (await $.fs.exists(`${at}/${name}`)) {
60      return `${at}/${name}`
61    }
62    if (at === '' || at === '.' || !at.includes('/')) {
63      return undefined
64    }
65  }
66}
67
68/**
69 * The paths an edit to `path` may write: as named, then where it lands. `realPath` follows every
70 * symbolic link; a case alias keeps its own spelling there, so the last name is read back from
71 * its folder's listing, which spells it as the disk stores it. A file not there yet lands in its
72 * folder's real path.
73 */
74async function candidates($: EngineInterface, path: string): Promise<string[]> {
75  const name = path.replace(/^.*\//, '')
76  const own = await $.fs.stat(path, { resolve: true }).catch(() => undefined)
77  const folder = own?.realPath
78    ? parent(own.realPath)
79    : (await $.fs.stat(parent(path), { resolve: true }).catch(() => undefined))?.realPath
80  if (folder === undefined) {
81    return [path]
82  }
83  const landed = own?.realPath ? own.realPath.replace(/^.*\//, '') : name
84  const listed = own ? await $.fs.list(folder).catch(() => []) : []
85  const spelled =
86    listed.some(entry => entry.name === landed)
87      ? landed
88      : (listed.find(entry => entry.name.toLowerCase() === landed.toLowerCase())?.name ?? landed)
89  const real = `${folder}/${spelled}`
90
91  return real === path ? [path] : [path, real]
92}
93
94async function absolute($: EngineInterface, path: string) {
95  const cwd = await $.session.cwd()
96  if (path.startsWith('~/')) {
97    return `${/^\/(?:Users|home)\/[^/]+/.exec(cwd)?.[0] ?? ''}${path.slice(1)}`
98  }
99
100  return path.startsWith('/') ? path : `${cwd}/${path}`
101}
102
103/** What marks a directory as a research project: a ledger, pinned quotations, a plan or a manuscript folder. */
104const MARKERS = ['.results', 'claims', PLAN, 'paper']
105
106/** The nearest research project at or above `dir`, or undefined. */
107async function projectOf($: EngineInterface, dir: string) {
108  for (let at = dir; at.includes('/') && at !== ''; at = parent(at)) {
109    for (const name of MARKERS) {
110      if (await $.fs.exists(`${at}/${name}`)) {
111        return at
112      }
113    }
114  }
115
116  return undefined
117}
118
119/** The directory a shell command works in when it opens with `cd <dir>`, or undefined. */
120const cdTarget = (command: string) => /(?:^|[;&]\s*)cd\s+["']?([^\s"';&]+)/.exec(command)?.[1]
121
122/** A command that saves a PDF from a URL: `[url, path]`, or undefined. curl and wget only. */
123function download(command: string): [string, string] | undefined {
124  if (!/\b(curl|wget)\b/.test(command)) {
125    return undefined
126  }
127  const url = /https?:\/\/[^\s"'<>|;&)]+/.exec(command)
128  const saved = /(?:-o|-O|--output|--output-document|>)\s*["']?([^\s"'|;&]+\.pdf)\b/i.exec(command)
129
130  return url && saved ? [url[0], saved[1] as string] : undefined
131}
132
133/** Whether a command runs an analysis. An inline script (`python3 - <<EOF`, `python -c`) is not one. */
134const runsAnAnalysis = (command: string) =>
135  !/\s-(c\s|\s*<<)/.test(command) &&
136  command.trim().split(/\s+/).slice(0, 3).some(word => RUNNERS.has(word.replace(/^.*\//, '')))
137
138/**
139 * The last full quotation check of each project, as `found/pinned`. Checking thousands of
140 * quotations takes minutes, so the status line never runs it: `/repro-verify` does, and the
141 * result is kept here, in the session's state, until the next one.
142 */
143const quotations = atom({ plugin: 'repro', key: 'quotations' } as const, {} as Record<string, string>)
144
145/**
146 * How many quotations that check reported as `not found`, by project. Kept apart from the
147 * fraction because pinned less found also counts the quotations the check could not read.
148 */
149const quotationsNotFound = atom(
150  { plugin: 'repro', key: 'quotationsNotFound' } as const,
151  {} as Record<string, number>,
152)
153
154const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
155
156/** The tools `repro <tool>` also runs, for an install that put only `repro` on PATH. */
157const VIA_REPRO = new Set(['claims', 'prereg', 'results', 'citations'])
158
159/**
160 * A command's output; undefined when it did not finish in time, and null when it is not installed.
161 *
162 * `$.process.run` rejects on a timeout, and a rejection here used to end the whole turn's hook:
163 * one slow `prereg check` on a busy machine left no status line at all. A check that did not
164 * finish now marks its own field and leaves the others standing. `uv tool install
165 * reproducible-science` puts only `repro` on PATH, so a tool that will not start is asked for
166 * again as `repro <tool>`, which runs the same command from `repro`'s own environment.
167 */
168async function output($: EngineInterface, argv: string[], cwd: string, timeoutMs: number) {
169  const run = async (args: string[]) => {
170    try {
171      const ran = await $.process.run(args, { cwd, timeoutMs })
172      return ran.exitCode === 127 ? null : ran.stdout
173    } catch (e) {
174      // A command that cannot start is not installed; anything else is one still running.
175      return /ENOENT|not found|no such file|spawn/i.test(String(e)) ? null : undefined
176    }
177  }
178  const got = await run(argv)
179  return got === null && VIA_REPRO.has(argv[0] ?? '') ? run(['repro', ...argv]) : got
180}
181
182/** A field whose command gave nothing to read: not installed, or still running at its deadline. */
183const unread = (tool: string, got: null | undefined) =>
184  `${tool}: ${got === null ? 'not installed' : 'not read (timed out)'}`
185
186/** The outcomes `claims verify` counts, the most serious first, which is the order the row gives them in. */
187const OUTCOMES = ['mismatch', 'not_found', 'error', 'unchecked', 'not_offered', 'verified']
188
189/** The kinds of evidence `claims verify` prints beside an assertion. Only `quote` is not a number. */
190const KINDS = new Set(['quote', 'metric', 'table', 'value', 'correspondence', 'aggregate'])
191
192/**
193 * The `repro` field and its warnings, from what `claims verify` printed:
194 *
195 *       MISS  effect-size  correspondence effect-delta: manuscript 0.055, run 0.0453
196 *
197 *       1 mismatch, 2 verified
198 *       policy publication: FAILED  (1 errors, 0 warnings)
199 *
200 * The counts are the tool's own summary line, under its own words. A pinned file that changed
201 * is counted too: the assertions read from it still say `verified`, of a file that is not the
202 * declared one, and `3/3 verified` would be the row saying so.
203 */
204function assertions(printed: string | null | undefined) {
205  if (printed == null) {
206    return { field: unread('repro', printed), wrong: [] }
207  }
208  // Without the policy line nothing was verified: the manifest did not load.
209  if (!/^\s+policy \S+: (passed|FAILED)/m.test(printed)) {
210    return { field: 'repro: manifest unreadable', wrong: [] }
211  }
212  const summary = /^\s+(\d+ \w+(?:, \d+ \w+)*)$/m.exec(printed)?.[1] ?? ''
213  const counts = new Map([...summary.matchAll(/(\d+) (\w+)/g)].map(([, n, word]) => [word as string, Number(n)]))
214  const total = [...counts.values()].reduce((a, b) => a + b, 0)
215  const said = (n: number) => n.toLocaleString('en-US')
216  const brokenPins = (printed.match(/^\s+BROKEN PIN\s/gm) ?? []).length
217  const parts = [
218    ...(brokenPins ? [`${said(brokenPins)} broken ${brokenPins === 1 ? 'pin' : 'pins'}`] : []),
219    ...OUTCOMES.filter(word => counts.has(word)).map(word => `${said(counts.get(word) ?? 0)} ${word.replace(/_/g, ' ')}`),
220  ]
221  const verified = counts.get('verified') ?? 0
222  // The row counts checks, one per assertion. Claims are counted on the results row, where
223  // `results claim` makes them. Where every assertion is printed the row is a fraction even
224  // when some failed; otherwise it is a fraction only when all verified.
225  const lines = [...printed.matchAll(/^\s+(ok|MISS|GONE|--|ERR|none)\s+(\S+)\s/gm)]
226  const pins = brokenPins ? `, ${said(brokenPins)} broken ${brokenPins === 1 ? 'pin' : 'pins'}` : ''
227
228  const wrong: string[] = []
229  const mismatched = counts.get('mismatch') ?? 0
230  if (mismatched) {
231    // The kind is the word after the claim's id. An id with a space in it moves that word, and
232    // a line cut short hides one, so the kinds are believed only when every one is a known kind.
233    const kinds = [...printed.matchAll(/^\s+MISS\s+\S+\s+(\S+)/gm)].map(match => match[1] as string)
234    const quotes = kinds.filter(kind => kind === 'quote').length
235    if (kinds.length !== mismatched || !kinds.every(kind => KINDS.has(kind))) {
236      wrong.push(`${plural(mismatched, 'claim')} mismatched`)
237    } else {
238      if (mismatched > quotes) {
239        wrong.push(`${plural(mismatched - quotes, 'number')} mismatched`)
240      }
241      if (quotes) {
242        wrong.push(`${plural(quotes, 'quotation')} mismatched`)
243      }
244    }
245  }
246
247  return {
248    field:
249      total === 0
250        ? 'repro: no claims declared'
251        : lines.length === total
252          ? `repro: ${said(verified)}/${said(total)} checks verified${pins}`
253          : verified === total && !brokenPins
254            ? `repro: ${said(verified)}/${said(total)} checks verified`
255            : `repro: ${parts.join(', ')}`,
256    wrong,
257  }
258}
259
260const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
261
262/** What `repro stale --format json` says of one declared command. */
263type Rerun = { state?: string; rerun_at?: string | null; witness?: { kind?: string } | null }
264
265/**
266 * The field for re-runs of the commands the manifest declares, from `repro stale`:
267 *
268 *     repro: 7/7 reproduced, last 13 Oct
269 *     repro: 5/7 reproduced, 2 stale since 13 Oct
270 *     repro: 0/7 reproduced
271 *
272 * The counts are declared commands, one per record under `regenerations`. A command is counted
273 * as reproduced where `repro stale` calls it `current`: a recorded re-run that reproduced ran
274 * today's command over the files now on disk. The date is when the latest re-run those states
275 * were read against started, in this machine's time zone, and `in CI` follows where that
276 * re-run's entry carries a witness.
277 *
278 * Undefined, and no row, where the manifest declares no command, and where `repro stale` did
279 * not finish or printed no report: a record of re-runs with a line it cannot read, or a `repro`
280 * with no `stale` command. `repro stale` executes nothing and hashes the files `claims verify`
281 * has just hashed, so it costs what the row above costs, and it is not run at all for a manifest
282 * with no `regenerations`.
283 */
284async function reruns($: EngineInterface, root: string, manifest: string) {
285  let declared = ''
286  try {
287    declared = await $.fs.read(manifest)
288  } catch {
289    return undefined
290  }
291  if (!/^regenerations\s*:/m.test(declared)) {
292    return undefined
293  }
294  let commands: Rerun[] = []
295  try {
296    const report = JSON.parse((await output($, ['repro', 'stale', '--format', 'json'], root, 60_000)) ?? '')
297    commands = report.staleness.regenerations
298  } catch {
299    return undefined
300  }
301  if (!Array.isArray(commands) || commands.length === 0) {
302    return undefined
303  }
304  const count = (state: string) => commands.filter(command => command.state === state).length
305  const stale = count('stale')
306  const undetermined = count('undetermined')
307  const last = commands
308    .filter(command => !Number.isNaN(Date.parse(command.rerun_at ?? '')))
309    .sort((a, b) => Date.parse(b.rerun_at ?? '') - Date.parse(a.rerun_at ?? ''))[0]
310  const at = last ? new Date(last.rerun_at ?? '') : undefined
311  const when = at ? `${at.getDate()} ${MONTHS[at.getMonth()]}${last?.witness ? ' in CI' : ''}` : undefined
312
313  return [
314    `repro: ${count('current')}/${commands.length} reproduced`,
315    ...(stale ? [`${stale} stale${when ? ` since ${when}` : ''}`] : []),
316    ...(undetermined ? [`${undetermined} undetermined`] : []),
317    ...(!stale && when ? [`last ${when}`] : []),
318  ].join(', ')
319}
320
321/**
322 * Every `claims` folder in the project, relative to its root. A paper keeps its pinned quotations
323 * beside the manuscript as often as at the top (`paper/prior_art/claims`), and looking only at
324 * the top reported 63 pinned quotations as none.
325 */
326async function claimsFolders($: EngineInterface, root: string) {
327  const found = await output(
328    $,
329    ['find', '.', '-maxdepth', '4', '-type', 'd', '-name', 'claims', '-not', '-path', '*/node_modules/*', '-not', '-path', '*/.git/*'],
330    root,
331    20_000,
332  )
333
334  return (found ?? '')
335    .split('\n')
336    .map(line => line.replace(/^\.\//, '').trim())
337    .filter(line => line.length > 0)
338    .sort()
339}
340
341/**
342 * Folders below the project that hold a `PREREG.md` of their own. `prereg check` reads the plan
343 * nearest the folder it runs in, so a study kept in a subfolder was never listed: a repository
344 * with a second frozen plan under `artifact_survey/` read `1/1 frozen`.
345 */
346async function planFolders($: EngineInterface, root: string) {
347  const found = await output(
348    $,
349    ['find', '.', '-mindepth', '2', '-maxdepth', '4', '-type', 'f', '-name', 'PREREG.md', '-not', '-path', '*/node_modules/*', '-not', '-path', '*/.git/*'],
350    root,
351    20_000,
352  )
353
354  return (found ?? '')
355    .split('\n')
356    .map(line => line.replace(/^\.\//, '').trim())
357    .filter(line => line.endsWith('/PREREG.md'))
358    .map(line => line.slice(0, -'/PREREG.md'.length))
359    .sort()
360}
361
362/**
363 * What the last `status` found wrong, each in a few words. Drawn on the engine's pinned line
364 * under the prompt, which is one row and spends about 28 columns on this plugin's name, so a
365 * warning names the problem and `/repro-status` says what to do. The line is kept for these
366 * because of its warning mark: a line that is there every turn stops being read as a warning.
367 */
368let warnings: string[] = []
369
370/**
371 * One line, one field per tool, in a fixed order so each is found in the same place every turn:
372 *
373 *     study · prereg: 1/1 frozen · results: 2/3 runs sealed, 4 claims bound · citations: 120/120 quotes found · repro: 34/34 checks verified
374 *
375 * The `repro` field is there only in a project with a manifest, and a second one follows it where
376 * the manifest declares commands: `repro: 7/7 reproduced, last 13 Oct`. Fractions only where there is a real total. The project's name stays, because the project
377 * followed is the one whose files the session touches, which need not be where it started.
378 *
379 * `withFiles` also hashes every sealed file, which is the check that finds a changed input and
380 * the one that costs: it runs for `/repro-status`, never at the end of every turn.
381 */
382async function status($: EngineInterface, root: string, withFiles: boolean) {
383  const fields = [root.replace(/^.*\//, '')]
384  const wrong: string[] = []
385
386  // `prereg check` reads every plan at, above and below the directory it runs in.
387  const plans = await output($, ['prereg', 'check'], root, 60_000)
388  // One line per plan, whichever folder reported it: a check run in a subfolder also lists the
389  // plan above it.
390  const listed = new Set((plans ?? '').split('\n'))
391  if (plans != null) {
392    for (const folder of await planFolders($, root)) {
393      const below = await output($, ['prereg', 'check'], `${root}/${folder}`, 60_000)
394      for (const line of (below ?? '').split('\n')) {
395        listed.add(line)
396      }
397    }
398  }
399  const counts = new Map<string, number>()
400  for (const line of listed) {
401    // A plan frozen with `prereg freeze` is listed by its absolute path. A registration frozen by a
402    // commit line in the document is listed by its path in the repository, under its own words:
403    // text added after the frozen text leaves the plan intact, and a commit that is pending or not
404    // in the repository could not be checked, which is not a change. A draft `prereg check` lists
405    // as superseded is one plan with the document that ends its chain, which is listed too, and a
406    // plan listed as withdrawn awaits no freeze: neither matches here, so neither is counted.
407    const pinned = /^(unchanged|appended|CHANGED|pending|unknown commit)\s{2,}[^/\s]/.exec(line)?.[1]
408    const label =
409      /^([A-Za-z][A-Za-z ]*?)\s{2,}\//.exec(line)?.[1]?.toLowerCase() ??
410      (pinned && { unchanged: 'unchanged', appended: 'unchanged', CHANGED: 'changed' }[pinned]) ??
411      (pinned ? 'not frozen' : undefined)
412    // `log  <path>  4 entries, chain intact` reports the log kept beside a plan. It is not a
413    // plan, and counted as one it read as a plan that was neither frozen nor a draft: changed.
414    if (label && label !== 'log') {
415      counts.set(label, (counts.get(label) ?? 0) + 1)
416    }
417  }
418  const total = [...counts.values()].reduce((a, b) => a + b, 0)
419  const frozen = counts.get('unchanged') ?? 0
420  const broken = total - frozen - (counts.get('not frozen') ?? 0)
421  fields.push(
422    plans == null
423      ? unread('prereg', plans)
424      : total === 0
425        ? 'prereg: none drafted'
426        : broken
427          ? `prereg: ${broken} changed`
428          : `prereg: ${frozen}/${total} frozen`,
429  )
430  if (broken) {
431    wrong.push(`${plural(broken, 'plan')} edited after freeze`)
432  }
433
434  let runs = 0
435  if (await $.fs.exists(`${root}/${LEDGER}`)) {
436    const verified = await output(
437      $,
438      ['results', 'verify', ...(withFiles ? ['--files'] : [])],
439      root,
440      withFiles ? 300_000 : 60_000,
441    )
442    const head = verified?.split('\n')[0] ?? ''
443    if (verified == null) {
444      fields.push(unread('results', verified))
445    } else if (/chain intact: \d+ events/.test(head)) {
446      const ledger = await $.fs.read(`${root}/${LEDGER}`)
447      // A run counts as sealed when inputs were sealed before it was recorded. A run named as a
448      // test (`smoke_…`, `prefreeze_…`, `test_…`, `dryrun_…`) is left out of the row: it is
449      // recorded before a plan is frozen, and nothing may be claimed from it.
450      const events = ledger.split('\n').flatMap(line => {
451        try {
452          return line.trim() ? [JSON.parse(line) as { event?: string; run_id?: string }] : []
453        } catch {
454          return []
455        }
456      })
457      const isTest = (id: string | undefined) => /^(smoke|prefreeze|test|dryrun)[_-]/.test(id ?? '')
458      const claims = events.filter(event => event.event === 'claim')
459      let hasSeal = false
460      let sealed = 0
461      for (const event of events) {
462        if (event.event === 'seal') {
463          hasSeal = true
464        } else if (event.event === 'run' && !isTest(event.run_id)) {
465          runs += 1
466          sealed += hasSeal ? 1 : 0
467        }
468      }
469      // Two spaces exactly: a sealed file under `file hashes:`. A review's or an annotation's
470      // subject is listed four deep with the same word, and is not a seal. RESEALED, APPENDED,
471      // IGNORED and RETIRED pass `results verify --files` and are not counted; REVERTED and
472      // REAPPEARED fail it.
473      const changed = (verified.match(/^ {2}(CHANGED|MISSING|REVERTED|REAPPEARED)\s/gm) ?? []).length
474      const onTests = claims.filter(event => isTest(event.run_id)).length
475      fields.push(
476        `results: ${changed ? `${changed} changed, ` : ''}` +
477          `${runs ? `${sealed}/${runs} runs sealed` : '0 runs'}, ${plural(claims.length, 'claim')} bound`,
478      )
479      if (changed) {
480        wrong.push(`${plural(changed, 'sealed file')} changed`)
481      }
482      if (onTests) {
483        wrong.push(`${plural(onTests, 'claim')} on test runs`)
484      }
485      if (/^TIMESTAMP CONTRADICTS/m.test(verified)) {
486        wrong.push('ledger rewritten after timestamp')
487      }
488      if (runs > 0 && !hasSeal) {
489        wrong.push(`${plural(runs, 'run')}, nothing sealed`)
490      }
491    } else {
492      // `CHAIN TRUNCATED — events are missing from the end`: the word after CHAIN.
493      const fault = /^(?:CHAIN|NO)\s+(\w+)/.exec(head)?.[1]?.toLowerCase() ?? 'unreadable'
494      fields.push(`results: ${fault}`)
495      wrong.push(`ledger ${fault}`)
496    }
497  } else {
498    fields.push('results: no ledger')
499  }
500  if (runs > 0 && total > 0 && frozen === 0 && !broken) {
501    wrong.push(`${plural(runs, 'run')}, no plan frozen`)
502  }
503
504  const folders = await claimsFolders($, root)
505  if (folders.length > 0) {
506    const last = (await read($, quotations))[root]
507    if (last) {
508      fields.push(`citations: ${last}`)
509      const notFound = (await read($, quotationsNotFound))[root] ?? 0
510      if (notFound) {
511        wrong.push(`${plural(notFound, 'quotation')} not found`)
512      }
513    } else {
514      // Counting what is pinned is one grep; checking it is minutes, and `/repro-verify` does that.
515      const counted = await output(
516        $,
517        ['grep', '-rhcE', '^[[:space:]]*-?[[:space:]]*exact:', ...folders],
518        root,
519        20_000,
520      )
521      const pinned = (counted ?? '').split('\n').reduce((sum, n) => sum + (Number(n) || 0), 0)
522      fields.push(`citations: ${pinned.toLocaleString('en-US')} pinned, not verified`)
523    }
524  } else {
525    // Said, so the row always holds the same three fields and a missing one is not read as fine.
526    fields.push('citations: none pinned')
527  }
528
529  // `claims verify` reads the `repro.yaml` at or above the directory it runs in and no other, so
530  // that is the only manifest looked for. It takes under a second on 34 assertions, and runs here.
531  // With no manifest the field says so, as the others do for a missing ledger or plan: a row
532  // left out reads the same as nothing to check.
533  const manifest = await above($, root, MANIFEST)
534  if (manifest) {
535    // The two read the same files and neither waits on the other.
536    const [printed, rerun] = await Promise.all([
537      output($, ['claims', 'verify'], root, 60_000),
538      reruns($, root, manifest),
539    ])
540    const checked = assertions(printed)
541    fields.push(checked.field)
542    wrong.push(...checked.wrong)
543    if (rerun) {
544      fields.push(rerun)
545    }
546  } else {
547    fields.push('repro: no manifest')
548  }
549
550  warnings = wrong
551
552  return fields.join(' · ')
553}
554
555/** The pane that lists the research projects, one button each, to pick one from. */
556const PICKER = 'repro-projects'
557
558/** Each project's button is addressed by this prefix and its folder name. */
559const ROW = 'project:'
560
561// In a pane the arrows walk the buttons only while the whole tree fits: once there are rows to
562// scroll, an arrow scrolls the pane and the focus ring stays where it was. So the picker never
563// draws more rows than fit. It draws a window onto the list and slides the window as the ring
564// reaches either edge of it.
565
566// Both live in the session's state, which the pane reads while it draws: a write then redraws
567// the pane by itself. Kept in module variables, a slide changed the number and drew nothing.
568
569/** How many projects the window shows. Corrected from the pane's real height on a first scroll. */
570const windowRows = atom({ plugin: 'repro', key: 'windowRows' } as const, 8)
571
572/** The index in `found` of the window's first row. */
573const top = atom({ plugin: 'repro', key: 'top' } as const, 0)
574
575const lastTop = (rows: number) => Math.max(0, found.length - rows)
576
577/** The line of the pane the focus ring is on, from 0, to tell a wrap from an ordinary move. */
578let lastLine = 0
579
580/** The research projects last found beside the session's folder, by folder name. */
581let found: string[] = []
582
583/**
584 * The research projects in the folder that holds the session's own: each folder there with a
585 * ledger, pinned quotations or a plan at its top level, the ones with a ledger first.
586 */
587async function discover($: EngineInterface) {
588  const home = parent(await $.session.cwd())
589  const withLedger: string[] = []
590  const others: string[] = []
591  const papersOnly: string[] = []
592  for (const entry of await $.fs.list(home)) {
593    if (entry.kind !== 'dir' || entry.name.startsWith('.')) {
594      continue
595    }
596    if (await $.fs.exists(`${home}/${entry.name}/${LEDGER}`)) {
597      withLedger.push(entry.name)
598    } else if (
599      (await $.fs.exists(`${home}/${entry.name}/claims`)) ||
600      (await $.fs.exists(`${home}/${entry.name}/${PLAN}`))
601    ) {
602      others.push(entry.name)
603    } else if (await $.fs.exists(`${home}/${entry.name}/paper`)) {
604      papersOnly.push(entry.name)
605    }
606  }
607  found = [...withLedger.sort(), ...others.sort(), ...papersOnly.sort()]
608
609  return found
610}
611
612/** Paths and projects already told once this session, so a note is not repeated. */
613const told = new Set<string>()
614
615/**
616 * The research project this session last worked in, wherever the session was started.
617 *
618 * A session opened in one folder edits files in another, so the project is read off the paths
619 * the tools touch: the nearest directory above a touched file that holds a ledger, pinned
620 * quotations, a plan or a manuscript folder.
621 */
622let project: string | undefined
623
624/** Set when the person named the project themselves; the tools' paths then stop moving it. */
625let isPinned = false
626
627// The session keeps both, so a reload of this module does not forget which project is open.
628const savedProject = atom({ plugin: 'repro', key: 'project' } as const, null)
629const savedPin = atom({ plugin: 'repro', key: 'isPinned' } as const, false)
630/** Whether the person hid the readout above the prompt with `/repro-hide`. Warnings still show. */
631const hidden = atom({ plugin: 'repro', key: 'isHidden' } as const, false)
632
633async function save($: EngineInterface) {
634  await update($, savedProject, () => project ?? null)
635  await update($, savedPin, () => isPinned)
636}
637
638/** What the checks last said, shown on the status line and given to the model with the gates. */
639let lastStatus = ''
640
641/**
642 * The same line, drawn in the band above the prompt. Kept in the session's state
643 * so a change redraws it: a `$.ui.status` line carried this plugin's name and a warning mark ahead
644 * of the text, and in a narrow terminal that left room for the project name and little else.
645 */
646const shownStatus = atom({ plugin: 'repro', key: 'statusLine' } as const, '')
647
648async function show($: EngineInterface) {
649  // The pinned line under the prompt carries a warning mark and this plugin's name, so it holds
650  // only what is wrong, and nothing at all when nothing is.
651  $.ui.status(warnings.length > 0 ? warnings.join(' · ') : undefined)
652  await update($, shownStatus, () => lastStatus)
653}
654
655/** Makes the project above `path` the active one, when there is one. */
656async function track($: EngineInterface, path: string) {
657  if (isPinned) {
658    return
659  }
660  const before = project
661  project = (await projectOf($, await absolute($, path))) ?? project
662  if (project !== before) {
663    await save($)
664  }
665}
666
667/**
668 * Names the working project: a path, part of the name of a folder beside the one the session
669 * started in, or its number in the list. `auto` hands it back to the paths the tools touch.
670 * Answers what it did, for the transcript.
671 */
672async function choose($: EngineInterface, wanted: string) {
673  if (wanted === 'auto') {
674    isPinned = false
675    await save($)
676
677    return 'Following the files this session touches.'
678  }
679  const cwd = await $.session.cwd()
680  let name = wanted
681  if (!/^[~/.]/.test(wanted)) {
682    const names = found.length > 0 ? found : await discover($)
683    const hits = /^\d+$/.test(wanted)
684      ? names.slice(Number(wanted) - 1, Number(wanted))
685      : names.includes(wanted)
686        ? [wanted]
687        : names.filter(one => one.toLowerCase().includes(wanted.toLowerCase()))
688    if (hits.length !== 1) {
689      return hits.length === 0
690        ? `No research project matches "${wanted}". /repro-status list shows them all.`
691        : `"${wanted}" matches ${hits.length} projects. Specify the name further:\n  ${hits.join('\n  ')}`
692    }
693    name = hits[0] as string
694  }
695  const path = /^[~/.]/.test(name) ? await absolute($, name) : `${parent(cwd)}/${name}`
696  if (!(await $.fs.exists(path))) {
697    return `No such folder: ${path}`
698  }
699  project = (await projectOf($, path)) ?? path
700  isPinned = true
701  await save($)
702
703  return `Working project set to ${project}`
704}
705
706async function refresh($: EngineInterface) {
707  lastStatus = project ? await status($, project, false) : ''
708  await show($)
709}
710
711export const register: Register = on => {
712  on('session.start', async ($, e, next) => {
713    await $.command.register({
714      name: 'repro-status',
715      description: "(reproducible-science) Instant status of a project's ledger, plans and quotations",
716      argumentHint: '[part of a project name | pick | list | auto]',
717    })
718    await $.command.register({
719      name: 'repro-hide',
720      description: '(reproducible-science) Hide the readout above the prompt',
721    })
722    await $.command.register({
723      name: 'repro-show',
724      description: '(reproducible-science) Show the readout above the prompt again',
725    })
726    await $.command.register({
727      name: 'repro-verify',
728      description: "(reproducible-science) Check every pinned quotation of the working project against its source",
729    })
730    project = (await read($, savedProject)) ?? undefined
731    isPinned = await read($, savedPin)
732    await $.tool.register({
733      name: 'set_project',
734      description:
735        'Declare which research project this session is working on, when it differs from the ' +
736        'folder the session started in. Give the project folder as an absolute path. The ' +
737        'record checks, the status line and the gates then follow that project.',
738      inputSchema: {
739        type: 'object',
740        properties: { path: { type: 'string', description: 'Absolute path of the project folder' } },
741        required: ['path'],
742      },
743    })
744    await track($, await $.session.cwd())
745    await refresh($)
746
747    return next(e)
748  })
749
750  on('tool.call', { tool: 'Read' }, async ($, e, next) => {
751    await track($, e.file_path)
752
753    return next(e)
754  })
755
756  on('turn.complete', async ($, e, next) => {
757    await refresh($)
758
759    return next(e)
760  })
761
762  on('prompt.compose', async ($, e, next) => {
763    const composed = await next(e)
764
765    return project
766      ? {
767          sections: [
768            ...composed.sections,
769            {
770              id: 'repro:gates',
771              text: `${GATES}\n\nState of this project's records as of the last turn: ${lastStatus}.`,
772              scope: 'session',
773            },
774          ],
775        }
776      : composed
777  })
778
779  for (const tool of ['Edit', 'Write'] as const) {
780    on('tool.call', { tool }, async ($, e, next) => {
781      const edited = await absolute($, e.file_path)
782      await track($, edited)
783
784      // The file as named, then where it lands: an editor writes through a symbolic link, and on a
785      // disk that ignores case `prereg.md` opens `PREREG.md`. The shared hook does the same.
786      for (const path of await candidates($, edited)) {
787        if (path.includes('/') && (await $.fs.exists(recordOf(path)))) {
788          return {
789            deny:
790              `${path} has a freeze record (${recordOf(path)}), and a frozen file never changes by ` +
791              `one byte. Record a note with \`prereg log\`, or a change to the plan as an ` +
792              `amendment with \`prereg amend\`, which is a file of its own. Ask the user before ` +
793              `doing either.`,
794          }
795        }
796
797        if (path.endsWith(`/${PLAN}`) && (await $.fs.exists(path)) && FROZEN.test(await $.fs.read(path))) {
798          return {
799            deny:
800              `${path} is a frozen registration, and a frozen plan is not edited in place. ` +
801              `Record a note with \`prereg log\`, or a change to the plan as an amendment with ` +
802              `\`prereg amend\`, which is a file of its own. Ask the user before doing either.`,
803          }
804        }
805      }
806
807      const ran = await next(e)
808      if (ran.deny !== undefined || !MANUSCRIPT.test(edited) || told.has(edited)) {
809        return ran
810      }
811      if (await above($, dirOf(edited), LEDGER)) {
812        return ran
813      }
814      told.add(edited)
815
816      return {
817        ...ran,
818        context: [
819          ...(ran.context ?? []),
820          `reproducible-science: ${edited} is a manuscript and no .results/ ledger exists at or above it, ` +
821            `so no number in it is bound to a run. Before reporting a result here, run ` +
822            `\`results init\`, seal the inputs, and bind each sentence with \`results claim\`. ` +
823            `If this file reports no results of this project, say so to the user and continue.`,
824        ],
825      }
826    })
827  }
828
829  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
830    const target = cdTarget(e.command)
831    if (target) {
832      await track($, target)
833    }
834    const ran = await next(e)
835    const cwd = target ? await absolute($, target) : await $.session.cwd()
836    const fetched = download(e.command)
837    if (ran.deny === undefined && !ran.isError && fetched && !told.has(fetched[1])) {
838      told.add(fetched[1])
839
840      return {
841        ...ran,
842        context: [
843          ...(ran.context ?? []),
844          `reproducible-science: ${fetched[1]} was downloaded from ${fetched[0]}. When this source is ` +
845            `pinned, write that address as \`url:\` under \`source:\` in its claims file, beside ` +
846            `its sha256 and its \`doi:\`, so \`citations fetch\` can retrieve the same bytes ` +
847            `for a reader. Record the address the file came from, not a landing page.`,
848        ],
849      }
850    }
851    if (ran.deny !== undefined || !project || told.has(cwd) || !runsAnAnalysis(e.command)) {
852      return ran
853    }
854    if (await above($, cwd, LEDGER)) {
855      return ran
856    }
857    told.add(cwd)
858
859    return {
860      ...ran,
861      context: [
862        ...(ran.context ?? []),
863        `reproducible-science: that command ran an analysis in a project with no .results/ ledger. If a ` +
864          `paper will report its output, \`results init\` and \`results seal\` the inputs before ` +
865          `the run that counts. If it was exploratory, no record is owed.`,
866      ],
867    }
868  })
869
870  on('tool.call', { tool: 'mcp__repro__set_project' }, async ($, e) => {
871    const said = await choose($, String(e.path ?? ''))
872    await refresh($)
873
874    return { result: `${said}\n${lastStatus}` }
875  })
876
877  // One dim row directly above the prompt, drawn by this mod. The hint line under the prompt
878  // takes a `tail`, and the terminal leaves the tail out where the row has no room beside its
879  // own mode labels, which on a session with several of them is always.
880  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
881    const line = await read($, shownStatus)
882    if (!line || e.props.hasSurvey || (await read($, hidden))) {
883      return next(e)
884    }
885    const { Box, Text } = $.ui.resolve(e)
886
887    // The engine draws its collapse mark, `[-]`, over the last columns of the band's first row.
888    // Unpadded, a line wrapping there lost the characters under it: `4 sealed, 0 claims` showed
889    // as `4 sealed,` then `claims`.
890    // One field per row, always: the project's name with the plans, then the runs, then the
891    // quotations, then the manifest's assertions where there is a manifest,
892    // then the re-runs of its commands where it declares any. Laid side by side they read differently at every window width.
893    const [name, first, ...rest] = line.split(' · ')
894    const fields = first === undefined ? [name ?? ''] : [`${name} · ${first}`, ...rest]
895
896    // A row with a next step still to take names the command that takes it.
897    const isNew = fields.length === NOTHING.length && NOTHING.every((state, at) => state.test(fields[at] ?? ''))
898    const hints = fields.map((field, at) =>
899      isNew ? (at === 0 ? 'repro init' : undefined) : HINTS.find(([state]) => state.test(field))?.[1],
900    )
901    // The hint follows its row directly. Set in a column, it sat as far right as the longest row,
902    // and a long project name pushed it off the edge of the window.
903    const rows = fields.map((field, at) => (hints[at] ? `${field}  →  ${hints[at]}` : field))
904
905    return h(
906      Box,
907      { paddingRight: 5, flexDirection: 'column' },
908      ...rows.map((row, at) => h(Text, { key: `field:${at}`, dimColor: true }, row)),
909    )
910  })
911
912  on('ui.render', { component: 'Pane', requestId: PICKER }, async ($, e) => {
913    const { Box, Button, Text } = $.ui.resolve(e)
914    const rows = await read($, windowRows)
915    const first = Math.min(await read($, top), lastTop(rows))
916    const shown = found.slice(first, first + rows)
917    const current = project?.replace(/^.*\//, '')
918    const start = shown.includes(current ?? '') ? current : shown[0]
919
920    return h(
921      Box,
922      { flexDirection: 'column' },
923      ...shown.map(name =>
924        h(Button, {
925          key: `${ROW}${name}`,
926          label: name,
927          plain: true,
928          dimColor: true,
929          ...(name === start ? { autoFocus: true } : {}),
930          // Closed first: the checks behind the status take seconds, and a pane that waits
931          // for them looks like a pick that did nothing.
932          onPress: async () => {
933            await $.ui.close({ id: PICKER })
934            await choose($, name)
935            await refresh($)
936          },
937        }),
938      ),
939      h(
940        Text,
941        { dimColor: true },
942        `${first + 1}–${Math.min(first + rows, found.length)} of ${found.length} · Enter to pick · Esc to close`,
943      ),
944    )
945  })
946
947  // The ring keeps its position in the pane, not its row: after the window slides, the ring is
948  // on the same line and that line shows the next project. So the window slides exactly when an
949  // arrow on the last line asks the ring to wrap to the first (or the reverse): the wrap is
950  // refused, the window moves by one, and the ring stays on its line, now showing the next
951  // project. The ring wraps for real only at the two ends of the whole list.
952  on('ui.focus', async ($, e, next) => {
953    const landed = e.element ?? (e as { key?: string }).key
954    if (e.requestId !== PICKER || !landed?.startsWith(ROW)) {
955      return next(e)
956    }
957    const rows = Math.min(await read($, windowRows), found.length)
958    const first = Math.min(await read($, top), lastTop(rows))
959    const line = found.indexOf(landed.slice(ROW.length)) - first
960
961    const isWrapDown = lastLine === rows - 1 && line === 0
962    const isWrapUp = lastLine === 0 && line === rows - 1
963    if (e.origin?.kind !== 'person' || rows < 2 || !(isWrapDown || isWrapUp)) {
964      lastLine = line
965
966      return next(e)
967    }
968    if (isWrapDown && first < lastTop(rows)) {
969      await update($, top, () => first + 1)
970    } else if (isWrapUp && first > 0) {
971      await update($, top, () => first - 1)
972    } else {
973      // An end of the whole list: go round to the other end.
974      await update($, top, () => (isWrapDown ? 0 : lastTop(rows)))
975      lastLine = isWrapDown ? 0 : rows - 1
976      void $.ui.focus({ requestId: PICKER, key: `${ROW}${found[isWrapDown ? 0 : found.length - 1]}` })
977    }
978
979    return { deny: 'the list moved to the next project' }
980  })
981
982  // A scroll in the picker means the tree did not fit the pane the layout granted. The window
983  // shrinks to the pane's real height, and the pane is held at its top.
984  on('ui.scroll', async ($, e, next) => {
985    if (e.requestId !== PICKER || e.origin.kind !== 'person') {
986      return next(e)
987    }
988    if (e.contentRows > e.bodyRows) {
989      await update($, windowRows, () => Math.max(2, e.bodyRows - 1))
990    }
991
992    return next({ ...e, offset: 0 })
993  })
994
995  on('command.run', { command: 'repro-status' }, async ($, e) => {
996    const wanted = (e.args ?? '').trim()
997    if (wanted === 'list') {
998      const names = await discover($)
999
1000      return {
1001        text:
1002          `${names.length} research projects. Set one with /repro-status <number or ` +
1003          `part of its name>:\n${names.map((name, at) => `  ${String(at + 1).padStart(2)}  ${name}`).join('\n')}`,
1004      }
1005    }
1006    if (wanted === 'pick' || (!wanted && !project)) {
1007      const names = await discover($)
1008      const here = names.indexOf(project?.replace(/^.*\//, '') ?? '')
1009      const rows = await read($, windowRows)
1010      await update($, top, () => Math.min(Math.max(0, here - 1), lastTop(rows)))
1011      lastLine = 0
1012      await $.ui.open({
1013        id: PICKER,
1014        title: 'Research projects',
1015        focus: true,
1016        closeOnEscape: true,
1017        holdToasts: true,
1018        rows: rows + 1,
1019      })
1020
1021      return {
1022        text:
1023          `${names.length} research projects. ↑ and ↓ to move, Enter to pick, Esc to close. ` +
1024          `Or run /repro-status <part of a name>.`,
1025      }
1026    }
1027    const said = wanted ? [await choose($, wanted)] : []
1028    if (!project || said.some(line => !line.startsWith('Working project') && !line.startsWith('Following'))) {
1029      return { text: said.join('\n') }
1030    }
1031    const lines = [...said, await status($, project, true)]
1032    lastStatus = lines[said.length] ?? lastStatus
1033    await show($)
1034
1035    return { text: lines.join('\n') }
1036  })
1037
1038  // The readout is drawn every turn, and in a short window it takes rows the person may want back.
1039  // A warning is not part of it: that line stays, because it only appears when something is wrong.
1040  on('command.run', { command: 'repro-hide' }, async $ => {
1041    await update($, hidden, () => true)
1042
1043    return { text: 'Readout hidden. /repro-show brings it back.' }
1044  })
1045
1046  on('command.run', { command: 'repro-show' }, async $ => {
1047    await update($, hidden, () => false)
1048
1049    return { text: 'Readout shown.' }
1050  })
1051
1052  // The full quotation check. It reads every pinned source, which takes minutes on a large
1053  // project, so it has its own command and `/repro-status` stays instant.
1054  on('command.run', { command: 'repro-verify' }, async $ => {
1055    if (!project) {
1056      return { text: 'No working project. Run /repro-status <part of a name> first.' }
1057    }
1058    const checked: string[] = []
1059    const folders = await claimsFolders($, project)
1060    const count = (text: string | undefined) => Number((text ?? '0').replace(/,/g, ''))
1061    let pinned = 0
1062    let found = 0
1063    let notFound = 0
1064    for (const folder of folders) {
1065      const ran = await $.process.run(['citations', 'verify', '--claims', folder], {
1066        cwd: project,
1067        timeoutMs: 300_000,
1068      })
1069      checked.push(
1070        folder,
1071        ...ran.stdout.split('\n').filter(line => /^\s+(found|not found|unchecked|ambiguous)\s/.test(line)),
1072      )
1073      pinned += count(/^([\d,]+) quotes?$/m.exec(ran.stdout)?.[1])
1074      found += count(/^\s+found\s+([\d,]+)/m.exec(ran.stdout)?.[1])
1075      notFound += count(/^\s+not found\s+([\d,]+)/m.exec(ran.stdout)?.[1])
1076    }
1077    if (pinned > 0) {
1078      const root = project
1079      const line = `${found.toLocaleString('en-US')}/${pinned.toLocaleString('en-US')} quotes found`
1080      await update($, quotations, saved => ({ ...saved, [root]: line }))
1081      await update($, quotationsNotFound, saved => ({ ...saved, [root]: notFound }))
1082    }
1083    if (folders.length === 0) {
1084      checked.push('no claims folder, so no quotations are pinned')
1085    }
1086    const lines = [await status($, project, true), ...checked]
1087    lastStatus = lines[0] ?? lastStatus
1088    await show($)
1089
1090    return { text: lines.join('\n') }
1091  })
1092}
1093
types/index.d.ts 25 lines
1/** The research project a session is working in: its folder, or null before one is touched. */
2export type WorkingProject = string | null
3
4declare module 'claude-code' {
5  interface PluginState {
6    'repro': {
7      project: WorkingProject
8      /** Whether the person named that project, so the tools' paths no longer move it. */
9      isPinned: boolean
10      /** Whether the person hid the readout above the prompt. */
11      isHidden: boolean
12      /** The index of the first project the picker's window shows. */
13      top: number
14      /** How many projects the picker's window shows. */
15      windowRows: number
16      /** The readout drawn in the band above the prompt. */
17      statusLine: string
18      /** The last full quotation check of each project, as `found/pinned found`, by folder. */
19      quotations: Record<string, string>
20      /** How many quotations that check reported as not found, by folder. */
21      quotationsNotFound: Record<string, number>
22    }
23  }
24}
25