Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion harness/.claude-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "harness",
"version": "0.3.4",
"version": "0.4.0",
"description": "Integrated harness: the user's Claude rules enforced at the tool call (git, worktree, delete, venv, port, Linear, memory and order guards; a merge-and-release gate; report lint), plus session tooling and workflow automation.",
"author": {
"name": "unohee"
Expand Down
11 changes: 10 additions & 1 deletion harness/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ The user's own Claude harness as one mod (formerly `house-rules`). It covers thr
- session tooling that used to be shell hooks and prose commands;
- workflow automation for `/commit` and the heartbeat loop.

Each rule feature can be switched with `/harness on|off guards|ship-gate|report-lint|repo-size`. The choice is kept across sessions. `/harness status` shows the current state.
Each rule feature can be switched with `/harness on|off guards|ship-gate|report-lint|repo-size|linear-flow`. The choice is kept across sessions. `/harness status` shows the current state.

Design rule: a check that is deterministic and unambiguous **refuses**. A heuristic one only adds a **note** for the model, and is promoted once false positives have been measured.

Expand Down Expand Up @@ -47,6 +47,15 @@ Refuses or rewrites a single tool call.
- When an AskUserQuestion auto-continues unanswered, the model is told to take each question's `(Recommended)` option.
- If that option is irreversible, it takes the safe hold option instead.

## linear-flow (on)

Since 2026-11-13 an agent works under a Linear issue, and the issue ends Done. This replaces the "only on request" rule of CLAUDE.md §1.5 for creating issues and comments (cancel/split still need the user's approval).

- **Open first:** `Edit`, `Write`, `NotebookEdit`, `git commit`, `git push` and `gh pr create` are refused until the session has an issue: one it created (`save_issue` with no `id`) or an existing one it picked up (`save_issue` with an `id` and a non-Done state, e.g. In Progress). Editing under `~/.claude/`, `/tmp`, `$TMPDIR` or a `trash/` folder is not project work and is exempt. The refusal says how to search for duplicates, open the issue, and which team `~/.claude/linear.json` maps the repo to.
- **Done before stop:** the turn may not stop while an issue the session opened or picked up is not Done. The Stop is blocked up to twice (the ship-gate counter), then only a toast. An issue the user merely names is not tracked until the agent picks it up.
- **Issue ID:** read from the `identifier` field of the `save_issue` result.
- **Off:** `/harness off linear-flow` (kept across sessions) brings back the "only on request" behaviour. Do that when Linear is unavailable, or the refusal would deadlock the session.

## repo-size (on)

Keeps repos under `~/dev` within a size budget: 5 GB of the whole directory, `.git` and ignored files included. Measured on 2026-10-31, most overruns came from `worktrees/`, `trash/` and `testing/`, which the user's own rules produce. A few came from a `.git` full of loose objects.
Expand Down
2 changes: 1 addition & 1 deletion harness/hooks/ask-default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { DEFAULT_TOGGLES } from './state'

type On = Parameters<Register>[0]

const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-2' })
const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-3' })

export type AskQuestion = { question: string; options: ReadonlyArray<{ label: string }> }

Expand Down
67 changes: 65 additions & 2 deletions harness/hooks/flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ type World = {
// Extra process answers a test adds: stdout for an argv, or undefined to fall through.
proc?: (argv: readonly string[]) => string | undefined
logs: string[]
// What a Linear save_issue (create) answers with.
created?: string
}

// The engine beneath the plugin: tools answer with what they were given, so a
Expand All @@ -27,7 +29,9 @@ function world(on: On, store: Record<string, unknown> = {}): World {
w.logs.push(String(e.text))
return { value: undefined }
})
mock.store(on, store)
// The Linear flow is opt-in per test: the older tests edit files with no issue open.
const stored = store.toggles as Record<string, unknown> | undefined
mock.store(on, { ...store, toggles: { linearFlow: false, ...stored } })
mock.env(on, { HOME: '/Users/u', TMPDIR: '/var/folders/xx/T/' })
on('command.register', (_, e) => ({ value: { command: e.name } }))
on('session.start', (_, e) => ({ cwd: e.cwd }))
Expand Down Expand Up @@ -62,6 +66,7 @@ function world(on: On, store: Record<string, unknown> = {}): World {
on('tool.call', (_, e) => {
const input = e as unknown as { command?: string }
w.ran.push(input.command ?? e.tool)
if (e.tool === 'mcp__linear-server__save_issue' && w.created !== undefined && !('id' in e)) return { result: w.created }
return { result: input.command ?? 'ok' }
})

Expand Down Expand Up @@ -405,7 +410,7 @@ describe('phase 3', () => {
})

test('session.start draws the normal status (no row) and session.end clears the piece by the ending id', async ($, on) => {
const w = world(on)
const w = world(on, { toggles: { linearFlow: true } })
on('session.id', () => ({ value: 'live' }))
on('session.end', (_, e) => ({ sessionId: e.sessionId }))
const statuses: unknown[] = []
Expand All @@ -430,3 +435,61 @@ describe('phase 3', () => {
expect(w.ran.filter(r => r.startsWith('source /Users/u/dev/mlx_env/bin/activate && '))).toHaveLength(2)
})
})

describe('linear flow', () => {
const FLOW = { toggles: { linearFlow: true, reportLint: false } }
const save = ($: Engine, input: Record<string, unknown>) => $.tool.call({ tool: 'mcp__linear-server__save_issue', ...input })

test('a change is refused until an issue is opened, then allowed; paths outside the project are exempt', async ($, on) => {
const w = world(on, FLOW)
w.created = '[{"type":"text","text":"{\\"id\\":\\"QQQ-5\\",\\"title\\":\\"x\\"}"}]'
await start($)
await prompt($, '테스트 고쳐줘')
const refused = await $.tool.call({ tool: 'Write', file_path: '/repo/a.py', content: 'x\n' })
expect(refused.deny).toContain('Linear flow')
expect((await $.tool.call({ tool: 'Bash', command: 'git commit -m "x"' })).deny).toContain('Linear flow')
expect((await $.tool.call({ tool: 'Bash', command: 'ls' })).deny).toBeUndefined()
expect((await $.tool.call({ tool: 'Write', file_path: '/Users/u/.claude/projects/-x/memory/a.md', content: 'x\n' })).deny).toBeUndefined()
expect((await $.tool.call({ tool: 'Write', file_path: '/tmp/scratch.py', content: 'x\n' })).deny).toBeUndefined()

expect((await save($, { title: 'x', team: 'T' })).deny).toBeUndefined()
expect((await $.tool.call({ tool: 'Write', file_path: '/repo/a.py', content: 'x\n' })).deny).toBeUndefined()
expect(w.ran).toContain('ls')
})

test('an opened issue blocks the stop until it is Done', async ($, on) => {
world(on, FLOW).created = '{"identifier":"QQQ-5"}'
await start($)
await prompt($, '고쳐줘')
await save($, { title: 'x', team: 'T' })
await $.tool.call({ tool: 'Write', file_path: '/repo/a.py', content: 'x\n' })

const blocked = await $.classic.Stop(STOP)
expect(blocked.block).toContain('QQQ-5')
await save($, { id: 'QQQ-5', state: 'Done' })
expect((await $.classic.Stop(STOP)).block).toBeUndefined()
})

test('picking up an existing issue counts; after two blocks the stop passes with a toast', async ($, on) => {
const w = world(on, FLOW)
await start($)
await prompt($, 'QQQ-7 진행해줘')
expect((await $.tool.call({ tool: 'Write', file_path: '/repo/a.py', content: 'x\n' })).deny).toContain('Linear flow')
await save($, { id: 'QQQ-7', state: 'In Progress' })
expect((await $.tool.call({ tool: 'Write', file_path: '/repo/a.py', content: 'x\n' })).deny).toBeUndefined()

expect((await $.classic.Stop(STOP)).block).toContain('QQQ-7')
expect((await $.classic.Stop(STOP)).block).toContain('QQQ-7')
expect((await $.classic.Stop(STOP)).block).toBeUndefined()
expect(w.toasts.join(' ')).toContain('QQQ-7')
})

test('off: nothing is required; subagent stops are left alone', async ($, on) => {
world(on, FLOW)
await start($)
await command($, 'off linear-flow')
await prompt($, '고쳐줘')
expect((await $.tool.call({ tool: 'Write', file_path: '/repo/a.py', content: 'x\n' })).deny).toBeUndefined()
expect((await $.classic.Stop(STOP)).block).toBeUndefined()
})
})
4 changes: 2 additions & 2 deletions harness/hooks/guards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ import { DEFAULT_TOGGLES, INITIAL_LINT, INITIAL_SHIP } from './state'
import type { ToolCallHook } from './state'

const envAtom = atom({ plugin: 'harness', key: 'env' } as const, {}, { shape: 'env-1' })
const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-2' })
const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-3' })
const lintAtom = atom({ plugin: 'harness', key: 'lint' } as const, INITIAL_LINT, { shape: 'lint-1' })
const shipAtom = atom({ plugin: 'harness', key: 'ship' } as const, INITIAL_SHIP, { shape: 'ship-2' })
const shipAtom = atom({ plugin: 'harness', key: 'ship' } as const, INITIAL_SHIP, { shape: 'ship-3' })
// The venv note was given in this session: once is enough (it rode every
// Python call, measured 2026-10-29, saying the same thing each time).
const venvNotedAtom = atom({ plugin: 'harness', key: 'venvNoted' } as const, false, { shape: 'venv-noted-1' })
Expand Down
80 changes: 80 additions & 0 deletions harness/hooks/linear-flow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { commandWords, programOf, segments, stripProse } from './shell'

// Linear flow (user decision 2026-11-13, replaces CLAUDE.md §1.5's "only on
// request"): an agent that changes things must work under a Linear issue, and
// the issue must end Done.
// - Before the first change (Edit/Write/NotebookEdit, git commit/push, gh pr
// create) the session needs an issue: one it opened (save_issue without id)
// or one it claimed (save_issue on an existing id, e.g. In Progress).
// - A turn may not stop while such an issue is not Done.

export type FlowFacts = {
// Issues this session created.
opened: readonly string[]
// Existing issues the session picked up with save_issue.
claimed: readonly string[]
}

export function hasIssue(facts: FlowFacts): boolean {
return facts.opened.length + facts.claimed.length > 0
}

// Paths whose edits are not project work: the user's own config and memory,
// scratch space and the trash folder.
export function isExemptPath(path: string, home: string | undefined, tmpdir: string | undefined): boolean {
if (/(^|\/)trash\//.test(path) || /^\/(private\/)?tmp\//.test(path) || /^\/private\/var\/folders\//.test(path)) return true
if (tmpdir !== undefined && tmpdir !== '' && path.startsWith(tmpdir)) return true
if (home !== undefined && path.startsWith(`${home}/.claude/`)) return true

return false
}

// A Bash command that publishes work: the commit, the push, the PR.
export function isWorkCommand(command: string): boolean {
return segments(stripProse(command)).some(segment => {
const words = commandWords(segment)
const program = programOf(words)
if (program === 'git') return words[1] === 'commit' || words[1] === 'push'

return program === 'gh' && words[1] === 'pr' && words[2] === 'create'
})
}

export function missingIssueMessage(tool: string, team: string | undefined): string {
const where = team === undefined ? '' : ` This repo maps to team "${team}" in ~/.claude/linear.json.`

return [
`Harness Linear flow: ${tool} changes the project, and this session has no Linear issue for it.`,
'1) Search first so you do not duplicate: list_issues with a project/team and a query.',
'2) Open one with save_issue (no id; title, team, a short description), or pick an existing one up with save_issue (id, state In Progress).',
`3) Then repeat this call. When the work is finished, move that issue to Done (save_issue id + state Done) before ending the turn.${where}`,
].join('\n')
}

export function openIssuesMessage(ids: readonly string[]): string {
return [
'Linear flow: finished work is moved to Done in the same turn.',
...ids.map(id => `- ${id}: save_issue id=${id} state=Done (add an evidence comment with the commit/PR via save_comment)`),
'If the work is really unfinished, say so to the user with AskUserQuestion instead of leaving the issue open silently.',
].join('\n')
}

// The issue identifier a save_issue result carries. Measured live 2026-11-13:
// the Linear MCP answers `[{"type":"text","text":"{\"id\":\"AX-2212\",\"uuid\":...}"}]`, so the
// identifier is in "id" (an "identifier" key is accepted too). It wins over any
// other ID-shaped text, such as one in the description.
export function createdIssueId(result: unknown, patterns: readonly string[] | undefined): string | undefined {
const text = typeof result === 'string' ? result : JSON.stringify(result ?? '')
const labelled = text.match(/\\?"(?:identifier|id)\\?"\s*:\s*\\?"([A-Z][A-Z0-9]{1,5}-\d+)\\?"/)?.[1]
if (labelled !== undefined) return labelled
const any = text.match(/\b[A-Z][A-Z0-9]{1,5}-\d+\b/g) ?? []
const tests = (patterns ?? []).flatMap(pattern => {
try {
return [new RegExp(`^(?:${pattern})$`)]
} catch {
return []
}
})

return tests.length === 0 ? any[0] : any.find(id => tests.some(test => test.test(id)))
}
33 changes: 33 additions & 0 deletions harness/hooks/pure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { checkAgentWorktree, checkMemorySecret, checkSystemPython, checkTradingO
import { kstNow, statusCounts } from './commands'
import { splitPorcelain } from './commit'
import { fireTag, holdReason, parseInterval } from './heartbeat'
import { createdIssueId, hasIssue, isExemptPath, isWorkCommand } from './linear-flow'
import { grantAllowsLinear, grantVerdict, senderName } from './grant'
import { gcSignature, gcSummary } from './memory-gc'
import { checkListIssues, checkSaveComment, checkSaveIssue, isLinearRequest, withoutReminders } from './linear-guard'
Expand Down Expand Up @@ -369,3 +370,35 @@ describe('linearIds', () => {
expect(linearIds(['MAX-1'], patterns)).toEqual([])
})
})

describe('linear flow', () => {
test('work commands: commit, push and PR create, not prose or reads', () => {
expect(isWorkCommand('git commit -m "x"')).toBe(true)
expect(isWorkCommand('cd r && git push origin main')).toBe(true)
expect(isWorkCommand('gh pr create --title t')).toBe(true)
expect(isWorkCommand('git status && git diff')).toBe(false)
expect(isWorkCommand('echo "git commit later"')).toBe(false)
expect(isWorkCommand('git log -1 --format=%s')).toBe(false)
})

test('exempt paths: user config, scratch and trash', () => {
expect(isExemptPath('/Users/u/.claude/projects/p/memory/a.md', '/Users/u', undefined)).toBe(true)
expect(isExemptPath('/tmp/x.py', '/Users/u', undefined)).toBe(true)
expect(isExemptPath('/var/folders/T/x', '/Users/u', '/var/folders/T/')).toBe(true)
expect(isExemptPath('/repo/trash/old.py', '/Users/u', undefined)).toBe(true)
expect(isExemptPath('/repo/src/a.py', '/Users/u', undefined)).toBe(false)
})

test('the created issue ID comes from the identifier field, else a pattern match', () => {
expect(createdIssueId('{"id":"uuid","identifier":"AX-12","title":"see HSG-01"}', undefined)).toBe('AX-12')
expect(createdIssueId({ identifier: 'KT-3' }, undefined)).toBe('KT-3')
// The live Linear MCP shape (measured 2026-11-13).
const live = [{ type: 'text', text: '{"id":"AX-2212","uuid":"4f59","title":"t","description":"relates to HSG-01"}' }]
expect(createdIssueId(live, ['AX-\\d+'])).toBe('AX-2212')
expect(createdIssueId(live, undefined)).toBe('AX-2212')
expect(createdIssueId('created HSG-01 and AX-9', ['AX-\\d+'])).toBe('AX-9')
expect(createdIssueId('no id here', undefined)).toBeUndefined()
expect(hasIssue({ opened: [], claimed: [] })).toBe(false)
expect(hasIssue({ opened: [], claimed: ['AX-1'] })).toBe(true)
})
})
10 changes: 6 additions & 4 deletions harness/hooks/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ import { issueIds, registerShipGate, shipPrompt, shipStop } from './ship-gate'
import { DEFAULT_TOGGLES, INITIAL_SHIP } from './state'

const envAtom = atom({ plugin: 'harness', key: 'env' } as const, {}, { shape: 'env-1' })
const shipAtom = atom({ plugin: 'harness', key: 'ship' } as const, INITIAL_SHIP, { shape: 'ship-2' })
const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-2' })
const shipAtom = atom({ plugin: 'harness', key: 'ship' } as const, INITIAL_SHIP, { shape: 'ship-3' })
const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-3' })

// harness: the user's CLAUDE.md and ~/.claude/rules enforced at the tool
// call (guards, ship-gate, report-lint: each switchable, all on by default),
Expand Down Expand Up @@ -62,6 +62,7 @@ const FEATURES: Record<string, keyof Toggles> = {
'ship-gate': 'shipGate',
'report-lint': 'reportLint',
'repo-size': 'repoSize',
'linear-flow': 'linearFlow',
}

function showStatus($: EngineInterface, toggles: Toggles) {
Expand Down Expand Up @@ -183,7 +184,7 @@ export const register: Register = (on, options) => {
scheduleSweep($)
await $.command.register({
name: COMMAND,
description: 'Harness: /harness [status | on|off guards|ship-gate|report-lint|repo-size | skip-codeql | heartbeat start [5m]|stop|status]',
description: 'Harness: /harness [status | on|off guards|ship-gate|report-lint|repo-size|linear-flow | skip-codeql | heartbeat start [5m]|stop|status]',
})
// A user command of the same name keeps its name; the rest still register.
for (const spec of EXTRA_COMMANDS) {
Expand Down Expand Up @@ -305,9 +306,10 @@ export const register: Register = (on, options) => {

return {
text: [
`guards ${toggles.guards ? 'on' : 'off'} · ship-gate ${toggles.shipGate ? 'on' : 'off'} · report-lint ${toggles.reportLint ? 'on' : 'off'} · repo-size ${toggles.repoSize ? 'on' : 'off'}`,
`guards ${toggles.guards ? 'on' : 'off'} · ship-gate ${toggles.shipGate ? 'on' : 'off'} · report-lint ${toggles.reportLint ? 'on' : 'off'} · repo-size ${toggles.repoSize ? 'on' : 'off'} · linear-flow ${toggles.linearFlow ? 'on' : 'off'}`,
`venv: ${env.venv ?? `missing (${env.venvMissing ?? 'unknown platform'})`}`,
`ship-gate this session: open-PR check ${ship.prListed ? 'done' : 'not yet'}, CodeQL ${ship.codeqlRan ? 'ran' : ship.skipCodeql ? 'waived' : 'not yet'}, issues awaiting Done: ${ship.pending.filter(issue => !issue.done || !issue.commented).map(issue => issue.id).join(', ') || 'none'}`,
`linear-flow this session: opened ${ship.opened.join(', ') || 'none'} · claimed ${ship.claimed.join(', ') || 'none'} · done ${ship.doneIds.join(', ') || 'none'}`,
].join('\n'),
}
})
Expand Down
2 changes: 1 addition & 1 deletion harness/hooks/report-lint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { DEFAULT_TOGGLES, INITIAL_LINT } from './state'
import type { PromptHook, StopHook, ToolCallHook } from './state'

const lintAtom = atom({ plugin: 'harness', key: 'lint' } as const, INITIAL_LINT, { shape: 'lint-1' })
const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-2' })
const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-3' })

// Report lint (toggle, on by default): at most one nudge per turn when the
// final message breaks the user's reporting rules (CLAUDE.md §1, §2). The turn
Expand Down
Loading
Loading