SLOPSHOPPER

Topia

71-skill Topia Nexus for Claude Code — discipline rails via native hooks (readiness/guardian/completion-gate/quarantine). 315 synapses + 49 pulses, Maestro…

panebandguardcommandtoaststatus
★ 1v3.10.1MITupdated 2026-10-25linenoize/topia
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · topia
│ ┃ Topia mods ✕ › fix the failing auth test and add an audit log call │ ┃ Save for [ this project (app) ] [ all my pro │ ┃ [ on ] Git band source-gitBand ⏺ Read(src/auth.ts) │ ┃ [ on ] Standing orders source-standingOrder ⎿ Read 6 lines │ ┃ [ off ] Remote hosts source-remoteHosts ⏺ Update(src/auth.ts) │ ┃ [ on ] Quiet reports source-quietReports ⎿ Added 2 lines, removed 1 line │ ┃ [ on ] Model preset source-modelPreset ⏺ Bash(bun test) │ ┃ [ off ] Prompt routing source-promptRouting ⎿ 3 pass, 1 fail │ ┃ Status line: usage-ctx usage-cache usage-usd │ ┃ Clear this project's choices Stop asking in ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ⓘ Hover or Tab to a value to see what it │ ┃ means. ✻ Worked for 42s · done 4:20 PM │ ┃ /mods │ ┃ [git|orders|hosts|quiet|model|routing|all] › /mods │ ┃ [on|off|reset] [--project|--user] · /mods ⎿ topia: Topia mods: git · orders · quiet · model · routing on, ho │ ┃ forget-project │ git-branch git-changed git-upstream [ Commit ] [ Commit & push ] Hide ⓘ Hover or Tab to a value to see what it means. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ topia: ctx 49% · cache 93% · $0.42 · 5h 31%

Draws

Band
git-branch git-changed git-upstream [ Commit ] [ Commit & push ] Hide ⓘ Hover or Tab to a value to see what it means.
Pane · Topia mods
Save for [ this project (app) ] [ all my projects ] [ on ] Git band source-gitBand [ on ] Standing orders source-standingOrders [ off ] Remote hosts source-remoteHosts [ on ] Quiet reports source-quietReports [ on ] Model preset source-modelPreset [ off ] Prompt routing source-promptRouting Status line: usage-ctx usage-cache usage-usd usage-5h Clear this project's choices Stop asking in new projects No ⓘ Hover or Tab to a value to see what it means. /mods [git|orders|hosts|quiet|model|routing|all] [on|off|reset] [--project|--user] · /mods forget-project
Pane · Standing orders
Added to the system prompt for this project. Press to toggle. [ off ] Fan out independent work to parallel subagents [ off ] End tasks with a skipped / deferred ledger [ off ] Hand-offs are one logged script with yes/no confirms [ off ] Commit and push when a task is done
Pane · Topia activity (hidden from the model)
Kept out of context this session: 0.0k chars (~0 tokens) 0 session reports · 0 guardian advisories · 0 install/migration banners ctx 49%: How full the model's context window is. cache 93%: The share of the last turn's input read from the prompt cache: cheaper and faster. $0.42: The estimated cost of this session so far. 5h 31%: How much of your five-hour usage limit is used. No Topia session report yet this session.
Pane · topia-remote-hosts
No hosts yet. They are learned from ssh commands that succeed.
README

<img src="assets/banner.svg" alt="Topia — discipline rails for AI coding agents" width="100%">

<strong>Topia — internal skill toolkit for AI coding assistants.</strong><br> 71 skills · 315 synapses · 49 pulses · 10 extension packs · optional persistent memory via agora-code MCP

<strong>Claude Code</strong> (native) · <strong>Cursor</strong> · <strong>Antigravity</strong> · <strong>Codex</strong> · <strong>OpenCode</strong> · <strong>OpenClaw</strong>


What Topia is

AI coding agents are smart but undisciplined. They skip steps, forget context across sessions, and ship code that "looks done." Topia gives them workflow rails the model can't skip:

  • Plan before code — idea elicits requirements, plan writes phase files, adversary red-teams the plan, all before a line of code.
  • Tests before commits — test writes failing tests first (red), fix implements until green. TDD enforced, not suggested.
  • Hooks block bad work — guardian (secrets, OWASP), readiness (logic, regressions), completion-gate (validates agent claims have evidence). Auto-fire on tool use.
  • Memory survives sessions — journal persists ADRs to .topia/, optional agora-code MCP adds SQLite-backed semantic recall across sessions.

One source of truth (skills/) compiles to six IDE rule formats — switch IDEs without rewriting your workflow rules.


Install (Claude Code)

Full guide: docs/INSTALL.md. Teams: see Team policy below.

Step 1 — Install the plugin (in chat, no terminal)

/plugin marketplace add linenoize/topia
/plugin install topia@linenoize

Restart Claude Code if /topia:build does not appear.

Marketplace pathWorks?
linenoize/topia (recommended)✓
Git URL to the repo✓
Direct URL to marketplace.json✓ (v3.1.2+)
Local clone path✓

Plugin id is lowercase topia. If install fails, run /plugin marketplace update linenoize first.

After Step 1 you have: all /topia:* skills, plugin hooks (session-start, secrets-scan, quarantine, …), and file-based .topia/ memory — but not machine-wide dispatch hooks, team org.md policy, or agora-code MCP until Step 2.

Step 2 — Finalize (in chat, recommended)

/topia finalize

Run this once per machine (and again when you want to change hooks or org policy). It enables:

What finalize addsWhy it matters
Dispatch hooks (readiness, guardian, completion-gate, dependency-doctor)Auto-fire on edits and shell commands in every repo, even when the plugin is not loaded
Team org policy (interview → .topia/org/org.md)guardian and readiness enforce your review, security, and deploy rules — not the template
agora-code MCP (optional)Cross-session semantic memory
Project .gitignore (optional)Keeps .topia/ session state out of git (except org/)

If you skip Step 2: skills still work when you invoke them; discipline gates only run when you remember to call them or when plugin hooks fire in that session. Cross-repo consistency and team policy injection are the main gaps.

Details: docs/INSTALL-CLAUDE-CODE.md · commands/finalize.md

Per project (each repo you work in)

Run in that project's Claude Code session:

StepCommandWhat you get
1/topia onboardCLAUDE.md + .topia/ context so every session starts with codebase knowledge
2/topia org-configTeam policy in .topia/org/org.md (also offered during finalize)
3/topia doctorVerify install and nexus health

Teams: commit .topia/org/ to git so every teammate and agent shares the same gates. See docs/ORG-CONFIG.md.

Team policy (org.md)

.topia/org/org.md is where your team defines roles, reviewers, security SLAs, deploy windows, and governance level. Topia compiles it into guardian and readiness hooks — so "we require two reviewers on security files" becomes an actual gate, not a wiki page.

  • Set up in chat: /topia org-config (structured interview) or during /topia finalize
  • Edit later: change org.md, then refresh hooks (/topia finalize or topia setup --global)

Other IDEs (Cursor, Codex, Windsurf, …)

The Claude plugin does not compile Cursor/Codex rules. One-time terminal compile from your project root:

node "<path-to-topia>/compiler/bin/topia.js" init --platform cursor

→ docs/INSTALL-NON-CLAUDE.md (secondary path; Claude install above is primary)

Contributors / terminal install

git clone https://github.com/linenoize/topia.git
cd topia && npm install
node compiler/bin/topia.js install

Optional stable location: ~/.claude/skills/topia. topia install registers the plugin, wires hooks, installs agora-code MCP (if Python 3.10+), and runs doctor. Restart Claude Code after install.

node compiler/bin/topia.js install --dry-run        # preview every step
node compiler/bin/topia.js install --here           # hooks per-project instead of global
node compiler/bin/topia.js install --preset strict  # blocking gates (default: gentle)
node compiler/bin/topia.js install --skip-agora     # skip Python MCP
node compiler/bin/topia.js install --yes            # non-interactive (CI-friendly)

Verify (terminal)

From a Topia clone or plugin cache path:

node compiler/bin/topia.js doctor
# ✓ 71 skills, 315 synapses, 49 pulses — nexus is healthy

Claude-only users can use /topia doctor in chat instead.

About agora-code MCP

Topia ships a vendored copy of agora-code at mcp-servers/agora-code/. Four skills (journal, build, idea, neural-memory) detect it automatically. Without it, skills fall back to file-based .topia/ persistence.

Integration: docs/mcp-integrations/agora-code.md. Do NOT run agora-code install-hooks --claude-code — Topia's hooks are canonical.

Coming from rune-kit?

topia install handles migration. Manual path:

node compiler/bin/topia.js migrate-from-rune --dry-run
node compiler/bin/topia.js migrate-from-rune

See docs/migration/from-rune.md.


Use

Every skill is invoked as /topia <name>. The router picks the right skill from a natural description of what you want done.

/topia onboard                # generate CLAUDE.md + .topia/ context for a new project
/topia build "add JWT auth"   # implement a feature (full TDD cycle)
/topia debug "login 401s"     # root-cause an issue
/topia rescue                 # refactor legacy code safely
/topia audit                  # 8-dimension project health check
/topia sentinel               # security scan before commit
/topia incident "503s"        # production incident response
/topia retro                  # engineering retrospective

The 8-step build flow (route → recall → plan → test → implement → gate → verify → persist+commit) is documented on the landing page. Concrete scenarios — "I just inherited this codebase," "production is down," "I want to steal a pattern from a GitHub repo" — live in the Scenarios section.


Skill catalog

Core development & workflow

SkillPurpose
buildL1 orchestrator — full TDD cycle (Understand → Plan → Test → Implement → Verify → Commit). Default route for most code tasks.
rescueL1 orchestrator — multi-session legacy refactor with safety nets.
scaffoldL1 orchestrator — bootstrap a new project from a description.
teamL1 orchestrator — decompose into parallel workstreams with worktree isolation.
launchL1 orchestrator — deploy + verify + announce.
fixApply code changes from diagnosis or review findings.
debugRoot-cause analysis; hands off to fix.
testTDD test writer — red first, green after.
scoutFast read-only codebase scanner.
verificationRun lint + type-check + tests + build.
dbMigrations, rollbacks, query validation.
gitSemantic commits, PR bodies, branch naming.
integratePort features from external GitHub repos.
surgeonIncremental refactor (Strangler Fig, Branch by Abstraction).
safeguardCharacterization tests + rollback markers before risky refactors.
improve-architectureFind friction; propose deepening opportunities.
mcp-builderGenerate MCP servers from spec.

Security, governance, infrastructure

SkillPurpose
guardianPre-commit security gate — OWASP, secrets, deps.
readinessPre-commit quality gate — logic, regressions, completeness.
guardian-envOS + runtime + tools + ports + env-var check before work starts.
sastStatic-analysis wrapper (ESLint, Semgrep, Bandit, Clippy).
adversaryPre-implementation red-team analysis on high-risk plans.
logic-guardianProtects business logic from accidental deletion.
quarantineAdvisory on untrusted MCP / WebFetch / upload content.
hallucination-guardCatch phantom imports, non-existent packages.
deployMulti-platform deploy with health checks.
watchdogPost-deploy health monitoring.
incidentProduction incident response (triage → contain → root-cause → postmortem).
dependency-doctorOutdated packages + CVE scan + prioritized update plan.
audit8-dimension project health audit.
perfPerformance regression gate (N+1, sync-in-async, bundle bloat).

Knowledge, research, strategy

SkillPurpose
researchWeb search for technologies + best practices.
docsAuto-generate + maintain README, API, architecture docs.
docs-seekerLocate API references, changelogs, migration guides.
documentationLeadership-ready packages, user stories, Jira CSV.
onboardGenerate CLAUDE.md + .topia/ context for a new project.
brainstormGenerate 2-3 approaches with trade-offs.
designDesign-system generator (palette, typography, anti-patterns).
problem-solver19 analytical frameworks + 12 bias detectors.
sequential-thinkingMulti-variable analysis with dependency ordering.
journalADRs, decisions, progress across sessions.
neural-memoryCross-session recall via semantic graph (uses agora-code MCP when registered).
trend-scoutMarket intelligence (Product Hunt, GitHub Trending, HN, Reddit).
autopsyHealth assessment of legacy codebases (rescue RECON).
doc-processorGenerate / parse PDF, DOCX, XLSX, PPTX, CSV.

Planning & management

SkillPurpose
planMaster plan + phase files for multi-phase features.
ideaRequirements elicitation — 5-question gate, cross-session memory.
reviewCode review with file:line findings.
review-intakeProcess external PR comments / issue triage.
retroEngineering retrospective on commit history.
scope-guardDetect + quantify scope creep.
context-packBundle context for sub-agent delegation.
completion-gateValidate agent claims against evidence trail.

Creative & specialized

SkillPurpose
asset-creatorSVG icons, OG images, social banners.
marketingLanding copy, SEO meta, blog posts, video scripts.
slidesMarp-compatible decks from JSON schema.
video-creatorVideo plans — scripts, storyboards, asset checklists.
browser-pilotPlaywright automation + a11y audit.

Internal toolkit primitives

SkillPurpose
skill-routerL0 — routes every action to the right skill.
skill-forgeBuild + verify new Topia skills.
context-engineContext-window management + compaction.
session-bridgeCross-session state persistence.
worktreeGit worktree lifecycle for parallel streams.
integrity-checkDetect adversarial content in .topia/ files.
constraint-checkValidate that HARD-GATEs were actually followed.

Full catalog with invocation markers (👤 user / 🔄 either / 🤖 agent): docs/SKILLS.md.


Extension packs

Install what you need; each pack adds 3–8 domain-specific skills that plug into the core toolkit.

PackFocus
@Topia/uiDesign systems, accessibility, animation, React patterns
@Topia/backendAPI, auth, DB, middleware
@Topia/mobileReact Native, Flutter, app store
@Topia/devopsDocker, CI/CD, SSL, monitoring
@Topia/securityPentest, supply chain, API hardening
@Topia/ecommerceShopify, payments, cart, inventory
@Topia/ai-mlLLM, RAG, embeddings
@Topia/contentBlog, CMS, MDX, i18n, SEO
@Topia/analyticsTracking, A/B, funnels
@Topia/chrome-extManifest V3, service workers

Auto-discipline hooks

node compiler/bin/topia.js hooks install --preset gentle     # advisory (default)
node compiler/bin/topia.js hooks install --preset strict     # blocking
node compiler/bin/topia.js hooks status                      # inspect wiring
node compiler/bin/topia.js hooks uninstall                   # remove cleanly
EventSkillFires
`PreToolUse(Edit\Write)`readinessBefore source-file edits
PreToolUse(Bash)guardianBefore shell commands
`PostToolUse(Edit\Write)`dependency-doctorAfter manifest edits
Stopcompletion-gateEnd of session

Architecture

Five layers, each with one responsibility:

LayerRoleCount
L0 RouterRoutes every action1
L1 OrchestratorsFull lifecycle workflows5 (build, team, launch, rescue, scaffold)
L2 Workflow HubsCross-hub coordination — the differentiator~30
L3 UtilitiesStateless, pure capabilities27
L4 ExtensionsDomain-specific packs10

Skills only call downward (with documented L3→L3 exceptions). Connections are declared in ## Calls / ## Called By. Event-driven coordination is declared in emit / listen pulses — full inventory in docs/PULSES.md. Full architecture: docs/ARCHITECTURE.md.


Cross-session state

.topia/
├── decisions.md     architectural decisions log
├── conventions.md   established patterns & style
├── progress.md      task progress tracker
├── session-log.md   brief session history
├── adr/             individual ADR files (numbered)
├── features/        per-feature requirements + plans
└── org/
    └── org.md       team / role / policy config — committed

Every new session loads .topia/ automatically.

Only the org/ tree is intended for commit; all other .topia/* (including active-packs.json) stays local per workspace.

Project .gitignore

topia install and topia setup --here prompt once to append Topia ignore rules (.topia/*, .mcp.json, with an exception for org/). Decline is remembered via .topia/skip-gitignore.flag. Verify anytime with topia doctor.

L4 packs: shipped vs activated

All @Topia/* packs ship with the plugin. Onboard, topia install, and topia init (non-Claude) run stack detection and write .topia/active-packs.json so each workspace declares which packs to lean on — not a separate install step. Re-run anytime with topia packs detect.

The org/ tree holds stable team and policy configuration. guardian and readiness consume it at compile time and inject an <ORG-POLICY> block into their runtime hooks. See .topia/org/org.md for the template.


Reference

DocContents
docs/INSTALL.mdInstall hub — Claude, Cursor, hybrid
docs/INSTALL-CLAUDE-CODE.mdClaude Code plugin install
docs/INSTALL-NON-CLAUDE.mdCursor, Codex, Windsurf, etc.
docs/GETTING_STARTED.mdFirst 5 minutes
docs/SKILLS.mdFull skill catalog with invocation markers
docs/SKILL-CATEGORIES.mdSkill taxonomy reference
docs/ARCHITECTURE.md5-layer architecture details
docs/PULSES.mdPulse inventory + emit/listen graph
docs/HOOKS.mdHook reference per platform
docs/mcp-integrations/agora-code.mdPersistent-memory MCP integration
docs/migration/from-rune.mdMigrating from rune-kit
docs/TROUBLESHOOTING.mdCommon issues + fixes
docs/VISION.mdStrategic positioning + skill-addition filter
CHANGELOG.mdRelease history
ROADTODO.mdRoadmap + outstanding work
mcp-servers/agora-code/README.mdVendored agora-code reference (Apache 2.0)

Numbers

Skills:            71 (L0:1 · L1:5 · L2:33 · L3:32)
Extension Packs:   10
Synapses:          315 (4.4 avg/skill)
Pulses:            49 (60 emit/listen edges)
Platforms:         Claude Code, Cursor, Codex, Antigravity, OpenCode, OpenClaw, Generic
Tests:             1,035 passing

Acknowledgments

  • agora-code (Apache 2.0) — vendored at mcp-servers/agora-code/ for optional persistent memory. See mcp-servers/agora-code/NOTICE-TOPIA.md for attribution + refresh procedure.
  • UI/UX Pro Max (MIT) — design-intelligence DB powering design + @Topia/ui.
  • biome (MIT) (Apache 2.0) - Installed for app use.
  • rune-kit (MIT) — Workflow, hooks, skill, methodology process grafted (integrated) into the topia operation.

License

MIT — see LICENSE. Vendored agora-code is Apache 2.0 — see mcp-servers/agora-code/LICENSE.

Source 12 files
mods/index.tsx 1055 lines
1import { atom, read, update } from 'claude-code'
2import type { BoxProps, ElementConstructor, EngineInterface, Register, TextProps } from 'claude-code'
3
4import { COMMIT, COMMIT_PUSH, NOT_A_REPO, PUSH, WRITING_TOOLS, parseStatus } from './lib/git-band'
5import {
6  DEFAULT_PREFS,
7  EMPTY_PROJECT,
8  MOD_IDS,
9  MODS,
10  MODS_USAGE,
11  NO_SETTINGS,
12  PREFS_KEY,
13  SOURCE_ABOUT,
14  SOURCE_LABELS,
15  USER_KEY,
16  choose,
17  defaultScope,
18  flipped,
19  parseModsArgs,
20  projectModsKey,
21  resolve,
22  shouldRecap,
23  summary,
24} from './lib/mod-settings'
25import type { Options } from './lib/mod-settings'
26import { projectKey, projectName } from './lib/model-preset'
27import {
28  compare,
29  contextText,
30  decorations,
31  describeSkill,
32  isWritten,
33  predict,
34  ranSkill,
35  skillColor,
36  startTurn,
37  toView,
38  viewKey,
39  withoutRouterSuggestion,
40} from './lib/prompt-routing'
41import { FAILED, composeText as hostsText, hostsKey, learnHosts, parseSsh } from './lib/remote-hosts'
42import { DEFAULTS, IDS, RULES, composeText as ordersText, ordersKey, ordersStatus } from './lib/standing-orders'
43import { joinStatus } from './lib/status'
44import type { StatusSlot } from './lib/status'
45import { filterHookText, formatUsage } from './lib/topia-quiet'
46import { GIT_ABOUT, ORDERS_STATUS_ABOUT, ROUTING_ABOUT, gitParts, scopeOf, usageParts } from './lib/value-help'
47import type {
48  GitInfo,
49  Host,
50  HiddenReport,
51  ModChoices,
52  ModId,
53  ModScope,
54  ModSettings,
55  ModsPrefs,
56  OrderId,
57  Orders,
58  ProjectMods,
59  RoutingView,
60  SshTarget,
61  UsageLine,
62} from './types'
63
64// Topia's Claude Code mods. Each has a userConfig switch in
65// .claude-plugin/plugin.json (its default), and /mods turns one on or off
66// for you (every project) or for this project, without a reload:
67//   gitBand        changed / unpushed counts above the prompt, Commit and Push buttons
68//   standingOrders per-project rules in the system prompt, /orders
69//   remoteHosts    SSH hosts learned from ssh calls that worked, per project, /hosts (off by default)
70//   quietReports   Topia's hook reports kept out of context, usage status line, /topia-activity
71//   modelPreset    the model used last per project, restored at startup, /model-preset
72//   promptRouting  the Topia skills a draft's wording points at, live above the prompt,
73//                  then predicted vs ran; promptRoutingHint tells the model too; /routing
74// The first session in a project (and the first onboard run there) asks which
75// to keep in a row above the prompt; a recap row comes back every so often.
76// A plugin registers each event once without a matcher, so the shared events
77// below run every mod's part in turn, each gated on whether it is on now. The
78// engine-facing code is all in this file; the logic it calls is in ./lib.
79
80const gitInfo = atom({ plugin: 'topia', key: 'gitInfo' } as const, null)
81const gitBandHidden = atom({ plugin: 'topia', key: 'gitBandHidden' } as const, false)
82const standingOrders = atom({ plugin: 'topia', key: 'standingOrders' } as const, null)
83const sshHosts = atom({ plugin: 'topia', key: 'sshHosts' } as const, {})
84const quietHidden = atom({ plugin: 'topia', key: 'quietHidden' } as const, [])
85const quietSavedChars = atom({ plugin: 'topia', key: 'quietSavedChars' } as const, 0)
86const quietUsage = atom({ plugin: 'topia', key: 'quietUsage' } as const, null)
87// Set on the session's first session.start, so a hot reload (which fires it
88// again) neither asks about mods again nor switches the model mid-session.
89const modelPresetApplied = atom({ plugin: 'topia', key: 'modelPresetApplied' } as const, false)
90const routingLive = atom({ plugin: 'topia', key: 'routingLive' } as const, null)
91const routingTurn = atom({ plugin: 'topia', key: 'routingTurn' } as const, null)
92const routingHidden = atom({ plugin: 'topia', key: 'routingHidden' } as const, false)
93const bandFocus = atom({ plugin: 'topia', key: 'bandFocus' } as const, null)
94const modSettings = atom({ plugin: 'topia', key: 'modSettings' } as const, null)
95const modsPrompt = atom({ plugin: 'topia', key: 'modsPrompt' } as const, null)
96const modsScope = atom({ plugin: 'topia', key: 'modsScope' } as const, 'project')
97const modsFocus = atom({ plugin: 'topia', key: 'modsFocus' } as const, null)
98const modsPrefs = atom({ plugin: 'topia', key: 'modsPrefs' } as const, null)
99
100const ORDERS_PANE = 'topia-standing-orders'
101const HOSTS_PANE = 'topia-remote-hosts'
102const ACTIVITY_PANE = 'topia-activity'
103const MODS_PANE = 'topia-mods'
104// Before /mods, /routing kept its own global switch; read once and folded in.
105const ROUTING_OFF_KEY = 'promptRouting:off'
106
107const COMMANDS = [
108  { name: 'mods', description: 'Turn Topia mods on or off, for you or for this project', argumentHint: '[mod] [on|off|reset] [--project|--user]' },
109  { name: 'routing', description: 'Turn the Topia prompt-routing band and highlights on or off', argumentHint: '[on|off]' },
110  { name: 'orders', description: 'Show or toggle your standing orders for this project', argumentHint: '[fanout|ledger|scripts|commit] [on|off]' },
111  { name: 'hosts', description: 'Show the SSH hosts the model knows about; forget one', argumentHint: '[forget <user@host>]' },
112  { name: 'topia-activity', description: "Show the Topia hook reports kept out of the model's context" },
113  { name: 'model-preset', description: 'Show or forget the model remembered for this project', argumentHint: '[forget]' },
114] as const
115
116// Module state: a reload clears it and each mod sets its slot again from
117// session.start.
118const statusSlots: Partial<Record<StatusSlot, string>> = {}
119
120function setStatus($: EngineInterface, slot: StatusSlot, text: string | undefined) {
121  if (text === undefined || text.length === 0) delete statusSlots[slot]
122  else statusSlots[slot] = text
123  $.ui.status(joinStatus(statusSlots))
124}
125
126// What a value means, in one fixed slot under the rows, like Claude Code's own
127// menus. The slot keeps its height whatever is shown, so the rows above never
128// move or rewrap: the line for the value under the pointer covers the slot
129// (hover, no hook), else the focused value's line (Tab, arrows, a click), else
130// the hint. Long lines wrap inside the slot and are clipped at its height.
131const ABOUT_LINES = 2
132
133function aboutSlot(
134  { Box, Text }: { Box: ElementConstructor<BoxProps>; Text: ElementConstructor<TextProps> },
135  abouts: Record<string, string>,
136  focused: string | undefined,
137) {
138  return (
139    <Box key="about" flexDirection="column" height={ABOUT_LINES} overflow="hidden">
140      {Object.keys(abouts).map(key => (
141        <Box key={`about-${key}`} display="none" height={ABOUT_LINES} flexShrink={0} hover={{ scope: scopeOf(key), display: 'flex' }}>
142          <Text dimColor wrap="wrap">
143            ⓘ {abouts[key]}
144          </Text>
145        </Box>
146      ))}
147      <Box key="about-rest" height={ABOUT_LINES} flexShrink={0}>
148        <Text dimColor wrap="wrap">
149          ⓘ {focused ?? 'Hover or Tab to a value to see what it means.'}
150        </Text>
151      </Box>
152    </Box>
153  )
154}
155
156function offText(id: ModId): string {
157  return `${MODS[id].label} is off. /mods ${MODS[id].short} on turns it on (for you; add --project for this project only).`
158}
159
160// ── mods on and off ─────────────────────────────────────────────────────────
161
162async function loadProject($: EngineInterface): Promise<ProjectMods> {
163  const saved = (await $.store.get(projectModsKey(await $.session.root()))) as Partial<ProjectMods> | undefined
164  return { ...EMPTY_PROJECT, ...(saved ?? {}) }
165}
166
167async function saveProject($: EngineInterface, change: (project: ProjectMods) => ProjectMods) {
168  const next = change(await loadProject($))
169  await $.store.set(projectModsKey(await $.session.root()), next)
170  return next
171}
172
173async function loadPrefs($: EngineInterface): Promise<ModsPrefs> {
174  const saved = (await $.store.get(PREFS_KEY)) as Partial<ModsPrefs> | undefined
175  const prefs = { ...DEFAULT_PREFS, ...(saved ?? {}) }
176  await update($, modsPrefs, () => prefs)
177  return prefs
178}
179
180async function savePrefs($: EngineInterface, change: (prefs: ModsPrefs) => ModsPrefs) {
181  const next = change(await loadPrefs($))
182  await $.store.set(PREFS_KEY, next)
183  await update($, modsPrefs, () => next)
184  return next
185}
186
187// The /config rows an organization's policy fixes: those switches win.
188async function lockedMods($: EngineInterface): Promise<ModId[]> {
189  try {
190    const rows = await $.config.list()
191    return MOD_IDS.filter(id => rows.some(row => row.key === `topia.${id}` && row.isLocked))
192  } catch {
193    return []
194  }
195}
196
197async function loadModSettings($: EngineInterface): Promise<ModSettings> {
198  const user = { ...(((await $.store.get(USER_KEY)) ?? {}) as ModChoices) }
199  const wasOff = await $.store.get(ROUTING_OFF_KEY)
200  if (wasOff !== undefined) {
201    if (wasOff === true && user.promptRouting === undefined) user.promptRouting = false
202    await $.store.set(USER_KEY, user)
203    await $.store.delete(ROUTING_OFF_KEY)
204  }
205  const settings: ModSettings = { user, project: (await loadProject($)).choices, locked: await lockedMods($) }
206  await update($, modSettings, () => settings)
207  return settings
208}
209
210// ── git band ────────────────────────────────────────────────────────────────
211
212async function refreshGit($: EngineInterface) {
213  const cwd = await $.session.cwd()
214  let next: GitInfo
215  try {
216    const ran = await $.process.run(['git', 'status', '--porcelain=v1', '--branch'], { cwd, timeoutMs: 10_000 })
217    next = ran.exitCode === 0 ? parseStatus(ran.stdout) : NOT_A_REPO
218  } catch {
219    next = NOT_A_REPO
220  }
221  await update($, gitInfo, () => next)
222}
223
224// ── standing orders ─────────────────────────────────────────────────────────
225
226async function loadOrders($: EngineInterface) {
227  const saved = (await $.store.get(ordersKey(await $.session.root()))) as Partial<Orders> | undefined
228  const merged: Orders = { ...DEFAULTS, ...(saved ?? {}) }
229  await update($, standingOrders, () => merged)
230  setStatus($, 'orders', ordersStatus(merged))
231  return merged
232}
233
234async function saveOrders($: EngineInterface, next: Orders) {
235  await $.store.set(ordersKey(await $.session.root()), next)
236  await update($, standingOrders, () => next)
237  setStatus($, 'orders', ordersStatus(next))
238}
239
240// Reads the latest value at press time, never the one a drawing captured.
241async function toggleOrder($: EngineInterface, id: OrderId) {
242  const latest = (await read($, standingOrders)) ?? DEFAULTS
243  await saveOrders($, { ...latest, [id]: !latest[id] })
244}
245
246// ── remote hosts ────────────────────────────────────────────────────────────
247
248async function loadHosts($: EngineInterface) {
249  const saved = ((await $.store.get(hostsKey(await $.session.root()))) ?? {}) as Record<string, Host>
250  await update($, sshHosts, () => saved)
251  return saved
252}
253
254async function forgetHost($: EngineInterface, id: string) {
255  const latest = { ...(await loadHosts($)) }
256  delete latest[id]
257  await $.store.set(hostsKey(await $.session.root()), latest)
258  await update($, sshHosts, () => latest)
259}
260
261async function learnFrom($: EngineInterface, targets: SshTarget[]) {
262  const today = new Date(await $.clock.now()).toISOString().slice(0, 10)
263  const { known, learned } = learnHosts(await loadHosts($), targets, today)
264  await $.store.set(hostsKey(await $.session.root()), known)
265  await update($, sshHosts, () => known)
266  for (const id of learned) {
267    $.ui.toast(`topia: learned ssh host ${id}${known[id]?.key ? ' (key)' : ''}`)
268  }
269}
270
271// ── quiet reports ───────────────────────────────────────────────────────────
272
273async function refreshUsage($: EngineInterface, cachePercent?: number) {
274  const now = await $.session.usage()
275  const previous = await read($, quietUsage)
276  const line: UsageLine = {
277    contextPercent: now.context.percent,
278    cachePercent: cachePercent ?? previous?.cachePercent,
279    usd: now.cost?.usd,
280    fiveHourPercent: now.rateLimits.find(limit => limit.kind === 'five_hour')?.percentUsed,
281  }
282  await update($, quietUsage, () => line)
283  setStatus($, 'usage', formatUsage(line, await read($, quietSavedChars)))
284}
285
286// ── model preset ────────────────────────────────────────────────────────────
287
288async function rememberModel($: EngineInterface) {
289  const root = await $.session.root()
290  const model = await $.session.model()
291  if (model && (await $.store.get(projectKey(root))) !== model) {
292    await $.store.set(projectKey(root), model)
293  }
294}
295
296async function applyModel($: EngineInterface) {
297  const root = await $.session.root()
298  const saved = await $.store.get(projectKey(root))
299  const current = await $.session.model()
300  if (typeof saved !== 'string' || saved === current) return
301
302  await $.command.run({ command: 'model', args: saved })
303  $.ui.toast(`topia: ${projectName(root)} last used ${saved}; switched (was ${current}).`, { timeoutMs: 8000 })
304}
305
306// ── prompt routing ──────────────────────────────────────────────────────────
307
308// Module state: what the band last showed, so a keystroke that changes
309// nothing in it does not redraw it.
310let routingShown = ''
311
312async function showLive($: EngineInterface, view: RoutingView | null) {
313  const key = viewKey(view)
314  if (key === routingShown) return
315  routingShown = key
316  await update($, routingLive, () => view)
317}
318
319async function recordRan($: EngineInterface, name: string) {
320  await update($, routingTurn, turn =>
321    turn === null || turn.isDone || turn.ran.includes(name) ? turn : { ...turn, ran: [...turn.ran, name] },
322  )
323}
324
325// ── mods on and off: what each switch does now ──────────────────────────────
326
327async function settingsNow($: EngineInterface): Promise<ModSettings> {
328  return (await read($, modSettings)) ?? NO_SETTINGS
329}
330
331async function isOn($: EngineInterface, config: Options, id: ModId): Promise<boolean> {
332  return resolve(id, config, await settingsNow($)).isOn
333}
334
335async function isHintOn($: EngineInterface, config: Options): Promise<boolean> {
336  return config.promptRoutingHint !== false && (await isOn($, config, 'promptRouting'))
337}
338
339// What turning a mod on or off does now, without a reload: start what it
340// shows, clear what it left behind, and bring back a row hidden this session.
341async function applyFlips($: EngineInterface, flips: { id: ModId; isOn: boolean }[]) {
342  for (const { id, isOn: turnedOn } of flips) {
343    if (id === 'gitBand' && turnedOn) {
344      await update($, gitBandHidden, () => false)
345      void refreshGit($)
346    }
347    if (id === 'standingOrders') {
348      if (turnedOn) await loadOrders($)
349      else setStatus($, 'orders', undefined)
350    }
351    if (id === 'remoteHosts' && turnedOn) await loadHosts($)
352    if (id === 'quietReports') {
353      if (turnedOn) void refreshUsage($)
354      else setStatus($, 'usage', undefined)
355    }
356    if (id === 'promptRouting') {
357      await update($, routingHidden, () => false)
358      if (!turnedOn) {
359        await showLive($, null)
360        await update($, routingTurn, () => null)
361      }
362    }
363  }
364}
365
366// Sets each mod at one scope (a boolean, 'toggle', or undefined to clear)
367// and saves that scope. A mod the policy locks is left as it is.
368async function setMods(
369  $: EngineInterface,
370  config: Options,
371  scope: ModScope,
372  ids: readonly ModId[],
373  value: boolean | undefined | 'toggle',
374): Promise<ModSettings> {
375  const before = (await read($, modSettings)) ?? (await loadModSettings($))
376  let after = before
377  for (const id of ids) {
378    if (before.locked.includes(id)) continue
379    const next = value === 'toggle' ? !resolve(id, config, after).isOn : value
380    after = choose(after, scope, id, next)
381  }
382  if (scope === 'user') await $.store.set(USER_KEY, after.user)
383  else await saveProject($, project => ({ ...project, choices: after.project, isConfirmed: true }))
384  await update($, modSettings, () => after)
385  await applyFlips($, flipped(config, before, after))
386  return after
387}
388
389async function forgetProject($: EngineInterface, config: Options): Promise<string> {
390  const root = await $.session.root()
391  const before = await settingsNow($)
392  for (const key of [projectModsKey(root), ordersKey(root), hostsKey(root), projectKey(root)]) await $.store.delete(key)
393  const after = await loadModSettings($)
394  await applyFlips($, flipped(config, before, after))
395  if (await isOn($, config, 'standingOrders')) await loadOrders($)
396  await update($, sshHosts, () => ({}))
397  return root
398}
399
400async function openModsPane($: EngineInterface) {
401  await update($, modsPrompt, () => null)
402  await saveProject($, project => ({ ...project, isConfirmed: true }))
403  await loadPrefs($)
404  await $.ui.open({ id: MODS_PANE, title: 'Topia mods', focus: true, closeOnEscape: true, holdToasts: true })
405}
406
407// The first session in a project asks which mods to keep there; after that,
408// a recap comes back every 10 sessions and 14 days at most.
409async function askAboutMods($: EngineInterface) {
410  const now = await $.clock.now()
411  const project = await loadProject($)
412  const prefs = await savePrefs($, saved => ({
413    ...saved,
414    sessionsSinceRecap: saved.sessionsSinceRecap + 1,
415    recapAt: saved.recapAt === 0 ? now : saved.recapAt,
416  }))
417  const ask = !project.isConfirmed && prefs.askNewProjects ? 'first-run' : shouldRecap(prefs, now) ? 'recap' : null
418  await update($, modsPrompt, () => ask)
419}
420
421// ── hooks ───────────────────────────────────────────────────────────────────
422
423export const register: Register = (on, options) => {
424  const config: Options = options
425
426  on('session.start', async ($, e, next) => {
427    const isFirstStart = !(await read($, modelPresetApplied))
428    await update($, modelPresetApplied, () => true)
429
430    for (const spec of COMMANDS) await $.command.register(spec)
431    await loadModSettings($)
432
433    if (await isOn($, config, 'gitBand')) void refreshGit($)
434    if (await isOn($, config, 'standingOrders')) await loadOrders($)
435    if (await isOn($, config, 'remoteHosts')) await loadHosts($)
436    if (await isOn($, config, 'quietReports')) void refreshUsage($)
437    // A reload clears the slots; this clears a line a mod now off left behind.
438    $.ui.status(joinStatus(statusSlots))
439
440    if (isFirstStart && e.isInteractive) await askAboutMods($)
441
442    const started = await next(e)
443    if (isFirstStart && e.isInteractive && (await isOn($, config, 'modelPreset'))) void applyModel($)
444
445    return started
446  })
447
448  on('session.end', async ($, e, next) => {
449    if (await isOn($, config, 'modelPreset')) await rememberModel($)
450
451    return next(e)
452  })
453
454  on('tool.call', async ($, e, next) => {
455    const tool = String(e.tool)
456    if (tool === 'Agent' && (await isOn($, config, 'promptRouting'))) {
457      const agent = ranSkill((e as { subagent_type?: unknown }).subagent_type as string | undefined)
458      if (agent !== null) await recordRan($, agent)
459    }
460
461    const ran = await next(e)
462    if (WRITING_TOOLS.has(tool) && (await isOn($, config, 'gitBand'))) void refreshGit($)
463
464    const command = (e as { command?: unknown }).command
465    const succeeded = ran.deny === undefined && ran.isError !== true && !FAILED.test(ran.text ?? '')
466    if (succeeded && (tool === 'Bash' || tool === 'PowerShell') && typeof command === 'string' && (await isOn($, config, 'remoteHosts'))) {
467      // The remote command may hold `;` or `|` inside quotes, which the segment
468      // split cuts, so sudo is judged on the whole line.
469      const targets = parseSsh(command).map(target => ({ ...target, remote: command }))
470      if (targets.length > 0) await learnFrom($, targets)
471    }
472
473    return ran
474  })
475
476  on('turn.complete', async ($, e, next) => {
477    if (await isOn($, config, 'gitBand')) void refreshGit($)
478    const result = await next(e)
479    if (e.agentId === undefined) {
480      if (await isOn($, config, 'quietReports')) {
481        const turn = e.usage
482        const input = turn ? turn.input_tokens + turn.cache_read_input_tokens + turn.cache_creation_input_tokens : 0
483        void refreshUsage($, turn && input > 0 ? (turn.cache_read_input_tokens / input) * 100 : undefined)
484      }
485      // The /model picker settles after its command returns, so the choice is
486      // read again once each main-thread turn ends, and when the session ends.
487      if (await isOn($, config, 'modelPreset')) await rememberModel($)
488      await update($, routingTurn, turn => (turn === null ? null : { ...turn, isDone: true }))
489    }
490
491    return result
492  })
493
494  // ── mods ──
495
496  on('command.run', { command: 'mods' }, async ($, e) => {
497    const asked = parseModsArgs(e.args)
498    if (asked.kind === 'error') return { text: asked.text }
499    if (asked.kind === 'open') {
500      await openModsPane($)
501      return { text: `Topia mods: ${summary(config, await settingsNow($))}. The pane is open.` }
502    }
503    if (asked.kind === 'forget-project') {
504      const root = await forgetProject($, config)
505      return {
506        text: `Forgot Topia's data for ${projectName(root)}: its mod choices, standing orders, SSH hosts and model. Now: ${summary(config, await settingsNow($))}.`,
507      }
508    }
509
510    const settings = (await read($, modSettings)) ?? (await loadModSettings($))
511    const locked = asked.ids.filter(id => settings.locked.includes(id))
512    const scope = asked.scope ?? defaultScope(settings, asked.ids[0] ?? 'gitBand')
513    const after = await setMods($, config, scope, asked.ids, asked.value)
514    const where = scope === 'project' ? `this project (${projectName(await $.session.root())})` : 'you (every project)'
515    const names = asked.ids.filter(id => !locked.includes(id)).map(id => MODS[id].label)
516    const verb = asked.value === undefined ? 'reset' : asked.value === 'toggle' ? 'switched' : asked.value ? 'on' : 'off'
517    const lockNote = locked.length > 0 ? ` ${locked.map(id => MODS[id].label).join(', ')}: locked by your organization's policy.` : ''
518
519    return {
520      text: `${names.length > 0 ? `${names.join(', ')} ${verb} for ${where}.` : 'Nothing changed.'}${lockNote} Now: ${summary(config, after)}.`,
521    }
522  })
523
524  on('ui.focus', { component: 'Pane' }, async ($, e, next) => {
525    if (e.requestId === MODS_PANE && e.plugin === 'topia') await update($, modsFocus, () => e.element ?? null)
526
527    return next(e)
528  })
529
530  on('ui.render', { component: 'Pane', requestId: MODS_PANE }, async ($, e) => {
531    const { Box, Button, Text } = $.ui.resolve(e)
532    const settings = await settingsNow($)
533    const scope = await read($, modsScope)
534    const prefs = (await read($, modsPrefs)) ?? DEFAULT_PREFS
535    const focus = await read($, modsFocus)
536    const hidden = { gitBand: await read($, gitBandHidden), promptRouting: await read($, routingHidden) } as Partial<Record<ModId, boolean>>
537    const here = projectName(await $.session.root())
538
539    const abouts: Record<string, string> = {}
540    const described = (key: string, about: string) => {
541      abouts[key] = about
542      return { key, hover: { scope: scopeOf(key), underline: true } }
543    }
544    const toggle = async (id: ModId) => {
545      if (settings.locked.includes(id)) {
546        $.ui.toast(`topia: ${MODS[id].label} is locked by your organization's policy.`)
547        return
548      }
549      const latest = await settingsNow($)
550      if (scope === 'user' && latest.project[id] !== undefined) {
551        $.ui.toast(`topia: this project has its own choice for ${MODS[id].label}; switch "Save for" to this project, or clear it.`)
552        return
553      }
554      await setMods($, config, scope, [id], 'toggle')
555    }
556    const usage = usageParts(await read($, quietUsage), await read($, quietSavedChars))
557    const ordersOn = statusSlots.orders
558
559    return (
560      <Box flexDirection="column">
561        <Box key="scope" flexDirection="row" gap={1}>
562          <Text dimColor>Save for</Text>
563          <Button
564            {...described('scope-project', `Choices apply in ${here} only and beat your all-projects choices.`)}
565            label={`this project (${here})`}
566            hotkey="p"
567            variant={scope === 'project' ? 'primary' : 'secondary'}
568            onPress={() => update($, modsScope, () => 'project')}
569          />
570          <Button
571            {...described('scope-user', 'Choices apply in every project that has no choice of its own.')}
572            label="all my projects"
573            hotkey="u"
574            variant={scope === 'user' ? 'primary' : 'secondary'}
575            onPress={() => update($, modsScope, () => 'user')}
576          />
577        </Box>
578        {MOD_IDS.map((id, index) => {
579          const { isOn: modOn, source } = resolve(id, config, settings)
580          return (
581            <Box key={`row-${id}`} flexDirection="row" gap={1}>
582              <Button
583                {...described(`mod-${id}`, MODS[id].about)}
584                hotkey={String(index + 1)}
585                label={modOn ? 'on ' : 'off'}
586                variant={modOn ? 'primary' : 'secondary'}
587                onPress={() => toggle(id)}
588              />
589              <Text dimColor={!modOn}>{MODS[id].label}</Text>
590              <Button {...described(`source-${id}`, SOURCE_ABOUT[source])} plain onPress={() => update($, modsFocus, () => `source-${id}`)}>
591                <Text dimColor>
592                  {SOURCE_LABELS[source]}
593                  {hidden[id] ? ' · hidden this session' : ''}
594                </Text>
595              </Button>
596            </Box>
597          )
598        })}
599        {(usage.length > 0 || ordersOn !== undefined) && (
600          <Box key="status" flexDirection="row" gap={1}>
601            <Text dimColor>Status line:</Text>
602            {ordersOn !== undefined && (
603              <Button {...described('status-orders', ORDERS_STATUS_ABOUT)} plain onPress={() => update($, modsFocus, () => 'status-orders')}>
604                <Text dimColor>{ordersOn}</Text>
605              </Button>
606            )}
607            {usage.map(part => (
608              <Button {...described(part.key, part.about)} plain onPress={() => update($, modsFocus, () => part.key)}>
609                <Text dimColor>{part.text}</Text>
610              </Button>
611            ))}
612          </Box>
613        )}
614        <Box key="actions" flexDirection="row" gap={1}>
615          <Button
616            {...described('clear-project', `Drops ${here}'s own choices, so your all-projects choices apply here.`)}
617            label="Clear this project's choices"
618            plain
619            onPress={async () => {
620              await setMods($, config, 'project', MOD_IDS, undefined)
621            }}
622          />
623          <Button
624            {...described('ask-new', 'Whether a new project asks which mods to keep the first time you open it.')}
625            label={prefs.askNewProjects ? 'Stop asking in new projects' : 'Ask in new projects'}
626            plain
627            onPress={() => savePrefs($, saved => ({ ...saved, askNewProjects: !saved.askNewProjects }))}
628          />
629          <Button
630            {...described('recap', 'Whether a reminder of these settings shows every 10 sessions and 14 days.')}
631            label={prefs.isRecapOff ? 'Remind me now and then' : 'No more reminders'}
632            plain
633            onPress={() => savePrefs($, saved => ({ ...saved, isRecapOff: !saved.isRecapOff }))}
634          />
635        </Box>
636        {aboutSlot({ Box, Text }, abouts, focus !== null ? abouts[focus] : undefined)}
637        <Text dimColor>{MODS_USAGE}</Text>
638      </Box>
639    )
640  })
641
642  // ── prompt routing ──
643
644  on('prompt.edit', async ($, e, next) => {
645    const box = await next(e)
646    if (!(await isOn($, config, 'promptRouting'))) return box
647
648    const prediction = predict(box.text)
649    await showLive($, toView(prediction))
650    const runs = decorations(prediction)
651
652    return runs.length === 0 ? box : { ...box, decorations: [...(box.decorations ?? []), ...runs] }
653  })
654
655  on('prompt.submit', async ($, e, next) => {
656    if (!isWritten(e.origin) || !(await isOn($, config, 'promptRouting'))) return next(e)
657
658    const view = toView(predict(e.text))
659    await showLive($, null)
660    await update($, bandFocus, () => null)
661    // Typed over a running turn, it waits; that turn keeps its own tally.
662    if (e.turnId === undefined) await update($, routingTurn, () => (view === null ? null : startTurn(view)))
663    if (view === null || !(await isHintOn($, config))) return next(e)
664
665    return next({ ...e, context: [...(e.context ?? []), contextText(view)] })
666  })
667
668  on('skill.prompt', async ($, e, next) => {
669    const name = ranSkill(e.skill)
670    if (name !== null && (await isOn($, config, 'promptRouting'))) await recordRan($, name)
671    // The first onboard run in a project asks about mods too.
672    if (name === 'onboard') {
673      const project = await loadProject($)
674      if (!project.isOnboardAsked) {
675        await saveProject($, saved => ({ ...saved, isOnboardAsked: true }))
676        await update($, modsPrompt, () => 'onboard')
677      }
678    }
679
680    return next(e)
681  })
682
683  on('ui.focus', { component: 'AbovePrompt' }, async ($, e, next) => {
684    await update($, bandFocus, () => (e.plugin === 'topia' ? (e.element ?? null) : null))
685
686    return next(e)
687  })
688
689  on('command.run', { command: 'routing' }, async ($, e) => {
690    const arg = e.args.trim().toLowerCase()
691    const settings = (await read($, modSettings)) ?? (await loadModSettings($))
692    const value = arg === 'off' ? false : arg === 'on' ? true : 'toggle'
693    const after = await setMods($, config, defaultScope(settings, 'promptRouting'), ['promptRouting'], value)
694    const { isOn: routingOn, source } = resolve('promptRouting', config, after)
695    const hintOff = options.promptRoutingHint === false ? ' The model hint is off (promptRoutingHint in /config).' : ''
696    const lock = source === 'locked' ? " It is locked by your organization's policy." : ''
697
698    return {
699      text: routingOn
700        ? `Prompt routing is on.${hintOff}${lock}`
701        : `Prompt routing is off: no band, no highlights, nothing added for the model. /routing on brings it back.${lock}`,
702    }
703  })
704
705  on('prompt.compose', async ($, e, next) => {
706    const composed = await next(e)
707    const sections = [...composed.sections]
708
709    const current = (await isOn($, config, 'standingOrders')) ? await read($, standingOrders) : null
710    const rules = current === null ? null : ordersText(current)
711    if (rules !== null) sections.push({ id: 'topia:standing-orders', text: rules, scope: 'session' as const })
712
713    const known = (await isOn($, config, 'remoteHosts')) ? hostsText(await read($, sshHosts)) : null
714    if (known !== null) sections.push({ id: 'topia:known-hosts', text: known, scope: 'session' as const })
715
716    return sections.length === composed.sections.length ? composed : { sections }
717  })
718
719  // The intent-router hook's suggestion is dropped whatever the switches: the
720  // band and the hint stand in for it, and /routing off means none at all.
721  on('prompt.attachment', async ($, e, next) => {
722    if (e.origin.kind !== 'hook') return next(e)
723
724    const text = withoutRouterSuggestion(e.text)
725    const filtered = text.length > 0 && (await isOn($, config, 'quietReports')) ? filterHookText(text) : null
726    if (filtered === null) return text === e.text ? next(e) : { text: text.length > 0 ? text : null }
727
728    const removed = e.text.length - (filtered.text?.length ?? 0)
729    const report: HiddenReport = {
730      event: e.origin.event,
731      kind: filtered.kind,
732      chars: removed,
733      at: await $.clock.now(),
734      text: e.text.slice(0, 4000),
735    }
736    await update($, quietHidden, list => [...list, report].slice(-30))
737    await update($, quietSavedChars, total => total + removed)
738
739    return { text: filtered.text }
740  })
741
742  // ── the band: mods prompt, prompt routing, git ──
743
744  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
745    if (e.props.hasSurvey) return next(e)
746
747    const settings = await settingsNow($)
748    const ask = await read($, modsPrompt)
749
750    const info = (await isOn($, config, 'gitBand')) ? await read($, gitInfo) : null
751    const isClean = info === null || !info.isRepo || (info.changed === 0 && info.unpushed === 0)
752    const showGit = !isClean && !(await read($, gitBandHidden))
753
754    const isRouting = (await isOn($, config, 'promptRouting')) && !(await read($, routingHidden))
755    const live = isRouting ? await read($, routingLive) : null
756    const turn = isRouting && live === null ? await read($, routingTurn) : null
757    const focus = await read($, bandFocus)
758
759    if (ask === null && !showGit && live === null && turn === null) return next(e)
760
761    const { Box, Button, Text } = $.ui.resolve(e)
762    const submit = (text: string) => () => $.prompt.submit({ text, asUser: true })
763    const hideRouting = () => update($, routingHidden, () => true)
764
765    // Every value carries a line on what it means, shown in the slot under
766    // the band (aboutSlot).
767    const abouts: Record<string, string> = {}
768    const described = (key: string, about: string) => {
769      abouts[key] = about
770      return { key, hover: { scope: scopeOf(key), underline: true } }
771    }
772    const value = (key: string, label: string, about: string, look: { color?: string; bold?: boolean } = {}, onPress?: () => unknown) => (
773      <Button
774        {...described(key, about)}
775        plain
776        onPress={async () => {
777          await update($, bandFocus, () => key)
778          await onPress?.()
779        }}
780      >
781        <Text color={look.color} dimColor={look.color === undefined} bold={look.bold}>
782          {label}
783        </Text>
784      </Button>
785    )
786
787    let modsRow = null
788    if (ask !== null) {
789      const here = projectName(await $.session.root())
790      const chips = MOD_IDS.map(id => {
791        const { isOn: modOn, source } = resolve(id, config, settings)
792        const about = `${MODS[id].label}: ${MODS[id].about} (${modOn ? 'on' : 'off'}, ${SOURCE_LABELS[source]})`
793        return ask === 'recap'
794          ? value(`mods-${id}`, `${MODS[id].short} ${modOn ? '✓' : '✗'}`, about, modOn ? { color: 'green' } : {})
795          : value(`mods-${id}`, `${MODS[id].short} ${modOn ? '✓' : '✗'}`, `${about} Press to switch it for ${here}.`, modOn ? { color: 'green' } : {}, () =>
796              setMods($, config, 'project', [id], 'toggle'),
797            )
798      })
799      const keep = async () => {
800        await saveProject($, project => ({ ...project, isConfirmed: true }))
801        await update($, modsPrompt, () => null)
802      }
803      const gotIt = async () => {
804        const now = await $.clock.now()
805        await savePrefs($, saved => ({ ...saved, recapAt: now, sessionsSinceRecap: 0 }))
806        await update($, modsPrompt, () => null)
807      }
808      modsRow =
809        ask === 'recap' ? (
810          <Box key="mods" flexDirection="row" gap={1}>
811            <Text color="cyan">topia mods</Text>
812            {chips}
813            <Text dimColor>· /mods changes them, for you or this project</Text>
814            <Button {...described('mods-got-it', 'Hides this reminder until it is due again.')} label="Got it" plain onPress={gotIt} />
815            <Button
816              {...described('mods-no-recap', 'Stops these reminders; /mods turns them back on.')}
817              label="Don't remind me"
818              plain
819              onPress={async () => {
820                await savePrefs($, saved => ({ ...saved, isRecapOff: true }))
821                await update($, modsPrompt, () => null)
822              }}
823            />
824          </Box>
825        ) : (
826          <Box key="mods" flexDirection="row" gap={1}>
827            <Text color="cyan">{ask === 'onboard' ? 'topia onboard · which mods here?' : `topia mods for ${here}?`}</Text>
828            {chips}
829            <Button {...described('mods-keep', `Keeps these for ${here}; /mods changes them any time.`)} label="Keep" variant="primary" onPress={keep} />
830            <Button {...described('mods-choose', 'Opens the mods pane: save for this project or all your projects.')} label="More…" plain onPress={() => openModsPane($)} />
831            <Button
832              {...described('mods-no-ask', 'New projects stop asking; the reminder still comes now and then.')}
833              label="Don't ask in new projects"
834              plain
835              onPress={async () => {
836                await savePrefs($, saved => ({ ...saved, askNewProjects: false }))
837                await keep()
838              }}
839            />
840          </Box>
841        )
842    }
843
844    const chip = (name: string, label: string, about: string, color?: 'cyan' | 'magenta' | 'yellow' | 'green', bold?: boolean) =>
845      value(`route-${name}`, label, about, { color, bold })
846    const skillAbout = (name: string, note?: string) => `${name}: ${describeSkill(name)}${note ? ` (${note})` : ''}`
847
848    let routingRow = null
849    if (live !== null) {
850      routingRow = (
851        <Box key="routing" flexDirection="row" gap={1}>
852          <Text dimColor>topia →</Text>
853          {live.skills.map((skill, index) =>
854            chip(skill.name, skill.name, skillAbout(skill.name, `matched ${skill.keywords.join(', ')}`), skillColor(index), skill.isExplicit),
855          )}
856          {live.chain.length > 0 && value('routing-chain', `then ${live.chain.join(' → ')}`, ROUTING_ABOUT.chain)}
857          <Button {...described('routing-hide', ROUTING_ABOUT.hide)} label="Hide" plain onPress={hideRouting} />
858        </Box>
859      )
860    } else if (turn !== null) {
861      const { hit, chained, extra } = compare(turn)
862      routingRow = (
863        <Box key="routing" flexDirection="row" gap={1}>
864          <Text dimColor>{turn.isDone ? 'topia predicted' : 'topia →'}</Text>
865          {turn.predicted.map((name, index) =>
866            !turn.isDone
867              ? chip(name, name, skillAbout(name), skillColor(index))
868              : hit.includes(name)
869                ? chip(name, `${name} ✓`, skillAbout(name, ROUTING_ABOUT.hit), 'green')
870                : chip(name, `${name} ✗`, skillAbout(name, ROUTING_ABOUT.missed)),
871          )}
872          {chained.length + extra.length > 0 && <Text dimColor>· also ran</Text>}
873          {chained.map(name => chip(name, name, skillAbout(name, ROUTING_ABOUT.chained), 'cyan'))}
874          {extra.map(name => chip(name, name, skillAbout(name, ROUTING_ABOUT.extra), 'yellow'))}
875          <Button {...described('routing-hide', ROUTING_ABOUT.hide)} label="Hide" plain onPress={hideRouting} />
876        </Box>
877      )
878    }
879
880    let gitRow = null
881    if (showGit && info !== null) {
882      const color = info.changed > 0 ? 'yellow' : 'cyan'
883      gitRow = (
884        <Box key="git" flexDirection="row" gap={1}>
885          {gitParts(info).map(part => value(part.key, part.text, part.about, { color }))}
886          {!e.props.isWorking && info.changed > 0 && (
887            <Button {...described('commit', GIT_ABOUT.commit)} label="Commit" hotkey="c" onPress={submit(COMMIT)} />
888          )}
889          {!e.props.isWorking && info.changed > 0 && (
890            <Button {...described('commit-push', GIT_ABOUT.commitPush)} label="Commit & push" hotkey="p" variant="primary" onPress={submit(COMMIT_PUSH)} />
891          )}
892          {!e.props.isWorking && info.changed === 0 && info.unpushed > 0 && (
893            <Button {...described('push', GIT_ABOUT.push)} label="Push" hotkey="p" variant="primary" onPress={submit(PUSH)} />
894          )}
895          <Button {...described('hide', GIT_ABOUT.hide)} label="Hide" plain onPress={() => update($, gitBandHidden, () => true)} />
896        </Box>
897      )
898    }
899
900    return (
901      <Box flexDirection="column">
902        {modsRow}
903        {routingRow}
904        {gitRow}
905        {aboutSlot({ Box, Text }, abouts, focus !== null ? abouts[focus] : undefined)}
906      </Box>
907    )
908  })
909
910  // ── standing orders ──
911
912  on('command.run', { command: 'orders' }, async ($, e) => {
913    if (!(await isOn($, config, 'standingOrders'))) return { text: offText('standingOrders') }
914    const current = (await read($, standingOrders)) ?? (await loadOrders($))
915    const [id, value] = e.args.trim().toLowerCase().split(/\s+/)
916
917    if (!id) {
918      await $.ui.open({ id: ORDERS_PANE, title: 'Standing orders', focus: true, closeOnEscape: true })
919      return { text: 'Standing orders pane opened.' }
920    }
921    if (!IDS.includes(id as OrderId)) {
922      return { text: `Unknown order "${id}". Orders: ${IDS.join(', ')}.` }
923    }
924
925    const key = id as OrderId
926    const turnOn = value === 'on' ? true : value === 'off' ? false : !current[key]
927    await saveOrders($, { ...current, [key]: turnOn })
928
929    return { text: `Standing order "${key}" is now ${turnOn ? 'on' : 'off'} for this project.` }
930  })
931
932  on('ui.render', { component: 'Pane', requestId: ORDERS_PANE }, async ($, e) => {
933    const { Box, Button, Text } = $.ui.resolve(e)
934    const current = (await read($, standingOrders)) ?? DEFAULTS
935
936    return (
937      <Box flexDirection="column">
938        <Text dimColor>Added to the system prompt for this project. Press to toggle.</Text>
939        {IDS.map((id, index) => (
940          <Box key={`row-${id}`} flexDirection="row" gap={1}>
941            <Button
942              key={id}
943              hotkey={String(index + 1)}
944              label={current[id] ? 'on ' : 'off'}
945              variant={current[id] ? 'primary' : 'secondary'}
946              onPress={() => toggleOrder($, id)}
947            />
948            <Text dimColor={!current[id]}>{RULES[id].label}</Text>
949          </Box>
950        ))}
951      </Box>
952    )
953  })
954
955  // ── remote hosts ──
956
957  on('command.run', { command: 'hosts' }, async ($, e) => {
958    if (!(await isOn($, config, 'remoteHosts'))) return { text: offText('remoteHosts') }
959    const [verb, id] = e.args.trim().split(/\s+/)
960    if (verb === 'forget' && id) {
961      const known = await loadHosts($)
962      if (!known[id]) return { text: `No host "${id}". Known: ${Object.keys(known).join(', ') || 'none'}.` }
963      await forgetHost($, id)
964      return { text: `Forgot ${id}.` }
965    }
966
967    await $.ui.open({ id: HOSTS_PANE, title: 'Known SSH hosts', focus: true, closeOnEscape: true })
968    return { text: 'Known SSH hosts pane opened.' }
969  })
970
971  on('ui.render', { component: 'Pane', requestId: HOSTS_PANE }, async ($, e) => {
972    const { Box, Button, Text } = $.ui.resolve(e)
973    const list = Object.entries(await read($, sshHosts)).sort(([, a], [, b]) => b.lastOk.localeCompare(a.lastOk))
974
975    return (
976      <Box flexDirection="column">
977        {list.length === 0 && <Text dimColor>No hosts yet. They are learned from ssh commands that succeed.</Text>}
978        {list.map(([id, h]) => (
979          <Box key={`row-${id}`} flexDirection="row" gap={1}>
980            <Button key={`forget-${id}`} label="Forget" plain onPress={() => forgetHost($, id)} />
981            <Text bold>{id}</Text>
982            <Text dimColor>
983              {h.key ? 'key' : 'no key'} · {h.sudoOk ? 'sudo ✓' : 'sudo ?'} · {h.uses} uses · last {h.lastOk}
984            </Text>
985          </Box>
986        ))}
987      </Box>
988    )
989  })
990
991  // ── quiet reports ──
992
993  on('command.run', { command: 'topia-activity' }, async ($, e) => {
994    if (!(await isOn($, config, 'quietReports'))) return { text: offText('quietReports') }
995    await $.ui.open({ id: ACTIVITY_PANE, title: 'Topia activity (hidden from the model)', focus: true, closeOnEscape: true })
996
997    return { text: 'Topia activity pane opened.' }
998  })
999
1000  on('ui.render', { component: 'Pane', requestId: ACTIVITY_PANE }, async ($, e) => {
1001    const { Box, Markdown, Text } = $.ui.resolve(e)
1002    const list = await read($, quietHidden)
1003    const saved = await read($, quietSavedChars)
1004    const counts = { 'session-report': 0, 'guardian-advisory': 0, 'install-banner': 0 }
1005    for (const one of list) counts[one.kind] += 1
1006    const lastReport = [...list].reverse().find(one => one.kind === 'session-report')
1007    const usage = usageParts(await read($, quietUsage), saved)
1008
1009    return (
1010      <Box flexDirection="column">
1011        <Text>
1012          Kept out of context this session: {(saved / 1000).toFixed(1)}k chars (~{Math.round(saved / 4)} tokens)
1013        </Text>
1014        <Text dimColor>
1015          {counts['session-report']} session reports · {counts['guardian-advisory']} guardian advisories ·{' '}
1016          {counts['install-banner']} install/migration banners
1017        </Text>
1018        {usage.map(part => (
1019          <Text key={`means-${part.key}`} dimColor>
1020            {part.text}: {part.about}
1021          </Text>
1022        ))}
1023        {lastReport === undefined
1024          ? <Text dimColor>No Topia session report yet this session.</Text>
1025          : <Markdown key="report" text={lastReport.text} />}
1026      </Box>
1027    )
1028  })
1029
1030  // ── model preset ──
1031
1032  on('command.run', { command: 'model' }, async ($, e, next) => {
1033    const ran = await next(e)
1034    if (e.args.trim().length > 0 && (await isOn($, config, 'modelPreset'))) await rememberModel($)
1035
1036    return ran
1037  })
1038
1039  on('command.run', { command: 'model-preset' }, async ($, e) => {
1040    if (!(await isOn($, config, 'modelPreset'))) return { text: offText('modelPreset') }
1041    const root = await $.session.root()
1042    if (e.args.trim() === 'forget') {
1043      await $.store.delete(projectKey(root))
1044      return { text: `Forgot the model for ${projectName(root)}.` }
1045    }
1046    const saved = await $.store.get(projectKey(root))
1047
1048    return {
1049      text: typeof saved === 'string'
1050        ? `${projectName(root)} starts on ${saved}. /model to change it; /model-preset forget to stop.`
1051        : `No model remembered for ${projectName(root)} yet; the next one you use is kept.`,
1052    }
1053  })
1054}
1055
mods/lib/git-band.ts 44 lines
1import type { GitInfo } from '../types'
2
3export const WRITING_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit', 'Bash', 'PowerShell'])
4
5export const COMMIT = 'Commit the current changes with a descriptive message.'
6export const COMMIT_PUSH = 'Commit the current changes with a descriptive message, then push to the remote.'
7export const PUSH = 'Push the unpushed commits on this branch to the remote.'
8
9export const NOT_A_REPO: GitInfo = { isRepo: false, branch: '', changed: 0, unpushed: 0, behind: 0, hasUpstream: false }
10
11// `git status --porcelain=v1 --branch` → counts. The first line is the branch
12// header: `## main...origin/main [ahead 2, behind 1]`, `## main` (no upstream),
13// `## No commits yet on main`, or `## HEAD (no branch)`.
14export function parseStatus(stdout: string): GitInfo {
15  const lines = stdout.split(/\r?\n/).filter(line => line.length > 0)
16  const header = lines[0]?.startsWith('## ') ? lines[0].slice(3) : ''
17  const changed = lines.filter(line => !line.startsWith('## ')).length
18
19  let branch = header
20  let hasUpstream = false
21  const noCommits = /^No commits yet on (.+)$/.exec(header)
22  if (noCommits) {
23    branch = noCommits[1] ?? header
24  } else {
25    const split = header.split('...')
26    branch = (split[0] ?? header).split(' ')[0] ?? header
27    hasUpstream = split.length > 1
28  }
29
30  const ahead = Number(/ahead (\d+)/.exec(header)?.[1] ?? 0)
31  const behind = Number(/behind (\d+)/.exec(header)?.[1] ?? 0)
32
33  return { isRepo: true, branch, changed, unpushed: ahead, behind, hasUpstream }
34}
35
36export function bandParts(git: GitInfo): string[] {
37  return [
38    git.changed > 0 ? `${git.changed} changed` : '',
39    git.unpushed > 0 ? `${git.unpushed} unpushed` : '',
40    git.behind > 0 ? `${git.behind} behind` : '',
41    git.hasUpstream ? '' : 'no upstream',
42  ].filter(part => part.length > 0)
43}
44
mods/lib/mod-settings.ts 184 lines
1import type { ModChoices, ModId, ModScope, ModSettings, ModsPrefs, ProjectMods } from '../types'
2
3// Which of Topia's mods are on, and why. A choice saved for this project
4// beats one saved for you (all projects), which beats the /config switch;
5// a /config row an organization's policy locks beats them all. Choices live
6// in the plugin's own store under ~/.claude, never in the repo.
7
8export const MOD_IDS = ['gitBand', 'standingOrders', 'remoteHosts', 'quietReports', 'modelPreset', 'promptRouting'] as const
9
10export type ModInfo = {
11  short: string
12  label: string
13  isDefaultOn: boolean
14  about: string
15}
16
17export const MODS: Record<ModId, ModInfo> = {
18  gitBand: {
19    short: 'git',
20    label: 'Git band',
21    isDefaultOn: true,
22    about: 'A row above the prompt with uncommitted and unpushed counts and Commit / Push buttons; hidden when the tree is clean.',
23  },
24  standingOrders: {
25    short: 'orders',
26    label: 'Standing orders',
27    isDefaultOn: true,
28    about: 'Rules you turn on per project (/orders) added to the system prompt. Flipping it mid-session changes that prompt.',
29  },
30  remoteHosts: {
31    short: 'hosts',
32    label: 'Remote hosts',
33    isDefaultOn: false,
34    about: 'Remembers SSH hosts from ssh commands that worked in this project and lists them to the model (/hosts).',
35  },
36  quietReports: {
37    short: 'quiet',
38    label: 'Quiet reports',
39    isDefaultOn: true,
40    about: "Keeps Topia's session reports and banners out of the model's context (/topia-activity); usage in the status line.",
41  },
42  modelPreset: {
43    short: 'model',
44    label: 'Model preset',
45    isDefaultOn: true,
46    about: 'Remembers the model you last used in this project and starts the next session on it (/model-preset).',
47  },
48  promptRouting: {
49    short: 'routing',
50    label: 'Prompt routing',
51    isDefaultOn: true,
52    about: 'As you type, names the Topia skills your wording points at and underlines the words; predicted vs ran after.',
53  },
54}
55
56export type ModSource = 'default' | 'config' | 'user' | 'project' | 'locked'
57
58export const SOURCE_LABELS: Record<ModSource, string> = {
59  default: 'default',
60  config: '/config',
61  user: 'you',
62  project: 'this project',
63  locked: 'locked',
64}
65
66export const SOURCE_ABOUT: Record<ModSource, string> = {
67  default: "Nobody has chosen; this is the plugin's default.",
68  config: 'Set by the switch in /config, which applies to every project.',
69  user: 'Your choice for every project, saved with /mods.',
70  project: 'Chosen for this project only; it beats your all-projects choice.',
71  locked: "Your organization's policy fixes this switch in /config.",
72}
73
74export const NO_SETTINGS: ModSettings = { user: {}, project: {}, locked: [] }
75
76export const DEFAULT_PREFS: ModsPrefs = { askNewProjects: true, recapAt: 0, sessionsSinceRecap: 0, isRecapOff: false }
77
78// Every 10 sessions and 14 days, whichever comes later.
79export const RECAP_SESSIONS = 10
80export const RECAP_MS = 14 * 24 * 60 * 60 * 1000
81
82export type Options = Readonly<Record<string, unknown>>
83
84export function resolve(id: ModId, options: Options, settings: ModSettings): { isOn: boolean; source: ModSource } {
85  const config = options[id]
86  const configured = typeof config === 'boolean' ? config : MODS[id].isDefaultOn
87  if (settings.locked.includes(id)) return { isOn: configured, source: 'locked' }
88  const project = settings.project[id]
89  if (project !== undefined) return { isOn: project, source: 'project' }
90  const user = settings.user[id]
91  if (user !== undefined) return { isOn: user, source: 'user' }
92  return { isOn: configured, source: configured === MODS[id].isDefaultOn ? 'default' : 'config' }
93}
94
95export function effective(options: Options, settings: ModSettings): Record<ModId, boolean> {
96  return Object.fromEntries(MOD_IDS.map(id => [id, resolve(id, options, settings).isOn])) as Record<ModId, boolean>
97}
98
99// The mods whose effective state differs between two settings.
100export function flipped(options: Options, before: ModSettings, after: ModSettings): { id: ModId; isOn: boolean }[] {
101  const was = effective(options, before)
102  const now = effective(options, after)
103  return MOD_IDS.filter(id => was[id] !== now[id]).map(id => ({ id, isOn: now[id] }))
104}
105
106// One mod's choice at one scope: a boolean sets it, undefined clears it.
107export function choose(settings: ModSettings, scope: ModScope, id: ModId, value: boolean | undefined): ModSettings {
108  const next: ModChoices = { ...settings[scope] }
109  if (value === undefined) delete next[id]
110  else next[id] = value
111  return { ...settings, [scope]: next }
112}
113
114export function normalizeRoot(root: string): string {
115  return root.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
116}
117
118export const USER_KEY = 'mods:user'
119export const PREFS_KEY = 'mods:prefs'
120export function projectModsKey(root: string): string {
121  return `mods:${normalizeRoot(root)}`
122}
123
124export const EMPTY_PROJECT: ProjectMods = { choices: {}, isConfirmed: false, isOnboardAsked: false }
125
126export function shouldRecap(prefs: ModsPrefs, now: number): boolean {
127  return !prefs.isRecapOff && prefs.sessionsSinceRecap >= RECAP_SESSIONS && now - prefs.recapAt >= RECAP_MS
128}
129
130export function findMod(word: string): ModId | null {
131  const lower = word.toLowerCase()
132  return MOD_IDS.find(id => id.toLowerCase() === lower || MODS[id].short === lower) ?? null
133}
134
135export type ModsCommand =
136  | { kind: 'open' }
137  | { kind: 'set'; ids: ModId[]; value: boolean | undefined | 'toggle'; scope: ModScope | null }
138  | { kind: 'forget-project' }
139  | { kind: 'error'; text: string }
140
141export const MODS_USAGE =
142  '/mods [git|orders|hosts|quiet|model|routing|all] [on|off|reset] [--project|--user] · /mods forget-project'
143
144// `/mods`, `/mods git off`, `/mods all on --project`, `/mods routing reset`.
145export function parseModsArgs(args: string): ModsCommand {
146  const words = args.trim().toLowerCase().split(/\s+/).filter(word => word.length > 0)
147  if (words.length === 0) return { kind: 'open' }
148  if (words[0] === 'forget-project') return { kind: 'forget-project' }
149
150  let scope: ModScope | null = null
151  let value: boolean | undefined | 'toggle' = 'toggle'
152  const ids: ModId[] = []
153  for (const word of words) {
154    const bare = word.replace(/^--/, '')
155    if (bare === 'project' || bare === 'user') scope = bare
156    else if (bare === 'on' || bare === 'off') value = bare === 'on'
157    else if (bare === 'reset') value = undefined
158    else if (bare === 'all') ids.push(...MOD_IDS)
159    else {
160      const id = findMod(bare)
161      if (id === null) return { kind: 'error', text: `Unknown mod "${word}". ${MODS_USAGE}` }
162      ids.push(id)
163    }
164  }
165  if (ids.length === 0) return { kind: 'error', text: `Name a mod. ${MODS_USAGE}` }
166
167  return { kind: 'set', ids: [...new Set(ids)], value, scope }
168}
169
170// Where a choice goes when the command names no scope: this project if it
171// already has a choice for that mod (so the change takes effect), else you.
172export function defaultScope(settings: ModSettings, id: ModId): ModScope {
173  return settings.project[id] !== undefined ? 'project' : 'user'
174}
175
176export function summary(options: Options, settings: ModSettings): string {
177  const now = effective(options, settings)
178  const on = MOD_IDS.filter(id => now[id]).map(id => MODS[id].short)
179  const off = MOD_IDS.filter(id => !now[id]).map(id => MODS[id].short)
180  return [on.length > 0 ? `${on.join(' · ')} on` : '', off.length > 0 ? `${off.join(' · ')} off` : '']
181    .filter(part => part.length > 0)
182    .join(', ')
183}
184
mods/lib/model-preset.ts 8 lines
1export function projectKey(root: string) {
2  return `model:${root.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()}`
3}
4
5export function projectName(root: string) {
6  return root.replace(/\\/g, '/').replace(/\/+$/, '').split('/').pop() ?? root
7}
8
mods/lib/prompt-routing.ts 205 lines
1import type { RoutedSkill, RoutingTurn, RoutingView } from '../types'
2import { SKILL_ROUTES } from './skill-routes.generated'
3import type { SkillRoute } from './skill-routes.generated'
4
5// Reads a prompt's wording the way skill-router's tables do: which Topia
6// skills its words point at, and where in the text. A keyword is 3 points a
7// word (as the intent-router hook scores a word; "unit test" says more than
8// "test"), an L1 orchestrator 1 more, and a skill named outright
9// (/topia-debug, topia:debug) wins.
10
11export const MAX_SKILLS = 3
12// Past this a paste is not read further: the band is a hint, not a parser.
13export const MAX_CHARS = 8000
14
15const MIN_SCORE = 3
16const KEYWORD_SCORE = 3
17const EXPLICIT_SCORE = 100
18
19export type RouteMatch = { start: number; end: number; keyword: string }
20export type ScoredSkill = RoutedSkill & { score: number; matches: RouteMatch[] }
21export type Prediction = { skills: ScoredSkill[]; chain: string[] }
22
23const BY_NAME = new Map<string, SkillRoute>(SKILL_ROUTES.map(route => [route.name, route]))
24
25function escapeRegExp(text: string): string {
26  return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
27}
28
29// Whole words only, so "ui" never matches inside "build" nor "add" inside
30// "address"; the words of a phrase may be split by any spaces, and a word
31// may take a plain ending (tests, fixed, adding).
32function keywordPattern(keyword: string): RegExp {
33  const words = keyword.trim().split(/\s+/).map(escapeRegExp).join('\\s+')
34  const suffix = /[a-z]$/i.test(keyword) ? '(?:s|es|ed|d|ing)?' : ''
35  return new RegExp(`(?<![\\w-])${words}${suffix}(?![\\w-])`, 'gi')
36}
37
38const PATTERNS = SKILL_ROUTES.flatMap(route =>
39  route.keywords.map(keyword => ({ name: route.name, keyword, pattern: keywordPattern(keyword) })),
40)
41
42const EXPLICIT = /(?:\/topia[-:]|\/topia\s+|(?<![\w-])topia:)([a-z][\w-]*)/gi
43
44function layerRank(name: string): number {
45  return Number(BY_NAME.get(name)?.layer.replace(/\D/g, '') || 9)
46}
47
48// Within one skill the longest of overlapping matches wins: "unit test" is
49// one match, not "unit test" and "test".
50function dropOverlaps(matches: RouteMatch[]): RouteMatch[] {
51  const sorted = [...matches].sort((a, b) => a.start - b.start || b.end - a.end)
52  const kept: RouteMatch[] = []
53  for (const match of sorted) {
54    const last = kept[kept.length - 1]
55    if (last === undefined || match.start >= last.end) kept.push(match)
56  }
57  return kept
58}
59
60export function predict(text: string): Prediction {
61  const read = text.slice(0, MAX_CHARS)
62  const found = new Map<string, { matches: RouteMatch[]; isExplicit: boolean }>()
63  const entry = (name: string) => {
64    let one = found.get(name)
65    if (one === undefined) {
66      one = { matches: [], isExplicit: false }
67      found.set(name, one)
68    }
69    return one
70  }
71
72  for (const hit of read.matchAll(EXPLICIT)) {
73    const name = (hit[1] ?? '').toLowerCase()
74    if (!BY_NAME.has(name) || hit.index === undefined) continue
75    const one = entry(name)
76    one.isExplicit = true
77    one.matches.push({ start: hit.index, end: hit.index + hit[0].length, keyword: `topia:${name}` })
78  }
79
80  for (const { name, keyword, pattern } of PATTERNS) {
81    pattern.lastIndex = 0
82    for (const hit of read.matchAll(pattern)) {
83      if (hit.index === undefined) continue
84      entry(name).matches.push({ start: hit.index, end: hit.index + hit[0].length, keyword })
85    }
86  }
87
88  const scored: ScoredSkill[] = []
89  for (const [name, one] of found) {
90    const matches = dropOverlaps(one.matches)
91    const keywords = [...new Set(matches.map(match => match.keyword))]
92    // Each keyword counts once, so "fix it, fix it" does not outrank a
93    // prompt that says two different things.
94    const words = keywords.reduce((sum, keyword) => sum + keyword.split(/\s+/).length, 0)
95    let score = one.isExplicit ? EXPLICIT_SCORE : words * KEYWORD_SCORE
96    if (score > 0 && BY_NAME.get(name)?.layer === 'L1') score += 1
97    if (score >= MIN_SCORE) scored.push({ name, keywords, isExplicit: one.isExplicit, score, matches })
98  }
99
100  scored.sort((a, b) => b.score - a.score || layerRank(a.name) - layerRank(b.name) || a.name.localeCompare(b.name))
101  const skills = scored.slice(0, MAX_SKILLS)
102  const shown = new Set(skills.map(skill => skill.name))
103  const top = skills[0]
104  const chain = top === undefined ? [] : (BY_NAME.get(top.name)?.chain ?? []).filter(name => !shown.has(name))
105
106  return { skills, chain }
107}
108
109// What the band and the turn keep: names and keywords, never offsets or text.
110export function toView(prediction: Prediction): RoutingView | null {
111  if (prediction.skills.length === 0) return null
112  return {
113    skills: prediction.skills.map(({ name, keywords, isExplicit }) => ({ name, keywords, isExplicit })),
114    chain: prediction.chain,
115  }
116}
117
118export function viewKey(view: RoutingView | null): string {
119  return view === null ? '' : JSON.stringify(view)
120}
121
122// One painted run per matched span, in the color of the highest-ranked skill
123// that claims it.
124export const SKILL_COLORS = ['cyan', 'magenta', 'yellow'] as const
125export type SkillColor = (typeof SKILL_COLORS)[number]
126export type Run = { start: number; end: number; color: SkillColor; underline: true }
127
128export function skillColor(index: number): SkillColor {
129  return SKILL_COLORS[index % SKILL_COLORS.length] ?? 'cyan'
130}
131
132export function decorations(prediction: Prediction): Run[] {
133  const runs: Run[] = []
134  prediction.skills.forEach((skill, index) => {
135    const color = skillColor(index)
136    for (const match of skill.matches) {
137      const isTaken = runs.some(run => match.start < run.end && run.start < match.end)
138      if (!isTaken) runs.push({ start: match.start, end: match.end, color, underline: true })
139    }
140  })
141  return runs.sort((a, b) => a.start - b.start)
142}
143
144// The note the model reads beside the prompt (never shown to the person).
145export function contextText(view: RoutingView): string {
146  const parts = view.skills.map(skill =>
147    skill.isExplicit
148      ? `topia:${skill.name} (named outright)`
149      : `topia:${skill.name} (${skill.keywords.map(keyword => `"${keyword}"`).join(', ')})`,
150  )
151  const lead = view.skills[0]?.name
152  const chain = lead !== undefined && view.chain.length > 0 ? ` Usual hand-offs after topia:${lead}: ${view.chain.join(' → ')}.` : ''
153  return (
154    `[topia prompt-routing] The wording of this prompt points at ${parts.join(', ')}.${chain} ` +
155    'This is a keyword reading shown to the user in a band above the prompt; skill-router still decides the route.'
156  )
157}
158
159// A skill the turn ran, from the Skill tool or a slash command (`topia:build`,
160// `topia:topia-build` for the /topia-build alias) or a Topia subagent type.
161export function ranSkill(id: string | undefined): string | null {
162  if (id === undefined || !id.startsWith('topia:')) return null
163  const name = id.slice('topia:'.length).replace(/^topia-/, '')
164  return BY_NAME.has(name) ? name : null
165}
166
167// A prompt the person wrote: typed, sent from a phone or the SDK, or put in
168// as their own words by a plugin (the git band's Commit). Not a notification,
169// a peer's message or a scheduled task's.
170export function isWritten(origin: { kind: string; asUser?: true }): boolean {
171  return ['composer', 'bridge', 'sdk'].includes(origin.kind) || (origin.kind === 'plugin' && origin.asUser === true)
172}
173
174export function startTurn(view: RoutingView): RoutingTurn {
175  return { predicted: view.skills.map(skill => skill.name), chain: view.chain, ran: [], isDone: false }
176}
177
178export function compare(turn: RoutingTurn): { hit: string[]; missed: string[]; chained: string[]; extra: string[] } {
179  const ran = new Set(turn.ran)
180  const predicted = new Set(turn.predicted)
181  const chain = new Set(turn.chain)
182  return {
183    hit: turn.predicted.filter(name => ran.has(name)),
184    missed: turn.predicted.filter(name => !ran.has(name)),
185    chained: turn.ran.filter(name => !predicted.has(name) && chain.has(name)),
186    extra: turn.ran.filter(name => !predicted.has(name) && !chain.has(name)),
187  }
188}
189
190export function describeSkill(name: string, max = 220): string {
191  const text = BY_NAME.get(name)?.description ?? ''
192  return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text
193}
194
195// The intent-router hook (hooks/intent-router) prints the same reading for
196// hosts without this module. Where the module runs, the band and the hint
197// stand in for it, and its block is dropped so the model reads it once.
198const ROUTER_HEAD = '🧭 [Topia intent-router]'
199const ROUTER_BLOCK = /\n*🧭 \[Topia intent-router\][^\n]*(?:\n {3}[^\n]*)*\n*/g
200
201export function withoutRouterSuggestion(text: string): string {
202  if (!text.includes(ROUTER_HEAD)) return text
203  return text.replace(ROUTER_BLOCK, '\n').replace(/\n{3,}/g, '\n\n').trim()
204}
205
mods/lib/remote-hosts.ts 105 lines
1import type { Host, SshTarget } from '../types'
2
3// ssh options that take a value (`-i key`, or glued: `-p22`, `-oBatchMode=yes`).
4const VALUE_OPTS = new Set('BbcDEeFIiJLlmOoPpQRSWw'.split(''))
5export const FAILED = /Permission denied \(|Could not resolve hostname|Connection (timed out|refused|closed)|Host key verification failed|No route to host/i
6
7function tokenize(segment: string): string[] {
8  const tokens: string[] = []
9  for (const match of segment.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)) {
10    tokens.push(match[1] ?? match[2] ?? match[3] ?? '')
11  }
12  return tokens
13}
14
15// Every `ssh … destination [command]` in a shell command line.
16export function parseSsh(command: string): SshTarget[] {
17  const targets: SshTarget[] = []
18  for (const segment of command.split(/\r?\n|;|&&|\|\||(?<![|])\|(?![|])/)) {
19    const tokens = tokenize(segment)
20    const start = tokens.findIndex(token => /(^|[\\/])ssh(\.exe)?$/i.test(token))
21    if (start < 0) continue
22
23    let key: string | undefined
24    let port: string | undefined
25    let user: string | undefined
26    let index = start + 1
27    for (; index < tokens.length; index++) {
28      const token = tokens[index] ?? ''
29      if (!token.startsWith('-') || token === '-') break
30      const flag = token[1] ?? ''
31      if (!VALUE_OPTS.has(flag)) continue
32      const value = token.length > 2 ? token.slice(2) : tokens[++index] ?? ''
33      if (flag === 'i') key = value
34      if (flag === 'p') port = value
35      if (flag === 'l') user = value
36      if (flag === 'o' && /^user=/i.test(value)) user = value.slice(5)
37      if (flag === 'o' && /^port=/i.test(value)) port = value.slice(5)
38    }
39
40    const destination = (tokens[index] ?? '').replace(/^ssh:\/\//, '')
41    if (!destination || /[$`{}<>]/.test(destination)) continue
42    const at = destination.lastIndexOf('@')
43    const hostPort = at >= 0 ? destination.slice(at + 1) : destination
44    if (at >= 0) user = destination.slice(0, at)
45    const [host = '', glued] = hostPort.split(':')
46    if (!/^[A-Za-z0-9][A-Za-z0-9.\-]*$/.test(host)) continue
47    targets.push({ host, user, key, port: glued ?? port, remote: tokens.slice(index + 1).join(' ') })
48  }
49  return targets
50}
51
52// Hosts stay with the project they were learned in: one store key per
53// project root, so another repo never sees them.
54export function hostsKey(root: string) {
55  return `hosts:${root.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()}`
56}
57
58export function hostId(target: { host: string; user?: string }) {
59  return target.user ? `${target.user}@${target.host}` : target.host
60}
61
62export function composeText(known: Record<string, Host>): string | null {
63  const list = Object.entries(known)
64    .sort(([, a], [, b]) => b.lastOk.localeCompare(a.lastOk))
65    .slice(0, 15)
66  if (list.length === 0) return null
67
68  return [
69    '# Known SSH hosts',
70    'Learned from ssh commands that worked in earlier sessions of this project. Connect with these directly; do not ask the user ' +
71      'for connection details or run probe connections first. If one fails, say so and ask before guessing another.',
72    ...list.map(([id, h]) => {
73      const parts = [
74        `ssh${h.key ? ` -i "${h.key}"` : ''}${h.port ? ` -p ${h.port}` : ''} ${id}`,
75        h.sudoOk ? 'sudo worked non-interactively' : 'sudo untested',
76        `last worked ${h.lastOk}`,
77      ]
78      return `- ${parts.join(' — ')}`
79    }),
80  ].join('\n')
81}
82
83// Folds ssh targets that just worked into the known hosts; returns the new
84// map and the ids seen for the first time.
85export function learnHosts(known: Record<string, Host>, targets: SshTarget[], today: string) {
86  const next = { ...known }
87  const learned: string[] = []
88  for (const target of targets) {
89    const id = hostId(target)
90    const before = next[id]
91    if (!before) learned.push(id)
92    next[id] = {
93      host: target.host,
94      user: target.user,
95      key: target.key ?? before?.key,
96      port: target.port ?? before?.port,
97      sudoOk: (before?.sudoOk ?? false) || /\bsudo\b/.test(target.remote),
98      uses: (before?.uses ?? 0) + 1,
99      firstSeen: before?.firstSeen ?? today,
100      lastOk: today,
101    }
102  }
103  return { known: next, learned }
104}
105
mods/lib/standing-orders.ts 57 lines
1import type { OrderId, Orders } from '../types'
2
3// Off until the user turns one on with /orders: these change how the model works.
4export const DEFAULTS: Orders = { fanout: false, ledger: false, scripts: false, commit: false }
5
6export const RULES: Record<OrderId, { label: string; text: string }> = {
7  fanout: {
8    label: 'Fan out independent work to parallel subagents',
9    text:
10      'When work splits into independent parts (several files, modules, features or investigations), ' +
11      'fan it out to parallel subagents instead of working through it serially. Keep shared decisions ' +
12      'and the final integration in the main thread.',
13  },
14  ledger: {
15    label: 'End tasks with a skipped / deferred ledger',
16    text:
17      'End every task that changes code or docs with a short "Skipped / deferred" list: each item not done, ' +
18      'why, and the file path where it is recorded for later. Record deferred items in the project\'s existing ' +
19      'TODO or plan doc (create docs/TODO.md if there is none). If nothing was skipped, say so in one line.',
20  },
21  scripts: {
22    label: 'Hand-offs are one logged script with yes/no confirms',
23    text:
24      'When the user has to run something themselves (another machine, a server, an install), hand it over ' +
25      'as one script, not steps to copy and paste. The script says up front what it will do, prints clear ' +
26      'progress, writes a timestamped log file and prints its path so the user can hand it back for review, ' +
27      'and asks for an explicit yes/no before anything destructive.',
28  },
29  commit: {
30    label: 'Commit and push when a task is done',
31    text:
32      'When a task is finished and its checks pass, commit the changes with a descriptive message and push ' +
33      'to the current branch\'s remote, unless the user said not to.',
34  },
35}
36
37export const IDS = Object.keys(RULES) as OrderId[]
38
39export function ordersKey(root: string) {
40  return `orders:${root.replace(/\\/g, '/').toLowerCase()}`
41}
42
43export function ordersStatus(current: Orders): string | undefined {
44  const on = IDS.filter(id => current[id])
45  return on.length > 0 ? `orders: ${on.join('·')}` : undefined
46}
47
48export function composeText(current: Orders): string | null {
49  const on = IDS.filter(id => current[id])
50  if (on.length === 0) return null
51  return [
52    '# Standing orders from the user',
53    'The user has asked for these in every session of this project; follow them without being asked again.',
54    ...on.map(id => `- ${RULES[id].text}`),
55  ].join('\n')
56}
57
mods/lib/status.ts 10 lines
1// A plugin has one status line, so each mod owns a slot in it, joined in a
2// fixed order.
3export const STATUS_SLOTS = ['orders', 'usage'] as const
4export type StatusSlot = (typeof STATUS_SLOTS)[number]
5
6export function joinStatus(current: Partial<Record<StatusSlot, string>>): string | undefined {
7  const text = STATUS_SLOTS.map(slot => current[slot] ?? '').filter(part => part.length > 0).join(' · ')
8  return text.length > 0 ? text : undefined
9}
10
mods/lib/topia-quiet.ts 35 lines
1import type { HiddenReport, UsageLine } from '../types'
2
3// The blocks Topia's settings hooks print (hooks/session-start/index.cjs,
4// hooks/lib/session-report.cjs, compiler/commands/hook-dispatch.js).
5const RUNE_BLOCK = /\n?=== topia: Rune migration recommended ===[\s\S]*?migrate-from-rune --skip\n*/
6const INSTALL_MENU = /\n?\s*╭─+╮\s*\n\s*│\s*Topia Step 1 done[\s\S]*?auto-checks itself the next session\.\)\n*/
7const SESSION_REPORT = /<summary>Session activity<\/summary>|^Topia · \d+ skills? · /m
8const GUARDIAN = /^\s*Topia-hook: [\w:-]+ \[advisory\] — tool=\S+\s*$/
9
10export type Filtered = { text: string | null; kind: HiddenReport['kind'] } | null
11
12// What the model should read instead of a settings hook's text; null when
13// the text is none of Topia's noise and passes through unchanged.
14export function filterHookText(text: string): Filtered {
15  if (SESSION_REPORT.test(text)) return { text: null, kind: 'session-report' }
16  if (GUARDIAN.test(text)) return { text: null, kind: 'guardian-advisory' }
17
18  const stripped = text.replace(RUNE_BLOCK, '\n').replace(INSTALL_MENU, '\n')
19  if (stripped === text) return null
20
21  const kept = stripped.replace(/\n{3,}/g, '\n\n').trim()
22  return { text: kept.length > 0 ? kept : null, kind: 'install-banner' }
23}
24
25export function formatUsage(line: UsageLine, saved: number): string {
26  const parts = [
27    line.contextPercent !== undefined ? `ctx ${Math.round(line.contextPercent)}%` : '',
28    line.cachePercent !== undefined ? `cache ${Math.round(line.cachePercent)}%` : '',
29    line.usd !== undefined ? `$${line.usd.toFixed(2)}` : '',
30    line.fiveHourPercent !== undefined ? `5h ${Math.round(line.fiveHourPercent)}%` : '',
31    saved > 0 ? `topia −${(saved / 1000).toFixed(1)}k chars` : '',
32  ]
33  return parts.filter(part => part.length > 0).join(' · ')
34}
35
mods/lib/value-help.ts 78 lines
1import type { GitInfo, UsageLine } from '../types'
2
3// What each value the mods draw means, in a line: shown at the end of its row
4// while the pointer rests on it, and under the band while it holds the focus.
5
6export type Part = { key: string; text: string; about: string }
7
8export const GIT_ABOUT = {
9  branch: 'The branch checked out in this folder.',
10  changed: 'Files with changes not yet committed, new untracked files included.',
11  unpushed: 'Commits on this branch that its upstream does not have yet.',
12  behind: 'Commits on the upstream that you have not pulled.',
13  upstream: 'This branch tracks no remote branch, so nothing counts as unpushed; git push -u sets one.',
14  commit: 'Asks Claude to commit the current changes with a descriptive message.',
15  commitPush: 'Asks Claude to commit the current changes, then push them.',
16  push: 'Asks Claude to push the unpushed commits.',
17  hide: 'Hides this row until the session ends; /mods git off turns it off for good.',
18} as const
19
20export function gitParts(git: GitInfo): Part[] {
21  const parts: Part[] = [{ key: 'git-branch', text: `⎇ ${git.branch}`, about: GIT_ABOUT.branch }]
22  if (git.changed > 0) parts.push({ key: 'git-changed', text: `${git.changed} changed`, about: GIT_ABOUT.changed })
23  if (git.unpushed > 0) parts.push({ key: 'git-unpushed', text: `${git.unpushed} unpushed`, about: GIT_ABOUT.unpushed })
24  if (git.behind > 0) parts.push({ key: 'git-behind', text: `${git.behind} behind`, about: GIT_ABOUT.behind })
25  if (!git.hasUpstream) parts.push({ key: 'git-upstream', text: 'no upstream', about: GIT_ABOUT.upstream })
26  return parts
27}
28
29export const ROUTING_ABOUT = {
30  chain: 'The skills the lead skill usually hands off to next.',
31  hide: 'Hides this row until the session ends; /routing off (or /mods routing off) turns it off for good.',
32  hit: 'Predicted from your wording, and it ran this turn.',
33  missed: 'Predicted from your wording, but it did not run this turn.',
34  chained: 'Ran this turn as one of the lead skill’s usual hand-offs.',
35  extra: 'Ran this turn without being predicted from your wording.',
36} as const
37
38// The status line is plain text and takes no pointer or focus, so its items
39// are explained in the /mods and /topia-activity panes.
40export function usageParts(line: UsageLine | null, savedChars: number): Part[] {
41  const parts: Part[] = []
42  if (line?.contextPercent !== undefined) {
43    parts.push({ key: 'usage-ctx', text: `ctx ${Math.round(line.contextPercent)}%`, about: "How full the model's context window is." })
44  }
45  if (line?.cachePercent !== undefined) {
46    parts.push({
47      key: 'usage-cache',
48      text: `cache ${Math.round(line.cachePercent)}%`,
49      about: "The share of the last turn's input read from the prompt cache: cheaper and faster.",
50    })
51  }
52  if (line?.usd !== undefined) {
53    parts.push({ key: 'usage-usd', text: `$${line.usd.toFixed(2)}`, about: 'The estimated cost of this session so far.' })
54  }
55  if (line?.fiveHourPercent !== undefined) {
56    parts.push({
57      key: 'usage-5h',
58      text: `5h ${Math.round(line.fiveHourPercent)}%`,
59      about: 'How much of your five-hour usage limit is used.',
60    })
61  }
62  if (savedChars > 0) {
63    parts.push({
64      key: 'usage-saved',
65      text: `topia −${(savedChars / 1000).toFixed(1)}k chars`,
66      about: "Topia hook text kept out of the model's context this session (/topia-activity).",
67    })
68  }
69  return parts
70}
71
72export const ORDERS_STATUS_ABOUT = 'The standing orders on in this project (/orders).'
73
74// A hover group's name: 1 to 64 characters.
75export function scopeOf(key: string): string {
76  return `topia-about-${key}`.slice(0, 64)
77}
78
mods/lib/skill-routes.generated.ts 1078 lines
1// AUTO-GENERATED by compiler/commands/generate-slash-aliases.js from skills/*/SKILL.md
2// and compiler/lib/intent-keywords.js. Do not edit by hand. Regenerate: npm run generate:slash-aliases
3
4export type SkillRoute = {
5  name: string
6  layer: string
7  model: string
8  description: string
9  userInvocable: boolean
10  keywords: readonly string[]
11  chain: readonly string[]
12}
13
14export const SKILL_ROUTES: readonly SkillRoute[] = [
15  {
16    "name": "adversary",
17    "layer": "L2",
18    "model": "opus",
19    "description": "Pre-implementation red-team analysis. Use when a plan is high-risk, critical path, or expensive to reverse. Challenges plans before code is written — finds edge cases, security holes, scalability bottlenecks, error propagation risks, and integration conflicts. Catches flaws at plan time (10x cheaper than post-implementation).",
20    "userInvocable": true,
21    "keywords": [
22      "red team",
23      "challenge",
24      "stress test",
25      "edge case",
26      "poke holes"
27    ],
28    "chain": [
29      "documentation",
30      "build"
31    ]
32  },
33  {
34    "name": "architecture-mapper",
35    "layer": "L2",
36    "model": "opus",
37    "description": "Reverse-engineer an unfamiliar or legacy codebase into a drillable, cross-linked architecture knowledge base — per repo or across a polyrepo. Use to map how a system starts, wires together, and flows; or to refresh those docs after code changes. Read-mostly: writes only under docs/, never application code.",
38    "userInvocable": true,
39    "keywords": [
40      "architecture map",
41      "map the architecture",
42      "map the codebase",
43      "how the system starts"
44    ],
45    "chain": []
46  },
47  {
48    "name": "asset-creator",
49    "layer": "L3",
50    "model": "sonnet",
51    "description": "Creates code-based visual assets — SVG icons, OG image HTML templates, social banners, and icon sets. Outputs files with usage instructions.",
52    "userInvocable": true,
53    "keywords": [
54      "svg",
55      "icon",
56      "og image",
57      "banner",
58      "favicon"
59    ],
60    "chain": []
61  },
62  {
63    "name": "audit",
64    "layer": "L2",
65    "model": "sonnet",
66    "description": "Comprehensive project audit — security, dependencies, code quality, architecture, performance, infra, docs, and nexus analytics. Delegates to specialist skills and generates an 8-dimension health score.",
67    "userInvocable": true,
68    "keywords": [
69      "audit",
70      "health check",
71      "project assessment",
72      "codebase review"
73    ],
74    "chain": []
75  },
76  {
77    "name": "autopsy",
78    "layer": "L2",
79    "model": "opus",
80    "description": "Full codebase health assessment. Use when diagnosing project health or starting a rescue workflow on legacy code. Analyzes complexity, dependencies, dead code, tech debt, and git hotspots. Produces a health score and rescue plan.",
81    "userInvocable": true,
82    "keywords": [
83      "autopsy",
84      "health score",
85      "tech debt",
86      "codebase health"
87    ],
88    "chain": [
89      "safeguard",
90      "surgeon"
91    ]
92  },
93  {
94    "name": "brainstorm",
95    "layer": "L2",
96    "model": "opus",
97    "description": "Creative ideation and solution exploration. Generates multiple approaches with trade-offs, uses structured frameworks (SCAMPER, First Principles), and hands off to plan for structuring.",
98    "userInvocable": true,
99    "keywords": [
100      "brainstorm",
101      "ideas",
102      "alternatives",
103      "approaches",
104      "options"
105    ],
106    "chain": [
107      "plan"
108    ]
109  },
110  {
111    "name": "browser-pilot",
112    "layer": "L3",
113    "model": "sonnet",
114    "description": "Playwright browser automation. Navigates URLs, takes screenshots, checks accessibility tree, interacts with UI elements, and reports findings.",
115    "userInvocable": true,
116    "keywords": [
117      "browser",
118      "screenshot",
119      "playwright",
120      "click through",
121      "accessibility tree"
122    ],
123    "chain": []
124  },
125  {
126    "name": "build",
127    "layer": "L1",
128    "model": "sonnet",
129    "description": "Feature implementation orchestrator. ALWAYS use this skill for ANY code change — implement, build, add feature, create, fix bug, or any task that modifies source code. This is the default route for 70% of all requests. Runs full TDD cycle: understand → plan → test → implement → quality → verify → commit.",
130    "userInvocable": true,
131    "keywords": [
132      "implement",
133      "build",
134      "create",
135      "add",
136      "feature",
137      "fix",
138      "write",
139      "make",
140      "develop"
141    ],
142    "chain": [
143      "plan",
144      "test",
145      "fix",
146      "readiness",
147      "guardian",
148      "review",
149      "completion-gate",
150      "verification"
151    ]
152  },
153  {
154    "name": "completion-gate",
155    "layer": "L3",
156    "model": "haiku",
157    "description": "Validates agent claims against evidence trail. Use when verifying an agent has actually done what it claims — auto-fires at workflow end. Catches 'done' without proof, 'tests pass' without output, 'fixed' without verification. Called by build and team.",
158    "userInvocable": false,
159    "keywords": [],
160    "chain": []
161  },
162  {
163    "name": "constraint-check",
164    "layer": "L3",
165    "model": "haiku",
166    "description": "Meta-validator for HARD-GATEs. Use when auditing whether a skill's mandatory constraints were actually followed during a workflow (not just claimed). Called by build, team, and audit for discipline compliance.",
167    "userInvocable": false,
168    "keywords": [],
169    "chain": []
170  },
171  {
172    "name": "context-engine",
173    "layer": "L3",
174    "model": "haiku",
175    "description": "Context window management. Auto-triggered when context is filling up. Triggers smart compaction and preserves critical information across compaction boundaries. Called by L1 orchestrators at context thresholds.",
176    "userInvocable": false,
177    "keywords": [],
178    "chain": []
179  },
180  {
181    "name": "context-lifecycle",
182    "layer": "L3",
183    "model": "haiku",
184    "description": "Automated context boundary orchestration. Runs at phase ends, pre/post-compact, and after git push. Chunks work across sessions via session-bridge, context-pack, and neural-memory without losing continuity.",
185    "userInvocable": true,
186    "keywords": [
187      "compaction",
188      "context window"
189    ],
190    "chain": []
191  },
192  {
193    "name": "context-pack",
194    "layer": "L3",
195    "model": "haiku",
196    "description": "Creates structured handoff briefings between agents. Use when delegating complex work to subagents that would otherwise lose context. Packages task context, constraints, and progress into a compact packet that subagents can consume without re-reading the full conversation. Prevents the 'lost context' problem in multi-agent delegation.",
197    "userInvocable": false,
198    "keywords": [],
199    "chain": []
200  },
201  {
202    "name": "db",
203    "layer": "L2",
204    "model": "sonnet",
205    "description": "Database workflow specialist. Generates migration files with rollback scripts, detects breaking schema changes, and validates query parameterization.",
206    "userInvocable": true,
207    "keywords": [
208      "database",
209      "migration",
210      "schema",
211      "sql",
212      "sql query",
213      "database index"
214    ],
215    "chain": []
216  },
217  {
218    "name": "debug",
219    "layer": "L2",
220    "model": "sonnet",
221    "description": "Root cause analysis for bugs and unexpected behavior. Traces errors through code, uses structured reasoning, and hands off to fix when cause is found. Core of the debug↔fix chain.",
222    "userInvocable": true,
223    "keywords": [
224      "debug",
225      "error",
226      "bug",
227      "broken",
228      "trace",
229      "diagnose",
230      "crash",
231      "fail",
232      "not working",
233      "stack trace"
234    ],
235    "chain": [
236      "fix",
237      "test"
238    ]
239  },
240  {
241    "name": "dependency-doctor",
242    "layer": "L3",
243    "model": "haiku",
244    "description": "Dependency health management. Detects package manager, checks outdated packages and vulnerabilities, and produces a prioritized update plan.",
245    "userInvocable": true,
246    "keywords": [
247      "dependencies",
248      "outdated packages",
249      "npm audit",
250      "cve",
251      "upgrade packages"
252    ],
253    "chain": []
254  },
255  {
256    "name": "deploy",
257    "layer": "L2",
258    "model": "sonnet",
259    "description": "Deploy application to target platform. Use when user explicitly says 'deploy', 'push to production', 'ship it'. Handles Vercel, Netlify, AWS, GCP, DigitalOcean, and VPS with pre-deploy verification and health checks.",
260    "userInvocable": true,
261    "keywords": [
262      "deploy",
263      "ci/cd",
264      "pipeline",
265      "kubernetes",
266      "docker",
267      "vercel",
268      "netlify"
269    ],
270    "chain": [
271      "watchdog"
272    ]
273  },
274  {
275    "name": "design",
276    "layer": "L2",
277    "model": "sonnet",
278    "description": "Design system reasoning. Maps product domain to style, palette, typography, and platform-specific patterns. Generates .topia/design-system.md as the shared design contract for all UI-generating skills.",
279    "userInvocable": true,
280    "keywords": [
281      "ui",
282      "ux",
283      "design",
284      "layout",
285      "component design",
286      "wireframe",
287      "palette",
288      "typography"
289    ],
290    "chain": []
291  },
292  {
293    "name": "doc-processor",
294    "layer": "L3",
295    "model": "sonnet",
296    "description": "Generate and parse office documents — PDF, DOCX, XLSX, PPTX, CSV. Use when creating reports, exporting tabular data, or processing uploaded office files. NOT for project documentation (use docs).",
297    "userInvocable": true,
298    "keywords": [
299      "pdf",
300      "docx",
301      "xlsx",
302      "pptx",
303      "spreadsheet",
304      "csv"
305    ],
306    "chain": []
307  },
308  {
309    "name": "docs",
310    "layer": "L2",
311    "model": "sonnet",
312    "description": "Auto-generate and maintain project documentation. Creates README, API docs, architecture docs, changelogs, and keeps them in sync with code changes. The \\\"docs are never outdated\\\" skill.",
313    "userInvocable": true,
314    "keywords": [
315      "document",
316      "readme",
317      "api docs",
318      "changelog"
319    ],
320    "chain": []
321  },
322  {
323    "name": "docs-seeker",
324    "layer": "L3",
325    "model": "haiku",
326    "description": "Find documentation for APIs, libraries, and error messages. Looks up official docs, changelog entries, and migration guides.",
327    "userInvocable": true,
328    "keywords": [
329      "api reference",
330      "library docs",
331      "method signature",
332      "deprecated"
333    ],
334    "chain": []
335  },
336  {
337    "name": "documentation",
338    "layer": "L2",
339    "model": "sonnet",
340    "description": "Leadership-ready package generator. Produces feature folders, requirements, user stories, and Jira-compliant CSV tickets. Use after /topia plan and before /topia build to get stakeholder approval.",
341    "userInvocable": true,
342    "keywords": [
343      "jira",
344      "leadership package",
345      "stakeholder approval",
346      "tickets"
347    ],
348    "chain": [
349      "build"
350    ]
351  },
352  {
353    "name": "faq",
354    "layer": "L3",
355    "model": "haiku",
356    "description": "Lists Topia's HTML entry points (docs, guides, skill index, nexus diagram, live visualizer) with one-shot open-in-browser commands. Use when the user asks 'where are the docs?', 'how do I see the skill graph?', or `/topia:faq`.",
357    "userInvocable": true,
358    "keywords": [
359      "faq",
360      "where are the docs",
361      "skill graph"
362    ],
363    "chain": []
364  },
365  {
366    "name": "fix",
367    "layer": "L2",
368    "model": "sonnet",
369    "description": "Apply code changes and fixes. Writes implementation code, applies bug fixes, and verifies changes with tests. Core action hub in the Topia nexus.",
370    "userInvocable": true,
371    "keywords": [
372      "fix",
373      "patch",
374      "hotfix",
375      "resolve",
376      "repair"
377    ],
378    "chain": [
379      "test",
380      "readiness"
381    ]
382  },
383  {
384    "name": "git",
385    "layer": "L3",
386    "model": "haiku",
387    "description": "Specialized git operations — semantic commits, PR descriptions, branch management, conflict resolution guidance. Replaces ad-hoc git commands with a dedicated, convention-aware utility.",
388    "userInvocable": true,
389    "keywords": [
390      "commit",
391      "pull request",
392      "pr",
393      "branch",
394      "rebase",
395      "merge conflict"
396    ],
397    "chain": []
398  },
399  {
400    "name": "guardian",
401    "layer": "L2",
402    "model": "sonnet",
403    "description": "Automated security gatekeeper. Blocks unsafe code before commit — secret scanning, OWASP top 10, dependency audit, permission checks. A GATE, not a suggestion.",
404    "userInvocable": true,
405    "keywords": [
406      "security",
407      "vulnerability",
408      "owasp",
409      "secret",
410      "audit security"
411    ],
412    "chain": [
413      "fix"
414    ]
415  },
416  {
417    "name": "guardian-env",
418    "layer": "L3",
419    "model": "haiku",
420    "description": "Environment-aware pre-flight check. Use when starting work in a new environment, switching machines, or when 'works on my machine' bugs surface. Validates OS, runtime versions, installed tools, port availability, env vars, and disk space BEFORE coding starts. Like sentinel but for the environment, not the code.",
421    "userInvocable": true,
422    "keywords": [
423      "environment check",
424      "works on my machine",
425      "env vars",
426      "port in use"
427    ],
428    "chain": []
429  },
430  {
431    "name": "hallucination-guard",
432    "layer": "L3",
433    "model": "haiku",
434    "description": "Verify AI-generated imports, API calls, and packages actually exist. Use when finishing AI-generated code that introduces new imports or external API calls — auto-fires after fix/build to catch phantom functions, non-existent packages, and slopsquatting attacks.",
435    "userInvocable": true,
436    "keywords": [
437      "hallucinated",
438      "phantom import",
439      "fake package",
440      "typosquat"
441    ],
442    "chain": []
443  },
444  {
445    "name": "idea",
446    "layer": "L2",
447    "model": "opus",
448    "description": "Idea Elicitation agent. Use when starting a new feature requiring requirements elicitation BEFORE plan or build. Asks probing questions, identifies hidden requirements, maps stakeholders, defines scope boundaries, and produces a structured Requirements Document that plan and build consume.",
449    "userInvocable": true,
450    "keywords": [
451      "requirements",
452      "business analysis",
453      "user stories",
454      "stakeholder"
455    ],
456    "chain": [
457      "plan"
458    ]
459  },
460  {
461    "name": "improve-architecture",
462    "layer": "L2",
463    "model": "opus",
464    "description": "Find architectural friction in a codebase and propose deepening opportunities. Use when user wants to improve architecture, find refactor candidates, consolidate shallow modules, or make a codebase more testable. Outputs scored proposals (depth/leverage/locality) that surgeon and review can consume.",
465    "userInvocable": true,
466    "keywords": [
467      "shallow module",
468      "deepen",
469      "coupling",
470      "testability",
471      "architecture improvement"
472    ],
473    "chain": []
474  },
475  {
476    "name": "incident",
477    "layer": "L2",
478    "model": "sonnet",
479    "description": "Structured incident response. Use when user reports an outage, production error, or says 'incident', 'something is down', 'users are affected'. Triage severity, contain blast radius, root-cause, document timeline, generate postmortem.",
480    "userInvocable": true,
481    "keywords": [
482      "incident",
483      "outage",
484      "downtime",
485      "postmortem",
486      "production is down"
487    ],
488    "chain": [
489      "debug",
490      "fix"
491    ]
492  },
493  {
494    "name": "integrate",
495    "layer": "L2",
496    "model": "sonnet",
497    "description": "Clone, port, or convert features from any GitHub repo into your project. Use when stealing patterns from external repos or porting proven code. Understand before copy, challenge before implement. 4 modes: port (rewrite), compare (analysis), copy (transplant), improve (copy + optimize).",
498    "userInvocable": true,
499    "keywords": [
500      "integrate",
501      "port from",
502      "port this",
503      "steal the",
504      "from that repo"
505    ],
506    "chain": []
507  },
508  {
509    "name": "integrity-check",
510    "layer": "L3",
511    "model": "haiku",
512    "description": "Verify integrity of persisted state, skill outputs, and context bus data. Use when validating .topia/ files or sub-agent outputs against prompt injection, memory poisoning, identity spoofing, or adversarial payloads. Called by sentinel, team, session-bridge.",
513    "userInvocable": false,
514    "keywords": [],
515    "chain": []
516  },
517  {
518    "name": "journal",
519    "layer": "L3",
520    "model": "haiku",
521    "description": "Persistent state tracking and Architecture Decision Records across sessions. Use when recording a decision, ADR, or progress that must survive session boundaries. Manages progress state, module health, dependency graphs, and ADRs for any workflow.",
522    "userInvocable": true,
523    "keywords": [
524      "adr",
525      "decision record",
526      "journal",
527      "log the decision"
528    ],
529    "chain": []
530  },
531  {
532    "name": "launch",
533    "layer": "L1",
534    "model": "sonnet",
535    "description": "Deploy + marketing orchestrator. Use when user says 'launch', 'ship to production', 'deploy and announce', or 'go live'. Runs the full pipeline — pre-flight tests, deployment, live verification, marketing asset creation, and announcement.",
536    "userInvocable": true,
537    "keywords": [
538      "deploy",
539      "launch",
540      "release",
541      "ship",
542      "publish",
543      "production"
544    ],
545    "chain": [
546      "verification",
547      "deploy",
548      "watchdog",
549      "marketing"
550    ]
551  },
552  {
553    "name": "logic-guardian",
554    "layer": "L2",
555    "model": "sonnet",
556    "description": "Protects complex business logic from accidental deletion or overwrite. Use when editing payment, trading, state-machine, or other load-bearing business logic where a single deleted line can cause silent data corruption. Maintains a logic manifest, enforces pre-edit gates, validates post-edit diffs.",
557    "userInvocable": true,
558    "keywords": [
559      "business logic",
560      "protect logic",
561      "critical path"
562    ],
563    "chain": []
564  },
565  {
566    "name": "marketing",
567    "layer": "L2",
568    "model": "sonnet",
569    "description": "Create marketing assets and execute launch strategy. Generates landing copy, social banners, SEO meta, blog posts, and video scripts.",
570    "userInvocable": true,
571    "keywords": [
572      "marketing",
573      "landing page",
574      "seo",
575      "social media",
576      "landing copy",
577      "marketing copy"
578    ],
579    "chain": []
580  },
581  {
582    "name": "mcp-builder",
583    "layer": "L2",
584    "model": "sonnet",
585    "description": "Build Model Context Protocol servers from specifications. Use when creating an MCP server for a tool, resource, or service that AI agents should access. Generates tool definitions, resource handlers, and test suites in TypeScript or Python (FastMCP).",
586    "userInvocable": true,
587    "keywords": [
588      "mcp",
589      "mcp server",
590      "tool server",
591      "model context"
592    ],
593    "chain": []
594  },
595  {
596    "name": "neural-memory",
597    "layer": "L3",
598    "model": "haiku",
599    "description": "Cross-session cognitive persistence via Neural Memory MCP. Captures decisions, patterns, errors, and insights with rich semantic links. Provides recall, hypothesis tracking, and evidence-based reasoning across projects.",
600    "userInvocable": true,
601    "keywords": [
602      "remember this",
603      "capture learning",
604      "neural memory"
605    ],
606    "chain": []
607  },
608  {
609    "name": "onboard",
610    "layer": "L2",
611    "model": "sonnet",
612    "description": "Auto-generate project context for AI sessions. Use when starting on a new repo for the first time, or when CLAUDE.md / .topia/ context is missing or stale. Scans codebase and creates the setup so every future session starts with full context.",
613    "userInvocable": true,
614    "keywords": [
615      "onboard",
616      "get started",
617      "configure project",
618      "claude.md"
619    ],
620    "chain": []
621  },
622  {
623    "name": "org-config",
624    "layer": "L2",
625    "model": "sonnet",
626    "description": "Team org policy setup for Topia. Use during /topia finalize or when configuring .topia/org/org.md — asks structured questions and writes team roles, policies, approval flows, and governance level so guardian and readiness enforce your rules.",
627    "userInvocable": true,
628    "keywords": [
629      "org config",
630      "team roles",
631      "governance",
632      "approval flow"
633    ],
634    "chain": []
635  },
636  {
637    "name": "perf",
638    "layer": "L2",
639    "model": "sonnet",
640    "description": "Performance regression gate. Detects N+1 queries, sync-in-async, missing indexes, memory leaks, and bundle bloat before they reach production.",
641    "userInvocable": true,
642    "keywords": [
643      "performance",
644      "slow",
645      "optimize",
646      "n+1",
647      "memory leak",
648      "bundle size"
649    ],
650    "chain": []
651  },
652  {
653    "name": "plan",
654    "layer": "L2",
655    "model": "opus",
656    "description": "Create structured implementation plans from requirements. Produces master plan + phase files for enterprise-scale project management. Master plan = overview (<80 lines). Phase files = execution detail (<150 lines each). Each session handles 1 phase. Uses opus for deep reasoning.",
657    "userInvocable": true,
658    "keywords": [
659      "plan",
660      "architect",
661      "design system",
662      "roadmap",
663      "strategy"
664    ],
665    "chain": [
666      "adversary",
667      "documentation",
668      "build"
669    ]
670  },
671  {
672    "name": "problem-solver",
673    "layer": "L3",
674    "model": "sonnet",
675    "description": "Structured reasoning frameworks for complex problems. 19 analytical frameworks, 12 cognitive bias detectors, 10 decomposition methods, 10 mental models, Cynefin domain classification, ethical dimension check, and 6 communication patterns. McKinsey-grade problem solving for AI coding assistants.",
676    "userInvocable": true,
677    "keywords": [
678      "5 whys",
679      "root cause analysis",
680      "first principles",
681      "fishbone"
682    ],
683    "chain": []
684  },
685  {
686    "name": "quarantine",
687    "layer": "L3",
688    "model": "opus",
689    "description": "Advisory wrap for tool results from untrusted external surfaces. Appends `[QUARANTINE-NOTICE]` to next-turn context after `mcp__*`, `WebFetch`, and `Read` of `**/uploads/**` so prior tool output is treated as data — not directives. Use when the session ingests MCP user-content (Zendesk, Intercom, support tickets), fetched HTML, or operator-uploaded files. Hook fires AFTER ingestion — advisory, not structural.",
690    "userInvocable": false,
691    "keywords": [],
692    "chain": []
693  },
694  {
695    "name": "readiness",
696    "layer": "L2",
697    "model": "sonnet",
698    "description": "Pre-commit quality gate that catches 'almost right' code. Use when about to commit — auto-fires before commit to validate logic correctness, error handling, regressions, and completeness. Goes beyond linting.",
699    "userInvocable": true,
700    "keywords": [
701      "pre-commit",
702      "quality gate",
703      "check before",
704      "ready to commit"
705    ],
706    "chain": []
707  },
708  {
709    "name": "recall",
710    "layer": "L3",
711    "model": "haiku",
712    "description": "Unified cross-source memory recall: .remember/, .topia/, neural-memory, and agora-memory. Use at session start or before architecture decisions. Read-only orchestrator — writes stay on neural-memory Capture and session-bridge Save.",
713    "userInvocable": true,
714    "keywords": [
715      "recall",
716      "what did we do",
717      "last session",
718      "remember when"
719    ],
720    "chain": []
721  },
722  {
723    "name": "recon",
724    "layer": "L2",
725    "model": "haiku",
726    "description": "Fast codebase scanner. Use when any skill needs codebase context. Finds files, patterns, dependencies, project structure. Pure read-only — never modifies files.",
727    "userInvocable": true,
728    "keywords": [
729      "where is",
730      "find",
731      "search the codebase",
732      "scan the codebase",
733      "project structure"
734    ],
735    "chain": []
736  },
737  {
738    "name": "rescue",
739    "layer": "L1",
740    "model": "sonnet",
741    "description": "Legacy refactoring orchestrator. Use when user says 'refactor', 'modernize', 'clean up this mess', 'rescue', or when dealing with old/messy/legacy code. Multi-session workflow — autopsy, safety net, incremental surgery, progress tracking.",
742    "userInvocable": true,
743    "keywords": [
744      "legacy",
745      "refactor",
746      "modernize",
747      "rescue",
748      "clean up",
749      "old code",
750      "messy"
751    ],
752    "chain": [
753      "autopsy",
754      "safeguard",
755      "surgeon"
756    ]
757  },
758  {
759    "name": "research",
760    "layer": "L3",
761    "model": "haiku",
762    "description": "Web search and external knowledge lookup. Gathers data on technologies, libraries, best practices, and competitor solutions.",
763    "userInvocable": true,
764    "keywords": [
765      "research",
766      "compare libraries",
767      "best practice",
768      "look up"
769    ],
770    "chain": []
771  },
772  {
773    "name": "retro",
774    "layer": "L2",
775    "model": "sonnet",
776    "description": "Engineering retrospective. Analyzes commit history, work patterns, and code quality metrics with trend tracking. Per-person breakdowns, shipping streaks, and actionable improvements. Use when asked for \\\"retro\\\", \\\"weekly review\\\", \\\"what did we ship\\\", or \\\"engineering retrospective\\\".",
777    "userInvocable": true,
778    "keywords": [
779      "retrospective",
780      "retro",
781      "sprint review",
782      "velocity",
783      "what did we ship"
784    ],
785    "chain": []
786  },
787  {
788    "name": "review",
789    "layer": "L2",
790    "model": "sonnet",
791    "description": "Code quality review — patterns, security, performance, correctness. Finds bugs, suggests improvements, triggers fix for issues found. Escalates to opus for security-critical code.",
792    "userInvocable": true,
793    "keywords": [
794      "review",
795      "code review",
796      "check quality",
797      "audit code",
798      "look at this code"
799    ],
800    "chain": [
801      "fix"
802    ]
803  },
804  {
805    "name": "review-intake",
806    "layer": "L2",
807    "model": "sonnet",
808    "description": "Use when receiving external input that needs structured intake before action — PR review feedback, code review comments, OR issue tracker items (bug reports, feature requests). PR Review Mode (default) verifies suggestions before implementing. Issue Triage Mode classifies issues into a state machine (ready-for-agent / ready-for-human / needs-info / wontfix) and emits AGENT-BRIEFs for AFK execution. Prevents blind implementation, enforces verification-first discipline.",
809    "userInvocable": true,
810    "keywords": [
811      "pr feedback",
812      "review comments",
813      "received review",
814      "triage issues"
815    ],
816    "chain": []
817  },
818  {
819    "name": "safeguard",
820    "layer": "L2",
821    "model": "sonnet",
822    "description": "Build safety nets before refactoring. Use when running surgeon or any risky refactor that needs a rollback point. Creates characterization tests, boundary markers, config freezes, and rollback points.",
823    "userInvocable": true,
824    "keywords": [
825      "characterization test",
826      "safety net",
827      "rollback point"
828    ],
829    "chain": []
830  },
831  {
832    "name": "sast",
833    "layer": "L3",
834    "model": "haiku",
835    "description": "Static analysis tool runner. Wraps ESLint, Semgrep, Bandit, Clippy, and language-specific analyzers with unified severity output. Use when deeper code analysis needed beyond pattern matching.",
836    "userInvocable": true,
837    "keywords": [
838      "static analysis",
839      "semgrep",
840      "bandit",
841      "eslint",
842      "clippy"
843    ],
844    "chain": []
845  },
846  {
847    "name": "scaffold",
848    "layer": "L1",
849    "model": "sonnet",
850    "description": "Autonomous project bootstrapper. Generates complete project from a description — structure, code, tests, docs, config. Orchestrates idea → plan → design → fix → test → docs → git in one pipeline. The \\\"0 to production-ready\\\" skill.",
851    "userInvocable": true,
852    "keywords": [
853      "new project",
854      "bootstrap",
855      "scaffold",
856      "greenfield",
857      "starter",
858      "from scratch"
859    ],
860    "chain": [
861      "idea",
862      "plan",
863      "design",
864      "fix",
865      "test",
866      "docs",
867      "git",
868      "verification"
869    ]
870  },
871  {
872    "name": "scope-guard",
873    "layer": "L3",
874    "model": "haiku",
875    "description": "Detects scope creep by quantifying drift percentage. Auto-triggered by L1 orchestrators when files exceed the original plan. Compares git changes against plan, classifies drift into 4 tiers: ON_TRACK, MINOR_DRIFT, SIGNIFICANT_DRIFT, OUT_OF_CONTROL.",
876    "userInvocable": false,
877    "keywords": [],
878    "chain": []
879  },
880  {
881    "name": "sequential-thinking",
882    "layer": "L3",
883    "model": "sonnet",
884    "description": "Step-by-step complex reasoning for multi-variable problems. Breaks interconnected decisions into ordered logical steps with bias detection, reversibility classification, and second-order effect tracking.",
885    "userInvocable": true,
886    "keywords": [
887      "trade-off",
888      "tradeoff",
889      "interdependent",
890      "second-order"
891    ],
892    "chain": []
893  },
894  {
895    "name": "session-bridge",
896    "layer": "L3",
897    "model": "haiku",
898    "description": "Universal context persistence across sessions. Auto-saves decisions, conventions, and progress to .topia/ files. Loads state at session start. Use when any skill makes architectural decisions or establishes patterns that must survive session boundaries.",
899    "userInvocable": true,
900    "keywords": [
901      "save context",
902      "save state",
903      "pick up where",
904      "next session"
905    ],
906    "chain": []
907  },
908  {
909    "name": "skill-forge",
910    "layer": "L2",
911    "model": "opus",
912    "description": "Use when creating new Topia skills, editing existing skills, or verifying skill quality before deployment. Applies TDD discipline to skill authoring — test before write, verify before ship.",
913    "userInvocable": true,
914    "keywords": [
915      "new skill",
916      "create skill",
917      "edit skill"
918    ],
919    "chain": []
920  },
921  {
922    "name": "skill-router",
923    "layer": "L0",
924    "model": "haiku",
925    "description": "Meta-enforcement layer that routes EVERY agent action through the correct skill. MUST check this routing table before ANY response involving code, files, or technical decisions. Default: route to topia:build for code tasks. Prevents rationalization, enforces check-before-act discipline.",
926    "userInvocable": false,
927    "keywords": [],
928    "chain": []
929  },
930  {
931    "name": "slides",
932    "layer": "L3",
933    "model": "sonnet",
934    "description": "Generate Marp-compatible slide decks from structured JSON schema. Converts context into presentations for tech talks, sprint demos, and tutorials.",
935    "userInvocable": true,
936    "keywords": [
937      "slides",
938      "slide deck",
939      "presentation",
940      "marp"
941    ],
942    "chain": []
943  },
944  {
945    "name": "surgeon",
946    "layer": "L2",
947    "model": "sonnet",
948    "description": "Incremental refactorer. Use within a rescue workflow after safeguard has set up safety nets. Refactors ONE module per session using proven patterns — Strangler Fig, Branch by Abstraction, Expand-Migrate-Contract.",
949    "userInvocable": true,
950    "keywords": [
951      "refactor",
952      "extract",
953      "strangler",
954      "decompose"
955    ],
956    "chain": []
957  },
958  {
959    "name": "team",
960    "layer": "L1",
961    "model": "opus",
962    "description": "Multi-agent meta-orchestrator. Use when task spans 5+ files or 3+ modules, or when user says 'parallel', 'split this up', 'do all of these'. Decomposes large tasks into parallel workstreams, assigns to isolated build instances, coordinates merging.",
963    "userInvocable": true,
964    "keywords": [
965      "parallel",
966      "split this up",
967      "do all of these",
968      "fan out",
969      "many files",
970      "multi-module"
971    ],
972    "chain": [
973      "plan",
974      "worktree",
975      "build",
976      "completion-gate"
977    ]
978  },
979  {
980    "name": "test",
981    "layer": "L2",
982    "model": "sonnet",
983    "description": "TDD test writer. Writes failing tests FIRST (red), then verifies they pass after implementation (green). Covers unit, integration, and e2e tests.",
984    "userInvocable": true,
985    "keywords": [
986      "test",
987      "tdd",
988      "coverage",
989      "unit test",
990      "e2e",
991      "spec"
992    ],
993    "chain": [
994      "readiness"
995    ]
996  },
997  {
998    "name": "trend-scout",
999    "layer": "L3",
1000    "model": "haiku",
1001    "description": "Scan market trends, competitor activity, and emerging patterns. Monitors Product Hunt, GitHub Trending, HackerNews, and social platforms.",
1002    "userInvocable": true,
1003    "keywords": [
1004      "competitor",
1005      "trending",
1006      "market trends",
1007      "product hunt",
1008      "hacker news"
1009    ],
1010    "chain": []
1011  },
1012  {
1013    "name": "tut",
1014    "layer": "L3",
1015    "model": "haiku",
1016    "description": "Re-shows the structured first-run menu (finalize / onboard / doctor / faq / help) on demand, with current completion status. Use when the user wants to revisit the tutorial, asks 'what should I do next?', or types `/topia:tut`. This is the explicit re-entry point for the menu that auto-shows on session-start until completed.",
1017    "userInvocable": true,
1018    "keywords": [
1019      "tutorial",
1020      "what should i do next"
1021    ],
1022    "chain": []
1023  },
1024  {
1025    "name": "verification",
1026    "layer": "L3",
1027    "model": "haiku",
1028    "description": "Universal verification runner. Runs lint, type-check, tests, and build. Use after any code change to verify nothing is broken.",
1029    "userInvocable": true,
1030    "keywords": [
1031      "verify",
1032      "run the tests",
1033      "lint",
1034      "type check",
1035      "typecheck"
1036    ],
1037    "chain": []
1038  },
1039  {
1040    "name": "video-creator",
1041    "layer": "L3",
1042    "model": "sonnet",
1043    "description": "Video content planning. Writes narration scripts, storyboards, shot lists, and asset checklists. Saves plan to marketing/video-plan.md.",
1044    "userInvocable": true,
1045    "keywords": [
1046      "video",
1047      "storyboard",
1048      "narration",
1049      "youtube",
1050      "shot list"
1051    ],
1052    "chain": []
1053  },
1054  {
1055    "name": "watchdog",
1056    "layer": "L3",
1057    "model": "sonnet",
1058    "description": "Post-deploy monitoring. Use when verifying a deployed app is healthy after deploy or launch — auto-fires from launch/deploy. Checks HTTP status, response times, error detection, and smoke test report.",
1059    "userInvocable": true,
1060    "keywords": [
1061      "uptime",
1062      "monitor the site",
1063      "is it up",
1064      "response time"
1065    ],
1066    "chain": []
1067  },
1068  {
1069    "name": "worktree",
1070    "layer": "L3",
1071    "model": "haiku",
1072    "description": "Git worktree lifecycle management. Use when team needs parallel isolated workspaces for multi-stream development, or when an experiment must not touch the main working tree. Creates isolated workspaces, manages branches, handles cleanup. Called by team and build.",
1073    "userInvocable": false,
1074    "keywords": [],
1075    "chain": []
1076  }
1077]
1078
mods/types/index.d.ts 87 lines
1// State contract for Topia's Claude Code mods (mods/*.tsx). Every value is
2// held under the `topia` plugin, so each key carries its mod's prefix.
3
4export type GitInfo = {
5  isRepo: boolean
6  branch: string
7  changed: number
8  unpushed: number
9  behind: number
10  hasUpstream: boolean
11}
12
13export type OrderId = 'fanout' | 'ledger' | 'scripts' | 'commit'
14export type Orders = Record<OrderId, boolean>
15
16export type Host = {
17  host: string
18  user?: string
19  key?: string
20  port?: string
21  sudoOk: boolean
22  uses: number
23  firstSeen: string
24  lastOk: string
25}
26
27export type SshTarget = { host: string; user?: string; key?: string; port?: string; remote: string }
28
29export type HiddenReport = {
30  event: string
31  kind: 'session-report' | 'guardian-advisory' | 'install-banner'
32  chars: number
33  at: number
34  text: string
35}
36
37export type UsageLine = {
38  contextPercent?: number
39  cachePercent?: number
40  usd?: number
41  fiveHourPercent?: number
42}
43
44// Prompt routing: what a draft's wording points at, as the band shows it.
45// Keywords only, never the prompt's text.
46export type RoutedSkill = { name: string; keywords: string[]; isExplicit: boolean }
47export type RoutingView = { skills: RoutedSkill[]; chain: string[] }
48export type RoutingTurn = { predicted: string[]; chain: string[]; ran: string[]; isDone: boolean }
49
50// Mods on and off: a choice per scope, the effective value resolved in
51// lib/mod-settings.ts (project > user > /config; a policy lock beats all).
52export type ModId = 'gitBand' | 'standingOrders' | 'remoteHosts' | 'quietReports' | 'modelPreset' | 'promptRouting'
53export type ModChoices = Partial<Record<ModId, boolean>>
54export type ModScope = 'user' | 'project'
55export type ModSettings = { user: ModChoices; project: ModChoices; locked: ModId[] }
56// One project's record: its choices, whether the person has answered the
57// first-run row here, and whether onboard has asked yet.
58export type ProjectMods = { choices: ModChoices; isConfirmed: boolean; isOnboardAsked: boolean }
59// The person's own, for every project.
60export type ModsPrefs = { askNewProjects: boolean; recapAt: number; sessionsSinceRecap: number; isRecapOff: boolean }
61// The row above the prompt that asks about mods, when one shows.
62export type ModsPrompt = 'first-run' | 'onboard' | 'recap'
63
64declare module 'claude-code' {
65  interface PluginState {
66    topia: {
67      gitInfo: GitInfo | null
68      gitBandHidden: boolean
69      standingOrders: Orders | null
70      sshHosts: Record<string, Host>
71      quietHidden: HiddenReport[]
72      quietSavedChars: number
73      quietUsage: UsageLine | null
74      modelPresetApplied: boolean
75      routingLive: RoutingView | null
76      routingTurn: RoutingTurn | null
77      routingHidden: boolean
78      bandFocus: string | null
79      modSettings: ModSettings | null
80      modsPrompt: ModsPrompt | null
81      modsScope: ModScope
82      modsFocus: string | null
83      modsPrefs: ModsPrefs | null
84    }
85  }
86}
87