diff --git a/AGENTS.md b/AGENTS.md index 8d6923b16f..28f4183709 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -148,7 +148,7 @@ claude --plugin-dir ./apps/hook | `PLANNOTATOR_SHARE` | Set to `disabled` to turn off URL sharing entirely, including Guided Review share links (the review UI hides "Create share link", `POST /api/guide/:jobId/share` answers `403 { error: "sharing disabled" }`, and `plannotator guide share` refuses with exit 1). Default: enabled. Can also be set via `~/.plannotator/config.json` (`{ "share": "disabled" }`); the env var takes precedence. | | `PLANNOTATOR_SHARE_URL` | Custom base URL for share links (self-hosted portal). Default: `https://share.plannotator.ai`. | | `PLANNOTATOR_PASTE_URL` | Base URL of the paste service API for short URL sharing. Default: `https://plannotator-paste.plannotator.workers.dev`. | -| `PLANNOTATOR_CLAUDE_MOD` | Opt-in switch for the Claude Code mod (non-blocking plan review, annotate, code review and annotate-last, plus Ask this session; see "Claude Code mod"). Set to `1` / `true` / `on` to enable, `0` / `false` / `off` / `disabled` to force off; empty or unrecognized counts as unset. **Default: off**: a Claude Code that runs hooks modules (2.1.287+) loads the plugin's module for everyone, so until the owner makes it the default the module stays inert (every hook passes through, no command or tool is registered, no environment is set) and the classic PermissionRequest hook and `/plannotator-*` skills run exactly as before. Can also be set via `~/.plannotator/config.json` (`{ "claudeCodeMod": true }`, read from the data dir); the env var takes precedence (`resolveClaudeCodeMod` in `packages/shared/config.ts`, mirrored by `apps/hook/hooks/mod/enabled.ts` because a hooks module can import only its own files; `enabled.test.ts` keeps them in step). Read once when Claude Code starts, so a change applies to the next session start. Set it in the shell that starts Claude Code or in Claude Code's `settings.json` `env`. | +| `PLANNOTATOR_CLAUDE_MOD` | Switch for the Claude Code mod (non-blocking plan review, annotate, code review and annotate-last, the `plannotator` tool, the take-over of agent-run Bash `plannotator` commands, plus Ask this session; see "Claude Code mod"). **Default: on** wherever Claude Code runs hooks modules (2.1.287+, interactive CLI sessions; the mod still stands down by itself in `-p` / SDK sessions and where `/bin/sh` is missing, i.e. Windows). Set to `0` / `false` / `off` / `disabled` to turn it off, which leaves the module inert (every hook passes through, no command or tool is registered, no Bash command is taken over, no environment is set) so the classic PermissionRequest hook and `/plannotator-*` skills run exactly as before; `1` / `true` / `on` force it on, and empty or unrecognized counts as unset (on). Can also be turned off via `~/.plannotator/config.json` (`{ "claudeCodeMod": false }`, read from the data dir); the env var takes precedence (`resolveClaudeCodeMod` in `packages/shared/config.ts`, mirrored by `apps/hook/hooks/mod/enabled.ts` because a hooks module can import only its own files; `enabled.test.ts` keeps them in step). Read once when Claude Code starts, so a change applies to the next session start. Set it in the shell that starts Claude Code or in Claude Code's `settings.json` `env`. The plugin installs from the repo and the `plannotator` binary updates separately, so the mod also runs against older binaries; see "Version skew" in the mod section for what degrades. | | `PLANNOTATOR_HOST_RESULT_FILE` | Set by a host that starts the CLI detached (the Claude Code mod): when a review, annotate, annotate-last or `claude-mod-plan` session settles, the CLI writes one JSON decision record there atomically (mode 0600), with the agent message composed from the configured prompts. Only a path named `result.json` inside `/claude-code-mod/` is accepted (`isAllowedHostResultPath`); anything else is ignored with a stderr warning, so the variable cannot make the CLI create or replace an arbitrary file. Taken at startup and removed from the environment. Stdout is unchanged. See "Claude Code mod". | | `PLANNOTATOR_HOST_MESSAGES_FILE` | Set by the Claude Code mod for `annotate-last --stdin` (ignored without `--stdin`): a `messages.json` inside `/claude-code-mod/` (`isAllowedHostMessagesPath`; anything else is ignored with a stderr warning) holding `{ v: 1, messages: [{ messageId, text, timestamp? }] }`, newest first, which the CLI shows as the message picker instead of the single stdin message. Validated fail-closed (1..25 entries, string fields, unique ids, 2 MiB per message, 8 MiB file); a malformed file exits 1 with the reason. Taken at startup and removed from the environment. A CLI that predates it ignores it and opens the stdin text. See "Claude Code mod". | | `PLANNOTATOR_SESSION_TAG` | Set by the Claude Code mod in its session's environment (`claude-code:`), so processes the session starts can be matched to it; recorded as `hostSession` in the `sessions/` registry. Not meant to be set by hand. | @@ -293,14 +293,15 @@ as a message from the `plannotator` plugin). UX spec: questions are not answered yet, and the conservative choices below are the ones taken). -**Opt-in (`PLANNOTATOR_CLAUDE_MOD=1` or `{ "claudeCodeMod": true }`).** On -current Claude Code hooks modules load even with `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS` -unset, so shipping the module would otherwise switch every 2.1.287+ user to the -non-blocking flows on the next release. With the knob off (the default) -`session.start` stops before doing anything (no `$.command.register` or `$.tool.register`, no -`$.env.set`, no `$.store`, no process) and every other hook passes straight -through with `next(e)`, so the classic PermissionRequest hook and the -`/plannotator-*` skills run as they do without mods. See the env table row. +**On by default; opt out with `PLANNOTATOR_CLAUDE_MOD=0` or `{ "claudeCodeMod": false }`.** +The owner's call: every Claude Code that runs hooks modules (current Claude Code +loads them even with `CLAUDE_CODE_ENABLE_FUNCTION_HOOKS` unset) gets the +non-blocking flows, the `plannotator` tool and the Bash take-over of +agent-run `plannotator` commands (below). With the knob off `session.start` stops before doing +anything (no `$.command.register` or `$.tool.register`, no `$.env.set`, no +`$.store`, no process) and every other hook passes straight through with +`next(e)`, so the classic PermissionRequest hook and the `/plannotator-*` +skills run as they do without mods. See the env table row. **Inert without mods.** Checked live: Claude Code 2.1.150 (no hooks modules) validates and loads the plugin with the `modules` key, ignores it, and runs the @@ -366,11 +367,43 @@ approved-with-notes prompts OpenCode and Pi use; plan: `composePlanDeniedMessage unchanged for every caller. `noop` marks what never starts a turn: Done with nothing to send, review LGTM, Close, and a review posted straight to the PR platform (`platform: true`, logged plus a `$.prompt.suggest` to address the -comments). The plugin and the binary update separately, so the mod copes with -a CLI that predates both: an old CLI has no `claude-mod-plan` (the ExitPlanMode -call falls back to the classic flow) and writes no result record (a review or -annotate that exits 0 is delivered from its stdout, the text the skill would -have shown Claude; `legacyResult` in `delivery.ts`). +comments). + +**Version skew.** The plugin installs from the repo's main branch and the +binary updates separately, so with the mod on by default it routinely runs +against an older CLI. Verified by running the real mod controller against the +released 0.27.25 and 0.27.10 binaries as processes: +- ExitPlanMode: an old CLI has no `claude-mod-plan` (0.27.11+ prints `Unknown + command: claude-mod-plan`; older CLIs read the unknown subcommand as the + classic hook and print `No plan content in hook event`), exit 1 within + ~0.3 s. The mod recognizes either (`cliLacksModPlan` in `plan.ts`), lets the + call through to Claude Code's own flow, where the plugin's classic + PermissionRequest hook runs the familiar blocking review, logs ONE line + telling the user to update the CLI, removes the launch directory, and sends + every later ExitPlanMode straight to the classic flow without probing again. + The flag lives on the mod instance, not in `$.store`, so a restart or + `--resume` probes once more (and picks up a CLI updated in between). An old + CLI that refuses only after the hook stopped waiting (15 s) is caught by the + timer: same fallback, plus a plugin turn asking Claude to call ExitPlanMode + again, since it was told a review was open. While the hook waits, the timer + leaves the launch alone (`starting`), so only one of the two reports it. Any + other startup failure also falls back, with the CLI's error logged. Plan + review is therefore blocking, not broken. +- Review, annotate, last, the `plannotator` tool and taken-over Bash runs (the + same launch as the tool): work. The old CLI writes + the ready file (0.19.24+) and no result record; a decision that exits 0 is + delivered from its stdout (`legacyResult` in `delivery.ts`), with the default + review approval prompt read as an LGTM (logged, no turn) and the + approved-with-notes prompt as "Approved with notes" (a user-customized + approved prompt cannot be told apart and arrives as feedback). Close and an + empty Done log only. +- `last`: the old CLI ignores `PLANNOTATOR_HOST_MESSAGES_FILE` and opens the + newest message from stdin (no picker), though the command line still says + "N messages, newest first". +- Ask this session: the old server answers `404` on `/api/ai/bridge/poll`, the + mod's bridge stops, and Ask AI offers only its providers. +- A CLI before 0.19.24 writes no ready file: commands wait their full 45 s / + 15 s and say "Starting…", and decisions still arrive at exit. **Commands.** `/plannotator-review`, `/plannotator-annotate` and `/plannotator-last` keep their names (spec open question 7, conservative): when @@ -424,7 +457,7 @@ classic path, which falls back to the pre-compaction file. blocks and gives Ask AI a separate AI. The mod registers a real tool instead: `$.tool.register({ name: "plannotator", description, inputSchema })` at `session.start`, right after the commands, and only when the mod is on (the -opt-in knob, an interactive session, `/bin/sh` present); with the switch off, +knob not turned off, an interactive session, `/bin/sh` present); with the switch off, in `-p`/SDK runs and on Windows nothing is registered and Claude keeps the CLI through the `plannotator` skill. The engine names it `mcp__plannotator__plannotator` (the register call returns the full name, which `register.ts` keeps) and serves diff --git a/apps/hook/hooks/hooks.json b/apps/hook/hooks/hooks.json index 56325c54b4..e1d68d65c1 100644 --- a/apps/hook/hooks/hooks.json +++ b/apps/hook/hooks/hooks.json @@ -1,5 +1,5 @@ { - "description": "Plannotator: plan review on ExitPlanMode's permission request. Where Claude Code runs hooks modules and the user opted in (PLANNOTATOR_CLAUDE_MOD=1 or claudeCodeMod in config.json), the mod (mod/register.ts) makes plan review, annotate, code review and annotate-last non-blocking; otherwise the module passes every hook through.", + "description": "Plannotator: plan review on ExitPlanMode's permission request. Where Claude Code runs hooks modules (interactive CLI sessions), the mod (mod/register.ts) makes plan review, annotate, code review and annotate-last non-blocking, unless the user turned it off (PLANNOTATOR_CLAUDE_MOD=0 or \"claudeCodeMod\": false in config.json); then the module passes every hook through.", "modules": ["./mod/register.ts"], "hooks": { "PreToolUse": [ diff --git a/apps/hook/hooks/mod/controller.test.ts b/apps/hook/hooks/mod/controller.test.ts index e44c1df7d5..415e63b624 100644 --- a/apps/hook/hooks/mod/controller.test.ts +++ b/apps/hook/hooks/mod/controller.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from 'bun:test' import { PlannotatorMod, STORE_LAUNCHES } from './controller' import { PLAN_APPROVAL_NEXT_STEP } from './delivery' +import { CLASSIC_PLAN_REVIEW_TEXT } from './plan' import { fakeHost, type FakeHost, type RunCall } from './testing/fake-host' const SESSION = { sessionId: 'session-1', dataDir: '/data', interactive: true } @@ -168,6 +169,84 @@ describe('plan review', () => { expect(await mod.onPlanCall({ tool_use_id: 't1', plan: PLAN })).toEqual({ pass: true }) expect(host.logs.join('\n')).toContain('unknown subcommand') }) + + // Version skew: the plugin installs from main and the binary updates on its + // own, so a mod can meet a CLI with no claude-mod-plan. What those CLIs + // print, observed by running them: 0.27.25 (0.27.11+) and 0.27.10 (older + // CLIs read an unknown subcommand as the classic hook). + for (const [cli, stderr] of [ + ['0.27.11 to 0.27.25', "Unknown command: claude-mod-plan\n\nRun 'plannotator --help' for the list of commands.\n"], + ['before 0.27.11', 'No plan content in hook event\n'], + ] as const) { + test(`a CLI without claude-mod-plan (${cli}): every plan takes the classic review, said once, nothing left behind`, async () => { + const host = fakeHost() + host.onRun = (call) => { + if (isLaunch(call)) { + host.files.set(`${launchDirOf(call)}/stderr`, stderr) + host.files.set(`${launchDirOf(call)}/exit`, '1') + } + } + const mod = new PlannotatorMod(host, SESSION) + + expect(await mod.onPlanCall({ tool_use_id: 't1', plan: PLAN })).toEqual({ pass: true }) + expect(await mod.onPlanCall({ tool_use_id: 't2', plan: `${PLAN}2. More.\n` })).toEqual({ pass: true }) + + // One probe, then no more launches; one explanation, not an error per plan. + expect(launches(host)).toHaveLength(1) + expect(host.logs).toHaveLength(1) + expect(host.logs[0]).toContain('classic review') + expect(host.logs[0]).not.toContain('could not open') + // The plan copy on stdin is removed; nothing is waiting or watched. + const dir = launchDirOf(launches(host)[0]!) + expect(host.runs.some((call) => call.argv[3] === 'plannotator-cleanup' && call.argv[4] === dir)).toBe(true) + expect(host.store.get(STORE_LAUNCHES)).toEqual([]) + expect(mod.onPlanPermission('t2', { plan: PLAN })).toBeNull() + }) + } + + test('an old CLI that exits while the hook waits is reported once, by the hook, even when the timer ticks then', async () => { + const host = fakeHost() + let dir = '' + host.onRun = (call) => { + if (isLaunch(call)) dir = launchDirOf(call) + } + host.onWait = () => { + if (!dir || host.files.has(`${dir}/exit`)) return + host.files.set(`${dir}/stderr`, 'Unknown command: claude-mod-plan\n') + host.files.set(`${dir}/exit`, '1') + // The 1 s timer fires in the same moment the CLI exits. + void host.tick() + } + const mod = new PlannotatorMod(host, SESSION) + + expect(await mod.onPlanCall({ tool_use_id: 't1', plan: PLAN })).toEqual({ pass: true }) + await host.tick() + + expect(host.logs).toEqual([CLASSIC_PLAN_REVIEW_TEXT]) + expect(host.submits).toEqual([]) + }) + + test('an old CLI that refuses only after the hook stopped waiting: Claude is asked to call ExitPlanMode again', async () => { + const host = fakeHost() + const mod = new PlannotatorMod(host, SESSION) + + // Nothing within the hook's 15 s: Claude is told the review is open. + const answer = await mod.onPlanCall({ tool_use_id: 't1', plan: PLAN }) + expect('deny' in answer && answer.deny).toContain('NOT approved') + + const dir = launchDirOf(launches(host)[0]!) + host.files.set(`${dir}/stderr`, 'Unknown command: claude-mod-plan\n') + host.files.set(`${dir}/exit`, '1') + await host.tick() + + expect(host.logs).toEqual([CLASSIC_PLAN_REVIEW_TEXT]) + expect(host.submits).toHaveLength(1) + expect(host.submits[0]).toContain('Call ExitPlanMode again') + // The call it asks for goes to the classic review without another launch. + expect(await mod.onPlanCall({ tool_use_id: 't2', plan: PLAN })).toEqual({ pass: true }) + expect(launches(host)).toHaveLength(1) + expect(host.store.get(STORE_LAUNCHES)).toEqual([]) + }) }) describe('commands', () => { diff --git a/apps/hook/hooks/mod/controller.ts b/apps/hook/hooks/mod/controller.ts index 9af7eb3ec5..610faa5a4f 100644 --- a/apps/hook/hooks/mod/controller.ts +++ b/apps/hook/hooks/mod/controller.ts @@ -28,6 +28,9 @@ import { } from './launch' import { approvedPermissionDecision, + CLASSIC_PLAN_RETRY_TEXT, + CLASSIC_PLAN_REVIEW_TEXT, + cliLacksModPlan, decidingDenyText, isTrustablePlanPath, MAX_PLAN_FILE_BYTES, @@ -82,6 +85,11 @@ interface LiveLaunch extends LaunchRecord { pidMisses: number ticks: number settling: boolean + /** + * A hook is still waiting in `awaitReady` for this launch to come up or + * fail: that hook reports the outcome, so the timer leaves the launch alone. + */ + starting: boolean bridge: BridgeHandle | null } @@ -98,6 +106,12 @@ export class PlannotatorMod { /** ExitPlanMode calls passed through as the approved plan, by tool_use_id. */ private passing = new Map() private planVersion = 0 + /** + * The CLI has no `claude-mod-plan` (it is older than the plugin): every + * ExitPlanMode of this session takes Claude Code's own flow, and the + * plugin's classic hook reviews it, blocking, as before the mod. + */ + private classicPlanReview = false private timer: { cancel: () => void } | null = null private delivering: Promise = Promise.resolve() private sequence = 0 @@ -148,7 +162,7 @@ export class PlannotatorMod { } private adopt(record: LaunchRecord): LiveLaunch { - const live: LiveLaunch = { ...record, pidMisses: 0, ticks: 0, settling: false, bridge: null } + const live: LiveLaunch = { ...record, pidMisses: 0, ticks: 0, settling: false, starting: false, bridge: null } this.launches.set(record.id, live) return live } @@ -159,7 +173,7 @@ export class PlannotatorMod { (record) => record && record.sessionId !== this.session.sessionId, ) const mine: LaunchRecord[] = [...this.launches.values()].map( - ({ pidMisses: _misses, ticks: _ticks, settling: _settling, bridge: _bridge, ...record }) => record, + ({ pidMisses: _misses, ticks: _ticks, settling: _settling, starting: _starting, bridge: _bridge, ...record }) => record, ) await this.host.storeSet(STORE_LAUNCHES, [...others, ...mine]) } @@ -241,6 +255,15 @@ export class PlannotatorMod { * in a `$.clock` wait that would spend the hook's budget. */ private async awaitReady(launch: LiveLaunch, ms: number): Promise<'ready' | 'exited' | 'timeout'> { + launch.starting = true + try { + return await this.waitReadyOrExit(launch, ms) + } finally { + launch.starting = false + } + } + + private async waitReadyOrExit(launch: LiveLaunch, ms: number): Promise<'ready' | 'exited' | 'timeout'> { const ready = fileIn(launch.dir, 'ready') const exit = fileIn(launch.dir, 'exit') const deadline = (await this.host.now()) + ms @@ -278,6 +301,24 @@ export class PlannotatorMod { return text } + /** + * Not a failure to report each time: an older CLI. Say so once, and leave + * this instance's plans to the classic review (a resumed session probes + * once more, so a CLI updated in between is picked up). + */ + private async fallBackToClassicPlans(launch: LiveLaunch): Promise { + this.classicPlanReview = true + await this.forget(launch) + await this.host.run(cleanupArgv(launch.dir), { timeoutMs: 5_000 }).catch(() => undefined) + this.host.log(CLASSIC_PLAN_REVIEW_TEXT) + } + + /** The plan launch exited because the CLI has no `claude-mod-plan`. */ + private async lacksModPlan(launch: LiveLaunch): Promise { + const stderr = await this.host.readFile(fileIn(launch.dir, 'stderr')).catch(() => '') + return cliLacksModPlan(stderr) + } + // --- Commands ------------------------------------------------------------ /** `/plannotator-review`, `/plannotator-annotate`, `/plannotator-last`: open and return at once. */ @@ -411,6 +452,7 @@ export class PlannotatorMod { } private async startPlanReview(plan: string, planFilePath?: string): Promise<{ pass: true } | { deny: string }> { + if (this.classicPlanReview) return { pass: true } const version = this.planVersion + 1 const subject = subjectFor('plan', '', version) const stdin = (dir: string) => JSON.stringify({ plan, planFilePath, revisionFile: fileIn(dir, 'revision') }) @@ -423,6 +465,11 @@ export class PlannotatorMod { this.planVersion = version const outcome = await this.awaitReady(started, READY_WAIT_MS.other) if (outcome === 'exited') { + if (await this.lacksModPlan(started)) { + this.planVersion = version - 1 + await this.fallBackToClassicPlans(started) + return { pass: true } + } this.host.log(await this.startupFailure(started)) return { pass: true } } @@ -485,7 +532,7 @@ export class PlannotatorMod { private async tick(): Promise { if (this.disposed) return for (const launch of [...this.launches.values()]) { - if (launch.settling) continue + if (launch.settling || launch.starting) continue launch.ticks += 1 try { await this.check(launch) @@ -514,13 +561,22 @@ export class PlannotatorMod { launch.settling = true const code = (await this.host.readFile(fileIn(launch.dir, 'exit')).catch(() => '')).trim() // A CLI older than the host result file still prints the decision the - // skill would have shown Claude; a plan never gets here (an old CLI has - // no claude-mod-plan and the call fell back to the classic flow). + // skill would have shown Claude. (A plan never exits 0 without a record.) if (code === '0' && launch.kind !== 'plan') { const printed = (await this.host.readFile(fileIn(launch.dir, 'stdout')).catch(() => '')).trim() await this.settle(launch, legacyResult(launch.kind, printed)) return } + // An old CLI that took longer to refuse claude-mod-plan than the hook + // waited: Claude was told a review is open and is waiting on nothing. + if (launch.kind === 'plan' && (await this.lacksModPlan(launch))) { + await this.fallBackToClassicPlans(launch) + this.delivering = this.delivering + .then(() => this.host.submit(`Plannotator: ${launch.subject} — not opened.\n\n${CLASSIC_PLAN_RETRY_TEXT}`)) + .catch(() => undefined) + await this.delivering + return + } // Exited without a decision: a crash, a kill, or a startup failure we did not wait for. this.host.log(`The review server for ${launch.subject} stopped${code ? ` (exit ${code})` : ''} without a decision. Your draft is saved.`) await this.forget(launch) diff --git a/apps/hook/hooks/mod/delivery.test.ts b/apps/hook/hooks/mod/delivery.test.ts index eff439a35b..99960b5dba 100644 --- a/apps/hook/hooks/mod/delivery.test.ts +++ b/apps/hook/hooks/mod/delivery.test.ts @@ -1,5 +1,14 @@ import { describe, expect, test } from 'bun:test' -import { deliveryFor, PLAN_APPROVAL_NEXT_STEP, parseHostResult, type HostResultRecord } from './delivery' +import { DEFAULT_REVIEW_APPROVED_PROMPT, DEFAULT_REVIEW_APPROVED_WITH_NOTES_PROMPT } from '@plannotator/shared/prompts' +import { + deliveryFor, + LEGACY_REVIEW_APPROVED_TEXT, + LEGACY_REVIEW_APPROVED_WITH_NOTES_HEADING, + legacyResult, + PLAN_APPROVAL_NEXT_STEP, + parseHostResult, + type HostResultRecord, +} from './delivery' import { splitShellWords } from './shell-words' const CONTEXT = { subject: 'notes.md', overflowPath: '/data/x/feedback.md' } @@ -49,6 +58,36 @@ describe('deliveryFor', () => { }) }) +// An older CLI (no host result file, e.g. 0.27.25) only prints the decision +// on stdout; these are the outputs it was observed to print. +describe('legacyResult (a CLI that predates the host result file)', () => { + test('a review approval is an LGTM, not "Changes requested"', () => { + const lgtm = legacyResult('review', `${DEFAULT_REVIEW_APPROVED_PROMPT}\n`) + expect(deliveryFor(lgtm, CONTEXT).action).toBe('log') + }) + + test('a review approval with notes is delivered under its own outcome', () => { + const printed = DEFAULT_REVIEW_APPROVED_WITH_NOTES_PROMPT.replace('{{feedback}}', 'rename foo') + const delivery = deliveryFor(legacyResult('review', printed), CONTEXT) + expect(delivery.action).toBe('submit') + expect(delivery.text.split('\n')[0]).toBe('Plannotator: notes.md — Approved with notes.') + expect(delivery.text).toContain('rename foo') + }) + + test('feedback, close and the annotate approval line', () => { + expect(deliveryFor(legacyResult('review', '# Code Review Feedback\n\nfix'), CONTEXT).text).toContain('Changes requested') + expect(deliveryFor(legacyResult('review', 'Review session closed without feedback.'), CONTEXT).action).toBe('log') + expect(deliveryFor(legacyResult('annotate', 'The user approved.'), CONTEXT).action).toBe('log') + expect(deliveryFor(legacyResult('annotate', ''), CONTEXT).action).toBe('log') + }) + + // The mod cannot import packages/shared: its copies must follow the CLI's defaults. + test('the recognized approval texts are the CLI defaults', () => { + expect(LEGACY_REVIEW_APPROVED_TEXT).toBe(DEFAULT_REVIEW_APPROVED_PROMPT) + expect(DEFAULT_REVIEW_APPROVED_WITH_NOTES_PROMPT.split('\n')[0]).toBe(LEGACY_REVIEW_APPROVED_WITH_NOTES_HEADING) + }) +}) + describe('parseHostResult', () => { test('refuses records that are not the CLI host result', () => { expect(parseHostResult('{"v":1,"surface":"plan","decision":"approved","message":"m","noop":false}')).not.toBeNull() diff --git a/apps/hook/hooks/mod/delivery.ts b/apps/hook/hooks/mod/delivery.ts index 8e85ef38cf..66bfc9bdd1 100644 --- a/apps/hook/hooks/mod/delivery.ts +++ b/apps/hook/hooks/mod/delivery.ts @@ -132,10 +132,23 @@ export function deliveryFor(record: HostResultRecord, context: DeliveryContext): } } +/** + * The CLI's default review approval prompts (`DEFAULT_REVIEW_APPROVED_PROMPT` + * and the first line of `DEFAULT_REVIEW_APPROVED_WITH_NOTES_PROMPT` in + * packages/shared/prompts.ts; delivery.test.ts keeps them equal). An older + * CLI prints them on stdout for an approval, and only stdout says what the + * decision was. + */ +export const LEGACY_REVIEW_APPROVED_TEXT = '# Code Review\n\nCode review completed — no changes requested.' +export const LEGACY_REVIEW_APPROVED_WITH_NOTES_HEADING = '# Code Review — Approved with Notes' + /** * A CLI that predates the host result file (the plugin and the binary update * separately): what it printed on stdout, the text the skill would have shown - * Claude. Empty output, or the legacy close/approve lines, carry nothing. + * Claude. Empty output, or the legacy close/approve lines, carry nothing; a + * review approval (the default approved prompt) is an LGTM, as the newer CLI + * reports it, rather than "Changes requested". A user-customized approved + * prompt cannot be told apart from feedback and is delivered as feedback. */ export function legacyResult(kind: SessionKind, printed: string): HostResultRecord { const surface = kind === 'review' ? 'review' : kind === 'last' ? 'annotate-last' : 'annotate' @@ -144,5 +157,11 @@ export function legacyResult(kind: SessionKind, printed: string): HostResultReco return { v: 1, surface, decision: 'dismissed', message: '', noop: true } } if (text === 'The user approved.') return { v: 1, surface, decision: 'approved', message: '', noop: true } + if (surface === 'review' && text === LEGACY_REVIEW_APPROVED_TEXT) { + return { v: 1, surface, decision: 'approved', message: '', noop: true } + } + if (surface === 'review' && text.startsWith(LEGACY_REVIEW_APPROVED_WITH_NOTES_HEADING)) { + return { v: 1, surface, decision: 'approved', message: text, noop: false, withNotes: true } + } return { v: 1, surface, decision: 'annotated', message: text, noop: false } } diff --git a/apps/hook/hooks/mod/enabled.test.ts b/apps/hook/hooks/mod/enabled.test.ts index 8b94260fdd..3e9f10cd9a 100644 --- a/apps/hook/hooks/mod/enabled.test.ts +++ b/apps/hook/hooks/mod/enabled.test.ts @@ -5,7 +5,7 @@ import { resolveClaudeModEnabled } from './enabled' // The mod cannot import packages/shared, so it mirrors resolveClaudeCodeMod. // The failure this guards: the two drift, and the CLI docs/settings say the // mod is off while the mod turns itself on (or the reverse). -describe('opt-in knob', () => { +describe('on/off knob', () => { const envs = [undefined, '', '1', 'true', 'ON', ' on ', '0', 'false', 'off', 'disabled', 'yes', 'garbage'] const configs: unknown[] = [undefined, true, false, 'true', 'false', '1', '0', 'yes', 1, null] @@ -19,10 +19,21 @@ describe('opt-in knob', () => { } }) - test('off by default, including an unreadable config file', () => { - expect(resolveClaudeModEnabled(undefined, null)).toBe(false) - expect(resolveClaudeModEnabled(undefined, '{ not json')).toBe(false) + // The owner's decision: on for everyone who has not opted out. A regression + // here silently returns every user to the blocking flows. + test('on by default: no setting, an empty or unrecognized env value, an unreadable config file', () => { + expect(resolveClaudeModEnabled(undefined, null)).toBe(true) + expect(resolveClaudeModEnabled('', '{}')).toBe(true) + expect(resolveClaudeModEnabled('garbage', null)).toBe(true) + expect(resolveClaudeModEnabled(undefined, '{ not json')).toBe(true) + expect(resolveClaudeCodeMod({}, {})).toBe(true) + }) + + test('the opt-out: an off env value or claudeCodeMod false; the env wins over the file', () => { + for (const off of ['0', 'false', 'off', 'disabled', ' OFF ']) expect(resolveClaudeModEnabled(off, null)).toBe(false) + expect(resolveClaudeModEnabled(undefined, '{"claudeCodeMod":false}')).toBe(false) + expect(resolveClaudeModEnabled(undefined, '{"claudeCodeMod":"0"}')).toBe(false) + expect(resolveClaudeModEnabled('1', '{"claudeCodeMod":false}')).toBe(true) expect(resolveClaudeModEnabled('0', '{"claudeCodeMod":true}')).toBe(false) - expect(resolveClaudeModEnabled('1', null)).toBe(true) }) }) diff --git a/apps/hook/hooks/mod/enabled.ts b/apps/hook/hooks/mod/enabled.ts index ea91be6db4..f1a0a5339f 100644 --- a/apps/hook/hooks/mod/enabled.ts +++ b/apps/hook/hooks/mod/enabled.ts @@ -1,12 +1,14 @@ /** - * Whether the mod is switched on. It is OPT-IN: a Claude Code that runs hooks - * modules loads this plugin's module for everyone, so until the owner makes - * the non-blocking flows the default the mod stays inert (every hook passes - * straight through, nothing is registered, no environment is set) unless the - * user asks for it: + * Whether the mod is switched on. It is ON BY DEFAULT wherever Claude Code + * runs hooks modules (register.ts still stands down in `-p` / SDK sessions + * and where there is no `/bin/sh`). The user turns it off with: * - * PLANNOTATOR_CLAUDE_MOD=1 (env; wins over the config file) - * { "claudeCodeMod": true } (config.json in the data dir) + * PLANNOTATOR_CLAUDE_MOD=0 (env; also false/off/disabled; wins over the config file) + * { "claudeCodeMod": false } (config.json in the data dir) + * + * Off, the mod is inert: every hook passes straight through, nothing is + * registered, no environment is set, and the classic PermissionRequest hook + * and `/plannotator-*` skills run exactly as they do without mods. * * Mirrors `resolveClaudeCodeMod` in packages/shared/config.ts (a hooks module * may import only its own files); `enabled.test.ts` keeps the two in step. @@ -20,21 +22,26 @@ export function parseClaudeModEnv(value: string | undefined): boolean | undefine return undefined } -/** config.json's `claudeCodeMod`, coerced like the CLI's other boolean keys; default false. */ +/** + * config.json's `claudeCodeMod`, coerced like the CLI's other boolean keys + * (`coerceConfigBoolean`): a boolean, or the strings true/1 and false/0. + * Anything else, a missing key, or an unreadable file is the default: on. + */ export function parseClaudeModConfig(configText: string | null | undefined): boolean { - if (!configText) return false + if (!configText) return true let value: unknown try { value = (JSON.parse(configText) as Record | null)?.claudeCodeMod } catch { - return false + return true } if (typeof value === 'boolean') return value if (typeof value === 'string') { const v = value.trim().toLowerCase() if (v === 'true' || v === '1') return true + if (v === 'false' || v === '0') return false } - return false + return true } export function resolveClaudeModEnabled(envValue: string | undefined, configText: string | null | undefined): boolean { diff --git a/apps/hook/hooks/mod/plan.ts b/apps/hook/hooks/mod/plan.ts index 17db9bd4cc..e7b8cfc38e 100644 --- a/apps/hook/hooks/mod/plan.ts +++ b/apps/hook/hooks/mod/plan.ts @@ -93,6 +93,27 @@ export function revisionPendingDenyText(version: number): string { return `Plan v${version} was sent to the open Plannotator review. It is NOT approved. End your turn and wait for the decision.` } +/** + * Whether a `plannotator claude-mod-plan` launch failed because the CLI is + * older than the plugin (the two update separately) and has no such + * subcommand: 0.27.11+ answers "Unknown command", and older CLIs read any + * unknown subcommand as the classic hook, which finds no hook event on stdin. + */ +export function cliLacksModPlan(stderr: string): boolean { + return /Unknown command: claude-mod-plan\b/.test(stderr) || /No plan content in hook event/.test(stderr) +} + +/** Logged once per session when the CLI has no non-blocking plan review. */ +export const CLASSIC_PLAN_REVIEW_TEXT = + 'Your plannotator CLI is older than the Plannotator plugin and has no non-blocking plan review, so plans open in the classic review, which holds this session until you decide. Update the CLI (curl -fsSL https://plannotator.ai/install.sh | bash) and start or resume a session to get non-blocking plan review.' + +/** + * Sent to Claude when the old CLI refused only after the ExitPlanMode call had + * already been told a review was open: nothing is open, so ask for the call again. + */ +export const CLASSIC_PLAN_RETRY_TEXT = + "The plan review did not open: the user's plannotator CLI is older than the Plannotator plugin and has no non-blocking plan review. The plan is NOT approved. Call ExitPlanMode again with the same plan; it will open in the classic review." + /** Shown in the status line and toasts. */ export function planWaitingStatus(version: number): string { return `Plan v${version} · waiting for your review` diff --git a/apps/hook/hooks/mod/register.ts b/apps/hook/hooks/mod/register.ts index 007b6d1ab8..35017e006f 100644 --- a/apps/hook/hooks/mod/register.ts +++ b/apps/hook/hooks/mod/register.ts @@ -2,8 +2,8 @@ * The Plannotator mod: non-blocking plan review, annotate, code review and * annotate-last for Claude Code, plus "Ask this session". * - * OPT-IN (enabled.ts): with neither `PLANNOTATOR_CLAUDE_MOD=1` nor - * `{ "claudeCodeMod": true }` in config.json, every hook below passes straight + * ON BY DEFAULT (enabled.ts). With `PLANNOTATOR_CLAUDE_MOD=0` (or + * `{ "claudeCodeMod": false }` in config.json) every hook below passes straight * through and nothing is registered or set, so the classic hook and skills * run exactly as they do without mods. * @@ -155,7 +155,7 @@ async function currentMod($: Engine): Promise { } } -/** Whether the user turned the mod on (opt-in) and where its data dir is; null: stay inert. */ +/** Whether the mod runs here (on unless the user turned it off) and where its data dir is; null: stay inert. */ async function resolveAllowed($: Engine, e: { isInteractive?: unknown }): Promise { // A person at the prompt is what makes a later plugin turn mean anything; // `-p` and SDK runs keep the classic, blocking flows. @@ -169,7 +169,7 @@ async function resolveAllowed($: Engine, e: { isInteractive?: unknown }): Promis legacyExists: home ? await $.fs.exists(`${String(home).replace(/\/+$/, '')}/.plannotator`) : false, }) if (!dataDir) return null - // Opt-in: nothing happens unless the user turned the mod on. + // On by default; nothing happens when the user turned the mod off. const configText = await $.fs.read(`${dataDir}/config.json`).catch(() => null) if (!resolveClaudeModEnabled(await $.env.get('PLANNOTATOR_CLAUDE_MOD'), typeof configText === 'string' ? configText : null)) { return null diff --git a/apps/hook/tests/register.test.ts b/apps/hook/tests/register.test.ts index c5b3a75e06..755e5fcdd9 100644 --- a/apps/hook/tests/register.test.ts +++ b/apps/hook/tests/register.test.ts @@ -13,7 +13,7 @@ const TOOL_PREFIX = 'mcp__plugin_plannotator_tools__' const TOOL = `${TOOL_PREFIX}plannotator` /** The world beneath the mod: a session, a file map, and a CLI that comes up at once. */ -function world(on: any, options: { files?: Map; enabled?: boolean } = {}) { +function world(on: any, options: { files?: Map; modEnv?: string; cliStderr?: string } = {}) { const files = options.files ?? new Map() const runs: string[][] = [] const submits: string[] = [] @@ -31,8 +31,8 @@ function world(on: any, options: { files?: Map; enabled?: boolea tools.push({ name: e.name, inputSchema: e.inputSchema }) return { value: { tool: `${TOOL_PREFIX}${e.name}` } } }) - // The mod is opt-in; most tests turn it on through the env knob. - mock.env(on, options.enabled === false ? { HOME: '/home/me' } : { HOME: '/home/me', PLANNOTATOR_CLAUDE_MOD: '1' }) + // The mod is on by default: no knob set unless a test opts out. + mock.env(on, options.modEnv === undefined ? { HOME: '/home/me' } : { HOME: '/home/me', PLANNOTATOR_CLAUDE_MOD: options.modEnv }) const env = new Map() on('env.set', ($: any, e: any) => { env.set(e.name, e.value) @@ -49,7 +49,11 @@ function world(on: any, options: { files?: Map; enabled?: boolea on('process.run', ($: any, e: any) => { const argv: string[] = [...e.argv] runs.push(argv) - if (argv[3] === 'plannotator-launch') { + if (argv[3] === 'plannotator-launch' && options.cliStderr !== undefined) { + // A CLI that refuses the subcommand and exits at once. + files.set(`${argv[4]}/stderr`, options.cliStderr) + files.set(`${argv[4]}/exit`, '1\n') + } else if (argv[3] === 'plannotator-launch') { files.set(`${argv[4]}/ready`, `${JSON.stringify({ url: 'http://localhost:4321', isRemote: false, port: 4321 })}\n`) } return { value: { exitCode: 0, stdout: '', stderr: '' } } @@ -109,8 +113,8 @@ describe('register', () => { expect(w.runs.some((argv) => argv.includes('review'))).toBe(true) }) - test('knob off: inert. ExitPlanMode and the skills reach the classic flow; nothing is registered or set', async ($: any, on: any) => { - const w = world(on, { enabled: false }) + test('knob off (PLANNOTATOR_CLAUDE_MOD=0): inert. ExitPlanMode and the skills reach the classic flow; nothing is registered or set', async ($: any, on: any) => { + const w = world(on, { modEnv: '0' }) on('tool.call', () => ({ result: 'the classic flow ran' })) on('command.run', () => ({ text: 'the skill ran' })) await $.session.start(SESSION) @@ -174,15 +178,34 @@ describe('register', () => { expect(w.submits[0]).toContain('fix line 3') }) - test('knob on through config.json in the data dir', async ($: any, on: any) => { - const files = new Map([['/home/me/.plannotator', ''], ['/home/me/.plannotator/config.json', '{"claudeCodeMod": true}']]) - const w = world(on, { enabled: false, files }) + test('knob off through config.json in the data dir', async ($: any, on: any) => { + const files = new Map([['/home/me/.plannotator', ''], ['/home/me/.plannotator/config.json', '{"claudeCodeMod": false}']]) + const w = world(on, { files }) + on('tool.call', () => ({ result: 'the classic flow ran' })) await $.session.start(SESSION) const answer = await $.tool.call({ tool: 'ExitPlanMode', plan: '# Plan\n\n1. Ship.\n' }) - expect(answer.deny).toContain('NOT approved') - expect(w.runs.some((argv) => argv[3] === 'plannotator-launch')).toBe(true) + expect(answer.result).toBe('the classic flow ran') + expect(w.runs).toEqual([]) + expect(w.tools).toEqual([]) + }) + + // Version skew: the plugin updates from main, the binary on its own. A CLI + // with no claude-mod-plan (0.27.25 prints this) must leave plan review to the + // classic flow, every time, instead of failing the call. + test('a CLI without claude-mod-plan: ExitPlanMode reaches the classic flow, with one line saying why', async ($: any, on: any) => { + const w = world(on, { cliStderr: "Unknown command: claude-mod-plan\n\nRun 'plannotator --help' for the list of commands.\n" }) + on('tool.call', () => ({ result: 'the classic flow ran' })) + await $.session.start(SESSION) + + const first = await $.tool.call({ tool: 'ExitPlanMode', plan: '# Plan\n\n1. Ship.\n' }) + const second = await $.tool.call({ tool: 'ExitPlanMode', plan: '# Plan\n\n1. Ship.\n2. Test.\n' }) + + expect(first.result).toBe('the classic flow ran') + expect(second.result).toBe('the classic flow ran') + expect(w.runs.filter((argv) => argv[3] === 'plannotator-launch')).toHaveLength(1) + expect(w.logs.filter((line) => line.includes('classic review'))).toHaveLength(1) }) test('a -p session keeps the classic flow: ExitPlanMode is not touched', async ($: any, on: any) => { @@ -238,8 +261,8 @@ describe('register', () => { expect(w.runs.some((argv) => argv[3] === 'plannotator-launch')).toBe(false) }) - test('knob off: a Bash plannotator command runs as written', async ($: any, on: any) => { - const w = world(on, { enabled: false }) + test('knob off (PLANNOTATOR_CLAUDE_MOD=0): a Bash plannotator command runs as written', async ($: any, on: any) => { + const w = world(on, { modEnv: '0' }) on('tool.call', () => ({ result: { stdout: 'the command ran', stderr: '', interrupted: false } })) await $.session.start(SESSION) diff --git a/packages/shared/config.ts b/packages/shared/config.ts index 2e60d81587..c48fdd8c5b 100644 --- a/packages/shared/config.ts +++ b/packages/shared/config.ts @@ -231,11 +231,10 @@ export interface PlannotatorConfig { */ autoUpdate?: boolean; /** - * Turn on the Claude Code mod (apps/hook/hooks/mod/): non-blocking plan - * review, annotate, code review and annotate-last, plus "Ask this session", - * where Claude Code runs hooks modules. Opt-in while the owner decides - * whether it becomes the default; PLANNOTATOR_CLAUDE_MOD wins over this key. - * Default: false. + * The Claude Code mod (apps/hook/hooks/mod/): non-blocking plan review, + * annotate, code review and annotate-last, plus "Ask this session", where + * Claude Code runs hooks modules. On by default; `false` turns it off. + * PLANNOTATOR_CLAUDE_MOD wins over this key. Default: true. */ claudeCodeMod?: boolean; /** @@ -811,10 +810,10 @@ export function resolveAutoUpdate( } /** - * Resolve whether the Claude Code mod is on (opt-in). + * Resolve whether the Claude Code mod is on (default on; this is the opt-out). * * Priority (highest wins): - * PLANNOTATOR_CLAUDE_MOD env var → config.claudeCodeMod → default false + * PLANNOTATOR_CLAUDE_MOD env var → config.claudeCodeMod → default true * * Env `1` / `true` / `on` turn it on and `0` / `false` / `off` / `disabled` * turn it off; an empty or unrecognized value counts as unset. The mod is a @@ -828,7 +827,7 @@ export function resolveClaudeCodeMod( const v = env.PLANNOTATOR_CLAUDE_MOD?.trim().toLowerCase(); if (v === "1" || v === "true" || v === "on") return true; if (v === "0" || v === "false" || v === "off" || v === "disabled") return false; - return coerceConfigBoolean(config.claudeCodeMod, false); + return coerceConfigBoolean(config.claudeCodeMod, true); } /** The PLANNOTATOR_AUTO_UPDATE override, or undefined when it does not decide. */