SLOPSHOPPER

Megamaid

megamaid: a review → plan → fix pipeline for code review with configurable agents and authoritative project directives.

guardpromptagents
v0.4.0MITupdated 2026-10-19olioskar/megamaid-claude-plugin
A shopper browsing a rack in a slop shop
README

megamaid

A Claude Code plugin for code review. /megamaid:review finds issues, /megamaid:plan turns each one into a fix instruction, /megamaid:fix applies them, and /megamaid:vacu-suck runs all three in one go.

Reviewers follow eight shipped directives plus your own, and a layered config lets each project override the defaults.

Forked from comb. megamaid adds a hooks module (a load guard and a usage ledger) and requires a Claude Code build with hooks modules, with the module loaded; comb stays for builds without them.

With comb also installed, both plugins' model-invocable skills trigger on the same phrases; install one, or use explicit /megamaid:* commands.

Commands

  • /megamaid:review runs 1–5 reviewer agents over a PR, branch, file list, or spec. A code change gets a severity-ranked report with a verdict. A prose change (spec, design doc) gets a shorter report with labelled findings.
  • /megamaid:plan writes one self-contained fix instruction per finding; for a prose report, one revise-<spec>.md.
  • /megamaid:fix applies the instructions: an implementer and a reviewer per item, items that touch different files in parallel, one commit per passing item. Only you can start it; see "Let Claude start fixes" below to change that.
  • /megamaid:vacu-suck runs review, plan, and fix without pauses. On a prose change it stops after review.
  • /megamaid:patterns scans the codebase and writes a PATTERNS manifest: the project's actual conventions, with file:line references. Review, plan, and fix give agents the relevant excerpt as a baseline. --shave shrinks an existing manifest without changing what it says.
  • /megamaid:configure changes the config from a plain-language request.
  • /megamaid:help prints an overview. /megamaid:help <command> shows one command in detail.

Review, plan, fix, vacu-suck, and patterns take a free-form focus brief that steers which agents run (review and vacu-suck) and what every dispatched agent prioritizes:

/megamaid:review look for spec/plan misalignment
/megamaid:vacu-suck ensure simplicity, scope discipline, and TDD coverage

Requirements

  • Claude Code with hooks modules (tested on 2.1.303, the version in vendor/claude-code-types/), with megamaid's hooks module loaded. A command that replies MEGAMAID-MODULE-NOT-LOADED means it did not load; /megamaid:help lists the causes.
  • python3; the scripts are stdlib-only. Every command but help starts by running one and stops if it can't.
  • git. gh is also needed to review a PR by number.

Install

claude --plugin-dir /path/to/megamaid-claude-plugin

Migrating

Coming from comb? Before your first megamaid run, and only while docs/megamaid/ does not exist yet, move comb's output folder with git mv docs/combs docs/megamaid (plain mv if it is untracked); this also puts the PATTERNS manifest where megamaid reads it. Then run /megamaid:configure to migrate comb's config, and point any paths.* it copied from docs/combs/ at docs/megamaid/. If you don't move the folder, /megamaid:configure offers to move or copy the manifest instead. An empty {} megamaid.config.json silences the config notice.

Quick start

In a git repo with changes on a branch, run /megamaid:review. The report lands in docs/megamaid/reviews/, with the run's token ledger (…-usage.md) beside it (docs/features/usage-ledger.md). Run /megamaid:plan on it, then /megamaid:fix. Or run /megamaid:vacu-suck to do all three.

Configuration

Three layers are deep-merged, later layers winning: config/defaults.json in the plugin, then ~/.claude/megamaid.config.json (global), then <project-root>/.claude/megamaid.config.json (project).

/megamaid:configure makes changes for you, for example "disable test-auditor" or "use sonnet for the fix implementer". It shows a diff and, after you confirm, writes the change to the global or project file.

config/defaults.json lists every key with its default. Three kinds of setting are absent by default: effort.<lane>, and the per-role agents.<role>.model and agents.<role>.effort. Every key: docs/api/config.md.

Models and effort

{ "models": { "fix": { "implementer_standard": "sonnet" } },
  "effort": { "review": "medium" },
  "agents": { "simplifier": { "model": "haiku" } } }
  • Models can be sonnet, opus, haiku, or fable. The agent dispatch rejects a full model ID.
  • Where to save: the planner is the senior of the pair. A good instruction lets a cheaper implementer apply it, so lower models.fix.implementer_standard or models.fix.implementer_trivial and keep models.plan strong.
  • Effort can be low, medium, high, xhigh, or max. When it is unset, agents use your session's effort. On one fixture (experiments/README.md) medium matched high for about 8% less.
  • Per-role settings beat the lane setting.

Turn off per-item commits

{ "fix": { "commit_per_item": false } }

Let Claude start fixes

{ "fix": { "model_invocation": true } }

/megamaid:fix is user-only by default because it edits code and commits. With this flag, asking in your own words ("apply the fixes") runs the same workflow, with the same questions and commits. Without the flag, such a request gets a short reply naming /megamaid:fix and the flag.

Use your own writer or planner

{ "agents": { "implementer": { "subagent_type": "your-org:implementer" }, "planner": { "subagent_type": "your-org:planner" } } }

The default writer, megamaid:implementer, edits only the files the instruction names, never commits, and reports every file it touched. The default planner, megamaid:planner, writes one instruction file per finding and never edits source. A writer or planner from outside this plugin gets an explicit instruction that the directives are authoritative, the same boundaries, and the same checks after it returns.

Add or swap reviewers

{ "agents": { "react-expert": { "subagent_type": "react-expert", "when_to_use": "Diff includes React components, hooks, or JSX." },
              "simplifier": { "subagent_type": "pr-review-toolkit:code-simplifier" },
              "test-auditor": null } }

A new role needs subagent_type and when_to_use. Overriding a shipped role can set just the fields you change. null removes a role.

Use your own directives

{ "directives": { "user_path": "docs/our-rules" } }

Directives

The plugin ships eight directives in directives/:

FileRule
simplicity.mdno overengineering or speculative fixes
modularity.mdsingle responsibility, clear interfaces
reusability.mdno copy-paste, no premature abstraction
maintainability.mdnaming, comments, no dead code
quality.mdcorrectness, error handling
consistency.mdfollow existing patterns and the spec
scope-discipline.mdstay inside the requested change
testing.mdreal tests that cover changed behavior

Your directives in directives.user_path (default docs/directives/) apply on top. Both sets are authoritative, and findings cite them as <file>.md §N.N. Agents get the files by path, not pasted into their prompt. To use only your own directives, set "directives": { "include_plugin_defaults": false }.

Agents

AgentRole
megamaid:code-reviewerbugs, logic, contracts, security
megamaid:simplifieroverengineering, dead code, duplication
megamaid:silent-failure-hunterswallowed errors, hidden fallbacks
megamaid:test-auditorcoverage and test quality
megamaid:consistency-auditorfit with existing patterns and with the spec or plan
megamaid:plannerwrites the instructions for /megamaid:plan and for the issues /megamaid:fix discovers
megamaid:implementerthe writer for /megamaid:fix
megamaid:pattern-scannerused only by /megamaid:patterns
megamaid:pattern-shaverused only by /megamaid:patterns --shave

The five reviewers are read-only: Write, Edit, and NotebookEdit are withheld in their agent files; Bash stays for git. A clean diff should come back with few or no findings. simplifier, silent-failure-hunter, and consistency-auditor re-check their findings in a final step; code-reviewer and test-auditor have no such step.

Before a finding enters the report, /megamaid:review opens every cited line and recomputes every count. Each finding carries a Verified: line stating what was checked and what was not. /megamaid:plan re-checks anything marked unchecked.

How it works

The skills in skills/ are the contract; bundled stdlib scripts do the bookkeeping (config merge, model resolution, directive matching, report naming, batching), and a hooks module gates the commands and writes a usage ledger per run. Per-command behavior is in docs/features/; the design is in docs/architecture/overview.md.

Development

The process is in docs/process/dev-flow.md. Two free gates, claude plugin validate . and bash scripts/check-contract.sh, run on every commit and in CI (pushes to main, every pull request, manual dispatch). The remaining gates are in docs/architecture/gates.md; the eval suite (nine behavioral cases, about 5 USD per pass, manual dispatch in CI) in evals/README.md. Docs: docs/INDEX.md lists every reference set.

Status

v0.4.0. See CHANGELOG.md; earlier history is linked from its 0.1.0 entry.

License

MIT

Source 10 files
hooks/register.ts 15 lines
1import type { Register } from 'claude-code'
2import { registerSkillPrompt } from './skill-prompt'
3import { registerReadNote } from './read-note'
4import { registerAgents } from './agents'
5import { registerUsage } from './usage'
6import { registerSession } from './session'
7
8export const register: Register = on => {
9  registerSkillPrompt(on)
10  registerReadNote(on)
11  registerAgents(on)
12  registerUsage(on)
13  registerSession(on)
14}
15
hooks/skill-prompt.ts 28 lines
1import { update } from 'claude-code'
2import type { On } from 'claude-code'
3import { stripStopLine } from './stop-line'
4import { isRunSkill, startRun } from './run'
5
6const RUN = { plugin: 'megamaid', key: 'run' } as const
7
8// One registration on purpose: if a second skill.prompt hook of this plugin threw, the strip would
9// be lost and a loaded module would read as "not loaded". Run start sits in try; the .catch
10// replays next (nothing beneath runs twice) and strips, so an overrun cannot cost the strip either.
11export function registerSkillPrompt(on: On): void {
12  on('skill.prompt', { skill: /^megamaid:/ }, async ($, e, next) => {
13    const text = stripStopLine((await next(e)).text)
14    try {
15      if (isRunSkill(e.skill)) {
16        // The session's cost at run start; a host with no cost ledger (or the test kit) leaves it null.
17        const usage = await $.session.usage().catch(() => undefined)
18        const run = startRun(crypto.randomUUID(), e.skill, await $.clock.now(), usage?.cost?.usd ?? null)
19        await update($, RUN, () => run)
20        $.ui.log(`run ${e.skill} started (${run.id})`, { to: 'debug' })
21      }
22    } catch (err) {
23      $.ui.log(`run detection failed: ${err instanceof Error ? err.message : String(err)}`, { to: 'debug' })
24    }
25    return { text }
26  }).catch(async ($, e, next) => ({ text: stripStopLine((await next(e)).text) }))
27}
28
hooks/read-note.ts 29 lines
1import type { On } from 'claude-code'
2import { SKIP_NOTE, STOP_SKILLS } from './stop-line'
3
4// vacu-suck and fix-auto Read sub-skill files that open with the stop line. While the module is
5// loaded, their main-loop Read gets a note that the line does not apply; with no module there is
6// no note and the run stops. The hook refuses nothing: a fault means no note, which stops the run.
7export function registerReadNote(on: On): void {
8  on('tool.call', { tool: 'Read' }, async ($, e, next) => {
9    const r = await next(e)
10    if (e.tool !== 'Read' || e.agentId !== undefined) return r
11    if (r.deny !== undefined || r.isError === true) return r
12    const path = String(e.file_path)
13    if (!/[\\/]SKILL\.md$/.test(path)) return r
14    const root = (await $.fs.stat($.plugin.root, { resolve: true })).realPath
15    const real = (await $.fs.stat(path, { resolve: true })).realPath
16    if (root === undefined || real === undefined) return r
17    const name = skillName(root, real)
18    if (name === null || !STOP_SKILLS.includes(name)) return r
19    return { ...r, context: [...(r.context ?? []), SKIP_NOTE] }
20  }).catch(($, e, next) => next(e))
21}
22
23// The skill a resolved path names when it is <root>/skills/<name>/SKILL.md, else null.
24function skillName(root: string, real: string): string | null {
25  if (!real.startsWith(root)) return null
26  const m = /^[\\/]skills[\\/]([^\\/]+)[\\/]SKILL\.md$/.exec(real.slice(root.length))
27  return m?.[1] ?? null
28}
29
hooks/agents.ts 53 lines
1import { update } from 'claude-code'
2import type { On } from 'claude-code'
3import { addAgent, parseBrief, startRun } from './run'
4
5const RUN = { plugin: 'megamaid', key: 'run' } as const
6
7// Records megamaid's own main-loop dispatches: a prompt that names a run brief, or (the briefless
8// scanner and shaver) a megamaid-provided agent while the stored run is patterns. A spawn nested in
9// a recorded agent is recorded under the parent's lane, role and stem. The stored run is the last
10// run, not an active one, so nothing else is attributed to it. The hook refuses nothing.
11export function registerAgents(on: On): void {
12  on('agent.spawn', async ($, e, next) => {
13    const r = await next(e)
14    if (r.agentId === undefined) return r
15    const agentId = r.agentId
16    const parentId = e.parentAgentId
17    if (parentId !== undefined) {
18      const { value: stored } = await $.state.get(RUN)
19      const parent = stored?.agents[parentId]
20      if (parent === undefined) return r
21      await update($, RUN, run => {
22        const p = run?.agents[parentId]
23        if (run === null || run === undefined || p === undefined) return run ?? null
24        return addAgent(run, agentId, {
25          subagentType: e.subagentType, provider: e.provider.plugin,
26          role: p.role, lane: p.lane, runStem: p.runStem, parent: parentId, usage: null,
27        })
28      })
29      $.ui.log(`${parent.lane ?? '-'}/${parent.role} nested spawn ${e.subagentType} (${agentId}) under ${parentId}`, { to: 'debug' })
30      return r
31    }
32    const brief = parseBrief(e.prompt)
33    if (brief === null) {
34      if (e.provider.plugin.split('@')[0] !== 'megamaid') return r
35      const { value: stored } = await $.state.get(RUN)
36      if (stored?.skill !== 'megamaid:patterns') return r
37    }
38    const now = await $.clock.now()
39    const fresh = crypto.randomUUID()
40    await update($, RUN, run => addAgent(run ?? startRun(fresh, 'none', now), agentId, {
41      subagentType: e.subagentType,
42      provider: e.provider.plugin,
43      role: brief?.role ?? 'unknown',
44      lane: brief?.lane ?? null,
45      runStem: brief?.runStem ?? null,
46      parent: null,
47      usage: null,
48    }))
49    $.ui.log(`${brief?.lane ?? '-'}/${brief?.role ?? 'unknown'} spawned as ${e.subagentType} (${agentId})`, { to: 'debug' })
50    return r
51  }).catch(($, e, next) => next(e))
52}
53
hooks/usage.ts 83 lines
1import { update } from 'claude-code'
2import type { CoreEngineInterface, HookFailure, On } from 'claude-code'
3import type { MegamaidRun } from '../types'
4import { REPORT_SKILLS, ZERO, addUsage, ledgerPath, renderLedger, reportName, usageKey } from './ledger'
5
6const RUN = { plugin: 'megamaid', key: 'run' } as const
7
8const GITIGNORE = '.megamaid/.gitignore'
9
10// Records what each turn of a stored run cost: the main loop's to the orchestrator, a recorded
11// agent's to that agent; every other turn counts nowhere. A main-loop turn counts only while one is
12// owed: the run's first always is, and a recorded spawn, a recorded agent's turn or the report
13// Write owes the next one; so chat after the run's last answer adds nothing. Finds the review
14// report a review or sweep writes so the ledger can sit beside it. Neither hook refuses or
15// rewrites anything: a fault means a missing or stale ledger.
16export function registerUsage(on: On): void {
17  on('turn.complete', async ($, e, next) => {
18    const r = await next(e)
19    const usage = e.usage
20    if (usage === undefined) return r
21    const { value: stored } = await $.state.get(RUN)
22    if (stored === null || stored === undefined) return r
23    // A run stored before the ledger (a 0.3.x run across a hot reload) has no usage; it is left uncounted.
24    if (stored.usage === undefined) return r
25    const agentId = e.agentId
26    if (agentId !== undefined && stored.agents[agentId] === undefined) return r
27    if (agentId === undefined && stored.owed === false) return r
28    const now = await $.clock.now()
29    const run = await update($, RUN, run => {
30      if (run === null || run === undefined) return null
31      if (agentId === undefined) return run.owed === false ? run : { ...run, usage: addUsage(run.usage, usage), lastTurnAt: now, owed: false }
32      const agent = run.agents[agentId]
33      if (agent === undefined) return run
34      return { ...run, agents: { ...run.agents, [agentId]: { ...agent, usage: addUsage(agent.usage ?? ZERO, usage) } }, lastTurnAt: now, owed: true }
35    })
36    if (run === null) return r
37    const agent = agentId === undefined ? undefined : run.agents[agentId]
38    const key = agentId === undefined ? 'orchestrator' : agent === undefined ? agentId : usageKey(agent)
39    const turns = agentId === undefined ? run.usage.turns : agent?.usage?.turns ?? 0
40    const input = usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
41    $.ui.log(`usage ${key} +${input}/${usage.output_tokens} (${turns})`, { to: 'debug' })
42    await writeLedger($, run)
43    return r
44  }).catch(($, e, next) => { failed($, next.error); return next(e) })
45
46  // The main loop's first Write of a file named like megamaid.py report-name's output, in a review
47  // or sweep run, names the report; a sweep's later rounds leave it.
48  on('tool.call', { tool: 'Write' }, async ($, e, next) => {
49    const r = await next(e)
50    if (e.tool !== 'Write' || e.agentId !== undefined) return r
51    if (r.deny !== undefined || r.isError === true) return r
52    const path = String(e.file_path)
53    if (!reportName(path)) return r
54    const { value: stored } = await $.state.get(RUN)
55    if (stored === null || stored === undefined || !REPORT_SKILLS.includes(stored.skill) || stored.report !== null) return r
56    const run = await update($, RUN, run => run === null || run === undefined ? null : { ...run, report: run.report ?? path, owed: true })
57    if (run !== null) await writeLedger($, run)
58    return r
59  }).catch(($, e, next) => { failed($, next.error); return next(e) })
60}
61
62// A failed hook is replayed beneath and named in the debug log.
63function failed($: Pick<CoreEngineInterface, 'ui'>, error: HookFailure): void {
64  $.ui.log(`usage hook failed: ${error.message ?? error.kind}`, { to: 'debug' })
65}
66
67type LedgerDollar = Pick<CoreEngineInterface, 'fs' | 'session' | 'ui'>
68
69// Writes the run's ledger where ledgerPath puts it; nothing when it has no place yet. The
70// self-ignoring .megamaid/.gitignore goes first when the ledger lives under .megamaid/.
71export async function writeLedger($: LedgerDollar, run: MegamaidRun): Promise<void> {
72  const path = ledgerPath(run)
73  if (path === null) return
74  try {
75    if (path.startsWith('.megamaid/') && !(await $.fs.exists(GITIGNORE))) await $.fs.write(GITIGNORE, '*\n')
76    const cost = await $.session.usage().then(u => u.cost?.usd ?? null, () => null)
77    await $.fs.write(path, renderLedger(run, cost))
78    $.ui.log(`ledger ${path}`, { to: 'debug' })
79  } catch (err) {
80    $.ui.log(`ledger failed: ${err instanceof Error ? err.message : String(err)}`, { to: 'debug' })
81  }
82}
83
hooks/session.ts 21 lines
1import { update } from 'claude-code'
2import type { On } from 'claude-code'
3
4const RUN = { plugin: 'megamaid', key: 'run' } as const
5
6export function registerSession(on: On): void {
7  // smoke.sh reads this line to know the module loaded.
8  on('session.start', async ($, e, next) => {
9    const { version } = await $.session.version()
10    $.ui.log(`module loaded (Claude Code ${version})`, { to: 'debug' })
11    return next(e)
12  })
13  // /clear ends the conversation too; the next skill starts a fresh run. next first: the chain
14  // shares one time limit, so the write spends what is left after the other hooks.
15  on('session.end', async ($, e, next) => {
16    const r = await next(e)
17    await update($, RUN, () => null)
18    return r
19  }).catch(($, e, next) => next(e))
20}
21
hooks/stop-line.ts 12 lines
1// The stop line is copied into every skill but help (check-contract §11 keeps the copies equal to
2// STOP_LINE). The module strips it; with no module the model reads it and stops.
3export const STOP_LINE = "STOP. megamaid's hooks module is not loaded in this session, so everything below this line is disabled: do not follow it, run no tools, and reply only with `MEGAMAID-MODULE-NOT-LOADED: run /megamaid:help`."
4export const STOP_TOKEN = 'MEGAMAID-MODULE-NOT-LOADED'
5export const TOKEN_LINE = 'MEGAMAID-MODULE-NOT-LOADED: run /megamaid:help'
6export const SKIP_NOTE = "megamaid's hooks module is loaded; the STOP line at the top of this file does not apply."
7export const STOP_SKILLS: readonly string[] = ['configure', 'fix', 'fix-auto', 'patterns', 'plan', 'review', 'vacu-suck']
8
9export function stripStopLine(text: string): string {
10  return text.split('\n').filter(line => line.replace(/\r$/, '') !== STOP_LINE).join('\n')
11}
12
hooks/run.ts 35 lines
1import type { MegamaidAgent, MegamaidRun } from '../types'
2import { ZERO } from './ledger'
3
4// Pure helpers for run detection. No $ here, and no state ref: each file that writes state
5// declares its own RUN const (validate reads a ref only as a literal const of that file).
6
7export function isRunSkill(name: string): boolean {
8  return name.startsWith('megamaid:') && name !== 'megamaid:help'
9}
10
11export function startRun(id: string, skill: string, startedAt: number, costAtStart: number | null = null): MegamaidRun {
12  return { id, skill, startedAt, agents: {}, usage: ZERO, report: null, costAtStart, lastTurnAt: null, owed: true }
13}
14
15// A run brief: .megamaid/excerpts/<stem>.<lane>.<role>.brief.md, written by megamaid.py brief.
16// <stem> is <skill>-<digits>-<hex4>; <lane> is the brief's skill (review, plan, fix); <role> is a
17// config key, unrestricted, so it is whatever stands between <lane>. and .brief.md.
18const BRIEF = /\.megamaid[\\/]excerpts[\\/]([a-z][a-z-]*-[0-9]+-[0-9a-f]{4})\.([a-z][a-z-]*)\.([^\s\\/]+?)\.brief\.md/
19
20export type Brief = { runStem: string; lane: string; role: string }
21
22export function parseBrief(prompt: string): Brief | null {
23  const m = BRIEF.exec(prompt)
24  if (m === null) return null
25  const [, runStem, lane, role] = m
26  if (runStem === undefined || lane === undefined || role === undefined) return null
27  return { runStem, lane, role }
28}
29
30// seq is the spawn order within the run: Object.values(run.agents) would put an all-digit id first.
31// A recorded spawn is run activity: the next main-loop turn is owed.
32export function addAgent(run: MegamaidRun, agentId: string, agent: Omit<MegamaidAgent, 'seq'>): MegamaidRun {
33  return { ...run, agents: { ...run.agents, [agentId]: { ...agent, seq: Object.keys(run.agents).length } }, owed: true }
34}
35
hooks/ledger.ts 103 lines
1import type { TurnUsage } from 'claude-code'
2import type { MegamaidAgent, MegamaidRun, MegamaidUsage } from '../types'
3
4// Pure helpers for the usage ledger. No $ here.
5
6export const ZERO: MegamaidUsage = { turns: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, model: null }
7
8// The runs whose ledger sits beside the review report they write.
9export const REPORT_SKILLS: readonly string[] = ['megamaid:review', 'megamaid:vacu-suck']
10
11// megamaid.py report-name's shape, repeated here in a second language: <pr-N|branch-…>-round<N>-report.md.
12// check-contract keeps the two equal.
13export const REPORT_NAME = /^(pr-[0-9]+|branch-.+)-round[0-9]+-report\.md$/
14
15export function addUsage(u: MegamaidUsage, t: TurnUsage): MegamaidUsage {
16  return {
17    turns: u.turns + 1,
18    input: u.input + t.input_tokens,
19    cacheRead: u.cacheRead + t.cache_read_input_tokens,
20    cacheWrite: u.cacheWrite + t.cache_creation_input_tokens,
21    output: u.output + t.output_tokens,
22    model: t.model,
23  }
24}
25
26// The ledger row an agent is summed into: <lane>/<role> for a briefed dispatch, its agent type otherwise.
27export function usageKey(agent: MegamaidAgent): string {
28  return agent.lane === null ? agent.subagentType : `${agent.lane}/${agent.role}`
29}
30
31export function reportName(path: string): boolean {
32  const base = path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1)
33  return REPORT_NAME.test(base)
34}
35
36// Where a run's ledger goes: beside the report for a report run (null until it has one), else
37// .megamaid/usage/<skill>-<startedAt>.md, relative to the working directory.
38export function ledgerPath(run: MegamaidRun): string | null {
39  if (REPORT_SKILLS.includes(run.skill)) {
40    if (run.report === null) return null
41    return run.report.replace(/-report\.md$/, '-usage.md')
42  }
43  return `.megamaid/usage/${run.skill.replace(/^megamaid:/, '')}-${run.startedAt}.md`
44}
45
46type Row = { key: string; agents: number; usage: MegamaidUsage; models: string[] }
47
48function sum(a: MegamaidUsage, b: MegamaidUsage): MegamaidUsage {
49  return {
50    turns: a.turns + b.turns, input: a.input + b.input, cacheRead: a.cacheRead + b.cacheRead,
51    cacheWrite: a.cacheWrite + b.cacheWrite, output: a.output + b.output, model: null,
52  }
53}
54
55function share(part: number, total: number): string {
56  return `${total === 0 ? 0 : Math.round((100 * part) / total)}%`
57}
58
59function inputOf(u: MegamaidUsage): number {
60  return u.input + u.cacheRead + u.cacheWrite
61}
62
63function iso(ms: number | null): string {
64  return ms === null ? 'none yet' : new Date(ms).toISOString()
65}
66
67export function renderLedger(run: MegamaidRun, costNow: number | null): string {
68  const rows: Row[] = [{ key: 'orchestrator', agents: 0, usage: run.usage, models: run.usage.model === null ? [] : [run.usage.model] }]
69  const byKey = new Map<string, Row>()
70  for (const agent of Object.values(run.agents).sort((a, b) => a.seq - b.seq)) {
71    const key = usageKey(agent)
72    let row = byKey.get(key)
73    if (row === undefined) { row = { key, agents: 0, usage: ZERO, models: [] }; byKey.set(key, row); rows.push(row) }
74    row.agents += 1
75    if (agent.usage !== null) {
76      row.usage = sum(row.usage, agent.usage)
77      if (agent.usage.model !== null && !row.models.includes(agent.usage.model)) row.models.push(agent.usage.model)
78    }
79  }
80  const total = rows.reduce<Row>(
81    (acc, r) => ({ key: 'total', agents: acc.agents + r.agents, usage: sum(acc.usage, r.usage), models: [] }),
82    { key: 'total', agents: 0, usage: ZERO, models: [] })
83  const cost = run.costAtStart === null || costNow === null
84    ? 'Cost: unavailable (no session cost at run start or now)'
85    : `Cost: ${(costNow - run.costAtStart).toFixed(2)} USD (session spend from run start to the last counted turn; includes anything else in the session meanwhile)`
86  const line = (r: Row, agents: string, models: string) =>
87    `| ${r.key} | ${agents} | ${r.usage.turns} | ${r.usage.input} | ${r.usage.cacheRead} | ${r.usage.cacheWrite} | ${r.usage.output} | ${models} |`
88  return [
89    `# megamaid usage: ${run.skill}`,
90    '',
91    `Run: started ${iso(run.startedAt)}, last turn ${iso(run.lastTurnAt)} (UTC)`,
92    cost,
93    '',
94    '| Lane/role | Agents | Turns | Input | Cache read | Cache write | Output | Model |',
95    '|---|---|---|---|---|---|---|---|',
96    ...rows.map((r, i) => line(r, i === 0 ? '-' : String(r.agents), r.models.length === 0 ? '-' : r.models.join(', '))),
97    line(total, String(total.agents), ''),
98    '',
99    `Orchestrator share: ${share(inputOf(run.usage), inputOf(total.usage))} of input tokens, ${share(run.usage.output, total.usage.output)} of output tokens.`,
100    '',
101  ].join('\n')
102}
103
types/index.d.ts 9 lines
1export type MegamaidUsage = { turns: number; input: number; cacheRead: number; cacheWrite: number; output: number; model: string | null }
2export type MegamaidAgent = { subagentType: string; provider: string; role: string; lane: string | null; runStem: string | null; parent: string | null; seq: number; usage: MegamaidUsage | null }
3export type MegamaidRun = { id: string; skill: string; startedAt: number; agents: Record<string, MegamaidAgent>; usage: MegamaidUsage; report: string | null; costAtStart: number | null; lastTurnAt: number | null; owed?: boolean }
4declare module 'claude-code' {
5  interface PluginState {
6    megamaid: { run: MegamaidRun | null }
7  }
8}
9