SLOPSHOPPER

Useful Skills

Claude Code engineering workflows, safety reviews, and local memory tools

commandtoastprocess
v0.4.2GPL-3.0-onlyupdated 2026-10-26MSpiechowicz/harness-useful-skills
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · harness-useful-skills
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /useful-skills ⎿ harness-useful-skills: dev ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

<img src="docs/brand/lockup-light.svg" alt="harness skills" width="430">

Harness Skills for Oh My Pi, Claude Code, OpenCode, and Codex

From a natural-language request to reviewed, verified work.

Owned us-* skills for development, focused audits, delivery, and project memory. Oh My Pi (OMP), Claude Code, OpenCode, and Codex discover their descriptions; the model follows the relevant instructions using native tools and workers.

https://github.com/user-attachments/assets/86bc6cf3-b61e-4ade-9ebd-5e48b27fac38

<sub>A 72-second tour with sound: one request from research and plan approval through workers and fresh reviews to a verified pull request, then the short path for small fixes, read-only audits, memory and installation. The terminals are illustrations. Download the full-quality 4K video (27 MB).</sub>

DevelopInspectDeliverRemember
Clarify, research, approve, implement, reviewFocused security, performance, and quality auditsExplicitly authorized feature-branch PR deliveryDurable facts alongside code relationships

Start here: Installation · Claude Code · OpenCode · Codex · Workflow & skills · Model configuration · Memory

Reference: Management · Audits & delivery · Updates · Development · Attribution

No Anvil dependency, custom workflow executor, model router, phase database, or stop-hook continuation loop.

Installation

The OMP installation below requires OMP with marketplace support and Node.js 22+. It needs no npm dependencies, build step, host configuration, prompt file, or startup flag. Claude Code, OpenCode, and Codex have their own installation sections; the OpenCode installer edits OpenCode's opencode.json (see below), and the Codex installer registers an MCP server through the codex CLI.

omp plugin marketplace add MSpiechowicz/harness-useful-skills
omp plugin install harness-useful-skills@harness-useful-skills --scope user

These commands and ./useful-skills install below require a published release of the new catalog; until then, load this source checkout with omp -e /absolute/path/to/harness-useful-skills as shown below.

Restart OMP after installation or update. Ordinary startup adds discovery and, when enabled for the current repository in the active profile, narrowly scoped session-local workflow-stage guidance. Use --scope project from the project directory for a project installation, or prefix both commands with omp --profile NAME for an isolated profile. Installation scope is separate from the repository-local workflow master and six profile-wide stage preferences. The marketplace and plugin are both named harness-useful-skills; the OMP plugin ID is harness-useful-skills@harness-useful-skills. OMP does not import this plugin's Claude Code MCP server: its manifest declares empty mcpServers. Claude Code loads its own separate MCP tools when installed there.

Upgrading from 0.3.x: one name everywhere

Releases after 0.3.13 (a breaking change) give every host the same name, harness-useful-skills. Install it as described below on top of an older install. The old names stop working, so update anything that mentions them (permission rules, prompts, scripts):

WhatBeforeNow
Claude marketplace and plugin IDuseful-skills@useful-skills-localharness-useful-skills@harness-useful-skills
Codex plugin IDuseful-skills@harness-useful-skillsharness-useful-skills@harness-useful-skills
MCP server (Claude, OpenCode, Codex)useful_skillsharness-useful-skills
Claude toolsmcp__plugin_useful-skills_useful_skills__*mcp__plugin_harness-useful-skills_harness-useful-skills__*
OpenCode toolsuseful_skills_memory_status and so onharness-useful-skills_memory_status and so on
Claude skills and agents/useful-skills:us-*, useful-skills:planner/harness-useful-skills:us-*, harness-useful-skills:planner
Claude data and settings~/.claude/useful-skills/~/.claude/harness-useful-skills/
Generated Claude agents~/.claude/agents/useful-skills-*.md~/.claude/agents/harness-useful-skills-*.md
OpenCodeplugins/useful-skills.js, plugins/useful-skills/, useful-skills/models.ymlplugins/harness-useful-skills.js, plugins/harness-useful-skills/, harness-useful-skills/models.yml
Codex$CODEX_HOME/useful-skills/$CODEX_HOME/harness-useful-skills/

The role agents us-*, the skill names us-*, the /useful-skills command, and the ./useful-skills script keep their names. The old files are cleaned up only when they are safe to remove:

  • OpenCode and Codex: re-run the installer (install.sh, install.ps1, or ./useful-skills install --host ...). It removes the old plugin files, the useful_skills MCP entry and (Codex) the old plugin only while they are still what the old install wrote, keeps any file you edited and says so, and moves the data folders to the new names. Nothing is lost: a file is deleted from the old place only after an identical copy exists in the new one, and a models.yml you edited in both places stays in both. uninstall removes both the old and the new names. doctor --host ... reports whatever is left of an old install. The in-app update install of an old OpenCode runtime cannot install this release (the release no longer ships the old file names): run the install script once instead.
  • Claude Code: install the new plugin (claude plugin install harness-useful-skills@harness-useful-skills) and remove the old one (claude plugin uninstall useful-skills@useful-skills-local), because Claude keeps them as two separate plugins and both would load. On its first session the new plugin moves ~/.claude/useful-skills/ (role models, saved settings) to ~/.claude/harness-useful-skills/, replaces the generated agents ~/.claude/agents/useful-skills-*.md with harness-useful-skills-*.md (only files Harness Skills generated), and copies the saved memory out of the old plugin's data folder. /useful-skills doctor lists a still-installed old plugin.
  • OMP: the plugin ID did not change. The first session moves <agentDir>/useful-skills/ (workflow settings, saved memory) to <agentDir>/harness-useful-skills/.

The downloaded Graphify environment (dependencies/) is not moved, because it holds absolute paths. It is installed again the next time a build needs it.

Remove or migrate an OMP installation

Uninstall each historic ID that is installed in the relevant scope; check omp plugin list --json if unsure. These commands remove installed plugins, not their marketplace registration:

omp plugin uninstall oh-my-pi-useful-skills@omp-useful-skills --scope user
omp plugin uninstall useful-skills@omp-useful-skills --scope user

An old installation is not renamed by updating a checkout or publishing a release, and loading the checkout does not remove its startup message. You can uninstall it before the new catalog is published. If no plugins need the old marketplace, optionally remove its registration with omp plugin marketplace remove omp-useful-skills. After the new catalog is published, use the installation commands above to add the new marketplace and install the new ID. The updater does not migrate old installations or marketplace registrations.

Uninstalling the plugin leaves the agents copied into <agentDir>/agents. They stay active in every project after the plugin is removed or disabled, so run ./useful-skills uninstall --host omp first (add --profile NAME for a named profile): it deletes only the files this sync generated there (~/.omp/profiles/NAME/agent for a named profile, else PI_CODING_AGENT_DIR, default ~/.omp/agent) and prints the omp plugin uninstall harness-useful-skills@harness-useful-skills command to run next.

For a project installation, run these commands from that project directory with --scope project instead of --scope user. For an isolated profile, prefix each command with omp --profile NAME instead of omp, retaining the original scope and project directory. Restart OMP after installation.

For local development, load the package directory, not the extension file alone:

omp -e /absolute/path/to/harness-useful-skills

./useful-skills install [--scope user|project] [--profile NAME] installs the published marketplace plugin, not the checkout itself. Source checkouts are updated with git pull --ff-only; the updater never overwrites them.

Claude Code

The Claude Code adapter requires Node.js 22+ and a marketplace installation. For a local checkout, use its absolute path:

claude plugin marketplace add /absolute/path/to/harness-useful-skills --scope user
claude plugin install harness-useful-skills@harness-useful-skills --scope user

Or add the same repository as a GitHub marketplace:

claude plugin marketplace add MSpiechowicz/harness-useful-skills
claude plugin install harness-useful-skills@harness-useful-skills --scope user

The Claude plugin ID is harness-useful-skills@harness-useful-skills in either case. Install through the marketplace, not claude --plugin-dir .: that loads the repository-root OMP skills/ instead of the marketplace's selected Claude skills. Restart Claude Code after installation. The OMP installation, commands, and profile behavior above remain unchanged.

Claude exposes 21 namespaced skills (for example, /harness-useful-skills:us-run-workflow) and seven native agents: planner, scout, frontend, backend, general-purpose, reviewer, and security-reviewer. All declare model: inherit; per-role models come from a Claude-owned config file instead (see Claude Code model roles). Permissions and stronger host rules remain authoritative. Plugin userConfig has seven default-true booleans: workflow, research, plan, review, security_review, backend_memory, and graphify_memory. Configure them in Claude Code's /plugin configure flow or at install time with repeatable --config key=false flags (for example, --config workflow=false). Disabling workflow suppresses automatic stages without changing the other saved values. A direct /harness-useful-skills:us-ignore-workflow invocation bypasses package-mandatory stages for one request only; quoted or copied text is not an opt-out. With a recent Claude Code that supports mods, /useful-skills is also available: without arguments it opens a menu (Settings, Status, Browse, Help); with arguments it runs the commands in Management. Saved settings mirror OMP's layout under the Claude config directory ($CLAUDE_CONFIG_DIR or ~/.claude): the per-repository workflow master is useful-skills/workflow-settings/repositories/<sha256(scopeRoot)>/workflow.json (same repository scope rules as OMP) and the six profile-wide stage switches are useful-skills/workflow-settings/<stage>.json, all private. For each setting a saved file wins, then the /plugin option, then enabled; an unreadable or unsafe saved file makes that setting unknown with no fallback. /plugin options remain fallbacks, and the only control on Claude Code versions without mods.

The Claude plugin adds a separate local stdio MCP server with five tools: memory_status, memory_search, memory_save, graph_build, and graph_query. Facts are project-scoped private files under Claude plugin data, searched by literal text; they are not OMP's native Mnemopi facts and are not shared with them. Graphify is the shared code-relationship implementation, with lazy managed setup on explicit graph actions rather than at startup. Do not save credentials, personal data, transcripts, or tool dumps; secret detection is only a backstop. A Bash pre-tool guard denies recognized dangerous commands, and successful tool responses can be redacted by PostToolUse; failed third-party tool responses (PostToolUseFailure) cannot receive equivalent redaction. These protections are not a sandbox or a substitute for Claude's permissions, user approval, or publication controls.

In Claude Code, /useful-skills doctor also prepares memory for the session's project (see Management); it never writes the workflow or stage settings files.

To submit Claude Code to the Claude plugin directory, node scripts/build-claude-plugin.js generates a Claude-only plugin bundle at plugins/claude/; the self-hosted marketplace install above is unchanged. plugins/claude/ is generated: run the script after editing Claude runtime files or skills (CI runs it with --check). Only plugins/claude/README.md and plugins/claude/evals/ (cases for claude plugin eval) are hand-written, and generated output is outside the 500-line cap.

OMP's updater and release process do not update the Claude or OpenCode installations automatically (OpenCode has its own update commands, and Codex updates by re-running its installer).

OpenCode

The OpenCode adapter supports OpenCode v1.x (plugin API V1, tested on 1.19.3) and OpenCode v2.x (plugin API V2, tested on 2.1.2) and needs Node.js 22+ on PATH: the plugin itself runs under OpenCode's own runtime, but settings, memory, and doctor run as Node subprocesses. One installed plugins/harness-useful-skills.js serves both: its default export carries the V1 server function and the V2 setup function, and each OpenCode reads the one it knows (OpenCode V2).

One-line install of the latest release into your user config (macOS and Linux, needs curl, tar, gzip, and Node.js 22+):

curl --proto '=https' --tlsv1.2 -fsSL https://raw.githubusercontent.com/MSpiechowicz/harness-useful-skills/main/install.sh | sh

On Windows (PowerShell, needs the tar.exe in System32 from Windows 10 or newer, and Node.js 22+):

irm https://raw.githubusercontent.com/MSpiechowicz/harness-useful-skills/main/install.ps1 | iex

The script downloads the release tarball from GitHub over HTTPS, runs the same checks as update install (no links, no absolute or .. paths, one top-level directory, a package.json and plugin manifest that both match the release tag), and then runs that release's ./useful-skills install --host opencode --scope user from your home directory. Nothing is installed when a check fails, and the temporary download is always removed. Set HARNESS_SKILLS_VERSION to a release tag such as v0.3.7 to install that release instead of the latest (also the way around a failed GitHub API lookup). Put the variable on the shell that reads the script, not on curl:

curl --proto '=https' --tlsv1.2 -fsSL https://raw.githubusercontent.com/MSpiechowicz/harness-useful-skills/main/install.sh | HARNESS_SKILLS_VERSION=v0.3.7 sh
$env:HARNESS_SKILLS_VERSION = 'v0.3.7'; irm https://raw.githubusercontent.com/MSpiechowicz/harness-useful-skills/main/install.ps1 | iex

Re-run the installer to update. The PowerShell script cannot stop a download at the size cap (it checks Content-Length when sent and the file afterwards), and it does not check extracted hard links.

Or install from a checkout, which also supports the project scope:

./useful-skills install --host opencode [--scope user|project]

Restart OpenCode afterwards. The default scope is user. Omitting --host, or --host omp, keeps today's OMP behavior; --profile with --host opencode is an error.

What it writes, all under the scope directory (<config>/opencode for user, where <config> is $XDG_CONFIG_HOME if absolute, else ~/.config; <cwd>/.opencode for project):

  • plugins/harness-useful-skills.js, plugins/harness-useful-skills/**, and plugins/harness-useful-skills/install-record.json (version, scope, paths, and a SHA-256 for every owned file)
  • skills/us-* (21 skills), commands/useful-skills.md, and commands/us-ignore-workflow.md
  • agents/us-<agent>.md, generated from the bundled templates with a # Generated by Useful Skills marker (see OpenCode model roles)
  • harness-useful-skills/models.yml in the scope directory
  • an mcp.harness-useful-skills entry in opencode.json (below)

Outside the scope directory, the plugin keeps data at ${XDG_DATA_HOME:-~/.local/share}/opencode/harness-useful-skills (mode 0700) and workflow settings at ${XDG_CONFIG_HOME:-~/.config}/opencode/harness-useful-skills/workflow-settings/ for both scopes, in the same layout as OMP and Claude Code. OPENCODE_CONFIG_DIR is not an install target.

Config edit. The installer adds or updates only mcp.harness-useful-skills (a local server running node on the installed mcp-server.js, enabled, timeout 600000) in the scope's opencode.json, or in a comment-free opencode.jsonc when that is the file present. It never clobbers other keys and reports a different existing mcp.harness-useful-skills before replacing it. It refuses to edit a config that contains comments, does not parse, is not an object, has a non-object mcp, or is a symlink: it then prints the snippet to add yourself and exits 0 with "Action required".

Ownership. The installer never overwrites a file it does not own or one you edited since installing, and refuses symlinked targets. Project scope writes <cwd>/.opencode/ and its opencode.json with machine-specific absolute paths; add them to .gitignore instead of committing them.

Update. ./useful-skills update check|install --host opencode (or /useful-skills update check|install in chat) downloads the latest stable GitHub release tarball over HTTPS, verifies it (no links, no absolute or .. paths, matching versions) and runs its installer for the recorded scope. Nothing changes on any failure. It updates the installed copy, never the checkout, and works from the first release that contains the OpenCode adapter. On OpenCode 1.x the plugin also makes one quiet check at startup and shows a toast when a newer release exists.

Uninstall. ./useful-skills uninstall --host opencode [--scope user|project] removes only owned files that still match their recorded hash, marker-owned agents, and the mcp.harness-useful-skills entry if it is unchanged. It keeps data, settings, and models.yml, and prints their paths. ./useful-skills doctor --host opencode reports the installation from the terminal.

OpenCode exposes the 21 skills by their plain us-* names through its skill tool and as /us-* slash commands. Workers are the seven us-* agents below, dispatched with the task tool. The memory MCP server adds harness-useful-skills_memory_status, harness-useful-skills_memory_search, harness-useful-skills_memory_save, harness-useful-skills_graph_build, and harness-useful-skills_graph_query: project-scoped private facts under the OpenCode data directory searched by literal text, plus Graphify as in Claude Code. They are not shared with OMP or Claude Code facts. A Bash pre-tool guard that denies recognized dangerous commands is always on, as in Claude Code, and successful tool output is redacted for common secret patterns.

Limits:

  • OpenCode skips the after-tool hook when a tool fails, so failed tool output is not redacted.
  • /useful-skills output is relayed by the model: the plugin runs the command and the model is told to show the result verbatim, best-effort.
  • On OpenCode 1.x, workflow guidance uses experimental.chat.system.transform, which OpenCode may change.
  • Like the other hosts, the Bash guard does not stop a model from running the bundled command.js or editing settings files through tools; the restriction that settings change only from commands you type applies to the plugin's command path, not to everything a model can do.
  • On OpenCode 1.x, workflow context is added to every LLM call in a session, including OpenCode's title and compaction calls: plugin API V1 cannot tell them apart from chat turns. OpenCode 2.x has separate hooks, so only the agent's own requests get it.
  • Startup runs sync-agents (it writes harness-useful-skills/models.yml and the generated agents) and one read-only update check, which may call gh auth token to raise the GitHub rate limit; both fail quietly.
  • The installer re-serializes opencode.json as 2-space JSON, so exotic numeric values and duplicate keys normalize.
  • Long /useful-skills commands (doctor, graph test, update install) have a 10-minute budget (60 seconds for the others), and their subprocesses are stopped when OpenCode quits.
  • These protections are not a sandbox or a substitute for OpenCode's permissions.
OpenCode V2

OpenCode 2.x loads plugins/harness-useful-skills.js as a plugin definition (export default { id, setup }) and rejects a file with only named exports. OpenCode 1.x reads the same default export and calls its server function, so the installed entry exports one object with id, server (V1), and setup (V2), and the installer is the same for both. The runtime directory plugins/harness-useful-skills/ is ignored by the V2 loader because it has no index or server module.

opencode/v2.js maps the V2 Promise plugin API onto the same session logic as V1, with these differences:

BehaviorOpenCode 1.xOpenCode 2.x
Workflow guidanceexperimental.chat.system.transformsession.hook("context"), appended to the system prompt of the agent's requests only (not title or compaction)
Per-prompt refreshchat.messagesession.hook("prompt")
Bash guard and redactionbash tool, tool.execute.before/aftershell (or bash) tool, `tool.hook("execute.before"\"execute.after"), plus redaction of background and user shell output messages in session.hook("context")`
Subagent sessionssession.created event, then a session lookupctx.event.subscribe events, then a session lookup
/useful-skills, /us-ignore-workflowcommand.execute.beforeplugin commands registered with ctx.command.transform (see below)
Update and Node.js noticestoastsnone: V2 server plugins have no toast, and the startup update check is skipped

OpenCode 2.x has no command hook. The plugin registers useful-skills and us-ignore-workflow as plugin commands, so they run only when you (or a client acting for you) run the command, never because some prompt text looks like one: the prompt hook also sees MCP prompt commands, API clients, and other plugins. A command runs only in a session the host confirms is a main session, and the commands in commands/*.md stay as the fallback that tells the model nothing ran. The host applies command registrations in order and its own markdown-command loader registers after plugins, so the plugin checks the host's command list and registers again whenever its commands are no longer the active ones, giving up after five registrations in a row that the list does not confirm. A command typed within milliseconds of a project loading can still reach the fallback text. /useful-skills sends its relayed result as the prompt, and /us-ignore-workflow sends the text of its markdown file with what you typed and opts that one request out. The plugin reads the us-ignore-workflow file when it loads, so edits to it apply after a restart. V2 limits: a fail

Source 1 files
hooks/register.ts 375 lines
1import type { EngineInterface, PluginOptions, Register } from 'claude-code'
2
3// Claude Code function-hooks module: `/useful-skills`, backed by claude/command.js.
4
5const COMMAND_TIMEOUT_MS = 60_000
6const DOCTOR_TIMEOUT_MS = 600_000
7const MAX_ARGUMENTS = 8
8
9const NODE_REQUIRED = 'Useful Skills needs Node.js 22+ on PATH to run /useful-skills.'
10const FAILED = 'Useful Skills could not complete /useful-skills.'
11const CANCELLED = 'Cancelled; no settings changed.'
12const NO_CHANGE = 'No change.'
13const NO_OUTPUT = 'Useful Skills command produced no output; nothing was confirmed.'
14const WRITE_REFUSED = 'Workflow settings can only be changed from your own prompt.'
15const DOCTOR_PREPARING = 'Useful Skills doctor: preparing memory; first setup can take several minutes'
16const DOCTOR_TIMED_OUT = 'Useful Skills doctor did not finish within 10 minutes; setup may be partial — run it again.'
17const USAGE = [
18  'Usage: /useful-skills [status|workflow|stage|list|doctor|help]',
19  'Run /useful-skills help for the full list.',
20].join('\n')
21const TOO_MANY_ARGUMENTS = [`Too many arguments (at most ${MAX_ARGUMENTS}).`, USAGE].join('\n')
22
23// `doctor` alone prepares memory (writes); `doctor --check` only reports.
24const DOCTOR_SETUP: readonly string[] = ['doctor']
25const DOCTOR_CHECK: readonly string[] = ['doctor', '--check']
26
27// Boolean plugin options travel to the CLI as the env vars Claude gives hook processes.
28const OPTION_ENV: Readonly<Record<string, string>> = {
29  workflow: 'CLAUDE_PLUGIN_OPTION_WORKFLOW',
30  research: 'CLAUDE_PLUGIN_OPTION_RESEARCH',
31  plan: 'CLAUDE_PLUGIN_OPTION_PLAN',
32  review: 'CLAUDE_PLUGIN_OPTION_REVIEW',
33  security_review: 'CLAUDE_PLUGIN_OPTION_SECURITY_REVIEW',
34  backend_memory: 'CLAUDE_PLUGIN_OPTION_BACKEND_MEMORY',
35  graphify_memory: 'CLAUDE_PLUGIN_OPTION_GRAPHIFY_MEMORY',
36}
37
38// Only these origins are the person's own prompt; every other origin may only read.
39const WRITE_ORIGINS: ReadonlySet<string> = new Set(['composer', 'sdk'])
40
41// Every other subcommand can change saved settings; `doctor` from these origins only checks.
42const READ_ONLY: ReadonlySet<string> = new Set(['status', 'help', 'list', 'doctor', 'update', 'graph'])
43
44type Stage = { key: string; label: string }
45
46const STAGES_FIRST: readonly Stage[] = [
47  { key: 'research', label: 'Research' },
48  { key: 'plan', label: 'Plan' },
49  { key: 'review', label: 'Review' },
50]
51const STAGES_SECOND: readonly Stage[] = [
52  { key: 'security-review', label: 'Security review' },
53  { key: 'backend-memory', label: 'Backend memory' },
54  { key: 'graphify-memory', label: 'Graphify memory' },
55]
56
57type Run = (tokens: readonly string[]) => Promise<string>
58
59/** A menu entry either opens a submenu, goes back, or runs one CLI command. */
60type Choice = { label: string; menu?: Menu; command?: readonly string[]; back?: true }
61type Menu = { question: string; header: string; choices: readonly Choice[] }
62
63type CliResult = { exitCode: number; text: string }
64type CliRunOptions = { timeoutMs?: number; extraEnv?: Record<string, string> }
65
66class CliUnavailable extends Error {}
67class DoctorTimedOut extends Error {}
68
69function optionEnvironment(options: PluginOptions): Record<string, string> {
70  const env: Record<string, string> = {}
71
72  for (const [field, name] of Object.entries(OPTION_ENV)) {
73    const value = options[field]
74
75    if (typeof value === 'boolean') {
76      env[name] = value ? 'true' : 'false'
77    }
78  }
79
80  return env
81}
82
83/** Runs the CLI and returns its output; a failure to start it is never described in detail. */
84async function runCli(
85  $: EngineInterface,
86  env: Record<string, string>,
87  tokens: readonly string[],
88  options: CliRunOptions = {},
89): Promise<CliResult> {
90  try {
91    const cwd = await $.session.cwd()
92    const result = await $.process.run(['node', `${$.plugin.root}/claude/command.js`, ...tokens], {
93      cwd,
94      env: { ...env, ...options.extraEnv },
95      timeoutMs: options.timeoutMs ?? COMMAND_TIMEOUT_MS,
96    })
97    const text = result.stdout.trim() || result.stderr.trim()
98
99    return { exitCode: result.exitCode, text }
100  } catch {
101    throw new CliUnavailable()
102  }
103}
104
105function sameTokens(tokens: readonly string[], expected: readonly string[]): boolean {
106  return tokens.length === expected.length && tokens.every((token, index) => token === expected[index])
107}
108
109/** A toast is only a hint: one that cannot be shown, now or later, never stops the command. */
110function showToast($: EngineInterface, text: string): void {
111  try {
112    const shown: unknown = $.ui.toast(text)
113
114    // Not awaited: a toast that fails later is dropped, never an unhandled rejection.
115    Promise.resolve(shown).catch(() => {})
116  } catch {
117    // No surface to show it on; the command still runs.
118  }
119}
120
121/** Full memory setup: may run for minutes, so it gets the longest timeout the host allows. */
122async function runDoctorSetup($: EngineInterface, env: Record<string, string>, extraEnv: Record<string, string>): Promise<CliResult> {
123  showToast($, DOCTOR_PREPARING)
124
125  const startedAt = await $.clock.now()
126  const hasTimedOut = async () => (await $.clock.now()) - startedAt >= DOCTOR_TIMEOUT_MS
127  let result: CliResult
128
129  try {
130    result = await runCli($, env, DOCTOR_SETUP, { timeoutMs: DOCTOR_TIMEOUT_MS, extraEnv })
131  } catch (error) {
132    if (await hasTimedOut()) {
133      throw new DoctorTimedOut()
134    }
135
136    throw error
137  }
138
139  // A host may report a run it killed at the limit as a silent failure (a signal reads as exit 1).
140  const isSilentFailure = result.exitCode !== 0 && !result.text
141
142  if (isSilentFailure && (await hasTimedOut())) {
143    throw new DoctorTimedOut()
144  }
145
146  return result
147}
148
149/** Runs one command; every `doctor` run is told the session's project root. */
150async function runTokens($: EngineInterface, env: Record<string, string>, tokens: readonly string[]): Promise<CliResult> {
151  if (tokens[0] !== 'doctor') {
152    return runCli($, env, tokens)
153  }
154
155  const extraEnv = { CLAUDE_PROJECT_DIR: await $.session.root() }
156
157  if (sameTokens(tokens, DOCTOR_SETUP)) {
158    return runDoctorSetup($, env, extraEnv)
159  }
160
161  return runCli($, env, tokens, { extraEnv })
162}
163
164/** Saved enabled/disabled values by key; empty when the CLI cannot report them. */
165async function readSaved($: EngineInterface, env: Record<string, string>): Promise<Record<string, string>> {
166  const saved: Record<string, string> = {}
167
168  try {
169    const { exitCode, text } = await runCli($, env, ['status', '--json'])
170
171    if (exitCode !== 0) {
172      return saved
173    }
174
175    const status = JSON.parse(text)
176    const entries: Record<string, unknown> = { workflow: status?.workflow, ...status?.stages }
177
178    for (const [key, entry] of Object.entries(entries)) {
179      const value = (entry as { saved?: unknown } | undefined)?.saved
180
181      if (value === 'enabled' || value === 'disabled' || value === 'unknown') {
182        saved[key] = value
183      }
184    }
185  } catch {
186    return {}
187  }
188
189  return saved
190}
191
192function modeMenu(title: string, header: string, saved: string, subject: readonly string[]): Menu {
193  return {
194    question: `Set ${title} (saved: ${saved})?`,
195    header,
196    choices: [
197      { label: 'Enabled', command: [...subject, 'enabled'] },
198      { label: 'Disabled', command: [...subject, 'disabled'] },
199      { label: 'Back', back: true },
200    ],
201  }
202}
203
204function stagesMenu(header: string, stages: readonly Stage[], saved: Record<string, string>): Menu {
205  const choices: Choice[] = stages.map(stage => {
206    const current = saved[stage.key] ?? 'unknown'
207
208    return {
209      label: `${stage.label} (${current})`,
210      menu: modeMenu(`${stage.label} stage`, 'Stage', current, ['stage', stage.key]),
211    }
212  })
213
214  return { question: 'Which stage?', header, choices: [...choices, { label: 'Back', back: true }] }
215}
216
217function buildMenu(saved: Record<string, string>): Menu {
218  const workflow = saved.workflow ?? 'unknown'
219
220  const settings: Menu = {
221    question: 'Which setting?',
222    header: 'Settings',
223    choices: [
224      {
225        label: `Repository workflow (${workflow})`,
226        menu: modeMenu('repository workflow', 'Workflow', workflow, ['workflow']),
227      },
228      { label: 'Stages 1/2', menu: stagesMenu('Stages 1/2', STAGES_FIRST, saved) },
229      { label: 'Stages 2/2', menu: stagesMenu('Stages 2/2', STAGES_SECOND, saved) },
230      { label: 'Back', back: true },
231    ],
232  }
233
234  // Setup installs and writes; checking only reports. The person picks which, never by default.
235  const doctor: Menu = {
236    question: 'Doctor: set up memory (may install and write files) or only check it?',
237    header: 'Doctor',
238    choices: [
239      { label: 'Set up memory', command: DOCTOR_SETUP },
240      { label: 'Check only', command: DOCTOR_CHECK },
241      { label: 'Back', back: true },
242    ],
243  }
244
245  const browse: Menu = {
246    question: 'What would you like to browse?',
247    header: 'Browse',
248    choices: [
249      { label: 'List', command: ['list'] },
250      { label: 'Doctor…', menu: doctor },
251      { label: 'Back', back: true },
252    ],
253  }
254
255  return {
256    question: 'Useful Skills: what would you like to do?',
257    header: 'Menu',
258    choices: [
259      { label: 'Settings', menu: settings },
260      { label: 'Status', command: ['status'] },
261      { label: 'Browse', menu: browse },
262      { label: 'Help', command: ['help'] },
263    ],
264  }
265}
266
267/** Walks the menu tree; only an exact option label ever reaches the CLI. */
268async function chooseAndRun($: EngineInterface, run: Run, saved: Record<string, string>): Promise<string> {
269  const path: Menu[] = [buildMenu(saved)]
270  let hasAsked = false
271
272  for (;;) {
273    const menu = path[path.length - 1]!
274    let answer: string
275
276    try {
277      answer = await $.ui.ask(menu.question, { options: menu.choices.map(choice => choice.label), header: menu.header })
278    } catch {
279      // Dismissed, or no UI to ask in (`-p`): help before any prompt, otherwise cancel.
280      return hasAsked ? CANCELLED : run(['help'])
281    }
282
283    hasAsked = true
284
285    const choice = menu.choices.find(entry => entry.label === answer)
286
287    if (!choice) {
288      return NO_CHANGE
289    }
290
291    if (choice.back) {
292      path.pop()
293    } else if (choice.menu) {
294      path.push(choice.menu)
295    } else if (choice.command) {
296      return run(choice.command)
297    }
298  }
299}
300
301export const register: Register = (on, options) => {
302  const env = optionEnvironment(options)
303
304  on('session.start', async ($, e, next) => {
305    const started = await next(e)
306
307    await $.command.register({
308      name: 'useful-skills',
309      description: 'Workflow settings, status, skills, and health for Useful Skills',
310      argumentHint: '[status|workflow|stage|list|doctor|help]',
311    })
312
313    return started
314  })
315
316  on('command.run', { command: 'useful-skills' }, async ($, e) => {
317    const run: Run = async tokens => {
318      const { exitCode, text } = await runTokens($, env, tokens)
319
320      if (text) {
321        return text
322      }
323
324      // Silence is never success: a CLI that did nothing must not be reported as done.
325      return exitCode === 0 ? NO_OUTPUT : `Useful Skills command failed (exit ${exitCode}).`
326    }
327
328    try {
329      const tokens = e.args.trim().split(/\s+/).filter(Boolean)
330
331      if (tokens.length > MAX_ARGUMENTS) {
332        return { text: TOO_MANY_ARGUMENTS }
333      }
334
335      // Fail closed: a missing or unrecognized origin is read-only, with no menu.
336      const kind: unknown = e.origin?.kind
337
338      if (typeof kind !== 'string' || !WRITE_ORIGINS.has(kind)) {
339        if (tokens.length === 0) {
340          return { text: await run(['help']) }
341        }
342
343        // Memory setup writes, so from here `doctor` only ever checks.
344        if (tokens[0] === 'doctor') {
345          const isCheckable = sameTokens(tokens, DOCTOR_SETUP) || sameTokens(tokens, DOCTOR_CHECK)
346
347          return { text: isCheckable ? await run(DOCTOR_CHECK) : USAGE }
348        }
349
350        if (!READ_ONLY.has(tokens[0]!)) {
351          return { text: WRITE_REFUSED }
352        }
353      }
354
355      if (tokens.length > 0) {
356        return { text: await run(tokens) }
357      }
358
359      const saved = await readSaved($, env)
360
361      return { text: await chooseAndRun($, run, saved) }
362    } catch (error) {
363      if (error instanceof DoctorTimedOut) {
364        return { text: DOCTOR_TIMED_OUT }
365      }
366
367      if (error instanceof CliUnavailable) {
368        return { text: NODE_REQUIRED }
369      }
370
371      return { text: FAILED }
372    }
373  })
374}
375