fix(act): scope project-scope removals, --yes safety, --only validation (#604)

Review fixes plus one coordinator amendment on top of the initial
optimize --apply implementation.

- mcp-project-scope no longer strips a server from every projects[*]
  container in ~/.claude.json: only the top-level entry and the
  finding's cold projects lose it, and the cwd's own config files count
  as cold only when the cwd is in the cold list. The plan preview
  annotates ~/.claude.json with the project entries that lose the
  server.
- unused-mcp findings are now appliable (remove-everywhere mcp-remove
  plans, same as low-coverage).
- Notes are rendered under manual findings too, so an all-unparseable
  config surfaces its parse error instead of a bare "manual".
- ConfigDocs strips a leading UTF-8 BOM before JSON.parse.
- claude-md plans are excluded from --apply --yes (they write to
  cwd/CLAUDE.md); they apply via the interactive picker or an explicit
  --only selection, and --yes prints them as skipped with the reason.
- --only with an unknown or not-appliable id errors to stderr with the
  run's valid appliable ids and exit code 2.
- EOF at the interactive prompt prints "Nothing applied." and exits 0;
  an answer that arrives together with EOF is still honored.

Adds end-to-end tests driving runOptimizeApply over injected stdio and
a fixture home: --yes output with journal ids and undo hints, picker
parsing, --only filtering and validation, EOF, claude-md skip, the
projects[*] over-deletion regression, manual-note rendering, and BOM
configs.
This commit is contained in:
AgentSeal 2026-07-03 11:14:06 +02:00
parent 0dd54366b7
commit 92d970196e
4 changed files with 417 additions and 51 deletions

View file

@ -2,7 +2,7 @@ import { createInterface } from 'node:readline/promises'
import { homedir } from 'os'
import chalk from 'chalk'
import type { DateRange, ProjectSummary } from '../types.js'
import { scanAndDetect } from '../optimize.js'
import { scanAndDetect, type WasteFinding } from '../optimize.js'
import { formatCost } from '../currency.js'
import { formatTokens } from '../format.js'
import { runAction } from './apply.js'
@ -15,6 +15,13 @@ export type ApplyOptions = {
only?: string
actionsDir?: string
ctx?: PlanContext
// Test seams: crafted findings skip the session scan; streams default to
// the real stdio.
findings?: WasteFinding[]
costRate?: number
input?: NodeJS.ReadableStream
output?: NodeJS.WritableStream
errorOutput?: NodeJS.WritableStream
}
function short(p: string): string {
@ -23,9 +30,11 @@ function short(p: string): string {
}
function changeLines(fp: FindingPlan): string[] {
return fp.plan!.changes.map(c =>
c.op === 'move' ? `${short(c.path)} -> ${short(c.movedTo)}` : short(c.path),
)
return fp.plan!.changes.map(c => {
const base = c.op === 'move' ? `${short(c.path)} -> ${short(c.movedTo)}` : short(c.path)
const note = fp.pathNotes?.[c.path]
return note ? `${base} (${note})` : base
})
}
export function renderApplyList(appliable: FindingPlan[], manual: FindingPlan[], costRate: number): string {
@ -42,7 +51,10 @@ export function renderApplyList(appliable: FindingPlan[], manual: FindingPlan[],
if (manual.length > 0) {
lines.push('')
lines.push(chalk.dim(' Not auto-appliable (apply by hand):'))
for (const fp of manual) lines.push(chalk.dim(` - ${fp.finding.title} [${fp.finding.id}] manual`))
for (const fp of manual) {
lines.push(chalk.dim(` - ${fp.finding.title} [${fp.finding.id}] manual`))
for (const note of fp.notes) lines.push(chalk.yellow(` ! ${note}`))
}
}
lines.push('')
return lines.join('\n')
@ -62,10 +74,17 @@ function selectPlans(answer: string, appliable: FindingPlan[]): FindingPlan[] {
return picked
}
async function ask(question: string): Promise<string> {
const rl = createInterface({ input: process.stdin, output: process.stdout })
async function ask(question: string, input: NodeJS.ReadableStream, output: NodeJS.WritableStream): Promise<string> {
const rl = createInterface({ input, output })
try {
return await rl.question(question)
// EOF (piped stdin) closes the interface with the question pending;
// treat it as "quit" instead of hanging or dying silently. The close
// fallback is deferred one tick so an answer that arrived together with
// EOF still wins the race.
return await new Promise<string>(resolve => {
rl.question(question).then(resolve, () => resolve(''))
rl.once('close', () => setImmediate(() => resolve('')))
})
} finally {
rl.close()
}
@ -76,50 +95,83 @@ export async function runOptimizeApply(
dateRange: DateRange | undefined,
opts: ApplyOptions = {},
): Promise<void> {
process.stderr.write(chalk.dim(' Analyzing your sessions...\n'))
const { findings, costRate } = await scanAndDetect(projects, dateRange)
const output = opts.output ?? process.stdout
const errout = opts.errorOutput ?? process.stderr
const print = (line = ''): void => { output.write(line + '\n') }
let findings = opts.findings
let costRate = opts.costRate ?? 0
if (!findings) {
errout.write(chalk.dim(' Analyzing your sessions...\n'))
const scanned = await scanAndDetect(projects, dateRange)
findings = scanned.findings
costRate = scanned.costRate
}
const plans = planFindings(findings, opts.ctx)
let appliable = plans.filter(p => p.plan !== null)
const manual = plans.filter(p => p.plan === null)
if (opts.only) {
const wanted = new Set(opts.only.split(',').map(s => s.trim()).filter(Boolean))
appliable = appliable.filter(p => wanted.has(p.finding.id))
const onlyIds = opts.only ? opts.only.split(',').map(s => s.trim()).filter(Boolean) : []
if (onlyIds.length > 0) {
const valid = new Set<string>(appliable.map(p => p.finding.id))
const bad = onlyIds.filter(id => !valid.has(id))
if (bad.length > 0) {
const validList = valid.size > 0 ? [...valid].join(', ') : '(none)'
errout.write(`codeburn optimize --apply: unknown or not-appliable finding id${bad.length === 1 ? '' : 's'}: ${bad.join(', ')}. Appliable ids for this run: ${validList}\n`)
process.exitCode = 2
return
}
appliable = appliable.filter(p => onlyIds.includes(p.finding.id))
}
if (appliable.length === 0) {
console.log(chalk.dim('\n No appliable config-class fixes for this period.\n'))
print(chalk.dim('\n No appliable config-class fixes for this period.'))
for (const fp of manual) {
for (const note of fp.notes) print(chalk.yellow(` ! ${fp.finding.id}: ${note}`))
}
print()
return
}
console.log(renderApplyList(appliable, manual, costRate))
print(renderApplyList(appliable, manual, costRate))
if (opts.dryRun) {
console.log(chalk.dim(' Dry run: nothing was changed.\n'))
print(chalk.dim(' Dry run: nothing was changed.\n'))
return
}
let selected = appliable
if (!opts.yes) {
const answer = await ask(' Apply all / pick numbers / quit [a / 1 2 3 / q]: ')
selected = selectPlans(answer, appliable)
if (selected.length === 0) {
console.log(chalk.dim(' Nothing applied.\n'))
return
let selected: FindingPlan[]
if (opts.yes) {
// CLAUDE.md rules land in the cwd's file; blanket --yes from an unrelated
// directory would write advice into the wrong project. They need the
// interactive picker or an explicit --only selection.
const explicit = new Set(onlyIds)
const skipped = appliable.filter(fp => fp.plan!.kind === 'claude-md-rule' && !explicit.has(fp.finding.id))
selected = appliable.filter(fp => !skipped.includes(fp))
for (const fp of skipped) {
print(chalk.yellow(` Skipped ${fp.finding.id}: CLAUDE.md edits are not applied with --yes; use the interactive picker or --only ${fp.finding.id}.`))
}
} else {
const answer = await ask(' Apply all / pick numbers / quit [a / 1 2 3 / q]: ', opts.input ?? process.stdin, output)
selected = selectPlans(answer, appliable)
}
console.log('')
if (selected.length === 0) {
print(chalk.dim(' Nothing applied.\n'))
return
}
print()
for (const fp of selected) {
try {
const record = await runAction(fp.plan!, opts.actionsDir)
console.log(` Applied ${chalk.bold(shortId(record.id))} ${record.description}`)
console.log(chalk.dim(` Undo anytime: codeburn act undo ${shortId(record.id)}`))
print(` Applied ${chalk.bold(shortId(record.id))} ${record.description}`)
print(chalk.dim(` Undo anytime: codeburn act undo ${shortId(record.id)}`))
} catch (e) {
console.error(chalk.red(` Failed to apply ${fp.finding.id}: ${e instanceof Error ? e.message : String(e)}`))
errout.write(chalk.red(` Failed to apply ${fp.finding.id}: ${e instanceof Error ? e.message : String(e)}`) + '\n')
process.exitCode = 1
}
}
console.log('')
print()
}

View file

@ -19,6 +19,9 @@ export type BuiltPlan = {
plan: ActionPlan | null
// Human-facing skip reasons and parse errors, surfaced in the apply summary.
notes: string[]
// Per-file preview annotations (path -> text), e.g. which ~/.claude.json
// project entries lose a server.
pathNotes?: Record<string, string>
}
export type FindingPlan = BuiltPlan & { finding: WasteFinding }
@ -68,6 +71,7 @@ export function planFindings(findings: WasteFinding[], ctx: PlanContext = {}): F
function buildPlan(finding: WasteFinding, r: ResolvedPaths): BuiltPlan {
switch (finding.id) {
case 'mcp-low-coverage': return buildMcpRemove(finding, r)
case 'unused-mcp': return buildMcpRemove(finding, r)
case 'mcp-project-scope': return buildMcpProjectScope(finding, r)
case 'unused-skills': return buildArchive(finding, r, 'skill')
case 'unused-agents': return buildArchive(finding, r, 'agent')
@ -127,6 +131,7 @@ class ConfigDocs {
this.docs.set(path, null)
return null
}
if (raw.charCodeAt(0) === 0xfeff) raw = raw.slice(1)
try {
const doc = JSON.parse(raw) as Record<string, unknown>
const state: DocState = { path, doc, existed: true, dirty: false }
@ -158,55 +163,78 @@ class ConfigDocs {
}
}
function serverContainers(state: DocState, isUserClaudeJson: boolean): Array<Record<string, unknown>> {
const containers: Array<Record<string, unknown>> = []
type ContainerRef = { container: Record<string, unknown>; projectPath: string | null }
function serverContainers(state: DocState, isUserClaudeJson: boolean): ContainerRef[] {
const containers: ContainerRef[] = []
const top = state.doc.mcpServers
if (top && typeof top === 'object') containers.push(top as Record<string, unknown>)
if (top && typeof top === 'object') containers.push({ container: top as Record<string, unknown>, projectPath: null })
if (isUserClaudeJson) {
const projects = state.doc.projects
if (projects && typeof projects === 'object') {
for (const entry of Object.values(projects as Record<string, unknown>)) {
for (const [projectPath, entry] of Object.entries(projects as Record<string, unknown>)) {
const pm = (entry as Record<string, unknown> | null)?.['mcpServers']
if (pm && typeof pm === 'object') containers.push(pm as Record<string, unknown>)
if (pm && typeof pm === 'object') containers.push({ container: pm as Record<string, unknown>, projectPath })
}
}
}
return containers
}
function deleteServer(state: DocState, server: string, isUserClaudeJson: boolean): boolean {
// Deletes the server from the file's containers. With projectScope set, only
// the top-level container and the listed (cold) project entries are touched;
// entries under any other project path keep their copy.
function deleteServer(
state: DocState,
server: string,
isUserClaudeJson: boolean,
projectScope?: ReadonlySet<string>,
): { removed: boolean; projectEntries: string[] } {
let removed = false
for (const container of serverContainers(state, isUserClaudeJson)) {
const projectEntries: string[] = []
for (const { container, projectPath } of serverContainers(state, isUserClaudeJson)) {
if (projectScope && projectPath !== null && !projectScope.has(projectPath)) continue
const key = findServerKey(container, server)
if (key) {
delete container[key]
state.dirty = true
removed = true
}
if (!key) continue
delete container[key]
state.dirty = true
removed = true
if (projectPath !== null) projectEntries.push(projectPath)
}
return removed
return { removed, projectEntries }
}
function readServerValue(state: DocState, server: string, isUserClaudeJson: boolean): unknown {
for (const container of serverContainers(state, isUserClaudeJson)) {
for (const { container } of serverContainers(state, isUserClaudeJson)) {
const key = findServerKey(container, server)
if (key) return container[key]
}
return undefined
}
function projectRemovalNote(server: string, entries: string[], homeDir: string): string {
const noun = entries.length === 1 ? 'entry' : 'entries'
return `removes ${server} from ${entries.length} project ${noun}: ${entries.map(e => shortPath(e, homeDir)).join(', ')}`
}
function buildMcpRemove(finding: WasteFinding, r: ResolvedPaths): BuiltPlan {
const servers = finding.apply?.kind === 'mcp-remove' ? finding.apply.servers : []
const searchPaths = [r.projectMcpJson, r.projectSettings, r.projectSettingsLocal, r.userClaudeJson]
const docs = new ConfigDocs(r.homeDir)
const skips: string[] = []
const pathNotes: Record<string, string> = {}
const addPathNote = (path: string, note: string): void => {
pathNotes[path] = pathNotes[path] ? `${pathNotes[path]}; ${note}` : note
}
for (const server of servers) {
let removed = false
for (const path of searchPaths) {
const state = docs.load(path)
if (!state) continue
if (deleteServer(state, server, path === r.userClaudeJson)) removed = true
const res = deleteServer(state, server, path === r.userClaudeJson)
if (res.removed) removed = true
if (res.projectEntries.length > 0) addPathNote(path, projectRemovalNote(server, res.projectEntries, r.homeDir))
}
if (!removed) skips.push(`skipped ${server}: not found in editable config (plugin or managed config?)`)
}
@ -217,6 +245,7 @@ function buildMcpRemove(finding: WasteFinding, r: ResolvedPaths): BuiltPlan {
return {
plan: mcpPlan('mcp-remove', finding.id, `Remove ${changes.length === 1 ? 'an MCP server' : 'MCP servers'} from config`, changes),
notes,
...(Object.keys(pathNotes).length > 0 ? { pathNotes } : {}),
}
}
@ -225,8 +254,12 @@ function buildMcpProjectScope(finding: WasteFinding, r: ResolvedPaths): BuiltPla
const searchPaths = [r.projectMcpJson, r.projectSettings, r.projectSettingsLocal, r.userClaudeJson]
const docs = new ConfigDocs(r.homeDir)
const skips: string[] = []
const pathNotes: Record<string, string> = {}
const addPathNote = (path: string, note: string): void => {
pathNotes[path] = pathNotes[path] ? `${pathNotes[path]}; ${note}` : note
}
for (const { server, keepProjects } of entries) {
for (const { server, keepProjects, removeProjects } of entries) {
const keepers = keepProjects.filter(p => isAbsolute(p))
if (keepers.length === 0) {
skips.push(`skipped ${server}: no absolute keeper project path to scope into`)
@ -245,12 +278,19 @@ function buildMcpProjectScope(finding: WasteFinding, r: ResolvedPaths): BuiltPla
continue
}
// Scoped removal: only the global entry and the finding's cold projects
// lose the server. The cwd's own config files count as cold only when
// the cwd is in the cold list; a keeper or unrelated cwd keeps its copy.
const coldSet = new Set(removeProjects)
const keeperMcpPaths = new Set(keepers.map(k => join(k, '.mcp.json')))
for (const path of searchPaths) {
if (keeperMcpPaths.has(path)) continue
const isUser = path === r.userClaudeJson
if (!isUser && !coldSet.has(r.cwd)) continue
const state = docs.load(path)
if (!state) continue
deleteServer(state, server, path === r.userClaudeJson)
const res = deleteServer(state, server, isUser, isUser ? coldSet : undefined)
if (res.projectEntries.length > 0) addPathNote(path, projectRemovalNote(server, res.projectEntries, r.homeDir))
}
for (const keeper of keepers) {
@ -274,6 +314,7 @@ function buildMcpProjectScope(finding: WasteFinding, r: ResolvedPaths): BuiltPla
return {
plan: mcpPlan('mcp-project-scope', finding.id, `Project-scope ${entries.length === 1 ? 'an MCP server' : 'MCP servers'}`, changes),
notes,
...(Object.keys(pathNotes).length > 0 ? { pathNotes } : {}),
}
}

View file

@ -212,7 +212,9 @@ export type FindingId =
// on findings that have an appliable plan; absent otherwise.
export type FindingApply =
| { kind: 'mcp-remove'; servers: string[] }
| { kind: 'mcp-project-scope'; servers: Array<{ server: string; keepProjects: string[] }> }
// keepProjects gain the entry; removeProjects (the cold projects) are the
// only per-project containers a scoped removal may touch.
| { kind: 'mcp-project-scope'; servers: Array<{ server: string; keepProjects: string[]; removeProjects: string[] }> }
| { kind: 'archive'; names: string[] }
export type WasteFinding = {
@ -1222,7 +1224,11 @@ export function detectMcpProfileAdvisor(
},
apply: {
kind: 'mcp-project-scope',
servers: candidates.map(c => ({ server: c.server, keepProjects: c.hotProjects.map(p => p.projectPath) })),
servers: candidates.map(c => ({
server: c.server,
keepProjects: c.hotProjects.map(p => p.projectPath),
removeProjects: c.coldProjects.map(p => p.projectPath),
})),
},
}
}
@ -1525,6 +1531,7 @@ export function detectUnusedMcp(
explanation: `Never called in this period: ${unused.join(', ')}. Each server loads ~${TOOLS_PER_MCP_SERVER * TOKENS_PER_MCP_TOOL} tokens of tool schema into every session.`,
impact: unused.length >= UNUSED_MCP_HIGH_THRESHOLD ? 'high' : 'medium',
tokensSaved,
apply: { kind: 'mcp-remove', servers: unused },
fix: {
type: 'command',
label: `Remove unused server${unused.length > 1 ? 's' : ''}:`,

View file

@ -4,12 +4,13 @@ import { existsSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { createHash } from 'node:crypto'
import { PassThrough, Writable } from 'node:stream'
import { planFor, planFindings } from '../src/act/plans.js'
import { renderApplyList } from '../src/act/optimize-apply.js'
import { planFor, planFindings, type PlanContext } from '../src/act/plans.js'
import { renderApplyList, runOptimizeApply, type ApplyOptions } from '../src/act/optimize-apply.js'
import { runAction } from '../src/act/apply.js'
import { undoAction } from '../src/act/undo.js'
import { readRecords } from '../src/act/journal.js'
import { readRecords, shortId } from '../src/act/journal.js'
import {
detectBloatedClaudeMd,
detectDuplicateReads,
@ -118,7 +119,7 @@ describe('mcp-project-scope plan', () => {
const finding = makeFinding('mcp-project-scope', { type: 'paste', destination: 'prompt', label: '', text: '' }, {
kind: 'mcp-project-scope',
servers: [{ server: 'srv', keepProjects: [keeper] }],
servers: [{ server: 'srv', keepProjects: [keeper], removeProjects: [] }],
})
const plan = planFor(finding, { homeDir: fx.home, cwd: fx.project })
expect(plan).not.toBeNull()
@ -320,3 +321,268 @@ describe('finding-id regression guard', () => {
expect(new Set(ids).size).toBe(ids.length)
})
})
describe('unused-mcp plan', () => {
it('builds a remove-everywhere plan, including other projects[*] entries', async () => {
const fx = await makeFixture()
const claudeJson = join(fx.home, '.claude.json')
await writeFile(claudeJson, JSON.stringify({
mcpServers: { u: { command: 'u' } },
projects: { '/some/other': { mcpServers: { u: { command: 'u' }, keepme: {} } } },
}, null, 2) + '\n')
const finding = makeFinding('unused-mcp', CMD_FIX, { kind: 'mcp-remove', servers: ['u'] })
const plan = planFor(finding, { homeDir: fx.home, cwd: fx.project })
expect(plan).not.toBeNull()
expect(plan!.kind).toBe('mcp-remove')
await runAction(plan!, fx.actionsDir)
const after = JSON.parse(await readFile(claudeJson, 'utf-8'))
expect(after.mcpServers).toEqual({})
expect(after.projects['/some/other'].mcpServers).toEqual({ keepme: {} })
})
})
describe('BOM handling', () => {
it('parses a config file with a UTF-8 BOM', async () => {
const fx = await makeFixture()
const claudeJson = join(fx.home, '.claude.json')
await writeFile(claudeJson, '' + JSON.stringify({ mcpServers: { b: {} }, keep: 1 }, null, 2) + '\n')
const { plan, notes } = planFindings(
[makeFinding('mcp-low-coverage', CMD_FIX, { kind: 'mcp-remove', servers: ['b'] })],
{ homeDir: fx.home, cwd: fx.project },
)[0]!
expect(notes).toEqual([])
expect(plan).not.toBeNull()
const written = JSON.parse(String(plan!.changes[0]!.content))
expect(written).toEqual({ mcpServers: {}, keep: 1 })
})
})
// ---------------------------------------------------------------------------
// runOptimizeApply end-to-end (injected stdio, crafted findings, fixture home)
// ---------------------------------------------------------------------------
const ANSI = /\[[0-9;]*m/g
type Io = {
input: PassThrough
output: Writable
errorOutput: Writable
stdout(): string
stderr(): string
}
function makeIo(answer?: string): Io {
const input = new PassThrough()
input.end(answer ?? '')
const outChunks: Buffer[] = []
const errChunks: Buffer[] = []
const output = new Writable({ write(c, _e, cb) { outChunks.push(Buffer.from(c)); cb() } })
const errorOutput = new Writable({ write(c, _e, cb) { errChunks.push(Buffer.from(c)); cb() } })
return {
input,
output,
errorOutput,
stdout: () => Buffer.concat(outChunks).toString('utf-8').replace(ANSI, ''),
stderr: () => Buffer.concat(errChunks).toString('utf-8').replace(ANSI, ''),
}
}
function applyOpts(fx: Fixture, io: Io, extra: Partial<ApplyOptions> & { findings: WasteFinding[] }): ApplyOptions {
const ctx: PlanContext = { homeDir: fx.home, cwd: fx.project, shell: '/bin/zsh' }
return {
ctx,
actionsDir: fx.actionsDir,
input: io.input,
output: io.output,
errorOutput: io.errorOutput,
...extra,
}
}
// One mcp server, one skill, one shell cap: three appliable findings in a
// stable 1/2/3 order for the picker tests.
async function threeFindingFixture(): Promise<{ fx: Fixture; findings: WasteFinding[] }> {
const fx = await makeFixture()
await writeFile(join(fx.home, '.claude.json'), JSON.stringify({ mcpServers: { a: { command: 'a' } } }, null, 2) + '\n')
await mkdir(join(fx.home, '.claude', 'skills', 'foo'), { recursive: true })
await writeFile(join(fx.home, '.claude', 'skills', 'foo', 'SKILL.md'), 'x')
const findings: WasteFinding[] = [
makeFinding('mcp-low-coverage', CMD_FIX, { kind: 'mcp-remove', servers: ['a'] }),
makeFinding('unused-skills', CMD_FIX, { kind: 'archive', names: ['foo'] }),
makeFinding('bash-output-cap', { type: 'paste', destination: 'shell-config', label: '', text: 'export BASH_MAX_OUTPUT_LENGTH=15000' }),
]
return { fx, findings }
}
describe('runOptimizeApply end-to-end', () => {
it('--yes applies every plan and prints journal short ids with the undo hint', async () => {
const { fx, findings } = await threeFindingFixture()
const io = makeIo()
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings, yes: true }))
const records = await readRecords(fx.actionsDir)
expect(records).toHaveLength(3)
const out = io.stdout()
for (const rec of records) {
expect(out).toContain(`Applied ${shortId(rec.id)}`)
expect(out).toContain(`Undo anytime: codeburn act undo ${shortId(rec.id)}`)
}
expect(JSON.parse(await readFile(join(fx.home, '.claude.json'), 'utf-8')).mcpServers).toEqual({})
expect(existsSync(join(fx.home, '.claude', 'skills', '.archived', 'foo'))).toBe(true)
expect(existsSync(join(fx.home, '.zshrc'))).toBe(true)
})
it('interactive pick "2" applies only the second plan', async () => {
const { fx, findings } = await threeFindingFixture()
const io = makeIo('2\n')
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings }))
const records = await readRecords(fx.actionsDir)
expect(records).toHaveLength(1)
expect(records[0]!.kind).toBe('archive-skill')
expect(JSON.parse(await readFile(join(fx.home, '.claude.json'), 'utf-8')).mcpServers).toEqual({ a: { command: 'a' } })
expect(existsSync(join(fx.home, '.zshrc'))).toBe(false)
})
it('interactive pick "1,3" applies the first and third plans', async () => {
const { fx, findings } = await threeFindingFixture()
const io = makeIo('1,3\n')
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings }))
const records = await readRecords(fx.actionsDir)
expect(records.map(r => r.kind).sort()).toEqual(['mcp-remove', 'shell-config'])
expect(existsSync(join(fx.home, '.claude', 'skills', 'foo'))).toBe(true)
})
it('a garbage answer applies nothing and prints the empty outcome', async () => {
const { fx, findings } = await threeFindingFixture()
const io = makeIo('wat\n')
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings }))
expect(await readRecords(fx.actionsDir)).toHaveLength(0)
expect(io.stdout()).toContain('Nothing applied.')
})
it('EOF at the prompt prints "Nothing applied." and leaves the exit code untouched', async () => {
const { fx, findings } = await threeFindingFixture()
const io = makeIo()
const prevExit = process.exitCode
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings }))
expect(process.exitCode).toBe(prevExit)
expect(io.stdout()).toContain('Nothing applied.')
expect(await readRecords(fx.actionsDir)).toHaveLength(0)
})
it('--only restricts the applied set', async () => {
const { fx, findings } = await threeFindingFixture()
const io = makeIo()
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings, yes: true, only: 'unused-skills' }))
const records = await readRecords(fx.actionsDir)
expect(records).toHaveLength(1)
expect(records[0]!.kind).toBe('archive-skill')
expect(JSON.parse(await readFile(join(fx.home, '.claude.json'), 'utf-8')).mcpServers).toEqual({ a: { command: 'a' } })
})
it('--only with an unknown or not-appliable id errors with the valid ids and exit code 2', async () => {
const { fx, findings } = await threeFindingFixture()
const io = makeIo()
const prevExit = process.exitCode
try {
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings, yes: true, only: 'read-edit-ratio' }))
expect(process.exitCode).toBe(2)
const err = io.stderr()
expect(err).toContain('read-edit-ratio')
expect(err).toContain('Appliable ids for this run:')
expect(err).toContain('mcp-low-coverage')
expect(await readRecords(fx.actionsDir)).toHaveLength(0)
expect(io.stdout()).not.toContain('No appliable config-class fixes')
} finally {
process.exitCode = prevExit
}
})
it('--yes skips claude-md plans with a reason unless explicitly selected via --only', async () => {
const { fx, findings } = await threeFindingFixture()
const claudeMdFinding = makeFinding('read-edit-ratio', { type: 'paste', destination: 'claude-md', label: '', text: 'Read first.' })
const io = makeIo()
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings: [claudeMdFinding, ...findings], yes: true }))
expect(io.stdout()).toContain('Skipped read-edit-ratio: CLAUDE.md edits are not applied with --yes')
expect(existsSync(join(fx.project, 'CLAUDE.md'))).toBe(false)
expect((await readRecords(fx.actionsDir)).map(r => r.kind)).not.toContain('claude-md-rule')
const fx2 = await makeFixture()
const io2 = makeIo()
await runOptimizeApply([], undefined, applyOpts(fx2, io2, { findings: [claudeMdFinding], yes: true, only: 'read-edit-ratio' }))
expect((await readRecords(fx2.actionsDir)).map(r => r.kind)).toEqual(['claude-md-rule'])
expect(await readFile(join(fx2.project, 'CLAUDE.md'), 'utf-8')).toContain('<!-- codeburn:begin read-edit-ratio -->')
})
it('project-scope leaves unrelated projects[*] entries untouched and previews the cold removals', async () => {
const fx = await makeFixture()
const claudeJson = join(fx.home, '.claude.json')
const serverValue = { command: 'srv' }
await writeFile(claudeJson, JSON.stringify({
mcpServers: { srv: serverValue },
projects: {
'/cold/one': { mcpServers: { srv: serverValue } },
'/unrelated/proj': { mcpServers: { srv: serverValue, keepme: {} } },
},
}, null, 2) + '\n')
const keeper = join(fx.root, 'keeper')
await mkdir(keeper, { recursive: true })
const finding = makeFinding('mcp-project-scope', CMD_FIX, {
kind: 'mcp-project-scope',
servers: [{ server: 'srv', keepProjects: [keeper], removeProjects: ['/cold/one'] }],
})
const io = makeIo()
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings: [finding], yes: true }))
expect(io.stdout()).toContain('(removes srv from 1 project entry: /cold/one)')
const after = JSON.parse(await readFile(claudeJson, 'utf-8'))
expect(after.mcpServers).toEqual({})
expect(after.projects['/cold/one'].mcpServers).toEqual({})
expect(after.projects['/unrelated/proj'].mcpServers).toEqual({ srv: serverValue, keepme: {} })
expect(JSON.parse(await readFile(join(keeper, '.mcp.json'), 'utf-8')).mcpServers).toEqual({ srv: serverValue })
})
it('surfaces parse-error notes when every plan resolves to null', async () => {
const fx = await makeFixture()
await writeFile(join(fx.home, '.claude.json'), 'not json{{{')
const finding = makeFinding('mcp-low-coverage', CMD_FIX, { kind: 'mcp-remove', servers: ['ghost'] })
const io = makeIo()
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings: [finding], yes: true }))
const out = io.stdout()
expect(out).toContain('No appliable config-class fixes')
expect(out).toContain('could not parse')
expect(out).toContain('.claude.json')
expect(await readRecords(fx.actionsDir)).toHaveLength(0)
})
it('renders notes under manual findings alongside appliable ones', async () => {
const fx = await makeFixture()
await writeFile(join(fx.home, '.claude.json'), 'not json{{{')
await mkdir(join(fx.home, '.claude', 'skills', 'foo'), { recursive: true })
await writeFile(join(fx.home, '.claude', 'skills', 'foo', 'SKILL.md'), 'x')
const findings: WasteFinding[] = [
makeFinding('mcp-low-coverage', CMD_FIX, { kind: 'mcp-remove', servers: ['ghost'] }),
makeFinding('unused-skills', CMD_FIX, { kind: 'archive', names: ['foo'] }),
]
const io = makeIo()
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings, dryRun: true }))
const out = io.stdout()
expect(out).toContain('[mcp-low-coverage] manual')
expect(out).toContain('could not parse')
})
})