The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Add an opt-in destructive-action gate and a spend brake
bubu-dudueee67f9aaa44
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex fee9c9d09..211a4cf36 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -79,6 +79,9 @@ function argValue(name, fallback) {return fallback}+// Set by the claude PreToolUse gate branch; written to stdout at exit (see the finally block).+let gateOutput = null+function argEngine() {const i = process.argv.indexOf('--engine')const value = i !== -1 ? process.argv[i + 1] : ''@@ -236,6 +239,35 @@ function readStdin() {})}+// Like post(), but resolves the parsed JSON reply (or null). Used where the daemon's answer matters:+// the destructive-action gate hands a permissionDecision back through PreToolUse.+function postJson(port, path, body) {+ return new Promise((resolve) => {+ const payload = JSON.stringify(body)+ const credential = readHookCredential()+ if (!credential) { resolve(null); return }+ const req = http.request(+ {+ host: '127.0.0.1', port, path, method: 'POST',+ headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload), 'X-Harness-Hook-Token': credential },+ timeout: Math.max(1, Math.min(1500, remainingBudget())),+ },+ (res) => {+ let text = ''+ res.setEncoding('utf8')+ res.on('data', (chunk) => { if (text.length < 65536) text += chunk })+ res.on('end', () => {+ if (!((res.statusCode || 0) >= 200 && (res.statusCode || 0) < 300)) { resolve(null); return }+ try { resolve(JSON.parse(text)) } catch { resolve(null) }+ })+ },+ )+ req.on('error', () => resolve(null))+ req.on('timeout', () => { req.destroy(); resolve(null) })+ req.end(payload)+ })+}+function boundedPrompt(prompt) {// An oversized/escape-heavy prompt must still announce its submission so the daemon// clears earlier scope. Keep the serialized field within the hook receiver's bounds.@@ -1481,6 +1513,33 @@ async function main() {return}+ // Claude's PreToolUse is installed ONLY by `harness gate install` (lib/hooks.ts installGateHook). The+ // daemon classifies the tool call against the machine's action policy; a non-allow verdict goes back+ // on stdout in the shape Claude Code reads, so the engine shows its own permission prompt (which the+ // question watcher mirrors to the device). Silence, on any failure, means allow: the gate must never+ // wedge a session because the daemon was busy.+ if (engine === 'claude' && event === 'PreToolUse') {+ if (typeof input.tool_use_id !== 'string' || typeof input.tool_name !== 'string') return+ const reply = await postJson(port, '/api/hook/tool-start', {+ sessionId: input.session_id,+ toolUseId: input.tool_use_id,+ toolName: input.tool_name,+ input: input.tool_input,+ ...mutationFields,+ })+ const gate = reply && reply.gate+ if (gate && (gate.decision === 'ask' || gate.decision === 'deny')) {+ gateOutput = JSON.stringify({+ hookSpecificOutput: {+ hookEventName: 'PreToolUse',+ permissionDecision: gate.decision,+ permissionDecisionReason: `Harness gate: ${gate.reason || gate.rule || 'machine policy'}`,+ },+ })+ }+ return+ }+if (engine === 'cursor' && event === 'preToolUse') {if (input.tool_name === 'Task' && typeof input.tool_use_id === 'string') {await persistCursorTask(input)@@ -1617,5 +1676,6 @@ main()Promise.resolve(acknowledgeMemoryOutput()).catch(() => {}).finally(() => process.exit(0))})else if (e === 'cursor' || e === 'hermes' || e === 'agy' || e === 'copilot') process.stdout.write('{}\n', () => process.exit(0))+ else if (gateOutput) process.stdout.write(gateOutput + '\n', () => process.exit(0)) // claude PreToolUse gate verdictelse process.exit(0)})diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex e11d362e9..7c9646ee6 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -458,7 +458,12 @@ Machine:harness attention [--kanban] every agent's state: working, waiting on you, needs permission, failed, doneharness stop-all [--except=<agentId>]cancel every agent's turn on this computer (the panic stop)- harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktop+ harness gate init|install|uninstall|status|reload+ opt-in Claude guard: ask before git push, rm -rf, sudo …; refuse disk+ writes and ~/.ssh (policy: ~/.harness/cli/data/action-policy.json)+ harness spend status|set --agent-usd=N --day-usd=N|on|off+ per-agent and per-day spend caps; a pane over its cap is held (off by default)+ harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktopharness tui all of Harness in this terminal: swarms, panes, every machine (⌥O ⌥P ⌥N)harness new [agent] [@machine] [folder|name] [-- task]make a harness from a shell: \`harness new\` is claude here; see \`harness new -h\`@@ -4206,7 +4211,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {machineName: () => terminalHintMachineName(),sessions: () => registry.advertised().map(fleetSession),sendLocal: (frame) => backend.sendLocal(frame),+ sendError: (agentId, dbSessionId, message) => backend.send({ type: 'error', agentId, dbSessionId, payload: { message } }),cancelAgent: (agentId, confirmed) => cancelAgent(agentId, confirmed),+ tokenUsage: (s) => { const r = registry.resolve(s.agentId); return r ? agentTokenUsage.get(r) : null },+ // A getter: the port is known once the hook server below has bound, and only `gate install` asks.+ hookPort: () => hookPort,})fleetControlRef = fleetControl@@ -4331,6 +4340,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {},onToolStart: ({ sessionId, toolUseId, toolName, input: toolInput }) => {if (toolName === 'Task') onCursorTaskStart(sessionId, toolUseId, toolInput)+ // The destructive-action gate: classify against the machine policy; the verdict rides back to the+ // hook script, which turns ask/deny into the engine's own permission prompt.+ return fleetControl.gate(sessionId, agentIdFor(sessionId), toolName, toolInput)},onTurnStop: ({ sessionId, status }) => {const session = registry.resolve(sessionId)@@ -7142,6 +7154,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {console.log(`[msg] ${sid(sessionId)} slash-command adapted for engine=${engine}`)}console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · bytes=${Buffer.byteLength(adapted, 'utf8')}`)+ // The spend brake (off until `harness spend set`): a pane over its cap is held and the web is told why.+ if (record && fleetControl.spendCheck(fleetSession(record)).action === 'pause') {+ console.log(`[msg] ${sid(sessionId)} held by the spend brake`)+ return+ }input.submit(record?.agentId ?? sessionId, adapted, deliveryId, tabId)}backend.onMessage = (id, content, deliveryId, tabId) => submitAgent(id, content, deliveryId, tabId)@@ -7972,11 +7989,20 @@ async function daemonCall(method: 'GET' | 'POST', path: string, body?: unknown):async function fleetCommand(cmd: string, args: string[], flags: string[]): Promise<void> {const json = flags.includes('--json')const flag = (name: string): string | undefined => flags.find((f) => f.startsWith(`--${name}=`))?.slice(name.length + 3)+ const num = (name: string): number | null | undefined => { const v = flag(name); if (v === undefined) return undefined; if (v === 'off' || v === 'null') return null; const n = Number(v); return Number.isFinite(n) ? n : undefined }let action = cmdlet body: Record<string, unknown> = {}switch (cmd) {case 'attention': breakcase 'stop-all': body = { except: flag('except') ?? args[0] ?? null }; break+ case 'gate': action = `gate-${args[0] ?? 'status'}`; break+ case 'spend': {+ action = `spend-${args[0] ?? 'status'}`+ if (action === 'spend-set') body = { perAgentUsd: num('agent-usd'), perAgentTokens: num('agent-tokens'), perDayUsd: num('day-usd'), perDayTokens: num('day-tokens'), warnAt: num('warn-at') ?? undefined, ...(flags.includes('--off') ? { enabled: false } : flags.includes('--on') ? { enabled: true } : {}) }+ if (action === 'spend-off') { action = 'spend-set'; body = { enabled: false } }+ if (action === 'spend-on') { action = 'spend-set'; body = { enabled: true } }+ break+ }default: action = args[0] ?? ''; body = {}; if (!action) { console.error('Usage: harness fleet <action> [--key=value ...]'); process.exit(1) }for (const f of flags) { const m = /^--([a-zA-Z-]+)=(.*)$/.exec(f); if (m) body[m[1]!] = m[2] }}@@ -9229,7 +9255,7 @@ switch (cmd) {case 'reset':resetCommand().catch(onError)break- case 'attention': case 'stop-all': case 'fleet':+ case 'attention': case 'stop-all': case 'gate': case 'spend': case 'fleet':fleetCommand(cmd, args, flags).catch(onError)breakcase 'status':diff --git a/cli/src/fleet/control.spec.ts b/cli/src/fleet/control.spec.tsindex b99c9fb4b..d570a6f34 100644--- a/cli/src/fleet/control.spec.ts+++ b/cli/src/fleet/control.spec.ts@@ -1,11 +1,13 @@// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT), as nixfredWiring.spec.ts.-import { mkdtempSync, rmSync } from 'node:fs'+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { FleetControl, type FleetControlDeps, type FleetSessionLike } from './control.js'+vi.mock('../lib/hooks.js', () => ({ installGateHook: () => 'installed', uninstallGateHook: () => 'removed', gateHookInstalled: () => false }))+const session = (agentId: string, extra: Partial<FleetSessionLike> = {}): FleetSessionLike => ({agentId, sessionId: `s-${agentId}`, engine: 'claude', active: true, tmuxPane: '%3', cwd: '/tmp/proj', name: agentId, model: 'claude-sonnet', ...extra,})@@ -14,7 +16,9 @@ describe('FleetControl', () => {let dir: stringlet sent: Array<{ type: string; payload: Record<string, unknown> }>let cancelled: string[]+ let errors: string[]let sessions: FleetSessionLike[]+ let tokens: numberlet fleet: FleetControllet now: number@@ -24,13 +28,16 @@ describe('FleetControl', () => {machineName: () => 'gus',sessions: () => sessions,sendLocal: (f) => { sent.push(f) },+ sendError: (_a, _s, m) => { errors.push(m) },cancelAgent: async (id) => { cancelled.push(id); return true },+ tokenUsage: () => ({ totalTokens: tokens }),+ hookPort: () => 18473,now: () => now,})beforeEach(() => {dir = mkdtempSync(join(tmpdir(), 'fleet-'))- sent = []; cancelled = []; now = Date.UTC(2026, 8, 26, 16, 0)+ sent = []; cancelled = []; errors = []; tokens = 0; now = Date.UTC(2026, 8, 26, 16, 0)sessions = [session('a'), session('b')]fleet = new FleetControl(deps())})@@ -47,6 +54,33 @@ describe('FleetControl', () => {expect(p.agents.map((a) => `${a.agentId}:${a.state}:${a.glyph}`)).toEqual(['b:permission:!', 'a:working:~'])})+ it('gate asks on a push, allows a plain command, and marks the agent as needing permission', () => {+ expect(fleet.gate('s-a', 'a', 'Bash', { command: 'git status' }).decision).toBe('allow')+ const v = fleet.gate('s-a', 'a', 'Bash', { command: 'git push origin main' })+ expect(v).toMatchObject({ decision: 'ask', rule: 'git push' })+ expect(fleet.attention.get('a')?.state).toBe('permission')+ })++ it('spend brake pauses the pane once the per-agent cap is hit and tells the web', () => {+ fleet.spendSet({ perAgentUsd: 1, perDayUsd: null })+ tokens = 100_000+ expect(fleet.spendCheck(session('a')).action).toBe('run')+ tokens = 400_000 // sonnet: 320k in * 3 + 80k out * 15 per M = 0.96 + 1.2 = 2.16 USD+ const v = fleet.spendCheck(session('a'))+ expect(v.action).toBe('pause')+ expect(errors[0]).toMatch(/Spend brake paused: agent at \$2\.16 of \$1/)+ expect(fleet.attention.get('a')).toMatchObject({ state: 'waiting' })+ expect(JSON.parse(readFileSync(join(dir, 'spend-caps.json'), 'utf8')).perAgentUsd).toBe(1)+ const row = (fleet.attentionPayload().agents as Array<{ agentId: string; spend: { usd: number; fraction: number } | null }>).find((r) => r.agentId === 'a')+ expect(row?.spend).toMatchObject({ usd: 2.16, fraction: 1.5 })+ })++ it('leaves the spend brake off until a cap is set', () => {+ tokens = 50_000_000+ expect(fleet.spendCheck(session('a')).action).toBe('run')+ expect(errors).toEqual([])+ })+it('stopAll cancels every active agent but the one kept', async () => {const out = await fleet.stopAll('b')expect(out.cancelled).toEqual(['a'])@@ -60,5 +94,10 @@ describe('FleetControl', () => {expect(att.agents).toHaveLength(2)const stopped = await fleet.command('stop-all', { except: 'a' }) as { cancelled: string[] }expect(stopped.cancelled).toEqual(['b'])+ const status = await fleet.command('gate-status', {}) as { enabled: boolean; rules: number; installed: boolean }+ expect(status).toMatchObject({ enabled: true, installed: false })+ expect(status.rules).toBeGreaterThan(10)+ const caps = await fleet.command('spend-set', { perDayUsd: 42 }) as { caps: { perDayUsd: number; enabled: boolean } }+ expect(caps.caps).toMatchObject({ perDayUsd: 42, enabled: true })})})diff --git a/cli/src/fleet/control.ts b/cli/src/fleet/control.tsindex 7db75ecfa..5b7439aa5 100644--- a/cli/src/fleet/control.ts+++ b/cli/src/fleet/control.ts@@ -7,11 +7,17 @@** attention turn/question/cancel taps → `attention` frames to local windows, `GET /api/attention`* stop-all cancel every agent turn on this machine (`POST /api/stop-all`, `harness stop-all`)+ * gate tool-start → policy verdict (Claude PreToolUse permissionDecision), `harness gate`+ * spend submit → pause when caps are hit; ledger persisted per day, `harness spend`* commands the `harness <command>` local API behind `POST /api/fleet`*/-import { mkdirSync } from 'node:fs'+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'import { env } from '../config/env.js'import { AttentionTracker, summarizeAttention, type AttentionRow } from '../lib/attention.js'+import { DEFAULT_POLICY, evaluateToolCall, parsePolicy, type ActionPolicy, type GateVerdict } from '../lib/actionPolicy.js'+import { DEFAULT_CAPS, decideSpend, emptyLedger, parseCaps, recordUsage, type BrakeVerdict, type SpendCaps, type SpendLedger } from '../lib/spendBrake.js'+import { gateHookInstalled, installGateHook, uninstallGateHook } from '../lib/hooks.js'export interface FleetSessionLike {agentId: string@@ -32,29 +38,61 @@ export interface FleetControlDeps {sessions: () => FleetSessionLike[]/** Push a frame to every local window (desktop). */sendLocal: (frame: { type: string; payload: Record<string, unknown> }) => void+ /** Push an error message frame to the web for one agent. */+ sendError: (agentId: string, sessionId: string, message: string) => voidcancelAgent: (agentId: string, confirmed: boolean) => Promise<boolean>+ tokenUsage: (s: FleetSessionLike) => { totalTokens: number | null } | null+ hookPort: () => numbernow?: () => number}+function readJson<T>(file: string): T | null {+ try { return JSON.parse(readFileSync(file, 'utf8')) as T } catch { return null }+}+function writeJson(file: string, value: unknown): void {+ mkdirSync(join(file, '..'), { recursive: true })+ const tmp = `${file}.${process.pid}.tmp`+ writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n')+ renameSync(tmp, file)+}+export class FleetControl {readonly attention: AttentionTrackerprotected readonly dataDir: stringprotected readonly now: () => number+ private policy: ActionPolicy+ private caps: SpendCaps+ private ledger: SpendLedgerconstructor(protected readonly deps: FleetControlDeps) {this.now = deps.now ?? Date.nowthis.dataDir = deps.dataDir ?? env.ADAPTER_DATA_DIRmkdirSync(this.dataDir, { recursive: true })this.attention = new AttentionTracker(this.now)+ this.policy = this.loadPolicy()+ this.caps = this.loadCaps()+ this.ledger = readJson<SpendLedger>(this.file('spend-ledger.json')) ?? emptyLedger(this.now())this.attention.onChange(() => this.pushAttention())}+ protected file(name: string): string { return join(this.dataDir, name) }+// ── attention ───────────────────────────────────────────────────────────────────────────────────snapshot(): AttentionRow[] { return this.attention.snapshot(this.deps.sessions(), this.deps.machineName()) }attentionPayload(): Record<string, unknown> {- const agents = this.snapshot()+ // Each agent carries the name of the first policy lane its name matches (planner, publisher ...),+ // so the bar can show the role beside the state.+ const lanes = this.policy.lanes ?? []+ const agents = this.snapshot().map((row) => {+ const spent = this.ledger.agents[row.agentId]+ const cap = this.caps.enabled ? this.caps.perAgentUsd : null+ // Spend rides on the row so the bar can draw it as the ring's outer arc: fraction of the+ // per-agent cap when one is set, else null (no arc).+ const spend = spent ? { usd: Number(spent.usd.toFixed(2)), tokens: spent.input + spent.output, fraction: cap ? Math.min(1.5, spent.usd / cap) : null } : null+ return { ...row, lane: lanes.find((l) => { try { return new RegExp(l.agent, 'i').test(row.name) } catch { return false } })?.name ?? null, spend }+ })return { machineId: this.deps.machineId(), hostname: this.deps.machineName(), at: this.now(), summary: summarizeAttention(agents), agents }}@@ -63,6 +101,76 @@ export class FleetControl {this.deps.sendLocal({ type: 'attention', payload: this.attentionPayload() })}+ // ── gate ────────────────────────────────────────────────────────────────────────────────────────++ private loadPolicy(): ActionPolicy {+ const raw = readJson<unknown>(this.file('action-policy.json'))+ if (raw === null) return DEFAULT_POLICY+ const parsed = parsePolicy(raw)+ if (parsed.ok) return parsed.policy+ console.error(`[gate] action-policy.json ignored: ${parsed.problems.join('; ')}`)+ return DEFAULT_POLICY+ }++ /** A tool call is about to run: classify it. Only reached when `harness gate install` added the hook. */+ gate(sessionId: string, agentId: string, toolName: string, input: unknown): GateVerdict {+ const agentName = this.deps.sessions().find((s) => s.agentId === agentId)?.name ?? ''+ const verdict = evaluateToolCall(this.policy, toolName, input, agentName)+ if (verdict.decision !== 'allow') {+ console.log(`[gate] ${agentId} ${sessionId} ${toolName} → ${verdict.decision} (${verdict.rule})`)+ if (verdict.decision === 'ask') this.attention.question(agentId, true, verdict.reason)+ }+ return verdict+ }++ gateStatus(): Record<string, unknown> {+ return { installed: gateHookInstalled(), enabled: this.policy.enabled, rules: this.policy.rules.length, file: this.file('action-policy.json'), fileExists: existsSync(this.file('action-policy.json')) }+ }++ gateInit(): string { const f = this.file('action-policy.json'); if (!existsSync(f)) writeJson(f, DEFAULT_POLICY); this.policy = this.loadPolicy(); return f }++ // ── spend ───────────────────────────────────────────────────────────────────────────────────────++ private loadCaps(): SpendCaps {+ const raw = readJson<unknown>(this.file('spend-caps.json'))+ if (raw === null) return DEFAULT_CAPS+ const parsed = parseCaps(raw)+ if (parsed.ok) return parsed.caps+ console.error(`[spend] spend-caps.json ignored: ${parsed.problems.join('; ')}`)+ return DEFAULT_CAPS+ }++ /** Record what this agent has used so far, then decide whether its next turn may run. */+ spendCheck(s: FleetSessionLike): BrakeVerdict {+ const usage = this.deps.tokenUsage(s)+ const total = usage?.totalTokens ?? 0+ // The engines report a total; treat a fifth as output, which is where most of the money goes.+ this.ledger = recordUsage(this.ledger, { agentId: s.agentId, model: s.model ?? null, input: Math.round(total * 0.8), output: Math.round(total * 0.2), now: this.now() })+ writeJson(this.file('spend-ledger.json'), this.ledger)+ const verdict = decideSpend(this.caps, this.ledger, s.agentId)+ if (verdict.action !== 'run') console.log(`[spend] ${s.agentId} ${verdict.action}: ${verdict.reason}`)+ if (verdict.action === 'pause') {+ this.attention.question(s.agentId, false, `spend brake: ${verdict.reason}`)+ this.deps.sendError(s.agentId, s.sessionId, `Spend brake ${verdict.reason}. Raise the cap with "harness spend set" to continue.`)+ }+ return verdict+ }++ spendStatus(): Record<string, unknown> {+ return { caps: this.caps, day: this.ledger.day, agents: Object.values(this.ledger.agents).map((a) => ({ agentId: a.agentId, model: a.model, tokens: a.input + a.output, usd: Number(a.usd.toFixed(4)) })) }+ }++ spendSet(patch: Partial<SpendCaps>): SpendCaps {+ // Setting a cap is asking for the brake: the default is off (subscription users pay no list price).+ const setsCap = ['perAgentUsd', 'perAgentTokens', 'perDayUsd', 'perDayTokens'].some((k) => typeof (patch as Record<string, unknown>)[k] === 'number')+ const next = { ...this.caps, ...(setsCap && patch.enabled === undefined ? { enabled: true } : {}), ...patch, version: 1 as const }+ const parsed = parseCaps(next)+ if (!parsed.ok) throw new Error(parsed.problems.join('; '))+ this.caps = parsed.caps+ writeJson(this.file('spend-caps.json'), this.caps)+ return this.caps+ }+// ── panic stop ─────────────────────────────────────────────────────────────────────────────────async stopAll(exceptAgentId: string | null): Promise<{ cancelled: string[] }> {@@ -83,9 +191,24 @@ export class FleetControl {switch (action) {case 'attention': return this.attentionPayload()case 'stop-all': return this.stopAll(str('except') || null)+ case 'gate-status': return this.gateStatus()+ case 'gate-init': return { file: this.gateInit() }+ case 'gate-install': return { result: installGateHook(this.deps.hookPort()), ...this.gateStatus() }+ case 'gate-uninstall': return { result: uninstallGateHook(), ...this.gateStatus() }+ case 'gate-reload': this.policy = this.loadPolicy(); return this.gateStatus()+ case 'spend-status': return this.spendStatus()+ case 'spend-set': {+ const patch: Partial<SpendCaps> = {}+ for (const k of ['perAgentUsd', 'perAgentTokens', 'perDayUsd', 'perDayTokens', 'warnAt'] as const) {+ if (args[k] === null) patch[k] = null as never+ else if (typeof args[k] === 'number') patch[k] = args[k] as never+ }+ if (typeof args.enabled === 'boolean') patch.enabled = args.enabled+ return { caps: this.spendSet(patch) }+ }default: throw new Error(`unknown fleet action: ${action}`)}}}-export type { AttentionRow }+export type { AttentionRow, GateVerdict, BrakeVerdict }diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.tsindex 50b846a42..0568b8dd6 100644--- a/cli/src/hookNotify.spec.ts+++ b/cli/src/hookNotify.spec.ts@@ -1169,3 +1169,20 @@ describe('hook notify Command Code re-registration', () => {expect(requests.map((r) => r.url)).toEqual(['/api/hook/turn-stop'])})})++// The destructive-action gate (cli/src/lib/actionPolicy.ts; first written by Fred Nix in the nixfred fork).+describe('claude PreToolUse gate', () => {+ const input = { hook_event_name: 'PreToolUse', session_id: 'claude-session', tool_name: 'Bash', tool_use_id: 'toolu_1', tool_input: { command: 'git push origin main' } }+ it('turns the daemon\'s ask verdict into Claude\'s own permission prompt', async () => {+ const { port, requests } = await collect({ ok: true, gate: { decision: 'ask', rule: 'git push', reason: 'git push needs your approval' } })+ const stdout = await runHook({ port, tmuxPane: '%7', input })+ expect(JSON.parse(stdout)).toEqual({ hookSpecificOutput: {+ hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: 'Harness gate: git push needs your approval',+ } })+ expect(requests.find((r) => r.url === '/api/hook/tool-start')?.body).toMatchObject({ sessionId: 'claude-session', toolName: 'Bash', input: { command: 'git push origin main' } })+ })+ it('stays silent (allow) when the daemon says nothing about the call', async () => {+ const { port } = await collect({ ok: true })+ expect(await runHook({ port, tmuxPane: '%7', input })).toBe('')+ })+})diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 2b1f98b85..9e8c24336 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -13,6 +13,7 @@ import { hermesSessionSource, isHermesInteractiveSource } from './engines/hermesimport { hermesDbPath, listHermesHomes } from './engines/hermes/home.js'import { isRecentlyDeleted } from './lib/deletedSessions.js'import { registry, type RegisterInput, type RegisteredSession } from './lib/registry.js'+import type { GateVerdict } from './lib/actionPolicy.js'import { LOCAL_WEB_HTML } from './webui.js'import { sid } from './lib/log.js'import { VERSION } from './version.js'@@ -115,7 +116,7 @@ export interface HookServerHandlers {toolUseId: stringtoolName: stringinput: unknown- }) => void+ }) => void | GateVerdict | Promise<void | GateVerdict>/** GET /api/attention: every agent's attention state for the bar widget and other local readers. */onAttention?: () => unknown/** POST /api/stop-all: cancel every agent's turn except one (the panic stop). */@@ -705,16 +706,24 @@ export function startHookServer(body = parsed} catch { json(400, { error: 'bad json' }); return }if (!await verifiedBoundMutation(body, handlers)) { json(403, { error: 'UNBOUND_HOOK' }); return }+ let gate: GateVerdict | undefinedif (body.sessionId && body.toolUseId && body.toolName) {console.log(`[hooks] ${sid(body.sessionId)} tool-start · tool=${body.toolName}`)- handlers.onToolStart?.({- sessionId: body.sessionId,- toolUseId: body.toolUseId,- toolName: body.toolName,- input: body.input,- })+ try {+ const verdict = await handlers.onToolStart?.({+ sessionId: body.sessionId,+ toolUseId: body.toolUseId,+ toolName: body.toolName,+ input: body.input,+ })+ if (verdict && verdict.decision !== 'allow') gate = verdict+ } catch (e) {+ console.error('[hooks] tool-start handler failed:', e instanceof Error ? e.message : e)+ }}- json(200, { ok: true })+ // The gate verdict rides back to the hook script, which turns it into the engine's own+ // permission prompt. Allow is the absence of the field, so an older script sees `{ok:true}`.+ json(200, gate ? { ok: true, gate } : { ok: true })return}diff --git a/cli/src/lib/actionPolicy.spec.ts b/cli/src/lib/actionPolicy.spec.tsnew file mode 100644index 000000000..b9ca31919--- /dev/null+++ b/cli/src/lib/actionPolicy.spec.ts@@ -0,0 +1,94 @@+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).++import { describe, expect, it } from 'vitest'+import { DEFAULT_POLICY, claudePreToolUseOutput, evaluateToolCall, flattenToolInput, parsePolicy } from './actionPolicy.js'++const bash = (command: string) => evaluateToolCall(DEFAULT_POLICY, 'Bash', { command })++describe('evaluateToolCall with the default policy', () => {+ it('allows ordinary commands', () => {+ expect(bash('git status && npm test').decision).toBe('allow')+ expect(bash('ls -la ~/Projects').decision).toBe('allow')+ expect(bash('grep -rn "rm -rf" docs/').decision).toBe('ask') // conservative: the text matches+ })+ it('asks before push, force push, hard reset, branch -D, rm -rf, sudo', () => {+ expect(bash('git push origin main')).toMatchObject({ decision: 'ask', rule: 'git push' })+ expect(bash('git push --force origin main').decision).toBe('ask')+ expect(bash('git reset --hard HEAD~1')).toMatchObject({ decision: 'ask', rule: 'git reset --hard / checkout -- / restore .' })+ expect(bash('git branch -D feature').rule).toBe('branch delete')+ expect(bash('rm -rf build/').rule).toBe('recursive delete')+ expect(bash('rm -fr build/').rule).toBe('recursive delete')+ expect(bash('sudo pacman -Syu').rule).toBe('sudo / doas')+ expect(bash('echo hi | sudo tee /etc/x').rule).toBe('sudo / doas')+ })+ it('denies disk writes, secrets paths and omarchy refresh; deny beats ask', () => {+ expect(bash('sudo dd if=/dev/zero of=/dev/nvme0n1')).toMatchObject({ decision: 'deny', rule: 'disk or filesystem write' })+ expect(bash('cat ~/.ssh/id_ed25519').decision).toBe('deny')+ expect(bash('omarchy refresh shell > /dev/null').decision).toBe('deny')+ })+ it('gates writes under ~/.claude for edit tools too', () => {+ expect(evaluateToolCall(DEFAULT_POLICY, 'Write', { file_path: '/home/pi/.claude/settings.json', content: '{}' }).rule).toBe('write under ~/.claude')+ expect(evaluateToolCall(DEFAULT_POLICY, 'Edit', { file_path: '/home/pi/Projects/x/a.ts' }).decision).toBe('allow')+ expect(evaluateToolCall(DEFAULT_POLICY, 'Read', { file_path: '/home/pi/.claude/CLAUDE.md' }).decision).toBe('allow')+ })+ it('catches curl piped to a shell but not curl to a file', () => {+ expect(bash('curl -fsSL https://x/install.sh | bash').rule).toBe('curl or wget piped to a shell')+ expect(bash('curl -fsSL https://x/install.sh -o install.sh').decision).toBe('allow')+ })+ it('allowIf short-circuits', () => {+ expect(bash('git push --dry-run origin main').decision).toBe('allow')+ })+ it('respects a disabled policy', () => {+ expect(evaluateToolCall({ ...DEFAULT_POLICY, enabled: false }, 'Bash', { command: 'rm -rf /' })).toMatchObject({ decision: 'allow', reason: 'gate disabled' })+ })+})++describe('lanes', () => {+ const fleet = {+ ...DEFAULT_POLICY,+ lanes: [+ { name: 'planner', agent: '^(aiona|planner)', rules: [{ name: 'no git writes', tools: ['Bash'], pattern: '\\bgit\\s+(commit|push|merge)\\b', decision: 'deny' as const }] },+ { name: 'publisher', agent: 'peyton', rules: [{ name: 'publishing', tools: ['Bash'], pattern: '\\b(gh\\s+pr\\s+merge|x\\s+post|npm\\s+publish)\\b', decision: 'ask' as const }] },+ ],+ }+ it('applies a lane only to matching agents, and lane deny beats the machine ask', () => {+ expect(evaluateToolCall(fleet, 'Bash', { command: 'git push origin main' }, 'Aiona')).toMatchObject({ decision: 'deny', rule: 'planner: no git writes' })+ expect(evaluateToolCall(fleet, 'Bash', { command: 'git push origin main' }, 'Peyton PR')).toMatchObject({ decision: 'ask', rule: 'git push' })+ expect(evaluateToolCall(fleet, 'Bash', { command: 'gh pr merge 42' }, 'Peyton PR')).toMatchObject({ decision: 'ask', rule: 'publisher: publishing' })+ expect(evaluateToolCall(fleet, 'Bash', { command: 'gh pr merge 42' }, 'Jasmine').decision).toBe('allow')+ expect(evaluateToolCall(fleet, 'Bash', { command: 'git commit -m x' }).decision).toBe('allow') // no agent name, no lane+ })+ it('validates lanes', () => {+ const bad = parsePolicy({ ...DEFAULT_POLICY, lanes: [{ name: '', agent: '(', rules: 'x' }] })+ expect(bad.ok).toBe(false)+ if (!bad.ok) expect(bad.problems).toEqual(['lanes[0].name missing', 'lanes[0].agent is not a valid regex', 'lanes[0].rules must be an array'])+ })+})++describe('flattenToolInput', () => {+ it('flattens nested objects and arrays, bounded depth', () => {+ expect(flattenToolInput({ a: 'x', b: [1, { c: 'y' }], d: null })).toBe('x\n1\ny\n')+ expect(flattenToolInput('plain')).toBe('plain')+ })+})++describe('parsePolicy', () => {+ it('accepts the default and rejects broken rules with specific problems', () => {+ expect(parsePolicy(DEFAULT_POLICY)).toEqual({ ok: true, policy: DEFAULT_POLICY })+ const bad = parsePolicy({ version: 2, enabled: 'yes', rules: [{ name: '', pattern: '(', decision: 'maybe', tools: [1] }] })+ expect(bad.ok).toBe(false)+ if (!bad.ok) expect(bad.problems).toEqual([+ 'version must be 1', 'enabled must be a boolean', 'rules[0].name missing',+ 'rules[0].pattern is not a valid regex', 'rules[0].decision must be ask or deny', 'rules[0].tools must be strings',+ ])+ })+})++describe('claudePreToolUseOutput', () => {+ it('is null for allow and the documented shape otherwise', () => {+ expect(claudePreToolUseOutput({ decision: 'allow', rule: null, reason: '' })).toBeNull()+ expect(claudePreToolUseOutput({ decision: 'ask', rule: 'git push', reason: 'git push needs your approval' })).toEqual({+ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: 'Harness gate: git push needs your approval' },+ })+ })+})diff --git a/cli/src/lib/actionPolicy.ts b/cli/src/lib/actionPolicy.tsnew file mode 100644index 000000000..d7263a1b2--- /dev/null+++ b/cli/src/lib/actionPolicy.ts@@ -0,0 +1,152 @@+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).++/**+ * The destructive-action gate. A per-machine policy file names tool calls that must be asked about or+ * refused before the engine runs them. The decision is handed back through the engine's own hook+ * (Claude Code PreToolUse `permissionDecision`), so the prompt appears in the terminal and reaches the+ * device through the question watcher that already mirrors permission dialogs. Nothing here executes;+ * it only classifies.+ */+export type GateDecision = 'allow' | 'ask' | 'deny'++export interface GateRule {+ /** Human name, shown as the reason. */+ name: string+ /** Tool names this applies to; empty means every tool. */+ tools?: string[]+ /** Regex (source) matched against the flattened tool input. */+ pattern: string+ decision: Exclude<GateDecision, 'allow'>+}++/**+ * A lane: rules that apply only to agents whose name matches. This is how a fleet says "the planner+ * never pushes, the publisher never posts without me": one policy file, one lane per role, the+ * machine-wide rules still apply underneath.+ */+export interface GateLane {+ name: string+ /** Regex (source) matched case-insensitively against the agent's display name. */+ agent: string+ rules: GateRule[]+}++export interface ActionPolicy {+ version: 1+ enabled: boolean+ rules: GateRule[]+ /** Substrings that, when present in the flattened input, always allow (for known-safe wrappers). */+ allowIf?: string[]+ lanes?: GateLane[]+}++const HOME = '(?:~|\\$HOME|/home/[^/\\s]+|/Users/[^/\\s]+)'++/** What `harness gate init` writes when no policy file exists: ask before risky writes, refuse the unrecoverable. */+export const DEFAULT_POLICY: ActionPolicy = {+ version: 1,+ enabled: true,+ rules: [+ { name: 'git push', tools: ['Bash'], pattern: '\\bgit\\s+push\\b', decision: 'ask' },+ { name: 'force push', tools: ['Bash'], pattern: '\\bgit\\s+push\\b[^\\n]*(--force|-f\\b|\\+\\S)', decision: 'ask' },+ { name: 'git reset --hard / checkout -- / restore .', tools: ['Bash'], pattern: '\\bgit\\s+(reset\\s+--hard|checkout\\s+--\\s|restore\\s+\\.|clean\\s+-\\w*f)', decision: 'ask' },+ { name: 'branch delete', tools: ['Bash'], pattern: '\\bgit\\s+branch\\s+-D\\b', decision: 'ask' },+ { name: 'recursive delete', tools: ['Bash'], pattern: '\\brm\\s+(-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r|-r\\b|-R\\b)', decision: 'ask' },+ { name: 'sudo / doas', tools: ['Bash'], pattern: '(^|[\\s;&|])(sudo|doas)\\s', decision: 'ask' },+ { name: 'disk or filesystem write', tools: ['Bash'], pattern: '\\b(mkfs(\\.\\w+)?\\b|dd\\s+if=|wipefs\\b|fdisk\\b|parted\\b)', decision: 'deny' },+ { name: 'curl or wget piped to a shell', tools: ['Bash'], pattern: '\\b(curl|wget)\\b[^\\n|]*\\|\\s*(sudo\\s+)?(ba|z|da)?sh\\b', decision: 'ask' },+ { name: 'world-writable chmod', tools: ['Bash'], pattern: '\\bchmod\\s+(-R\\s+)?[0-7]?777\\b', decision: 'ask' },+ { name: 'kill everything', tools: ['Bash'], pattern: '\\b(pkill|killall)\\s+(-9\\s+)?(-f\\s+)?["\']?(claude|codex|tmux|harness|node)\\b', decision: 'ask' },+ { name: 'write under ~/.claude', tools: ['Bash', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit'], pattern: `${HOME}/\\.claude/`, decision: 'ask' },+ { name: 'write under ~/.ssh or ~/.env', tools: ['Bash', 'Write', 'Edit', 'MultiEdit'], pattern: `${HOME}/(\\.ssh/|\\.env\\b|\\.gnupg/)`, decision: 'deny' },+ { name: 'systemd unit or service change', tools: ['Bash'], pattern: '\\bsystemctl\\s+(--user\\s+)?(enable|disable|mask|stop|restart)\\b', decision: 'ask' },+ { name: 'omarchy refresh (factory reset)', tools: ['Bash'], pattern: '\\bomarchy\\s+refresh\\b|omarchy-refresh-', decision: 'deny' },+ ],+ allowIf: ['--dry-run'],+}++/** Flatten any tool input into one searchable string (command, file_path, content, nested fields). */+export function flattenToolInput(input: unknown, depth = 0): string {+ if (input == null) return ''+ if (typeof input === 'string') return input+ if (typeof input === 'number' || typeof input === 'boolean') return String(input)+ if (depth > 4) return ''+ if (Array.isArray(input)) return input.map((v) => flattenToolInput(v, depth + 1)).join('\n')+ if (typeof input === 'object') return Object.values(input as Record<string, unknown>).map((v) => flattenToolInput(v, depth + 1)).join('\n')+ return ''+}++export interface GateVerdict { decision: GateDecision; rule: string | null; reason: string }++const compiled = new WeakMap<GateRule, RegExp>()+function regex(rule: GateRule): RegExp {+ let re = compiled.get(rule)+ if (!re) { re = new RegExp(rule.pattern, 'i'); compiled.set(rule, re) }+ return re+}++const laneRegex = new WeakMap<GateLane, RegExp>()+function laneMatches(lane: GateLane, agentName: string): boolean {+ let re = laneRegex.get(lane)+ if (!re) { re = new RegExp(lane.agent, 'i'); laneRegex.set(lane, re) }+ return re.test(agentName)+}++/** Deny beats ask beats allow. An `allowIf` substring short-circuits to allow. Lane rules run first. */+export function evaluateToolCall(policy: ActionPolicy, toolName: string, input: unknown, agentName = ''): GateVerdict {+ if (!policy.enabled) return { decision: 'allow', rule: null, reason: 'gate disabled' }+ const text = flattenToolInput(input)+ if (!text) return { decision: 'allow', rule: null, reason: 'no input' }+ for (const safe of policy.allowIf ?? []) if (text.includes(safe)) return { decision: 'allow', rule: null, reason: `allowIf ${safe}` }+ let verdict: GateVerdict = { decision: 'allow', rule: null, reason: 'no rule matched' }+ const laneRules = (policy.lanes ?? []).filter((l) => agentName && laneMatches(l, agentName)).flatMap((l) => l.rules.map((r) => ({ ...r, name: `${l.name}: ${r.name}` })))+ for (const rule of [...laneRules, ...policy.rules]) {+ if (rule.tools && rule.tools.length && !rule.tools.includes(toolName)) continue+ if (!regex(rule).test(text)) continue+ if (rule.decision === 'deny') return { decision: 'deny', rule: rule.name, reason: `${rule.name} is refused by the machine policy` }+ if (verdict.decision === 'allow') verdict = { decision: 'ask', rule: rule.name, reason: `${rule.name} needs your approval` }+ }+ return verdict+}++/** Validate a parsed policy file; returns the policy or a list of problems. Unknown fields are kept. */+export function parsePolicy(raw: unknown): { ok: true; policy: ActionPolicy } | { ok: false; problems: string[] } {+ const problems: string[] = []+ if (!raw || typeof raw !== 'object') return { ok: false, problems: ['policy must be an object'] }+ const p = raw as Record<string, unknown>+ if (p.version !== 1) problems.push('version must be 1')+ if (typeof p.enabled !== 'boolean') problems.push('enabled must be a boolean')+ if (!Array.isArray(p.rules)) problems.push('rules must be an array')+ else p.rules.forEach((r, i) => {+ const rule = r as Record<string, unknown>+ if (typeof rule.name !== 'string' || !rule.name) problems.push(`rules[${i}].name missing`)+ if (typeof rule.pattern !== 'string') problems.push(`rules[${i}].pattern missing`)+ else { try { new RegExp(rule.pattern) } catch { problems.push(`rules[${i}].pattern is not a valid regex`) } }+ if (rule.decision !== 'ask' && rule.decision !== 'deny') problems.push(`rules[${i}].decision must be ask or deny`)+ if (rule.tools !== undefined && (!Array.isArray(rule.tools) || rule.tools.some((t) => typeof t !== 'string'))) problems.push(`rules[${i}].tools must be strings`)+ })+ if (p.allowIf !== undefined && (!Array.isArray(p.allowIf) || p.allowIf.some((t) => typeof t !== 'string'))) problems.push('allowIf must be strings')+ if (p.lanes !== undefined) {+ if (!Array.isArray(p.lanes)) problems.push('lanes must be an array')+ else p.lanes.forEach((l, i) => {+ const lane = l as Record<string, unknown>+ if (typeof lane.name !== 'string' || !lane.name) problems.push(`lanes[${i}].name missing`)+ if (typeof lane.agent !== 'string') problems.push(`lanes[${i}].agent missing`)+ else { try { new RegExp(lane.agent) } catch { problems.push(`lanes[${i}].agent is not a valid regex`) } }+ if (!Array.isArray(lane.rules)) problems.push(`lanes[${i}].rules must be an array`)+ })+ }+ return problems.length ? { ok: false, problems } : { ok: true, policy: raw as ActionPolicy }+}++/** The JSON Claude Code expects on a PreToolUse hook's stdout for a non-allow verdict. */+export function claudePreToolUseOutput(v: GateVerdict): Record<string, unknown> | null {+ if (v.decision === 'allow') return null+ return {+ hookSpecificOutput: {+ hookEventName: 'PreToolUse',+ permissionDecision: v.decision,+ permissionDecisionReason: `Harness gate: ${v.reason}`,+ },+ }+}diff --git a/cli/src/lib/hooks.spec.ts b/cli/src/lib/hooks.spec.tsindex 22526d591..d332b672b 100644--- a/cli/src/lib/hooks.spec.ts+++ b/cli/src/lib/hooks.spec.ts@@ -602,3 +602,37 @@ describe('Hermes hook allowlist', () => {expect(new Set(ours.map((a) => a.event)).size).toBe(ours.length)})})++// The opt-in destructive-action gate hook (first written by Fred Nix in the nixfred fork).+describe('Claude gate hook (harness gate install)', () => {+ let home = ''+ const settingsFile = () => join(home, '.claude', 'settings.json')+ const read = () => JSON.parse(readFileSync(settingsFile(), 'utf8')) as { hooks: Record<string, Array<{ matcher?: string; hooks: Array<{ command: string }> }>> }+ beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'adapter-claude-gate-')); vi.stubEnv('HOME', home) })+ afterEach(() => { vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }) })++ it('installs PreToolUse beside a foreign one, reports unchanged, and uninstalls only its own block', async () => {+ mkdirSync(join(home, '.claude'), { recursive: true })+ writeFileSync(settingsFile(), JSON.stringify({ hooks: { PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: 'my-own-guard' }] }] } }))+ const { installGateHook, uninstallGateHook, gateHookInstalled } = await loadHooks()+ expect(gateHookInstalled()).toBe(false)+ expect(installGateHook(18473)).toBe('installed')+ expect(installGateHook(18473)).toBe('unchanged')+ expect(gateHookInstalled()).toBe(true)+ const blocks = read().hooks.PreToolUse+ expect(blocks.map((b) => b.hooks[0]!.command)).toEqual(['my-own-guard', expect.stringContaining('notify.mjs')])+ expect(blocks[1]).toMatchObject({ matcher: 'Bash|Write|Edit|MultiEdit|NotebookEdit' })+ expect(uninstallGateHook()).toBe('removed')+ expect(read().hooks.PreToolUse.map((b) => b.hooks[0]!.command)).toEqual(['my-own-guard'])+ expect(uninstallGateHook()).toBe('absent')+ })++ it('keeps an installed gate on the session hooks\' port, and never adds one by itself', async () => {+ const { installGateHook, installSessionHooks } = await loadHooks()+ installSessionHooks(18473)+ expect(read().hooks.PreToolUse).toBeUndefined()+ installGateHook(18473)+ installSessionHooks(18599)+ expect(read().hooks.PreToolUse[0]!.hooks[0]!.command).toContain('--port 18599')+ })+})diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.tsindex 146756464..a52082d8d 100644--- a/cli/src/lib/hooks.ts+++ b/cli/src/lib/hooks.ts@@ -129,6 +129,15 @@ export function installSessionHooks(port: number): void {settings.hooks[event] = [...foreign, { hooks: [{ type: 'command', command: cmd, timeout: 5 }] }]}+ // The opt-in gate hook (installGateHook) runs the same command: keep its path and port in step with+ // the session hooks, but never add it here — only `harness gate install` does that.+ const gateBlocks = Array.isArray(settings.hooks[GATE_EVENT]) ? settings.hooks[GATE_EVENT] : []+ if (gateBlocks.some((b) => isOurs(b) && b.hooks.some((h) => isOurs({ hooks: [h] }) && h.command !== cmd))) {+ settings.hooks[GATE_EVENT] = gateBlocks.map((b) => isOurs(b) ? { ...b, hooks: b.hooks.map((h) => isOurs({ hooks: [h] }) ? { ...h, command: cmd } : h) } : b)+ changed = true+ updated = true+ }+if (!changed) {console.log('[hooks] Claude session + turn (Stop/StopFailure) hooks already installed')return@@ -148,6 +157,58 @@ export function installSessionHooks(port: number): void {}}+/**+ * The destructive-action gate for Claude Code (lib/actionPolicy.ts; first written by Fred Nix in the+ * nixfred fork): a PreToolUse hook on the tools that can change the world. OPT-IN (`harness gate+ * install`), never part of `harness start`: it edits a person's own Claude settings, and the gate only+ * earns its place once a policy has been read and agreed to. The same notify script serves it; the+ * daemon answers with a `permissionDecision` the engine understands.+ */+export const GATE_EVENT = 'PreToolUse'+export const GATE_MATCHER = 'Bash|Write|Edit|MultiEdit|NotebookEdit'++export function installGateHook(port: number): 'installed' | 'updated' | 'unchanged' | 'failed' {+ let settings: Settings = {}+ try { settings = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8')) as Settings } catch { /* start empty */ }+ if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}+ const cmd = command(port, 'claude')+ const blocks = Array.isArray(settings.hooks[GATE_EVENT]) ? settings.hooks[GATE_EVENT] : []+ const foreign = blocks.filter((b) => !isOurs(b))+ const ours = blocks.filter(isOurs)+ const existingCmd = ours[0]?.hooks?.find((h) => isOurs({ hooks: [h] }))?.command+ const state = ours.length === 0 ? 'installed' : (existingCmd !== cmd || ours[0]?.matcher !== GATE_MATCHER || ours.length > 1) ? 'updated' : 'unchanged'+ if (state === 'unchanged') return state+ settings.hooks[GATE_EVENT] = [...foreign, { matcher: GATE_MATCHER, hooks: [{ type: 'command', command: cmd, timeout: 5 }] }]+ try {+ mkdirSync(dirname(SETTINGS_PATH), { recursive: true })+ writeJsonAtomic(SETTINGS_PATH, settings)+ console.log(`[gate] ${state} Claude PreToolUse gate hook → ${SETTINGS_PATH} (takes effect on the next claude session start)`)+ return state+ } catch (err) {+ console.error('[gate] failed to write settings.json:', err)+ return 'failed'+ }+}++export function uninstallGateHook(): 'removed' | 'absent' | 'failed' {+ let settings: Settings = {}+ try { settings = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8')) as Settings } catch { return 'absent' }+ const blocks = Array.isArray(settings.hooks?.[GATE_EVENT]) ? settings.hooks![GATE_EVENT] : []+ const foreign = blocks.filter((b) => !isOurs(b))+ if (foreign.length === blocks.length) return 'absent'+ if (foreign.length) settings.hooks![GATE_EVENT] = foreign+ else delete settings.hooks![GATE_EVENT]+ try { writeJsonAtomic(SETTINGS_PATH, settings); return 'removed' } catch (err) { console.error('[gate] failed to write settings.json:', err); return 'failed' }+}++export function gateHookInstalled(): boolean {+ try {+ const settings = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8')) as Settings+ const blocks = Array.isArray(settings.hooks?.[GATE_EVENT]) ? settings.hooks![GATE_EVENT] : []+ return blocks.some(isOurs)+ } catch { return false }+}+function writeJsonAtomic(file: string, value: unknown): void {mkdirSync(dirname(file), { recursive: true })const tmp = `${file}.${process.pid}.tmp`diff --git a/cli/src/lib/spendBrake.spec.ts b/cli/src/lib/spendBrake.spec.tsnew file mode 100644index 000000000..301da1885--- /dev/null+++ b/cli/src/lib/spendBrake.spec.ts@@ -0,0 +1,65 @@+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).++import { describe, expect, it } from 'vitest'+import { DEFAULT_CAPS, dayKey, decideSpend, emptyLedger, estimateUsd, parseCaps, priceFor, recordUsage } from './spendBrake.js'++// 2026-09-26T03:30:00Z is 23:30 on the 25th in New York.+const NIGHT = Date.UTC(2026, 8, 26, 3, 30)+const MORNING = Date.UTC(2026, 8, 26, 12, 0)++describe('prices', () => {+ it('matches by family substring with a fallback', () => {+ expect(priceFor('claude-opus-4-1')).toEqual({ input: 15, output: 75 })+ expect(priceFor('qwen2.5-coder:14b-local').input).toBe(0)+ expect(priceFor('mystery-model')).toEqual({ input: 3, output: 15 })+ expect(estimateUsd({ input: 1_000_000, output: 100_000 }, priceFor('sonnet'))).toBeCloseTo(4.5)+ })+})++describe('ledger', () => {+ it('keys days in the given time zone and rolls over at its local midnight', () => {+ const tz = 'America/New_York'+ expect(dayKey(NIGHT, tz)).toBe('2026-09-25')+ expect(dayKey(MORNING, tz)).toBe('2026-09-26')+ let l = recordUsage(emptyLedger(NIGHT, tz), { agentId: 'a', model: 'sonnet', input: 500_000, output: 50_000, now: NIGHT }, undefined, tz)+ expect(l.agents.a?.usd).toBeCloseTo(2.25)+ l = recordUsage(l, { agentId: 'b', model: 'sonnet', input: 100, output: 10, now: MORNING }, undefined, tz)+ expect(l.day).toBe('2026-09-26')+ expect(Object.keys(l.agents)).toEqual(['b'])+ })+})++describe('decideSpend', () => {+ const caps = { ...DEFAULT_CAPS, enabled: true, perAgentUsd: 10, perDayUsd: 20 }+ it('runs, warns at 80 percent, pauses at the cap, naming the tightest cap', () => {+ let l = recordUsage(emptyLedger(MORNING), { agentId: 'a', model: 'sonnet', input: 1_000_000, output: 100_000, now: MORNING }) // $4.50+ expect(decideSpend(caps, l, 'a').action).toBe('run')+ l = recordUsage(l, { agentId: 'a', model: 'sonnet', input: 2_000_000, output: 150_000, now: MORNING }) // $8.25+ expect(decideSpend(caps, l, 'a')).toMatchObject({ action: 'warn', fraction: 0.825 })+ l = recordUsage(l, { agentId: 'a', model: 'sonnet', input: 3_000_000, output: 100_000, now: MORNING }) // $10.50+ const v = decideSpend(caps, l, 'a')+ expect(v.action).toBe('pause')+ expect(v.reason).toBe('paused: agent at $10.50 of $10')+ })+ it('the day cap pauses a cheap agent when others spent the budget', () => {+ let l = recordUsage(emptyLedger(MORNING), { agentId: 'big', model: 'opus', input: 1_000_000, output: 100_000, now: MORNING }) // $22.50+ l = recordUsage(l, { agentId: 'small', model: 'haiku', input: 1000, output: 100, now: MORNING })+ const v = decideSpend(caps, l, 'small')+ expect(v.action).toBe('pause')+ expect(v.reason).toMatch(/machine at \$22\.50 of \$20 today/)+ })+ it('disabled or capless means run', () => {+ const l = emptyLedger(MORNING)+ expect(decideSpend({ ...caps, enabled: false }, l, 'a').action).toBe('run')+ expect(decideSpend({ ...caps, perAgentUsd: null, perDayUsd: null }, l, 'a').reason).toBe('no caps set')+ })+})++describe('parseCaps', () => {+ it('validates shape', () => {+ expect(parseCaps(DEFAULT_CAPS).ok).toBe(true)+ const bad = parseCaps({ version: 1, enabled: true, perAgentUsd: -1, perAgentTokens: null, perDayUsd: 'x', perDayTokens: null, warnAt: 2 })+ expect(bad.ok).toBe(false)+ if (!bad.ok) expect(bad.problems).toEqual(['perAgentUsd must be null or a non-negative number', 'perDayUsd must be null or a non-negative number', 'warnAt must be in (0, 1]'])+ })+})diff --git a/cli/src/lib/spendBrake.ts b/cli/src/lib/spendBrake.tsnew file mode 100644index 000000000..89c1d75be--- /dev/null+++ b/cli/src/lib/spendBrake.ts@@ -0,0 +1,118 @@+// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).++/**+ * Spend brake: token and dollar caps per agent, per machine and per day that pause a pane instead of+ * letting an overnight Loop run up a bill. The daemon already counts tokens per agent+ * (lib/agentTokenUsage.ts) but has no price table and nothing that stops; this is both, pure.+ */+export interface PriceUsdPerMillion { input: number; output: number }++/** Rough list prices, USD per million tokens, by model family substring. First match wins. */+export const DEFAULT_PRICES: Array<{ match: string; price: PriceUsdPerMillion }> = [+ { match: 'opus', price: { input: 15, output: 75 } },+ { match: 'sonnet', price: { input: 3, output: 15 } },+ { match: 'haiku', price: { input: 0.8, output: 4 } },+ { match: 'gpt-5', price: { input: 1.25, output: 10 } },+ { match: 'o3', price: { input: 2, output: 8 } },+ { match: 'codex', price: { input: 1.5, output: 6 } },+ { match: 'grok', price: { input: 3, output: 15 } },+ { match: 'gemini', price: { input: 1.25, output: 10 } },+ { match: 'kimi', price: { input: 0.6, output: 2.5 } },+ { match: 'local', price: { input: 0, output: 0 } },+ { match: 'ollama', price: { input: 0, output: 0 } },+]+export const FALLBACK_PRICE: PriceUsdPerMillion = { input: 3, output: 15 }++export function priceFor(model: string | null | undefined, table = DEFAULT_PRICES): PriceUsdPerMillion {+ const m = (model ?? '').toLowerCase()+ for (const row of table) if (m.includes(row.match)) return row.price+ return FALLBACK_PRICE+}++export function estimateUsd(tokens: { input: number; output: number }, price: PriceUsdPerMillion): number {+ return (tokens.input * price.input + tokens.output * price.output) / 1_000_000+}++export interface SpendCaps {+ version: 1+ enabled: boolean+ /** Per agent for its lifetime. */+ perAgentUsd: number | null+ perAgentTokens: number | null+ /** Per machine per local calendar day. */+ perDayUsd: number | null+ perDayTokens: number | null+ /** Warn at this fraction of any cap (0.8 = 80 percent). */+ warnAt: number+}++export const DEFAULT_CAPS: SpendCaps = { version: 1, enabled: false, perAgentUsd: null, perAgentTokens: null, perDayUsd: null, perDayTokens: null, warnAt: 0.8 }++export interface AgentSpend { agentId: string; model: string | null; input: number; output: number; usd: number; updatedAt: number }++export interface BrakeVerdict {+ action: 'run' | 'warn' | 'pause'+ reason: string+ agentUsd: number+ dayUsd: number+ /** 0..1 of the tightest cap consumed; > 1 when over. */+ fraction: number+}++export interface SpendLedger {+ day: string+ agents: Record<string, AgentSpend>+}++/** The calendar day a reading belongs to, in this machine's own time zone unless one is named. */+export function dayKey(now: number, timeZone?: string): string {+ return new Intl.DateTimeFormat('en-CA', { ...(timeZone ? { timeZone } : {}), year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(now))+}++export function emptyLedger(now: number, timeZone?: string): SpendLedger { return { day: dayKey(now, timeZone), agents: {} } }++/** Fold a usage reading into the ledger, starting a new day when the calendar turns. */+export function recordUsage(ledger: SpendLedger, reading: { agentId: string; model: string | null; input: number; output: number; now: number }, prices = DEFAULT_PRICES, timeZone?: string): SpendLedger {+ const day = dayKey(reading.now, timeZone)+ const base = ledger.day === day ? ledger : emptyLedger(reading.now, timeZone)+ const usd = estimateUsd({ input: reading.input, output: reading.output }, priceFor(reading.model, prices))+ return { ...base, agents: { ...base.agents, [reading.agentId]: { agentId: reading.agentId, model: reading.model, input: reading.input, output: reading.output, usd, updatedAt: reading.now } } }+}++export function dayTotals(ledger: SpendLedger): { usd: number; tokens: number } {+ let usd = 0, tokens = 0+ for (const a of Object.values(ledger.agents)) { usd += a.usd; tokens += a.input + a.output }+ return { usd, tokens }+}++/** Should this agent's next turn run, run with a warning, or be paused? */+export function decideSpend(caps: SpendCaps, ledger: SpendLedger, agentId: string): BrakeVerdict {+ const agent = ledger.agents[agentId]+ const agentUsd = agent?.usd ?? 0+ const agentTokens = agent ? agent.input + agent.output : 0+ const day = dayTotals(ledger)+ if (!caps.enabled) return { action: 'run', reason: 'brake disabled', agentUsd, dayUsd: day.usd, fraction: 0 }+ const fractions: Array<[number, string]> = []+ if (caps.perAgentUsd) fractions.push([agentUsd / caps.perAgentUsd, `agent at $${agentUsd.toFixed(2)} of $${caps.perAgentUsd}`])+ if (caps.perAgentTokens) fractions.push([agentTokens / caps.perAgentTokens, `agent at ${agentTokens} of ${caps.perAgentTokens} tokens`])+ if (caps.perDayUsd) fractions.push([day.usd / caps.perDayUsd, `machine at $${day.usd.toFixed(2)} of $${caps.perDayUsd} today`])+ if (caps.perDayTokens) fractions.push([day.tokens / caps.perDayTokens, `machine at ${day.tokens} of ${caps.perDayTokens} tokens today`])+ if (!fractions.length) return { action: 'run', reason: 'no caps set', agentUsd, dayUsd: day.usd, fraction: 0 }+ const [fraction, reason] = fractions.reduce((a, b) => (b[0] > a[0] ? b : a))+ if (fraction >= 1) return { action: 'pause', reason: `paused: ${reason}`, agentUsd, dayUsd: day.usd, fraction }+ if (fraction >= caps.warnAt) return { action: 'warn', reason: `warning: ${reason}`, agentUsd, dayUsd: day.usd, fraction }+ return { action: 'run', reason, agentUsd, dayUsd: day.usd, fraction }+}++export function parseCaps(raw: unknown): { ok: true; caps: SpendCaps } | { ok: false; problems: string[] } {+ const problems: string[] = []+ if (!raw || typeof raw !== 'object') return { ok: false, problems: ['caps must be an object'] }+ const c = raw as Record<string, unknown>+ if (c.version !== 1) problems.push('version must be 1')+ if (typeof c.enabled !== 'boolean') problems.push('enabled must be a boolean')+ for (const k of ['perAgentUsd', 'perAgentTokens', 'perDayUsd', 'perDayTokens'] as const) {+ if (c[k] !== null && !(typeof c[k] === 'number' && c[k] >= 0)) problems.push(`${k} must be null or a non-negative number`)+ }+ if (!(typeof c.warnAt === 'number' && c.warnAt > 0 && c.warnAt <= 1)) problems.push('warnAt must be in (0, 1]')+ return problems.length ? { ok: false, problems } : { ok: true, caps: raw as SpendCaps }+}