diff --git a/auto-claude/.claude-plugin/plugin.json b/auto-claude/.claude-plugin/plugin.json index c2def8b..e5d3bce 100644 --- a/auto-claude/.claude-plugin/plugin.json +++ b/auto-claude/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "auto-claude", - "version": "1.1.0", + "version": "1.2.0", "description": "Finishes a repository's work unattended and live: Claude plans the long-term end state, its milestones and how it deploys; the built-in loop builds each milestone in its own worktree and judges it; auto-claude ships it (push, PR, CI, merge when green), deploys and smoke-checks it, and a watchdog keeps the run moving until the final check passes. Absorbs goal-mode's loop (1.0.0).", "author": { "name": "unohee" diff --git a/auto-claude/README.md b/auto-claude/README.md index a0cb51c..ac6bb60 100644 --- a/auto-claude/README.md +++ b/auto-claude/README.md @@ -81,6 +81,18 @@ A committed `.claude/auto-deploy.json` takes precedence: the person decided. The - It is merged like any milestone, and the deploy then runs again. - 3 deploys failing in a row stop the run. Nothing more is merged on top of a broken live service. +## Linear + +A run keeps the repository's Linear project in step, through the session's own `linear-server` MCP connection (no API key is read). Only a repository mapped to a project syncs: `repo_mapping..projectId` or `projectName` in `~/.claude/linear.json`. A team alone is shared by many repositories, so it is not enough. An unmapped repository syncs nothing, and `status` says `linear: off`. + +- **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. +- **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. +- `--queue` runs neither read nor write Linear. + ## Autonomy and its limits - **Choices.** Claude decides every choice itself and records it under `## Decisions`. Irreversible steps (credentials, payment, deleting data, a new public release) go through `mcp__auto-claude__defer_goal` and are never taken. diff --git a/auto-claude/hooks/auto.test.ts b/auto-claude/hooks/auto.test.ts index b5f2f17..9f99da7 100644 --- a/auto-claude/hooks/auto.test.ts +++ b/auto-claude/hooks/auto.test.ts @@ -1158,3 +1158,111 @@ describe('a directory with no git repository', () => { expect(w.runs.some(a => a.includes(' init'))).toBe(false) }) }) + +describe('Linear sync', () => { + // A fake Linear behind $.mcp.call: issues, comments and every write. + function linear(on: On, w: W) { + const l = { + issues: [{ id: 'KT-1', title: 'add() is wrong', updatedAt: '2026-11-13T10:00:00Z', status: 'Todo', statusType: 'unstarted' }] as Array<Record<string, string>>, + comments: {} as Record<string, Array<{ body: string; createdAt: string }>>, + writes: [] as string[], + } + w.files.set('/home/.claude/linear.json', JSON.stringify({ repo_mapping: { repo: { team: 'T', projectName: 'Repo' } } })) + const text = (v: unknown) => ({ value: { content: [{ type: 'text' as const, text: JSON.stringify(v) }], isError: false } }) + on('mcp.call', (_, e) => { + const a = e.args + if (e.tool === 'list_issues') return text({ issues: l.issues.filter(i => i.statusType === a.state), hasNextPage: false }) + if (e.tool === 'list_comments') return text({ comments: l.comments[String(a.issueId)] ?? [] }) + if (e.tool === 'get_issue') return text(l.issues.find(i => i.id === a.id) ?? {}) + if (e.tool === 'save_issue') { + l.writes.push(`state ${String(a.id)} ${String(a.state)}`) + const issue = l.issues.find(i => i.id === a.id) + // A write moves updatedAt, as Linear does. + if (issue !== undefined) Object.assign(issue, { updatedAt: '2026-11-13T11:00:00Z', statusType: a.state === 'completed' ? 'completed' : 'started' }) + return text(issue ?? {}) + } + if (e.tool === 'save_comment') { + l.writes.push(`comment ${String(a.issueId)} ${String(a.body)}`) + ;(l.comments[String(a.issueId)] ??= []).push({ body: String(a.body), createdAt: '2026-11-13T11:00:00Z' }) + return text({ id: 'c' }) + } + return { value: { content: [{ type: 'text' as const, text: 'unknown tool' }], isError: true } } + }) + return l + } + + test('the planning prompt lists open issues; a milestone naming one moves it to started, and its merge to Done with evidence', async ($, on) => { + const w = world(on) + const l = linear(on, w) + await $.session.start({ cwd: '/repo', surface: 'terminal', isInteractive: true }) + await cmd($, 'start') + await w.clock.advance(200) + expect(w.prompts[0]).toContain('Linear project "Repo" has 1 open issue(s)') + expect(w.prompts[0]).toContain('KT-1 [Todo] add() is wrong') + w.files.set('/repo/.claude/auto-plan.md', PLAN) + w.files.set(GOALS, QUEUE.replace('- [ ] add()', '- [ ] [KT-1] add()')) + await ready($) + await w.clock.advance(1_200) + await w.clock.advance(TICK) + expect(l.writes).toContain('state KT-1 started') + + await meet($, w) + await w.clock.advance(TICK) + expect(l.writes).toContain('state KT-1 completed') + expect(l.writes.find(x => x.startsWith('comment KT-1'))).toContain('[auto-claude] Merged into main') + expect((await cmd($, 'status')).text).toContain('linear: project Repo') + }) + + test('an issue opened or commented on mid-run is queued as a milestone; the driver\'s own comments are not changes', async ($, on) => { + const w = world(on) + const l = linear(on, w) + await planned($, w) + // A new issue, and a person's comment on the one the plan saw. + l.issues.push({ id: 'KT-2', title: 'sub() needs docs', updatedAt: '2026-11-13T12:00:00Z', status: 'Todo', statusType: 'unstarted' }) + l.comments['KT-1'] = [{ body: 'also handle floats', createdAt: '2026-11-13T12:30:00Z' }, { body: '[auto-claude] noise', createdAt: '2026-11-13T13:00:00Z' }] + await w.clock.advance(11 * MIN) + const queue = w.files.get(GOALS) ?? '' + expect(queue).toContain('- [ ] [KT-2] sub() needs docs: what Linear KT-2 asks is resolved on this branch') + expect(queue).toContain('- [ ] [KT-1] add() is wrong: the comments and changes on KT-1 since 2026-11-13T10:00:00Z are handled') + // The lines parse back to one condition each, with no check. + expect(parseQueue(queue).filter(i => i.condition.startsWith('[KT-')).every(i => i.check === undefined)).toBe(true) + // Nothing new: the next sync queues nothing more. + await w.clock.advance(11 * MIN) + expect(parseQueue(w.files.get(GOALS) ?? '').filter(i => i.condition.startsWith('[KT-')).length).toBe(2) + }) + + test('a pending line whose issue was closed is blocked, and a closed issue is never moved to started', async ($, on) => { + const w = world(on) + const l = linear(on, w) + l.issues.push({ id: 'KT-3', title: 'sub', updatedAt: '2026-11-13T10:00:00Z', status: 'Todo', statusType: 'unstarted' }) + await $.session.start({ cwd: '/repo', surface: 'terminal', isInteractive: true }) + await cmd($, 'start') + w.files.set('/repo/.claude/auto-plan.md', PLAN) + w.files.set(GOALS, QUEUE.replace('- [ ] sub()', '- [ ] [KT-3] sub()')) + await ready($) + await w.clock.advance(1_200) + // The person cancels KT-3 while milestone 1 is built. + Object.assign(l.issues[1]!, { statusType: 'canceled', status: 'Canceled' }) + await w.clock.advance(11 * MIN) + expect(w.files.get(GOALS)).toMatch(/- \[!\] \[KT-3\] sub\(\).*Linear KT-3 was closed \(Canceled\)/) + expect(l.writes.filter(x => x.startsWith('state KT-3'))).toEqual([]) + }) + + test('a run that started without Linear adopts the project on a tick once the repo is mapped', async ($, on) => { + const w = world(on) + linear(on, w) + const mapping = w.files.get('/home/.claude/linear.json')! + w.files.delete('/home/.claude/linear.json') + await planned($, w) + expect((await cmd($, 'status')).text).toContain('linear: off') + w.files.set('/home/.claude/linear.json', mapping) + await w.clock.advance(TICK) + expect((await cmd($, 'status')).text).toContain('linear: project Repo') + }) + + test('a repository mapped to no project syncs nothing and says so', async ($, on) => { + const w = world(on) + await planned($, w) + expect((await cmd($, 'status')).text).toContain('linear: off') + }) +}) diff --git a/auto-claude/hooks/linear.ts b/auto-claude/hooks/linear.ts new file mode 100644 index 0000000..264f870 --- /dev/null +++ b/auto-claude/hooks/linear.ts @@ -0,0 +1,302 @@ +import type { EngineInterface } from 'claude-code' + +import type { LinearSync } from '../types' + +// Linear sync (2026-11-13: runs kept missing issue updates). The driver, not +// the model, reads the repository's Linear project on a timer and writes back: +// - a planning prompt lists the project's open issues; a milestone that +// resolves one starts with its ID: `- [ ] [AX-12] <end state> :: check: ...`; +// - every SYNC_MS the open issues and their newest comments are read; an issue +// that is new or changed since the run last covered it, and has no milestone +// pending, gets one appended to the queue (the driver's line has no check: +// the evaluator judges it); +// - a milestone that starts moves its issues to started; one that merges moves +// them to completed with an evidence comment, unless comments came in while it +// was built (then a follow-up line is queued instead); a held or blocked one +// gets a comment only. +// Only a repository mapped to a project in ~/.claude/linear.json (projectId or +// projectName under repo_mapping.<folder name>) syncs: a team alone is shared +// by many repositories. Comments the driver writes start with MARK, so its own +// writes never count as changes. Comments do not move an issue's updatedAt +// (measured 2026-11-13), so they are read on their own. + +export const LINEAR_SERVER = 'linear-server' +export const SYNC_MS = 10 * 60_000 +export const MARK = '[auto-claude]' +// Issues whose comments are read on each sync, newest first (plus every issue the run tracks). +export const COMMENT_SCAN = 25 +// Lines appended per sync at most; the rest come on the next one. +export const MAX_APPENDS = 5 +// Follow-up lines per issue at most: comments that keep coming (a model that +// comments on its own issue) must not grow the queue forever. +export const MAX_FOLLOW_UPS = 2 + +const ID = /^\s*((?:\[[A-Z][A-Z0-9]{1,5}-\d+\]\s*)+)/ +const DONE_TYPES = new Set(['completed', 'canceled', 'cancelled', 'duplicate']) + +export type LinearIssue = { id: string; title: string; updatedAt: string; statusType?: string; status?: string } +export type LinearComment = { body: string; createdAt: string } + +// Issue IDs a queue condition names at its start: "[AX-1][AX-2] ...". +export function lineIssues(condition: string): string[] { + const m = condition.match(ID) + return m === null ? [] : [...m[1]!.matchAll(/\[([A-Z][A-Z0-9]{1,5}-\d+)\]/g)].map(x => x[1]!) +} + +export function isOpen(issue: Pick<LinearIssue, 'statusType'>): boolean { + return !DONE_TYPES.has((issue.statusType ?? '').toLowerCase()) +} + +// The latest change on an issue: its own update, or the newest comment a +// person wrote (the driver's own, marked, do not count). +export function stampOf(issue: Pick<LinearIssue, 'updatedAt'>, comments: readonly LinearComment[]): string { + let stamp = issue.updatedAt + for (const c of comments) if (!c.body.trimStart().startsWith(MARK) && c.createdAt > stamp) stamp = c.createdAt + return stamp +} + +// What one sync does with the open issues: lines to append and the stamps the +// run now covers. `pending`: IDs with a queue line not yet started (it reads +// the issue when it starts, so it covers any change); `active`: IDs being +// built or shipped (their changes are looked at when they merge). +export function planSync( + issues: readonly LinearIssue[], + comments: Readonly<Record<string, readonly LinearComment[]>>, + seen: Readonly<Record<string, string>>, + pending: ReadonlySet<string>, + active: ReadonlySet<string>, + followUps: Readonly<Record<string, number>> = {}, +): { append: LinearIssue[]; seen: Record<string, string> } { + const next: Record<string, string> = { ...seen } + const append: LinearIssue[] = [] + for (const issue of issues) { + if (!isOpen(issue)) continue + const stamp = stampOf(issue, comments[issue.id] ?? []) + const covered = seen[issue.id] + if (covered !== undefined && stamp <= covered) continue + if (active.has(issue.id)) continue + if (pending.has(issue.id)) { + next[issue.id] = stamp + continue + } + if (append.length >= MAX_APPENDS) continue + if (covered !== undefined && (followUps[issue.id] ?? 0) >= MAX_FOLLOW_UPS) { + next[issue.id] = stamp + continue + } + append.push(issue) + next[issue.id] = stamp + } + return { append, seen: next } +} + +// A queue line that stays one line and parses back to the same condition. +function clean(text: string, max: number): string { + return text.replace(/<!--|-->/g, ' ').replace(/::/g, ':').replace(/\s+/g, ' ').trim().slice(0, max) +} + +export function issueLine(issue: Pick<LinearIssue, 'id' | 'title'>, followUp: boolean, since?: string): string { + const what = followUp + ? `the comments and changes on ${issue.id} since ${since ?? 'its last milestone'} are handled on this branch` + : `what Linear ${issue.id} asks is resolved on this branch` + return `- [ ] [${issue.id}] ${clean(issue.title, 90)}: ${what} (read it first: get_issue and list_comments on ${issue.id}; never change its state or comment on it: auto-claude does)` +} + +// The open issues for the planning prompt. +export function issueBrief(issues: readonly LinearIssue[], project: string): string { + const open = issues.filter(isOpen) + if (open.length === 0) return `Linear project "${project}" has no open issue now; auto-claude still checks it every ${SYNC_MS / 60_000} min while the run goes.` + return [ + `Linear project "${project}" has ${open.length} open issue(s) (auto-claude reads it every ${SYNC_MS / 60_000} min and queues what changes):`, + ...open.slice(0, 60).map(i => `- ${i.id} [${i.status ?? i.statusType ?? '?'}] ${clean(i.title, 100)}`), + 'Read the ones that bear on the goal (get_issue, list_comments). Each milestone that resolves issues starts with their IDs: `- [ ] [AX-12] <end state> :: check: <command>`. auto-claude moves them to started and, once merged, to Done with an evidence comment: never change their state or comment on them yourself. An open issue you leave out gets one line under ## Decisions saying why.', + ].join('\n') +} + +// ~/.claude/linear.json's project for this repository, by its folder name. +export async function projectOf($: EngineInterface, root: string): Promise<string | undefined> { + const home = (await $.env.get('HOME').catch(() => undefined))?.replace(/\/$/, '') + if (home === undefined) return undefined + try { + const mapping = (JSON.parse(await $.fs.read(`${home}/.claude/linear.json`)) as { repo_mapping?: Record<string, { projectId?: unknown; projectName?: unknown }> }).repo_mapping + const entry = mapping?.[root.split('/').pop() ?? ''] + const project = entry?.projectId ?? entry?.projectName + return typeof project === 'string' && project !== '' ? project : undefined + } catch { + return undefined + } +} + +async function call($: EngineInterface, tool: string, args: Record<string, unknown>): Promise<unknown> { + const res = await $.mcp.call(LINEAR_SERVER, tool, args) + const text = res.content.map(block => ('text' in block && typeof block.text === 'string' ? block.text : '')).join('') + if (res.isError) throw new Error(`${tool}: ${text.slice(0, 200)}`) + try { + return JSON.parse(text) + } catch { + return text + } +} + +// Open state types, asked one by one: a single list sorted by updatedAt fills +// up with recently closed issues and cuts old open ones off (measured +// 2026-11-13). New issues land in backlog by default, so backlog counts. +export const OPEN_TYPES = ['triage', 'backlog', 'unstarted', 'started'] as const + +export async function listOpen($: EngineInterface, project: string): Promise<LinearIssue[]> { + const all: LinearIssue[] = [] + for (const state of OPEN_TYPES) { + const got = (await call($, 'list_issues', { project, state, limit: 100, orderBy: 'updatedAt', fields: ['id', 'title', 'updatedAt', 'status', 'statusType'] })) as { issues?: unknown[] } + for (const raw of got.issues ?? []) { + const i = raw as Record<string, unknown> + if (typeof i.id === 'string' && typeof i.updatedAt === 'string' && !all.some(x => x.id === i.id)) { + all.push({ id: i.id, title: String(i.title ?? ''), updatedAt: i.updatedAt, statusType: typeof i.statusType === 'string' ? i.statusType : state, status: typeof i.status === 'string' ? i.status : undefined }) + } + } + } + // Newest change first, so the comment scan reads the live ones. + return all.filter(isOpen).sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1)) +} + +export async function listComments($: EngineInterface, id: string): Promise<LinearComment[]> { + const got = (await call($, 'list_comments', { issueId: id, limit: 10, orderBy: 'createdAt' })) as { comments?: unknown[] } + return (got.comments ?? []).flatMap(raw => { + const c = raw as Record<string, unknown> + return typeof c.body === 'string' && typeof c.createdAt === 'string' ? [{ body: c.body, createdAt: c.createdAt }] : [] + }) +} + +export async function getIssue($: EngineInterface, id: string): Promise<LinearIssue | undefined> { + const i = (await call($, 'get_issue', { id, fields: ['id', 'title', 'updatedAt', 'status', 'statusType'] })) as Record<string, unknown> + return typeof i?.id === 'string' && typeof i.updatedAt === 'string' + ? { id: i.id, title: String(i.title ?? ''), updatedAt: i.updatedAt, statusType: typeof i.statusType === 'string' ? i.statusType : undefined, status: typeof i.status === 'string' ? i.status : undefined } + : undefined +} + +export async function setState($: EngineInterface, id: string, state: 'started' | 'completed'): Promise<void> { + await call($, 'save_issue', { id, state }) +} + +export async function comment($: EngineInterface, id: string, body: string): Promise<void> { + await call($, 'save_comment', { issueId: id, body: `${MARK} ${body}` }) +} + +// One sync: reads the open issues and the newest comments, returns the lines to +// append and the new record. Errors are kept on the record, never thrown. +export async function readChanges( + $: EngineInterface, + sync: LinearSync, + pending: ReadonlySet<string>, + active: ReadonlySet<string>, + now: number, + runIds: ReadonlySet<string> = new Set(), +): Promise<{ sync: LinearSync; lines: string[]; open?: Set<string> }> { + try { + const issues = await listOpen($, sync.project) + // Comments are read for the most recently changed issues and every issue + // this run has a line for; an older issue's new comment waits until the + // issue itself changes (comments do not move updatedAt). + const tracked = new Set([...pending, ...active, ...runIds]) + const scan = issues.filter((issue, at) => at < COMMENT_SCAN || tracked.has(issue.id)) + const comments: Record<string, LinearComment[]> = {} + for (const issue of scan) comments[issue.id] = await listComments($, issue.id) + const planned = planSync(issues, comments, sync.seen, pending, active, sync.followUps ?? {}) + const lines = planned.append.map(issue => issueLine(issue, sync.seen[issue.id] !== undefined, sync.seen[issue.id])) + const followUps = { ...(sync.followUps ?? {}) } + for (const issue of planned.append) if (sync.seen[issue.id] !== undefined) followUps[issue.id] = (followUps[issue.id] ?? 0) + 1 + return { sync: { ...sync, seen: planned.seen, followUps, syncedAt: now, error: undefined }, lines, open: new Set(issues.map(issue => issue.id)) } + } catch (error) { + return { sync: { ...sync, syncedAt: now, error: String(error).slice(0, 200) }, lines: [] } + } +} + +export function baselineSeen(issues: readonly Pick<LinearIssue, 'id' | 'updatedAt'>[], now: number): Record<string, string> { + const at = new Date(now).toISOString() + const seen: Record<string, string> = {} + for (const issue of issues) seen[issue.id] = issue.updatedAt > at ? issue.updatedAt : at + return seen +} + +// The run starts covering every open issue as it is now: the planning prompt +// shows them, so only later changes are queued by the timer. +export async function baseline($: EngineInterface, project: string, now: number): Promise<{ sync: LinearSync; brief: string }> { + try { + const issues = await listOpen($, project) + // Covered up to now: comments written before the run started are not + // changes, whichever issues the later scans happen to read. + const seen = baselineSeen(issues, now) + return { sync: { project, seen, syncedAt: now }, brief: issueBrief(issues, project) } + } catch (error) { + const why = String(error).slice(0, 200) + return { sync: { project, seen: {}, syncedAt: now, error: why }, brief: `Linear project "${project}" could not be read (${why}); auto-claude tries again every ${SYNC_MS / 60_000} min.` } + } +} + +// The stamp an issue has right after the driver wrote to it, so the driver's +// own write is never read as a change. +async function restamp($: EngineInterface, sync: LinearSync, id: string): Promise<LinearSync> { + const issue = await getIssue($, id).catch(() => undefined) + if (issue === undefined) return sync + const prev = sync.seen[id] + return { ...sync, seen: { ...sync.seen, [id]: prev !== undefined && prev > issue.updatedAt ? prev : issue.updatedAt } } +} + +// A milestone naming issues started: they move to started. +export async function onStart($: EngineInterface, sync: LinearSync, ids: readonly string[]): Promise<LinearSync> { + for (const id of ids) { + try { + const issue = await getIssue($, id) + // Closed while the line waited (cancelled, done elsewhere): never reopened. + if (issue === undefined || !isOpen(issue)) continue + await setState($, id, 'started') + sync = await restamp($, sync, id) + } catch (error) { + sync = { ...sync, error: `${id}: ${String(error).slice(0, 160)}` } + } + } + return sync +} + +// A milestone naming issues merged: each moves to completed with the evidence, +// unless a person changed it while it was built; then a follow-up line is +// queued and the issue stays open. +export async function onMerged($: EngineInterface, sync: LinearSync, ids: readonly string[], evidence: string): Promise<{ sync: LinearSync; lines: string[] }> { + const lines: string[] = [] + for (const id of ids) { + try { + const issue = await getIssue($, id) + if (issue === undefined) continue + if (!isOpen(issue)) { + await comment($, id, `${evidence}. The issue was already ${issue.status ?? issue.statusType ?? 'closed'}, so its state is left as it is.`) + continue + } + const stamp = stampOf(issue, await listComments($, id)) + const covered = sync.seen[id] + const ups = sync.followUps?.[id] ?? 0 + if (covered !== undefined && stamp > covered && ups < MAX_FOLLOW_UPS) { + await comment($, id, `${evidence}. It changed in Linear while this was built, so it stays open and a follow-up milestone is queued.`) + lines.push(issueLine(issue, true, covered)) + sync = { ...sync, seen: { ...sync.seen, [id]: stamp }, followUps: { ...(sync.followUps ?? {}), [id]: ups + 1 } } + continue + } + await comment($, id, `${evidence}. Moved to Done by auto-claude.`) + await setState($, id, 'completed') + sync = { ...sync, seen: { ...sync.seen, [id]: stamp } } + } catch (error) { + sync = { ...sync, error: `${id}: ${String(error).slice(0, 160)}` } + } + } + return { sync, lines } +} + +// A milestone naming issues was held or blocked: a comment, the state kept. +export async function onHeld($: EngineInterface, sync: LinearSync, ids: readonly string[], why: string): Promise<LinearSync> { + for (const id of ids) { + try { + await comment($, id, `The milestone for this issue was held: ${why.slice(0, 300)}. The issue stays open.`) + } catch (error) { + sync = { ...sync, error: `${id}: ${String(error).slice(0, 160)}` } + } + } + return sync +} diff --git a/auto-claude/hooks/plan.ts b/auto-claude/hooks/plan.ts index 12d8caa..6eb7b5e 100644 --- a/auto-claude/hooks/plan.ts +++ b/auto-claude/hooks/plan.ts @@ -111,7 +111,7 @@ function deployRules(fixed: string | undefined): string[] { ] } -export function kickoffText(hint: string, base: string, noRemote = false, fixedDeploy?: string): string { +export function kickoffText(hint: string, base: string, noRemote = false, fixedDeploy?: string, linearBrief?: string): string { return [ '[auto-claude] The person started an autonomous run of this repository. Plan it now; build nothing yet.', hint !== '' ? `Their aim: ${hint}` : 'No aim was given: finish what this repository is evidently for.', @@ -120,13 +120,14 @@ export function kickoffText(hint: string, base: string, noRemote = false, fixedD '1. .claude/auto-plan.md: ## Goal (the end state, with its quality bar), a line `Final check: <one shell command that passes only when the whole goal is met>`, the deploy lines below, ## Milestones (ordered, why each), ## Decisions (empty for now).', `2. .claude/goals.md: one line per milestone, in order: \`- [ ] <milestone end state> :: check: <shell command that proves it>\`. Each milestone is one reviewable PR, built in its own worktree from ${base} after the earlier milestones are merged, so each check must pass from such a checkout. State only what is true on the milestone's own branch: never \"merged\", \"pushed\", \"PR opened\" or \"deployed\" (that happens after it is met).`, ...deployRules(fixedDeploy), + ...(linearBrief !== undefined ? [linearBrief] : []), `Then call mcp__auto-claude__${READY_TOOL}. It checks the files and starts the run: auto-claude builds each milestone in a worktree, pushes it, opens a PR, waits for CI, merges when green and deploys.`, 'Nobody is watching: decide every choice yourself (the recommended or safest option), write each decision with its reason under ## Decisions, and ask only for credentials, payment or an irreversible step.', ...(noRemote ? [`This repository has no remote: each milestone lands in ${base} in this checkout, judged by its own check, with no PR and no CI. If the repository is empty or nearly so, make the first milestone its scaffold (README, manifest, test setup, one passing test) with a check that proves it runs.`] : []), ].join('\n') } -export function replanText(round: number, finalCheck: string, output: string): string { +export function replanText(round: number, finalCheck: string, output: string, linearBrief?: string): string { return [ `[auto-claude] Round ${round}: the queue is done, but the final check still fails.`, `Final check: ${finalCheck}`, @@ -134,6 +135,7 @@ export function replanText(round: number, finalCheck: string, output: string): s '```', output.slice(-3000), '```', + ...(linearBrief !== undefined ? [linearBrief] : []), 'Find what is still missing for the goal in .claude/auto-plan.md and append new milestone lines to .claude/goals.md (leave done and blocked lines as they are). Note the reason under ## Decisions. Keep the Deploy, Smoke check and CodeQL lines (change them only with a decision that says why).', `Then call mcp__auto-claude__${READY_TOOL}; the run continues with them. Decide yourself; nobody is watching.`, ].join('\n') @@ -146,6 +148,7 @@ export const POLICY = [ '- When you are waiting on something (CI, the next milestone, a merge), just end the turn: auto-claude carries on by itself and prompts you when there is work. Never end a turn asking the person to check status.', '- auto-claude sets each milestone as the goal itself: never call ProposeGoal or /goal during the run (a session goal would hold the loop).', '- An irreversible step (deleting data, credentials, payment, a new public release) is never taken: call mcp__auto-claude__defer_goal with the reason instead.', + '- Linear issues named at the start of a milestone ("[AX-12] ...") are the driver\'s to move and comment on: read them, never change their state or comment on them, and never create Linear issues during a run (a new issue in the project becomes a milestone of this run).', ].join('\n') // The reminder for a run still waiting on its plan, with what the files lack. diff --git a/auto-claude/hooks/pure.test.ts b/auto-claude/hooks/pure.test.ts index 8df5ea9..2504b0d 100644 --- a/auto-claude/hooks/pure.test.ts +++ b/auto-claude/hooks/pure.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from 'claude-code/testing' +import { baselineSeen, lineIssues, MAX_FOLLOW_UPS, planSync } from './linear' import { countSarif, parseDeploy, scriptsOf, specOfPlan } from './deploy' import { parseVerdict, transcriptTail } from './evaluator' @@ -433,3 +434,32 @@ describe('evaluator', () => { expect(tail).toContain('[tool_result] 2 passed') }) }) + +describe('Linear sync rules', () => { + test('issue IDs come from the start of a condition only', async () => { + expect(lineIssues('[AX-1][AX-2] two at once')).toEqual(['AX-1', 'AX-2']) + expect(lineIssues('fix AX-1 later')).toEqual([]) + }) + + test('changes on issues in flight wait for the merge; pending lines absorb them; follow-ups are capped', async () => { + const issue = (id: string, updatedAt: string) => ({ id, title: id, updatedAt, statusType: 'unstarted' }) + const issues = [issue('A-1', 't2'), issue('A-2', 't2'), issue('A-3', 't2'), issue('A-4', 't2'), { ...issue('A-5', 't2'), statusType: 'completed' }] + const seen = { 'A-1': 't1', 'A-2': 't1', 'A-3': 't1', 'A-4': 't1' } + const got = planSync(issues, {}, seen, new Set(['A-2']), new Set(['A-1']), { 'A-4': MAX_FOLLOW_UPS }) + expect(got.append.map(i => i.id)).toEqual(['A-3']) + expect(got.seen['A-1']).toBe('t1') + expect(got.seen['A-2']).toBe('t2') + expect(got.seen['A-4']).toBe('t2') + expect(got.seen['A-5']).toBeUndefined() + }) +}) + +test('a comment written before the run started is not a change, whichever issues a scan reads', () => { + const now = Date.parse('2026-11-13T15:00:00Z') + const issues = Array.from({ length: 30 }, (_, n) => ({ id: `A-${n}`, title: 't', updatedAt: '2026-11-01T00:00:00Z', statusType: 'backlog' })) + const seen = baselineSeen(issues, now) + const old = Object.fromEntries(issues.map(i => [i.id, [{ body: 'old note', createdAt: '2026-11-10T00:00:00Z' }]])) + expect(planSync(issues, old, seen, new Set(), new Set()).append).toEqual([]) + const fresh = { 'A-29': [{ body: 'new ask', createdAt: '2026-11-13T15:05:00Z' }] } + expect(planSync(issues, fresh, seen, new Set(), new Set()).append.map(i => i.id)).toEqual(['A-29']) +}) diff --git a/auto-claude/hooks/register.ts b/auto-claude/hooks/register.ts index e009acd..c2dd540 100644 --- a/auto-claude/hooks/register.ts +++ b/auto-claude/hooks/register.ts @@ -10,7 +10,8 @@ import { bootstrapRepo } from './bootstrap' import { ensureLines, FILES, fetchRemote, LOCAL, out, readText, refOf, repoRoot, run, tell } from './io' import { appendLog, blockCurrent, DEFER_TOOL, DEFER_TOOL_ID, deferCall, guardRefusal, LOOP_EXCLUDES, LOOP_POLICY, loopView, MIN_CHECKS_TO_DEFER, onStop, readLoop, resumeLoop, setOnFinish, startNext, stopLoop, watch, writeLoop } from './loop' import { capReached, causeOf, ciAction, diagnose, httpsOf, idleDue, inFlight, isWaiting, LOOP_WAKES, MAX_IDLE_NUDGES, MAX_RED, mergeable, noRequired, onlyCancelled, parseChecks, prNumber, progressSig, readLog, repoSlug, shipRemedy, startBase, summary, unfinished, wakeDue } from './ship' -import { nextPending } from './queue' +import { markItem, nextPending } from './queue' +import { baseline, getIssue, isOpen, lineIssues, onHeld, onMerged, onStart, projectOf, readChanges, SYNC_MS } from './linear' import type { StallFacts } from './ship' import type { Caps } from './ship' @@ -32,7 +33,7 @@ const COMMAND = 'auto-claude' // The ready tool's full name, as the tool.call matcher sees it. const READY_TOOL_ID = 'mcp__auto-claude__auto_plan_ready' const STORE = (root: string) => `auto:${root}` -const EXCLUDES = ['.claude/auto-plan.md', '.claude/auto-claude.stop', '.claude/auto-claude.stop.cleared', ...LOOP_EXCLUDES] +const EXCLUDES = ['.claude/auto-plan.md', '.claude/auto-claude.stop', '.claude/auto-claude.stop.cleared', '.claude/auto-claude.on', ...LOOP_EXCLUDES] const DENY = ['\\bgh\\s+pr\\s+merge\\b', '\\bgh\\s+release\\b', '\\bgit\\s+push\\b.*\\bHEAD:(main|master)\\b'] // A run whose owning session has not ticked for this long is orphaned. @@ -74,9 +75,71 @@ 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). + await $.fs.write(`${r.root}/.claude/auto-claude.on`, `${JSON.stringify({ on: r.on, phase: r.phase, at: await $.clock.now() })}\n`).catch(() => undefined) await show($, r) } +// Issue IDs of queue lines not started yet, and of the milestones being built or shipped. +async function linearSets($: EngineInterface, r: AutoRecord): Promise<{ pending: Set<string>; active: Set<string> }> { + const current = (await readLoop($, r.root))?.current?.condition + const queue = parseQueue((await readText($, FILES(r.root).queue)) ?? '') + const pending = new Set(queue.filter(i => i.mark === ' ' && i.condition !== current).flatMap(i => lineIssues(i.condition))) + const active = new Set([...(current === undefined ? [] : lineIssues(current)), ...r.ships.filter(s => s.state !== 'merged' && s.state !== 'held').flatMap(s => lineIssues(s.goal))]) + return { pending, active } +} + +// Linear changes since the last look become queue lines; `force` skips the timer. +// A run started before this version (or before its repo was mapped) adopts the +// project here, covered from now on. +async function linearSync($: EngineInterface, r: AutoRecord, force = false): Promise<{ r: AutoRecord; added: number }> { + if (r.buildOnly === true || r.phase !== 'run') return { r, added: 0 } + const now = await $.clock.now() + if (r.linear === undefined) { + const project = await projectOf($, r.root) + if (project === undefined) return { r, added: 0 } + const got = await baseline($, project, now) + await tell($, r, `Linear: syncing project ${project} from now on`) + return { r: { ...r, linear: got.sync }, added: 0 } + } + if (!force && now - (r.linear.syncedAt ?? 0) < SYNC_MS) return { r, added: 0 } + const sets = await linearSets($, r) + const queue = parseQueue((await readText($, FILES(r.root).queue)) ?? '') + const runIds = new Set(queue.flatMap(i => lineIssues(i.condition))) + const got = await readChanges($, r.linear, sets.pending, sets.active, now, runIds) + // A line whose issue was closed while it waited is blocked, not built. + if (got.open !== undefined) { + for (const id of sets.pending) { + if (got.open.has(id)) continue + const issue = await getIssue($, id).catch(() => undefined) + if (issue === undefined || isOpen(issue)) continue + const text = (await readText($, FILES(r.root).queue)) ?? '' + let marked = text + for (const item of parseQueue(text)) { + if (item.mark === ' ' && lineIssues(item.condition).includes(id)) marked = markItem(marked, item.condition, '!', `Linear ${id} was closed (${issue.status ?? issue.statusType ?? 'closed'}) before this was built`) + } + if (marked !== text) { + await $.fs.write(FILES(r.root).queue, marked) + await tell($, r, `Linear ${id} was closed; its pending milestone is blocked`) + } + } + } + for (const line of got.lines) await appendQueue($, r.root, line) + if (got.lines.length > 0) await tell($, r, `Linear: ${got.lines.length} changed issue(s) queued as milestones`) + // A failing sync is told once, when it starts failing. + if (got.sync.error !== undefined && r.linear.error === undefined) await tell($, r, `Linear sync failed: ${got.sync.error}; retried every ${SYNC_MS / 60_000} min`) + return { r: { ...r, linear: got.sync }, added: got.lines.length } +} + +// The planning prompt's Linear part, with the run's sync started from what it shows. +async function linearKickoff($: EngineInterface, root: string): Promise<{ linear?: AutoRecord['linear']; brief?: string }> { + const project = await projectOf($, root) + if (project === undefined) return {} + const got = await baseline($, project, await $.clock.now()) + return { linear: got.sync, brief: got.brief } +} + async function show($: EngineInterface, r: AutoRecord | undefined) { if (r === undefined || !r.on) { await segment($, r?.phase === 'done' ? 'auto·done' : '') @@ -193,6 +256,8 @@ async function hold($: EngineInterface, r: AutoRecord, item: ShipItem, note: str const cause = causeOf(note) const streak = r.holdCause === cause ? (r.holdStreak ?? 0) + 1 : 1 await tell($, r, `held: ${item.goal.slice(0, 60)}${item.pr !== undefined ? ` (PR #${item.pr})` : ''}: ${note.slice(0, 160)}; going on with the next milestone`) + const ids = lineIssues(item.goal) + if (r.linear !== undefined && ids.length > 0) r = { ...r, linear: await onHeld($, r.linear, ids, `${item.pr !== undefined ? `PR #${item.pr}: ` : ''}${note}`) } // A held repair frees the stacked milestones; their deploys count toward the stop. return { r: { ...r, held: r.held + 1, holdCause: cause, holdStreak: streak, ...(item.repair === true ? { repair: undefined } : {}) }, item: { ...item, state: 'held', note } } } @@ -326,6 +391,15 @@ async function advance($: EngineInterface, r: AutoRecord, item: ShipItem): Promi const landed = item.pr !== undefined ? `PR #${item.pr}` : `into ${r.defaultBranch}` let next: AutoRecord = { ...r, merges: r.merges + 1, holdStreak: 0, holdCause: undefined, ...(item.repair === true ? { repair: undefined } : {}) } await tell($, next, `merged ${landed}: ${item.goal.slice(0, 80)}`) + const ids = lineIssues(item.goal) + if (next.linear !== undefined && ids.length > 0) { + // The merged tip, fetched first: the local ref still points before the merge. + await fetchRemote($, r, r.root) + const sha = (await run($, ['git', '-C', r.root, 'rev-parse', '--short', refOf(r)], r.root, 15_000)).stdout.trim() + const done = await onMerged($, next.linear, ids, `Merged ${landed}${sha !== '' ? ` (${r.defaultBranch} at ${sha})` : ''}: ${item.goal.slice(0, 160)}`) + for (const line of done.lines) await appendQueue($, r.root, line) + next = { ...next, linear: done.sync } + } const merged = update({ state: 'merged', note: undefined }) if (r.deploy !== undefined) next = await deployAfter($, next, r.deploy, landed) return { r: next, item: merged } @@ -400,9 +474,12 @@ async function finalCheck($: EngineInterface, r: AutoRecord, caps: Caps): Promis return stopRun($, r, `the final check passed after ${r.round} round(s)${r.deploy !== undefined ? ' and what was merged is deployed' : ''}`, 'done') } if (r.round >= caps.maxRounds) return stopRun($, r, `the final check still fails after ${r.round} round(s)`) - const next: AutoRecord = { ...r, phase: 'plan', round: r.round + 1, queueEmpty: false, phaseAt: await $.clock.now(), nudges: 0 } + let next: AutoRecord = { ...r, phase: 'plan', round: r.round + 1, queueEmpty: false, phaseAt: await $.clock.now(), nudges: 0 } + const kick = r.linear === undefined ? {} : await linearKickoff($, r.root) + // Changes a replan sees in the brief are covered by the lines it writes. + if (kick.linear !== undefined && r.linear !== undefined) next = { ...next, linear: { ...kick.linear, followUps: r.linear.followUps } } await writeRecord($, next) - const text = replanText(next.round, check, `${ran.stdout}\n${ran.stderr}`) + const text = replanText(next.round, check, `${ran.stdout}\n${ran.stderr}`, kick.brief) $.clock.after(100, () => { $.prompt.submit({ text }).catch(() => {}) }) @@ -525,7 +602,13 @@ async function nextOrFinish($: EngineInterface, r: AutoRecord, caps: Caps): Prom return } const building = (await readLoop($, r.root))?.current !== undefined - if (unfinished(r.ships).length === 0 && !building && r.started <= r.finished) await finalCheck($, { ...r, phase: 'final' }, caps) + if (unfinished(r.ships).length === 0 && !building && r.started <= r.finished) { + // The run is not done while Linear has changes it has not queued. + const synced = await linearSync($, r, true) + if (synced.r.linear !== r.linear) await writeRecord($, synced.r) + if (synced.added > 0) return + await finalCheck($, { ...synced.r, phase: 'final' }, caps) + } } async function tick($: EngineInterface, caps: Caps, pollMs: number): Promise<void> { @@ -566,6 +649,7 @@ async function tick($: EngineInterface, caps: Caps, pollMs: number): Promise<voi } r = await watchdog($, r) if (!r.on) return + r = (await linearSync($, r)).r await writeRecord($, r) // A pending CI is looked at again soon, between the ticks. @@ -608,6 +692,8 @@ async function readEvents($: EngineInterface, r: AutoRecord): Promise<AutoRecord for (const e of read.entries) { if (e.event === 'start' && e.branch !== undefined) { r = { ...r, started: r.started + 1, worktrees: { ...r.worktrees, [e.branch]: e.worktree ?? '' } } + const ids = e.goal === undefined ? [] : lineIssues(e.goal) + if (r.linear !== undefined && r.buildOnly !== true && ids.length > 0) r = { ...r, linear: await onStart($, r.linear, ids) } } else if (e.event === 'met' && e.goal !== undefined && e.branch !== undefined) { r = { ...r, finished: r.finished + 1 } if (r.buildOnly !== true) r = await metToShip($, r, e.goal, e.branch) @@ -618,6 +704,8 @@ async function readEvents($: EngineInterface, r: AutoRecord): Promise<AutoRecord const parent: string | undefined = e.goal === undefined ? undefined : r.fixes[e.goal] if (parent !== undefined) r = { ...r, ships: r.ships.map((s): ShipItem => (s.headRef === parent ? { ...s, state: 'held', note: 'its fix goal was blocked' } : s)) } await tell($, r, `${e.event}: ${(e.goal ?? '').slice(0, 80)}${e.reason !== undefined ? ` (${e.reason.slice(0, 100)})` : ''}; going on`) + const ids = e.goal === undefined ? [] : lineIssues(e.goal) + if (r.linear !== undefined && r.buildOnly !== true && ids.length > 0) r = { ...r, linear: await onHeld($, r.linear, ids, `${e.event}${e.reason !== undefined ? `: ${e.reason}` : ''}`) } } else if (e.event === 'queue-empty') { r = { ...r, queueEmpty: true } } @@ -799,6 +887,9 @@ async function startCommand($: EngineInterface, hint: string, ciMode: string, bu ...(buildOnly ? { buildOnly: true } : {}), ...(deploy === undefined ? {} : { deploy, deploys: 0 }), } + // The Linear baseline first: a tick between two writes would lose it. + const kick = buildOnly ? {} : await linearKickoff($, root) + if (kick.linear !== undefined) r.linear = kick.linear activeRoot = root // A milestone left open by an earlier run belongs to that run's plan. await stopLoop($, root, true) @@ -808,7 +899,7 @@ async function startCommand($: EngineInterface, hint: string, ciMode: string, bu $.clock.after(100, () => void tickNow?.()) return `auto-claude building the queue in ${root}: one worktree per pending line, judged by its check; nothing is pushed, merged or deployed.${clearedNote(stop)}` } - const text = kickoffText(hint, refOf({ remote, defaultBranch }), remote === LOCAL, deploy?.command) + const text = kickoffText(hint, refOf({ remote, defaultBranch }), remote === LOCAL, deploy?.command, kick.brief) $.clock.after(100, () => { $.prompt.submit({ text }).catch(() => $.ui.toast('auto-claude: the planning prompt was not submitted; send any message to start.')) }) @@ -860,6 +951,9 @@ async function statusText($: EngineInterface): Promise<string> { `queue: ${queue.filter(i => i.mark === 'x').length} done, ${queue.filter(i => i.mark === '!').length} blocked, ${queue.filter(i => i.mark === ' ').length} pending · ${summary(r.merges, r.held, r.ships)}`, current !== undefined ? `building: ${current.condition.slice(0, 80)} (${current.branch})` : undefined, ...r.ships.filter(s => s.state !== 'merged').map(s => `- ${s.state}${s.pr !== undefined ? ` PR #${s.pr}` : ''}: ${s.goal.slice(0, 70)}${s.note ? ` (${s.note.slice(0, 80)})` : ''}`), + r.linear !== undefined + ? `linear: project ${r.linear.project} · ${Object.keys(r.linear.seen).length} issue(s) covered · last sync ${r.linear.syncedAt !== undefined ? `${Math.round(((await $.clock.now()) - r.linear.syncedAt) / 60_000)} min ago` : 'never'}${r.linear.error !== undefined ? ` · error: ${r.linear.error}` : ''}` + : r.buildOnly === true ? undefined : 'linear: off (this folder maps to no project in ~/.claude/linear.json repo_mapping: add projectId or projectName)', r.note !== undefined ? `note: ${r.note}` : undefined, await stallLine($, r), ] @@ -1050,7 +1144,8 @@ export const register: Register = (on, options) => { if ('error' in stop) return { text: `Not resumed: ${stop.error}.` } const now = await $.clock.now() const phase = r.phase === 'done' || r.phase === 'stopped' || r.phase === 'final' ? (r.pausedPhase ?? 'run') : r.phase - // A run still planning gets its prompt again. + // A run still planning gets its prompt again, with Linear read before the record is written. + const kick = phase === 'plan' ? await linearKickoff($, r.root) : {} const next: AutoRecord = { ...r, on: true, @@ -1061,13 +1156,14 @@ export const register: Register = (on, options) => { holdStreak: 0, deployFails: 0, ...(phase === 'plan' ? { phaseAt: now, nudges: 0 } : {}), + ...(kick.linear !== undefined ? { linear: kick.linear } : {}), } activeRoot = r.root orphanTold = undefined await writeRecord($, next) clearSessionGoal($) if (phase === 'plan') { - const text = kickoffText(r.hint, refOf(r), r.remote === LOCAL, r.deploy?.source === 'file' ? r.deploy.command : undefined) + const text = kickoffText(r.hint, refOf(r), r.remote === LOCAL, r.deploy?.source === 'file' ? r.deploy.command : undefined, kick.brief) $.clock.after(100, () => { $.prompt.submit({ text }).catch(() => $.ui.toast('auto-claude: the planning prompt was not submitted; send any message to start.')) }) diff --git a/auto-claude/types/index.d.ts b/auto-claude/types/index.d.ts index 4023c76..75c125f 100644 --- a/auto-claude/types/index.d.ts +++ b/auto-claude/types/index.d.ts @@ -37,6 +37,16 @@ export type ShipItem = { repair?: boolean } +// The run's Linear sync (hooks/linear.ts): the project, the change stamp each +// issue is covered up to, and follow-up lines queued per issue. +export type LinearSync = { + project: string + seen: Record<string, string> + followUps?: Record<string, number> + syncedAt?: number + error?: string +} + export type AutoPhase = 'plan' | 'run' | 'final' | 'done' | 'stopped' export type AutoRecord = { @@ -106,6 +116,8 @@ export type AutoRecord = { movedAt?: number idleNudges?: number idleNudgedAt?: number + // Linear sync; unset when the repository maps to no project. + linear?: LinearSync } // A goal of the loop: one queue line being built in its own worktree. diff --git a/harness/.claude-plugin/plugin.json b/harness/.claude-plugin/plugin.json index 91eb6c8..8158537 100644 --- a/harness/.claude-plugin/plugin.json +++ b/harness/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "harness", - "version": "0.4.0", + "version": "0.4.1", "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 2de7fe9..52f930d 100644 --- a/harness/README.md +++ b/harness/README.md @@ -51,9 +51,10 @@ Refuses or rewrites a single tool call. 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. +- **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) diff --git a/harness/hooks/flow.test.ts b/harness/hooks/flow.test.ts index 65071ca..8d7df4f 100644 --- a/harness/hooks/flow.test.ts +++ b/harness/hooks/flow.test.ts @@ -492,4 +492,28 @@ describe('linear flow', () => { expect((await $.tool.call({ tool: 'Write', file_path: '/repo/a.py', content: 'x\n' })).deny).toBeUndefined() expect((await $.classic.Stop(STOP)).block).toBeUndefined() }) + + 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() })) + 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() + 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/linear-flow.ts b/harness/hooks/linear-flow.ts index 702e8ce..f06848d 100644 --- a/harness/hooks/linear-flow.ts +++ b/harness/hooks/linear-flow.ts @@ -78,3 +78,27 @@ export function createdIssueId(result: unknown, patterns: readonly string[] | un 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 f8b3ea4..e67acaf 100644 --- a/harness/hooks/pure.test.ts +++ b/harness/hooks/pure.test.ts @@ -15,7 +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 { 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' @@ -402,3 +402,24 @@ describe('linear flow', () => { 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/ship-gate.ts b/harness/hooks/ship-gate.ts index f2992c7..f7daa2d 100644 --- a/harness/hooks/ship-gate.ts +++ b/harness/hooks/ship-gate.ts @@ -4,7 +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 { 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' @@ -207,13 +207,17 @@ export function registerShipGate(on: On): void { const input = e as unknown as { id?: unknown; state?: unknown } if (typeof input.id === 'string') { const id = input.id - const done = isDoneState(input.state) + 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, 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()])], + 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($)) @@ -254,11 +258,25 @@ async function missingIssue($: EngineInterface, what: string): Promise<string | 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> { @@ -266,8 +284,10 @@ 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 || + (toggles.linearFlow && !(await autoClaudeRun($))) || ship.linearRequested || (await heartbeatOn($)) || grantAllowsLinear(await readGrant($, (await read($, envAtom)).home), Date.now()) return check({ requested, mentioned: ship.mentioned, askUsed: lint.askUsed }) @@ -284,7 +304,8 @@ export async function shipStop($: EngineInterface, e: Parameters<StopHook>[1], n 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 ? [...new Set([...ship.opened, ...ship.claimed])].filter(id => !ship.doneIds.includes(id.toUpperCase())) : [] + 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 (ship.pending.length > 0) await update($, shipAtom, s => ({ ...s, pending: [] }))