From 40090bcabfcde2a3401799377f20e3749bcaedaa Mon Sep 17 00:00:00 2001 From: unohee Date: Fri, 13 Nov 2026 23:58:30 +0900 Subject: [PATCH] harness 0.4.0: linear-flow, work under a Linear issue that ends Done - Edit/Write/NotebookEdit, git commit/push and gh pr create are refused until the session opened or picked up a Linear issue; ~/.claude, /tmp, $TMPDIR and trash/ are exempt. - The Stop is blocked (twice, then a toast) while such an issue is not Done. - Issue creation and comments no longer need an explicit request while the flow is on; cancel/split still need AskUserQuestion approval. - The created issue ID is read from the save_issue result's "id" field (live Linear MCP shape, measured 2026-11-13). - /harness on|off linear-flow toggles it; toggles/ship atom shapes bumped. Closes AX-2213 --- harness/.claude-plugin/plugin.json | 2 +- harness/README.md | 11 +++- harness/hooks/ask-default.ts | 2 +- harness/hooks/flow.test.ts | 67 ++++++++++++++++++++++++- harness/hooks/guards.ts | 4 +- harness/hooks/linear-flow.ts | 80 ++++++++++++++++++++++++++++++ harness/hooks/pure.test.ts | 33 ++++++++++++ harness/hooks/register.ts | 10 ++-- harness/hooks/report-lint.ts | 2 +- harness/hooks/ship-gate.ts | 69 +++++++++++++++++++++----- harness/hooks/state.ts | 5 +- harness/types/index.d.ts | 6 +++ 12 files changed, 266 insertions(+), 25 deletions(-) create mode 100644 harness/hooks/linear-flow.ts diff --git a/harness/.claude-plugin/plugin.json b/harness/.claude-plugin/plugin.json index c1b0241..91eb6c8 100644 --- a/harness/.claude-plugin/plugin.json +++ b/harness/.claude-plugin/plugin.json @@ -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" diff --git a/harness/README.md b/harness/README.md index 029bf97..2de7fe9 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`. 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. @@ -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. diff --git a/harness/hooks/ask-default.ts b/harness/hooks/ask-default.ts index a59b2a5..efd0164 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[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 }> } diff --git a/harness/hooks/flow.test.ts b/harness/hooks/flow.test.ts index a802fb7..65071ca 100644 --- a/harness/hooks/flow.test.ts +++ b/harness/hooks/flow.test.ts @@ -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 @@ -27,7 +29,9 @@ function world(on: On, store: Record = {}): 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 | 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 })) @@ -62,6 +66,7 @@ function world(on: On, store: Record = {}): 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' } }) @@ -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[] = [] @@ -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) => $.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() + }) +}) diff --git a/harness/hooks/guards.ts b/harness/hooks/guards.ts index 49d3ac5..4fe47e5 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-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' }) diff --git a/harness/hooks/linear-flow.ts b/harness/hooks/linear-flow.ts new file mode 100644 index 0000000..702e8ce --- /dev/null +++ b/harness/hooks/linear-flow.ts @@ -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))) +} diff --git a/harness/hooks/pure.test.ts b/harness/hooks/pure.test.ts index a472bbc..f8b3ea4 100644 --- a/harness/hooks/pure.test.ts +++ b/harness/hooks/pure.test.ts @@ -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' @@ -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) + }) +}) diff --git a/harness/hooks/register.ts b/harness/hooks/register.ts index 6a61c68..7e393c7 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-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), @@ -62,6 +62,7 @@ const FEATURES: Record = { 'ship-gate': 'shipGate', 'report-lint': 'reportLint', 'repo-size': 'repoSize', + 'linear-flow': 'linearFlow', } function showStatus($: EngineInterface, toggles: Toggles) { @@ -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) { @@ -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'), } }) diff --git a/harness/hooks/report-lint.ts b/harness/hooks/report-lint.ts index 63e69ed..1d5e228 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-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 diff --git a/harness/hooks/ship-gate.ts b/harness/hooks/ship-gate.ts index 9c05a2a..f2992c7 100644 --- a/harness/hooks/ship-gate.ts +++ b/harness/hooks/ship-gate.ts @@ -4,6 +4,7 @@ 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, isExemptPath, isWorkCommand, missingIssueMessage, openIssuesMessage } from './linear-flow' import { heartbeatOn } from './heartbeat' import { checkListIssues, checkSaveComment, checkSaveIssue, isLinearRequest, repoTeam, withoutReminders } from './linear-guard' import type { LinearFacts } from './linear-guard' @@ -11,8 +12,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-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' }) 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' }) @@ -155,6 +156,11 @@ 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 = [ @@ -181,17 +187,37 @@ 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, 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 (ran.deny === undefined && ran.isError !== true && typeof input.id === 'string' && isDoneState(input.state)) { + if (typeof input.id === 'string') { const id = input.id + const done = isDoneState(input.state) await update($, shipAtom, ship => ({ ...ship, - pending: ship.pending.map(issue => (issue.id === id ? { ...issue, done: true } : issue)), + pending: done ? ship.pending.map(issue => (issue.id === id ? { ...issue, done: true } : issue)) : ship.pending, + doneIds: done ? [...new Set([...ship.doneIds, id.toUpperCase()])] : ship.doneIds.filter(item => item !== id.toUpperCase()), + // Any non-Done update is the agent picking an existing issue up. + claimed: done || ship.opened.includes(id.toUpperCase()) ? ship.claimed : [...new Set([...ship.claimed, id.toUpperCase()])], })) + } else { + const created = createdIssueId(ran, await issuePatterns($)) + if (created !== undefined) await update($, shipAtom, ship => ({ ...ship, opened: [...new Set([...ship.opened, created])] })) } return ran @@ -223,13 +249,25 @@ 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 { + if (!(await read($, togglesAtom)).linearFlow) return undefined + const ship = await read($, shipAtom) + if (hasIssue(ship)) return undefined + const env = await read($, envAtom) + + return missingIssueMessage(what, await repoTeam($, env.home)) +} + // 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 { - if (!(await read($, togglesAtom)).guards) return undefined + const toggles = await read($, togglesAtom) + if (!toggles.guards) return undefined const ship = await read($, shipAtom) const lint = await read($, lintAtom) const requested = + toggles.linearFlow || ship.linearRequested || (await heartbeatOn($)) || grantAllowsLinear(await readGrant($, (await read($, envAtom)).home), Date.now()) return check({ requested, mentioned: ship.mentioned, askUsed: lint.askUsed }) @@ -245,13 +283,15 @@ export async function shipStop($: EngineInterface, e: Parameters[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))) - if (open.length === 0) { + // Linear flow: issues this session opened or picked up end Done. + const unclosed = toggles.linearFlow ? [...new Set([...ship.opened, ...ship.claimed])].filter(id => !ship.doneIds.includes(id.toUpperCase())) : [] + if (open.length === 0 && unclosed.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).join(', ')}`) + $.ui.toast(`Ship gate: still not closed in Linear: ${[...open.map(issue => issue.id), ...unclosed].join(', ')}`) return below } @@ -260,11 +300,16 @@ export async function shipStop($: EngineInterface, e: Parameters[1], n return { ...below, block: [ - '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 ')}`, - ), + ...(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)]), ].join('\n'), } } diff --git a/harness/hooks/state.ts b/harness/hooks/state.ts index 9d192b5..7dabc57 100644 --- a/harness/hooks/state.ts +++ b/harness/hooks/state.ts @@ -8,12 +8,15 @@ 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 } +export const DEFAULT_TOGGLES: Toggles = { guards: true, shipGate: true, reportLint: true, repoSize: true, linearFlow: 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 77d1d01..5e0cb6d 100644 --- a/harness/types/index.d.ts +++ b/harness/types/index.d.ts @@ -3,6 +3,8 @@ 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 = { @@ -25,6 +27,10 @@ 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