SLOPSHOPPER

Temper

Claude cannot write code before you approve the intent. Gated plan, TDD, review and check for AI written code, with a phase bar in Claude Code.

panebandspinnerrowsguardtoast
★ 18v9.7.4MITupdated 2026-10-21galando/temper
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · temper
│ ┃ temper ✕ › fix the failing auth test and add an audit log call │ ┃ ◈ Temper │ ┃ No Temper run is active yet. A run started ⏺ Read(src/auth.ts) │ ┃ with /temper:temper and a feature ⎿ Read 6 lines │ ┃ description shows here. ⏺ 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 │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · temper
◈ Temper No Temper run is active yet. A run started with /temper:temper and a feature description shows here.
README

Temper

Claude cannot write code before you approve the intent.

Temper is an intent gated workflow for code that AI writes. A small CLI computes each gate verdict. The model never decides a verdict. With Claude Code 2.1.287 or later, a mod refuses writes outside the current stage (the mod).

Plugin directory Version Claude Code License: MIT

https://github.com/user-attachments/assets/ec84e98e-7c28-45f9-87c2-8df0b80e19b8

Website · Getting Started · Commands · The mod · Haiku Build · Releases

Install

/plugin marketplace add galando/temper
/plugin install temper

On Claude Code 2.1.275 or later, one line does both:

/plugin install temper --marketplace galando/temper

You can also open the Plugins page in Claude, choose Discover and search for "temper".

Your first /temper:temper "describe the feature" sets up the project. It adds the config, the .temper/ folder and a pre-commit hook. The hook blocks git commit while a gate is red.

The short form /temper is an interactive shortcut. It may not work on every surface. Claude Code 2.1.287 or later adds the stage bar and the refusals. Older versions run each stage as a prompt.

The problem

AI writes code fast, but it fails in predictable ways:

  • Happy paths without edge cases.
  • Features that nobody asked for.
  • Calls to methods that do not exist.
  • Correct code that nothing uses.

Most tools check that the code compiles. Temper checks that the code solves the right problem. It does this mechanically. It does not ask the model to grade itself.

How it works

One loop, with a human gate at each stage. You review the cheapest artifact first. The order is Intent, Plan, Build, Review, Check, then Done. You decide each gate in one question. A failed Review or Check goes back to Build when you choose so.

flowchart LR
  I["Intent<br/>you approve it"] --> P["Plan<br/>files it may touch"]
  P --> B["Build<br/>failing test first"]
  B --> R["Review<br/>fix or accept"]
  R --> C["Check<br/>run all checks"]
  C --> D(("Done<br/>commit allowed"))
  C -- "a check fails, you loop back" --> B
  • The intent gate comes first. You approve the problem and the success criteria before Claude explores or designs. A wrong intent costs words here. Later, it costs the whole plan.
  • Each gate is computed. scripts/temper is auditable bash with no network. It reads an evidence ledger and prints PASS or FAIL for each requirement. A red gate blocks git commit through a real hook. A person can override a gate at the gate question, and Temper records that and why. A confused model cannot.
  • The mod makes the stages real. It refuses writes outside the stage, --no-verify, and a step only you may take when you did not choose it in the gate question. It draws the stage bar and the run's pane; at the end the run prints its report, and writes it as a page when you ask. It is not a sandbox: Trust lists what it does not see, and the mod has the details.

https://github.com/user-attachments/assets/31a9f4dc-8860-41be-97ca-f03460630f2f

What the mod reads and writes

The mod makes no network, process or env call, starts no agent and writes no file itself. It sets no setting and runs no command.

  • Reads: .temper/view.json, the one file the CLI writes for it. To find the project it looks for that file in the session folder and in up to 11 folders above it. It also reads its own options, store and state, and the Claude Code version. When reviewerModel is set it reads the session's agent list (id and type only).
  • Configuration and environment it sets: none. It sets no environment variable and changes no setting, its own included. You set its options in /config: Temper UI mode (full, minimal or off) and Temper enforcement (on or off), and the others below. /temper:temper mode and /temper:temper enforcement only say what is set and where to change it.
  • Slash commands it runs: none. The bar has no button; you type /temper:temper to take a run up again.
  • Hooks, and what each changes:
  • tool.call reads the path of Write, Edit, MultiEdit and NotebookEdit and the text of Bash, and refuses some calls with a reason. Always: a write to the CLI's run files in .temper/, and a Bash word that expands to more words than it reads (a long brace list). During a /temper or /temper:fix run: --no-verify, a changed hooks path, and a write to the config or git's hooks. During a /temper run: a write outside the stage, a write to the mod's plugin data folder, a step only you may take, an unquoted glob in a Temper call that could spell such a step, and a Bash call its own check failed on. Any other call goes on, and its result comes back unchanged. After a question dialog it reads your answer from the result.
  • command.run handles only /temper:temper (and /temper). It answers status, timeline, help, report, mode, enforcement and pane itself. Of those, only pane changes something (it opens or closes the pane, in full mode) and report keeps the run report in its store; mode and enforcement only say what is set. Typed in your prompt box, any other word opens the pane in full mode, then goes on unchanged; every other command goes on unchanged.
  • session.start and classic.SessionStart find the project folder and load the run. Neither adds or changes a context, an instruction, a setting or another hook: each returns what Claude Code gave it.
  • prompt.compose adds one system prompt section, temper:phase, to each request: enforcement on or off, the stage, the run title, the passed criteria, the next step for Claude (from .temper/view.json), a line when the mod cannot read the run as it should, and one fixed line (answer a message at a gate; after a requested change, run the gate again and ask again).
  • turn.step sets the model and effort from phaseModels, and the review agent's model from reviewerModel; empty options change nothing.
  • attribution.text adds one Temper line to a pull request description during a run, when prAttribution is on.
  • turn.complete adds a one line status under an answer in full mode.
  • ui.render draws the bar, the pane, the spinner word, the prompt hint and one line above the question dialog, which stays as it is; ui.close notes a pane you closed, so it does not open again by itself.
  • What reading the run again changes: the session hooks, tool.call (after a Bash call or a question dialog), turn.complete and command.run read the run again. That changes only the mod's own state: the project folder, the bar's view and the mode in $.state, which other plugins can read; at Done the run report kept in its store; in full mode a toast for a stage change, and the pane opened for a run that started.
  • Keeps: your answers in the question dialogs and the run report, in its plugin store.

Outside your project folder, Temper reads its own global pack folder ~/.claude/packs (if you made one), the mod's plugin store, and the folders above the session folder where the mod looks for the project. It asks git for its hooks folder, which may be one your git config names, and reads no name or email from git: an accepted intent or an override records that the person decided it at the gate. It reads no key, login, transcript, settings or other Claude Code file. Setting up a project (/temper:init, or your first /temper:temper) points the repository's own core.hooksPath at Temper's commit hook, or, when that would stop a hook of yours, prints one line to add to it. Temper never opens a Claude Code settings file, the project's or your home folder's: the guardrails pack prints its hook entries for you to add yourself. The full list is in The mod.

Commands

Three you will actually type. /temper:temper runs and routes the rest.

CommandPurpose
/temper:temper "..."The whole pipeline, intent gate to commit
/temper:fix "..."Root cause, a failing test that is write protected, a minimal fix
/temper:intent "..."Capture an idea as a committed draft, build it later

/temper:temper also takes status, report, pr, mode and pane. A word such as approve or back only brings up the gate question, where you decide. See Commands.

Granular control. Each stage on its own: /temper:plan, /temper:design, /temper:build, /temper:review, /temper:check. Utilities: /temper:status, /temper:pack, /temper:init.

Autonomy (opt in) runs stages after the plan gate unattended. It never pushes, never merges to a remote and never makes the feature commit; its only commits are Build's local task commits and merges. Packs: docs/packs.md. CI: examples/workflow/README.md.

Documentation, contributing and license

Source 24 files
hooks/temper-mod/register.tsx 602 lines
1import type { CommandRunResult, EngineInterface, PluginOptions, Register } from 'claude-code'
2
3import { FIX_RUN, VIEW_PATH, composeText, idleSnapshot, keepDecision, keptReport, live, loadSnapshot, publish, reportText, settingsFrom, spendDecision, statusText, timelineText, viewOf, writeReport } from './adapter'
4import type { Io, Snapshot } from './adapter'
5import { pluginCliFrom } from './core/cli'
6import { HELP, parseArgs } from './core/commands'
7import type { Parsed } from './core/commands'
8import { parsePhaseModel, parsePhaseModels, versionAtLeast } from './core/config'
9import type { UiMode } from './core/config'
10import { answersIn } from './core/answers'
11import { evaluate } from './core/rules'
12import { readShell } from './core/shell'
13import type { RuleContext } from './core/rules'
14import { SECTION_ID } from './core/section'
15import { stageToast, turnLine } from './core/view'
16import type { View } from './core/view'
17import { hintProps } from './ui/hint'
18import { renderBand } from './ui/band'
19import { PANE_ID, renderPane } from './ui/pane'
20import { renderQuestion } from './ui/question'
21import { spinnerProps } from './ui/spinner'
22
23type Api = EngineInterface
24
25// Module state. A hot reload runs register() again and session.start fires again, so
26// nothing here has to outlive a reload.
27let options: PluginOptions = {}
28let current: Promise<Snapshot> | null = null
29let root = ''
30let paneOpen = false
31// The person closed the pane by hand (its close mark, or /temper:temper pane): the mod does not open it for them again
32// in this session; /temper:temper pane does.
33let paneShut = false
34// The last stage announced, so a toast goes out once per stage change and never at load.
35let lastStage: string | null | undefined
36
37// One toast. Every toast of the mod goes through here.
38function showToast($: Api, text: string): void {
39  $.ui.toast(text)
40}
41
42// The mod writes no file. The report it makes at Done is kept in the plugin store, under the full path it stands for
43// (`vf:<path>`). Past VF_MAX kept texts the oldest is dropped, so the store (4 MiB for every project on the machine)
44// never fills up.
45const VF = 'vf:'
46const VF_LIST = 'vflist'
47const VF_MAX = 40
48
49async function keepText($: Api, full: string, text: string): Promise<void> {
50  await $.store.set(VF + full, text)
51  const raw = await $.store.get(VF_LIST)
52  const list = (Array.isArray(raw) ? raw.filter((p): p is string => typeof p === 'string') : []).filter(p => p !== full)
53  list.push(full)
54  while (list.length > VF_MAX) await $.store.delete(VF + (list.shift() as string))
55  await $.store.set(VF_LIST, list)
56}
57
58// `$` is spelled only in this file, at each call site, so the adapter and the pure core
59// stay free of it.
60function makeIo($: Api): Io {
61  // A relative path means the project the session started in, even after Claude ran `cd` in a Bash
62  // call: without this the files of the run are not found and the band goes away.
63  const abs = (path: string): string => (root && !path.startsWith('/') ? `${root.replace(/\/$/, '')}/${path}` : path)
64  return {
65    read: path => $.fs.read(abs(path)).then(t => (typeof t === 'string' ? t : null)),
66    keep: (name, text) => keepText($, abs(`.temper/${name}`), text),
67    kept: async name => {
68      const text = await $.store.get(VF + abs(`.temper/${name}`))
69      return typeof text === 'string' ? text : null
70    },
71    storeGet: key => $.store.get(key),
72    storeSet: (key, value) => $.store.set(key, value),
73    storeDelete: key => $.store.delete(key),
74    version: () => $.session.version().then(v => v.version),
75    setRun: async run => {
76      await $.state.set({ plugin: 'temper', key: 'run' } as const, run)
77    },
78    setMode: async mode => {
79      await $.state.set({ plugin: 'temper', key: 'mode' } as const, mode)
80    },
81    cli: pluginCli(),
82  }
83}
84// The last snapshot that held a run. Enforcement is sticky: once the mod has seen a run in progress, a view.json that
85// turns missing, unreadable or corrupt (chmod 000, a delete, a git clean) does not end it.
86// The last known state keeps applying until the file reads again, the person turns enforcement off, or the mod reloads.
87let lastRun: Snapshot | null = null
88
89const LOST_STATE =
90  'Temper state: .temper/view.json is missing or unreadable. The last known state still applies. Run temper next, which writes it again, or turn Temper enforcement off in /config.'
91
92// The last known run, when it was in progress; null when it was over (Done) or never seen.
93function heldRun(): Snapshot | null {
94  const r = lastRun
95  if (r === null || r.inert || r.failOpen || r.run === null || r.run.stage === 'commit') return null
96  // The settings are the live ones (the person may have turned enforcement off since); the run is the last known.
97  return { ...r, ...settingsFrom(options), line: LOST_STATE }
98}
99
100// Whether the folder the mod reads the run from has been seen to hold one (see load).
101let rootVerified = false
102// Where the session began (session.start); used to look for the CLI's root again.
103let sessionCwd = ''
104
105// A failed load never throws. With no run it is a no-run snapshot (nothing enforced); a run that was in progress
106// stays enforced (see lastRun).
107async function load($: Api): Promise<Snapshot> {
108  // After a hot reload no session.start has run yet: the project root comes back from `$.state`.
109  if (!root) root = await rememberedRoot($)
110  let snap: Snapshot | null = await loadSnapshot(makeIo($), options).catch(() => null)
111  if (snap !== null && snap.slug === null && !snap.inert && lastRun === null && !rootVerified && sessionCwd) {
112    // No run in the folder the mod chose at the first session start. A run the CLI starts later may live in a folder
113    // above it (the CLI root): look again before deciding there is none.
114    const found = await locateRoot($, sessionCwd)
115    if (found !== null && found !== root) {
116      root = found
117      await $.state.set({ plugin: 'temper', key: 'root' } as const, root).catch(() => undefined)
118      snap = await loadSnapshot(makeIo($), options).catch(() => null)
119    }
120  }
121  if (snap !== null && snap.slug !== null) {
122    lastRun = snap
123    rootVerified = true
124    return snap
125  }
126  const held = heldRun()
127  if (held !== null) {
128    lastRun = held
129    return held
130  }
131  lastRun = null
132  return snap ?? idleSnapshot(options, false)
133}
134
135// ---- The project root ------------------------------------------------------------------------
136// The folder of the project is fixed once. A session folder reported later (after Claude ran `cd` into
137// the plugin folder, or another repo, and a hot reload started the session there) never replaces it:
138// view.json and the report are always read and kept under the first root. `$.state` keeps it across a hot reload.
139
140async function rememberedRoot($: Api): Promise<string> {
141  const read = await $.state.get({ plugin: 'temper', key: 'root' } as const).catch(() => null)
142  return typeof read?.value === 'string' ? read.value : ''
143}
144
145// The nearest folder at or above `cwd` that holds .temper/view.json; null when none does.
146async function locateRoot($: Api, cwd: string): Promise<string | null> {
147  let dir = cwd.replace(/\/+$/, '')
148  for (let i = 0; i < 12 && dir !== ''; i++) {
149    if ((await $.fs.read(`${dir}/${VIEW_PATH}`).catch(() => undefined)) !== undefined) return dir
150    dir = dir.slice(0, Math.max(0, dir.lastIndexOf('/')))
151  }
152  return null
153}
154
155// Session start: keep the remembered root; the first time, find it and remember it.
156async function settleRoot($: Api, cwd: string | undefined): Promise<void> {
157  const known = await rememberedRoot($)
158  if (known) {
159    root = known
160    return
161  }
162  if (!cwd) return
163  // An inert mod (a version below the minimum) touches no Temper file, not even to find the root.
164  const version = await $.session.version().then(v => v.version).catch(() => undefined)
165  if (!versionAtLeast(version)) {
166    root = cwd
167    return
168  }
169  const found = await locateRoot($, cwd)
170  root = found ?? cwd
171  rootVerified = found !== null
172  // No run was found: the root is the session folder for now, and a run that starts above it is looked for later (see load).
173  sessionCwd = found === null ? cwd : ''
174  await $.state.set({ plugin: 'temper', key: 'root' } as const, root).catch(() => undefined)
175}
176
177function ensure($: Api): Promise<Snapshot> {
178  current ??= load($)
179  return current
180}
181
182// One toast per stage change, in full mode, never at the first load.
183function announce($: Api, snap: Snapshot): void {
184  const stage = snap.run?.stage ?? null
185  if (lastStage !== undefined && stage !== lastStage && stage !== null && !snap.inert) {
186    const toast = snap.mode === 'full' ? stageToast(stage) : null
187    if (toast) showToast($, toast)
188  }
189  lastStage = stage
190}
191
192// The run reached Done since the stage last announced: its report is kept, so /temper:temper report shows it after the
193// run state is gone.
194function reachedDone(snap: Snapshot): boolean {
195  return snap.run?.stage === 'commit' && !snap.inert && snap.runCommand !== 'fix' && lastStage !== undefined && lastStage !== null && lastStage !== 'commit'
196}
197
198// Takes a snapshot as the current one. A run it holds is the last known run too.
199function adopt($: Api, snap: Snapshot): Snapshot {
200  current = Promise.resolve(snap)
201  if (snap.slug !== null) lastRun = snap
202  if (reachedDone(snap)) void writeReport(makeIo($), snap).catch(() => undefined)
203  announce($, snap)
204  return snap
205}
206
207async function refresh($: Api): Promise<Snapshot> {
208  current = load($)
209  const snap = await current
210  await publish(makeIo($), snap).catch(() => undefined)
211  if (reachedDone(snap)) await writeReport(makeIo($), snap).catch(() => undefined)
212  const started = startedHere(snap)
213  announce($, snap)
214  if (started) await autoOpenPane($, snap).catch(() => undefined)
215  return snap
216}
217
218// A run the mod first sees after it saw none in this session (a run started with /temper:temper,
219// a door or `temper state init`): the pane opens for it as it does at a session start.
220function startedHere(snap: Snapshot): boolean {
221  return lastStage === null && !snap.inert && snap.run !== null && snap.run.stage !== 'commit'
222}
223
224// The session's directory, to make absolute tool paths project relative: the cwd the
225// session reported, else where `.` resolves.
226async function rootOf($: Api): Promise<string> {
227  if (root) return root
228  const stat = await $.fs.stat('.', { resolve: true }).catch(() => undefined)
229  return stat?.realPath ?? ''
230}
231
232// What the drawing hooks read: the view and the live mode, from `$.state`, so a write
233// to either redraws the sites that read it. Null before the mod has published.
234async function readUi($: Api): Promise<{ view: View; mode: UiMode } | null> {
235  const run = await $.state.get({ plugin: 'temper', key: 'run' } as const)
236  const mode = await $.state.get({ plugin: 'temper', key: 'mode' } as const)
237  if (!run.value || !mode.value) return null
238  return { view: run.value.view, mode: mode.value }
239}
240
241// ---- Pane ------------------------------------------------------------------------
242
243async function openPane($: Api): Promise<boolean> {
244  const placed = await $.ui.open({ id: PANE_ID, title: 'Temper' })
245  paneOpen = placed.isPlaced
246  live.paneOpen = placed.isPlaced
247  return placed.isPlaced
248}
249
250async function closePane($: Api): Promise<void> {
251  await $.ui.close({ id: PANE_ID })
252  paneOpen = false
253  live.paneOpen = false
254}
255
256async function togglePane($: Api): Promise<string> {
257  if (paneOpen) {
258    paneShut = true
259    await closePane($)
260    return 'The Temper pane is closed.'
261  }
262  paneShut = false
263  return (await openPane($)) ? 'The Temper pane is open.' : 'The Temper pane needs a wider terminal.'
264}
265
266// Opens the pane where the surface places it now. Where it would only wait undrawn, it is
267// closed again so it does not pop up later.
268async function placeOrDrop($: Api): Promise<void> {
269  const placed = await $.ui.open({ id: PANE_ID, title: 'Temper' })
270  if (placed.isPlaced) {
271    paneOpen = true
272    live.paneOpen = true
273  } else {
274    await $.ui.close({ id: PANE_ID })
275    paneOpen = false
276    live.paneOpen = false
277  }
278}
279
280// Opened unasked, in full mode, for a run in progress: at a session start, and when a run
281// starts later in the session (see refresh). The engine places an unasked pane only on a
282// wide terminal.
283async function autoOpenPane($: Api, snap: Snapshot): Promise<void> {
284  if (paneOpen || paneShut || snap.mode !== 'full' || snap.run === null || snap.run.stage === 'commit') return
285  await placeOrDrop($)
286}
287
288// The person's own /temper:temper with a run word (a feature description, a decision word,
289// or nothing), in full mode: the pane opens as their command, which the engine places at any
290// width. A run they start has no state yet; the pane draws it once the CLI writes it.
291async function openForPerson($: Api): Promise<void> {
292  const snap = await ensure($)
293  if (paneOpen || paneShut || snap.inert || snap.mode !== 'full' || snap.runCommand === 'fix') return
294  await placeOrDrop($)
295}
296// ---- The person's answers ---------------------------------------------------------------
297
298// Claude asks every gate in Claude Code's own question dialog, exactly as `temper next --json` gives it (ADR 0013). The
299// person's answer is read from the dialog's result, after the call ran, matched exactly against the question view.json
300// holds (core/answers.ts), and kept as a decision stamped with the CLI's run and step. Claude then carries the answer
301// out in the same turn; nothing is sent to Claude here. Only the result counts: it is what the dialog returned after the
302// person chose.
303async function recordAnswers($: Api, result: unknown): Promise<void> {
304  const snap = await refresh($)
305  if (snap.inert || snap.run === null || snap.view === null) return
306  const io = makeIo($)
307  const stage = snap.run.stage
308  let kept = false
309  for (const a of answersIn(result, snap.view)) {
310    if (a.kind === 'gate') await keepDecision(io, snap.at, a.stage || stage, { kind: 'gate', label: a.option.label, move: a.option.move ?? '', calls: a.option.calls, steps: a.option.steps, reason: a.reason, ask: a.ask })
311    else if (a.kind === 'restart') await keepDecision(io, snap.at, stage, { kind: 'restart', calls: a.option.calls, reason: '' })
312    else await keepDecision(io, snap.at, stage, { kind: 'drift', path: a.path, choice: a.choice, reason: a.reason })
313    kept = true
314  }
315  if (kept) adopt($, await refresh($))
316}
317
318// ---- The guard ---------------------------------------------------------------------------
319
320export const MOD_CLI = pluginCliFrom((import.meta as { url?: string }).url)
321
322function pluginCli(): string {
323  return MOD_CLI
324}
325
326function ruleContext(snap: Snapshot, rootDir: string): RuleContext {
327  return { run: snap.run, allowed: snap.allowed, restart: snap.restart, drift: snap.drift, root: rootDir, cli: pluginCli(), fixRun: snap.runCommand === 'fix' }
328}
329
330const GUARD_ERROR =
331  'Temper: the guard hit an error while it checked this command, and a run is active. Temper does not pass a command it could not check. ' +
332  'Next: run the command again. If it keeps failing, ask the user (the user can turn Temper enforcement off in /config).'
333
334// A guard that threw: Bash is refused while a run is active (a command the guard cannot read is the one to refuse),
335// every other tool passes (the mod must not make Temper worse than without it).
336function failedGuard(tool: string): Guarded {
337  const r = lastRun
338  const active = r !== null && !r.inert && r.enforcement !== 'off' && !r.failOpen && r.run !== null
339  return { deny: tool === 'Bash' && active ? GUARD_ERROR : null }
340}
341
342// The one place this module denies. A decision the call spends (an Allow once answer) is spent here, when the call is
343// let through.
344// `trivialExit`: the call is a `state clear` of a run that never left Intent (view.json's trivial_exit). Once it ran, the
345// run it cleared is not held any more (see lastRun), so the work that follows is not judged against a run that is gone.
346type Guarded = { deny: string | null; trivialExit?: boolean }
347
348async function guard($: Api, tool: string, input: Record<string, unknown>): Promise<Guarded> {
349  // A Bash call may run the CLI, so it is judged on the run as the files say now; a write on the run last read.
350  const snap = tool === 'Bash' ? await refresh($) : await ensure($)
351  // Fail open: when the mod cannot tell where the run is, it never blocks Temper.
352  if (snap.inert || snap.enforcement === 'off' || snap.failOpen) return { deny: null }
353  const command = typeof input.command === 'string' ? input.command : ''
354  // A `state clear` at Intent (the TRIVIAL exit), as view.json says now.
355  const clearable = tool === 'Bash' && snap.run?.trivialExit === true && readShell(command).calls.some(w => w[0] === 'state' && w[1] === 'clear')
356  const rootDir = await rootOf($)
357  const r = evaluate(ruleContext(snap, rootDir), { tool, input })
358  if ('deny' in r) return { deny: r.deny }
359  if (r.use !== undefined) {
360    await spendDecision(makeIo($), r.use)
361    adopt($, await refresh($))
362  }
363  return { deny: null, ...(clearable ? { trivialExit: true } : {}) }
364}
365
366// ---- /temper:temper -------------------------------------------------------------------------
367
368// Where the person changes the two settings: Claude Code's /config, the plugin's own options. The mod never writes them.
369const MODE_WHERE = 'Change it in /config: Temper UI mode (full, minimal or off).'
370const ENFORCEMENT_WHERE = 'Change it in /config: Temper enforcement (on or off).'
371
372async function handleTemper($: Api, parsed: Parsed): Promise<CommandRunResult | null> {
373  const snap = await ensure($)
374  if (snap.inert) return null
375  switch (parsed.word) {
376    case 'help':
377      return { text: HELP }
378    case 'status':
379      return { text: statusText(await refresh($)) }
380    case 'timeline':
381      return { text: timelineText(await refresh($)) }
382    case 'report': {
383      const fresh = await refresh($)
384      if (fresh.slug === null || fresh.runCommand === 'fix') {
385        const kept = await keptReport(makeIo($))
386        return { text: kept === null ? 'No run is active. There is no report to show.' : `No run is active. The last report kept for this project:\n\n${kept}` }
387      }
388      // A run held from memory (its state file is gone) is shown but not kept.
389      if (fresh.line === LOST_STATE) return { text: `${LOST_STATE}\n\n${reportText(fresh)}` }
390      return { text: await writeReport(makeIo($), fresh) }
391    }
392    // The mod changes no setting: the two words say what is set and where the person changes it.
393    case 'mode':
394      return { text: `Temper mode: ${snap.mode}. ${MODE_WHERE}` }
395    case 'enforcement':
396      return { text: `Temper enforcement: ${snap.enforcement}. ${ENFORCEMENT_WHERE}` }
397    case 'pane':
398      if (snap.mode !== 'full') return { text: `The pane shows in full mode only. ${MODE_WHERE}` }
399      return { text: await togglePane($) }
400  }
401}
402
403const REVIEWERS = ['temper-review', 'temper:temper-review']
404
405// Whether each subagent seen at turn.step is the Temper review agent, by its id. The agent list is read once per id.
406const reviewerIds = new Map<string, boolean>()
407
408async function isReviewer($: Api, agentId: string): Promise<boolean> {
409  const known = reviewerIds.get(agentId)
410  if (known !== undefined) return known
411  const agents = await $.agent.list()
412  const found = agents.find(a => a.id === agentId)
413  if (found === undefined) return false
414  const yes = REVIEWERS.includes(found.type)
415  reviewerIds.set(agentId, yes)
416  return yes
417}
418
419// The model and effort a step runs with: on the main loop from the phaseModels option (keyed by stage), in the Temper
420// review agent from the reviewerModel option. Null leaves the step exactly as the engine built it.
421async function phasePick($: Api, agentId: string | undefined): Promise<{ model?: string; effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' } | null> {
422  if (agentId !== undefined) {
423    const model = typeof options.reviewerModel === 'string' ? options.reviewerModel.trim() : ''
424    return model && (await isReviewer($, agentId)) ? { model } : null
425  }
426  const raw = options.phaseModels
427  if (typeof raw !== 'string' || raw.trim() === '') return null
428  const snap = await ensure($)
429  if (snap.inert || snap.run === null || snap.run.stage === 'commit') return null
430  const pick = parsePhaseModel(parsePhaseModels(raw)[snap.run.stage])
431  return pick.model || pick.effort ? pick : null
432}
433
434// Wiring only. Every hook fails open: an exception passes the call through, except the detected violation, which is the
435// one place this module denies.
436export const register: Register = (on, opts) => {
437  options = opts
438  current = null
439  root = ''
440  lastRun = null
441  rootVerified = false
442  sessionCwd = ''
443  paneOpen = false
444  paneShut = false
445  lastStage = undefined
446  live.paneOpen = undefined
447  reviewerIds.clear()
448
449  on('session.start', async ($, e, next) => {
450    await settleRoot($, e.cwd)
451    current = null
452    await refresh($)
453      .then(snap => autoOpenPane($, snap))
454      .catch(() => undefined)
455    return next(e)
456  })
457
458  on('classic.SessionStart', async ($, e, next) => {
459    await settleRoot($, e.cwd)
460    await refresh($).catch(() => undefined)
461    return next(e)
462  })
463
464  // Only the words the mod answers are handled here; anything else (a feature description, a decision word, or nothing)
465  // goes on to the prompt based command unchanged.
466  on('command.run', async ($, e, next) => {
467    if (e.command !== 'temper' && e.command !== 'temper:temper') return next(e)
468    const parsed = parseArgs(e.args)
469    if (parsed === null) {
470      // The person's own run word, from the prompt box, opens the pane in full mode; any other origin opens nothing.
471      if (e.origin?.kind === 'composer') await openForPerson($).catch(() => undefined)
472      return next(e)
473    }
474    const out = await handleTemper($, parsed).catch(() => null)
475    return out ?? next(e)
476  })
477
478  // One Temper line on a generated pull request description, while a run is on and the prAttribution option is on.
479  on('attribution.text', { kind: 'pr' }, async ($, e, next) => {
480    const result = await next(e)
481    try {
482      const snap = await ensure($)
483      if (snap.inert || snap.prAttribution !== 'on' || snap.slug === null) return result
484      return { text: `${result.text}\n\nMade with Temper. The phases have gates. /temper:temper report shows the report.` }
485    } catch {
486      return result
487    }
488  })
489
490  // Subagent calls arrive here too (e.agentId names the loop); they are held to the same rules as the main loop.
491  on('tool.call', async ($, e, next) => {
492    const g = await guard($, e.tool, { ...e }).catch(() => failedGuard(e.tool))
493    if (g.deny !== null) return { deny: g.deny }
494    let result
495    try {
496      result = await next(e)
497    } finally {
498      // After the TRIVIAL exit ran (or failed): the cleared run is no longer held, and the run is read again. When the
499      // clear did not take effect, build-state.json is still there and the run reads back as it was.
500      if (g.trivialExit) {
501        lastRun = null
502        await refresh($).catch(() => undefined)
503      }
504    }
505    const errored = (result as { isError?: boolean }).isError === true
506    // A command may have moved the run (the CLI), and an answer is a decision: read the run again.
507    if (e.tool === 'AskUserQuestion' && !errored) await recordAnswers($, result).catch(() => undefined)
508    else if (e.tool === 'Bash') await refresh($).catch(() => undefined)
509    return result
510  }).catch(($, e, next) => {
511    // The engine skips a hook that throws or outruns its budget, and the tool would run unguarded. In its place: what the
512    // call already settled to, else the rule of a guard that could not check (Bash refused while a run is active, every
513    // other tool passes). No `$` call here: a re-entered handler may not make one.
514    if (next.called) return next(e)
515    const g = failedGuard(e.tool)
516    return g.deny !== null ? { deny: g.deny } : next(e)
517  })
518
519  // One session scope section, last, rebuilt from the cached state on every request, so it survives /compact by
520  // construction. Absent when the mod is inert: with no marker line the skills announce that enforcement is off here.
521  on('prompt.compose', async ($, e, next) => {
522    const result = await next(e)
523    try {
524      const snap = await ensure($)
525      if (snap.inert) return result
526      const others = result.sections.filter(s => s.id !== SECTION_ID)
527      return { sections: [...others, { id: SECTION_ID, text: composeText(snap), scope: 'session' as const }] }
528    } catch {
529      return result
530    }
531  })
532
533  // The bar: the stage timeline, and in full mode the status and details of the stage. It has no button. Off draws
534  // nothing; a survey holding the band is left alone.
535  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
536    if (e.props.hasSurvey) return next(e)
537    const ui = await readUi($).catch(() => null)
538    if (ui === null) return next(e)
539    const band = renderBand($.ui.resolve(e), ui.view, ui.mode, e.props.bodyColumns)
540    return band ?? next(e)
541  })
542
543  // A pane closed by its own mark: forget it, so the next toggle opens it again. Closed by the
544  // person, it is not opened for them again in this session.
545  on('ui.close', async ($, e, next) => {
546    if (e.id === PANE_ID) {
547      paneOpen = false
548      live.paneOpen = false
549      if (e.origin?.kind === 'person') paneShut = true
550    }
551    return next(e)
552  })
553
554  on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e, next) => {
555    const ui = await readUi($).catch(() => null)
556    if (ui === null || ui.mode !== 'full') return next(e)
557    return renderPane($.ui.resolve(e), ui.view, e.props.placement === 'inline')
558  })
559
560  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
561    const ui = await readUi($).catch(() => null)
562    const props = ui !== null && ui.mode === 'full' ? spinnerProps(e.props, ui.view) : null
563    return props === null ? next(e) : next({ ...e, props })
564  })
565
566  // The terminal draws a dim tail after the engine's hint line; other surfaces pass.
567  on('ui.render', { component: 'PromptHint' }, async ($, e, next) => {
568    const ui = await readUi($).catch(() => null)
569    const props = ui !== null && ui.mode === 'full' ? hintProps(e.props, ui.view, e.surface) : null
570    return props === null ? next(e) : next({ ...e, props })
571  })
572
573  // One Temper line above the engine's dialog, which stays exactly once in the tree.
574  on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {
575    const engine = await next(e)
576    const ui = await readUi($).catch(() => null)
577    if (ui === null || ui.mode !== 'full') return engine
578    return renderQuestion($.ui.resolve(e), ui.view, engine) ?? engine
579  })
580
581  // A line beneath the answer (stage, progress, next stage). Nothing is submitted.
582  on('turn.complete', async ($, e, next) => {
583    const result = await next(e)
584    try {
585      if (e.agentId !== undefined || e.reason !== 'answer') return result
586      const snap = await refresh($)
587      if (snap.inert || snap.mode !== 'full') return result
588      const line = turnLine(viewOf(snap))
589      return line ? { ...result, text: line } : result
590    } catch {
591      return result
592    }
593  })
594
595  // Optional: a model or effort per stage (userConfig phaseModels, "build=sonnet:high"), and a model for the steps of the
596  // Temper review agent (userConfig reviewerModel). Empty means the step is passed on exactly as the engine built it.
597  on('turn.step', async function* ($, e, next) {
598    const pick = await phasePick($, e.agentId).catch(() => null)
599    return yield* next(pick ? { ...e, ...pick } : e)
600  })
601}
602
hooks/temper-mod/adapter.ts 268 lines
1// Adapter helpers: everything that touches Claude Code's `$` (files, store, state, version), so register.tsx stays
2// wiring only. The pure rules live in core/.
3//
4// Where state lives (ADR 0013): the mod reads one file of the CLI's, `.temper/view.json`, and never writes it. The CLI
5// writes it after every command that may change the run. The person's decisions are the mod's own: kept in the plugin
6// store, one list per run, each stamped with the CLI's run id and step (core/decisions.ts).
7
8import type { PluginOptions } from 'claude-code'
9
10import { parseEnforcement, parseOnOff, parseUiMode, versionAtLeast } from './core/config'
11import type { UiMode } from './core/config'
12import { allowedCalls, currentAnswer, decisionsOf, describe, driftOf, parseBook, restartFor } from './core/decisions'
13import type { At, Decision, DriftState } from './core/decisions'
14import { renderReport } from './core/report'
15import type { RunFacts } from './core/rules'
16import { VIEW_VERSION, parseRunView } from './core/runview'
17import type { RunView } from './core/runview'
18import { sectionText } from './core/section'
19import { cliStage } from './core/stages'
20import { buildView } from './core/view'
21import type { View } from './core/view'
22import type { TemperRun } from '../../types'
23
24// Everything the adapter needs from Claude Code, as plain functions. register.tsx builds one from `$` (the module scan
25// only follows `$` inside the file that spells it), which also lets this file be tested without an engine.
26export type Io = {
27  // File text, or null when the file is missing or unreadable.
28  read: (path: string) => Promise<string | null>
29  // A text the mod keeps for the project in its store (the mod writes no file), and reads back.
30  keep: (name: string, text: string) => Promise<void>
31  kept: (name: string) => Promise<string | null>
32  storeGet: (key: string) => Promise<unknown>
33  storeSet: (key: string, value: unknown) => Promise<void>
34  storeDelete: (key: string) => Promise<void>
35  version: () => Promise<string | undefined>
36  setRun: (run: TemperRun) => Promise<void>
37  // The live mode, mirrored so a redraw sees a change at once.
38  setMode: (mode: UiMode) => Promise<void>
39  // Where the Temper script is (pluginCliFrom). Left out: the plain `scripts/temper`.
40  cli?: string
41}
42
43export type Snapshot = {
44  // True below the minimum Claude Code version or when it cannot be read: nothing acts.
45  inert: boolean
46  enforcement: 'on' | 'off'
47  mode: UiMode
48  prAttribution: 'on' | 'off'
49  // view.json is of a version this mod does not read, or names a stage it does not know: it blocks nothing.
50  failOpen: boolean
51  // The one line shown under the bar when the mod cannot read the run as it should; null when all is well.
52  line: string | null
53  // view.json as read; null with no run.
54  view: RunView | null
55  slug: string | null
56  // The command that started the run (`temper` or `fix`). A /temper:fix run is left to commands/fix.md.
57  runCommand: string | null
58  specDir: string
59  // The run as the guard reads it; null when no /temper run is active.
60  run: RunFacts | null
61  // The CLI's run id and step: where a new decision is stamped, and what an old one is read against.
62  at: At
63  // The person's decisions in this run, oldest first, and the latest gate answer at this step.
64  decisions: Decision[]
65  answer: Extract<Decision, { kind: 'gate' }> | null
66  // The calls the person's answers at this step map to, and those of the CLI's own action (see RuleContext).
67  allowed: string[]
68  restart: boolean
69  drift: DriftState
70}
71
72export const VIEW_PATH = '.temper/view.json'
73const REPORT = 'report.md'
74// The store keys of the decisions: one list per run (`dec:<run id>`), the runs kept (oldest first), and the ids a call
75// spent (`used:<id>`).
76const BOOK = 'dec:'
77const RUNS = 'decruns'
78const USED = 'used:'
79const MAX_RUNS = 40
80
81const str = (options: PluginOptions, key: string): string | undefined => {
82  const v = options[key]
83  return typeof v === 'string' ? v : undefined
84}
85
86// Whether the pane is open, as the mod last placed or closed it. The mode and enforcement come only from the options,
87// which the person changes in /config (the module reloads with the new options); the mod writes no setting.
88export const live: { paneOpen?: boolean } = {}
89
90export function settingsFrom(options: PluginOptions) {
91  return {
92    mode: parseUiMode(str(options, 'uiMode')),
93    enforcement: parseEnforcement(str(options, 'enforcement')),
94    prAttribution: parseOnOff(str(options, 'prAttribution'), 'on'),
95  }
96}
97
98export function idleSnapshot(options: PluginOptions, inert: boolean): Snapshot {
99  return {
100    inert,
101    ...settingsFrom(options),
102    failOpen: false,
103    line: null,
104    view: null,
105    slug: null,
106    runCommand: null,
107    specDir: '',
108    run: null,
109    at: { run: '', step: -1 },
110    decisions: [],
111    answer: null,
112    allowed: [],
113    restart: false,
114    drift: { added: [], allowOnce: [] },
115  }
116}
117
118const readText = (io: Io, path: string): Promise<string | null> => io.read(path).catch(() => null)
119
120async function usedIds(io: Io, book: readonly Decision[]): Promise<Set<string>> {
121  const used = new Set<string>()
122  for (const d of book) if (d.kind === 'drift' && d.choice === 'allow-once') if (await io.storeGet(USED + d.id).catch(() => undefined)) used.add(d.id)
123  return used
124}
125
126// The decisions kept for one run.
127export async function readBook(io: Io, run: string): Promise<Decision[]> {
128  return parseBook(await io.storeGet(BOOK + run).catch(() => undefined))
129}
130
131// Keeps one decision of the person, stamped with the CLI's run and step. The store holds the decisions of the last
132// MAX_RUNS runs on this machine; an older run's list is dropped.
133export async function keepDecision(io: Io, at: At, stage: string, body: Record<string, unknown> & { kind: Decision['kind'] }): Promise<Decision> {
134  const now = Date.now()
135  const d = { ...body, id: `${now.toString(36)}-${Math.random().toString(36).slice(2, 10)}`, run: at.run, step: at.step, stage, ts: now } as Decision
136  await io.storeSet(BOOK + at.run, [...(await readBook(io, at.run)), d])
137  const raw = await io.storeGet(RUNS).catch(() => undefined)
138  const runs = (Array.isArray(raw) ? raw.filter((r): r is string => typeof r === 'string') : []).filter(r => r !== at.run)
139  runs.push(at.run)
140  while (runs.length > MAX_RUNS) {
141    const old = runs.shift() as string
142    await io.storeDelete(BOOK + old).catch(() => undefined)
143  }
144  await io.storeSet(RUNS, runs)
145  return d
146}
147
148// An Allow once answer a write used: it counts once.
149export async function spendDecision(io: Io, id: string): Promise<void> {
150  await io.storeSet(USED + id, 1)
151}
152
153const CANNOT_TELL = 'Temper state: the mod cannot tell where the run is. It does not block anything until the state can be read.'
154const NEWER = `Temper state: .temper/view.json is not of version ${VIEW_VERSION}, the one this mod reads. It draws nothing and blocks nothing; update Temper.`
155
156export async function loadSnapshot(io: Io, options: PluginOptions): Promise<Snapshot> {
157  const version = await io.version().catch(() => undefined)
158  if (!versionAtLeast(version)) return idleSnapshot(options, true)
159  const idle = idleSnapshot(options, false)
160  const text = await readText(io, VIEW_PATH)
161  if (text === null) return idle
162  const rv = parseRunView(text)
163  if (rv === null) {
164    // A view of another version is no view: fail open. Text that is not a view at all is no run (the last run read is
165    // held, see register.tsx).
166    let other = false
167    try {
168      const v = (JSON.parse(text) as { version?: unknown }).version
169      other = v !== undefined && v !== VIEW_VERSION
170    } catch {
171      other = false
172    }
173    return other ? { ...idle, failOpen: true, line: NEWER } : idle
174  }
175  if (rv.run === null) return idle
176  // A /temper:fix run: the mod stands aside. commands/fix.md asks every gate in the conversation and the native commit
177  // hook gates the commit; the mod draws no bar, refuses nothing and records nothing for it.
178  if (rv.run.command === 'fix' || rv.guard?.fixRun === true) return { ...idle, view: rv, slug: rv.run.slug, specDir: rv.run.spec, runCommand: 'fix' }
179
180  const stage = cliStage(rv.run.stage)
181  const g = rv.guard
182  const at: At = { run: rv.run.id, step: rv.run.step }
183  const book = await readBook(io, at.run)
184  const used = await usedIds(io, book)
185  const run: RunFacts | null =
186    stage === null || g === null
187      ? null
188      : { stage, step: g.step, specDir: g.spec, planFiles: g.planFiles, groupedActive: g.grouped, trivialExit: g.trivialExit, prefix: g.prefix }
189  return {
190    ...idle,
191    failOpen: run === null,
192    line: run === null ? CANNOT_TELL : null,
193    view: rv,
194    slug: rv.run.slug,
195    runCommand: rv.run.command,
196    specDir: rv.run.spec,
197    run,
198    at,
199    decisions: decisionsOf(book, at.run),
200    answer: currentAnswer(book, at, rv.ask?.question.question ?? null),
201    allowed: [...allowedCalls(book, at), ...rv.next.calls, ...rv.next.steps],
202    restart: restartFor(book, at) !== null,
203    drift: driftOf(book, at.run, used),
204  }
205}
206
207// The report of the run as it stands, not kept.
208export function reportText(snap: Snapshot): string {
209  if (snap.view === null) return 'No Temper run is active. There is no report to show.'
210  return renderReport({ view: snap.view, decisions: snap.decisions, generatedAt: Date.now() })
211}
212
213// Keeps the report (the mod writes no file) and returns its text.
214export async function writeReport(io: Io, snap: Snapshot): Promise<string> {
215  const md = reportText(snap)
216  await io.keep(REPORT, md)
217  return md
218}
219
220// The report kept last in this project, for `/temper:temper report` with no run active. Null when there is none.
221export async function keptReport(io: Io): Promise<string | null> {
222  const text = await io.kept(REPORT).catch(() => null)
223  return text !== null && text.trim() !== '' ? text : null
224}
225
226// The line of the system prompt for a /temper:fix run, where the mod stands aside (see loadSnapshot).
227export const FIX_RUN = 'Phase: a /temper:fix run. The Temper bar and its guard stand aside for it: ask every gate in the conversation, as commands/fix.md says.'
228
229export function composeText(snap: Snapshot): string {
230  if (snap.runCommand === 'fix' && snap.run === null) {
231    return sectionText({ enforcement: snap.enforcement, view: null }).replace('Phase: none. No Temper run is active.', FIX_RUN)
232  }
233  return sectionText({ enforcement: snap.enforcement, view: snap.run === null ? null : viewOf(snap), line: snap.line })
234}
235
236const EMPTY: RunView = parseRunView(JSON.stringify({ version: VIEW_VERSION, run: null })) as RunView
237
238export const viewOf = (snap: Snapshot): View =>
239  buildView({ view: snap.view ?? EMPTY, decisions: snap.decisions, answer: snap.answer, enforcement: snap.enforcement, line: snap.line, paneOpen: live.paneOpen ?? false })
240
241// Mirrors the run into `$.state` for drawing and compaction.
242export async function publish(io: Io, snap: Snapshot): Promise<void> {
243  const v = viewOf(snap)
244  await io.setRun({ slug: snap.slug, stage: v.stage, title: v.title, summary: composeText(snap), view: v })
245  await io.setMode(snap.mode)
246}
247
248const iso = (ts: number): string => new Date(ts).toISOString()
249
250// `/temper:temper status`: the section text plus the counts a person wants at a glance.
251export function statusText(snap: Snapshot): string {
252  if (snap.runCommand === 'fix' && snap.run === null) return FIX_RUN
253  if (snap.run === null || snap.view === null) return snap.line ?? 'No Temper run is active. Start one with /temper:temper <feature description>.'
254  const lines = [composeText(snap)]
255  lines.push(`Mode: ${snap.mode}, enforcement: ${snap.enforcement}`)
256  const skipped = snap.view.skips.map(s => s.stage)
257  if (skipped.length > 0) lines.push(`Skipped: ${skipped.join(', ')}`)
258  for (const l of snap.view.loops) lines.push(`Loop ${l.from} to ${l.to}: ${l.iteration} of ${l.max}`)
259  if (snap.decisions.length > 0) lines.push(`Your decisions in this run: ${snap.decisions.length} (/temper:temper timeline lists them)`)
260  return lines.join('\n')
261}
262
263// `/temper:temper timeline`: the person's decisions in this run, oldest first.
264export function timelineText(snap: Snapshot): string {
265  if (snap.decisions.length === 0) return 'No decisions yet in this run.'
266  return snap.decisions.map(d => `${iso(d.ts)}  ${describe(d)}`).join('\n')
267}
268
hooks/temper-mod/core/cli.ts 20 lines
1// Where the Temper script is, for the texts that name it. Pure. The stage names are in stages.ts.
2
3export const CLI = 'scripts/temper'
4
5// Where the mod's module file sits in the plugin folder: the plugin folder is its module URL with this taken off.
6export const MOD_FILE = '/hooks/temper-mod/register.tsx'
7
8// The Temper script in the plugin folder as a full path, from the module URL of the mod (<plugin> followed by
9// MOD_FILE). The path is decoded FIRST and then checked, so an encoded space or quote (%20, %27) cannot reach a
10// command. Any odd location gives `scripts/temper`.
11export function pluginCliFrom(url: string | undefined): string {
12  try {
13    const here = decodeURIComponent(new URL(url ?? '').pathname)
14    if (here.endsWith(MOD_FILE) && !/[\s'"`$;&|<>()\\]/.test(here)) return `${here.slice(0, -MOD_FILE.length)}/scripts/temper`
15  } catch {
16    // no module URL here
17  }
18  return CLI
19}
20
hooks/temper-mod/core/commands.ts 32 lines
1// The first words of `/temper:temper` that the mod answers itself: the ones that show the run, open or close the pane,
2// or say how Temper shows and enforces it (the person changes those two in /config). Pure. Every other word goes on to the prompt based /temper:temper: a feature description starts or
3// resumes a run, and a decision word (approve, back, override, accept, pause, restart and the like) makes Claude ask
4// the `Temper gate` question, where the person decides with a click (ADR 0012).
5
6export const RESERVED = ['status', 'timeline', 'help', 'report', 'mode', 'enforcement', 'pane'] as const
7
8export type Reserved = (typeof RESERVED)[number]
9
10export const isReserved = (w: string): w is Reserved => (RESERVED as readonly string[]).includes(w)
11
12export type Parsed = { word: Reserved; rest: string }
13
14// null when the first word is not one the mod answers (a feature description, a decision word, or nothing).
15export function parseArgs(args: string): Parsed | null {
16  const text = args.trim()
17  const m = /^(\S+)\s*([\s\S]*)$/.exec(text)
18  const word = (m?.[1] ?? '').toLowerCase()
19  return m && isReserved(word) ? { word, rest: (m[2] ?? '').trim() } : null
20}
21
22export const HELP = [
23  'Temper subcommands (type them after /temper:temper):',
24  '  status               show where the run is',
25  '  timeline             list your decisions in this run',
26  '  report               show the run report (with no run active, the last one kept)',
27  '  pane                 open or close the Temper pane (full mode)',
28  '  mode, enforcement    show what Temper shows and enforces (change both in /config)',
29  'You decide at every gate in the Temper gate question: Continue, Loop back, Override and continue, Save for later.',
30  'Any other text after /temper:temper is a feature description. It starts or resumes a run. With no text it takes the run up again.',
31].join('\n')
32
hooks/temper-mod/core/config.ts 64 lines
1// The plain text userConfig fields the mod reads. userConfig declares no `options` (that
2// would stop the whole plugin loading before Claude Code 2.1.271), so every value is
3// validated here. The mod reads no `.claude/temper.config`: the CLI puts what it needs in view.json.
4
5export type UiMode = 'full' | 'minimal' | 'off'
6
7const norm = (v: string | undefined): string => (v ?? '').trim().toLowerCase()
8
9export function parseUiMode(v: string | undefined): UiMode {
10  const n = norm(v)
11  return n === 'minimal' || n === 'off' || n === 'full' ? n : 'full'
12}
13
14export function parseOnOff(v: string | undefined, fallback: 'on' | 'off'): 'on' | 'off' {
15  const n = norm(v)
16  return n === 'on' || n === 'off' ? n : fallback
17}
18
19export const parseEnforcement =(v: string | undefined): 'on' | 'off' => parseOnOff(v, 'on')
20
21// "build=sonnet, plan=opus" -> { build: 'sonnet', plan: 'opus' }; malformed pairs skipped.
22export function parsePhaseModels(v: string | undefined): Record<string, string> {
23  const out: Record<string, string> = {}
24  for (const pair of (v ?? '').split(',')) {
25    const m = /^\s*([A-Za-z-]+)\s*=\s*(\S+)\s*$/.exec(pair)
26    if (m?.[1] && m[2]) out[m[1].toLowerCase()] = m[2]
27  }
28  return out
29}
30
31export const MIN_VERSION = '2.1.287'
32
33// "2.1.288" or "2.1.280-dev.2026..." -> [2, 1, 288 or 280]; null when not a release.
34export function parseVersion(v: string): [number, number, number] | null {
35  const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v.trim())
36  return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null
37}
38
39// True when `v` is at least `min`. An unparseable version is not supported: the mod
40// stays inert rather than guess.
41export function versionAtLeast(v: string | undefined, min: string = MIN_VERSION): boolean {
42  const have = parseVersion(v ?? '')
43  const want = parseVersion(min)
44  if (!have || !want) return false
45  for (let i = 0; i < 3; i++) {
46    const a = have[i] ?? 0
47    const b = want[i] ?? 0
48    if (a !== b) return a > b
49  }
50  return true
51}
52
53export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
54const EFFORTS: readonly string[] = ['low', 'medium', 'high', 'xhigh', 'max']
55
56// "sonnet", "sonnet:high" or ":high" -> a model, an effort, or both; empty parts stay out.
57export function parsePhaseModel(value: string | undefined): { model?: string; effort?: Effort } {
58  const [model = '', effort = ''] = (value ?? '').split(':').map(s => s.trim())
59  const out: { model?: string; effort?: Effort } = {}
60  if (model) out.model = model
61  if (EFFORTS.includes(effort)) out.effort = effort as Effort
62  return out
63}
64
hooks/temper-mod/core/answers.ts 99 lines
1// The person's answers, read from the result of a question dialog (ADR 0013). Claude asks each question exactly as
2// `temper next --json` gives it; the CLI writes the same question into view.json. An answer counts only when its
3// header, its question and the chosen label match exactly what the view holds for the run and step the CLI is at, so a
4// reworded question is no answer. A typed answer ("Other") is never a move: it is a change request or a question, except
5// as the answer to a reason question, where any answer but Cancel is the person's reason. Pure.
6
7import type { Ask, Option, Question, RunView } from './runview'
8
9export const CANCEL = 'Cancel'
10
11export type DriftChoice = 'add' | 'revert' | 'allow-once'
12
13export type Answer =
14  // A gate question's option (and the reason, when the option needs one).
15  // `ask` is the CLI's question of this step that the answer belongs to (More options and the reason question included).
16  | { kind: 'gate'; stage: string; question: string; ask: string; option: Option; reason: string }
17  // The `Temper resume` question's Start over.
18  | { kind: 'restart'; option: Option }
19  // A Scope drift question's answer for one file.
20  | { kind: 'drift'; path: string; choice: DriftChoice; reason: string }
21
22type Result = { questions?: unknown; answers?: unknown; annotations?: unknown; afkTimeoutMs?: unknown; followUp?: unknown }
23
24// The result of a dialog the person answered. A dialog that resolved by itself while the person was away
25// (`afkTimeoutMs`), or one the person answered by asking for another round (`followUp`), holds no answer.
26export function answeredResult(result: unknown): Result | null {
27  const r = (result && typeof result === 'object' ? (result as { result?: unknown }).result : undefined) as Result | undefined
28  if (!r || !Array.isArray(r.questions) || !r.answers || typeof r.answers !== 'object') return null
29  if (r.afkTimeoutMs !== undefined || r.followUp === true) return null
30  return r
31}
32
33const same = (a: { header: string; question: string }, header: unknown, text: unknown): boolean => a.header === header && a.question === text
34
35// Every question the view asks at this step: the gate question, its More options and Accept a finding questions.
36function asks(a: Ask | null): Ask[] {
37  if (a === null) return []
38  return [a, ...asks(a.more), ...asks(a.accept)]
39}
40
41const DRIFT_CHOICE: Record<string, DriftChoice> = { 'Add to plan': 'add', Revert: 'revert', 'Allow once': 'allow-once' }
42
43// The value of a `Label: value` line of a question.
44const line = (text: string, label: string): string => {
45  for (const l of text.split('\n')) if (l.trim().startsWith(label)) return l.trim().slice(label.length).trim()
46  return ''
47}
48
49export function answersIn(result: unknown, view: RunView): Answer[] {
50  const r = answeredResult(result)
51  if (r === null) return []
52  const answers = r.answers as Record<string, unknown>
53  const notes = r.annotations && typeof r.annotations === 'object' ? (r.annotations as Record<string, unknown>) : {}
54  const out: Answer[] = []
55  for (const raw of r.questions as unknown[]) {
56    const q = (raw && typeof raw === 'object' ? raw : {}) as { header?: unknown; question?: unknown; multiSelect?: unknown }
57    if (typeof q.question !== 'string' || typeof q.header !== 'string' || q.multiSelect === true) continue
58    const answer = answers[q.question]
59    if (typeof answer !== 'string' || answer === '') continue
60    const noteRow = notes[q.question]
61    const noted = noteRow && typeof noteRow === 'object' ? (noteRow as { notes?: unknown }).notes : undefined
62    const note = typeof noted === 'string' ? noted.trim() : ''
63
64    // The gate question, More options, Accept a finding: the chosen option, exactly. One that needs a reason counts with
65    // the person's note; without one, it counts once the reason question is answered.
66    for (const a of asks(view.ask)) {
67      if (!same(a.question, q.header, q.question)) continue
68      const option = a.options.find(o => o.label === answer)
69      if (option === undefined || option.move === null) continue
70      if (option.reasonQuestion !== null && note === '') continue
71      out.push({ kind: 'gate', stage: a.stage, question: q.question, ask: view.ask?.question.question ?? q.question, option, reason: note })
72    }
73    // A reason question: any answer but Cancel is the reason, a typed one too.
74    for (const a of asks(view.ask)) {
75      for (const option of a.options) {
76        const rq: Question | null = option.reasonQuestion
77        if (rq === null || !same(rq, q.header, q.question) || answer === CANCEL) continue
78        out.push({ kind: 'gate', stage: a.stage, question: a.question.question, ask: view.ask?.question.question ?? a.question.question, option, reason: [answer, note].filter(t => t !== '').join(' ') })
79      }
80    }
81    // Start over.
82    if (view.restart !== null && same(view.restart, q.header, q.question)) {
83      const option = view.restart.options.find(o => o.label === answer)
84      if (option !== undefined && option.move === 'restart') out.push({ kind: 'restart', option })
85    }
86    // Scope drift: the header, a first line `Outside the plan: <path>`, and one of the three choices.
87    if (q.header === view.drift.header && q.question.split('\n')[0]?.startsWith(view.drift.prefix) && view.drift.options.includes(answer)) {
88      const path = ((q.question.split('\n')[0] ?? '').slice(view.drift.prefix.length).trim().split(/\s+/)[0] ?? '').replace(/[.,;:]+$/, '')
89      const choice = DRIFT_CHOICE[answer]
90      if (path !== '' && choice !== undefined) {
91        // Allow once keeps Claude's why, marked as Claude's, which the person accepted.
92        const why = line(q.question, 'Why:')
93        out.push({ kind: 'drift', path, choice, reason: choice === 'allow-once' ? `why (Claude): ${why || 'not given'}` : note })
94      }
95    }
96  }
97  return out
98}
99
hooks/temper-mod/core/rules.ts 457 lines
1// The guard (ADR 0013): `evaluate(ctx, call)` answers allow or deny for one tool call. Pure. It claims only what it can
2// enforce, in three jobs:
3//  1. a CLI call that only the person may cause is one the person's answer at the CLI's current step maps to, word for
4//     word, or one the CLI's own action lists (an armed run's move, the commit steps);
5//  2. Temper's own files (the CLI's files in `.temper`, and during a run the config and the git hooks) are written by
6//     neither the editing tools nor a plain Bash write, and each stage allows its own writes by the editing tools;
7//  3. a short Bash list: no commit around the native hook (`--no-verify`, a changed `core.hooksPath`).
8// Where the run is comes from view.json's guard field (RunFacts); the person's choices come from the question dialogs
9// (core/decisions.ts). Whether a stage may be left on its verdict is the CLI's to decide (it refuses the call). Every
10// deny text ends with what to do next. core/shell.ts reads a Bash command; it is not a shell parser, and Temper is not a
11// sandbox (docs/trust.md).
12
13import { callWords, globCould, readShell, sameCall } from './shell'
14import type { DriftState } from './decisions'
15import { CLI } from './cli'
16import { matchesPlan, normalizePath } from './paths'
17import type { Stage } from './stages'
18import { STAGES, isStage, stageIndex, stageLabel } from './stages'
19
20export const DRIFT_HEADER = 'Scope drift'
21export const DRIFT_PREFIX = 'Outside the plan:'
22
23// What view.json says about the run, for the guard.
24export type RunFacts = {
25  // The stage the CLI is at. `commit`: every gate is behind the run; it is done.
26  stage: Stage
27  // The CLI's step count: 0 right after `state init`.
28  step: number
29  // The spec directory, relative to the root: `.temper/specs/{slug}`.
30  specDir: string
31  // The files the person approved at the plan gate (before it, the plan's files as they are).
32  planFiles: readonly string[]
33  // A grouped Build run is active, and the CLI (not an agent) ticks the run's tasks.md.
34  groupedActive: boolean
35  // The run never left Intent and holds no spec file: a `state clear` loses nothing (the TRIVIAL exit).
36  trivialExit: boolean
37  // The project's folder from the top of its git repository (`packages/app/`); "" or absent at the top. A group or task
38  // worktree is a checkout of the whole repository, so the project's files are under this prefix in it.
39  prefix?: string
40}
41
42export type RuleContext = {
43  // The run, or null when no /temper run is active (the mod then guards only what needs no run).
44  run: RunFacts | null
45  // The calls the person's answers at this step map to, and the calls and steps of the CLI's own action (an armed
46  // run's move, the commit steps): a call only the person may cause passes when it is one of these, word for word.
47  allowed: readonly string[]
48  // The person chose Start over in this run.
49  restart: boolean
50  // The person's Scope drift answers in this run.
51  drift: DriftState
52  // A /temper:fix run is active: the mod judges none of its moves (commands/fix.md asks every gate), but nothing goes
53  // around the native commit hook, and the config and the git hooks stay the person's.
54  fixRun?: boolean
55  // Absolute project root; absolute tool paths inside it are made relative.
56  root?: string
57  // Where the Temper script is: every deny text names the CLI by it.
58  cli?: string
59}
60
61export type ToolCall = { tool: string; input: Record<string, unknown> }
62
63// `use`: a decision this call spends (Keep the agent's commits, an Allow once answer); it counts once.
64export type RuleResult = { allow: true; use?: string } | { deny: string; drift?: string }
65
66const ALLOW: RuleResult = { allow: true }
67const WRITE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
68
69const TEST_FILE = [/(^|\/)(?:tests?|__tests__|specs?)\//, /\.(?:test|spec)\.[^/]+$/, /(^|\/)test_[^/]*$/, /_test\.[^/]+$/]
70
71export const isTestFile = (path: string): boolean => TEST_FILE.some(re => re.test(path))
72
73const ASK = 'ask the user with AskUserQuestion, header `Temper gate`'
74
75export const ONLY_USER = `Only the user decides this. Next: ask the question \`temper next --json\` gives, exactly as given (header \`Temper gate\`), then wait.`
76
77const AUTONOMY_REPORT = '.temper/autonomy-report.md'
78
79function targetPath(call: ToolCall): string | null {
80  const raw = call.tool === 'NotebookEdit' ? call.input.notebook_path : call.input.file_path
81  return typeof raw === 'string' && raw.length > 0 ? raw : null
82}
83
84const inDir = (path: string, dir: string): boolean => path === dir || path.startsWith(dir + '/')
85
86// The files the editing tools never write. `config` and `hooks` only while a run is active (the person writes the config
87// with /temper:init, and installs the hooks, when no run is on). `hooks` is the native commit gate: the git hooks, the
88// git config (core.hooksPath) and the Temper commit hook (the temper-gate folder in the git folder, the older
89// temper-pre-commit file there, and the older folders hooks-temper and temper-git-hooks).
90export type ProtectedKind = 'events' | 'gates' | 'status' | 'overrides' | 'state' | 'folder' | 'evidence' | 'loops' | 'config' | 'hooks'
91
92// Every name is compared without regard to case: macOS (APFS) and Windows folders are case insensitive.
93const PROTECTED: ReadonlyArray<readonly [ProtectedKind, RegExp]> = [
94  ['events', /(^|\/)\.temper\/specs\/[^/\s]+\/events(\/|$)/i],
95  ['gates', /(^|\/)\.temper\/gates\.json$/i],
96  ['status', /(^|\/)\.temper\/status\.json$/i],
97  ['overrides', /(^|\/)\.temper\/overrides\.json$/i],
98  // The run state, the grouped Build record, the usage record and the view the mod draws: the CLI writes them.
99  ['state', /(^|\/)\.temper\/(?:build-state|groups|usage|view)\.json$/i],
100  ['evidence', /(^|\/)\.temper\/evidence\/[^/]+\.json$/i],
101  ['loops', /(^|\/)\.temper\/feedback-loops\.json$/i],
102  ['config', /(^|\/)\.claude\/temper\.config$/i],
103  ['hooks', /(^|\/)\.git\/(?:hooks(\/|$)|hooks-temper(\/|$)|temper-git-hooks(\/|$)|config$|config\.worktree$|worktrees\/[^/]+\/config\.worktree$|temper-gate(\/|$)|temper-pre-commit(\/|$))/i],
104  // Folders that hold guarded files: removing or replacing one removes them too.
105  ['folder', /(^|\/)\.temper(\/specs(\/[^/\s]+)?|\/evidence)?\/?$/i],
106]
107
108// A guarded path of each kind, to test a glob a Bash command writes against (`rm .temper/*.json`).
109const GUARDED_SAMPLES = [
110  '.temper', '.temper/specs', '.temper/evidence', '.temper/gates.json', '.temper/status.json', '.temper/overrides.json',
111  '.temper/build-state.json', '.temper/groups.json', '.temper/usage.json', '.temper/view.json', '.temper/feedback-loops.json',
112  '.temper/evidence/review.json', '.claude/temper.config', '.git/config', '.git/hooks', '.git/hooks/pre-commit', '.git/temper-gate',
113]
114// A glob as bash reads it, one segment at a time: `*` and `?` stay inside a segment, and a segment that starts with one
115// does not match a name that starts with a dot (bash's default: `rm -rf *` leaves `.temper` alone).
116const globRe = (glob: string): RegExp =>
117  new RegExp(
118    '^' +
119      glob
120        .split('/')
121        .map(seg => (/^[*?[]/.test(seg) ? '(?!\\.)' : '') + seg.split('').map(c => (c === '*' ? '[^/]*' : c === '?' ? '[^/]' : c === '[' || c === ']' ? c : c.replace(/[.+^${}()|\\]/g, '\\$&'))).join(''))
122        .join('/') +
123      '$',
124    'i',
125  )
126
127// Which guarded kind a glob a command writes can reach, or null (the glob against a guarded path of each kind).
128function globKind(path: string): ProtectedKind | null {
129  if (!/[*?[]/.test(path)) return null
130  let re: RegExp
131  try {
132    re = globRe(path)
133  } catch {
134    return null
135  }
136  const hit = GUARDED_SAMPLES.find(g => re.test(g))
137  return hit === undefined ? null : protectedKind(hit)
138}
139
140// Which guarded Temper path a path names, or null. `..` and `.` segments are collapsed first.
141export function protectedKind(path: string): ProtectedKind | null {
142  const p = normalizePath(path)
143  for (const [kind, re] of PROTECTED) if (re.test(p)) return kind
144  return null
145}
146
147// A /temper run is on, at any stage up to and with Commit: the commit gate can still fail at the commit stage (a missing
148// verdict, an autonomous park), so nothing may go around it there either. At Commit only the spec folder is written (stageWriteRule).
149const isActive = (ctx: RuleContext): ctx is RuleContext & { run: RunFacts } => ctx.run !== null
150
151function protectedDeny(kind: ProtectedKind, cli: string): RuleResult {
152  if (kind === 'events' || kind === 'overrides') return { deny: ONLY_USER }
153  if (kind === 'folder') {
154    return {
155      deny:
156        'Temper: the .temper folders hold the run, its verdicts and its decisions. Do not remove or replace them by hand. ' +
157        `Next: use ${cli} state archive after the run, or name one file.`,
158    }
159  }
160  if (kind === 'config') {
161    return {
162      deny:
163        'Temper: .claude/temper.config sets how this run is checked (autonomy, thresholds, what blocks a review). Only the user changes it while a run is active. ' +
164        'Next: ask the user to edit it themselves, or to end the run first.',
165    }
166  }
167  if (kind === 'evidence' || kind === 'loops') {
168    return {
169      deny:
170        'Temper: the evidence ledger and the loop counter belong to the temper CLI. Do not write them by hand. ' +
171        `Next: use ${cli} evidence add, run or resolve, and ${cli} state loop.`,
172    }
173  }
174  if (kind === 'hooks') {
175    return {
176      deny:
177        'Temper: the git hooks, the Temper commit hook and core.hooksPath are the native commit gate. Do not change them while a run is active. ' +
178        'Next: ask the user, or finish the run first.',
179    }
180  }
181  if (kind === 'state') {
182    return {
183      deny: 'Temper: use the temper CLI to change run state. Do not write it by hand. ' + `Next: use ${cli} state set or ${cli} state advance.`,
184    }
185  }
186  return {
187    deny: 'Temper: the temper CLI makes the gate verdicts. Do not write them by hand. ' + `Next: run ${cli} gate <stage> and read the verdict.`,
188  }
189}
190
191// The path inside a group or task worktree of THIS run (`.claude/worktrees/temper-{slug}-G{n}/...` or `-T{n}/...`),
192// relative to the project folder in that worktree; null for any other path. The path is normalized already, so a `..`
193// after the prefix has been collapsed and cannot leave the worktree this way. A worktree is a checkout of the whole
194// repository: for a project below its top (`project`, as `packages/app/`), a path outside the project reads as `../...`,
195// which no plan names.
196function worktreeRelative(path: string, specDir: string, project = ''): string | null {
197  const slug = normalizePath(specDir).split('/').pop() ?? ''
198  if (slug === '') return null
199  const prefix = `.claude/worktrees/temper-${slug}-`
200  if (!path.startsWith(prefix)) return null
201  const m = /^[GT](\d+)\/(.+)$/.exec(path.slice(prefix.length))
202  const rel = m?.[2]
203  if (rel === undefined) return null
204  const pre = normalizePath(project)
205  if (pre === '') return rel
206  if (rel.startsWith(pre + '/')) return rel.slice(pre.length + 1)
207  return '../'.repeat(pre.split('/').length) + rel
208}
209
210const TASKS_OWNED =
211  'Next: run the tasks through the CLI (task test, task gate); the CLI ticks the boxes. To change the plan, ask the user whether to loop back to Plan.'
212
213function stageWriteRule(ctx: RuleContext & { run: RunFacts }, rawPath: string): RuleResult {
214  const r = ctx.run
215  // A write in a group or task worktree of this run is judged by its worktree-relative path, with the same rule.
216  const rel = worktreeRelative(rawPath, r.specDir, r.prefix)
217  const path = rel ?? rawPath
218  const spec = normalizePath(r.specDir)
219  // The person approved tasks.md at the plan gate, and in Build the CLI ticks it: from Design on, no agent writes it
220  // (a change needs a step back to Plan and the person's approval again).
221  if (stageIndex(r.stage) >= stageIndex('design') && path === `${spec}/tasks.md`) {
222    return { deny: `Temper: the plan is approved. Writing ${rawPath} is not allowed: the run's tasks.md is the plan the user approved, and the temper CLI ticks it. ${TASKS_OWNED}` }
223  }
224  const inSpec = inDir(path, spec)
225  const specFile = (name: string) => path === `${spec}/${name}`
226  const label = stageLabel(r.stage)
227
228  switch (r.stage) {
229    case 'intent':
230      if (specFile('intent.md') || specFile('intent-context.json')) return ALLOW
231      return {
232        deny:
233          `Temper: ${label} stage. Writing ${path} is not allowed until the user approves the intent. ` +
234          'Do not look for another way. Do not offer to turn Temper off. ' +
235          `Next: finish intent.md. Then ${ASK} (Continue to Plan).`,
236      }
237    case 'plan':
238    case 'design': {
239      const ok =
240        ['intent.md', 'plan.md', 'tasks.md', 'design.md', 'config-suggestions.json'].some(specFile) ||
241        (inSpec && /-context\.json$/.test(path)) ||
242        (path.startsWith('docs/decisions/') && path.endsWith('.md'))
243      if (ok) return ALLOW
244      return {
245        deny:
246          `Temper: ${label} stage. Writing ${path} is not allowed until the user approves the plan and Build starts. ` +
247          'Do not look for another way. Do not offer to turn Temper off. ' +
248          `Next: finish the ${r.stage === 'plan' ? 'plan' : 'design'}. Then ${ASK}.`,
249      }
250    }
251    case 'review':
252      if (inSpec) return ALLOW
253      return {
254        deny:
255          `Temper: ${label} stage. Writing ${path} is not allowed. Review changes the spec folder only. ` +
256          `Next: write the finding in the spec folder. To fix it, ${ASK} whether to loop back to Build.`,
257      }
258    case 'check':
259      // A config suggestion the user accepts after Check passed goes into the project's agent instructions.
260      if (inSpec || PROJECT_NOTES.has(path)) return ALLOW
261      return {
262        deny:
263          `Temper: ${label} stage. Writing ${path} is not allowed. Check only runs checks. ` +
264          `Next: finish the check stage. To change code, ${ASK} whether to loop back to Build.`,
265      }
266    case 'build': {
267      if (inSpec || isTestFile(path) || matchesPlan(path, r.planFiles) || ctx.drift.added.some(p => normalizePath(p) === path)) return ALLOW
268      const once = ctx.drift.allowOnce.find(a => normalizePath(a.path) === path)
269      if (once) return { allow: true, use: once.id }
270      return {
271        deny:
272          `Temper: scope drift. ${path} is not in the plan, so the user decides first: add to plan, revert, or allow once. ` +
273          'Do not write it another way. Next: in the Build stage, stop this task and list the file in the DRIFT section of your ' +
274          'panel, with why it is needed and what you would change. In the main conversation, ask with AskUserQuestion: ' +
275          `header "${DRIFT_HEADER}", a question whose first line is "${DRIFT_PREFIX} ${path}", then a "Why:" line and a ` +
276          '"Change:" line, and the options Add to plan, Revert, Allow once.',
277        drift: path,
278      }
279    }
280    case 'commit':
281      // Every gate has passed: the code is what Review and Check saw. The commit steps write in the spec folder only
282      // (the plan's deviations, the report page).
283      if (inSpec || PROJECT_NOTES.has(path)) return ALLOW
284      return {
285        deny:
286          `Temper: ${label} stage. Writing ${path} is not allowed: Review and Check passed on the code as it is, and the commit carries that. ` +
287          `Next: do the commit steps. To change code, ${ASK} (Save for later, then a new run), or loop back from Check before the commit.`,
288      }
289  }
290}
291
292// The project's agent instructions, where an accepted config suggestion is written (reference/config-suggestions.md).
293const PROJECT_NOTES = new Set(['CLAUDE.md', 'AGENTS.md', '.claude/CLAUDE.md', '.claude/AGENTS.md'])
294
295const AUTONOMY_DENY =
296  'Temper: only the user can turn on autonomous mode, at the plan gate. ' +
297  `Next: ${ASK} at the plan gate, exactly as \`temper next --json\` gives it. ` +
298  'It needs autonomy.enabled: true in .claude/temper.config, which only the user sets.'
299
300// The keys of build-state.json that only the CLI's own moves write. next_stage is a step (see the back calls).
301const GUARD_KEYS = new Set(['stage', 'branch', 'spec_path', 'command', 'run_id', 'step', 'approved_files', 'plan_hash', 'archived', 'enter', 'built_before', 'review_snapshot'])
302
303const DONE_OVERRIDE_DENY =
304  "Temper: the run is done, and an override now is the user's choice. " +
305  `Next: show the failed commit gate and ${ASK}: "Override and commit" (with a reason) or "Save for later". ` +
306  'Then run every override that commit needs.'
307
308const STATE_RESTART =
309  'Temper: state init and state loop restart or move the run. Only the user decides that. ' +
310  'Next: ask the user with AskUserQuestion, header `Temper resume`, whether to start over (or, for a step back, the Loop back choice of the `Temper gate` question).'
311
312const STATE_END = (cli: string): string =>
313  'Temper: do not clear or archive the run state during a run. Next: finish the run, ' +
314  `commit, then run ${cli} state archive. To throw the run away, ask the user with AskUserQuestion, header \`Temper resume\`, whether to start over.`
315
316const HOOKS_DENY =
317  'Temper: --no-verify, -n and core.hooksPath switch the native pre-commit hook off. The hook is the commit gate for every commit. ' +
318  'Next: commit without them. If the hook blocks the commit, finish the stages it names.'
319
320const TOO_MANY_DENY =
321  'Temper: a word of this command expands to more words (a brace list) than the guard reads, so what it writes is not known. ' +
322  'Next: write the paths out, or split the command.'
323
324// The words the check of a call only the person may cause reads (personOnly), and the stages a step back may name.
325const PERSON_WORDS = ['override', 'group', 'reopen', '--accept-foreign', 'evidence', 'accept', 'clear', 'state', 'advance', 'intent_complete',
326  'plan_complete', 'loop', 'init', 'archive', 'set', 'run_mode', 'next_stage', 'autonomous', 'interactive', 'rca', 'fix', ...STAGES]
327
328const GLOB_DENY =
329  'Temper: a word of this temper call is an unquoted glob (`*`, `?`, `[...]`), which bash may expand to the name of a file, so the call it makes is not known. ' +
330  'Next: write the call out, or quote the word.'
331
332// The plugin data folder of Claude Code (`~/.claude/plugins/data/`) holds the mod's store, and in it the person's
333// decisions. The editing tools do not write it while a run is active.
334const PLUGIN_DATA = /\.claude\/plugins\/data(?:\/|\b)/
335
336const PLUGIN_DATA_DENY =
337  'Temper: the plugin data folder under ~/.claude holds the decisions the user made. Do not change it while a run is active. ' +
338  `Next: ${ASK} for a decision.`
339
340const KEY_DENY = (key: string): string =>
341  `Temper: state set ${key} is allowed only in the form and the stage the orchestrator uses ` +
342  '(complexity while the plan is open, base_sha as the current commit in Plan or Build; run_id, step and command never). ' +
343  'Next: ask the user if the run needs another value.'
344
345function evaluateBash(ctx: RuleContext, command: string): RuleResult {
346  const c = readShell(command)
347  const cli = ctx.cli ?? CLI
348  const active = isActive(ctx)
349  // Nothing goes around the native commit hook while a /temper run or a /temper:fix run is active.
350  const guardsCommit = active || ctx.fixRun === true
351
352  if (guardsCommit && c.noVerify) return { deny: HOOKS_DENY }
353  if (guardsCommit && c.hooksPath) return protectedDeny('hooks', cli)
354  if (c.tooMany) return { deny: TOO_MANY_DENY }
355  // A plain write onto a protected file: the same list, and the same texts, as the editing tools. A copy, move or link
356  // whose last word is a folder of the run (`cp notes.md .temper/specs/pw/`) puts its files in that folder: the folder
357  // is not replaced, and each file that lands there is judged by its own path.
358  const kindOf = (p: string): ProtectedKind | null => {
359    const n = normalizePath(p, ctx.root)
360    return protectedKind(n) ?? globKind(n)
361  }
362  // A target that is a folder of the run is not replaced; a glob is no folder (bash may expand `.temper/[Eg][Va]*` to
363  // one file), so it is judged as a write.
364  const target = (p: string): ProtectedKind | null => {
365    const k = kindOf(p)
366    return k === 'folder' && !/[*?[]/.test(p) ? null : k
367  }
368  const kinds = [...c.writes.map(kindOf), ...c.targets.map(target), ...c.landings.map(kindOf)].filter(
369    (k): k is ProtectedKind => k !== null && (guardsCommit || (k !== 'config' && k !== 'hooks')),
370  )
371  if (kinds.length > 0) return protectedDeny(kinds.find(k => k === 'events' || k === 'overrides') ?? (kinds[0] as ProtectedKind), cli)
372
373  if (!active) return ALLOW
374  // An unquoted glob in a call that could spell a word of a call only the person may cause (`o?erride`, `lo[o]p`,
375  // `--accept-for?ign`): bash expands it when a file of that name exists. Any other glob (`sonnet[1m]`) is no refusal.
376  if (c.globWords.some(ws => ws.some(w => PERSON_WORDS.some(t => globCould(w, t) || globCould(w.split('=')[0] ?? w, t))))) return { deny: GLOB_DENY }
377  const r = ctx.run
378  for (const call of c.calls) {
379    const w = callWords(call)
380    const [a, b, key, value] = w
381    if (a === 'state' && b === 'set' && key !== undefined) {
382      if (GUARD_KEYS.has(key)) return { deny: KEY_DENY(key) }
383      // The keys the orchestrator sets itself, only in the form and the stage it sets them: the complexity while the
384      // plan is open (a later change would drop Design), base_sha as the current commit in Plan or Build.
385      if (key === 'complexity' && !((r.stage === 'intent' || r.stage === 'plan') && /^(?:trivial|simple|medium|complex)$/.test(value ?? ''))) return { deny: KEY_DENY(key) }
386      if (key === 'base_sha') {
387        const v = value ?? ''
388        const form = /^[0-9a-f]{7,40}$/i.test(v) || v === '$(git rev-parse HEAD)' || v === '`git rev-parse HEAD`'
389        if (!((r.stage === 'plan' || r.stage === 'build') && form)) return { deny: KEY_DENY(key) }
390      }
391    }
392    if (!personOnly(w, r)) continue
393    // The person's answer at this step, or the CLI's own action, maps to this very call.
394    if (ctx.allowed.some(written => sameCall(written, w))) continue
395    const resets = a === 'state' && (b === 'clear' || b === 'archive' || b === 'init')
396    // The TRIVIAL exit of the orchestrator: a clear of a run that never left Intent loses nothing.
397    if (a === 'state' && b === 'clear' && r.trivialExit && r.stage === 'intent' && r.step <= 0) continue
398    // Start over: the saved run state goes, and a run of the same command begins (never a fix run, which the mod stands
399    // aside for).
400    if (resets && ctx.restart && !w.some((x, i) => (x === '--command' && w[i + 1] === 'fix') || x === '--command=fix')) continue
401    return { deny: personDeny(w, r, cli) }
402  }
403  return ALLOW
404}
405
406// The temper calls only the person may cause (ADR 0013), by their words after the script: leaving Intent or Plan, a
407// skip, a step back, accepting a finding, arming autonomy, keeping a task agent's commits, and starting over or ending
408// the run before it is done.
409function personOnly(w: readonly string[], r: RunFacts): boolean {
410  const [a, b, c, d] = w
411  if (a === 'override') return true
412  if (a === 'group' && b === 'reopen') return w.some(x => x === '--accept-foreign' || x.startsWith('--accept-foreign='))
413  // Accepting a finding, or clearing a ledger (which erases what a stage found), is the person's.
414  if (a === 'evidence') return b === 'accept' || b === 'clear'
415  if (a !== 'state') return false
416  if (b === 'advance') return c === 'intent_complete' || c === 'plan_complete'
417  if (b === 'loop' || b === 'init' || b === 'clear' || b === 'archive') return true
418  if (b === 'set' && c === 'run_mode') return d !== 'interactive'
419  // A step back (a set to the stage the run is at changes nothing; a step forward is the CLI's to check).
420  if (b === 'set' && c === 'next_stage') return !(d !== undefined && isStage(d) && stageIndex(d) >= stageIndex(r.stage))
421  return false
422}
423
424function personDeny(w: readonly string[], r: RunFacts, cli: string): string {
425  const [a, b, c] = w
426  if (a === 'state' && (b === 'clear' || b === 'archive')) return STATE_END(cli)
427  if (a === 'state' && (b === 'init' || b === 'loop')) return STATE_RESTART
428  if (a === 'state' && b === 'set' && c === 'run_mode') return AUTONOMY_DENY
429  if (a === 'override' && r.stage === 'commit') return DONE_OVERRIDE_DENY
430  return ONLY_USER
431}
432
433export function evaluate(ctx: RuleContext, call: ToolCall): RuleResult {
434  if (call.tool === 'Bash') {
435    const command = typeof call.input.command === 'string' ? call.input.command : ''
436    return evaluateBash(ctx, command)
437  }
438  if (!WRITE_TOOLS.has(call.tool)) return ALLOW
439
440  const raw = targetPath(call)
441  if (raw === null) return ALLOW
442  const path = normalizePath(raw, ctx.root)
443  const active = isActive(ctx)
444  if (active && PLUGIN_DATA.test(raw)) return { deny: PLUGIN_DATA_DENY }
445
446  const kind = protectedKind(path)
447  // The config, the git hooks and the Temper commit hook are guarded while a run is active, a fix run too (the person
448  // writes them with no run on).
449  if (kind !== null && (active || ctx.fixRun === true || (kind !== 'config' && kind !== 'hooks'))) return protectedDeny(kind, ctx.cli ?? CLI)
450  // The report a parked autonomous run leaves (reference/autonomy.md): a note of the run, at any stage.
451  if (path === AUTONOMY_REPORT) return ALLOW
452
453  // Save for later stops the run; it lifts no rule (enforcement off is the person's way to lift them).
454  if (!active) return ALLOW
455  return stageWriteRule(ctx, path)
456}
457
hooks/temper-mod/core/shell.ts 664 lines
1// What the guard reads in a Bash command (ADR 0013). It is not a shell parser: it splits the text into statements and
2// words, honouring quotes (`'...'`, `"..."`, `$'...'` with its escapes, `$"..."`, a backslash), expands every word's
3// brace lists as bash does, and looks for three things only:
4//  - the temper CLI calls written out (`scripts/temper ...` or `temper ...`), so a call only the person may cause needs
5//    the person's answer;
6//  - a commit that switches the native pre-commit hook off (`--no-verify`, `-n`), a change of `core.hooksPath`, or a
7//    config git is handed that can do either (an included file, an alias, a home folder);
8//  - the paths the command writes: a redirect's target, and the files a writing program names (rm, mv, cp, tee,
9//    sed -i and the like). The guard holds them to the same list of protected files as the editing tools.
10// A program is named by its last path segment, without regard to case (macOS and Windows file systems ignore it), and
11// by a glob that can expand to its name (`/usr/bin/gi[t]`). Anything this does not see (a variable, the output of a
12// substitution, a script on disk, a program that builds a name at run time) passes. Temper is not a sandbox
13// (docs/trust.md): the native hook and the editing tool rules are the hard guarantees.
14
15export type ShellRead = {
16  // Each temper call written out: its words after the script (`state advance plan_complete build`).
17  calls: string[][]
18  // `git commit --no-verify` or `-n`: the native pre-commit hook would not run.
19  noVerify: boolean
20  // A change of `core.hooksPath`, or a config handed to git that could make one: git would run other hooks than Temper's.
21  hooksPath: boolean
22  // The paths the command writes, as written.
23  writes: string[]
24  // The last word of a copy, move or link (`cp a b DIR`), kept apart from `writes`: when it is a folder the files land
25  // inside it and the folder itself is not replaced; when it is a file it is written.
26  targets: string[]
27  // Where the files of such a command land when its last word is a folder (`DIR/a`, `DIR/b`).
28  landings: string[]
29  // A word that expands to more words than the guard reads (a brace list): what it writes is not known.
30  tooMany: boolean
31  // The unquoted glob words of each temper call, masked, but for the value of its `--reason` (`temper o?erride ...`):
32  // bash may expand one to a file's name, so the rules check whether it could spell a word they read.
33  globWords: string[][]
34}
35
36// A quoted character that bash does not expand (a brace list's braces and commas, a glob's characters) is kept apart
37// from an unquoted one while the guard reads the command: a private use character stands for it until the words are
38// expanded.
39const MASK: Record<string, string> = { '{': '', '}': '', ',': '', '*': '', '?': '', '[': '', ']': '' }
40const UNMASK: Record<string, string> = Object.fromEntries(Object.entries(MASK).map(([k, v]) => [v, k]))
41const mask = (text: string): string => text.replace(/[{},*?[\]]/g, c => MASK[c] ?? c)
42const unmask = (text: string): string => text.replace(/[-]/g, c => UNMASK[c] ?? c)
43
44// The text of an ANSI-C quote (`$'...'`, without its quotes) as bash reads it: `\n`, `\t`, `\\`, `\'`, octal `\nnn`,
45// `\xHH`, `\uHHHH`, `\UHHHHHHHH`, `\cX` and the rest.
46function ansiC(s: string): string {
47  const simple: Record<string, string> = { a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v', '\\': '\\', "'": "'", '"': '"', '?': '?' }
48  let out = ''
49  for (let i = 0; i < s.length; i++) {
50    const c = s[i] as string
51    if (c !== '\\' || i + 1 >= s.length) {
52      out += c
53      continue
54    }
55    const n = s[++i] as string
56    const digits = (re: RegExp, max: number): string => {
57      let d = ''
58      while (d.length < max && re.test(s[i + 1] ?? '')) d += s[++i]
59      return d
60    }
61    if (n in simple) out += simple[n]
62    else if (/[0-7]/.test(n)) out += String.fromCharCode(parseInt(n + digits(/[0-7]/, 2), 8) & 0xff)
63    else if (n === 'x') {
64      const h = digits(/[0-9a-fA-F]/, 2)
65      out += h === '' ? '\\x' : String.fromCharCode(parseInt(h, 16))
66    } else if (n === 'u' || n === 'U') {
67      const h = digits(/[0-9a-fA-F]/, n === 'u' ? 4 : 8)
68      out += h === '' ? `\\${n}` : String.fromCodePoint(Math.min(parseInt(h, 16), 0x10ffff))
69    } else if (n === 'c' && i + 1 < s.length) out += String.fromCharCode((s[++i] as string).charCodeAt(0) & 31)
70    else out += `\\${n}`
71  }
72  return out
73}
74
75// Where the ANSI-C quote that starts at `i` (`$'`) ends: the index of its closing quote, or the end of the text.
76function ansiEnd(command: string, i: number): number {
77  for (let j = i + 2; j < command.length; j++) {
78    if (command[j] === '\\') j++
79    else if (command[j] === "'") return j
80  }
81  return command.length
82}
83
84// Where the command substitution that starts at `i` (`$(` or a backquote) ends: the index of its `)` or backquote, or
85// the end of the text.
86function substitutionEnd(command: string, i: number): number {
87  if (command[i] === '`') {
88    for (let j = i + 1; j < command.length; j++) {
89      if (command[j] === '\\') j++
90      else if (command[j] === '`') return j
91    }
92    return command.length
93  }
94  let depth = 0
95  for (let j = i + 1; j < command.length; j++) {
96    const c = command[j]
97    if (c === '\\') j++
98    else if (c === "'") {
99      const close = command.indexOf("'", j + 1)
100      j = close < 0 ? command.length : close
101    } else if (c === '"') {
102      for (j++; j < command.length && command[j] !== '"'; j++) if (command[j] === '\\') j++
103    } else if (c === '`') j = substitutionEnd(command, j)
104    else if (c === '(') depth++
105    else if (c === ')' && --depth === 0) return j
106  }
107  return command.length
108}
109
110// The text as statements of words, with quoted characters masked (see MASK). A quoted part keeps its spaces and loses
111// its quotes; an operator outside quotes (`;`, `&`, `|`, a newline, a bracket) ends the statement. A redirect is a word
112// of its own (`>`, `>>`). A command substitution (`$(...)` or a backquote, inside double quotes too) keeps its text in
113// the word around it, as bash expands braces before it runs one (`{a,$(b)}`); its commands are statements of their
114// own, after the others. The body of a here document is text, not commands: it is skipped.
115function tokens(command: string): string[][] {
116  const out: string[][] = []
117  let words: string[] = []
118  let word = ''
119  let inWord = false
120  // The here documents of the current line, in order: their end words, and whether `<<-` lets the end word be indented.
121  const docs: Array<{ end: string; dash: boolean }> = []
122  const inner: string[][] = []
123  // A substitution at `i`: its commands are read, and its text joins the word (masked inside double quotes, where bash
124  // expands no brace list of it). Returns where it ends.
125  const substitution = (i: number, quoted: boolean): number => {
126    const end = substitutionEnd(command, i)
127    inner.push(...tokens(command.slice(command[i] === '`' ? i + 1 : i + 2, end)))
128    const text = command.slice(i, end + 1)
129    word += quoted ? mask(text) : text
130    inWord = true
131    return end
132  }
133  const endWord = () => {
134    if (inWord) words.push(word)
135    word = ''
136    inWord = false
137  }
138  const endStatement = () => {
139    endWord()
140    if (words.length > 0) out.push(words)
141    words = []
142  }
143  for (let i = 0; i < command.length; i++) {
144    const ch = command[i] as string
145    if (ch === "'") {
146      const close = command.indexOf("'", i + 1)
147      const end = close < 0 ? command.length : close
148      word += mask(command.slice(i + 1, end))
149      inWord = true
150      i = end
151    } else if (ch === '$' && command[i + 1] === "'") {
152      // `$'...'`: a quote whose escapes bash decodes.
153      const end = ansiEnd(command, i)
154      word += mask(ansiC(command.slice(i + 2, end)))
155      inWord = true
156      i = end
157    } else if (ch === '$' && command[i + 1] === '"') {
158      // `$"..."`: a double quote (bash translates it, and with no translation it is the text as it is).
159      continue
160    } else if (ch === '"') {
161      let j = i + 1
162      for (; j < command.length && command[j] !== '"'; j++) {
163        if (command[j] === '\\' && command[j + 1] === '\n') {
164          j++
165          continue
166        }
167        if (command[j] === '`' || (command[j] === '$' && command[j + 1] === '(')) {
168          j = substitution(j, true)
169          continue
170        }
171        if (command[j] === '\\' && j + 1 < command.length) j++
172        word += mask(command[j] as string)
173      }
174      inWord = true
175      i = j
176    } else if (ch === '\\' && command[i + 1] === '\n') {
177      // A line continuation: bash joins the two lines.
178      i++
179    } else if (ch === '\\' && i + 1 < command.length) {
180      word += mask(command[i + 1] as string)
181      inWord = true
182      i++
183    } else if (ch === '<' && command[i + 1] === '<' && command[i + 2] !== '<') {
184      endWord()
185      let j = i + 2
186      const dash = command[j] === '-'
187      if (dash) j++
188      while (command[j] === ' ' || command[j] === '\t') j++
189      let end = ''
190      for (; j < command.length && !/[\s;&|<>()]/.test(command[j] as string); j++) if (command[j] !== "'" && command[j] !== '"' && command[j] !== '\\') end += command[j]
191      if (end !== '') docs.push({ end, dash })
192      words.push('<<')
193      i = j - 1
194    } else if (ch === '>' || ch === '<') {
195      // A redirect: `>`, `>>`, `>|`, `&>`, `2>`, `>&`, `<>`. A file descriptor number before it belongs to it.
196      if (/^\d+$/.test(word)) {
197        word = ''
198        inWord = false
199      }
200      endWord()
201      let op = ch
202      while (i + 1 < command.length && (command[i + 1] === '>' || command[i + 1] === '|' || command[i + 1] === '&')) op += command[++i]
203      words.push(op)
204    } else if (/\s/.test(ch)) {
205      if (ch !== '\n') endWord()
206      else {
207        endStatement()
208        // Skip each here document's body, up to its end word.
209        for (const doc of docs.splice(0)) {
210          while (i < command.length) {
211            const next = command.indexOf('\n', i + 1)
212            const line = command.slice(i + 1, next < 0 ? command.length : next)
213            i = next < 0 ? command.length : next
214            if ((doc.dash ? line.replace(/^\t+/, '') : line) === doc.end) break
215          }
216        }
217      }
218    } else if (ch === '&' && command[i + 1] === '>') {
219      // `&>`: the redirect of both outputs; the `>` comes next.
220      endWord()
221    } else if (ch === '`' || (ch === '$' && command[i + 1] === '(')) {
222      i = substitution(i, false)
223    } else if (';&|()'.includes(ch)) {
224      endStatement()
225    } else {
226      word += ch
227      inWord = true
228    }
229  }
230  endStatement()
231  return [...out, ...inner]
232}
233
234// The text as statements of words, as bash reads its quotes (brace lists not expanded).
235export function statements(command: string): string[][] {
236  return tokens(command).map(st => st.map(unmask))
237}
238
239// Programs that write, remove or lock the files they name.
240const WRITERS = new Set(['rm', 'rmdir', 'unlink', 'shred', 'truncate', 'touch', 'chmod', 'chown', 'tee', 'mv', 'cp', 'install', 'ln', 'rsync'])
241// Every program whose words name what it writes: the writers, and sed and perl in place, and dd.
242const WRITER_NAMES = [...WRITERS, 'sed', 'perl', 'dd']
243// The ones whose last word is where they write.
244const TO_LAST = new Set(['cp', 'install', 'ln', 'rsync'])
245// The ones that take the folder they write into as `-t DIR`.
246const TARGET_DIR = new Set(['cp', 'mv', 'install', 'ln'])
247// A word that sets a variable (`NAME=value`, or `NAME+=value`, which appends and sets an unset one).
248const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*\+?=/
249
250// A word's program name: its last path segment (`/usr/bin/env` is env).
251const base = (word: string): string => word.split('/').pop() ?? ''
252
253// A (masked) glob as a regular expression, and how much literal text it has: a plain character, or a bracket set
254// that lists characters (`[g]`, `[gG]`); a negated set or a class (`[!x]`, `[[:alpha:]]`) is no literal text.
255function globRegex(b: string): { re: RegExp | null; literal: number } {
256  let re = ''
257  let literal = 0
258  for (let i = 0; i < b.length; i++) {
259    const c = b[i] as string
260    if (c === '*') re += '.*'
261    else if (c === '?') re += '.'
262    else if (c === '[' && bracketEnd(b, i) > 0) {
263      const close = bracketEnd(b, i)
264      const inner = b.slice(i + 1, close)
265      // A class (`[[:alpha:]]`), an equivalence class or a collating symbol in it: read as any one character.
266      if (/\[[:=.]/.test(inner)) re += '.'
267      else {
268        if (!/^[!^]/.test(inner)) literal++
269        re += `[${unmask(inner).replace(/^!/, '^').replace(/\\/g, '\\\\').replace(/\]/g, '\\]')}]`
270      }
271      i = close
272    } else {
273      literal++
274      re += unmask(c).replace(/[.*+?^${}()|\\[\]]/g, '\\$&')
275    }
276  }
277  try {
278    return { re: new RegExp(`^${re}$`, 'i'), literal }
279  } catch {
280    return { re: null, literal }
281  }
282}
283
284const isGlob = (masked: string): boolean => /[*?]|\[.*\]/.test(masked)
285
286// Whether a (masked) word can name the program `name`: its last segment is the name without regard to case, or an
287// unquoted glob with some literal text that matches it (`gi[t]`, `[g][i][t]`, `scripts/tempe?`). A glob of no literal
288// text (`*`, `[[:alpha:]]*`) names no program here.
289function nameIs(word: string, name: string): boolean {
290  const b = base(word)
291  if (!/[*?[]/.test(b)) return unmask(b).toLowerCase() === name
292  const g = globRegex(b)
293  return g.literal > 0 && g.re !== null && g.re.test(name)
294}
295
296// Whether an unquoted glob word of a call (masked) could expand to `word`: bash expands it to a file's name when one
297// matches, so `o?erride` is `override` once a file of that name exists.
298export function globCould(masked: string, word: string): boolean {
299  if (!isGlob(masked)) return false
300  const g = globRegex(masked)
301  return g.re === null || g.re.test(word)
302}
303
304// Where the bracket expression that opens at `i` closes, or -1: a `]` first in it (after any `!` or `^`) is one of its
305// characters, and so is a `]` inside `[:...:]`, `[=...=]` or `[. ... .]`.
306function bracketEnd(b: string, i: number): number {
307  let j = i + 1
308  if (b[j] === '!' || b[j] === '^') j++
309  if (b[j] === ']') j++
310  for (; j < b.length; j++) {
311    const kind = b[j] === '[' ? b[j + 1] : undefined
312    if (kind === ':' || kind === '=' || kind === '.') {
313      const end = b.indexOf(`${kind}]`, j + 2)
314      if (end < 0) return -1
315      j = end + 1
316    } else if (b[j] === ']') return j
317  }
318  return -1
319}
320
321// The temper script: a word naming it that sets no variable.
322const isScript = (word: string): boolean => !ASSIGNMENT.test(unmask(word)) && nameIs(word, 'temper')
323
324// Where a program the guard reads may run in a statement: every word that names it. Bash runs a program after
325// `VAR=value` words, after a keyword (`then`, `do`, `{`, `!`, `coproc`, `function f {`), and after a program that runs
326// the words that follow (`env`, `timeout 5`, `sudo -D /x`, `exec -a x`, `flock f`, a full path to one); no list of
327// these is ever whole, so each word that names the program is read as where it starts. The price: a statement that
328// only names such a command as words (`echo rm .temper/gates.json`) is read as running it.
329function starts(words: readonly string[], named: (word: string) => boolean): number[] {
330  const at: number[] = []
331  for (let i = 0; i < words.length; i++) if (named(words[i] as string)) at.push(i)
332  return at
333}
334
335// More words than one word of a command may expand to before the guard stops reading it.
336const BRACE_CAP = 1024
337
338// The first brace list bash expands in a word: the text before it, its words (`{a,b}`, or a sequence `{1..3}`,
339// `{a..c}`, `{1..9..2}`) and the text after it. A `{` with no list or sequence in it, or one of `${`, stays as it is.
340function braceList(w: string): { pre: string; alts: string[]; post: string } | null {
341  for (let i = 0; i < w.length; i++) {
342    if (w[i] !== '{' || w[i - 1] === '$') continue
343    let depth = 0
344    let end = -1
345    const commas: number[] = []
346    for (let j = i; j < w.length && end < 0; j++) {
347      if (w[j] === '{') depth++
348      else if (w[j] === '}' && --depth === 0) end = j
349      else if (w[j] === ',' && depth === 1) commas.push(j)
350    }
351    if (end < 0) continue
352    let alts: string[] | null = null
353    if (commas.length > 0) {
354      alts = []
355      let from = i + 1
356      for (const c of commas) {
357        alts.push(w.slice(from, c))
358        from = c + 1
359      }
360      alts.push(w.slice(from, end))
361    } else alts = sequence(w.slice(i + 1, end))
362    if (alts !== null) return { pre: w.slice(0, i), alts, post: w.slice(end + 1) }
363  }
364  return null
365}
366
367// The words of a sequence `x..y` or `x..y..step` (two integers, or two letters), at most one more than the cap; null when
368// the text is no sequence. Integers keep the width of a bound written with a leading zero (`{08..10}`).
369function sequence(text: string): string[] | null {
370  const num = /^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/.exec(text)
371  const chr = /^([A-Za-z])\.\.([A-Za-z])(?:\.\.(-?\d+))?$/.exec(text)
372  const m = num ?? chr
373  if (m === null) return null
374  const from = num !== null ? Number(m[1]) : (m[1] as string).charCodeAt(0)
375  const to = num !== null ? Number(m[2]) : (m[2] as string).charCodeAt(0)
376  const step = Math.abs(Number(m[3] ?? 1)) || 1
377  const padded = num !== null && [m[1], m[2]].some(b => /^-?0\d/.test(b as string))
378  const width = padded ? Math.max((m[1] as string).length, (m[2] as string).length) : 0
379  const out: string[] = []
380  for (let v = from; (from <= to ? v <= to : v >= to) && out.length <= BRACE_CAP; v += from <= to ? step : -step) {
381    out.push(num !== null ? (v < 0 ? '-' + String(-v).padStart(width - 1, '0') : String(v).padStart(width, '0')) : String.fromCharCode(v))
382  }
383  return out
384}
385
386// A word as bash expands its brace lists, each word as many times as bash gives it (`-m {-n,-n}` is `-m -n -n`); null
387// when it expands to more than the cap.
388function braces(word: string): string[] | null {
389  const out: string[] = []
390  let steps = 0
391  const expand = (w: string): boolean => {
392    if (++steps > BRACE_CAP * 8) return false
393    const list = braceList(w)
394    if (list === null) {
395      out.push(w)
396      return out.length <= BRACE_CAP
397    }
398    return list.alts.every(alt => expand(`${list.pre}${alt}${list.post}`))
399  }
400  return expand(word) ? out : null
401}
402
403type Written = { writes: string[]; targets: string[]; landings: string[] }
404
405// The paths a statement writes: a redirect's target, and the files a writing program names. `plain` are the words,
406// `masked` the same words with their quoted characters masked (to tell what names a program), and `known` says whether
407// the guard read a word whole (a word past the cap is not).
408function written(plain: string[], masked: string[], known: (word: string) => void): Written {
409  const out: Written = { writes: [], targets: [], landings: [] }
410  for (let i = 0; i < plain.length; i++) {
411    const op = plain[i] as string
412    const to = plain[i + 1]
413    if (to === undefined) continue
414    // `>`, `>>`, `>|` and `<>` write their file; `>&` and `>>&` write a file unless they name a file descriptor (`2>&1`).
415    if (/^(?:>[>|]?|<>)$/.test(op) || (/^>>?&$/.test(op) && !/^(?:\d+|-)$/.test(to))) {
416      known(to)
417      out.writes.push(to)
418    }
419  }
420  for (let i = 0; i < masked.length; i++) {
421    const cmd = WRITER_NAMES.find(n => nameIs(masked[i] as string, n))
422    if (cmd === undefined) continue
423    const w = programWrites(plain, i, cmd, known)
424    out.writes.push(...w.writes)
425    out.targets.push(...w.targets)
426    out.landings.push(...w.landings)
427  }
428  return out
429}
430
431const lastName = (path: string): string => path.replace(/\/+$/, '').split('/').pop() ?? path
432
433// The files the writing program `cmd` at `at` names.
434function programWrites(words: string[], at: number, cmd: string, known: (word: string) => void): Written {
435  const out: Written = { writes: [], targets: [], landings: [] }
436  const edits = cmd === 'sed' || cmd === 'perl'
437  // The program's file words: no flag, no redirect and its file, and for sed and perl no script (`-e x`, or sed's
438  // first word when no -e names the script).
439  const args: string[] = []
440  let script = false
441  // `cp -t DIR SRC...` (also mv, install, ln): the files land in DIR.
442  let into: string | null = null
443  // `cp -T`, `mv --no-target-directory`: the last word is the file itself, never a folder to land in.
444  let noTarget = false
445  for (let i = at + 1; i < words.length; i++) {
446    const w = words[i] as string
447    const cluster = /^-([A-Za-su-z]*)t(.*)$/.exec(w)
448    const long = w.startsWith('--t') && '--target-directory'.startsWith(w.split('=')[0] as string)
449    if (/^[<>]/.test(w)) i++
450    // `-t DIR`, `-at DIR`, `-tDIR`, `--target-directory DIR`, `--target=DIR` (git and coreutils take an abbreviation).
451    else if (TARGET_DIR.has(cmd) && cluster !== null) into = cluster[2] !== '' ? (cluster[2] as string) : (words[++i] ?? null)
452    else if (TARGET_DIR.has(cmd) && long) into = w.includes('=') ? w.slice(w.indexOf('=') + 1) : (words[++i] ?? null)
453    else if (edits && ['-e', '-f', '--expression', '--file'].includes(w)) {
454      script = true
455      i++
456    } else if (edits && (/^--(?:expression|file)=/.test(w) || /^-[A-Za-z]*e./.test(w))) {
457      // The script in the same word: `--expression=s/a/b/`, `-es/a/b/`.
458      script = true
459    } else if (edits && /^-[A-Za-z]*e$/.test(w)) {
460      script = true
461      i++
462    } else if (!w.startsWith('-')) {
463      known(w)
464      args.push(w)
465    } else if (/^-[A-Za-z]*T[A-Za-z]*$/.test(w) || w === '--no-target-directory') noTarget = true
466  }
467  if (cmd === 'sed' && !script) args.shift()
468  const flags = words.slice(at + 1).filter(w => w.startsWith('-'))
469  // `cp --parents a/b DIR` and `rsync -R a/b DIR` keep each source's path under DIR (`DIR/a/b`).
470  const keepPath = (cmd === 'cp' && flags.includes('--parents')) || (cmd === 'rsync' && flags.some(f => f === '--relative' || /^-[A-Za-z]*R/.test(f)))
471  const land = (dir: string, a: string): string => `${dir.replace(/\/+$/, '')}/${keepPath ? a.replace(/^(?:\/|\.\/)+/, '') : lastName(a)}`
472  // `rsync --remove-source-files` removes what it copied.
473  if (cmd === 'rsync' && flags.includes('--remove-source-files')) out.writes.push(...args.slice(0, -1))
474  if (into !== null) {
475    known(into)
476    const dir = into
477    out.writes.push(...(cmd === 'mv' ? args : []), ...args.map(a => land(dir, a)))
478    return out
479  }
480  if (WRITERS.has(cmd)) {
481    // A copy, move or link into a folder (`cp a .temper/specs/pw/`): the files land in it, and it is not replaced. Its
482    // last word is a target, not a write, so that another statement's write of the same path is still read as one. rsync
483    // with a source that ends in `/` copies that folder's files, whose names the guard does not know, and so does the cp of
484    // macOS and the BSDs (`cp -R dir/ .temper/`).
485    const contents = (cmd === 'rsync' || cmd === 'cp') && args.slice(0, -1).some(a => a.endsWith('/'))
486    const sources = cmd === 'mv' ? args.slice(0, -1) : []
487    if ((TO_LAST.has(cmd) || cmd === 'mv') && args.length >= 2 && !noTarget && !contents) {
488      const target = args[args.length - 1] as string
489      out.writes.push(...sources)
490      out.targets.push(target)
491      out.landings.push(...args.slice(0, -1).map(a => land(target, a)))
492    } else out.writes.push(...(TO_LAST.has(cmd) ? args.slice(-1) : args))
493    return out
494  }
495  // sed -i, perl -i: they rewrite the files they are given.
496  if (edits && words.slice(at + 1).some(w => /^-[A-Za-z]*i/.test(w) || w === '--in-place' || w.startsWith('--in-place='))) out.writes.push(...args)
497  else if (cmd === 'dd') out.writes.push(...args.filter(a => a.startsWith('of=')).map(a => a.slice(3)))
498  return out
499}
500
501// The git command that starts at `at`: its subcommand, the words after it, and git's own options before it.
502function gitParts(words: string[], at: number): { sub: string; rest: string[]; opts: string[] } {
503  const opts: string[] = []
504  let i = at + 1
505  for (; i < words.length; i++) {
506    const w = words[i] as string
507    if (['-c', '-C', '--git-dir', '--work-tree', '--config-env', '--namespace'].includes(w)) {
508      opts.push(w, words[i + 1] ?? '')
509      i++
510    } else if (w.startsWith('-')) opts.push(w)
511    else break
512  }
513  return { sub: words[i] ?? '', rest: words.slice(i + 1), opts }
514}
515
516const HOOKS_PATH = /core\.hookspath/i
517// A config key that loads another config file, which can set core.hooksPath.
518const INCLUDE = /^include(?:if\..*)?\.path$/i
519// A git alias: its body runs as a git command (or, after `!`, as a shell command).
520const ALIAS = /^alias\.[^=]+$/i
521
522// `git commit` with `--no-verify` or `-n`. In a cluster of short flags a letter that takes a value (`-m`, `-F`, `-C`,
523// `-c`, `-t`) takes the rest of the cluster, or the next word.
524function skipsHook(args: string[]): boolean {
525  for (let i = 0; i < args.length; i++) {
526    const w = args[i] as string
527    // git takes an unambiguous abbreviation of a long option: `--no-veri` and `--no-verif` are `--no-verify`.
528    if (/^--no-veri(?:fy?)?$/.test(w)) return true
529    if (w === '--') return false
530    if (!/^-[A-Za-z]+$/.test(w)) continue
531    for (let k = 1; k < w.length; k++) {
532      const letter = w[k] as string
533      if (letter === 'n') return true
534      if ('mFCct'.includes(letter)) {
535        if (k === w.length - 1) i++
536        break
537      }
538    }
539  }
540  return false
541}
542
543// What a git alias body does, read as the command it runs, added to `read`.
544function aliasBody(read: ShellRead, body: string): void {
545  const text = body.trim()
546  const sub = readShell(text.startsWith('!') ? text.slice(1) : `git ${text}`)
547  read.noVerify ||= sub.noVerify
548  read.hooksPath ||= sub.hooksPath
549  read.tooMany ||= sub.tooMany
550  read.globWords.push(...sub.globWords)
551  read.calls.push(...sub.calls)
552  read.writes.push(...sub.writes)
553  read.targets.push(...sub.targets)
554  read.landings.push(...sub.landings)
555}
556
557// One config pair handed to git for this call (`-c key=value`, `--config-env key=VAR`): a hooks path, an included file
558// or an alias. `known`: the value is in the text (an environment variable's value is not).
559function configPair(read: ShellRead, pair: string, known: boolean): void {
560  const eq = pair.indexOf('=')
561  const key = eq < 0 ? pair : pair.slice(0, eq)
562  if (HOOKS_PATH.test(key) || INCLUDE.test(key)) read.hooksPath = true
563  if (ALIAS.test(key)) {
564    if (!known) read.hooksPath = true
565    else aliasBody(read, eq < 0 ? '' : pair.slice(eq + 1))
566  }
567}
568
569export function readShell(command: string): ShellRead {
570  const read: ShellRead = { calls: [], noVerify: false, hooksPath: false, writes: [], targets: [], landings: [], tooMany: false, globWords: [] }
571  // git reads the config of the home folder it is given (`HOME=/tmp/h git ci`, `$XDG_CONFIG_HOME/git/config`), which
572  // can hold an alias or a hooks path.
573  let home = false
574  let runsGit = false
575  for (const raw of tokens(command)) {
576    // Every word as bash expands its brace lists, so no list hides a program, a call or a path (`{git,commit}`). A word
577    // past the cap is read as it is: it is refused when it holds a list of words (which could name a program) or when
578    // it is a path a program writes.
579    const masked: string[] = []
580    const over = new Set<string>()
581    for (const w of raw) {
582      const all = braces(w)
583      if (all !== null) masked.push(...all)
584      else {
585        masked.push(w)
586        over.add(unmask(w))
587        if (/\{[^{}]*,/.test(w)) read.tooMany = true
588      }
589    }
590    const words = masked.map(unmask)
591    const w = written(words, masked, word => {
592      if (over.has(word)) read.tooMany = true
593    })
594    read.writes.push(...w.writes)
595    read.targets.push(...w.targets)
596    read.landings.push(...w.landings)
597    // A variable set to name core.hooksPath, before git or in a statement of its own (`export GIT_CONFIG_KEY_0=...`):
598    // git reads its config from the environment it is given. Also a config file, an included file or an alias handed
599    // to git that way.
600    for (const x of words) {
601      if (!ASSIGNMENT.test(x)) continue
602      if (/^(?:HOME|XDG_CONFIG_HOME)\+?=/.test(x)) home = true
603      if (HOOKS_PATH.test(x)) read.hooksPath = true
604      if (/^GIT_CONFIG(?:_[A-Z0-9_]*)?\+?=/i.test(x) && /include(?:if\.[^=\s]*)?\.path|alias\.|^GIT_CONFIG(?:_GLOBAL|_SYSTEM)?\+?=/i.test(x)) read.hooksPath = true
605    }
606    for (const gitAt of starts(masked, x => nameIs(x, 'git'))) {
607      runsGit = true
608      const git = gitParts(words, gitAt)
609      // `git -c core.hooksPath=...`, `git -c include.path=...`, `git -c alias.x=...`, `git --config-env ...`.
610      if (git.opts.some(o => HOOKS_PATH.test(o))) read.hooksPath = true
611      git.opts.forEach((o, i) => {
612        if (o === '-c') configPair(read, git.opts[i + 1] ?? '', true)
613        else if (o === '--config-env') configPair(read, git.opts[i + 1] ?? '', false)
614        else if (o.startsWith('--config-env=')) configPair(read, o.slice('--config-env='.length), false)
615      })
616      if (git.sub === 'commit' && skipsHook(git.rest)) read.noVerify = true
617      if (git.sub === 'config') {
618        const at = git.rest.findIndex(x => HOOKS_PATH.test(x))
619        const reads = git.rest.some(x => ['--get', '--get-all', '--get-regexp', '--list', '-l'].includes(x))
620        // `git config core.hooksPath` with no value reads it; with a value, or with --unset, it changes it.
621        if (at >= 0 && !reads && (git.rest[at + 1] !== undefined || git.rest.some(x => x.startsWith('--unset') || x === '--replace-all' || x === '--add'))) read.hooksPath = true
622        // Removing or renaming the core section drops core.hooksPath with it (also git 2.46's `git config remove-section`).
623        const section = git.rest.findIndex(x => ['--remove-section', '--rename-section', 'remove-section', 'rename-section'].includes(x))
624        if (section >= 0 && (git.rest.slice(section + 1).find(x => !x.startsWith('-')) ?? '').toLowerCase() === 'core') read.hooksPath = true
625        // git 2.46's `git config unset core.hooksPath`.
626        if (at >= 0 && !reads && git.rest.slice(0, at).includes('unset')) read.hooksPath = true
627        // A config file included from the repository's config can set core.hooksPath (include.path, includeIf.*.path).
628        const include = git.rest.findIndex(x => INCLUDE.test(x))
629        if (include >= 0 && !reads && git.rest.slice(include + 1).some(x => !x.startsWith('-'))) read.hooksPath = true
630        // An alias written into the config runs its body later: read the body as the command it is.
631        const alias = git.rest.findIndex(x => ALIAS.test(x))
632        if (alias >= 0 && !reads && git.rest[alias + 1] !== undefined) aliasBody(read, git.rest[alias + 1] as string)
633      }
634    }
635    // Every word that names the script starts a call: the words after it are the call's.
636    for (let i = 0; i < masked.length; i++) {
637      if (!isScript(masked[i] as string)) continue
638      read.calls.push(words.slice(i + 1))
639      const rest = masked.slice(i + 1)
640      read.globWords.push(rest.filter((x, k) => isGlob(x) && !x.startsWith('--reason=') && rest[k - 1] !== '--reason'))
641    }
642  }
643  if (home && runsGit) read.hooksPath = true
644  return read
645}
646
647// A call's words with its leading flags left out (`--spec-path X` takes a value).
648export function callWords(words: readonly string[]): string[] {
649  let i = 0
650  while (i < words.length && (words[i] as string).startsWith('-')) i += words[i] === '--spec-path' ? 2 : 1
651  return words.slice(i)
652}
653
654// Whether `words` are the call the CLI wrote in `written` (a command line it printed), word for word. A placeholder in
655// braces (`{reason}`) stands for one word that is not empty.
656export function sameCall(written: string, words: readonly string[]): boolean {
657  const st = tokens(written)[0] ?? []
658  const at = st.findIndex(isScript)
659  if (at < 0) return false
660  const want = callWords(st.slice(at + 1).map(unmask))
661  const have = callWords(words)
662  return want.length === have.length && want.every((w, i) => (/^\{[^{}]*\}$/.test(w) ? (have[i] ?? '') !== '' : w === have[i]))
663}
664
hooks/temper-mod/core/section.ts 44 lines
1// The text of the `temper:phase` system prompt section. Pure: the adapter appends the returned text as a session scope
2// section on every request. One flow in every mode (ADR 0012, ADR 0013): `temper next --json` says what comes next, and
3// Claude asks every gate exactly as it gives the question.
4
5import { stageLabel } from './stages'
6import { nextStep } from './view'
7import type { View } from './view'
8
9export const SECTION_ID = 'temper:phase'
10
11// What a message from the user at a gate means: the gate's "Other" choice. Also in commands/temper.md.
12export const GATE_MESSAGE = 'If the user writes a message at a gate, answer it. If it asks for a change, make the change, run the gate again, then ask the gate question again.'
13
14export type SectionInput = {
15  enforcement: 'on' | 'off'
16  // The run's view; null when no /temper run is active.
17  view: View | null
18  // The line that says the mod cannot read the run as it should.
19  line?: string | null
20}
21
22export function sectionText(input: SectionInput): string {
23  const lines: string[] = [input.enforcement === 'on' ? 'Temper enforcement: active' : 'Temper enforcement: off (UI only)']
24  const v = input.view
25  if (v === null || v.stage === null) {
26    lines.push('Phase: none. No Temper run is active.')
27    if (input.line) lines.push(input.line)
28    return lines.join('\n')
29  }
30  let phase = `Phase: ${v.stage === 'commit' ? 'Done' : stageLabel(v.stage)}`
31  if (v.wait === 'saved') phase += ' (saved for later)'
32  if (v.title) phase += ` · Intent: "${v.title}"`
33  lines.push(phase)
34  if (v.total > 0) {
35    const ids = v.criteria.filter(c => c.status === 'passed').map(c => c.id)
36    lines.push(`Criteria: ${v.passed} of ${v.total} passed${ids.length > 0 ? ` (${ids.join(', ')})` : ''}`)
37  }
38  const next = nextStep(v)
39  if (next) lines.push(`Next: ${next}`)
40  if (input.line) lines.push(input.line)
41  lines.push(GATE_MESSAGE)
42  return lines.join('\n')
43}
44
hooks/temper-mod/core/view.ts 302 lines
1// The view model: what the bar, the pane, the spinner, the hint, the question header and the system prompt show, made
2// once from view.json (the CLI's) and the person's decisions (the mod's), so each drawing is a plain function of plain
3// data (ADR 0013). It holds no button that decides: the person decides in the question dialog. Pure and JSON safe: it is
4// mirrored into `$.state`, which survives reload and compaction.
5
6import type { Decision } from './decisions'
7import { describe } from './decisions'
8import type { RunView } from './runview'
9import type { Stage } from './stages'
10import { cliStage, isStage, stageLabel } from './stages'
11
12// How a stage stands on the timeline: its check passed, failed, or the person skipped it; the run is at it; or it is
13// still to come.
14export type Mark = 'passed' | 'failed' | 'skipped' | 'current' | 'pending'
15
16export type StageView = { id: Stage; label: string; mark: Mark; failed: boolean; skip: string | null }
17
18// What the run waits for at its current stage:
19//  gate    the question is out: the person answers it
20//  chosen  the person chose; Claude carries it out
21//  saved   the person saved the run for later
22//  work    the stage is being worked
23//  armed   an armed autonomous run goes on by itself
24//  done    every gate is behind the run: Commit is next
25export type Wait = 'gate' | 'chosen' | 'saved' | 'work' | 'armed' | 'done'
26
27export type TaskCell = { n: number; title: string; state: 'waiting' | 'running' | 'passed' | 'failed' | 'parked'; model: string | null; attempt: number | null }
28
29export type GroupRow = { id: string; title: string; state: 'waiting' | 'running' | 'passed' | 'parked'; tasks: TaskCell[] }
30
31// A task in the Build grid: its state as the CLI's ledger shows it (RED and GREEN from the task's own evidence), the
32// model it ran on, and how many times it ran again.
33export type GridTask = { n: number; title: string; state: 'waiting' | 'running' | 'red' | 'green' | 'pass' | 'fail' | 'parked'; model: string | null; retries: number }
34
35export type GridGroup = { id: string; title: string; status: string; tasks: GridTask[] }
36
37// A loop back on the timeline, with the reason the person (or the armed run) gave.
38export type LoopMark = { from: string; to: string; iteration: number; max: number; reason: string }
39
40export type FindingRow = { id: number; severity: string; confidence: number | null; where: string | null; claim: string; state: 'open' | 'resolved' | 'accepted' }
41
42export type Marker = { name: string; state: 'pass' | 'fail' | 'info' | 'none'; detail: string; lines: string[] }
43
44export type View = {
45  title: string | null
46  stage: Stage | null
47  enforcement: 'on' | 'off'
48  stages: StageView[]
49  wait: Wait | null
50  // One plain sentence: where the run is and what it waits for.
51  status: string
52  // The lines under it, for the current stage: the groups in Build, the findings in Review, the failed checks.
53  detail: string[]
54  // The failed checks of the current stage's gate, for the pane.
55  failedChecks: Array<{ name: string; detail: string }>
56  groups: GroupRow[] | null
57  findings: Array<{ id: string; severity: string; claim: string }>
58  criteria: Array<{ id: string; text: string; status: 'passed' | 'open'; priority: string; evidence: string[] }>
59  passed: number
60  total: number
61  // Minutes from the run's start to its last change (null when not known).
62  clock: { minutes: number | null }
63  loopMarks: LoopMark[]
64  // The plan's files by Build group (approved: as the person approved them at the plan gate); null with no plan.
65  planTree: { approved: boolean; groups: Array<{ id: string; title: string; files: string[] }>; other: string[] } | null
66  // Build, a cell per task; null with no grouped tasks.
67  grid: GridGroup[] | null
68  // Every Review finding, open, resolved or accepted.
69  findingRows: FindingRow[]
70  // The five Check markers: compile, tests, coverage, lint, security.
71  markers: Marker[]
72  // The person's decisions in this run, as sentences, oldest first.
73  decisions: string[]
74  // The loops of the run with their budget: "Review to Build: 1 of 2".
75  loops: string[]
76  // The one line that says the mod cannot read the run as it should; null when all is well.
77  line: string | null
78  // What `temper next` does now (the system prompt names it).
79  next: { action: string; say: string; header: string | null }
80  paneOpen: boolean
81}
82
83export type ViewInput = {
84  view: RunView
85  // The person's decisions in this run, and the latest gate answer at the CLI's step.
86  decisions: readonly Decision[]
87  answer: Extract<Decision, { kind: 'gate' }> | null
88  enforcement: 'on' | 'off'
89  line?: string | null
90  paneOpen?: boolean
91}
92
93const MARKS: Record<string, Mark> = { passed: 'passed', failed: 'failed', skipped: 'skipped', here: 'current', todo: 'pending' }
94
95const TASK_CELL: Record<string, TaskCell['state']> = { waiting: 'waiting', running: 'running', red: 'running', green: 'running', pass: 'passed', fail: 'failed', parked: 'parked' }
96
97function groupsOf(rv: RunView): GroupRow[] | null {
98  if (rv.build.groups.length === 0) return null
99  return rv.build.groups.map(g => {
100    const tasks = g.tasks.map(t => ({ n: t.n, title: t.title, state: TASK_CELL[t.state] ?? 'waiting', model: t.model, attempt: t.attempts > 0 ? t.attempts : null }))
101    const state: GroupRow['state'] = g.status === 'parked' ? 'parked' : g.status === 'passed' || g.status === 'merged' ? 'passed' : tasks.some(t => t.state !== 'waiting') ? 'running' : 'waiting'
102    return { id: g.id, title: g.title, state, tasks }
103  })
104}
105
106const TASK_GLYPH: Record<string, string> = { waiting: '○', running: '◐', passed: '✓', failed: '✗', parked: '⏸' }
107
108// One line a group in Build: "G2 Payments  ✓1 ✓2 ◐3 ○4".
109export function groupLine(g: GroupRow): string {
110  const tasks = g.tasks.map(t => `${TASK_GLYPH[t.state] ?? '○'}${t.n}`).join(' ')
111  const state = g.state === 'parked' ? ' (parked)' : g.state === 'passed' ? ' (passed)' : ''
112  return `${g.id}${g.title ? ` ${g.title}` : ''}${state}  ${tasks}`
113}
114
115function waitOf(input: ViewInput, stage: Stage | null): Wait | null {
116  const rv = input.view
117  if (stage === null) return null
118  if (stage === 'commit' && rv.next.action !== 'ask') return 'done'
119  if (input.answer?.move === 'pause') return 'saved'
120  if (input.answer !== null) return 'chosen'
121  if (rv.next.action === 'auto' || rv.guard?.armed === true) return 'armed'
122  return rv.next.action === 'ask' ? 'gate' : 'work'
123}
124
125function statusOf(input: ViewInput, stage: Stage | null, wait: Wait | null): string {
126  if (stage === null) return ''
127  const label = stageLabel(stage)
128  if (wait === 'saved') return `${label} is saved for later. Type /temper:temper when you are ready.`
129  if (wait === 'chosen' && input.answer !== null) return `${label}: your choice (${input.answer.label}). Claude carries it out.`
130  return input.view.status
131}
132
133function detailOf(rv: RunView, stage: Stage | null, groups: GroupRow[] | null, failed: ReadonlyArray<{ name: string }>): string[] {
134  if (stage === null) return []
135  const out: string[] = []
136  if (stage === 'build' && groups !== null) {
137    const done = groups.reduce((n, g) => n + g.tasks.filter(t => t.state === 'passed').length, 0)
138    const all = groups.reduce((n, g) => n + g.tasks.length, 0)
139    out.push(`Tasks: ${done} of ${all} done`)
140    for (const g of groups) out.push(groupLine(g))
141  }
142  if (stage === 'review') {
143    const open = rv.findings.filter(f => f.state === 'open')
144    const by = new Map<string, number>()
145    for (const f of open) by.set(f.severity, (by.get(f.severity) ?? 0) + 1)
146    out.push(open.length === 0 ? 'No open findings.' : `Open findings: ${[...by.entries()].map(([s, n]) => `${n} ${s}`).join(', ')}`)
147  }
148  if (failed.length > 0) out.push(`Failed: ${failed.map(q => q.name).join(', ')}`)
149  return out
150}
151
152export function buildView(input: ViewInput): View {
153  const rv = input.view
154  const stage = cliStage(rv.run?.stage ?? null)
155  const wait = waitOf(input, stage)
156  const here = rv.stages.find(s => s.mark === 'here')
157  const failed = here?.failed ?? []
158  const groups = groupsOf(rv)
159  const criteria = rv.criteria.map(c => ({ id: c.id, text: c.text || c.id, status: c.status === 'passed' ? ('passed' as const) : ('open' as const), priority: c.priority, evidence: c.evidence }))
160  return {
161    title: rv.run?.title ?? null,
162    stage,
163    enforcement: input.enforcement,
164    stages: rv.stages
165      .filter((s): s is typeof s & { id: Stage } => isStage(s.id))
166      .map(s => ({ id: s.id, label: s.label || stageLabel(s.id), mark: MARKS[s.mark] ?? 'pending', failed: s.verdict === 'FAIL', skip: s.skipped?.reason ?? null })),
167    wait,
168    status: statusOf(input, stage, wait),
169    detail: detailOf(rv, stage, groups, failed),
170    failedChecks: failed.map(q => ({ name: q.name, detail: q.detail })),
171    groups,
172    findings: rv.findings.filter(f => f.state === 'open').map(f => ({ id: String(f.id), severity: f.severity, claim: f.claim })),
173    criteria,
174    passed: criteria.filter(c => c.status === 'passed').length,
175    total: criteria.length,
176    decisions: input.decisions.map(describe),
177    loops: rv.loops.map(l => `${cap(l.from)} to ${cap(l.to)}: ${l.iteration} of ${l.max}${l.reason ? ` (${l.reason})` : ''}`),
178    line: input.line ?? null,
179    next: { action: rv.next.action, say: rv.next.say, header: rv.ask?.question.header ?? null },
180    clock: { minutes: minutesOf(rv.time.started, rv.time.updated) },
181    loopMarks: rv.loops.map(l => ({ from: l.from, to: l.to, iteration: l.iteration, max: l.max, reason: l.reason })),
182    planTree: planTreeOf(rv),
183    grid: rv.build.groups.length === 0 ? null : rv.build.groups.map(g => ({ id: g.id, title: g.title, status: g.status, tasks: g.tasks.map(t => ({ n: t.n, title: t.title, state: t.state, model: t.model, retries: Math.max(t.attempts - 1, 0) })) })),
184    findingRows: rv.findings.map(f => ({ id: f.id, severity: f.severity, confidence: f.confidence, where: f.file ? `${f.file}:${f.line ?? ''}` : null, claim: f.file ? f.claim.replace(/^\s*\S+:\d+\s*/, '') : f.claim, state: f.state })),
185    markers: rv.markers.map(m => ({ name: m.name, state: m.state, detail: m.detail, lines: m.lines })),
186    paneOpen: input.paneOpen ?? false,
187  }
188}
189
190// Whole minutes between two ISO times; null when either does not read.
191function minutesOf(start: string | null, end: string | null): number | null {
192  const a = start ? Date.parse(start) : NaN
193  const b = end ? Date.parse(end) : NaN
194  return Number.isFinite(a) && Number.isFinite(b) && b >= a ? Math.floor((b - a) / 60000) : null
195}
196
197function planTreeOf(rv: RunView): View['planTree'] {
198  if (rv.plan.groups.length === 0 && rv.plan.files.length === 0) return null
199  const grouped = new Set(rv.plan.groups.flatMap(g => g.files))
200  return { approved: rv.plan.approved, groups: rv.plan.groups, other: rv.plan.files.filter(f => !grouped.has(f)) }
201}
202
203// "42 min": the band's measure of the run; null when it is not known.
204export function clockText(v: View): string | null {
205  if (v.clock.minutes === null) return null
206  return v.clock.minutes >= 60 ? `${Math.floor(v.clock.minutes / 60)} h ${v.clock.minutes % 60} min` : `${v.clock.minutes} min`
207}
208
209// "↺ Review to Build (1 of 2): a real bug": a loop on the timeline.
210export const loopText = (l: LoopMark): string => `↺ ${cap(l.from)} to ${cap(l.to)} (${l.iteration} of ${l.max})${l.reason ? `: ${l.reason}` : ''}`
211
212// The cell of a task in the Build grid: its glyph and its word.
213export const TASK_STATE: Record<GridTask['state'], [string, string]> = {
214  waiting: ['○', 'waiting'],
215  running: ['◐', 'running'],
216  red: ['●', 'RED'],
217  green: ['●', 'GREEN'],
218  pass: ['✓', 'PASS'],
219  fail: ['✗', 'FAIL'],
220  parked: ['⏸', 'parked'],
221}
222
223const cap = (s: string): string => `${s.charAt(0).toUpperCase()}${s.slice(1)}`
224
225// The glyph for each mark on the timeline. The current stage is a filled circle; a failed check is a cross.
226export const MARK: Record<Mark, string> = { passed: '✓', failed: '✗', skipped: '↷', current: '●', pending: '○' }
227
228export const LEGEND = '✓ passed  ✗ failed  ↷ skipped  ● here  ○ to come'
229
230// "Step 4 of 7: Build" (the run's own stages, Design only when it has one).
231export function whereText(v: View): string {
232  if (v.stage === null) return ''
233  if (v.stage === 'commit') return 'Done'
234  const at = v.stages.findIndex(s => s.id === v.stage)
235  return `Step ${at + 1} of ${v.stages.length}: ${stageLabel(v.stage)}`
236}
237
238const VERB: Record<Stage, string> = {
239  intent: 'Capturing intent',
240  plan: 'Planning',
241  design: 'Designing',
242  build: 'Building',
243  review: 'Reviewing',
244  check: 'Checking',
245  commit: 'Committing',
246}
247
248// "Building · criterion 2 of 5": the criterion being worked is the first not yet passed.
249export function spinnerWord(v: View): string | null {
250  if (v.stage === null) return null
251  const verb = VERB[v.stage]
252  if (v.total === 0) return verb
253  return `${verb} · criterion ${Math.min(v.passed + 1, v.total)} of ${v.total}`
254}
255
256// The dim line after the engine's prompt hint on the terminal.
257export function hintTail(v: View): string | null {
258  if (v.stage === null) return null
259  return v.stage === 'commit' ? 'Temper: the run is done.' : `Temper. ${whereText(v)}. ${v.status}`
260}
261
262// One dim line beneath an answer when a turn ends: "Build · 2 of 4 criteria met · next: Review".
263export function turnLine(v: View): string | null {
264  if (v.stage === null) return null
265  if (v.stage === 'commit') return 'Done · next: commit'
266  const parts = [stageLabel(v.stage)]
267  if (v.total > 0) parts.push(`${v.passed} of ${v.total} criteria met`)
268  const at = v.stages.findIndex(s => s.id === v.stage)
269  const next = v.stages[at + 1]
270  parts.push(`next: ${next ? next.label : 'Commit'}`)
271  return parts.join(' · ')
272}
273
274// One line above the engine's own question dialog.
275export function questionHeader(v: View): string | null {
276  if (v.stage === null || v.stage === 'commit') return null
277  return v.total > 0 ? `Temper: ${whereText(v)}, criterion ${Math.min(v.passed + 1, v.total)} of ${v.total}` : `Temper: ${whereText(v)}`
278}
279
280// The toast when the run reaches another stage: "Build is open." Null for no run.
281export function stageToast(stage: Stage | null): string | null {
282  if (stage === null) return null
283  return stage === 'commit' ? 'The run is done. Commit is next.' : `${stageLabel(stage)} is open.`
284}
285
286// What Claude does next, for the system prompt: what `temper next --json` says, in one line.
287export function nextStep(v: View): string {
288  if (v.stage === null) return ''
289  switch (v.wait) {
290    case 'saved':
291      return 'the user saved the run for later: do nothing for the run until the user takes it up again'
292    case 'chosen':
293      return 'the user answered the question: carry out the calls of that option, as `temper next --json` gave them'
294    case 'gate':
295      return `ask the \`${v.next.header ?? 'Temper gate'}\` question exactly as \`temper next --json\` gives it, then wait`
296    case 'armed':
297      return 'the run is armed: run the calls `temper next --json` gives, and never ask "Shall I...?"'
298    default:
299      return v.next.say ? `${v.next.say} Do what \`temper next --json\` says.` : 'do what `temper next --json` says'
300  }
301}
302
hooks/temper-mod/ui/hint.tsx 18 lines
1import type { RenderPropsOf } from 'claude-code'
2
3import { hintTail } from '../core/view'
4import type { View } from '../core/view'
5
6// Terminal only: the engine keeps its line (pills stay live) and draws `tail` dim at its
7// end. Other surfaces draw no tail, so the props pass through unchanged.
8export function hintProps(
9  props: RenderPropsOf['PromptHint'],
10  view: View,
11  surface: string,
12): RenderPropsOf['PromptHint'] | null {
13  if (surface !== 'terminal') return null
14  const tail = hintTail(view)
15  if (tail === null) return null
16  return { ...props, tail }
17}
18
hooks/temper-mod/ui/band.tsx 107 lines
1import type { RenderElement } from 'claude-code'
2
3import type { UiMode } from '../core/config'
4import { barStyle } from '../core/modes'
5import { MARK, clockText, loopText, whereText } from '../core/view'
6import type { StageView, View } from '../core/view'
7import type { Kit } from './kit'
8
9// Below this width the band uses its compact form: no borders, the stages as plain words. Nothing wraps into a mess.
10export const COMPACT_BELOW = 100
11
12// The most detail lines the band shows under the status (the pane shows them all).
13const MAX_DETAIL = 5
14
15const COLOR: Record<StageView['mark'], string | undefined> = { passed: 'green', failed: 'red', skipped: 'yellow', current: 'blue', pending: undefined }
16
17// One chip of the stage timeline: passed is green with a check, failed red with a cross, a skipped stage yellow, the
18// current stage a filled blue chip (red when its check failed), stages to come dim and outlined.
19function chip(kit: Kit, step: StageView, compact: boolean) {
20  const { Box, Text } = kit
21  const isCurrent = step.mark === 'current'
22  const bad = isCurrent && step.failed
23  const text = (
24    <Text bold={isCurrent} color={isCurrent ? 'white' : COLOR[step.mark]} dimColor={step.mark === 'pending'}>
25      {`${MARK[step.mark]} ${step.label}`}
26    </Text>
27  )
28  const fill = isCurrent ? (bad ? 'red' : 'blue') : undefined
29  if (compact) {
30    return (
31      <Box key={`stage-${step.id}`} paddingX={1} backgroundColor={fill}>
32        {text}
33      </Box>
34    )
35  }
36  return (
37    <Box key={`stage-${step.id}`} borderStyle="round" borderColor={fill ?? COLOR[step.mark] ?? 'gray'} borderDimColor={step.mark === 'pending'} backgroundColor={fill} paddingX={1}>
38      {text}
39    </Box>
40  )
41}
42
43// The band above the prompt. It has no button and decides nothing: the person decides in the `Temper gate` question,
44// and takes a run up again by typing /temper:temper. Full mode: TEMPER, the title, where the run is, its time,
45// the stage timeline with its loops back and their reasons, the status of the stage and its details (the groups in
46// Build, the findings in Review, the failed checks). Minimal draws the timeline only. Off draws nothing (the caller
47// passes next(e)).
48export function renderBand(kit: Kit, view: View, mode: UiMode, columns = 120): RenderElement | null {
49  const style = barStyle(mode)
50  if (style === 'none' || view.stage === null) return null
51  const { Box, Text } = kit
52  const compact = columns < COMPACT_BELOW
53
54  const chips = (
55    <Box flexDirection="row" columnGap={compact ? 0 : 1} flexWrap="wrap">
56      {view.stages.map(s => chip(kit, s, compact))}
57    </Box>
58  )
59
60  if (style === 'stages') {
61    return (
62      <Box flexDirection="row" columnGap={1} alignItems="center" key="temper-band">
63        <Text bold color="magenta">TEMPER</Text>
64        {chips}
65      </Box>
66    )
67  }
68
69  const head = (
70    <Box flexDirection="row" columnGap={1} key="row-head" flexWrap="wrap">
71      <Text bold color="magenta">TEMPER</Text>
72      {view.title ? <Text bold>{view.title}</Text> : null}
73      <Text dimColor>{`· ${whereText(view)}`}</Text>
74      {view.total > 0 ? <Text dimColor>{`· criteria ${view.passed} of ${view.total}`}</Text> : null}
75      {clockText(view) ? <Text dimColor>{`· ${clockText(view)}`}</Text> : null}
76      <Text dimColor={view.enforcement === 'on'} color={view.enforcement === 'on' ? undefined : 'yellow'}>{`· enforcement ${view.enforcement}`}</Text>
77    </Box>
78  )
79  const waiting = view.wait === 'gate' || view.wait === 'saved'
80  const status = (
81    <Text bold={waiting} color={waiting ? 'yellow' : undefined}>
82      {view.status}
83    </Text>
84  )
85  const detail = view.detail.slice(0, MAX_DETAIL)
86  const more = view.detail.length - detail.length
87  return (
88    <Box flexDirection="column" key="temper-band">
89      {head}
90      {chips}
91      {view.loopMarks.map((l, i) => (
92        <Text key={`loop-${i}`} color="cyan">
93          {loopText(l)}
94        </Text>
95      ))}
96      {status}
97      {detail.map((line, i) => (
98        <Text key={`detail-${i}`} dimColor>
99          {line}
100        </Text>
101      ))}
102      {more > 0 ? <Text dimColor>{`and ${more} more lines in the pane (/temper:temper pane)`}</Text> : null}
103      {view.line ? <Text color="yellow">{view.line}</Text> : null}
104    </Box>
105  )
106}
107