SLOPSHOPPER

dh

Portable AI-assisted development kit: coordinator plus specialist agents, skills and work commands with owner-authorized delivery.

guardcommandtoastpromptprocesstimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · dh
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────────╮ │ dh │ ⏺ Read(src/auth.ts) │ Coordinator: Write of a new file on │ ⎿ Read 6 lines │ /work/app/src/audit.ts. Dispatch a builder │ ⏺ Update(src/auth.ts) │ for work beyond a small correction (5 │ ⎿ Added 2 lines, removed 1 line ╰────────────────────────────────────────────╯ ⏺ Bash(bun test) ╭────────────────────────────────────────────╮ ⎿ 3 pass, 1 fail │ dh │ │ Coordinator: Write of a new file on │ ● Done. refresh now rejects expired claims and logs an audit event. │ /work/app/src/cache.ts. Dispatch a builder │ │ for work beyond a small correction (5 │ ✻ Worked for 42s · done 4:20 PM ╰────────────────────────────────────────────╯ › /dashboard ⎿ dh: dh dashboard exited 0 but printed no URL ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

dev-harness

English: README.en.md

O que é

Kit portátil de desenvolvimento assistido por IA, instalado como plugin do Claude Code: um Coordenador, agentes especialistas, skills e comandos /dh:<comando> que levam um pedido de ideia a entrega com revisão e verificação. Licença MIT.

Requisitos

Claude Code autenticado, com acesso a um modelo; Git.

Instalar

Dentro de uma sessão do Claude Code, no projeto em que você vai trabalhar. A forma por URL baixa só o marketplace.json, sem clonar o repositório:

/plugin marketplace add https://raw.githubusercontent.com/danielmalka/dev-harness/main/.claude-plugin/marketplace.json
/plugin install dh@dev-harness

A forma curta /plugin marketplace add danielmalka/dev-harness também funciona, mas clona o repositório inteiro (cerca de 90 MB, por causa dos binários dh de cada versão). O install baixa só a pasta do plugin, na tag fixada em .claude-plugin/marketplace.json, de onde vem a versão. Para um time, o projeto pode declarar o marketplace em extraKnownMarketplaces e o plugin em enabledPlugins no .claude/settings.json.

Início rápido

Na sessão, dentro do projeto, rode /dh:doctor e depois /dh:setup. O primeiro diagnostica o ambiente; o segundo escolhe o modo (.harness/ no repositório ou pasta global ~/.harness/) e registra o projeto. Depois use os comandos de trabalho (/dh:discover, /dh:plan, /dh:build, /dh:review, /dh:verify, ou /dh:auto para encadear). Passo a passo: tutorial e início rápido.

O Coordenador responde no idioma em que você escreve (inglês por padrão). O /dh:setup grava language: en ou language: pt-br em project.yaml; o PRD é sempre em inglês.

Atualizar

O plugin vem da tag fixada em .claude-plugin/marketplace.json. Para uma versão nova, atualize o marketplace (claude plugin marketplace update dev-harness) e o plugin (claude plugin update dh@dev-harness); confira com /dh:doctor. As mudanças de cada versão estão em CHANGELOG.md.

Desinstalar e remover dados

  1. Na sessão: /plugin uninstall dh@dev-harness. Isso remove o plugin; não apaga seus dados.
  2. Pasta global: apague ~/.harness (ou o caminho de DH_HOME) para remover o registro de projetos, os registros do modo global, os snapshots e o token do dashboard.
  3. Se você adicionou ~/.harness em additionalDirectories no ~/.claude/settings.json, remova essa entrada.
  4. Em cada repositório em modo repositório: apague a pasta .harness/ (memória, tarefas, PRDs e ADRs do projeto). O kit nunca a apaga sozinho.

O que o kit grava e onde

No modo global, a pasta ~/.harness/ (DH_HOME muda o lugar) é única por máquina e por ambiente; .harness/ no repositório vence quando existe. Detalhes na seção "Modo global" do tutorial.

OndeO queQuem grava
<repositório>/.harness/modo repositório: MEMORY, EPOCHAL, RISKS, project.yaml, tarefas, PRDs, ADRsCoordenador e comandos /dh:
~/.harness/config.yamlregistro de projetos e padrões (language, mode, dashboard.sprites)só o dh (dh config, dh link)
~/.harness/projects/<nome>/modo global: os mesmos registros do .harness/Coordenador e comandos /dh:
<repositório>/REVIEW.mdguia de revisão do projeto, criado pelo /dh:setup quando falta, nos dois modos; único arquivo que o setup grava na árvore em modo global; nunca sobrescreve/dh:setup (via especialista)
~/.harness/sessions/snapshot por sessão do Claude Code (dh snapshot prune apaga os com mais de 7 dias)mod do plugin
~/.harness/dashboard/token de parada do dashboard, por portadashboard
~/.harness/projects/<nome>/pdocs/documentação HTML do projeto (/dh:document pdocs)docs-guide
127.0.0.1:4747dashboard local, só nesta máquina, quando você o inicia com /dashboardbinário dh

Desligar

  • Dashboard: dh dashboard --stop (--port N para outra porta). Ele não mata processo de outro programa.
  • Plugin: claude plugin disable dh@dev-harness (ou desinstale, como acima); o mod e as travas saem junto.
  • Não há chave por hook para o mod nem para a trava de commit: desligar é desabilitar o plugin inteiro.

Se algo falhar

  • Rode /dh:doctor na sessão ou dh doctor no terminal; ele aponta o que falta.
  • Porta ocupada: o dashboard avisa; use /dashboard --port N e dh dashboard --stop --port N.
  • Plugin não encontrado: confira /plugin marketplace add ... e /plugin install dh@dev-harness; ao carregar de um clone, não use ~ entre aspas em --plugin-dir (o Claude ignora o plugin em silêncio).
  • Não resolveu: abra uma issue em GitHub Issues. Vulnerabilidade: ver SECURITY.md.

Usar junto com

Opcional; o kit não precisa de nenhum dos dois.

Mapa da documentação

  • Início rápido e tutorial: comece por aqui. Roadmap e CHANGELOG.md: o que foi entregue e o que vem.
  • docs/prd/, docs/adr/ e docs/discovery/: histórico de design, em pt-br.
  • evals/: histórico de medição; não é preciso para usar o kit.
  • docs/plano-produto.html: plano de produto, em pt-br e interno.
  • Páginas em inglês: os mesmos temas dentro de docs/en/ (início rápido: docs/en/quick-start.html).

Para quem contribui

Esta seção é só para quem mantém o kit; quem usa não precisa dela. Regras completas em CONTRIBUTING.md. Requer Go 1.22+ (e Python 3 só para a fixture slice-01).

go test ./...
go run ./cmd/dh build
go run ./cmd/dh validate .
CaminhoPapel
.agents/ .commands/ .skills/ templates/ profiles/Fontes canônicas
cmd/dh, internal/Binário Go dh. go run ./cmd/dh build gera dist/claude-code/dev-harness
dist/Pacote gerado. Não editar.
adapters/Mapeamento para o Claude Code (claude-code/) e uso manual em outra IA, sem paridade (generic/)

Carregar a partir do clone, no projeto em que você vai trabalhar:

claude --plugin-dir "$HOME/caminho/do/clone/dist/claude-code/dev-harness" --agent coordinator

Use $HOME/... ou o caminho completo, nunca ~ entre aspas. Se o runtime exigir o nome qualificado, use --agent dh:coordinator. Diagnóstico sem o Claude: dist/claude-code/dev-harness/bin/dh doctor dist/claude-code/dev-harness. Templates de trabalho: docs/tutoriais/templates.html.

Source 8 files
hooks/panel.ts 387 lines
1import type { EngineInterface, Register } from 'claude-code'
2import { denySpawn, guardFile, homeFrom, resolvePath, warnThenNext } from './runtime-guard.ts'
3import { DASHBOARD_COMMAND, registerDashboard } from './dashboard-command.ts'
4import { applyEvent, iso, limitsFrom, type Ev, type Limits, type Snap } from './snapshot-writer.ts'
5import { driftMessage, findDrift, statusValue } from './status-drift.ts'
6import {
7  COMMIT, commandDir, deniesAiMention, gateAt, type Harness, harnessArgv, HARNESS_SECTION, harnessText, isGateCommand,
8  isHarnessPath, MSG, native, parseGateCommands, parseHarness, parseLanguage, taskStatus,
9} from './lib/gate.ts'
10import { GH_MSG, ghDenied } from './lib/gh-guard.ts'
11export { commandDir, deniesAiMention, harnessArgv, HARNESS_SECTION, harnessText, isGateCommand, isHarnessPath, native, parseGateCommands, parseHarness, parseLanguage, resolvePath, taskStatus }
12
13// ponytail: module-level state; a mod reload resets the gate (current session only).
14// Absolute paths edited since the last green gate of their repository.
15const dirty = new Set<string>()
16// PRD-027 R4: agentId -> subagentType from agent.spawn; the gh/git push guard reads it.
17const agentTypes = new Map<string, string>()
18const inside = (f: string, root: string) => f === root || f.startsWith(root === '/' ? '/' : `${root}/`)
19
20async function home($: EngineInterface): Promise<string> {
21  try { return (await $.env.get('HOME')) ?? '' } catch { return '' }
22}
23
24// Repository root of `dir` from git; `dir` itself when git does not answer.
25async function repoRoot($: EngineInterface, dir: string): Promise<string> {
26  try {
27    const r = await $.process.run(['git', '-C', native(dir), 'rev-parse', '--show-toplevel'], { timeoutMs: 2_000 })
28    const top = r.exitCode === 0 ? r.stdout.trim() : ''
29    return /^(\/|[A-Za-z]:)/.test(top) ? resolvePath('/', top) : dir
30  } catch {
31    return dir
32  }
33}
34
35async function rootOf($: EngineInterface, command: string, at?: number): Promise<string> {
36  return repoRoot($, commandDir(command, await $.session.cwd(), await home($), at))
37}
38
39// <home> by the ADR-007 rule, plus the user home for `~`; literal names so `claude plugin validate` lists them.
40async function homes($: EngineInterface): Promise<{ home: string; user: string; cwd: string }> {
41  try {
42    const cwd = await $.session.cwd().catch(() => '/')
43    const dh = await $.env.get('DH_HOME'), hm = await $.env.get('HOME'), up = await $.env.get('USERPROFILE')
44    return { home: homeFrom(dh, hm, up, cwd), user: hm || up || '', cwd }
45  } catch {
46    return { home: '', user: '', cwd: '/' }
47  }
48}
49
50// R8: <home> is read here and passed in; guardFile cannot take $ across the import.
51async function guardWrite($: EngineInterface, e: any, next: any): Promise<any> {
52  const { home, user, cwd } = await homes($)
53  return guardFile(home, e, async (x: typeof e) => markDirty($, await warnThenNext($, x, home, cwd, next), x), cwd, user)
54}
55
56// R20: `dh harness-path --json <dir>`, the only resolver (R2: the mod never reads the global registry file).
57// undefined = dh failed (missing binary, exit != 0, bad JSON, timeout).
58const harnesses = new Map<string, Harness | undefined>()
59
60async function resolveHarness($: EngineInterface, dir: string): Promise<Harness | undefined> {
61  try {
62    const argv = harnessArgv($.plugin.root, dir)
63    if (!argv) return undefined
64    const r = await $.process.run(argv, { timeoutMs: 2_000 })
65    return r.exitCode === 0 ? parseHarness(r.stdout) : undefined
66  } catch {
67    return undefined // fail open
68  }
69}
70
71// Cached per directory. repo/global stick for the session; none and failures are dropped by every
72// prompt.compose (so /dh:setup or dh link apply without a restart) and re-resolved on the next read.
73// ponytail: readers between two composes reuse a none/failed answer, so a gate never spawns dh per call.
74// Resolved from the repository root (as the commit gate does), so a session opened in a subfolder
75// finds its repo's harness; a non-git dir resolves as itself. Roots are cached per directory.
76// ponytail: a `git init` mid-session is not seen for a dir already cached as non-git.
77const roots = new Map<string, string>()
78async function rootFor($: EngineInterface, dir: string): Promise<string> {
79  const key = resolvePath('/', dir)
80  let root = roots.get(key)
81  if (root === undefined) roots.set(key, root = await repoRoot($, key))
82  return root
83}
84
85async function harnessOf($: EngineInterface, dir: string): Promise<{ root: string; h: Harness | undefined }> {
86  const root = await rootFor($, dir)
87  if (!harnesses.has(root)) harnesses.set(root, await resolveHarness($, root))
88  return { root, h: harnesses.get(root) }
89}
90
91// The folder holding project.yaml, tasks/ and prd/ for `dir`: the resolved one, else `<dir>/.harness` when it exists, else `<root>/.harness`.
92async function harnessDir($: EngineInterface, dir: string): Promise<string> {
93  try {
94    const { root, h } = await harnessOf($, dir)
95    if (h && h.mode !== 'none') return h.dir
96    // 0.20.0 read `<cwd>/.harness`; keep it when that folder exists below the git toplevel.
97    const own = `${dir}/.harness`
98    return (await $.fs.exists(own).catch(() => false)) ? own : `${native(root)}/.harness`
99  } catch {
100    return `${dir}/.harness`
101  }
102}
103
104async function composeSection($: EngineInterface): Promise<{ id: string; text: string; scope: 'session' } | undefined> {
105  for (const [k, v] of harnesses) if (!v || v.mode === 'none') harnesses.delete(k)
106  const { h } = await harnessOf($, await $.session.cwd())
107  return h ? { id: HARNESS_SECTION, text: harnessText(h), scope: 'session' } : undefined
108}
109
110async function readProject($: EngineInterface, root?: string): Promise<{ gates: string[]; lang: 'en' | 'pt-br' }> {
111  try {
112    const y = await $.fs.read(`${await harnessDir($, root ?? await $.session.cwd())}/project.yaml`) as string
113    return { gates: parseGateCommands(y), lang: parseLanguage(y) }
114  } catch {
115    return { gates: [], lang: 'en' }
116  }
117}
118
119// R20: fail-open on any read error; no tickets (or no readable PRDs) means no drift.
120async function driftNow($: EngineInterface, cwd: string): Promise<ReturnType<typeof findDrift>> {
121  try {
122    const hdir = await harnessDir($, cwd)
123    const tickets: { id: string; md: string }[] = []
124    for (const entry of await $.fs.list(`${hdir}/tasks`)) {
125      const file = `${hdir}/tasks/${entry.name}/TASK.md`
126      if (entry.kind === 'dir' && (await $.fs.exists(file))) tickets.push({ id: entry.name, md: await $.fs.read(file) as string })
127    }
128    if (!tickets.length) return []
129    const prds = new Map<string, string>()
130    for (const dir of [`${cwd}/docs/prd`, `${hdir}/prd`]) {
131      try {
132        for (const f of (await $.fs.list(dir)).sort((a, b) => (a.name < b.name ? -1 : 1))) {
133          const id = /^(PRD-\d+)/.exec(f.name)?.[1]
134          if (!id || f.kind !== 'file' || !f.name.endsWith('.md') || f.name.endsWith('.review.md') || prds.has(id)) continue
135          prds.set(id, statusValue(await $.fs.read(`${dir}/${f.name}`) as string))
136        }
137      } catch { /* directory absent */ }
138    }
139    return findDrift(tickets, prds, taskStatus)
140  } catch {
141    return []
142  }
143}
144
145// PRD-027: the gh/git push deny for a shell-command call of any tool (Bash, Monitor, PowerShell).
146async function guardGh($: EngineInterface, command: string, agentId?: string, unreadable = false, powershell = false): Promise<string | undefined> {
147  const gh = ghDenied(command, agentId, agentId ? agentTypes.get(agentId) : undefined, unreadable, powershell)
148  return gh ? GH_MSG[(await readProject($)).lang](gh.verb, gh.unknown) : undefined
149}
150
151async function guardBash($: EngineInterface, command: string, agentId?: string): Promise<string | undefined> {
152  const ghMsg = await guardGh($, command, agentId)
153  if (ghMsg) return ghMsg
154  const aiHit = deniesAiMention(command)
155  const commit = COMMIT.exec(command)
156  if (!aiHit && !commit) return undefined
157  // The commit's repository, not the session's, decides the gate, the language and the drift check.
158  const root = commit ? await rootOf($, command, commit.index) : await $.session.cwd()
159  const { gates, lang } = await readProject($, native(root))
160  if (aiHit) return MSG[lang].ai
161  if ([...dirty].some(f => inside(f, root))) return MSG[lang].gate(gates.length ? gates.join(' && ') : MSG[lang].gateDefault)
162  const drift = await driftNow($, native(root))
163  return drift.length ? driftMessage(drift, lang, native(root)) : undefined
164}
165
166async function markDirty<R extends { deny?: unknown; isError?: boolean }>($: EngineInterface, r: R, e: any): Promise<R> {
167  const p = e.file_path ?? e.notebook_path
168  if (r.deny === undefined && r.isError !== true && p && !isHarnessPath(p, (await homes($)).home)) {
169    dirty.add(resolvePath(await $.session.cwd().catch(() => '/'), String(p)))
170  }
171  return r
172}
173
174// BUG-001 snapshot writer (engine events, no classic.*): per-session file, serialized writes.
175const SAFE_ID = /^[\w-]{1,128}$/
176const BEAT_MS = 30_000
177const JOB_MS = 2_000
178const END_MS = 1_000 // session.end's whole budget is 1.5s: wait at most this long for the close write
179
180// ponytail: module-level state; a mod reload resets it (current session only).
181let chain: Promise<unknown> = Promise.resolve()
182let beatSession = ''
183let beat: { cancel: () => void } | undefined
184const SKIP_LIMIT = 3
185const closedHere = new Set<string>() // ids this module instance closed via session.end: a late record must not reopen them
186const skips = new Map<string, number>() // consecutive skipped writes per session (unparseable file)
187
188// R10: <home>/sessions, <home> by the ADR-007 rule (DH_HOME is the only control); '' when no home is known.
189// $.fs.write creates missing parent directories (engine type doc), so a clean machine needs no `dh` call first.
190async function snapshotDir($: EngineInterface): Promise<string> {
191  const home = homeFrom(await $.env.get('DH_HOME'), await $.env.get('HOME'), await $.env.get('USERPROFILE'), await $.session.cwd().catch(() => '/'))
192  return home ? `${home.replace(/^\/([A-Z]):/, '$1:')}/sessions` : ''
193}
194
195// {} when the file does not exist; undefined when it exists but cannot be read or parsed (the caller skips the write).
196async function readPrev($: EngineInterface, path: string): Promise<Snap | undefined> {
197  try {
198    if (!(await $.fs.exists(path))) return {}
199    const o = JSON.parse(await $.fs.read(path) as string)
200    return o && typeof o === 'object' && !Array.isArray(o) ? o : undefined
201  } catch {
202    return undefined
203  }
204}
205
206// A hung fs/usage call must never hold the session: each serialized job gets 2s.
207function withTimeout<T>($: EngineInterface, p: Promise<T>): Promise<T> {
208  let t: { cancel: () => void } | undefined
209  const limit = new Promise<never>((_, reject) => { t = $.clock.after(JOB_MS, () => reject(new Error('snapshot job timed out'))) })
210  return Promise.race([p, limit]).finally(() => t?.cancel())
211}
212
213async function usageLimits($: EngineInterface): Promise<Limits | undefined> {
214  try { return limitsFrom((await $.session.usage()).rateLimits) } catch { return undefined } // no usage: keep previous
215}
216
217async function touch($: EngineInterface): Promise<void> {
218  const id = beatSession
219  const dir = await snapshotDir($)
220  if (!id || !dir) return
221  const path = `${dir}/${id}.json`
222  const prev = await readPrev($, path)
223  const limits = await usageLimits($) // a limit's age must reflect when it was measured
224  const now = iso(await $.clock.now())
225  // Re-checked after the last await, inside the serialized job: an ended session is never resurrected.
226  if (!prev || beatSession !== id || !prev.session_id || prev.state === 'closed') return
227  await $.fs.write(path, JSON.stringify({ ...prev, updated_at: now, ...(limits ? { rate_limits: limits } : {}) }, null, 2) + '\n')
228}
229
230async function write($: EngineInterface, name: string, e: Ev): Promise<void> {
231  if (!SAFE_ID.test(String(e.session_id ?? ''))) return
232  {
233    const dir = await snapshotDir($)
234    if (!dir) return
235    const path = `${dir}/${e.session_id}.json`
236    const limits = await usageLimits($)
237    let prev = await readPrev($, path)
238    if (!prev) {
239      // exists but unreadable/partial: do not overwrite what another writer is mid-way through,
240      // unless it stays unparseable for SKIP_LIMIT writes in a row (then it is corrupt, not partial)
241      const n = (skips.get(e.session_id) ?? 0) + 1
242      if (n < SKIP_LIMIT) { skips.set(e.session_id, n); return }
243      prev = {}
244    }
245    skips.delete(e.session_id)
246    // A late record of a session this instance ended never reopens it. A SessionStart or a prompt (always
247    // user-initiated, e.g. an in-process /resume of the same id) lifts the mark; the file's own state is no signal.
248    if (name === 'SessionStart' || name === 'UserPromptSubmit') closedHere.delete(e.session_id)
249    else if (name !== 'SessionEnd' && closedHere.has(e.session_id)) return
250    const now = iso(await $.clock.now())
251    const next = applyEvent(prev, name, e, now, limits)
252    if (!next) return
253    // After /clear or a resume the process continues under a new id and no session.start fires:
254    // fill what only that event would have written, so the dashboard can attribute the file to a project.
255    if (name !== 'SessionEnd') {
256      if (!next.cwd) { const c = await $.session.cwd().catch(() => undefined); if (typeof c === 'string' && c) next.cwd = c }
257      if (!next.model?.id) { const m = await $.session.model().catch(() => undefined); if (typeof m === 'string' && m) next.model = { ...(next.model ?? {}), id: m } }
258      next.started_at ||= now
259    }
260    await $.fs.write(path, JSON.stringify(next, null, 2) + '\n')
261    if (name !== 'SessionEnd') {
262      beatSession = e.session_id
263      beat ??= $.clock.every(BEAT_MS, () => { chain = chain.then(() => withTimeout($, touch($))).catch(() => undefined) })
264    }
265  }
266}
267
268// Events are serialized so two quick hooks never read-modify-write the same file out of order.
269// A failed write is silent: a snapshot is a convenience, never a reason to disturb the session.
270// The session id is read when the event happens, before queueing, so a late record never lands on the next id.
271async function record($: EngineInterface, name: string, e0: Ev): Promise<void> {
272  const e: Ev = { ...e0, session_id: e0.session_id ?? await $.session.id().catch(() => undefined) }
273  const job = chain.then(() => withTimeout($, write($, name, e)))
274  chain = job.catch(() => undefined)
275  await job.catch(() => undefined)
276}
277
278// What panel.ts calls from its engine hooks. Each is fail-open and returns a promise that never rejects.
279// Hot-path events (prompt, tool, subagent) do not wait for the write; chain keeps the order.
280async function recordStart($: EngineInterface, e: { cwd?: string }): Promise<void> {
281  const model = await $.session.model().catch(() => undefined) // agent type: the engine does not expose it
282  await record($, 'SessionStart', { cwd: e.cwd, model })
283}
284function recordPrompt($: EngineInterface): void { void record($, 'UserPromptSubmit', {}) }
285function recordTool($: EngineInterface): void { void record($, 'PostToolUse', {}) }
286function recordSpawn($: EngineInterface, subagentType: string, agentId: string): void {
287  void record($, 'SubagentStart', { agent_type: subagentType, agent_id: agentId })
288}
289// A subagent's turn.complete is SubagentStop (keeps activity, does not wait); the main loop's is Stop/StopFailure.
290function recordTurn($: EngineInterface, e: { agentId?: string; reason?: string }): Promise<void> {
291  if (e.agentId) { void record($, 'SubagentStop', { agent_id: e.agentId }); return Promise.resolve() }
292  return record($, e.reason === 'error' ? 'StopFailure' : 'Stop', {})
293}
294// The close write stays last in the chain (ordering kept), but session.end has 1.5s in all: when the chain
295// is slow (a hung fs, a long queue) stop waiting after END_MS and let the job finish on its own, instead of
296// being cut by the engine and replayed through failOpen.
297async function recordEnd($: EngineInterface, e: { sessionId?: string }): Promise<void> {
298  // Synchronously, before anything is queued: a hung fs call in the close job cannot leave the beat running,
299  // and records still queued for this id are dropped as late (the close write follows them).
300  if (e.sessionId) {
301    closedHere.add(e.sessionId)
302    if (e.sessionId === beatSession) { beat?.cancel(); beat = undefined; beatSession = '' }
303  }
304  let t: { cancel: () => void } | undefined
305  const cap = new Promise<void>(resolve => { t = $.clock.after(END_MS, () => resolve()) })
306  await Promise.race([record($, 'SessionEnd', { session_id: e.sessionId }), cap])
307  t?.cancel()
308}
309
310// ponytail: a mod failure never blocks a tool (fail-open); the trap is a convenience, not security.
311const failOpen = ($: EngineInterface, e: any, next: any) => next(e)
312
313// hooks.json `modules` accepts one entry per plugin and a duplicate on(event) is refused,
314// so panel.ts is the entry and chains the runtime-guard checks (ADR-005) ahead of its own.
315// The loader refuses $ passed across an import: denySpawn gets `{}`, guardFile gets <home> as a string.
316export const register: Register = on => {
317  registerDashboard(on)
318
319  on('session.start', async ($, e, next) => {
320    const r = await next(e)
321    await $.command.register(DASHBOARD_COMMAND).catch(() => undefined)
322    await recordStart($, e)
323    return r
324  })
325
326  on('turn.complete', async ($, e, next) => {
327    const r = await next(e)
328    await recordTurn($, e)
329    return r
330  })
331
332  on('agent.spawn', ($, e, next) => denySpawn({}, e, async (x: typeof e) => {
333    const r = await next(x)
334    if (r.agentId) { agentTypes.set(r.agentId, String(x.subagentType)); recordSpawn($, x.subagentType, r.agentId) }
335    return r
336  })).catch(failOpen)
337
338  on('prompt.submit', ($, e, next) => { recordPrompt($); return next(e) }).catch(failOpen)
339
340  // BUG-001: every other tool call is activity too; recorded after the guards beneath have answered.
341  on('tool.call', async ($, e, next) => {
342    const r = await next(e)
343    recordTool($)
344    return r
345  }).catch(failOpen)
346
347  on('session.end', async ($, e, next) => {
348    await recordEnd($, e)
349    return next(e)
350  }).catch(failOpen)
351
352  on('tool.call', { tool: 'Edit' }, guardWrite).catch(failOpen)
353  on('tool.call', { tool: 'Write' }, guardWrite).catch(failOpen)
354  on('tool.call', { tool: 'NotebookEdit' }, async ($, e, next) => markDirty($, await next(e), e)).catch(failOpen)
355
356  // R20: tell the session where its harness lives; a dh failure adds nothing (fail-open).
357  on('prompt.compose', async ($, e, next) => {
358    const r = await next(e)
359    const section = await composeSection($).catch(() => undefined)
360    return section ? { sections: [...r.sections, section] } : r
361  }).catch(failOpen)
362
363  // PRD-027 R3: the other tools that take a shell command get the gh guard only, on their command field.
364  for (const tool of ['Monitor', 'PowerShell']) {
365    on('tool.call', { tool } as any, async ($, e: any, next) => {
366      const ok = typeof e.command === 'string'
367      // a PowerShell call without a readable command is denied for a kit subagent; a Monitor without one is not a shell command
368      const denied = ok || tool === 'PowerShell' ? await guardGh($, ok ? e.command : '', e.agentId, !ok, tool === 'PowerShell').catch(() => undefined) : undefined
369      return denied ? { deny: denied } : next(e)
370    }).catch(failOpen)
371  }
372
373  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
374    const denied = await guardBash($, e.command, e.agentId).catch(() => undefined)
375    if (denied) return { deny: denied }
376    const r = await next(e)
377    // ponytail: pre-filter by generic + session gates (no git spawn on plain Bash); a custom gate that only
378    // another repo's project.yaml names does not clear that repo.
379    const at = r.deny === undefined && r.isError !== true && dirty.size ? gateAt(e.command, (await readProject($)).gates) : -1
380    if (at >= 0) {
381      const root = await rootOf($, e.command, at)
382      for (const f of dirty) if (inside(f, root)) dirty.delete(f)
383    }
384    return r
385  }).catch(failOpen)
386}
387
hooks/runtime-guard.ts 92 lines
1import type { EngineInterface, Register } from 'claude-code'
2import { warnWrite } from './lib/warn.ts'
3
4const FILES = ['MEMORY.md', 'EPOCHAL.md', 'RISKS.md']
5
6// Normalizes `p` against `base`: absolute result, no `.`/`..`/empty segments. A Windows drive path
7// (`C:\\x`, `c:/x`) is absolute too and reads as `/C:/x`, so git's `C:/repo` and the engine's `C:\\repo` meet.
8export function resolvePath(base: string, p: string): string {
9  const abs = (x: string) => x.replace(/\\/g, '/').replace(/^\/?([A-Za-z]):(?=\/|$)/, (_m, d: string) => `/${d.toUpperCase()}:`)
10  const n = abs(p)
11  const out: string[] = []
12  for (const seg of (n.startsWith('/') ? n : `${abs(base)}/${n}`).split('/')) {
13    if (seg === '..') out.pop()
14    else if (seg && seg !== '.') out.push(seg)
15  }
16  return `/${out.join('/')}`
17}
18
19// ADR-007: <home> = DH_HOME, else HOME/.harness, else USERPROFILE/.harness; '' when none is set.
20// Pure, so each module reads the three variables itself (literal names; $ does not cross an import).
21export function homeFrom(dhHome: unknown, home: unknown, userProfile: unknown, cwd = '/'): string {
22  const base = dhHome ? String(dhHome) : home ? `${home}/.harness` : userProfile ? `${userProfile}/.harness` : ''
23  return base ? resolvePath(cwd, base) : ''
24}
25
26export function denySpawn($: any, e: any, next: any) {
27  try {
28    if (e.parentAgentId) return { deny: 'only the Coordinator dispatches agents (dev-harness runtime guard)' }
29  } catch {} // fail open
30  return next(e)
31}
32
33// The protected record `file_path` names, or undefined: `<x>/.harness/<file>` (repo mode, by suffix) or
34// exactly `<home>/projects/<one segment>/<file>` (global mode), after expanding a leading `~` to `userHome`
35// and resolving against `cwd`. Case-insensitive on every platform: a look-alike denied is the safe side.
36// `home` '' turns the global pattern off (fail open, ADR-007 §4).
37// ponytail: accepted limits (ADR-005): a symlinked spelling of <home> is not resolved, and only Write/Edit
38// are guarded; a Bash redirect or any other write tool is outside the guard.
39export function protectedHit(home: string, filePath: unknown, cwd = '/', userHome = ''): string | undefined {
40  if (typeof filePath !== 'string' || !filePath) return undefined
41  const expanded = userHome ? filePath.replace(/^~(?=$|[\\/])/, userHome) : filePath
42  const abs = resolvePath(cwd, expanded) // `..` cannot walk around either pattern
43  const low = abs.toLowerCase()
44  const repo = FILES.find(f => low.endsWith(`/.harness/${f.toLowerCase()}`))
45  if (repo) return `.harness/${repo}`
46  if (!home) return undefined
47  const h = resolvePath('/', home)
48  const prefix = `${h === '/' ? '' : h}/projects/`
49  if (!low.startsWith(prefix.toLowerCase())) return undefined
50  const rest = abs.slice(prefix.length).split('/')
51  const file = FILES.find(f => f.toLowerCase() === rest[1]?.toLowerCase())
52  return rest.length === 2 && rest[0] && file ? abs : undefined
53}
54
55export function guardFile(home: string, e: any, next: any, cwd = '/', userHome = '') {
56  try {
57    const hit = e.agentId ? protectedHit(home, e.file_path, cwd, userHome) : undefined
58    if (hit) return { deny: `${hit} is written only by the Coordinator (dev-harness runtime guard); return the proposed update instead.` }
59  } catch {} // fail open
60  return next(e)
61}
62
63async function harnessHome($: EngineInterface): Promise<{ home: string; cwd: string; user: string }> {
64  try {
65    const cwd = await $.session.cwd().catch(() => '/')
66    const dh = await $.env.get('DH_HOME'), hm = await $.env.get('HOME'), up = await $.env.get('USERPROFILE')
67    return { home: homeFrom(dh, hm, up, cwd), cwd, user: hm || up || '' }
68  } catch {
69    return { home: '', cwd: '/', user: '' } // fail open: only the suffix pattern holds
70  }
71}
72
73// PRD-025 R5-R7: warn-only toast for the main session; the event always passes on unchanged.
74export async function warnThenNext($: any, e: any, home: string, cwd: string, next: any) {
75  try {
76    const text = await warnWrite(e, home, cwd, p => $.fs.exists(p))
77    if (text) $.ui.toast(text)
78  } catch {} // fail open
79  return next(e)
80}
81
82const guard = async ($: EngineInterface, e: any, next: any) => {
83  const { home, cwd, user } = await harnessHome($)
84  return guardFile(home, e, (x: any) => warnThenNext($, x, home, cwd, next), cwd, user)
85}
86
87export const register: Register = on => {
88  on('agent.spawn', denySpawn)
89  on('tool.call', { tool: 'Write' }, guard)
90  on('tool.call', { tool: 'Edit' }, guard)
91}
92
hooks/dashboard-command.ts 29 lines
1import type { On } from 'claude-code'
2
3// PRD-012 R6: `/dh:dashboard` exists only as a command the mod registers; it runs the plugin's own
4// `dh dashboard --detach` (idempotent) and answers with the URL it prints.
5export const DASHBOARD_COMMAND = { name: 'dashboard', description: 'Start the Dev Harness dashboard (local, detached) and print its URL' }
6
7export function dhPath(root: string): string {
8  return /^[A-Za-z]:[\\/]|^\\\\/.test(root) ? `${root}\\bin\\dh.cmd` : `${root}/bin/dh`
9}
10
11// Each user token is a plain flag or word: no shell metacharacters reach dh.cmd on Windows.
12const ARG_OK = /^--?[A-Za-z][\w-]*(=[\w.:-]+)?$|^[\w.:-]+$/
13
14export function registerDashboard(on: On): void {
15  on('command.run', { command: 'dashboard' }, async ($, e) => {
16    try {
17      const extra = e.args.trim().split(/\s+/).filter(Boolean) // dh flags only: argv, no shell
18      const bad = extra.find(t => !ARG_OK.test(t))
19      if (bad !== undefined) return { text: `dh dashboard: unsupported argument ${JSON.stringify(bad)}; use plain flags such as --port=4748` }
20      const r = await $.process.run([dhPath($.plugin.root), 'dashboard', '--detach', ...extra], { timeoutMs: 15_000 })
21      const url = r.stdout.trim()
22      if (r.exitCode === 0 && !url) return { text: 'dh dashboard exited 0 but printed no URL' }
23      return { text: r.exitCode === 0 ? url : `dh dashboard failed (exit ${r.exitCode}): ${(r.stderr || r.stdout).trim()}` }
24    } catch (err) {
25      return { text: `dh dashboard failed: ${String(err)}` }
26    }
27  }).catch((_$: unknown, e: any, next: any) => next(e))
28}
29
hooks/snapshot-writer.ts 64 lines
1// Pure part of the snapshot writer; the engine-facing part lives in panel.ts, because the loader never
2// follows `$` across an import (BUG-001). PRD-012 R11/R13/R13b/R14/R15: the mod writes the per-session snapshot (schema 2) that
3// `dh snapshot event` used to write, plus activity/rate_limits, and keeps updated_at alive.
4export type Ev = Record<string, any>
5export type Snap = Record<string, any>
6export type Limits = { five_hour?: number; seven_day?: number }
7
8// Keys are the snapshot's own event kinds (the names the dashboard and `dh snapshot event` know), not engine
9// events: BUG-001 maps session.start/prompt.submit/tool.call/agent.spawn/turn.complete/session.end onto them,
10// because the engine floors every `classic.*` hook on Team accounts. There is no un-floored "waiting" source.
11// state is the schema 1 vocabulary; activity is the dashboard's (R13 table).
12const MAP: Record<string, { activity: string; state: string }> = {
13  SessionStart: { activity: 'idle', state: 'idle' },
14  UserPromptSubmit: { activity: 'working', state: 'active' },
15  PostToolUse: { activity: 'working', state: 'active' },
16  SubagentStart: { activity: 'working', state: 'active' },
17  SubagentStop: { activity: 'working', state: 'active' },
18  StopFailure: { activity: 'error', state: 'idle' },
19  Stop: { activity: 'done', state: 'idle' },
20  SessionEnd: { activity: 'idle', state: 'closed' },
21}
22
23export function iso(ms: number): string {
24  return new Date(ms).toISOString().replace(/\.\d+Z$/, 'Z')
25}
26
27export function limitsFrom(rl: { kind: string; percentUsed: number }[]): Limits | undefined {
28  const out: Limits = {}
29  for (const r of rl) {
30    if (r.kind === 'five_hour') out.five_hour = r.percentUsed
31    if (r.kind === 'seven_day') out.seven_day = r.percentUsed
32  }
33  return Object.keys(out).length ? out : undefined
34}
35
36// Pure: previous file content + one snapshot event kind -> next content, or undefined when the event writes nothing.
37// Unknown fields of `prev` (tasks, ...) ride along.
38export function applyEvent(prev: Snap, name: string, e: Ev, now: string, limits?: Limits): Snap | undefined {
39  const m = MAP[name]
40  if (!m) return undefined
41  // A subagent finishing says nothing about the main thread: SubagentStop keeps the current activity.
42  const activity = name === 'SubagentStop' ? (prev.activity ?? m.activity) : m.activity
43  const s: Snap = { ...prev, schema: 2, session_id: e.session_id, state: m.state, activity, updated_at: now }
44  if (prev.activity !== activity || !prev.activity_at) s.activity_at = now
45  if (name === 'SessionStart') {
46    const title = e.session_name ?? e.session_title
47    if (typeof title === 'string') s.session_name = title
48    if (!s.started_at) s.started_at = now
49    if (typeof e.cwd === 'string') s.cwd = e.cwd
50    if (typeof e.agent_type === 'string') s.agent = e.agent_type
51    if (typeof e.model === 'string') s.model = { ...(prev.model ?? {}), id: e.model }
52  } else if (!s.cwd && typeof e.cwd === 'string') {
53    s.cwd = e.cwd // mod loaded mid-session: still attributable to a project
54  }
55  if (name === 'SubagentStart' || name === 'SubagentStop') {
56    const rec: Ev = { at: now, event: name }
57    if (typeof e.agent_type === 'string') rec.agent_type = e.agent_type
58    if (typeof e.agent_id === 'string') rec.agent_id = e.agent_id
59    s.events = [...(Array.isArray(prev.events) ? prev.events : []), rec].slice(-50)
60  }
61  if (limits) s.rate_limits = limits
62  return s
63}
64
hooks/status-drift.ts 52 lines
1// PRD-012 R19/R20: ticket/PRD status drift. Pure, mirrors internal/dashboard + internal/kit/status_drift.go.
2// Shared fixture: internal/dashboard/testdata/status-cases.json.
3const STATUS_ROW = /^\|\s*Status\s*\|\s*([^|]+)\|/m
4const STATUS_BOLD = /\*\*Status:?\*\*:?\s*([^\n]+)/
5const PRD_FIELD = /^\|\s*(?:Story \/ PRD|PRD \(RF-[^)]*\))\s*\|\s*([^|]+)\|/m
6const PRD_ID = /PRD-\d+/
7
8export function statusValue(md: string): string {
9  return (md.match(STATUS_ROW)?.[1] ?? md.match(STATUS_BOLD)?.[1] ?? '').trim().toLowerCase()
10}
11
12// The PRD id a ticket links to, or '' ("fora"/"nenhum" or no PRD-n).
13export function prdLink(md: string): string {
14  const v = md.match(PRD_FIELD)?.[1]
15  if (v === undefined || /^(fora|nenhum)/.test(v.trim().toLowerCase())) return ''
16  return v.match(PRD_ID)?.[0] ?? ''
17}
18
19export type Drift = { prd: string; kind: 'open-in-delivered' | 'all-done'; tickets: string[] }
20
21// tickets: id + TASK.md text; prds: PRD id -> lowercased header Status. classify = taskStatus (panel.ts).
22export function findDrift(tickets: { id: string; md: string }[], prds: Map<string, string>, classify: (md: string) => string): Drift[] {
23  const by = new Map<string, { total: number; open: string[] }>()
24  for (const t of tickets) {
25    const id = prdLink(t.md)
26    if (!id || !prds.has(id)) continue
27    const c = by.get(id) ?? { total: 0, open: [] }
28    c.total++
29    if (classify(t.md) !== 'done') c.open.push(t.id)
30    by.set(id, c)
31  }
32  const out: Drift[] = []
33  for (const id of [...by.keys()].sort()) {
34    const c = by.get(id)!
35    const delivered = (prds.get(id) ?? '').startsWith('entregue em') || (prds.get(id) ?? '').startsWith('delivered on')
36    c.open.sort()
37    if (delivered && c.open.length) out.push({ prd: id, kind: 'open-in-delivered', tickets: c.open })
38    if (!delivered && c.total > 0 && !c.open.length) out.push({ prd: id, kind: 'all-done', tickets: [] })
39  }
40  return out
41}
42
43export function driftMessage(drift: Drift[], lang: 'en' | 'pt-br', cwd = ''): string {
44  const pt = lang === 'pt-br'
45  const lines = drift.map(d => d.kind === 'open-in-delivered'
46    ? (pt ? `${d.prd}: tickets ainda abertos (${d.tickets.join(', ')}) mas o PRD está "entregue em" ou "delivered on"; conclua os tickets ou corrija o Status do PRD.`
47      : `${d.prd}: tickets still open (${d.tickets.join(', ')}) but the PRD is marked "entregue em" or "delivered on"; close the tickets or fix the PRD Status.`)
48    : (pt ? `${d.prd}: todos os tickets ligados estão concluídos mas o Status do PRD não começa com "entregue em" nem "delivered on"; atualize o Status.`
49      : `${d.prd}: all linked tickets are done but the PRD Status does not start with "entregue em" or "delivered on"; update the Status.`))
50  return `dev-harness: ${pt ? 'deriva de status entre tickets e PRD bloqueia este commit' : 'ticket/PRD status drift blocks this commit'}\n${lines.join('\n')}\n${pt ? `Corrija e commite de novo. (Verificado só em ${cwd || 'o diretório da sessão'}.)` : `Fix it and commit again. (Checked in the session directory only: ${cwd || 'cwd'}.)`}`
51}
52
hooks/lib/gate.ts 120 lines
1import { resolvePath } from '../runtime-guard.ts'
2import { dhPath } from '../dashboard-command.ts'
3import { statusValue } from '../status-drift.ts'
4
5// Pure helpers of the commit gate and the harness resolver, used by panel.ts.
6export type Harness = { mode: 'repo' | 'global' | 'none'; dir: string }
7
8// Commit/PR text that mentions AI: an empty `attribution` covers the default footer, this covers the rest.
9export const AI_MENTION = /co-authored-by:\s*claude|generated with \[?claude|🤖|anthropic\.com|\bclaude code\b/i
10export const GIT_C = String.raw`(?:-C\s+(?:"[^"]*"|'[^']*'|\S+)\s+)?`
11export const SHIPS = new RegExp(String.raw`\b(git\s+${GIT_C}commit|gh\s+pr\s+(create|edit)|gh\s+release\s+create)\b`)
12export const COMMIT = new RegExp(String.raw`\bgit\s+${GIT_C}commit(?![\w-])`)
13export const GENERIC_GATE = /\b(make\s+(check|test|lint|ci|stan|gate)|go\s+(test|vet)|golangci-lint|pytest|ruff\s+check|cargo\s+(test|clippy)|(npm|pnpm|yarn|bun)\s+(run\s+)?(test|lint|check|typecheck)|tsc\b|phpstan|phpunit|pint)\b/
14export const GATE_KEYS = /^ {2}(test|lint|vet|check|typecheck|stan|fmt[\w-]*):\s*\n\s+value:\s*(.+)$/gm
15
16export function deniesAiMention(command: string): boolean {
17  return SHIPS.test(command) && AI_MENTION.test(command)
18}
19
20export function parseGateCommands(projectYaml: string): string[] {
21  return [...projectYaml.matchAll(GATE_KEYS)]
22    .map(m => (m[2] ?? '').trim().replace(/^["']|["']$/g, ''))
23    .filter(v => v && v !== 'null')
24}
25
26export function isGateCommand(command: string, projectGates: string[]): boolean {
27  return GENERIC_GATE.test(command) || projectGates.some(g => command.includes(g))
28}
29
30export function parseLanguage(projectYaml: string): 'en' | 'pt-br' {
31  return /^language:\s*(\S+)/m.exec(projectYaml)?.[1]?.replace(/^["']|["']$/g, '').toLowerCase() === 'pt-br' ? 'pt-br' : 'en'
32}
33
34// D5: dh bookkeeping under .harness/ (or, global mode, under <home>/projects/) is not code churn,
35// so it does not dirty the gate. `home` is resolvePath-normalized; '' skips the global check.
36export function isHarnessPath(p: unknown, home = ''): boolean {
37  const n = String(p ?? '').replace(/\\/g, '/')
38  const abs = /^(\/|[A-Za-z]:)/.test(n)
39  const r = resolvePath('/', n) // `.harness/../src/a.go` is code, not bookkeeping
40  if (r.includes('/.harness/')) return true
41  return !!home && abs && r.startsWith(`${home === '/' ? '' : home}/projects/`)
42}
43
44const unquote = (s: string) => s.replace(/^(["'])(.*)\1$/, '$2')
45
46
47// Back to the platform's form for git and fs calls: `/C:/x` -> `C:/x`; POSIX paths unchanged.
48export const native = (p: string) => p.replace(/^\/([A-Z]):/, '$1:')
49
50// Directory a git commit (or a gate) at offset `at` runs in: each `cd <dir>` before `at` moves it
51// (relative to the previous one; a bare `cd` goes home), then `git -C <dir>` on the commit itself
52// resolves against that. `home` expands a leading `~`.
53// ponytail: shell parsing by regex; pushd, `cd -`, env-var dirs and `--git-dir` resolve wrong and fail open.
54export function commandDir(command: string, cwd: string, home: string, at = command.length): string {
55  let dir = cwd
56  const expand = (d: string) => resolvePath(dir, unquote(d).replace(/^~(?=\/|$)/, home))
57  for (const m of command.slice(0, at).matchAll(/(?:^|[;&|(\n]\s*|\bthen\s+)cd(?:\s+("[^"]*"|'[^']*'|[^\s;&|)]+))?(?=\s*(?:$|[;&|)\n]))/g)) {
58    dir = m[1] === undefined ? (home || dir) : expand(m[1])
59  }
60  const c = /^git\s+-C\s+("[^"]*"|'[^']*'|\S+)\s+/.exec(command.slice(at))
61  return c ? expand(c[1] ?? '.') : dir
62}
63
64// Offset of the first gate command in `command`, or -1.
65export function gateAt(command: string, projectGates: string[]): number {
66  const hits = [GENERIC_GATE.exec(command)?.index ?? -1, ...projectGates.map(g => command.indexOf(g))].filter(i => i >= 0)
67  return hits.length ? Math.min(...hits) : -1
68}
69
70export const MSG = {
71  en: {
72    ai: 'dev-harness: commit/PR text mentions AI/Claude. Remove the mention and retry.',
73    gate: (hint: string) => `dev-harness: files were edited after the last green gate in this session. Run ${hint} and commit again.`,
74    gateDefault: "the project's quality gate (tests + lint)",
75  },
76  'pt-br': {
77    ai: 'dev-harness: commit/PR menciona IA/Claude. Remova a menção e tente de novo.',
78    gate: (hint: string) => `dev-harness: houve edição depois do último gate verde nesta sessão. Rode ${hint} e commite de novo.`,
79    gateDefault: 'o quality gate do projeto (testes + lint)',
80  },
81}
82
83export function taskStatus(taskMd: string): 'done' | 'blocked' | 'open' {
84  const s = statusValue(taskMd)
85  if (/^(conclu|pronta, entregue|done)/.test(s)) return 'done'
86  if (/^bloque/.test(s)) return 'blocked'
87  return 'open'
88}
89
90// The argv for `dh harness-path`, or undefined when spawning is unsafe: on Windows dhPath is a .cmd that
91// cmd.exe parses, so a directory with a cmd metacharacter is never passed (treated as a dh failure).
92export function harnessArgv(pluginRoot: string, dir: string): string[] | undefined {
93  const dh = dhPath(pluginRoot)
94  const d = native(dir)
95  if (dh.endsWith('.cmd') && /[&|<>^%!"()\r\n]/.test(d)) return undefined
96  return [dh, 'harness-path', '--json', d]
97}
98
99// What `dh harness-path --json` printed, or undefined when it is not a usable answer: the dir must be
100// absolute, at most 4096 chars, and free of control/line-separator characters (it is shown to the model).
101export function parseHarness(stdout: string): Harness | undefined {
102  try {
103    const o = JSON.parse(stdout)
104    if (o?.mode === 'none') return { mode: 'none', dir: '' }
105    const d = o?.dir
106    if ((o?.mode === 'repo' || o?.mode === 'global') && typeof d === 'string' && d.length <= 4096
107      && /^(\/|[A-Za-z]:|\\\\)/.test(d) && !/[\u0000-\u001f\u007f\u2028\u2029]/.test(d)) return { mode: o.mode, dir: d }
108  } catch { /* fail open */ }
109  return undefined
110}
111
112export const HARNESS_SECTION = 'dh:harness'
113
114export function harnessText(h: Harness): string {
115  return h.mode === 'none'
116    ? 'Dev Harness: no harness for this project (mode none). Run /dh:setup to create one, or dh link if it already exists.'
117    : `Dev Harness: mode ${h.mode}; harness dir ${JSON.stringify(h.dir)}. Records (MEMORY.md, EPOCHAL.md, RISKS.md, project.yaml, tasks/, prd/) live there.`
118}
119
120
hooks/lib/gh-guard.ts 90 lines
1// PRD-027 2.3: a short rule on the command text, no parser. No I/O.
2// ponytail: accepted false positives and bypasses are listed in PRD 2.3 and 2.4. Ceiling: any text that names
3// `gh` or a git write word is denied unless it is a plain gh read or a plain grep; the main session runs the rest.
4
5// Word boundaries (PRD 2.3): a word starts at the start or after a char that is not a letter, digit or `_`.
6const START = '(?<=^|[^A-Za-z0-9_])'
7const word = (w: string, end = '(?=$|[^A-Za-z0-9_-])') => new RegExp(`${START}${w}${end}`)
8const GH = word('gh', '(?=$|\\.exe|[^A-Za-z0-9_-])') // gh also ends before `.exe`, but not before `-` (gh-pages)
9const GIT = word('git', '(?![A-Za-z0-9_])') // git ends before `-` too: git-push, git-lfs push
10const WRITE = ['push', 'send-pack', 'subtree', 'p4', 'svn', 'dcommit', 'alias'].map(w => ({ w, re: word(w) }))
11
12// gh reads (PRD 2.2): group -> allowed verbs.
13const READ: Record<string, string[]> = {
14  pr: ['view', 'diff', 'list', 'status', 'checks'], issue: ['view', 'list', 'status'], repo: ['view', 'list'],
15  run: ['view', 'list', 'watch'], release: ['view', 'list'], workflow: ['view', 'list'],
16}
17const SAFE = /^[A-Za-z0-9 ._/:=,@%+-]+$/
18const API_FLAG = /^(--paginate|-i|--include|--silent)$/ // flags without a value
19const API_VALUE = /^(--jq|-q|--cache)$/ // flags with a value, consumed with the next token
20const API_EQ = /^(--jq|--cache)=/
21const isR = (x: string | undefined) => x === '-R' || x === '--repo'
22
23// Left to right (PRD 2.2): a value flag consumes the next token whatever it looks like; a value flag without one is not a read.
24function isGhRead(raw: string): boolean {
25  const t = raw.trim().split(/\s+/)
26  if (!/(^|\/)gh(\.exe)?$/.test(t[0]!) || !SAFE.test(raw.trim())) return false
27  let i = 1
28  while (isR(t[i])) { if (i + 1 >= t.length) return false; i += 2 }
29  const group = t[i]
30  if (!group || group === '--version' || group === 'status' || group === 'search') return true
31  const rest = t.slice(i + 1)
32  if (group === 'api' || group === 'auth') {
33    // strict: only the flags of the table; -R / --repo is not one of them
34    if (group === 'auth' ? rest[0] !== 'status' : rest.some(x => x.includes('://'))) return false // a full URL can send the token away
35    for (let j = group === 'auth' ? 1 : 0; j < rest.length; j++) {
36      const x = rest[j]!
37      const value = group === 'auth' ? /^(-h|--hostname)$/ : API_VALUE
38      if (value.test(x)) { if (++j >= rest.length) return false }
39      else if (!x.startsWith('-')) continue
40      else if (group === 'auth' ? !/^(-a|--active|(-h|--hostname)=.*)$/.test(x) : !API_FLAG.test(x) && !API_EQ.test(x)) return false
41    }
42    return true
43  }
44  const a: string[] = []
45  for (let j = 0; j < rest.length; j++) {
46    if (isR(rest[j])) { if (++j >= rest.length) return false } else a.push(rest[j]!)
47  }
48  return !!READ[group] && (!a[0] || READ[group]!.includes(a[0]))
49}
50
51// The name for the deny message: `gh pr merge`, `git push`, or just `gh` / `git`.
52function verbOf(text: string, ghHit: boolean): string {
53  if (!ghHit) return `git ${WRITE.find(x => x.re.test(text))?.w ?? ''}`.trim()
54  const words = text.slice(text.search(GH) + 2).split(/\s+/).filter(x => /^[a-z][\w-]*$/.test(x))
55  return ['gh', ...(words[0] === 'api' ? ['api'] : words.slice(0, 2))].join(' ')
56}
57
58// The matched verb ('gh pr merge', 'git push', 'gh'), or undefined when the command is not denied.
59// `powershell`: the backtick is an ignored escape there, so it is removed and no exception applies (PRD 2.3).
60export function ghWriteVerb(command: string, powershell = false): string | undefined {
61  const lc = command.toLowerCase()
62  const cur = lc.replace(powershell ? /\\/g : /\\\\/g, '/').replace(powershell ? /['"`]/g : /[\\'"]/g, '')
63  // Bash: also the text with every backslash removed, since a backtick substitution drops one backslash layer first.
64  const texts = powershell ? [cur] : [lc.replace(/[\\'"]/g, ''), cur]
65  const hit = (t: string) => GIT.test(t) && WRITE.some(x => x.re.test(t))
66  const gitHit = texts.some(hit)
67  const text = texts.find(t => (gitHit ? hit(t) : GH.test(t)))
68  if (text === undefined) return undefined
69  const ghHit = GH.test(text)
70  if (powershell) return verbOf(text, ghHit)
71  if (!gitHit && isGhRead(command)) return undefined
72  if (/^\s*(grep|egrep|fgrep)\s/.test(command) && !/[;|&$()<>`\n]/.test(command)) return undefined
73  return verbOf(text, ghHit)
74}
75
76// PRD-027 R6: who may run it, and no retry, no workaround. `unknown` = the agentId has no recorded type.
77export const GH_MSG = {
78  en: (verb: string, unknown: boolean) => `dev-harness: \`${verb}\` is a remote write.${unknown ? ' Denied because the subagent type is unknown (unknown subagent type).' : ''} Only release-manager or the main session may run it. Do not retry and do not work around it; report it to the Coordinator. For a text search, use the Grep tool.`,
79  'pt-br': (verb: string, unknown: boolean) => `dev-harness: \`${verb}\` é uma escrita remota.${unknown ? ' Negado porque o tipo do subagente é desconhecido (unknown subagent type).' : ''} Só o release-manager ou a sessão principal pode rodá-lo. Não tente de novo nem contorne; avise o Coordinator. Para busca de texto, use a ferramenta Grep.`,
80}
81
82// The deny for a Bash call, or undefined. Kit subagents (dh:) other than release-manager and unknown ids are
83// denied on a match; the main session (no agentId) and non-kit subagents are not.
84export function ghDenied(command: string, agentId: unknown, type: string | undefined, unreadable = false, powershell = false): { verb: string; unknown: boolean } | undefined {
85  if (!agentId) return undefined
86  if (type !== undefined && (type === 'dh:release-manager' || !type.startsWith('dh:'))) return undefined
87  const verb = unreadable ? 'unreadable command' : ghWriteVerb(command, powershell)
88  return verb ? { verb, unknown: type === undefined } : undefined
89}
90
hooks/lib/warn.ts 51 lines
1import { resolvePath } from '../runtime-guard.ts'
2
3export const WARN_LINES = 5 // PRD-025 R3/R5: more than this many changed lines is not a small correction
4
5// This project's harness dir only (not any `.harness` on disk): repo mode = `<dir>/.harness/` for `dir` the
6// working dir or one of its ancestors (the repo root is one of them); global mode = under `<home>/projects/`.
7// ponytail: the project <name> is not known to a pure function, so any project under <home>/projects/ passes;
8// narrow it by passing the resolved harness dir if a sibling project's folder must warn.
9function inHarness(abs: string, cwd: string, home: string): boolean {
10  const c = resolvePath('/', cwd).split('/').filter(Boolean)
11  const h = home === '/' ? '' : home
12  for (let i = c.length; i >= 0; i--) {
13    const dir = `/${c.slice(0, i).join('/')}${i ? '/' : ''}.harness`
14    if (abs.startsWith(`${dir}/`) && dir !== h) return true // <home> itself is dh's, not this project's
15  }
16  return !!home && abs.startsWith(`${home === '/' ? '' : home}/projects/`)
17}
18
19// A trailing newline does not open a new line.
20const lines = (s: unknown): number => (typeof s === 'string' && s ? s.replace(/\n$/, '').split('\n').length : 0)
21
22// PRD-025 R5-R7: warning text for a main-session Edit/Write outside the harness dir, else undefined.
23// `exists` answers whether the absolute path is on disk; undefined/throw = unknown, so no warning (fail open).
24// Never denies. `home` is the ADR-007 <home>; '' skips the global-mode allowlist.
25export async function warnWrite(
26  e: any, home: string, cwd: string, exists: (abs: string) => boolean | undefined | Promise<boolean | undefined>,
27): Promise<string | undefined> {
28  try {
29    if (!e || e.agentId || typeof e.file_path !== 'string' || !e.file_path) return undefined
30    if (e.tool !== 'Edit' && e.tool !== 'Write') return undefined
31    const abs = resolvePath(cwd, e.file_path)
32    if (inHarness(abs, cwd, home)) return undefined
33    let why: string
34    if (e.tool === 'Edit') {
35      const n = Math.max(lines(e.old_string), lines(e.new_string))
36      if (n <= WARN_LINES) return undefined
37      why = `${n}-line Edit`
38    } else {
39      if (typeof e.content !== 'string') return undefined
40      const n = lines(e.content)
41      const there = await exists(abs)
42      if (there === undefined) return undefined // unknown: fail open
43      if (n <= WARN_LINES && there) return undefined
44      why = there ? `${n}-line Write` : 'Write of a new file'
45    }
46    return `Coordinator: ${why} on ${e.file_path}. Dispatch a builder for work beyond a small correction (${WARN_LINES} lines, one existing file) (dev-harness runtime guard, warning only).`
47  } catch {
48    return undefined // fail open
49  }
50}
51