diff --git a/README.md b/README.md index e320c9c..d1be259 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Claude Code mods (plugins with a hooks module), served as a local folder marketp | mod | version | what it does | | --- | --- | --- | -| [harness](harness/) | 0.3.4 | The integrated harness: the user's Claude rules enforced at the tool call, session tooling and workflow automation (formerly house-rules) | +| [harness](harness/) | 0.5.0 | The integrated harness: the user's Claude rules enforced at the tool call, session tooling and workflow automation (formerly house-rules) | | [auto-claude](auto-claude/) | 1.4.0 | Unattended run of a repository through to live: plans the long-term goal, milestones and deploy; its own loop builds and judges each milestone in a worktree; ships each (push, PR, required CI, merge), deploys and smoke-checks it; a watchdog repairs or routes around stalls; replans until the final check passes. Absorbed goal-mode in 1.0.0; since 1.1.0 the session never rests: the next milestone is built, stacked, while a PR waits on CI; since 1.3.0 a line can wait on a training run or cache build (`:: after:`, `wait_until`) without ending the run; since 1.4.0 `--always-on` stands by after the final check and wakes for new cycles from Linear, the live smoke check, the default branch's CI and labelled GitHub issues | | [model-tier](model-tier/) | 0.11.0 | Routes each main-loop turn to fable, opus, sonnet or haiku and a reasoning effort by task complexity, with a `set_tier` tool the model calls to correct either | | [refactor](refactor/) | 0.1.3 | Enforces the architecture a repo declares in `.claude/architecture.json` at Edit/Write (layer direction, forbidden imports), notes code smells with the refactoring.guru technique to apply, `/arch audit` for violations and import cycles | diff --git a/auto-claude/README.md b/auto-claude/README.md index e172a37..03eec2e 100644 --- a/auto-claude/README.md +++ b/auto-claude/README.md @@ -67,7 +67,7 @@ With `--always-on` (or the `alwaysOn` option), a run does not end when its final - **Trust.** Labelling needs triage access, so the label is the gate: an issue is work when someone who may label it says so, once. Only its number and title go into the line, with `::` and brackets removed, so a title cannot add a check or a base. The model reads the issue itself while building; its body is still third-party text, so label only issues whose body you would hand the run. Peer messages and webhook text do not wake a run. - **`--once`** opts a single start out when `alwaysOn` is the default. - **Waking.** Only when the session has had no turn for 2 min: a person may use the session while it stands by. A cycle builds, ships and deploys like any run, without a new planning round; its final check passing stands it by again. A failing one replans, as a run does. -- **Standing by owns nothing.** The guards and the unattended policy are off, `.claude/auto-claude.on` says `on: false, phase: standby` (harness's Linear rules apply again), and the watchdog's idle notices are quiet. +- **Standing by owns nothing.** The guards and the unattended policy are off, `.claude/auto-claude.on` says `on: false, phase: standby`, and the watchdog's idle notices are quiet. - **Caps.** `maxMerges` and `maxHours` count per cycle; standby time counts toward neither. `maxMergesPerDay` (20) holds a wake back while the last 24 h hold that many merges, told once. 3 deploys failing in a row still stop the run. - **Memory.** Each cycle adds one line under `## Cycles` in `auto-plan.md`: what woke it, what merged, was held and deployed. On entering standby the session is compacted once (when its context is 30% full or more), keeping the goal, decisions and cycles. - **Quiet.** In standby a person is told only of a wake (and why), a cycle's end, a failing smoke check or GitHub poll, and the daily cap. @@ -112,9 +112,9 @@ A run keeps the repository's Linear project in step, through the session's own ` - **Planning.** The planning prompt (and each replan) lists the project's open issues: triage, backlog, unstarted and started. A milestone that resolves issues starts with their IDs: `- [ ] [AX-12] :: check: `. An open issue the plan leaves out gets a line under `## Decisions`. - **While the run goes.** Every 10 minutes, and once more before the run may finish, the driver reads the open issues. It also reads the newest comments on the 25 most recently changed issues and on every issue the run has a line for. A new comment on an older issue waits until the issue itself changes. Every open issue counts as covered from the moment the run starts, so comments written before it never count. A run that started unmapped (or under an older version) adopts the project on its next tick. Comments do not move an issue's `updatedAt` (measured 2026-11-13), so they are read on their own. An issue that is new or changed since the run last covered it gets a queue line, at most 5 per sync. The line has no check, so the evaluator judges it: `- [ ] [AX-12] : what Linear AX-12 asks is resolved on this branch (…)`. A change to an issue whose line is still pending is covered by that line. A change to an issue being built or shipped is looked at when it merges. Each issue gets at most 2 follow-up lines. - **Closed issues.** An issue closed while its line waits (cancelled, done elsewhere) blocks that line. The driver never moves a closed issue back to `started`. At merge, a closed issue only gets the evidence comment. -- **No new issues during a run.** The model is told not to create issues, and harness refuses an unrequested create while a run owns the repository. Otherwise a new issue would become a milestone of the same run. +- **No new issues during a run.** The model is told not to create issues, and harness refuses an issue create the user did not ask for. Otherwise a new issue would become a milestone of the same run. - **Write-back.** A milestone that starts moves its issues to `started`. One that merges moves them to `completed`, with a comment naming the PR. If the issue changed in Linear while the milestone was built, it stays open instead, with a comment and a follow-up line. A held or blocked milestone gets a comment only. The driver's comments start with `[auto-claude]` and never count as changes. The model is told never to change these issues' state or comment on them. -- **Signal for other mods.** Each tick writes `.claude/auto-claude.on` (`{ on, phase, at }`, git-excluded). harness reads it, and leaves issue states to the driver while a run owns the repository. +- **Signal for other mods.** Each tick writes `.claude/auto-claude.on` (`{ on, phase, at }`, git-excluded), so other mods can tell whether a run owns the repository. - `--queue` runs neither read nor write Linear. ## Autonomy and its limits diff --git a/auto-claude/hooks/register.ts b/auto-claude/hooks/register.ts index a9a0aaa..f4803e4 100644 --- a/auto-claude/hooks/register.ts +++ b/auto-claude/hooks/register.ts @@ -89,16 +89,15 @@ async function readRecord($: EngineInterface, root: string): Promise<AutoRecord async function writeRecord($: EngineInterface, r: AutoRecord): Promise<void> { await $.store.set(STORE(r.root), r) - // Other plugins cannot read this store: harness reads this file to know a run - // owns the repository (its Linear flow leaves issue states to the driver). + // Other plugins cannot read this store: this file tells them a run owns the + // repository. // A run standing by owns nothing: the person may work in the repository meanwhile. await $.fs.write(`${r.root}/.claude/auto-claude.on`, `${JSON.stringify({ on: owns(r), phase: r.phase, at: await $.clock.now() })}\n`).catch(() => undefined) await show($, r) } // The run holds the session and the repository: on, and not standing by -// between cycles. Its guards, its unattended policy and harness's hands-off -// Linear flow apply only then. +// between cycles. Its guards and its unattended policy apply only then. const owns = (r: Pick<AutoRecord, 'on' | 'phase'> | undefined): boolean => r?.on === true && r.phase !== 'standby' // Issue IDs of queue lines not started yet, and of the milestones being built or shipped. diff --git a/harness/.claude-plugin/plugin.json b/harness/.claude-plugin/plugin.json index 8158537..52c9755 100644 --- a/harness/.claude-plugin/plugin.json +++ b/harness/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "harness", - "version": "0.4.1", + "version": "0.5.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" diff --git a/harness/README.md b/harness/README.md index 52f930d..029bf97 100644 --- a/harness/README.md +++ b/harness/README.md @@ -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|linear-flow`. 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`. 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. @@ -47,16 +47,6 @@ 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 started state: In Progress, In Review, `started`). A label or priority edit is not a pick-up. 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. A Cancel/Duplicate transition (which needs the user's approval) takes the issue off the list. 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 `id` field of the `save_issue` result (live shape, 2026-11-13); an `identifier` field is accepted too. -- **auto-claude runs:** while `<repo>/.claude/auto-claude.on` says a run is on and ticked within 15 minutes, nothing is gated and the Stop is not blocked: the auto-claude driver opens, moves and closes the issues itself. Creating an issue goes back to needing the user's request, since a new issue would become a milestone of that run. -- **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. diff --git a/harness/hooks/ask-default.ts b/harness/hooks/ask-default.ts index efd0164..0c8cac0 100644 --- a/harness/hooks/ask-default.ts +++ b/harness/hooks/ask-default.ts @@ -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-3' }) +const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-4' }) export type AskQuestion = { question: string; options: ReadonlyArray<{ label: string }> } diff --git a/harness/hooks/flow.test.ts b/harness/hooks/flow.test.ts index 8d7df4f..770eae6 100644 --- a/harness/hooks/flow.test.ts +++ b/harness/hooks/flow.test.ts @@ -17,7 +17,6 @@ type World = { 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 @@ -29,9 +28,7 @@ function world(on: On, store: Record<string, unknown> = {}): World { w.logs.push(String(e.text)) return { value: undefined } }) - // 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.store(on, store) 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 })) @@ -66,7 +63,6 @@ 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' } }) @@ -410,7 +406,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, { toggles: { linearFlow: true } }) + const w = world(on) on('session.id', () => ({ value: 'live' })) on('session.end', (_, e) => ({ sessionId: e.sessionId })) const statuses: unknown[] = [] @@ -436,84 +432,22 @@ describe('phase 3', () => { }) }) -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) +describe('linear-flow removed (0.5.0)', () => { + test('a stored linear-flow toggle is dropped: edits are not gated, a picked-up issue does not block the stop', async ($, on) => { + world(on, { toggles: { linearFlow: true, reportLint: false } }) 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 $.tool.call({ tool: 'Bash', command: 'git commit -m "x"' })).deny).toBeUndefined() + expect((await $.tool.call({ tool: 'mcp__linear-server__save_issue', id: 'QQQ-7', state: 'In Progress' })).deny).toBeUndefined() expect((await $.classic.Stop(STOP)).block).toBeUndefined() + expect((await command($, 'status')).text).not.toContain('linear-flow') }) - test('a label edit is not a claim; a cancelled issue is not demanded Done', async ($, on) => { - world(on, FLOW) - await start($) - await prompt($, 'QQQ-8 정리해줘') - await save($, { id: 'QQQ-8', priority: 2 }) - expect((await $.tool.call({ tool: 'Write', file_path: '/repo/a.py', content: 'x\n' })).deny).toContain('Linear flow') - await save($, { id: 'QQQ-8', state: 'In Progress' }) - await $.tool.call({ tool: 'AskUserQuestion', questions: [] }) - await save($, { id: 'QQQ-8', state: 'Canceled' }) - expect((await $.classic.Stop(STOP)).block).toBeUndefined() - }) - - test('while an auto-claude run owns the repo, nothing is gated or blocked', async ($, on) => { - const w = world(on, FLOW) - w.files.set('/repo/.claude/auto-claude.on', JSON.stringify({ on: true, phase: 'run', at: Date.now() })) + test('creating an issue needs a Linear request again', async ($, on) => { + world(on) await start($) - await prompt($, '[auto-claude loop] Milestone #1') - expect((await $.tool.call({ tool: 'Write', file_path: '/repo/worktrees/goal-01/a.py', content: 'x\n' })).deny).toBeUndefined() - expect((await $.tool.call({ tool: 'Bash', command: 'git commit -m "m1"' })).deny).toBeUndefined() + await prompt($, '테스트 고쳐줘') expect((await $.tool.call({ tool: 'mcp__linear-server__save_issue', title: 'x', team: 'T' })).deny).toContain('§1.5') - w.files.set('/repo/.claude/auto-claude.on', JSON.stringify({ on: false, phase: 'done', at: Date.now() })) - expect((await $.tool.call({ tool: 'Write', file_path: '/repo/a.py', content: 'x\n' })).deny).toContain('Linear flow') }) }) diff --git a/harness/hooks/guards.ts b/harness/hooks/guards.ts index 4fe47e5..d5da61d 100644 --- a/harness/hooks/guards.ts +++ b/harness/hooks/guards.ts @@ -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-3' }) +const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-4' }) 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-3' }) +const shipAtom = atom({ plugin: 'harness', key: 'ship' } as const, INITIAL_SHIP, { shape: 'ship-4' }) // 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' }) diff --git a/harness/hooks/linear-flow.ts b/harness/hooks/linear-flow.ts deleted file mode 100644 index f06848d..0000000 --- a/harness/hooks/linear-flow.ts +++ /dev/null @@ -1,104 +0,0 @@ -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))) -} - -// A save_issue state that means the agent took the issue up (In Progress, In -// Review, started). A label or priority edit, or a state given as an ID, is not. -export function isStartedState(state: unknown): boolean { - return typeof state === 'string' && /\b(progress|started|review|doing|active)\b/i.test(state) -} - -export function isDroppedState(state: unknown): boolean { - return typeof state === 'string' && /cancel|duplicate/i.test(state) -} - -// auto-claude's signal file (<repo>/.claude/auto-claude.on), written on each -// tick of a run: a run that is on and ticked within RUN_FRESH_MS owns the repo. -export const RUN_FRESH_MS = 15 * 60_000 - -export function runOwnsRepo(text: string | undefined, now: number): boolean { - if (text === undefined) return false - try { - const v = JSON.parse(text) as { on?: unknown; at?: unknown } - return v.on === true && typeof v.at === 'number' && now - v.at < RUN_FRESH_MS - } catch { - return false - } -} diff --git a/harness/hooks/pure.test.ts b/harness/hooks/pure.test.ts index e67acaf..a472bbc 100644 --- a/harness/hooks/pure.test.ts +++ b/harness/hooks/pure.test.ts @@ -15,7 +15,6 @@ import { checkAgentWorktree, checkMemorySecret, checkSystemPython, checkTradingO import { kstNow, statusCounts } from './commands' import { splitPorcelain } from './commit' import { fireTag, holdReason, parseInterval } from './heartbeat' -import { createdIssueId, hasIssue, isDroppedState, isExemptPath, isStartedState, isWorkCommand, runOwnsRepo } from './linear-flow' import { grantAllowsLinear, grantVerdict, senderName } from './grant' import { gcSignature, gcSummary } from './memory-gc' import { checkListIssues, checkSaveComment, checkSaveIssue, isLinearRequest, withoutReminders } from './linear-guard' @@ -370,56 +369,3 @@ 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) - }) -}) - -describe('linear flow states and auto-claude runs', () => { - test('only a started state takes an issue up; cancel and duplicate drop it', () => { - expect(isStartedState('In Progress')).toBe(true) - expect(isStartedState('started')).toBe(true) - expect(isStartedState('In Review')).toBe(true) - expect(isStartedState('Todo')).toBe(false) - expect(isStartedState(undefined)).toBe(false) - expect(isDroppedState('Canceled')).toBe(true) - expect(isDroppedState('Duplicate')).toBe(true) - expect(isDroppedState('Done')).toBe(false) - }) - - test('an auto-claude run owns the repo while it is on and ticked within 15 min', () => { - expect(runOwnsRepo(JSON.stringify({ on: true, at: 1_000 }), 1_000 + 60_000)).toBe(true) - expect(runOwnsRepo(JSON.stringify({ on: true, at: 1_000 }), 1_000 + 16 * 60_000)).toBe(false) - expect(runOwnsRepo(JSON.stringify({ on: false, at: 1_000 }), 1_000)).toBe(false) - expect(runOwnsRepo('not json', 0)).toBe(false) - expect(runOwnsRepo(undefined, 0)).toBe(false) - }) -}) diff --git a/harness/hooks/register.ts b/harness/hooks/register.ts index 7e393c7..1f198fe 100644 --- a/harness/hooks/register.ts +++ b/harness/hooks/register.ts @@ -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-3' }) -const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-3' }) +const shipAtom = atom({ plugin: 'harness', key: 'ship' } as const, INITIAL_SHIP, { shape: 'ship-4' }) +const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-4' }) // 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), @@ -62,7 +62,6 @@ const FEATURES: Record<string, keyof Toggles> = { 'ship-gate': 'shipGate', 'report-lint': 'reportLint', 'repo-size': 'repoSize', - 'linear-flow': 'linearFlow', } function showStatus($: EngineInterface, toggles: Toggles) { @@ -166,7 +165,11 @@ export const register: Register = (on, options) => { on('session.start', async ($, e, next) => { const stored = await $.store.get(STORE_KEY) - const toggles = { ...DEFAULT_TOGGLES, ...(typeof stored === 'object' && stored !== null ? (stored as Partial<Toggles>) : {}) } + // Only known features: a stored toggle of a removed feature (linear-flow, 0.5.0) is dropped. + const kept = typeof stored === 'object' && stored !== null ? (stored as Record<string, unknown>) : {} + const toggles = Object.fromEntries( + Object.entries(DEFAULT_TOGGLES).map(([key, value]) => [key, typeof kept[key] === 'boolean' ? kept[key] : value]), + ) as Toggles await update($, togglesAtom, () => toggles) await loadGuardEnv($) // Loaded into a running session: earlier prompts still count as requests. @@ -184,7 +187,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|linear-flow | skip-codeql | heartbeat start [5m]|stop|status]', + description: 'Harness: /harness [status | on|off guards|ship-gate|report-lint|repo-size | 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) { @@ -306,10 +309,9 @@ 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'} · linear-flow ${toggles.linearFlow ? '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'}`, `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'), } }) diff --git a/harness/hooks/report-lint.ts b/harness/hooks/report-lint.ts index 1d5e228..1f6e582 100644 --- a/harness/hooks/report-lint.ts +++ b/harness/hooks/report-lint.ts @@ -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-3' }) +const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-4' }) // 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 diff --git a/harness/hooks/ship-gate.ts b/harness/hooks/ship-gate.ts index f7daa2d..ad7fb10 100644 --- a/harness/hooks/ship-gate.ts +++ b/harness/hooks/ship-gate.ts @@ -4,7 +4,6 @@ import type { EngineInterface, Register } from 'claude-code' import type { PendingIssue } from '../types' import { mergedWorktreeNote } from './extra-guards' import { grantAllowsLinear, readGrant } from './grant' -import { createdIssueId, hasIssue, isDroppedState, isExemptPath, isStartedState, isWorkCommand, missingIssueMessage, openIssuesMessage, runOwnsRepo } from './linear-flow' import { heartbeatOn } from './heartbeat' import { checkListIssues, checkSaveComment, checkSaveIssue, isLinearRequest, repoTeam, withoutReminders } from './linear-guard' import type { LinearFacts } from './linear-guard' @@ -12,8 +11,8 @@ import { commandWords, programOf, segments, stripProse } from './shell' import { DEFAULT_TOGGLES, INITIAL_LINT, INITIAL_SHIP } from './state' import type { PromptHook, StopHook } from './state' -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' }) +const shipAtom = atom({ plugin: 'harness', key: 'ship' } as const, INITIAL_SHIP, { shape: 'ship-4' }) +const togglesAtom = atom({ plugin: 'harness', key: 'toggles' } as const, DEFAULT_TOGGLES, { shape: 'toggles-4' }) const lintAtom = atom({ plugin: 'harness', key: 'lint' } as const, INITIAL_LINT, { shape: 'lint-1' }) const envAtom = atom({ plugin: 'harness', key: 'env' } as const, {}, { shape: 'env-1' }) @@ -156,11 +155,6 @@ export function registerShipGate(on: On): void { if (!toggles.shipGate) return next(e) const command = e.command - if (isWorkCommand(command)) { - const missing = await missingIssue($, 'this git/PR command') - if (missing !== undefined) return { deny: missing } - } - if (isReleaseCommand(command)) { const ship = await read($, shipAtom) const missing = [ @@ -187,41 +181,15 @@ export function registerShipGate(on: On): void { return ran }) - for (const tool of ['Edit', 'Write', 'NotebookEdit'] as const) { - on('tool.call', { tool }, async ($, e, next) => { - const input = e as unknown as { file_path?: unknown; notebook_path?: unknown } - const path = input.file_path ?? input.notebook_path - const env = await read($, envAtom) - if (typeof path === 'string' && isExemptPath(path, env.home, env.tmpdir)) return next(e) - const missing = await missingIssue($, tool) - - return missing === undefined ? next(e) : { deny: missing } - }) - } - on('tool.call', { tool: 'mcp__linear-server__save_issue' }, async ($, e, next) => { const refusal = await linearRefusal($, facts => checkSaveIssue(e as unknown as Record<string, unknown>, facts)) if (refusal !== undefined) return { deny: refusal } const ran = await next(e) if (ran.deny !== undefined || ran.isError === true) return ran const input = e as unknown as { id?: unknown; state?: unknown } - if (typeof input.id === 'string') { + if (typeof input.id === 'string' && isDoneState(input.state)) { const id = input.id - const key = id.toUpperCase() - const done = isDoneState(input.state) && !isDroppedState(input.state) - const started = isStartedState(input.state) - const dropped = isDroppedState(input.state) - await update($, shipAtom, ship => ({ - ...ship, - pending: done ? ship.pending.map(issue => (issue.id === id ? { ...issue, done: true } : issue)) : ship.pending, - doneIds: done ? [...new Set([...ship.doneIds, key])] : started ? ship.doneIds.filter(item => item !== key) : ship.doneIds, - // Taken up only by a started state; a cancelled or duplicate issue is no longer the session's to finish. - claimed: dropped ? ship.claimed.filter(item => item !== key) : started && !ship.opened.includes(key) ? [...new Set([...ship.claimed, key])] : ship.claimed, - opened: dropped ? ship.opened.filter(item => item !== key) : ship.opened, - })) - } else { - const created = createdIssueId(ran, await issuePatterns($)) - if (created !== undefined) await update($, shipAtom, ship => ({ ...ship, opened: [...new Set([...ship.opened, created])] })) + await update($, shipAtom, ship => ({ ...ship, pending: ship.pending.map(issue => (issue.id === id ? { ...issue, done: true } : issue)) })) } return ran @@ -253,30 +221,6 @@ export function registerShipGate(on: On): void { }) } -// Linear flow: a change needs an issue this session opened or picked up. -async function missingIssue($: EngineInterface, what: string): Promise<string | undefined> { - if (!(await read($, togglesAtom)).linearFlow) return undefined - const ship = await read($, shipAtom) - if (hasIssue(ship)) return undefined - if (await autoClaudeRun($)) return undefined - const env = await read($, envAtom) - - return missingIssueMessage(what, await repoTeam($, env.home)) -} - -// An auto-claude run owns the repository: its driver opens, moves and closes -// the issues, so the Linear flow neither gates nor blocks the stop there. -async function autoClaudeRun($: EngineInterface): Promise<boolean> { - try { - const common = (await $.process.run(['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'], { timeoutMs: 5_000 })).stdout.trim() - if (!common.endsWith('/.git')) return false - const text = await $.fs.read(`${common.slice(0, -'/.git'.length)}/.claude/auto-claude.on`).catch(() => undefined) - return runOwnsRepo(text, Date.now()) - } catch { - return false - } -} - // The Linear guards run under the guards toggle, before the ship gate's own // bookkeeping of the same calls. async function linearRefusal($: EngineInterface, check: (facts: LinearFacts) => string | undefined): Promise<string | undefined> { @@ -284,11 +228,7 @@ async function linearRefusal($: EngineInterface, check: (facts: LinearFacts) => if (!toggles.guards) return undefined const ship = await read($, shipAtom) const lint = await read($, lintAtom) - // While an auto-claude run owns the repository, a new issue would become a - // milestone of that run: creating one needs the user's request again. - const requested = - (toggles.linearFlow && !(await autoClaudeRun($))) || - ship.linearRequested || (await heartbeatOn($)) || grantAllowsLinear(await readGrant($, (await read($, envAtom)).home), Date.now()) + const requested = ship.linearRequested || (await heartbeatOn($)) || grantAllowsLinear(await readGrant($, (await read($, envAtom)).home), Date.now()) return check({ requested, mentioned: ship.mentioned, askUsed: lint.askUsed }) } @@ -303,16 +243,13 @@ export async function shipStop($: EngineInterface, e: Parameters<StopHook>[1], n // Entries tracked before the pattern filter existed (or under another linear.json) are re-checked here. const linear = new Set(linearIds(ship.pending.map(issue => issue.id), await issuePatterns($))) const open = unresolved(ship.pending.filter(issue => linear.has(issue.id))) - // Linear flow: issues this session opened or picked up end Done. - const unclosed = - toggles.linearFlow && !(await autoClaudeRun($)) ? [...new Set([...ship.opened, ...ship.claimed])].filter(id => !ship.doneIds.includes(id.toUpperCase())) : [] - if (open.length === 0 && unclosed.length === 0) { + if (open.length === 0) { if (ship.pending.length > 0) await update($, shipAtom, s => ({ ...s, pending: [] })) return below } if (ship.stopBlocks >= MAX_STOP_BLOCKS) { - $.ui.toast(`Ship gate: still not closed in Linear: ${[...open.map(issue => issue.id), ...unclosed].join(', ')}`) + $.ui.toast(`Ship gate: still not closed in Linear: ${open.map(issue => issue.id).join(', ')}`) return below } @@ -321,16 +258,11 @@ export async function shipStop($: EngineInterface, e: Parameters<StopHook>[1], n return { ...below, block: [ - ...(open.length === 0 - ? [] - : [ - 'Ship gate (rules/linear-grooming.md §5): a merged PR closes its issues in the same turn.', - ...open.map( - issue => - `- ${issue.id} (PR ${issue.pr}): ${[issue.done ? undefined : 'move to Done (save_issue state)', issue.commented ? undefined : 'add an evidence comment with the commit hash (save_comment)'].filter(Boolean).join(' and ')}`, - ), - ]), - ...(unclosed.length === 0 ? [] : [openIssuesMessage(unclosed)]), + 'Ship gate (rules/linear-grooming.md §5): a merged PR closes its issues in the same turn.', + ...open.map( + issue => + `- ${issue.id} (PR ${issue.pr}): ${[issue.done ? undefined : 'move to Done (save_issue state)', issue.commented ? undefined : 'add an evidence comment with the commit hash (save_comment)'].filter(Boolean).join(' and ')}`, + ), ].join('\n'), } } diff --git a/harness/hooks/state.ts b/harness/hooks/state.ts index 7dabc57..9d192b5 100644 --- a/harness/hooks/state.ts +++ b/harness/hooks/state.ts @@ -8,15 +8,12 @@ import type { HeartbeatState, LintState, ShipState, Toggles } from '../types' // Change a shape tag when that value's fields change: it declines what an // earlier version stored, which outlives a reload. -export const DEFAULT_TOGGLES: Toggles = { guards: true, shipGate: true, reportLint: true, repoSize: true, linearFlow: true } +export const DEFAULT_TOGGLES: Toggles = { guards: true, shipGate: true, reportLint: true, repoSize: true } export const INITIAL_SHIP: ShipState = { mentioned: [], linearRequested: false, pending: [], - opened: [], - claimed: [], - doneIds: [], stopBlocks: 0, prListed: false, codeqlRan: false, diff --git a/harness/types/index.d.ts b/harness/types/index.d.ts index 5e0cb6d..77d1d01 100644 --- a/harness/types/index.d.ts +++ b/harness/types/index.d.ts @@ -3,8 +3,6 @@ export type Toggles = { shipGate: boolean reportLint: boolean repoSize: boolean - // Linear flow: work needs an issue, and the issue ends Done. - linearFlow: boolean } export type GuardEnv = { @@ -27,10 +25,6 @@ export type ShipState = { // The user asked for Linear work in this session (CLAUDE.md §1.5). linearRequested: boolean pending: PendingIssue[] - // Linear flow: issues this session created, existing ones it picked up, and those moved to Done. - opened: string[] - claimed: string[] - doneIds: string[] stopBlocks: number prListed: boolean codeqlRan: boolean