mirror of
https://github.com/AgentSeal/codeburn.git
synced 2026-12-03 03:29:51 +00:00
fix(optimize): conserve MCP action savings
This commit is contained in:
parent
1ea3d68e71
commit
8785b0dc55
8 changed files with 567 additions and 54 deletions
|
|
@ -37,17 +37,43 @@ function changeLines(fp: FindingPlan): string[] {
|
|||
})
|
||||
}
|
||||
|
||||
function planTokensSaved(fp: FindingPlan): number {
|
||||
if (fp.plan?.mcpSavingsUncertain) return Number.NaN
|
||||
const byServer = fp.finding.applyTokensSavedByServer
|
||||
const affected = fp.plan?.affectedMcpServers
|
||||
if (byServer && affected) return affected.reduce((sum, server) => sum + (byServer[server] ?? 0), 0)
|
||||
return fp.finding.applyTokensSaved ?? fp.finding.tokensSaved
|
||||
}
|
||||
|
||||
function manualActionLines(fp: FindingPlan): string[] {
|
||||
if (fp.finding.manualFollowUp) {
|
||||
return [fp.finding.manualFollowUp.label, fp.finding.manualFollowUp.text]
|
||||
}
|
||||
const action = fp.finding.fix
|
||||
if (action.type === 'paste' && action.destination === 'manual') {
|
||||
return [action.label, action.text]
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
export function renderApplyList(appliable: FindingPlan[], manual: FindingPlan[], costRate: number): string {
|
||||
const lines: string[] = ['']
|
||||
lines.push(chalk.bold(' Appliable config-class fixes:'))
|
||||
appliable.forEach((fp, i) => {
|
||||
const f = fp.finding
|
||||
const actionTokensSaved = f.applyTokensSaved ?? f.tokensSaved
|
||||
const savings = `~${formatTokens(actionTokensSaved)} tokens${costRate > 0 ? `, ~${formatCost(actionTokensSaved * costRate)}` : ''}`
|
||||
const actionTokensSaved = planTokensSaved(fp)
|
||||
const savings = Number.isFinite(actionTokensSaved)
|
||||
? `~${formatTokens(actionTokensSaved)} tokens${costRate > 0 ? `, ~${formatCost(actionTokensSaved * costRate)}` : ''}`
|
||||
: 'Savings not estimated'
|
||||
lines.push('')
|
||||
lines.push(` ${i + 1}. ${f.title} ${chalk.hex('#FFD700')(`(${savings})`)}`)
|
||||
if (fp.plan?.affectedMcpServers?.length) {
|
||||
const servers = fp.plan.affectedMcpServers.join(', ')
|
||||
lines.push(chalk.yellow(` Removes local MCP server${fp.plan.affectedMcpServers.length === 1 ? '' : 's'}: ${servers}`))
|
||||
}
|
||||
for (const line of changeLines(fp)) lines.push(chalk.dim(` ${line}`))
|
||||
for (const note of fp.notes) lines.push(chalk.yellow(` ! ${note}`))
|
||||
for (const line of manualActionLines(fp)) lines.push(chalk.cyan(` ${line}`))
|
||||
})
|
||||
if (manual.length > 0) {
|
||||
lines.push('')
|
||||
|
|
@ -55,6 +81,7 @@ export function renderApplyList(appliable: FindingPlan[], manual: FindingPlan[],
|
|||
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}`))
|
||||
for (const line of manualActionLines(fp)) lines.push(chalk.cyan(` ${line}`))
|
||||
}
|
||||
}
|
||||
lines.push('')
|
||||
|
|
@ -130,6 +157,7 @@ export async function runOptimizeApply(
|
|||
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}`))
|
||||
for (const line of manualActionLines(fp)) print(chalk.cyan(` ${line}`))
|
||||
}
|
||||
print()
|
||||
return
|
||||
|
|
|
|||
|
|
@ -275,12 +275,15 @@ function pathNoteAdder(pathNotes: Record<string, string>): (path: string, note:
|
|||
}
|
||||
|
||||
function buildMcpRemove(finding: WasteFinding, r: ResolvedPaths): BuiltPlan {
|
||||
const servers = finding.apply?.kind === 'mcp-remove' ? finding.apply.servers : []
|
||||
const servers = finding.apply?.kind === 'mcp-remove'
|
||||
? [...new Set(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 = pathNoteAdder(pathNotes)
|
||||
const affectedServers: string[] = []
|
||||
|
||||
for (const server of servers) {
|
||||
let removed = false
|
||||
|
|
@ -291,14 +294,24 @@ function buildMcpRemove(finding: WasteFinding, r: ResolvedPaths): BuiltPlan {
|
|||
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?)`)
|
||||
if (removed) affectedServers.push(server)
|
||||
else skips.push(`skipped ${server}: not found in editable config (plugin or managed config?)`)
|
||||
}
|
||||
|
||||
const changes = docs.changes()
|
||||
const notes = [...docs.errorNotes(), ...skips]
|
||||
const attribution = finding.applyTokensSavedByServer
|
||||
const partialWithoutAttribution = affectedServers.length < servers.length && !attribution
|
||||
const affectedMissingAttribution = attribution !== undefined
|
||||
&& affectedServers.some(server => !Object.hasOwn(attribution, server))
|
||||
const savingsUncertain = docs.errorNotes().length > 0
|
||||
|| partialWithoutAttribution
|
||||
|| affectedMissingAttribution
|
||||
if (changes.length === 0) return { plan: null, notes }
|
||||
const plan = mcpPlan('mcp-remove', finding.id, `Remove ${affectedServers.length === 1 ? 'an MCP server' : 'MCP servers'} from config`, changes, affectedServers)
|
||||
if (savingsUncertain) plan.mcpSavingsUncertain = true
|
||||
return {
|
||||
plan: mcpPlan('mcp-remove', finding.id, `Remove ${changes.length === 1 ? 'an MCP server' : 'MCP servers'} from config`, changes),
|
||||
plan,
|
||||
notes,
|
||||
...(Object.keys(pathNotes).length > 0 ? { pathNotes } : {}),
|
||||
}
|
||||
|
|
@ -371,8 +384,8 @@ function buildMcpProjectScope(finding: WasteFinding, r: ResolvedPaths): BuiltPla
|
|||
}
|
||||
}
|
||||
|
||||
function mcpPlan(kind: ActionKind, findingId: string, description: string, changes: PlannedChange[]): ActionPlan {
|
||||
return { kind, findingId, description, changes }
|
||||
function mcpPlan(kind: ActionKind, findingId: string, description: string, changes: PlannedChange[], affectedMcpServers?: string[]): ActionPlan {
|
||||
return { kind, findingId, description, changes, ...(affectedMcpServers ? { affectedMcpServers } : {}) }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -666,7 +666,8 @@ type CaptureCtx = {
|
|||
now: Date
|
||||
}
|
||||
|
||||
function mcpServersFromApply(finding: WasteFinding): string[] {
|
||||
function mcpServersFromApply(finding: WasteFinding, affectedMcpServers?: string[]): string[] {
|
||||
if (affectedMcpServers) return affectedMcpServers
|
||||
if (finding.apply?.kind === 'mcp-remove') return finding.apply.servers
|
||||
if (finding.apply?.kind === 'mcp-project-scope') return finding.apply.servers.map(s => s.server)
|
||||
return []
|
||||
|
|
@ -684,7 +685,12 @@ function deferServers(finding: WasteFinding, ctx: CaptureCtx): string[] {
|
|||
return observedMcpServers(ctx.projects)
|
||||
}
|
||||
|
||||
export function captureBaseline(finding: WasteFinding, kind: ActionKind, ctx: CaptureCtx): ActionBaseline | undefined {
|
||||
export function captureBaseline(
|
||||
finding: WasteFinding,
|
||||
kind: ActionKind,
|
||||
ctx: CaptureCtx,
|
||||
affectedMcpServers?: string[],
|
||||
): ActionBaseline | undefined {
|
||||
const common = {
|
||||
windowDays: ctx.windowDays,
|
||||
capturedAt: ctx.now.toISOString(),
|
||||
|
|
@ -692,16 +698,24 @@ export function captureBaseline(finding: WasteFinding, kind: ActionKind, ctx: Ca
|
|||
}
|
||||
|
||||
if (MCP_KINDS.has(kind)) {
|
||||
const servers = mcpServersFromApply(finding)
|
||||
const servers = mcpServersFromApply(finding, affectedMcpServers)
|
||||
if (servers.length === 0) return undefined
|
||||
const covByServer = new Map(ctx.coverage.map(c => [c.server, c]))
|
||||
const metrics: Record<string, number> = {}
|
||||
for (const server of servers) {
|
||||
const cov = covByServer.get(server)
|
||||
const tools = cov && cov.toolsAvailable > 0 ? cov.toolsAvailable : TOOLS_PER_MCP_SERVER
|
||||
// Removal realizes only the unused schema that the low-coverage
|
||||
// detector estimated. If coverage is unavailable, omit the numeric
|
||||
// claim instead of inventing a five-tool baseline.
|
||||
const tools = finding.id === 'mcp-low-coverage'
|
||||
? cov?.unusedTools.length ?? 0
|
||||
: cov && cov.toolsAvailable > 0 ? cov.toolsAvailable : TOOLS_PER_MCP_SERVER
|
||||
metrics[server] = tools * TOKENS_PER_MCP_TOOL
|
||||
}
|
||||
return { ...common, sessions: countSessionsLoading(ctx.projects, servers), metrics }
|
||||
const estimatedTokens = finding.applyTokensSavedByServer
|
||||
? Math.round(servers.reduce((sum, server) => sum + (finding.applyTokensSavedByServer?.[server] ?? 0), 0))
|
||||
: common.estimatedTokens
|
||||
return { ...common, estimatedTokens, sessions: countSessionsLoading(ctx.projects, servers), metrics }
|
||||
}
|
||||
|
||||
if (DEFER_KINDS.has(kind)) {
|
||||
|
|
@ -750,7 +764,8 @@ export async function captureBaselinesForPlans(
|
|||
const projects = await loadProjects({ start, end: now })
|
||||
const ctx: CaptureCtx = { projects, coverage: aggregateMcpCoverage(projects), windowDays: BASELINE_WINDOW_DAYS, now }
|
||||
for (const fp of applicable) {
|
||||
const baseline = captureBaseline(fp.finding, fp.plan!.kind, ctx)
|
||||
if (fp.plan!.mcpSavingsUncertain) continue
|
||||
const baseline = captureBaseline(fp.finding, fp.plan!.kind, ctx, fp.plan!.affectedMcpServers)
|
||||
if (baseline) fp.plan!.baseline = baseline
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -66,4 +66,10 @@ export type ActionPlan = {
|
|||
findingId?: string | null
|
||||
changes: PlannedChange[]
|
||||
baseline?: ActionBaseline
|
||||
// MCP plans only: exact server identities the generated file mutations own.
|
||||
// Preview and baseline capture must not claim skipped/managed targets.
|
||||
affectedMcpServers?: string[]
|
||||
// Relevant config scopes could not all be read, so removal may proceed
|
||||
// with warnings but savings/baseline claims must be suppressed.
|
||||
mcpSavingsUncertain?: boolean
|
||||
}
|
||||
|
|
|
|||
138
src/optimize.ts
138
src/optimize.ts
|
|
@ -305,6 +305,14 @@ export type WasteFinding = {
|
|||
/// subset of the finding. Omitted when `tokensSaved` already describes the
|
||||
/// whole apply action (or when the finding is manual-only).
|
||||
applyTokensSaved?: number
|
||||
/// Per-server shares from the same capped cost pass as `tokensSaved`.
|
||||
/// Internal apply/report consumers use this to price only targets that a
|
||||
/// concrete mutation plan can actually edit; JSON output remains stable.
|
||||
applyTokensSavedByServer?: Record<string, number>
|
||||
/// Additional by-hand action retained when `fix` is an executable local
|
||||
/// command (for example, connector guidance beside a local MCP removal).
|
||||
/// Internal apply UI metadata; the stable optimize JSON mapper omits it.
|
||||
manualFollowUp?: { label: string; text: string }
|
||||
fix: WasteAction
|
||||
trend?: Trend
|
||||
apply?: FindingApply
|
||||
|
|
@ -794,6 +802,12 @@ type McpSchemaCostEstimate = {
|
|||
effectiveInputTokens: number
|
||||
}
|
||||
|
||||
type McpSchemaCostAttribution = McpSchemaCostEstimate & {
|
||||
byServer: Record<string, McpSchemaCostEstimate>
|
||||
}
|
||||
|
||||
type McpUnusedToolsByServer = Record<string, number | readonly string[]>
|
||||
|
||||
/**
|
||||
* Aggregate MCP inventory and invocations across the projects in scope.
|
||||
*
|
||||
|
|
@ -969,49 +983,86 @@ export function estimateMcpSchemaCost(
|
|||
counts = unusedToolCounts
|
||||
}
|
||||
|
||||
const totalUnusedSchemaTokens = servers.reduce(
|
||||
(s, srv) => s + (counts[srv] ?? 0) * TOKENS_PER_MCP_TOOL,
|
||||
0,
|
||||
)
|
||||
if (totalUnusedSchemaTokens === 0) {
|
||||
return { cacheWriteTokens: 0, cacheReadTokens: 0, effectiveInputTokens: 0 }
|
||||
const attributed = estimateMcpSchemaCostAttributed(counts, projects, servers)
|
||||
return {
|
||||
cacheWriteTokens: attributed.cacheWriteTokens,
|
||||
cacheReadTokens: attributed.cacheReadTokens,
|
||||
effectiveInputTokens: attributed.effectiveInputTokens,
|
||||
}
|
||||
}
|
||||
|
||||
function estimateMcpSchemaCostAttributed(
|
||||
unusedToolsByServer: McpUnusedToolsByServer,
|
||||
projects: ProjectSummary[],
|
||||
servers: string[],
|
||||
): McpSchemaCostAttribution {
|
||||
servers = [...new Set(servers)]
|
||||
const byServer: Record<string, McpSchemaCostEstimate> = {}
|
||||
for (const server of servers) {
|
||||
byServer[server] = { cacheWriteTokens: 0, cacheReadTokens: 0, effectiveInputTokens: 0 }
|
||||
}
|
||||
|
||||
const serverSet = new Set(servers)
|
||||
let cacheWriteTokens = 0
|
||||
let cacheReadTokens = 0
|
||||
const addBucket = (
|
||||
loaded: Array<{ server: string; schemaTokens: number }>,
|
||||
bucket: number,
|
||||
key: 'cacheWriteTokens' | 'cacheReadTokens',
|
||||
): void => {
|
||||
if (bucket <= 0) return
|
||||
const totalSchemaTokens = loaded.reduce((sum, entry) => sum + entry.schemaTokens, 0)
|
||||
if (totalSchemaTokens <= 0) return
|
||||
const charged = Math.min(totalSchemaTokens, bucket)
|
||||
for (const entry of loaded) {
|
||||
byServer[entry.server]![key] += charged * (entry.schemaTokens / totalSchemaTokens)
|
||||
}
|
||||
}
|
||||
|
||||
for (const project of projects) {
|
||||
for (const session of project.sessions) {
|
||||
// A session counts only if its observed inventory included at least
|
||||
// one of the flagged servers — same invariant `aggregateMcpCoverage`
|
||||
// uses for `loadedSessions`.
|
||||
let loaded = false
|
||||
for (const fqn of session.mcpInventory ?? []) {
|
||||
const seg = fqn.split('__')[1]
|
||||
if (seg && serverSet.has(seg)) { loaded = true; break }
|
||||
const inventory = new Set(session.mcpInventory ?? [])
|
||||
const inventoryCounts = new Map<string, number>()
|
||||
for (const fqn of inventory) {
|
||||
const parts = fqn.split('__')
|
||||
if (parts[0] !== 'mcp' || !parts[1] || parts.length < 3) continue
|
||||
inventoryCounts.set(parts[1], (inventoryCounts.get(parts[1]) ?? 0) + 1)
|
||||
}
|
||||
if (!loaded) continue
|
||||
|
||||
const loaded: Array<{ server: string; schemaTokens: number }> = []
|
||||
for (const server of servers) {
|
||||
const unused = unusedToolsByServer[server]
|
||||
const toolCount = typeof unused === 'number'
|
||||
? Math.min(unused, inventoryCounts.get(server) ?? 0)
|
||||
: [...new Set(unused ?? [])].reduce((count, fqn) => count + (inventory.has(fqn) ? 1 : 0), 0)
|
||||
if (toolCount > 0) loaded.push({ server, schemaTokens: toolCount * TOKENS_PER_MCP_TOOL })
|
||||
}
|
||||
if (loaded.length === 0) continue
|
||||
|
||||
for (const turn of session.turns) {
|
||||
for (const call of turn.assistantCalls) {
|
||||
// Both buckets can be non-zero on the same call (cache rebuild
|
||||
// alongside a partial read), so account for them independently.
|
||||
// The cap is applied to the combined unused-schema budget so
|
||||
// multiple flagged servers cannot all claim the same call.
|
||||
if (call.usage.cacheCreationInputTokens > 0) {
|
||||
cacheWriteTokens += Math.min(totalUnusedSchemaTokens, call.usage.cacheCreationInputTokens)
|
||||
}
|
||||
if (call.usage.cacheReadInputTokens > 0) {
|
||||
cacheReadTokens += Math.min(totalUnusedSchemaTokens, call.usage.cacheReadInputTokens)
|
||||
}
|
||||
// A cache bucket is shared by every flagged schema loaded on this
|
||||
// call. Charge it once, then attribute the capped amount in
|
||||
// proportion to each server's unused schema. This conserves the
|
||||
// combined total and makes any local-only subset additive.
|
||||
addBucket(loaded, call.usage.cacheCreationInputTokens, 'cacheWriteTokens')
|
||||
addBucket(loaded, call.usage.cacheReadInputTokens, 'cacheReadTokens')
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const effectiveInputTokens = cacheWriteTokens * CACHE_WRITE_MULTIPLIER + cacheReadTokens * CACHE_READ_DISCOUNT
|
||||
return { cacheWriteTokens, cacheReadTokens, effectiveInputTokens }
|
||||
let cacheWriteTokens = 0
|
||||
let cacheReadTokens = 0
|
||||
for (const estimate of Object.values(byServer)) {
|
||||
estimate.effectiveInputTokens = estimate.cacheWriteTokens * CACHE_WRITE_MULTIPLIER
|
||||
+ estimate.cacheReadTokens * CACHE_READ_DISCOUNT
|
||||
cacheWriteTokens += estimate.cacheWriteTokens
|
||||
cacheReadTokens += estimate.cacheReadTokens
|
||||
}
|
||||
return {
|
||||
cacheWriteTokens,
|
||||
cacheReadTokens,
|
||||
effectiveInputTokens: cacheWriteTokens * CACHE_WRITE_MULTIPLIER + cacheReadTokens * CACHE_READ_DISCOUNT,
|
||||
byServer,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -1045,13 +1096,13 @@ export function detectMcpToolCoverage(
|
|||
|
||||
const lines: string[] = []
|
||||
const removeCommands: string[] = []
|
||||
const unusedCountsByServer: Record<string, number> = {}
|
||||
const unusedToolsByServer: Record<string, readonly string[]> = {}
|
||||
const flaggedServers: string[] = []
|
||||
const localServers: string[] = []
|
||||
const connectorServers: string[] = []
|
||||
|
||||
for (const c of flagged) {
|
||||
unusedCountsByServer[c.server] = c.toolsAvailable - c.toolsInvoked
|
||||
unusedToolsByServer[c.server] = c.unusedTools
|
||||
flaggedServers.push(c.server)
|
||||
const pct = Math.round(c.coverageRatio * 100)
|
||||
lines.push(
|
||||
|
|
@ -1069,10 +1120,15 @@ export function detectMcpToolCoverage(
|
|||
// total unused-schema budget across all flagged servers, so two
|
||||
// flagged servers cannot independently claim the same call's cache
|
||||
// bucket and overstate `tokensSaved`.
|
||||
const cost = estimateMcpSchemaCost(unusedCountsByServer, projects, flaggedServers)
|
||||
const cost = estimateMcpSchemaCostAttributed(unusedToolsByServer, projects, flaggedServers)
|
||||
const tokensSaved = Math.round(cost.effectiveInputTokens)
|
||||
const applyTokensSavedByServer = Object.fromEntries(localServers.map(server => [
|
||||
server,
|
||||
cost.byServer[server]?.effectiveInputTokens ?? 0,
|
||||
]))
|
||||
const localTokensSaved = Object.values(applyTokensSavedByServer).reduce((sum, value) => sum + value, 0)
|
||||
const applyTokensSaved = localServers.length > 0 && connectorServers.length > 0
|
||||
? Math.round(estimateMcpSchemaCost(unusedCountsByServer, projects, localServers).effectiveInputTokens)
|
||||
? Math.round(localTokensSaved)
|
||||
: undefined
|
||||
const impact: Impact = tokensSaved >= MCP_COVERAGE_HIGH_IMPACT_TOKENS
|
||||
? 'high'
|
||||
|
|
@ -1093,6 +1149,14 @@ export function detectMcpToolCoverage(
|
|||
const connectorGuidance = connectorServers.length > 0
|
||||
? ` ${connectorEvidence.join(', ')} ${connectorServers.length === 1 ? 'is a claude.ai connector namespace' : 'are claude.ai connector namespaces'}, separate from any similarly named local MCP server. Transcript inventory is aggregated across the selected projects; use /mcp in each project where ${connectorServers.length === 1 ? 'it loads' : 'they load'}, or manage ${connectorServers.length === 1 ? 'it' : 'them'} in claude.ai Settings > Connectors.`
|
||||
: ''
|
||||
const connectorAction = connectorServers.length > 0
|
||||
? {
|
||||
label: connectorServers.length === 1
|
||||
? 'Manage the underused claude.ai connector where it loads:'
|
||||
: 'Manage the underused claude.ai connectors where they load:',
|
||||
text: `Open /mcp in each affected project and disable ${connectorLabels.join(', ')}, or manage ${connectorServers.length === 1 ? 'it' : 'them'} in claude.ai Settings > Connectors.`,
|
||||
}
|
||||
: undefined
|
||||
const fix: WasteAction = localServers.length > 0
|
||||
? {
|
||||
type: 'command',
|
||||
|
|
@ -1104,10 +1168,8 @@ export function detectMcpToolCoverage(
|
|||
: {
|
||||
type: 'paste',
|
||||
destination: 'manual',
|
||||
label: connectorServers.length === 1
|
||||
? 'Manage the underused claude.ai connector where it loads:'
|
||||
: 'Manage the underused claude.ai connectors where they load:',
|
||||
text: `Open /mcp in each affected project and disable ${connectorLabels.join(', ')}, or manage ${connectorServers.length === 1 ? 'it' : 'them'} in claude.ai Settings > Connectors.`,
|
||||
label: connectorAction!.label,
|
||||
text: connectorAction!.text,
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
@ -1120,6 +1182,8 @@ export function detectMcpToolCoverage(
|
|||
impact,
|
||||
tokensSaved,
|
||||
...(applyTokensSaved !== undefined ? { applyTokensSaved } : {}),
|
||||
...(localServers.length > 0 ? { applyTokensSavedByServer } : {}),
|
||||
...(localServers.length > 0 && connectorAction ? { manualFollowUp: connectorAction } : {}),
|
||||
fix,
|
||||
...(localServers.length > 0
|
||||
? { apply: { kind: 'mcp-remove' as const, servers: localServers } }
|
||||
|
|
|
|||
|
|
@ -8,10 +8,12 @@ import {
|
|||
buildActReportJson,
|
||||
buildOptimizeAppliedHeader,
|
||||
captureBaseline,
|
||||
captureBaselinesForPlans,
|
||||
computeActReport,
|
||||
renderActReport,
|
||||
} from '../src/act/report.js'
|
||||
import type { ActionRecord } from '../src/act/types.js'
|
||||
import type { FindingPlan } from '../src/act/plans.js'
|
||||
import type { WasteFinding } from '../src/optimize.js'
|
||||
import type { ClassifiedTurn, ProjectSummary } from '../src/types.js'
|
||||
|
||||
|
|
@ -784,11 +786,11 @@ describe('partial-action baseline capture', () => {
|
|||
coverage: [{
|
||||
server: 'filesystem',
|
||||
toolsAvailable: 20,
|
||||
toolsInvoked: 0,
|
||||
unusedTools: [],
|
||||
toolsInvoked: 3,
|
||||
unusedTools: Array.from({ length: 17 }, (_, i) => `mcp__filesystem__unused${i}`),
|
||||
invocations: 0,
|
||||
loadedSessions: 2,
|
||||
coverageRatio: 0,
|
||||
coverageRatio: 3 / 20,
|
||||
}],
|
||||
windowDays: 14,
|
||||
now: NOW,
|
||||
|
|
@ -797,8 +799,135 @@ describe('partial-action baseline capture', () => {
|
|||
expect(baseline).toMatchObject({
|
||||
estimatedTokens: 20_000,
|
||||
sessions: 2,
|
||||
metrics: { filesystem: 8_000 },
|
||||
metrics: { filesystem: 6_800 },
|
||||
})
|
||||
expect(finding.tokensSaved).toBe(40_000)
|
||||
})
|
||||
|
||||
it('prices and measures only servers owned by the concrete mutation plan', () => {
|
||||
const finding: WasteFinding = {
|
||||
id: 'mcp-low-coverage',
|
||||
title: '2 MCP servers with low tool coverage',
|
||||
explanation: '',
|
||||
impact: 'medium',
|
||||
tokensSaved: 30_000,
|
||||
applyTokensSaved: 30_000,
|
||||
applyTokensSavedByServer: { filesystem: 10_000, managed: 20_000 },
|
||||
fix: { type: 'command', label: '', text: '' },
|
||||
apply: { kind: 'mcp-remove', servers: ['filesystem', 'managed'] },
|
||||
}
|
||||
const sessions = sessionsAt(2, daysAgo(1), {
|
||||
mcpInventory: [
|
||||
...Array.from({ length: 17 }, (_, i) => `mcp__filesystem__t${i}`),
|
||||
...Array.from({ length: 12 }, (_, i) => `mcp__managed__t${i}`),
|
||||
],
|
||||
})
|
||||
const coverage = [
|
||||
{
|
||||
server: 'filesystem', toolsAvailable: 20, toolsInvoked: 3,
|
||||
unusedTools: Array.from({ length: 17 }, (_, i) => `mcp__filesystem__t${i}`),
|
||||
invocations: 3, loadedSessions: 2, coverageRatio: 3 / 20,
|
||||
},
|
||||
{
|
||||
server: 'managed', toolsAvailable: 20, toolsInvoked: 8,
|
||||
unusedTools: Array.from({ length: 12 }, (_, i) => `mcp__managed__t${i}`),
|
||||
invocations: 8, loadedSessions: 2, coverageRatio: 8 / 20,
|
||||
},
|
||||
]
|
||||
|
||||
const baseline = captureBaseline(finding, 'mcp-remove', {
|
||||
projects: [projectOf(sessions)], coverage, windowDays: 14, now: NOW,
|
||||
}, ['filesystem'])
|
||||
|
||||
expect(baseline).toMatchObject({
|
||||
estimatedTokens: 10_000,
|
||||
sessions: 2,
|
||||
metrics: { filesystem: 6_800 },
|
||||
})
|
||||
expect(baseline!.metrics).not.toHaveProperty('managed')
|
||||
})
|
||||
|
||||
it('does not invent a low-coverage schema baseline when coverage is unavailable', () => {
|
||||
const finding: WasteFinding = {
|
||||
id: 'mcp-low-coverage',
|
||||
title: '1 MCP server with low tool coverage',
|
||||
explanation: '',
|
||||
impact: 'medium',
|
||||
tokensSaved: 10_000,
|
||||
applyTokensSavedByServer: { filesystem: 10_000 },
|
||||
fix: { type: 'command', label: '', text: '' },
|
||||
apply: { kind: 'mcp-remove', servers: ['filesystem'] },
|
||||
}
|
||||
|
||||
const baseline = captureBaseline(finding, 'mcp-remove', {
|
||||
projects: [projectOf(sessionsAt(2, daysAgo(1)))],
|
||||
coverage: [],
|
||||
windowDays: 14,
|
||||
now: NOW,
|
||||
}, ['filesystem'])
|
||||
|
||||
expect(baseline).toMatchObject({
|
||||
estimatedTokens: 10_000,
|
||||
metrics: { filesystem: 0 },
|
||||
})
|
||||
})
|
||||
|
||||
it('stamps a narrowed plan with only its concrete server baseline', async () => {
|
||||
const finding: WasteFinding = {
|
||||
id: 'mcp-low-coverage', title: '2 MCP servers', explanation: '', impact: 'medium',
|
||||
tokensSaved: 30_000, applyTokensSaved: 30_000,
|
||||
applyTokensSavedByServer: { filesystem: 10_000, managed: 20_000 },
|
||||
fix: { type: 'command', label: '', text: '' },
|
||||
apply: { kind: 'mcp-remove', servers: ['filesystem', 'managed'] },
|
||||
}
|
||||
const plan: FindingPlan = {
|
||||
finding,
|
||||
notes: [],
|
||||
plan: {
|
||||
kind: 'mcp-remove', description: 'Remove filesystem', changes: [],
|
||||
affectedMcpServers: ['filesystem'],
|
||||
},
|
||||
}
|
||||
const sessions = sessionsAt(2, daysAgo(1), {
|
||||
mcpInventory: [
|
||||
...Array.from({ length: 17 }, (_, i) => `mcp__filesystem__t${i}`),
|
||||
...Array.from({ length: 12 }, (_, i) => `mcp__managed__t${i}`),
|
||||
],
|
||||
})
|
||||
|
||||
await captureBaselinesForPlans([plan], {
|
||||
now: NOW,
|
||||
loadProjects: async () => [projectOf(sessions)],
|
||||
})
|
||||
|
||||
expect(plan.plan?.baseline).toMatchObject({
|
||||
estimatedTokens: 10_000,
|
||||
metrics: { filesystem: 6_800 },
|
||||
})
|
||||
expect(plan.plan?.baseline?.metrics).not.toHaveProperty('managed')
|
||||
})
|
||||
|
||||
it('does not stamp a numeric baseline onto an uncertain partial mutation', async () => {
|
||||
const finding: WasteFinding = {
|
||||
id: 'mcp-low-coverage', title: '1 MCP server', explanation: '', impact: 'medium',
|
||||
tokensSaved: 10_000, applyTokensSavedByServer: { filesystem: 10_000 },
|
||||
fix: { type: 'command', label: '', text: '' },
|
||||
apply: { kind: 'mcp-remove', servers: ['filesystem'] },
|
||||
}
|
||||
const plan: FindingPlan = {
|
||||
finding,
|
||||
notes: ['could not parse .mcp.json'],
|
||||
plan: {
|
||||
kind: 'mcp-remove', description: 'Remove filesystem', changes: [],
|
||||
affectedMcpServers: ['filesystem'], mcpSavingsUncertain: true,
|
||||
},
|
||||
}
|
||||
|
||||
await captureBaselinesForPlans([plan], {
|
||||
now: NOW,
|
||||
loadProjects: async () => [projectOf(sessionsAt(2, daysAgo(1)))],
|
||||
})
|
||||
|
||||
expect(plan.plan?.baseline).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -315,6 +315,23 @@ describe('estimateMcpSchemaCost', () => {
|
|||
expect(cost.cacheWriteTokens).toBe(24_000)
|
||||
})
|
||||
|
||||
it('does not count a duplicated server identifier twice', () => {
|
||||
const inventory = Array.from({ length: 20 }, (_, i) => `mcp__svc__t${i}`)
|
||||
const sessions = [makeSession({
|
||||
inventory,
|
||||
turns: [makeTurn([makeCall({ cacheCreation: 50_000 })])],
|
||||
})]
|
||||
|
||||
const cost = estimateMcpSchemaCost(
|
||||
{ svc: 20 },
|
||||
[project(sessions)],
|
||||
['svc', 'svc'],
|
||||
)
|
||||
|
||||
expect(cost.cacheWriteTokens).toBe(8_000)
|
||||
expect(cost.effectiveInputTokens).toBe(10_000)
|
||||
})
|
||||
|
||||
it('still works with the single-server signature (backward compat)', () => {
|
||||
const turns = [makeTurn([makeCall({ cacheCreation: 50_000 })])]
|
||||
const sessions = [makeSession({
|
||||
|
|
@ -418,6 +435,64 @@ describe('detectMcpToolCoverage', () => {
|
|||
})
|
||||
expect(report.findings[0]).not.toHaveProperty('apply')
|
||||
expect(report.findings[0]).not.toHaveProperty('applyTokensSaved')
|
||||
expect(report.findings[0]).not.toHaveProperty('applyTokensSavedByServer')
|
||||
expect(report.findings[0]).not.toHaveProperty('manualFollowUp')
|
||||
})
|
||||
|
||||
it('intersects globally unused tool identities with each session inventory', () => {
|
||||
const server = 'filesystem'
|
||||
const coverage = [{
|
||||
server,
|
||||
toolsAvailable: 20,
|
||||
toolsInvoked: 0,
|
||||
unusedTools: Array.from({ length: 20 }, (_, i) => `mcp__${server}__t${i}`),
|
||||
invocations: 0,
|
||||
loadedSessions: 2,
|
||||
coverageRatio: 0,
|
||||
}]
|
||||
const sessions = [5, 20].map((count, index) => makeSession({
|
||||
sessionId: `s${index}`,
|
||||
inventory: Array.from({ length: count }, (_, i) => `mcp__${server}__t${i}`),
|
||||
turns: [makeTurn([makeCall({ cacheCreation: 50_000 })])],
|
||||
}))
|
||||
|
||||
const finding = detectMcpToolCoverage([project(sessions)], coverage)
|
||||
|
||||
// 5*400 and 20*400, each at 1.25x cache-write pricing.
|
||||
expect(finding).toMatchObject({ tokensSaved: 12_500 })
|
||||
expect(finding!.applyTokensSavedByServer?.filesystem).toBe(12_500)
|
||||
})
|
||||
|
||||
it('conserves simultaneous cache-write and cache-read buckets with fractional shares', () => {
|
||||
const inventory = [
|
||||
...Array.from({ length: 15 }, (_, i) => `mcp__filesystem__t${i}`),
|
||||
...Array.from({ length: 11 }, (_, i) => `mcp__claude_ai_Slack__t${i}`),
|
||||
]
|
||||
const coverage: McpServerCoverage[] = [
|
||||
{
|
||||
server: 'filesystem', toolsAvailable: 15, toolsInvoked: 0,
|
||||
unusedTools: inventory.slice(0, 15), invocations: 0, loadedSessions: 2, coverageRatio: 0,
|
||||
},
|
||||
{
|
||||
server: 'claude_ai_Slack', toolsAvailable: 11, toolsInvoked: 0,
|
||||
unusedTools: inventory.slice(15), invocations: 0, loadedSessions: 2, coverageRatio: 0,
|
||||
},
|
||||
]
|
||||
// Duplicate inventory entries must not increase the schema share.
|
||||
const sessionInventory = [...inventory, inventory[0]!, inventory[15]!]
|
||||
const sessions = ['a', 'b'].map(sessionId => makeSession({
|
||||
sessionId,
|
||||
inventory: sessionInventory,
|
||||
turns: [makeTurn([makeCall({ cacheCreation: 5_001, cacheRead: 3_333 })])],
|
||||
}))
|
||||
|
||||
const finding = detectMcpToolCoverage([project(sessions)], coverage)!
|
||||
const total = 2 * (5_001 * 1.25 + 3_333 * 0.10)
|
||||
const local = total * (15 / 26)
|
||||
|
||||
expect(finding.tokensSaved).toBe(Math.round(total))
|
||||
expect(finding.applyTokensSaved).toBe(Math.round(local))
|
||||
expect(finding.applyTokensSavedByServer?.filesystem).toBeCloseTo(local, 8)
|
||||
})
|
||||
|
||||
it('pluralises manual guidance when only claude.ai connectors are flagged', () => {
|
||||
|
|
@ -522,6 +597,39 @@ describe('detectMcpToolCoverage', () => {
|
|||
expect(finding!.apply).toEqual({ kind: 'mcp-remove', servers: ['filesystem'] })
|
||||
})
|
||||
|
||||
it('attributes a capped mixed cache bucket proportionally to the local action', () => {
|
||||
const inventory = ['filesystem', 'claude_ai_Slack'].flatMap(server =>
|
||||
Array.from({ length: 20 }, (_, i) => `mcp__${server}__t${i}`),
|
||||
)
|
||||
const sessions = ['a', 'b'].map(sessionId => makeSession({
|
||||
sessionId,
|
||||
inventory,
|
||||
turns: [makeTurn([makeCall({ cacheCreation: 10_000 })])],
|
||||
}))
|
||||
|
||||
const finding = detectMcpToolCoverage([project(sessions)])
|
||||
|
||||
// Each call's 10K cache bucket is shared evenly by two 8K schemas.
|
||||
// Total: 2 * 10K * 1.25 = 25K. The local mutation owns half.
|
||||
expect(finding).toMatchObject({ tokensSaved: 25_000, applyTokensSaved: 12_500 })
|
||||
})
|
||||
|
||||
it('charges only the flagged servers actually loaded in each session', () => {
|
||||
const sessions = ['filesystem', 'claude_ai_Slack'].flatMap(server =>
|
||||
['a', 'b'].map(suffix => makeSession({
|
||||
sessionId: `${server}-${suffix}`,
|
||||
inventory: Array.from({ length: 20 }, (_, i) => `mcp__${server}__t${i}`),
|
||||
turns: [makeTurn([makeCall({ cacheCreation: 50_000 })])],
|
||||
})),
|
||||
)
|
||||
|
||||
const finding = detectMcpToolCoverage([project(sessions)])
|
||||
|
||||
// Four sessions each load one 8K schema. The combined finding must not
|
||||
// charge both schemas to every session merely because both are flagged.
|
||||
expect(finding).toMatchObject({ tokensSaved: 40_000, applyTokensSaved: 20_000 })
|
||||
})
|
||||
|
||||
it('disambiguates a claude.ai connector from a similarly named local server', () => {
|
||||
const sessions: SessionSummary[] = []
|
||||
for (const server of ['claude_ai_Netlify', 'netlify']) {
|
||||
|
|
|
|||
|
|
@ -163,6 +163,109 @@ describe('mcp-remove plan', () => {
|
|||
expect(preview).not.toContain('~80.0K tokens')
|
||||
expect(preview).not.toContain('~$0.160')
|
||||
})
|
||||
|
||||
it('scopes targets and savings to local servers actually present in editable config', async () => {
|
||||
const fx = await makeFixture()
|
||||
await writeFile(join(fx.home, '.claude.json'), JSON.stringify({
|
||||
mcpServers: { filesystem: { command: 'filesystem' } },
|
||||
}, null, 2) + '\n')
|
||||
const finding: WasteFinding = {
|
||||
id: 'mcp-low-coverage',
|
||||
title: '3 MCP servers with low tool coverage',
|
||||
explanation: '',
|
||||
impact: 'medium',
|
||||
tokensSaved: 60_000,
|
||||
applyTokensSaved: 30_000,
|
||||
applyTokensSavedByServer: { filesystem: 10_000, managed: 20_000 },
|
||||
fix: { type: 'command', label: '', text: "claude mcp remove 'filesystem'\nclaude mcp remove 'managed'" },
|
||||
apply: { kind: 'mcp-remove', servers: ['filesystem', 'managed'] },
|
||||
}
|
||||
|
||||
const plans = planFindings([finding], { homeDir: fx.home, cwd: fx.project })
|
||||
const preview = stripAnsi(renderApplyList(plans.filter(p => p.plan), plans.filter(p => !p.plan), 0))
|
||||
|
||||
expect(plans[0]!.plan?.affectedMcpServers).toEqual(['filesystem'])
|
||||
expect(preview).toContain('Removes local MCP server: filesystem')
|
||||
expect(preview).toContain('~10.0K tokens')
|
||||
expect(preview).not.toContain('~30.0K tokens')
|
||||
expect(preview).toContain('skipped managed: not found in editable config')
|
||||
})
|
||||
|
||||
it('suppresses savings for a legacy partial plan without per-server attribution', async () => {
|
||||
const fx = await makeFixture()
|
||||
await writeFile(join(fx.home, '.claude.json'), JSON.stringify({
|
||||
mcpServers: { filesystem: { command: 'filesystem' } },
|
||||
}, null, 2) + '\n')
|
||||
const finding: WasteFinding = {
|
||||
id: 'mcp-low-coverage',
|
||||
title: '2 MCP servers with low tool coverage',
|
||||
explanation: '',
|
||||
impact: 'medium',
|
||||
tokensSaved: 30_000,
|
||||
applyTokensSaved: 30_000,
|
||||
fix: { type: 'command', label: '', text: '' },
|
||||
apply: { kind: 'mcp-remove', servers: ['filesystem', 'managed'] },
|
||||
}
|
||||
|
||||
const plans = planFindings([finding], { homeDir: fx.home, cwd: fx.project })
|
||||
const preview = stripAnsi(renderApplyList(plans.filter(p => p.plan), plans.filter(p => !p.plan), 0))
|
||||
|
||||
expect(plans[0]!.plan?.affectedMcpServers).toEqual(['filesystem'])
|
||||
expect(plans[0]!.plan?.mcpSavingsUncertain).toBe(true)
|
||||
expect(preview).toContain('Savings not estimated')
|
||||
expect(preview).not.toContain('~30.0K tokens')
|
||||
})
|
||||
|
||||
it('deduplicates repeated removal targets before planning and pricing them', async () => {
|
||||
const fx = await makeFixture()
|
||||
await writeFile(join(fx.home, '.claude.json'), JSON.stringify({
|
||||
mcpServers: { filesystem: { command: 'filesystem' } },
|
||||
}, null, 2) + '\n')
|
||||
const finding: WasteFinding = {
|
||||
id: 'mcp-low-coverage',
|
||||
title: '1 MCP server with low tool coverage',
|
||||
explanation: '',
|
||||
impact: 'medium',
|
||||
tokensSaved: 10_000,
|
||||
applyTokensSavedByServer: { filesystem: 10_000 },
|
||||
fix: { type: 'command', label: '', text: '' },
|
||||
apply: { kind: 'mcp-remove', servers: ['filesystem', 'filesystem'] },
|
||||
}
|
||||
|
||||
const plans = planFindings([finding], { homeDir: fx.home, cwd: fx.project })
|
||||
const preview = stripAnsi(renderApplyList(plans.filter(p => p.plan), [], 0))
|
||||
|
||||
expect(plans[0]!.plan?.affectedMcpServers).toEqual(['filesystem'])
|
||||
expect(preview).toContain('~10.0K tokens')
|
||||
expect(preview).not.toContain('~20.0K tokens')
|
||||
})
|
||||
|
||||
it('does not claim savings when another relevant config scope is unreadable', async () => {
|
||||
const fx = await makeFixture()
|
||||
await writeFile(join(fx.home, '.claude.json'), JSON.stringify({
|
||||
mcpServers: { filesystem: { command: 'filesystem' } },
|
||||
}, null, 2) + '\n')
|
||||
await writeFile(join(fx.project, '.mcp.json'), 'not json{{{')
|
||||
const finding: WasteFinding = {
|
||||
id: 'mcp-low-coverage',
|
||||
title: '1 MCP server with low tool coverage',
|
||||
explanation: '',
|
||||
impact: 'medium',
|
||||
tokensSaved: 10_000,
|
||||
applyTokensSavedByServer: { filesystem: 10_000 },
|
||||
fix: { type: 'command', label: '', text: "claude mcp remove 'filesystem'" },
|
||||
apply: { kind: 'mcp-remove', servers: ['filesystem'] },
|
||||
}
|
||||
|
||||
const plans = planFindings([finding], { homeDir: fx.home, cwd: fx.project })
|
||||
const preview = stripAnsi(renderApplyList(plans.filter(p => p.plan), plans.filter(p => !p.plan), 0))
|
||||
|
||||
expect(plans[0]!.plan?.affectedMcpServers).toEqual(['filesystem'])
|
||||
expect(plans[0]!.plan?.mcpSavingsUncertain).toBe(true)
|
||||
expect(preview).toContain('Savings not estimated')
|
||||
expect(preview).toContain('could not parse')
|
||||
expect(preview).not.toContain('~10.0K tokens')
|
||||
})
|
||||
})
|
||||
|
||||
describe('mcp-project-scope plan', () => {
|
||||
|
|
@ -479,6 +582,53 @@ async function threeFindingFixture(): Promise<{ fx: Fixture; findings: WasteFind
|
|||
}
|
||||
|
||||
describe('runOptimizeApply end-to-end', () => {
|
||||
it('prints connector-only manual guidance when there is nothing to apply', async () => {
|
||||
const fx = await makeFixture()
|
||||
const connector: McpServerCoverage = {
|
||||
server: 'claude_ai_Netlify',
|
||||
toolsAvailable: 20,
|
||||
toolsInvoked: 0,
|
||||
unusedTools: Array.from({ length: 20 }, (_, i) => `mcp__claude_ai_Netlify__t${i}`),
|
||||
invocations: 0,
|
||||
loadedSessions: 2,
|
||||
coverageRatio: 0,
|
||||
}
|
||||
const finding = detectMcpToolCoverage([], [connector])!
|
||||
const io = makeIo()
|
||||
|
||||
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings: [finding], yes: true }))
|
||||
|
||||
expect(io.stdout()).toContain('No appliable config-class fixes')
|
||||
expect(io.stdout()).toContain('/mcp')
|
||||
expect(io.stdout()).toContain('claude.ai Netlify')
|
||||
expect(io.stdout()).not.toContain('claude mcp remove')
|
||||
})
|
||||
|
||||
it('names the exact local removal target and preserves connector follow-up in a mixed preview', async () => {
|
||||
const fx = await makeFixture()
|
||||
await writeFile(join(fx.home, '.claude.json'), JSON.stringify({
|
||||
mcpServers: { filesystem: { command: 'filesystem' }, netlify: { command: 'local-netlify' } },
|
||||
}, null, 2) + '\n')
|
||||
const coverage = (server: string): McpServerCoverage => ({
|
||||
server,
|
||||
toolsAvailable: 20,
|
||||
toolsInvoked: 0,
|
||||
unusedTools: Array.from({ length: 20 }, (_, i) => `mcp__${server}__t${i}`),
|
||||
invocations: 0,
|
||||
loadedSessions: 2,
|
||||
coverageRatio: 0,
|
||||
})
|
||||
const finding = detectMcpToolCoverage([], [coverage('filesystem'), coverage('claude_ai_Netlify')])!
|
||||
const io = makeIo()
|
||||
|
||||
await runOptimizeApply([], undefined, applyOpts(fx, io, { findings: [finding], dryRun: true }))
|
||||
|
||||
expect(io.stdout()).toContain('Removes local MCP server: filesystem')
|
||||
expect(io.stdout()).toContain('/mcp')
|
||||
expect(io.stdout()).toContain('claude.ai Netlify')
|
||||
expect(io.stdout()).not.toContain("claude mcp remove 'claude_ai_Netlify'")
|
||||
})
|
||||
|
||||
it('--yes applies every plan and prints journal short ids with the undo hint', async () => {
|
||||
const { fx, findings } = await threeFindingFixture()
|
||||
const io = makeIo()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue