Skip to content

The one and only agent harness for complex codebases. Project memory, planning, execution, and verified completion inside Codex.

chore: add sisyphuslabs Codex marketplace

YeonGyu-Kim4fe315b8a0e6
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json
new file mode 100644
index 00000000..f7e02925
--- /dev/null
+++ b/.agents/plugins/marketplace.json
@@ -0,0 +1,17 @@
+{
+ "name": "sisyphuslabs",
+ "interface": {
+ "displayName": "Sisyphus Labs"
+ },
+ "plugins": [
+ {
+ "name": "omo",
+ "source": "./plugins/omo",
+ "category": "Developer Tools",
+ "policy": {
+ "installation": "AVAILABLE",
+ "authentication": "ON_INSTALL"
+ }
+ }
+ ]
+}
diff --git a/plugins/omo/.codex-plugin/plugin.json b/plugins/omo/.codex-plugin/plugin.json
new file mode 100644
index 00000000..660b8467
--- /dev/null
+++ b/plugins/omo/.codex-plugin/plugin.json
@@ -0,0 +1,35 @@
+{
+ "name": "omo",
+ "version": "0.1.0",
+ "description": "One Codex plugin namespace for Yeongyu's local Codex components.",
+ "author": {
+ "name": "Yeongyu Kim",
+ "email": "[email protected]",
+ "url": "https://github.com/code-yeongyu"
+ },
+ "homepage": "https://github.com/code-yeongyu/omo",
+ "repository": "https://github.com/code-yeongyu/omo",
+ "license": "MIT",
+ "keywords": ["codex", "codex-plugin", "omo", "hooks", "mcp", "skills"],
+ "skills": "./skills/",
+ "hooks": "./hooks/hooks.json",
+ "mcpServers": "./.mcp.json",
+ "interface": {
+ "displayName": "OMO",
+ "shortDescription": "Unified local Codex components",
+ "longDescription": "OMO exposes the local Codex Rules, Comment Checker, LSP, Ultrawork, and Ultragoal components as one plugin namespace while keeping each component isolated under components/ for maintenance.",
+ "developerName": "Yeongyu Kim",
+ "category": "Developer Tools",
+ "capabilities": ["Hooks", "MCP Tools", "Code Intelligence", "Workflow", "Context Injection"],
+ "websiteURL": "https://github.com/code-yeongyu/omo",
+ "privacyPolicyURL": "https://github.com/code-yeongyu/omo#privacy",
+ "termsOfServiceURL": "https://github.com/code-yeongyu/omo#license",
+ "defaultPrompt": [
+ "Use OMO LSP diagnostics on this workspace.",
+ "Show which OMO rules matched this file.",
+ "ulw: run this change with evidence."
+ ],
+ "brandColor": "#7C3AED",
+ "screenshots": []
+ }
+}
diff --git a/plugins/omo/.mcp.json b/plugins/omo/.mcp.json
new file mode 100644
index 00000000..b36e4a79
--- /dev/null
+++ b/plugins/omo/.mcp.json
@@ -0,0 +1,9 @@
+{
+ "mcpServers": {
+ "lsp": {
+ "command": "node",
+ "args": ["./components/lsp/packages/lsp-tools-mcp/dist/cli.js", "mcp"],
+ "cwd": "."
+ }
+ }
+}
diff --git a/plugins/omo/README.md b/plugins/omo/README.md
new file mode 100644
index 00000000..a5a9bdc7
--- /dev/null
+++ b/plugins/omo/README.md
@@ -0,0 +1,13 @@
+# omo
+
+`omo` is the single local Codex plugin namespace for Yeongyu's Codex components.
+
+Internally each component remains isolated under `components/`:
+
+- `components/comment-checker`
+- `components/rules`
+- `components/lsp`
+- `components/ultrawork`
+- `components/ultragoal`
+
+The root plugin manifest exports one Codex plugin named `omo`, with aggregate hooks, skills, and the LSP MCP server.
diff --git a/plugins/omo/components/comment-checker/.gitattributes b/plugins/omo/components/comment-checker/.gitattributes
new file mode 100644
index 00000000..9363fdb7
--- /dev/null
+++ b/plugins/omo/components/comment-checker/.gitattributes
@@ -0,0 +1,13 @@
+# Normalize line endings: store LF in git, check out LF on every platform.
+# Required so biome's --check passes on Windows (default core.autocrlf=true).
+* text=auto eol=lf
+
+# Explicit binary types
+*.png binary
+*.jpg binary
+*.jpeg binary
+*.gif binary
+*.ico binary
+*.zip binary
+*.tgz binary
+*.gz binary
diff --git a/plugins/omo/components/comment-checker/.github/CODEOWNERS b/plugins/omo/components/comment-checker/.github/CODEOWNERS
new file mode 100644
index 00000000..ef9dbe9d
--- /dev/null
+++ b/plugins/omo/components/comment-checker/.github/CODEOWNERS
@@ -0,0 +1,12 @@
+* @code-yeongyu
+
+.github/workflows/* @code-yeongyu
+.github/dependabot.yml @code-yeongyu
+package.json @code-yeongyu
+package-lock.json @code-yeongyu
+LICENSE @code-yeongyu
+NOTICE @code-yeongyu
+README.md @code-yeongyu
+CHANGELOG.md @code-yeongyu
+.codex-plugin/plugin.json @code-yeongyu
+hooks/hooks.json @code-yeongyu
diff --git a/plugins/omo/components/comment-checker/.github/ISSUE_TEMPLATE/bug.yml b/plugins/omo/components/comment-checker/.github/ISSUE_TEMPLATE/bug.yml
new file mode 100644
index 00000000..c6c32ba1
--- /dev/null
+++ b/plugins/omo/components/comment-checker/.github/ISSUE_TEMPLATE/bug.yml
@@ -0,0 +1,40 @@
+name: Bug Report
+description: Report broken Codex hook, MCP, or comment-checking behavior
+labels: [bug]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Include the Codex tool payload, hook output, and plugin version needed to reproduce.
+
+ - type: textarea
+ id: what
+ attributes:
+ label: What happened?
+ description: Include exact output/errors.
+ validations:
+ required: true
+
+ - type: textarea
+ id: payload
+ attributes:
+ label: Tool payload
+ description: Paste the minimal PostToolUse or MCP payload that reproduces the issue.
+ render: json
+ validations:
+ required: false
+
+ - type: textarea
+ id: expected
+ attributes:
+ label: Expected behavior
+ validations:
+ required: true
+
+ - type: input
+ id: version
+ attributes:
+ label: codex-comment-checker version
+ placeholder: 0.1.0
+ validations:
+ required: false
diff --git a/plugins/omo/components/comment-checker/.github/ISSUE_TEMPLATE/feature.yml b/plugins/omo/components/comment-checker/.github/ISSUE_TEMPLATE/feature.yml
new file mode 100644
index 00000000..817e49c9
--- /dev/null
+++ b/plugins/omo/components/comment-checker/.github/ISSUE_TEMPLATE/feature.yml
@@ -0,0 +1,27 @@
+name: Feature Request
+description: Propose a Codex comment-checker hook or MCP improvement
+labels: [enhancement]
+body:
+ - type: textarea
+ id: problem
+ attributes:
+ label: Problem
+ description: What workflow is blocked or awkward today?
+ validations:
+ required: true
+
+ - type: textarea
+ id: proposal
+ attributes:
+ label: Proposal
+ description: What should codex-comment-checker do?
+ validations:
+ required: true
+
+ - type: textarea
+ id: alternatives
+ attributes:
+ label: Alternatives considered
+ description: What else could solve this?
+ validations:
+ required: false
diff --git a/plugins/omo/components/comment-checker/.github/branch-ruleset.json b/plugins/omo/components/comment-checker/.github/branch-ruleset.json
new file mode 100644
index 00000000..1f482bb6
--- /dev/null
+++ b/plugins/omo/components/comment-checker/.github/branch-ruleset.json
@@ -0,0 +1,45 @@
+{
+ "name": "main protection",
+ "target": "branch",
+ "enforcement": "active",
+ "conditions": {
+ "ref_name": {
+ "include": ["~DEFAULT_BRANCH"],
+ "exclude": []
+ }
+ },
+ "rules": [
+ { "type": "deletion" },
+ { "type": "non_fast_forward" },
+ { "type": "required_linear_history" },
+ {
+ "type": "pull_request",
+ "parameters": {
+ "required_approving_review_count": 1,
+ "dismiss_stale_reviews_on_push": true,
+ "require_code_owner_review": true,
+ "require_last_push_approval": false,
+ "required_review_thread_resolution": true
+ }
+ },
+ {
+ "type": "required_status_checks",
+ "parameters": {
+ "strict_required_status_checks_policy": true,
+ "required_status_checks": [
+ { "context": "test (ubuntu-latest · node 20)" },
+ { "context": "test (ubuntu-latest · node 22)" },
+ { "context": "test (macos-latest · node 20)" },
+ { "context": "test (macos-latest · node 22)" }
+ ]
+ }
+ }
+ ],
+ "bypass_actors": [
+ {
+ "actor_id": 5,
+ "actor_type": "RepositoryRole",
+ "bypass_mode": "always"
+ }
+ ]
+}
diff --git a/plugins/omo/components/comment-checker/.github/dependabot.yml b/plugins/omo/components/comment-checker/.github/dependabot.yml
new file mode 100644
index 00000000..1941ade1
--- /dev/null
+++ b/plugins/omo/components/comment-checker/.github/dependabot.yml
@@ -0,0 +1,16 @@
+version: 2
+updates:
+ - package-ecosystem: npm
+ directory: /
+ schedule:
+ interval: weekly
+ open-pull-requests-limit: 5
+ groups:
+ dev-dependencies:
+ dependency-type: development
+
+ - package-ecosystem: github-actions
+ directory: /
+ schedule:
+ interval: weekly
+ open-pull-requests-limit: 5
diff --git a/plugins/omo/components/comment-checker/.github/pull_request_template.md b/plugins/omo/components/comment-checker/.github/pull_request_template.md
new file mode 100644
index 00000000..9453fc8e
--- /dev/null
+++ b/plugins/omo/components/comment-checker/.github/pull_request_template.md
@@ -0,0 +1,19 @@
+## Summary
+
+<!-- Brief description, 1-3 bullets -->
+
+-
+
+## Verification
+
+- [ ] `npm run check` (typecheck + biome + build)
+- [ ] `npm test` (unit tests)
+- [ ] `npm pack --dry-run` (release sanity)
+- [ ] Hook smoke-tested locally with `node dist/cli.js hook post-tool-use`
+
+## Codex plugin impact
+
+- [ ] `.codex-plugin/plugin.json` remains valid
+- [ ] `hooks/hooks.json` still uses stable Codex hook JSON
+- [ ] No MCP server or MCP tool is exposed
+- [ ] CHANGELOG entry added for user-facing changes
diff --git a/plugins/omo/components/comment-checker/.github/workflows/ci.yml b/plugins/omo/components/comment-checker/.github/workflows/ci.yml
new file mode 100644
index 00000000..6cc7a165
--- /dev/null
+++ b/plugins/omo/components/comment-checker/.github/workflows/ci.yml
@@ -0,0 +1,47 @@
+name: ci
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ name: test (${{ matrix.os }} · node ${{ matrix.node }})
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 15
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ node: ["20", "22"]
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+
+ - name: Setup Node ${{ matrix.node }}
+ uses: actions/setup-node@v6
+ with:
+ node-version: ${{ matrix.node }}
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Check
+ run: npm run check
+
+ - name: Unit tests
+ run: npm test
+
+ - name: Package smoke
+ run: npm pack --dry-run
diff --git a/plugins/omo/components/comment-checker/.github/workflows/publish.yml b/plugins/omo/components/comment-checker/.github/workflows/publish.yml
new file mode 100644
index 00000000..4214a99b
--- /dev/null
+++ b/plugins/omo/components/comment-checker/.github/workflows/publish.yml
@@ -0,0 +1,51 @@
+name: publish
+
+on:
+ release:
+ types: [published]
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: false
+
+permissions:
+ contents: read
+ id-token: write
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+
+ - name: Setup Node 22
+ uses: actions/setup-node@v6
+ with:
+ node-version: "22"
+ registry-url: https://registry.npmjs.org
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Check
+ run: npm run check
+
+ - name: Unit tests
+ run: npm test
+
+ - name: Package smoke
+ run: npm pack --dry-run
+
+ - name: Publish to npm
+ run: |
+ if [ -z "$NODE_AUTH_TOKEN" ]; then
+ echo "NODE_AUTH_TOKEN is not configured; skipping npm publish."
+ exit 0
+ fi
+ npm publish --access public --provenance
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NODE_AUTH_TOKEN }}
diff --git a/plugins/omo/components/comment-checker/.gitignore b/plugins/omo/components/comment-checker/.gitignore
new file mode 100644
index 00000000..af760374
--- /dev/null
+++ b/plugins/omo/components/comment-checker/.gitignore
@@ -0,0 +1,7 @@
+node_modules/
+*.log
+.DS_Store
+.env
+.env.*
+coverage/
+.vitest/
diff --git a/plugins/omo/components/comment-checker/AGENTS.md b/plugins/omo/components/comment-checker/AGENTS.md
new file mode 100644
index 00000000..fc3449eb
--- /dev/null
+++ b/plugins/omo/components/comment-checker/AGENTS.md
@@ -0,0 +1,35 @@
+# Repository Conventions
+
+Conventions for human contributors and AI agents working on this repository.
+
+## Style
+
+- Terse technical prose. No emojis in commits, issues, PR comments, or code.
+- TypeScript strict mode. No `any`, no `unknown` casts where avoidable, no `@ts-ignore`, no `@ts-expect-error`, no enums.
+- ESM modules with `.js` suffix in runtime import paths.
+- Tabs for indentation. Double quotes for strings.
+- Tests use vitest with `#given .. #when .. #then` descriptions or plain `// given / // when / // then` body comments.
+
+## Commands
+
+- `npm install` - install dependencies.
+- `npm test` - run vitest once.
+- `npm run typecheck` - strict TypeScript check.
+- `npm run check` - type check, biome, and build.
+- `npm pack --dry-run` - release package smoke test.
+- `node dist/cli.js hook post-tool-use < fixture.json` - smoke-test the Codex hook.
+
+## Constraints
+
+- No Bun APIs. Runtime is Node only because Codex launches plugin hooks with Node.
+- Keep Codex `PostToolUse` hook behavior covered by tests.
+- Keep `apply_patch` extraction covered by tests.
+- `apply_patch` must support Codex `tool_input.command`, raw patch text, and OMO-compatible metadata.
+- Hook output must use the stable Codex hook JSON contract.
+- Do not expose an MCP server or MCP tool from this plugin.
+
+## Don'ts
+
+- No `git add -A` or `git add .`. Stage only the files you changed.
+- No `git commit --no-verify`. No force pushes. No history rewriting on shared branches.
+- Do not couple this package back to pi, omo, or senpi internal source paths.
diff --git a/plugins/omo/components/comment-checker/CHANGELOG.md b/plugins/omo/components/comment-checker/CHANGELOG.md
new file mode 100644
index 00000000..c5b91529
--- /dev/null
+++ b/plugins/omo/components/comment-checker/CHANGELOG.md
@@ -0,0 +1,33 @@
+# Changelog
+
+## Unreleased
+
+### Added
+
+- Restore `write`, `edit`, `multi_edit`, and `multiedit` PostToolUse coverage alongside `apply_patch`.
+- Forward Codex `transcript_path` into native comment-checker hook input when available.
+- Add package smoke coverage for portable hook entrypoints.
+
+### Changed
+
+- Treat the native checker binary as an optional dependency for unsupported platforms.
+- Cap child process stdout/stderr captured from the native checker.
+- Run CI on Windows in addition to Ubuntu and macOS.
+
+## [0.1.1] - 2026-05-15
+
+### Changed
+
+- Limit automatic comment checking to successful `apply_patch` hook events.
+- Remove the `comment_check` MCP tool and MCP server configuration.
+- Update plugin metadata, docs, and contributor guidance to describe hook-only behavior.
+
+## [0.1.0] - 2026-05-15
+
+### Added
+
+- Initial `codex-comment-checker` Codex plugin.
+- `PostToolUse` hook for `apply_patch`, `write`, `edit`, and `multiedit` style tool calls.
+- Blocking hook feedback when `comment-checker` reports warnings.
+- `comment_check` MCP tool for explicit write/edit/multiedit checks.
+- Codex plugin manifest, local MCP config, bundled skill, and GitHub repository metadata.
diff --git a/plugins/omo/components/comment-checker/LICENSE b/plugins/omo/components/comment-checker/LICENSE
new file mode 100644
index 00000000..09aac3c3
--- /dev/null
+++ b/plugins/omo/components/comment-checker/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Yeongyu Kim
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/plugins/omo/components/comment-checker/NOTICE b/plugins/omo/components/comment-checker/NOTICE
new file mode 100644
index 00000000..5b363ec2
--- /dev/null
+++ b/plugins/omo/components/comment-checker/NOTICE
@@ -0,0 +1,6 @@
+codex-comment-checker
+
+This package ports the pi-comment-checker hook into a Codex plugin repository.
+
+The plugin targets Codex plugin manifests and plugin-bundled lifecycle hooks.
+The checker engine is provided by @code-yeongyu/comment-checker.
diff --git a/plugins/omo/components/comment-checker/README.md b/plugins/omo/components/comment-checker/README.md
new file mode 100644
index 00000000..d48d38f8
--- /dev/null
+++ b/plugins/omo/components/comment-checker/README.md
@@ -0,0 +1,87 @@
+# codex-comment-checker
+
+[![ci](https://github.com/code-yeongyu/codex-comment-checker/actions/workflows/ci.yml/badge.svg)](https://github.com/code-yeongyu/codex-comment-checker/actions/workflows/ci.yml) [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
+
+Codex plugin that runs [`@code-yeongyu/comment-checker`](https://github.com/code-yeongyu/go-claude-code-comment-checker) after successful edit-like `PostToolUse` hook calls.
+
+## Behavior
+
+| Case | Result |
+|------|--------|
+| `apply_patch` succeeds | parses `tool_input.command` and checks added/updated files |
+| `write`, `edit`, `multi_edit`, or `multiedit` succeeds | maps the Codex payload to the native checker hook input |
+| non-edit tool succeeds | ignored |
+| checker exits `2` | returns Codex `PostToolUse` blocking feedback so the model fixes or explains the warning |
+| checker binary missing or unavailable on the current platform | emits no hook output |
+| checker exits unexpectedly | leaves hook output unchanged |
+
+Deletes are ignored because they cannot introduce new comments.
+
+## Codex Plugin
+
+The plugin ships:
+
+- `.codex-plugin/plugin.json` for Codex plugin discovery.
+- `hooks/hooks.json` for the `PostToolUse` hook.
+- `skills/comment-checker/SKILL.md` with usage guidance.
+
+The hook command is:
+
+```bash
+node "${PLUGIN_ROOT}/dist/cli.js" hook post-tool-use
+```
+
+No MCP server or `comment_check` tool is exposed.
+
+## Local Development
+
+```bash
+npm install
+npm test
+npm run typecheck
+npm run check
+npm pack --dry-run
+```
+
+Smoke-test the hook:
+
+```bash
+node dist/cli.js hook post-tool-use < test/fixtures/post-tool-use.json
+```
+
+## Local Codex Installation
+
+```bash
+bunx lazycodex install
+```
+
+The installer builds and copies the plugin into `~/.codex/plugins/cache/sisyphuslabs/omo/0.1.0`, registers the `sisyphuslabs` marketplace from the `lazycodex` Git repository, installs runtime dependencies there, and enables:
+
+```toml
+[features]
+plugins = true
+plugin_hooks = true
+
+[plugins."omo@sisyphuslabs"]
+enabled = true
+```
+
+## Branch Rules and Releases
+
+- `main` is protected by `.github/branch-ruleset.json`.
+- CI runs Node 20 and 22 on Ubuntu, macOS, and Windows.
+- Releases are GitHub Releases tagged as `v<semver>`.
+- Publishing runs from the `publish` workflow after a GitHub Release is published.
+
+## Privacy
+
+This plugin runs locally. It sends hook input to the optional local `comment-checker` binary when available and does not call a network service by itself.
+
+## License
+
+[MIT](LICENSE).
+
+## Related
+
+- [pi-comment-checker](https://github.com/code-yeongyu/pi-comment-checker) - source extension this Codex plugin ports.
+- [comment-checker](https://github.com/code-yeongyu/go-claude-code-comment-checker) - native checker binary.
diff --git a/plugins/omo/components/comment-checker/biome.json b/plugins/omo/components/comment-checker/biome.json
new file mode 100644
index 00000000..5aa1a0dc
--- /dev/null
+++ b/plugins/omo/components/comment-checker/biome.json
@@ -0,0 +1,48 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.4.15/schema.json",
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "recommended": true,
+ "style": {
+ "noDefaultExport": "error",
+ "noEnum": "error",
+ "noNonNullAssertion": "error",
+ "useImportType": "error",
+ "useConst": "error",
+ "useNodejsImportProtocol": "off"
+ },
+ "complexity": {
+ "useLiteralKeys": "off"
+ },
+ "suspicious": {
+ "noExplicitAny": "error",
+ "noTsIgnore": "error",
+ "noControlCharactersInRegex": "off",
+ "noEmptyInterface": "off"
+ }
+ }
+ },
+ "formatter": {
+ "enabled": true,
+ "formatWithErrors": false,
+ "indentStyle": "tab",
+ "indentWidth": 3,
+ "lineWidth": 120
+ },
+ "files": {
+ "includes": ["src/**/*.ts", "test/**/*.ts", "vitest.config.ts", "!**/node_modules/**/*", "!**/dist/**/*"]
+ },
+ "overrides": [
+ {
+ "includes": ["vitest.config.ts"],
+ "linter": {
+ "rules": {
+ "style": {
+ "noDefaultExport": "off"
+ }
+ }
+ }
+ }
+ ]
+}
diff --git a/plugins/omo/components/comment-checker/hooks/hooks.json b/plugins/omo/components/comment-checker/hooks/hooks.json
new file mode 100644
index 00000000..96fc9649
--- /dev/null
+++ b/plugins/omo/components/comment-checker/hooks/hooks.json
@@ -0,0 +1,17 @@
+{
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "^(apply_patch|write|Write|edit|Edit|multi_edit|multiedit|MultiEdit)$",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use",
+ "timeout": 30,
+ "statusMessage": "checking comments"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/omo/components/comment-checker/package.json b/plugins/omo/components/comment-checker/package.json
new file mode 100644
index 00000000..44f855e5
--- /dev/null
+++ b/plugins/omo/components/comment-checker/package.json
@@ -0,0 +1,57 @@
+{
+ "name": "@code-yeongyu/codex-comment-checker",
+ "version": "0.1.1",
+ "description": "Codex plugin that runs comment-checker after edit-like PostToolUse hooks.",
+ "type": "module",
+ "packageManager": "[email protected]",
+ "license": "MIT",
+ "homepage": "https://github.com/code-yeongyu/codex-comment-checker",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/code-yeongyu/codex-comment-checker.git"
+ },
+ "bugs": {
+ "url": "https://github.com/code-yeongyu/codex-comment-checker/issues"
+ },
+ "keywords": [
+ "codex",
+ "codex-plugin",
+ "comment-checker",
+ "hooks",
+ "typescript"
+ ],
+ "bin": {
+ "codex-comment-checker": "./dist/cli.js"
+ },
+ "files": [
+ "dist",
+ "hooks",
+ "skills",
+ ".codex-plugin",
+ "LICENSE",
+ "NOTICE",
+ "README.md",
+ "CHANGELOG.md"
+ ],
+ "scripts": {
+ "build": "tsc -p tsconfig.build.json",
+ "test": "vitest --run",
+ "test:watch": "vitest",
+ "typecheck": "tsc --noEmit",
+ "lint": "biome check .",
+ "lint:fix": "biome check --write .",
+ "check": "tsc --noEmit && biome check . && npm run build"
+ },
+ "optionalDependencies": {
+ "@code-yeongyu/comment-checker": "^0.8.0"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.15",
+ "@types/node": "^25.7.0",
+ "typescript": "^6.0.3",
+ "vitest": "^4.1.5"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+}
diff --git a/plugins/omo/components/comment-checker/skills/comment-checker/SKILL.md b/plugins/omo/components/comment-checker/skills/comment-checker/SKILL.md
new file mode 100644
index 00000000..7ce77101
--- /dev/null
+++ b/plugins/omo/components/comment-checker/skills/comment-checker/SKILL.md
@@ -0,0 +1,16 @@
+---
+name: comment-checker
+description: Use when Codex needs to understand or respond to automatic comment-checker feedback emitted after an edit-like PostToolUse hook.
+---
+
+# Codex Comment Checker
+
+The plugin registers a `PostToolUse` hook for successful `apply_patch`, `write`, `edit`, `multi_edit`, and `multiedit` calls.
+
+When comment-checker reports a warning after a patch, Codex receives blocking feedback and should fix or explain the flagged comment before moving on.
+
+## Scope
+
+- No MCP tool is exposed.
+- Non-edit tools are ignored by this plugin.
+- Missing checker binaries emit no hook output so normal Codex work can continue.
diff --git a/plugins/omo/components/comment-checker/src/cli.ts b/plugins/omo/components/comment-checker/src/cli.ts
new file mode 100644
index 00000000..ca899182
--- /dev/null
+++ b/plugins/omo/components/comment-checker/src/cli.ts
@@ -0,0 +1,12 @@
+#!/usr/bin/env node
+
+import { runCodexHookCli } from "./codex-hook.js";
+
+const [command, subcommand] = process.argv.slice(2);
+
+if (command === "hook" && subcommand === "post-tool-use") {
+ await runCodexHookCli();
+} else {
+ process.stderr.write("Usage: codex-comment-checker hook post-tool-use\n");
+ process.exitCode = 2;
+}
diff --git a/plugins/omo/components/comment-checker/src/codex-hook.ts b/plugins/omo/components/comment-checker/src/codex-hook.ts
new file mode 100644
index 00000000..ae76cea5
--- /dev/null
+++ b/plugins/omo/components/comment-checker/src/codex-hook.ts
@@ -0,0 +1,159 @@
+import { stdin as processStdin, stdout as processStdout } from "node:process";
+
+import {
+ type CommentCheckRequest,
+ extractCommentCheckRequests,
+ isRecord,
+ type ToolResultContent,
+ type ToolResultLike,
+ toHookInput,
+} from "./core.js";
+import { type CommentCheckerRunner, runCommentChecker } from "./runner.js";
+
+export type CodexPostToolUseInput = {
+ session_id: string;
+ turn_id: string;
+ transcript_path: string | null;
+ cwd: string;
+ hook_event_name: "PostToolUse";
+ model: string;
+ permission_mode: string;
+ tool_name: string;
+ tool_input: Record<string, unknown>;
+ tool_response: unknown;
+ tool_use_id: string;
+};
+
+export type CodexHookOptions = {
+ run?: CommentCheckerRunner;
+};
+
+export function extractCodexCommentCheckRequests(input: CodexPostToolUseInput): CommentCheckRequest[] {
+ return extractCommentCheckRequests(toToolResultLike(input));
+}
+
+export async function runCommentCheckerPostToolUse(
+ input: CodexPostToolUseInput,
+ options: CodexHookOptions = {},
+): Promise<string> {
+ const requests = extractCodexCommentCheckRequests(input);
+ if (requests.length === 0) return "";
+
+ const runner = options.run ?? runCommentChecker;
+ const warnings: Array<{ filePath: string; message: string }> = [];
+
+ for (const request of requests) {
+ const context = {
+ sessionId: input.session_id,
+ cwd: input.cwd,
+ ...(input.transcript_path === null ? {} : { transcriptPath: input.transcript_path }),
+ };
+ const result = await runner(toHookInput(request, context));
+ if (result.status === "missing" || result.status === "pass") continue;
+ if (result.status === "error") continue;
+ const message = result.message.trim();
+ if (message.length > 0) {
+ warnings.push({ filePath: request.filePath, message });
+ }
+ }
+
+ if (warnings.length === 0) return "";
+
+ return JSON.stringify({
+ decision: "block",
+ reason: formatWarnings(warnings),
+ });
+}
+
+export async function runCodexHookCli(): Promise<void> {
+ const input = await readStdin();
+ if (input.trim().length === 0) return;
+ const parsed = parseCodexPostToolUseInput(input);
+ if (!parsed) return;
+ const output = await runCommentCheckerPostToolUse(parsed);
+ if (output.length > 0) {
+ processStdout.write(output);
+ processStdout.write("\n");
+ }
+}
+
+export function parseCodexPostToolUseInput(input: string): CodexPostToolUseInput | undefined {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(input);
+ } catch {
+ return undefined;
+ }
+ return isCodexPostToolUseInput(parsed) ? parsed : undefined;
+}
+
+function toToolResultLike(input: CodexPostToolUseInput): ToolResultLike {
+ return {
+ toolName: input.tool_name,
+ input: normalizeToolInput(input.tool_name, input.tool_input),
+ content: normalizeToolResponse(input.tool_response),
+ isError: isErrorResponse(input.tool_response),
+ details: isRecord(input.tool_response) ? input.tool_response : undefined,
+ };
+}
+
+function normalizeToolInput(toolName: string, toolInput: Record<string, unknown>): Record<string, unknown> {
+ if (toolName === "apply_patch" && typeof toolInput["command"] === "string") {
+ return {
+ ...toolInput,
+ input: toolInput["command"],
+ patch: toolInput["command"],
+ };
+ }
+ return toolInput;
+}
+
+function normalizeToolResponse(toolResponse: unknown): ToolResultContent[] {
+ if (typeof toolResponse === "string") {
+ return [{ type: "text", text: toolResponse }];
+ }
+ if (isRecord(toolResponse) && typeof toolResponse["text"] === "string") {
+ return [{ type: "text", text: toolResponse["text"] }];
+ }
+ return [];
+}
+
+function isErrorResponse(toolResponse: unknown): boolean {
+ return isRecord(toolResponse) && toolResponse["is_error"] === true;
+}
+
+function formatWarnings(warnings: Array<{ filePath: string; message: string }>): string {
+ return warnings
+ .map((warning) => `comment-checker found issues in ${warning.filePath}:\n${warning.message}`)
+ .join("\n\n");
+}
+
+function isCodexPostToolUseInput(value: unknown): value is CodexPostToolUseInput {
+ return (
+ isRecord(value) &&
+ value["hook_event_name"] === "PostToolUse" &&
+ typeof value["session_id"] === "string" &&
+ typeof value["turn_id"] === "string" &&
+ (typeof value["transcript_path"] === "string" || value["transcript_path"] === null) &&
+ typeof value["cwd"] === "string" &&
+ typeof value["model"] === "string" &&
+ typeof value["permission_mode"] === "string" &&
+ typeof value["tool_name"] === "string" &&
+ isRecord(value["tool_input"]) &&
+ typeof value["tool_use_id"] === "string"
+ );
+}
+
+function readStdin(): Promise<string> {
+ return new Promise((resolve, reject) => {
+ let data = "";
+ processStdin.setEncoding("utf-8");
+ processStdin.on("data", (chunk: string) => {
+ data += chunk;
+ });
+ processStdin.once("error", reject);
+ processStdin.once("end", () => {
+ resolve(data);
+ });
+ });
+}
diff --git a/plugins/omo/components/comment-checker/src/core.ts b/plugins/omo/components/comment-checker/src/core.ts
new file mode 100644
index 00000000..d8506d69
--- /dev/null
+++ b/plugins/omo/components/comment-checker/src/core.ts
@@ -0,0 +1,361 @@
+export type TextContent = {
+ type: "text";
+ text: string;
+};
+
+export type ImageContent = {
+ type: "image";
+ data: string;
+ mimeType: string;
+};
+
+export type CheckerToolName = "Write" | "Edit" | "MultiEdit";
+
+export type CheckerEdit = {
+ old_string: string;
+ new_string: string;
+};
+
+export type CheckerToolInput = {
+ file_path: string;
+ content?: string;
+ old_string?: string;
+ new_string?: string;
+ edits?: CheckerEdit[];
+};
+
+export type CommentCheckRequest = {
+ sourceToolName: string;
+ toolName: CheckerToolName;
+ filePath: string;
+ toolInput: CheckerToolInput;
+};
+
+export type CommentCheckerHookInput = {
+ session_id: string;
+ tool_name: CheckerToolName;
+ transcript_path: string;
+ cwd: string;
+ hook_event_name: "PostToolUse";
+ tool_input: CheckerToolInput;
+};
+
+export type ToolResultContent = TextContent | ImageContent;
+
+export type ToolResultLike = {
+ toolName: string;
+ input: Record<string, unknown>;
+ content?: ToolResultContent[];
+ isError?: boolean;
+ details?: unknown;
+};
+
+type ApplyPatchAccumulator = {
+ operation: "add" | "delete" | "update";
+ filePath: string;
+ movePath?: string;
+ oldLines: string[];
+ newLines: string[];
+};
+
+type ApplyPatchFileMetadata = {
+ filePath: string;
+ movePath?: string;
+ before: string;
+ after: string;
+ type?: string;
+};
+
+export function extractCommentCheckRequests(event: ToolResultLike): CommentCheckRequest[] {
+ if (event.isError) return [];
+ if (isToolFailureOutput(getContentText(event.content))) return [];
+
+ const toolName = event.toolName.toLowerCase();
+ if (toolName === "write") return extractWriteRequest(event);
+ if (toolName === "edit") return extractEditRequest(event);
+ if (toolName === "multiedit" || toolName === "multi_edit") return extractMultiEditRequest(event);
+ if (toolName === "apply_patch") return extractApplyPatchRequests(event);
+ return [];
+}
+
+export function toHookInput(
+ request: CommentCheckRequest,
+ context: {
+ sessionId: string;
+ cwd: string;
+ transcriptPath?: string;
+ },
+): CommentCheckerHookInput {
+ return {
+ session_id: context.sessionId,
+ tool_name: request.toolName,
+ transcript_path: context.transcriptPath ?? "",
+ cwd: context.cwd,
+ hook_event_name: "PostToolUse",
+ tool_input: request.toolInput,
+ };
+}
+
+export function isToolFailureOutput(text: string): boolean {
+ const lower = text.trim().toLowerCase();
+ return (
+ lower.startsWith("error") ||
+ lower.includes("error:") ||
+ lower.includes("failed to") ||
+ lower.includes("could not")
+ );
+}
+
+function extractWriteRequest(event: ToolResultLike): CommentCheckRequest[] {
+ const filePath = getString(event.input, ["filePath", "file_path", "path"]);
+ const content = getString(event.input, ["content"]);
+ if (!filePath || content === undefined) return [];
+ return [
+ {
+ sourceToolName: event.toolName,
+ toolName: "Write",
+ filePath,
+ toolInput: {
+ file_path: filePath,
+ content,
+ },
+ },
+ ];
+}
+
+function extractEditRequest(event: ToolResultLike): CommentCheckRequest[] {
+ const filePath = getString(event.input, ["filePath", "file_path", "path"]);
+ const oldString = getString(event.input, ["oldString", "old_string"]);
+ const newString = getString(event.input, ["newString", "new_string"]);
+ if (!filePath || oldString === undefined || newString === undefined) return [];
+ const toolInput: CheckerToolInput = { file_path: filePath };
+ toolInput.old_string = oldString;
+ toolInput.new_string = newString;
+ return [
+ {
+ sourceToolName: event.toolName,
+ toolName: "Edit",
+ filePath,
+ toolInput,
+ },
+ ];
+}
+
+function extractMultiEditRequest(event: ToolResultLike): CommentCheckRequest[] {
+ const filePath = getString(event.input, ["filePath", "file_path", "path"]);
+ const edits = getEdits(event.input["edits"]);
+ if (!filePath || edits.length === 0) return [];
+ return [
+ {
+ sourceToolName: event.toolName,
+ toolName: "MultiEdit",
+ filePath,
+ toolInput: {
+ file_path: filePath,
+ edits,
+ },
+ },
+ ];
+}
+
+function extractApplyPatchRequests(event: ToolResultLike): CommentCheckRequest[] {
+ const metadataRequests = extractApplyPatchMetadataRequests(event.details, event.toolName);
+ if (metadataRequests.length > 0) return metadataRequests;
+
+ const patch = getString(event.input, ["input", "patch", "command"]);
+ if (!patch) return [];
+ return parseApplyPatchRequests(patch, event.toolName);
+}
+
+function extractApplyPatchMetadataRequests(details: unknown, sourceToolName: string): CommentCheckRequest[] {
+ const metadataFiles = getApplyPatchMetadataFiles(details);
+ if (metadataFiles.length === 0) return [];
+
+ const requests: CommentCheckRequest[] = [];
+ for (const file of metadataFiles) {
+ if (file.type === "delete") continue;
+ const filePath = file.movePath ?? file.filePath;
+ if (file.before.length === 0) {
+ requests.push({
+ sourceToolName,
+ toolName: "Write",
+ filePath,
+ toolInput: {
+ file_path: filePath,
+ content: file.after,
+ },
+ });
+ continue;
+ }
+ requests.push({
+ sourceToolName,
+ toolName: "Edit",
+ filePath,
+ toolInput: {
+ file_path: filePath,
+ old_string: file.before,
+ new_string: file.after,
+ },
+ });
+ }
+ return requests;
+}
+
+function getApplyPatchMetadataFiles(details: unknown): ApplyPatchFileMetadata[] {
+ if (!isRecord(details)) return [];
+ const direct = readApplyPatchMetadataFiles(details["files"]);
+ if (direct.length > 0) return direct;
+ const resultDetails = details["result"];
+ const result = isRecord(resultDetails) ? readApplyPatchMetadataFiles(resultDetails["files"]) : [];
+ if (result.length > 0) return result;
+ const metadataDetails = details["metadata"];
+ const metadata = isRecord(metadataDetails) ? readApplyPatchMetadataFiles(metadataDetails["files"]) : [];
+ return metadata;
+}
+
+function readApplyPatchMetadataFiles(value: unknown): ApplyPatchFileMetadata[] {
+ if (!Array.isArray(value)) return [];
+ const files: ApplyPatchFileMetadata[] = [];
+ for (const item of value) {
+ if (!isRecord(item)) continue;
+ const filePath = getString(item, ["filePath", "file_path", "path"]);
+ const movePath = getString(item, ["movePath", "move_path"]);
+ const before = getString(item, ["before", "old", "oldString", "old_string"]);
+ const after = getString(item, ["after", "new", "newString", "new_string"]);
+ const type = getString(item, ["type", "operation"]);
+ if (!filePath || before === undefined || after === undefined) continue;
+ files.push({
+ filePath,
+ before,
+ after,
+ ...(movePath === undefined ? {} : { movePath }),
+ ...(type === undefined ? {} : { type }),
+ });
+ }
+ return files;
+}
+
+export function parseApplyPatchRequests(patch: string, sourceToolName = "apply_patch"): CommentCheckRequest[] {
+ const requests: CommentCheckRequest[] = [];
+ let current: ApplyPatchAccumulator | undefined;
+
+ const flush = (): void => {
+ if (!current) return;
+ if (current.operation === "add") {
+ const content = joinPatchLines(current.newLines);
+ if (content.length > 0) {
+ requests.push({
+ sourceToolName,
+ toolName: "Write",
+ filePath: current.filePath,
+ toolInput: {
+ file_path: current.filePath,
+ content,
+ },
+ });
+ }
+ }
+ if (current.operation === "update") {
+ const newString = joinPatchLines(current.newLines);
+ if (newString.length > 0) {
+ const filePath = current.movePath ?? current.filePath;
+ requests.push({
+ sourceToolName,
+ toolName: "Edit",
+ filePath,
+ toolInput: {
+ file_path: filePath,
+ old_string: joinPatchLines(current.oldLines),
+ new_string: newString,
+ },
+ });
+ }
+ }
+ current = undefined;
+ };
+
+ for (const line of patch.split(/\r?\n/)) {
+ if (line === "*** Begin Patch" || line === "*** End Patch") continue;
+ if (line.startsWith("*** Add File: ")) {
+ flush();
+ current = makeAccumulator("add", line.slice("*** Add File: ".length).trim());
+ continue;
+ }
+ if (line.startsWith("*** Update File: ")) {
+ flush();
+ current = makeAccumulator("update", line.slice("*** Update File: ".length).trim());
+ continue;
+ }
+ if (line.startsWith("*** Delete File: ")) {
+ flush();
+ current = makeAccumulator("delete", line.slice("*** Delete File: ".length).trim());
+ continue;
+ }
+ if (line.startsWith("*** Move to: ")) {
+ if (current?.operation === "update") current.movePath = line.slice("*** Move to: ".length).trim();
+ continue;
+ }
+ if (!current) continue;
+ if (line.startsWith("@@")) continue;
+ if (current.operation === "add") {
+ if (line.startsWith("+")) current.newLines.push(line.slice(1));
+ continue;
+ }
+ if (current.operation === "update") {
+ if (line.startsWith("+")) current.newLines.push(line.slice(1));
+ if (line.startsWith("-")) current.oldLines.push(line.slice(1));
+ }
+ }
+
+ flush();
+ return requests;
+}
+
+function makeAccumulator(operation: ApplyPatchAccumulator["operation"], filePath: string): ApplyPatchAccumulator {
+ return {
+ operation,
+ filePath,
+ oldLines: [],
+ newLines: [],
+ };
+}
+
+function getEdits(value: unknown): CheckerEdit[] {
+ if (!Array.isArray(value)) return [];
+ const edits: CheckerEdit[] = [];
+ for (const item of value) {
+ if (!isRecord(item)) continue;
+ const oldString = getString(item, ["oldString", "old_string"]);
+ const newString = getString(item, ["newString", "new_string"]);
+ if (oldString === undefined || newString === undefined) continue;
+ edits.push({
+ old_string: oldString,
+ new_string: newString,
+ });
+ }
+ return edits;
+}
+
+function getContentText(content: ToolResultContent[] | undefined): string {
+ if (!content) return "";
+ return content
+ .filter((block): block is TextContent => block.type === "text")
+ .map((block) => block.text)
+ .join("\n");
+}
+
+function getString(input: Record<string, unknown>, keys: string[]): string | undefined {
+ for (const key of keys) {
+ const value = input[key];
+ if (typeof value === "string") return value;
+ }
+ return undefined;
+}
+
+function joinPatchLines(lines: string[]): string {
+ return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
+}
+
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null;
+}
diff --git a/plugins/omo/components/comment-checker/src/runner.ts b/plugins/omo/components/comment-checker/src/runner.ts
new file mode 100644
index 00000000..7d6ce285
--- /dev/null
+++ b/plugins/omo/components/comment-checker/src/runner.ts
@@ -0,0 +1,195 @@
+import { spawn } from "node:child_process";
+import { existsSync } from "node:fs";
+import { createRequire } from "node:module";
+import { dirname, join } from "node:path";
+
+import type { CommentCheckerHookInput } from "./core.js";
+
+export type ProcessResult = {
+ exitCode: number | null;
+ stdout: string;
+ stderr: string;
+};
+
+export const MAX_PROCESS_OUTPUT_BYTES = 64 * 1024;
+
+export type ProcessExecutor = (command: string, args: string[], stdin: string) => Promise<ProcessResult>;
+
+export type RunCommentCheckerOptions = {
+ binaryPath?: string;
+ customPrompt?: string;
+ resolveBinary?: () => string | undefined;
+ executor?: ProcessExecutor;
+};
+
+export type CommentCheckerRunResult = {
+ status: "pass" | "warning" | "error" | "missing";
+ message: string;
+ binaryPath?: string;
+ exitCode?: number | null;
+ stdout?: string;
+ stderr?: string;
+};
+
+export type CommentCheckerRunner = (input: CommentCheckerHookInput) => Promise<CommentCheckerRunResult>;
+
+export async function runCommentChecker(
+ input: CommentCheckerHookInput,
+ options: RunCommentCheckerOptions = {},
+): Promise<CommentCheckerRunResult> {
+ const binaryPath =
+ options.binaryPath ?? (options.resolveBinary ? options.resolveBinary() : resolveCommentCheckerBinary());
+ if (!binaryPath) {
+ return {
+ status: "missing",
+ message: "comment-checker binary not found. Run npm install for the codex-comment-checker plugin.",
+ };
+ }
+
+ const args = ["check"];
+ if (options.customPrompt) {
+ args.push("--prompt", options.customPrompt);
+ }
+
+ const executor = options.executor ?? spawnProcess;
+ const result = await executor(binaryPath, args, JSON.stringify(input));
+ const message = result.stderr || result.stdout;
+ if (result.exitCode === 0) {
+ return {
+ status: "pass",
+ message: "",
+ binaryPath,
+ exitCode: result.exitCode,
+ stdout: result.stdout,
+ stderr: result.stderr,
+ };
+ }
+ if (result.exitCode === 2) {
+ return {
+ status: "warning",
+ message,
+ binaryPath,
+ exitCode: result.exitCode,
+ stdout: result.stdout,
+ stderr: result.stderr,
+ };
+ }
+ return {
+ status: "error",
+ message,
+ binaryPath,
+ exitCode: result.exitCode,
+ stdout: result.stdout,
+ stderr: result.stderr,
+ };
+}
+
+export function resolveCommentCheckerBinary(): string | undefined {
+ const binaryName = process.platform === "win32" ? "comment-checker.exe" : "comment-checker";
+ const fromPackageApi = resolvePackageApiBinary();
+ if (fromPackageApi) return fromPackageApi;
+ const fromPackage = resolvePackageBinary(binaryName);
+ if (fromPackage) return fromPackage;
+ return undefined;
+}
+
+function resolvePackageApiBinary(): string | undefined {
+ try {
+ const require = createRequire(import.meta.url);
+ const packageExports: unknown = require("@code-yeongyu/comment-checker");
+ if (!isCommentCheckerPackage(packageExports)) return undefined;
+ const binaryPath = packageExports.getBinaryPath();
+ return existsSync(binaryPath) ? binaryPath : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function resolvePackageBinary(binaryName: string): string | undefined {
+ try {
+ const require = createRequire(import.meta.url);
+ const packagePath = require.resolve("@code-yeongyu/comment-checker/package.json");
+ const binaryPath = join(dirname(packagePath), "bin", binaryName);
+ return existsSync(binaryPath) ? binaryPath : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+function isCommentCheckerPackage(value: unknown): value is { getBinaryPath: () => string } {
+ return isRecord(value) && typeof value["getBinaryPath"] === "function";
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null;
+}
+
+interface OutputAccumulator {
+ text: string;
+ bytes: number;
+ truncated: boolean;
+}
+
+function appendOutput(output: OutputAccumulator, chunk: string, maxOutputBytes: number): void {
+ if (output.truncated) return;
+
+ const remainingBytes = maxOutputBytes - output.bytes;
+ const chunkBytes = Buffer.byteLength(chunk, "utf8");
+ if (chunkBytes <= remainingBytes) {
+ output.text += chunk;
+ output.bytes += chunkBytes;
+ return;
+ }
+
+ if (remainingBytes > 0) {
+ output.text += Buffer.from(chunk, "utf8").subarray(0, remainingBytes).toString("utf8");
+ output.bytes += remainingBytes;
+ }
+ output.truncated = true;
+}
+
+function formatOutput(output: OutputAccumulator, streamName: "stdout" | "stderr", maxOutputBytes: number): string {
+ if (!output.truncated) return output.text;
+ return `${output.text}\n[${streamName} truncated after ${maxOutputBytes} bytes]`;
+}
+
+export function spawnProcess(
+ command: string,
+ args: string[],
+ stdin: string,
+ maxOutputBytes: number = MAX_PROCESS_OUTPUT_BYTES,
+): Promise<ProcessResult> {
+ return new Promise((resolve) => {
+ const outputByteLimit = Number.isFinite(maxOutputBytes) && maxOutputBytes > 0 ? Math.floor(maxOutputBytes) : 0;
+ const proc = spawn(command, args, {
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ const stdout: OutputAccumulator = { text: "", bytes: 0, truncated: false };
+ const stderr: OutputAccumulator = { text: "", bytes: 0, truncated: false };
+
+ proc.stdout.setEncoding("utf-8");
+ proc.stderr.setEncoding("utf-8");
+ proc.stdout.on("data", (chunk: string) => {
+ appendOutput(stdout, chunk, outputByteLimit);
+ });
+ proc.stderr.on("data", (chunk: string) => {
+ appendOutput(stderr, chunk, outputByteLimit);
+ });
+ proc.once("error", (error) => {
+ appendOutput(stderr, error.message, outputByteLimit);
+ resolve({
+ exitCode: null,
+ stdout: formatOutput(stdout, "stdout", outputByteLimit),
+ stderr: formatOutput(stderr, "stderr", outputByteLimit),
+ });
+ });
+ proc.once("close", (exitCode) => {
+ resolve({
+ exitCode,
+ stdout: formatOutput(stdout, "stdout", outputByteLimit),
+ stderr: formatOutput(stderr, "stderr", outputByteLimit),
+ });
+ });
+ proc.stdin.end(stdin);
+ });
+}
diff --git a/plugins/omo/components/comment-checker/test/codex-hook.test.ts b/plugins/omo/components/comment-checker/test/codex-hook.test.ts
new file mode 100644
index 00000000..7d12f7b3
--- /dev/null
+++ b/plugins/omo/components/comment-checker/test/codex-hook.test.ts
@@ -0,0 +1,317 @@
+import { spawn } from "node:child_process";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+
+import {
+ type CodexPostToolUseInput,
+ extractCodexCommentCheckRequests,
+ runCommentCheckerPostToolUse,
+} from "../src/codex-hook.ts";
+
+type CliResult = {
+ exitCode: number | null;
+ stdout: string;
+ stderr: string;
+};
+
+const CLI_PATH = fileURLToPath(new URL("../dist/cli.js", import.meta.url));
+
+function runHookCli(input: string): Promise<CliResult> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [CLI_PATH, "hook", "post-tool-use"], {
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ stdout += chunk;
+ });
+ child.stderr.on("data", (chunk: string) => {
+ stderr += chunk;
+ });
+ child.once("error", reject);
+ child.once("close", (exitCode) => {
+ resolve({ exitCode, stdout, stderr });
+ });
+ child.stdin.end(input);
+ });
+}
+
+function postToolUseInput(overrides: Partial<CodexPostToolUseInput> = {}): CodexPostToolUseInput {
+ return {
+ session_id: "thread-1",
+ turn_id: "turn-1",
+ transcript_path: null,
+ cwd: "/repo",
+ hook_event_name: "PostToolUse",
+ model: "gpt-5.5",
+ permission_mode: "never",
+ tool_name: "apply_patch",
+ tool_input: {
+ command: [
+ "*** Begin Patch",
+ "*** Update File: src/example.ts",
+ "@@",
+ "-const value = 1;",
+ "+// explains value",
+ "+const value = 2;",
+ "*** End Patch",
+ ].join("\n"),
+ },
+ tool_response: "Success. Updated files.",
+ tool_use_id: "call-1",
+ ...overrides,
+ };
+}
+
+describe("extractCodexCommentCheckRequests", () => {
+ it("#given codex apply_patch command #when extracting #then returns edit request for changed file", () => {
+ const requests = extractCodexCommentCheckRequests(postToolUseInput());
+
+ expect(requests).toEqual([
+ {
+ sourceToolName: "apply_patch",
+ toolName: "Edit",
+ filePath: "src/example.ts",
+ toolInput: {
+ file_path: "src/example.ts",
+ old_string: "const value = 1;\n",
+ new_string: "// explains value\nconst value = 2;\n",
+ },
+ },
+ ]);
+ });
+
+ it("#given unsupported post tool event #when extracting #then returns no requests", () => {
+ const requests = extractCodexCommentCheckRequests(
+ postToolUseInput({
+ tool_name: "read",
+ tool_input: { file_path: "src/example.ts", content: "// hi\nconst value = 1;\n" },
+ }),
+ );
+
+ expect(requests).toEqual([]);
+ });
+
+ it("#given codex write payload #when extracting #then returns write request", () => {
+ const requests = extractCodexCommentCheckRequests(
+ postToolUseInput({
+ tool_name: "write",
+ tool_input: {
+ file_path: "src/example.ts",
+ content: "// explains value\nconst value = 1;\n",
+ },
+ }),
+ );
+
+ expect(requests).toEqual([
+ {
+ sourceToolName: "write",
+ toolName: "Write",
+ filePath: "src/example.ts",
+ toolInput: {
+ file_path: "src/example.ts",
+ content: "// explains value\nconst value = 1;\n",
+ },
+ },
+ ]);
+ });
+
+ it("#given codex edit payload #when extracting #then returns edit request", () => {
+ const requests = extractCodexCommentCheckRequests(
+ postToolUseInput({
+ tool_name: "edit",
+ tool_input: {
+ path: "src/example.ts",
+ oldString: "const value = 1;\n",
+ newString: "// explains value\nconst value = 2;\n",
+ },
+ }),
+ );
+
+ expect(requests).toEqual([
+ {
+ sourceToolName: "edit",
+ toolName: "Edit",
+ filePath: "src/example.ts",
+ toolInput: {
+ file_path: "src/example.ts",
+ old_string: "const value = 1;\n",
+ new_string: "// explains value\nconst value = 2;\n",
+ },
+ },
+ ]);
+ });
+
+ it("#given one-sided codex edit payload #when extracting #then returns no requests", () => {
+ const requests = extractCodexCommentCheckRequests(
+ postToolUseInput({
+ tool_name: "edit",
+ tool_input: {
+ path: "src/example.ts",
+ oldString: "const value = 1;\n",
+ },
+ }),
+ );
+
+ expect(requests).toEqual([]);
+ });
+
+ it("#given codex multi_edit payload #when extracting #then returns multiedit request", () => {
+ const requests = extractCodexCommentCheckRequests(
+ postToolUseInput({
+ tool_name: "multi_edit",
+ tool_input: {
+ filePath: "src/example.ts",
+ edits: [
+ { old_string: "const a = 1;\n", new_string: "// explains a\nconst a = 2;\n" },
+ { oldString: "const b = 1;\n", newString: "// explains b\nconst b = 2;\n" },
+ ],
+ },
+ }),
+ );
+
+ expect(requests).toEqual([
+ {
+ sourceToolName: "multi_edit",
+ toolName: "MultiEdit",
+ filePath: "src/example.ts",
+ toolInput: {
+ file_path: "src/example.ts",
+ edits: [
+ { old_string: "const a = 1;\n", new_string: "// explains a\nconst a = 2;\n" },
+ { old_string: "const b = 1;\n", new_string: "// explains b\nconst b = 2;\n" },
+ ],
+ },
+ },
+ ]);
+ });
+});
+
+describe("runCommentCheckerPostToolUse", () => {
+ it("#given checker warning #when hook runs #then returns blocking feedback JSON", async () => {
+ const output = await runCommentCheckerPostToolUse(postToolUseInput(), {
+ run: async () => ({
+ status: "warning",
+ message: "comment warning: explain less",
+ }),
+ });
+
+ expect(JSON.parse(output)).toEqual({
+ decision: "block",
+ reason: "comment-checker found issues in src/example.ts:\ncomment warning: explain less",
+ });
+ });
+
+ it("#given missing checker binary #when hook runs #then emits no hook output", async () => {
+ const output = await runCommentCheckerPostToolUse(postToolUseInput(), {
+ run: async () => ({
+ status: "missing",
+ message: "not installed",
+ }),
+ });
+
+ expect(output).toBe("");
+ });
+
+ it("#given transcript path #when hook runs #then forwards it to checker input", async () => {
+ let transcriptPath = "";
+
+ await runCommentCheckerPostToolUse(
+ postToolUseInput({
+ transcript_path: "/tmp/codex-comment-checker-transcript.jsonl",
+ tool_name: "write",
+ tool_input: {
+ file_path: "src/example.ts",
+ content: "// explains value\nconst value = 1;\n",
+ },
+ }),
+ {
+ run: async (input) => {
+ transcriptPath = input.transcript_path;
+ return {
+ status: "pass",
+ message: "",
+ };
+ },
+ },
+ );
+
+ expect(transcriptPath).toBe("/tmp/codex-comment-checker-transcript.jsonl");
+ });
+
+ it("#given null transcript path #when hook runs #then forwards empty string fallback", async () => {
+ let transcriptPath = "unset";
+
+ await runCommentCheckerPostToolUse(
+ postToolUseInput({
+ transcript_path: null,
+ tool_name: "write",
+ tool_input: {
+ file_path: "src/example.ts",
+ content: "// explains value\nconst value = 1;\n",
+ },
+ }),
+ {
+ run: async (input) => {
+ transcriptPath = input.transcript_path;
+ return {
+ status: "pass",
+ message: "",
+ };
+ },
+ },
+ );
+
+ expect(transcriptPath).toBe("");
+ });
+});
+
+describe("runCodexHookCli", () => {
+ it("#given malformed post-tool-use stdin #when hook CLI runs #then it no-ops without stderr", async () => {
+ // given
+ const input = "break;\n";
+
+ // when
+ const result = await runHookCli(input);
+
+ // then
+ expect(result).toEqual({
+ exitCode: 0,
+ stdout: "",
+ stderr: "",
+ });
+ });
+
+ it("#given non-object post-tool-use JSON #when hook CLI runs #then it no-ops without stderr", async () => {
+ // given
+ const input = '"break;"\n';
+
+ // when
+ const result = await runHookCli(input);
+
+ // then
+ expect(result).toEqual({
+ exitCode: 0,
+ stdout: "",
+ stderr: "",
+ });
+ });
+
+ it("#given non-string transcript path #when hook CLI runs #then it no-ops without stderr", async () => {
+ // given
+ const input = `${JSON.stringify({ ...postToolUseInput(), transcript_path: 42 })}\n`;
+
+ // when
+ const result = await runHookCli(input);
+
+ // then
+ expect(result).toEqual({
+ exitCode: 0,
+ stdout: "",
+ stderr: "",
+ });
+ });
+});
diff --git a/plugins/omo/components/comment-checker/test/fixtures/post-tool-use.json b/plugins/omo/components/comment-checker/test/fixtures/post-tool-use.json
new file mode 100644
index 00000000..b1d4c090
--- /dev/null
+++ b/plugins/omo/components/comment-checker/test/fixtures/post-tool-use.json
@@ -0,0 +1,15 @@
+{
+ "session_id": "00000000-0000-0000-0000-000000000000",
+ "turn_id": "00000000-0000-0000-0000-000000000001",
+ "transcript_path": "/tmp/codex-comment-checker-transcript.jsonl",
+ "cwd": ".",
+ "hook_event_name": "PostToolUse",
+ "model": "gpt-5.5",
+ "permission_mode": "default",
+ "tool_name": "apply_patch",
+ "tool_input": {
+ "command": "*** Begin Patch\n*** Add File: src/example.ts\n+export const meaning = 42;\n*** End Patch\n"
+ },
+ "tool_response": "Success. Updated files.",
+ "tool_use_id": "toolu_000000000000000000000000"
+}
diff --git a/plugins/omo/components/comment-checker/test/package-smoke.test.ts b/plugins/omo/components/comment-checker/test/package-smoke.test.ts
new file mode 100644
index 00000000..650cc580
--- /dev/null
+++ b/plugins/omo/components/comment-checker/test/package-smoke.test.ts
@@ -0,0 +1,109 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+type PackageJson = {
+ readonly type: string;
+ readonly packageManager: string;
+ readonly bin: Record<string, string>;
+ readonly dependencies?: Record<string, unknown>;
+ readonly optionalDependencies: Record<string, string>;
+};
+
+type PluginJson = {
+ readonly hooks: string;
+};
+
+type HookCommand = {
+ readonly command: string;
+};
+
+type HookEntry = {
+ readonly hooks: readonly HookCommand[];
+};
+
+type HooksJson = {
+ readonly hooks: Record<string, readonly HookEntry[]>;
+};
+
+function readPackageJson(path: string): PackageJson {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (!isPackageJson(parsed)) throw new TypeError(`Invalid package metadata: ${path}`);
+ return parsed;
+}
+
+function readPluginJson(path: string): PluginJson {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (!isPluginJson(parsed)) throw new TypeError(`Invalid plugin metadata: ${path}`);
+ return parsed;
+}
+
+function readHooksJson(path: string): HooksJson {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (!isHooksJson(parsed)) throw new TypeError(`Invalid hooks metadata: ${path}`);
+ return parsed;
+}
+
+describe("plugin package metadata", () => {
+ it("#given packaged plugin files #when validating entrypoints #then hook command uses portable plugin root interpolation", () => {
+ // given
+ const packageJson = readPackageJson("package.json");
+ const pluginJson = readPluginJson(".codex-plugin/plugin.json");
+ const hooksJson = readHooksJson("hooks/hooks.json");
+ const cliSource = readFileSync("src/cli.ts", "utf8");
+
+ // when
+ const command = hooksJson.hooks["PostToolUse"]?.[0]?.hooks[0]?.command;
+ const pluginRoot = ["$", "{PLUGIN_ROOT}"].join("");
+
+ // then
+ expect(packageJson.type).toBe("module");
+ expect(packageJson.packageManager).toBe("[email protected]");
+ expect(packageJson.dependencies ?? {}).not.toHaveProperty("@code-yeongyu/comment-checker");
+ expect(packageJson.optionalDependencies).toHaveProperty("@code-yeongyu/comment-checker");
+ expect(packageJson.bin["codex-comment-checker"]).toBe("./dist/cli.js");
+ expect(pluginJson.hooks).toBe("./hooks/hooks.json");
+ expect(cliSource.startsWith("#!/usr/bin/env node")).toBe(true);
+ expect(command).toBe(`node "${pluginRoot}/dist/cli.js" hook post-tool-use`);
+ });
+});
+
+function isPackageJson(value: unknown): value is PackageJson {
+ if (!isRecord(value)) return false;
+ const dependencies = value["dependencies"];
+ return (
+ value["type"] === "module" &&
+ value["packageManager"] === "[email protected]" &&
+ isStringRecord(value["bin"]) &&
+ isStringRecord(value["optionalDependencies"]) &&
+ (dependencies === undefined || isRecord(dependencies))
+ );
+}
+
+function isPluginJson(value: unknown): value is PluginJson {
+ return isRecord(value) && typeof value["hooks"] === "string";
+}
+
+function isHooksJson(value: unknown): value is HooksJson {
+ if (!isRecord(value) || !isRecord(value["hooks"])) return false;
+ return Object.values(value["hooks"]).every(isHookEntries);
+}
+
+function isHookEntries(value: unknown): value is readonly HookEntry[] {
+ return Array.isArray(value) && value.every(isHookEntry);
+}
+
+function isHookEntry(value: unknown): value is HookEntry {
+ return isRecord(value) && Array.isArray(value["hooks"]) && value["hooks"].every(isHookCommand);
+}
+
+function isHookCommand(value: unknown): value is HookCommand {
+ return isRecord(value) && typeof value["command"] === "string";
+}
+
+function isStringRecord(value: unknown): value is Record<string, string> {
+ return isRecord(value) && Object.values(value).every((item) => typeof item === "string");
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/plugins/omo/components/comment-checker/test/runner.test.ts b/plugins/omo/components/comment-checker/test/runner.test.ts
new file mode 100644
index 00000000..39a375b1
--- /dev/null
+++ b/plugins/omo/components/comment-checker/test/runner.test.ts
@@ -0,0 +1,66 @@
+import { existsSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+import {
+ MAX_PROCESS_OUTPUT_BYTES,
+ resolveCommentCheckerBinary,
+ runCommentChecker,
+ spawnProcess,
+} from "../src/runner.js";
+
+describe("spawnProcess", () => {
+ it("#given noisy checker process #when output exceeds cap #then stderr is bounded", async () => {
+ // given
+ const maxOutputBytes = 16;
+
+ // when
+ const result = await spawnProcess(
+ process.execPath,
+ ["-e", "process.stderr.write('x'.repeat(40)); process.exit(2);"],
+ "",
+ maxOutputBytes,
+ );
+
+ // then
+ expect(MAX_PROCESS_OUTPUT_BYTES).toBeGreaterThan(maxOutputBytes);
+ expect(result.exitCode).toBe(2);
+ expect(result.stderr).toBe(`${"x".repeat(maxOutputBytes)}\n[stderr truncated after 16 bytes]`);
+ });
+});
+
+describe("resolveCommentCheckerBinary", () => {
+ it("#given installed checker package #when resolving binary #then returns existing checker binary", () => {
+ // given / when
+ const binaryPath = resolveCommentCheckerBinary();
+
+ // then
+ expect(binaryPath).toBeDefined();
+ expect(binaryPath ?? "").toContain("comment-checker");
+ expect(existsSync(binaryPath ?? "")).toBe(true);
+ });
+});
+
+describe("runCommentChecker", () => {
+ it("#given missing checker binary #when runner starts #then returns missing result", async () => {
+ // given / when
+ const result = await runCommentChecker(
+ {
+ session_id: "session-1",
+ tool_name: "Write",
+ transcript_path: "",
+ cwd: "/repo",
+ hook_event_name: "PostToolUse",
+ tool_input: {
+ file_path: "src/example.ts",
+ content: "const value = 1;\n",
+ },
+ },
+ {
+ resolveBinary: () => undefined,
+ },
+ );
+
+ // then
+ expect(result.status).toBe("missing");
+ });
+});
diff --git a/plugins/omo/components/comment-checker/tsconfig.build.json b/plugins/omo/components/comment-checker/tsconfig.build.json
new file mode 100644
index 00000000..5b5bbcaf
--- /dev/null
+++ b/plugins/omo/components/comment-checker/tsconfig.build.json
@@ -0,0 +1,12 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "allowImportingTsExtensions": false,
+ "declaration": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "noEmit": false
+ },
+ "include": ["src/**/*"],
+ "exclude": ["test/**/*"]
+}
diff --git a/plugins/omo/components/comment-checker/tsconfig.json b/plugins/omo/components/comment-checker/tsconfig.json
new file mode 100644
index 00000000..342229c0
--- /dev/null
+++ b/plugins/omo/components/comment-checker/tsconfig.json
@@ -0,0 +1,27 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "lib": ["ES2022"],
+ "strict": true,
+ "exactOptionalPropertyTypes": true,
+ "noUncheckedIndexedAccess": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "verbatimModuleSyntax": true,
+ "noImplicitOverride": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "esModuleInterop": true,
+ "allowImportingTsExtensions": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "useDefineForClassFields": false,
+ "types": ["node"],
+ "noEmit": true
+ },
+ "include": ["src/**/*", "test/**/*"]
+}
diff --git a/plugins/omo/components/comment-checker/vitest.config.ts b/plugins/omo/components/comment-checker/vitest.config.ts
new file mode 100644
index 00000000..57bd8f12
--- /dev/null
+++ b/plugins/omo/components/comment-checker/vitest.config.ts
@@ -0,0 +1,9 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["test/**/*.test.ts"],
+ environment: "node",
+ pool: "threads",
+ },
+});
diff --git a/plugins/omo/components/lsp/.gitattributes b/plugins/omo/components/lsp/.gitattributes
new file mode 100644
index 00000000..9363fdb7
--- /dev/null
+++ b/plugins/omo/components/lsp/.gitattributes
@@ -0,0 +1,13 @@
+# Normalize line endings: store LF in git, check out LF on every platform.
+# Required so biome's --check passes on Windows (default core.autocrlf=true).
+* text=auto eol=lf
+
+# Explicit binary types
+*.png binary
+*.jpg binary
+*.jpeg binary
+*.gif binary
+*.ico binary
+*.zip binary
+*.tgz binary
+*.gz binary
diff --git a/plugins/omo/components/lsp/.github/CODEOWNERS b/plugins/omo/components/lsp/.github/CODEOWNERS
new file mode 100644
index 00000000..e2330ddf
--- /dev/null
+++ b/plugins/omo/components/lsp/.github/CODEOWNERS
@@ -0,0 +1 @@
+* @code-yeongyu
diff --git a/plugins/omo/components/lsp/.github/ISSUE_TEMPLATE/bug.yml b/plugins/omo/components/lsp/.github/ISSUE_TEMPLATE/bug.yml
new file mode 100644
index 00000000..c8529498
--- /dev/null
+++ b/plugins/omo/components/lsp/.github/ISSUE_TEMPLATE/bug.yml
@@ -0,0 +1,26 @@
+name: Bug report
+description: Report a reproducible codex-lsp bug.
+title: "[bug]: "
+labels: ["bug"]
+body:
+ - type: textarea
+ id: summary
+ attributes:
+ label: Summary
+ description: What happened?
+ validations:
+ required: true
+ - type: textarea
+ id: reproduction
+ attributes:
+ label: Reproduction
+ description: Exact steps, config, command output, and affected language server.
+ validations:
+ required: true
+ - type: input
+ id: version
+ attributes:
+ label: Version
+ placeholder: 0.1.0
+ validations:
+ required: true
diff --git a/plugins/omo/components/lsp/.github/ISSUE_TEMPLATE/feature.yml b/plugins/omo/components/lsp/.github/ISSUE_TEMPLATE/feature.yml
new file mode 100644
index 00000000..b9d3af72
--- /dev/null
+++ b/plugins/omo/components/lsp/.github/ISSUE_TEMPLATE/feature.yml
@@ -0,0 +1,19 @@
+name: Feature request
+description: Propose a focused codex-lsp improvement.
+title: "[feature]: "
+labels: ["enhancement"]
+body:
+ - type: textarea
+ id: problem
+ attributes:
+ label: Problem
+ description: What workflow should improve?
+ validations:
+ required: true
+ - type: textarea
+ id: proposal
+ attributes:
+ label: Proposal
+ description: What should codex-lsp do?
+ validations:
+ required: true
diff --git a/plugins/omo/components/lsp/.github/branch-ruleset.json b/plugins/omo/components/lsp/.github/branch-ruleset.json
new file mode 100644
index 00000000..1f482bb6
--- /dev/null
+++ b/plugins/omo/components/lsp/.github/branch-ruleset.json
@@ -0,0 +1,45 @@
+{
+ "name": "main protection",
+ "target": "branch",
+ "enforcement": "active",
+ "conditions": {
+ "ref_name": {
+ "include": ["~DEFAULT_BRANCH"],
+ "exclude": []
+ }
+ },
+ "rules": [
+ { "type": "deletion" },
+ { "type": "non_fast_forward" },
+ { "type": "required_linear_history" },
+ {
+ "type": "pull_request",
+ "parameters": {
+ "required_approving_review_count": 1,
+ "dismiss_stale_reviews_on_push": true,
+ "require_code_owner_review": true,
+ "require_last_push_approval": false,
+ "required_review_thread_resolution": true
+ }
+ },
+ {
+ "type": "required_status_checks",
+ "parameters": {
+ "strict_required_status_checks_policy": true,
+ "required_status_checks": [
+ { "context": "test (ubuntu-latest · node 20)" },
+ { "context": "test (ubuntu-latest · node 22)" },
+ { "context": "test (macos-latest · node 20)" },
+ { "context": "test (macos-latest · node 22)" }
+ ]
+ }
+ }
+ ],
+ "bypass_actors": [
+ {
+ "actor_id": 5,
+ "actor_type": "RepositoryRole",
+ "bypass_mode": "always"
+ }
+ ]
+}
diff --git a/plugins/omo/components/lsp/.github/dependabot.yml b/plugins/omo/components/lsp/.github/dependabot.yml
new file mode 100644
index 00000000..be719fac
--- /dev/null
+++ b/plugins/omo/components/lsp/.github/dependabot.yml
@@ -0,0 +1,11 @@
+version: 2
+updates:
+ - package-ecosystem: npm
+ directory: /
+ schedule:
+ interval: weekly
+ open-pull-requests-limit: 5
+ - package-ecosystem: github-actions
+ directory: /
+ schedule:
+ interval: weekly
diff --git a/plugins/omo/components/lsp/.github/pull_request_template.md b/plugins/omo/components/lsp/.github/pull_request_template.md
new file mode 100644
index 00000000..39f36ad4
--- /dev/null
+++ b/plugins/omo/components/lsp/.github/pull_request_template.md
@@ -0,0 +1,11 @@
+## Summary
+
+-
+
+## Validation
+
+-
+
+## Notes
+
+-
diff --git a/plugins/omo/components/lsp/.github/workflows/ci.yml b/plugins/omo/components/lsp/.github/workflows/ci.yml
new file mode 100644
index 00000000..f8d6415c
--- /dev/null
+++ b/plugins/omo/components/lsp/.github/workflows/ci.yml
@@ -0,0 +1,56 @@
+name: ci
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ name: test (${{ matrix.os }} · node ${{ matrix.node }})
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 15
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ node: ["20", "22"]
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+ with:
+ submodules: recursive
+
+ - name: Setup Node ${{ matrix.node }}
+ uses: actions/setup-node@v6
+ with:
+ node-version: ${{ matrix.node }}
+ cache: npm
+
+ - name: Bootstrap lsp-tools-mcp submodule
+ shell: bash
+ run: |
+ cd packages/lsp-tools-mcp
+ npm ci
+ npm run build
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Check
+ run: npm run check
+
+ - name: Unit tests
+ run: npm test
+
+ - name: Package smoke
+ run: npm pack --dry-run
diff --git a/plugins/omo/components/lsp/.github/workflows/publish.yml b/plugins/omo/components/lsp/.github/workflows/publish.yml
new file mode 100644
index 00000000..125a4558
--- /dev/null
+++ b/plugins/omo/components/lsp/.github/workflows/publish.yml
@@ -0,0 +1,60 @@
+name: publish
+
+on:
+ release:
+ types: [published]
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: false
+
+permissions:
+ contents: read
+ id-token: write
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+ with:
+ submodules: recursive
+
+ - name: Setup Node 22
+ uses: actions/setup-node@v6
+ with:
+ node-version: "22"
+ registry-url: https://registry.npmjs.org
+ cache: npm
+
+ - name: Bootstrap lsp-tools-mcp submodule
+ shell: bash
+ run: |
+ cd packages/lsp-tools-mcp
+ npm ci
+ npm run build
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Check
+ run: npm run check
+
+ - name: Unit tests
+ run: npm test
+
+ - name: Package smoke
+ run: npm pack --dry-run
+
+ - name: Publish to npm
+ run: |
+ if [ -z "$NODE_AUTH_TOKEN" ]; then
+ echo "NODE_AUTH_TOKEN is not configured; skipping npm publish."
+ exit 0
+ fi
+ npm publish --access public --provenance
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NODE_AUTH_TOKEN }}
diff --git a/plugins/omo/components/lsp/.gitignore b/plugins/omo/components/lsp/.gitignore
new file mode 100644
index 00000000..1bf09f16
--- /dev/null
+++ b/plugins/omo/components/lsp/.gitignore
@@ -0,0 +1,6 @@
+node_modules/
+*.log
+.env
+.DS_Store
+coverage/
+.vitest/
diff --git a/plugins/omo/components/lsp/.gitmodules b/plugins/omo/components/lsp/.gitmodules
new file mode 100644
index 00000000..f172b519
--- /dev/null
+++ b/plugins/omo/components/lsp/.gitmodules
@@ -0,0 +1,4 @@
+[submodule "packages/lsp-tools-mcp"]
+ path = packages/lsp-tools-mcp
+ url = https://github.com/code-yeongyu/lsp-tools-mcp.git
+ branch = main
diff --git a/plugins/omo/components/lsp/.mcp.json b/plugins/omo/components/lsp/.mcp.json
new file mode 100644
index 00000000..13ff674d
--- /dev/null
+++ b/plugins/omo/components/lsp/.mcp.json
@@ -0,0 +1,9 @@
+{
+ "mcpServers": {
+ "lsp": {
+ "command": "node",
+ "args": ["./packages/lsp-tools-mcp/dist/cli.js", "mcp"],
+ "cwd": "."
+ }
+ }
+}
diff --git a/plugins/omo/components/lsp/AGENTS.md b/plugins/omo/components/lsp/AGENTS.md
new file mode 100644
index 00000000..69e85a30
--- /dev/null
+++ b/plugins/omo/components/lsp/AGENTS.md
@@ -0,0 +1,25 @@
+# Repository Conventions
+
+Conventions for humans and agents working on this repository.
+
+## Style
+
+- TypeScript strict mode. No `any`, `@ts-ignore`, `@ts-expect-error`, or enums.
+- ESM modules with `.js` suffix in import paths.
+- Tabs for indentation. Double quotes for strings.
+- Runtime is Node only.
+- Tests use vitest and should exercise Codex hook/MCP behavior before implementation changes.
+
+## Commands
+
+- `npm install` installs dependencies.
+- `npm test` runs the test suite once.
+- `npm run typecheck` runs strict TypeScript checking.
+- `npm run check` runs typecheck, Biome, and build.
+
+## LSP Constraints
+
+- LSP server processes are owned by `LspManager`.
+- Tool execution acquires clients through `withLspClient(...)` unless it only reports static status.
+- `lsp.rename` mutates files by applying workspace edits; keep it sequential at the MCP caller level.
+- Do not add pi-coding-agent or omo source dependencies. This package is standalone.
diff --git a/plugins/omo/components/lsp/CHANGELOG.md b/plugins/omo/components/lsp/CHANGELOG.md
new file mode 100644
index 00000000..5853ed1f
--- /dev/null
+++ b/plugins/omo/components/lsp/CHANGELOG.md
@@ -0,0 +1,23 @@
+# Changelog
+
+## Unreleased
+
+## 0.2.0
+
+- Extracted the LSP runtime and MCP server into [`@code-yeongyu/lsp-tools-mcp`](https://github.com/code-yeongyu/lsp-tools-mcp).
+- codex-lsp now consumes that runtime as a git submodule at `packages/lsp-tools-mcp`.
+- Kept the Codex-specific PostToolUse hook in this package and routed MCP serving through the upstream CLI.
+
+- Extract LSP runtime to `lsp-tools-mcp` upstream and consume it via git submodule at `packages/lsp-tools-mcp`.
+- Renamed the MCP server namespace to `lsp` and exposed shorter tool names such as `lsp.diagnostics`.
+- Use portable Codex hook interpolation and add package smoke coverage for hook/MCP entrypoints.
+- Spawn language servers without shell mode; Windows `.cmd` and `.bat` shims are routed through `cmd.exe` with explicit arguments.
+- Cap directory diagnostics file traversal and run CI on Windows in addition to Ubuntu and macOS.
+- Replace the external JSON-RPC runtime dependency with an internal LSP framing layer so clean Codex plugin installs run without `node_modules`.
+
+## 0.1.0
+
+- Ported the standalone LSP client, server resolution, diagnostics aggregation, and workspace edit runtime from `pi-lsp-client`.
+- Added Codex `PostToolUse` diagnostics for edit-style tools.
+- Added MCP tools for status, diagnostics, definitions, references, symbols, prepare rename, and rename.
+- Added Codex plugin metadata, skill docs, CI, and release automation.
diff --git a/plugins/omo/components/lsp/LICENSE b/plugins/omo/components/lsp/LICENSE
new file mode 100644
index 00000000..09aac3c3
--- /dev/null
+++ b/plugins/omo/components/lsp/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Yeongyu Kim
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/plugins/omo/components/lsp/NOTICE b/plugins/omo/components/lsp/NOTICE
new file mode 100644
index 00000000..01916eda
--- /dev/null
+++ b/plugins/omo/components/lsp/NOTICE
@@ -0,0 +1,3 @@
+codex-lsp ports the standalone LSP runtime from pi-lsp-client into a Codex plugin.
+
+The package includes adapted code originally developed for pi-lsp-client.
diff --git a/plugins/omo/components/lsp/README.md b/plugins/omo/components/lsp/README.md
new file mode 100644
index 00000000..a449ef99
--- /dev/null
+++ b/plugins/omo/components/lsp/README.md
@@ -0,0 +1,149 @@
+# codex-lsp
+
+[![ci](https://github.com/code-yeongyu/codex-lsp/actions/workflows/ci.yml/badge.svg)](https://github.com/code-yeongyu/codex-lsp/actions/workflows/ci.yml) [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
+
+Codex plugin that ports the standalone LSP runtime from [`pi-lsp-client`](https://github.com/code-yeongyu/pi-lsp-client). It gives Codex post-edit diagnostics plus explicit MCP tools for language-aware code work.
+
+## Architecture
+
+The LSP runtime moved to [`lsp-tools-mcp`](https://github.com/code-yeongyu/lsp-tools-mcp) and is consumed here as a git submodule at `packages/lsp-tools-mcp/`.
+
+- `codex-lsp` keeps Codex-specific integration (`hook post-tool-use`, plugin metadata, package wiring).
+- `lsp-tools-mcp` owns MCP runtime, LSP manager, and tool implementations.
+- `src/cli.ts` routes `mcp` to upstream runtime and keeps `hook post-tool-use` local.
+
+## Behavior
+
+| Case | Result |
+|------|--------|
+| `apply_patch` succeeds | parses `tool_input.command`, extracts added/updated/moved files, and checks each with LSP error diagnostics |
+| `write` / `edit` / `multiedit` succeeds | checks `path`, `filePath`, or `file_path` aliases |
+| diagnostics contain errors | returns Codex `PostToolUse` blocking feedback and injects the same diagnostics as additional context so Codex fixes the file |
+| no diagnostics | emits no hook output |
+| unsupported extension | emits no hook output |
+| missing configured language server | surfaces the install/config message through hook or MCP output |
+
+Deletes are ignored because they cannot introduce new diagnostics.
+
+## MCP Tools
+
+- `lsp.status`
+- `lsp.diagnostics`
+- `lsp.goto_definition`
+- `lsp.find_references`
+- `lsp.symbols`
+- `lsp.prepare_rename`
+- `lsp.rename`
+
+`lsp.rename` applies the returned workspace edit to files. Use `lsp.prepare_rename` first when possible.
+
+## Configuration
+
+Project config:
+
+```text
+.codex/lsp-client.json
+```
+
+User config:
+
+```text
+~/.codex/lsp-client.json
+```
+
+Example:
+
+```json
+{
+ "lsp": {
+ "typescript": {
+ "command": ["typescript-language-server", "--stdio"],
+ "extensions": [".ts", ".tsx", ".js", ".jsx"]
+ }
+ }
+}
+```
+
+Built-in server definitions are used when no custom config overrides them. `lsp.status` shows which configured servers are installed or missing.
+
+## Codex Plugin
+
+The plugin ships:
+
+- `.codex-plugin/plugin.json` for Codex plugin discovery.
+- `.mcp.json` for the `lsp` MCP server.
+- `hooks/hooks.json` for the `PostToolUse` diagnostics hook.
+- `skills/lsp/SKILL.md` with MCP usage guidance.
+
+The runtime depends on `@code-yeongyu/lsp-tools-mcp` via `file:./packages/lsp-tools-mcp`, so marketplace builds must include submodule contents.
+
+The hook command is:
+
+```bash
+node "${PLUGIN_ROOT}/dist/cli.js" hook post-tool-use
+```
+
+The MCP command is:
+
+```bash
+node ./packages/lsp-tools-mcp/dist/cli.js mcp
+```
+
+## Local Development
+
+```bash
+git submodule update --init --recursive
+npm run bootstrap # installs + builds the lsp-tools-mcp submodule
+npm install
+npm test
+npm run typecheck
+npm run check
+npm pack --dry-run
+```
+
+The `bootstrap` script installs and builds the `lsp-tools-mcp` git submodule so
+`@code-yeongyu/lsp-tools-mcp/dist/*.js` is available for the codex-lsp build.
+
+Smoke-test the hook:
+
+```bash
+node dist/cli.js hook post-tool-use < test/fixtures/post-tool-use.json
+```
+
+Smoke-test the MCP server:
+
+```bash
+printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | node dist/cli.js mcp
+```
+
+## Local Codex Installation
+
+```bash
+bunx lazycodex install
+```
+
+The installer builds and copies the plugin into `~/.codex/plugins/cache/sisyphuslabs/omo/0.1.0`, registers the `sisyphuslabs` marketplace from the `lazycodex` Git repository, and enables:
+
+```toml
+[plugins."omo@sisyphuslabs"]
+enabled = true
+```
+
+## Branch Rules and Releases
+
+- `main` is protected by `.github/branch-ruleset.json`.
+- CI runs Node 20 and 22 on Ubuntu, macOS, and Windows.
+- Releases are GitHub Releases tagged as `v<semver>`.
+- Publishing runs from the `publish` workflow after a GitHub Release is published.
+
+## Privacy
+
+This plugin runs locally. It starts configured language-server commands on your machine and does not call a network service by itself.
+
+## License
+
+[MIT](LICENSE).
+
+## Related
+
+- [pi-lsp-client](https://github.com/code-yeongyu/pi-lsp-client) - source extension this Codex plugin ports.
diff --git a/plugins/omo/components/lsp/biome.json b/plugins/omo/components/lsp/biome.json
new file mode 100644
index 00000000..5aa1a0dc
--- /dev/null
+++ b/plugins/omo/components/lsp/biome.json
@@ -0,0 +1,48 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.4.15/schema.json",
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "recommended": true,
+ "style": {
+ "noDefaultExport": "error",
+ "noEnum": "error",
+ "noNonNullAssertion": "error",
+ "useImportType": "error",
+ "useConst": "error",
+ "useNodejsImportProtocol": "off"
+ },
+ "complexity": {
+ "useLiteralKeys": "off"
+ },
+ "suspicious": {
+ "noExplicitAny": "error",
+ "noTsIgnore": "error",
+ "noControlCharactersInRegex": "off",
+ "noEmptyInterface": "off"
+ }
+ }
+ },
+ "formatter": {
+ "enabled": true,
+ "formatWithErrors": false,
+ "indentStyle": "tab",
+ "indentWidth": 3,
+ "lineWidth": 120
+ },
+ "files": {
+ "includes": ["src/**/*.ts", "test/**/*.ts", "vitest.config.ts", "!**/node_modules/**/*", "!**/dist/**/*"]
+ },
+ "overrides": [
+ {
+ "includes": ["vitest.config.ts"],
+ "linter": {
+ "rules": {
+ "style": {
+ "noDefaultExport": "off"
+ }
+ }
+ }
+ }
+ ]
+}
diff --git a/plugins/omo/components/lsp/hooks/hooks.json b/plugins/omo/components/lsp/hooks/hooks.json
new file mode 100644
index 00000000..afdfe34a
--- /dev/null
+++ b/plugins/omo/components/lsp/hooks/hooks.json
@@ -0,0 +1,17 @@
+{
+ "hooks": {
+ "PostToolUse": [
+ {
+ "matcher": "^(apply_patch|Write|Edit|MultiEdit|multi_edit|write|edit|multiedit)$",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use",
+ "timeout": 60,
+ "statusMessage": "checking LSP diagnostics"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/omo/components/lsp/package.json b/plugins/omo/components/lsp/package.json
new file mode 100644
index 00000000..3a45e161
--- /dev/null
+++ b/plugins/omo/components/lsp/package.json
@@ -0,0 +1,64 @@
+{
+ "name": "@code-yeongyu/codex-lsp",
+ "version": "0.2.0",
+ "description": "Codex plugin that exposes Language Server Protocol tools and post-edit diagnostics.",
+ "type": "module",
+ "packageManager": "[email protected]",
+ "license": "MIT",
+ "homepage": "https://github.com/code-yeongyu/codex-lsp",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/code-yeongyu/codex-lsp.git"
+ },
+ "bugs": {
+ "url": "https://github.com/code-yeongyu/codex-lsp/issues"
+ },
+ "keywords": [
+ "codex",
+ "codex-plugin",
+ "lsp",
+ "language-server-protocol",
+ "mcp",
+ "diagnostics"
+ ],
+ "bin": {
+ "codex-lsp": "./dist/cli.js"
+ },
+ "files": [
+ "dist",
+ "hooks",
+ "skills",
+ ".codex-plugin",
+ ".mcp.json",
+ "LICENSE",
+ "NOTICE",
+ "README.md",
+ "CHANGELOG.md"
+ ],
+ "scripts": {
+ "bootstrap": "node scripts/bootstrap-submodule.mjs",
+ "prebuild": "node scripts/bootstrap-submodule.mjs",
+ "build": "tsc -p tsconfig.build.json",
+ "pretest": "node scripts/bootstrap-submodule.mjs",
+ "test": "vitest --run",
+ "test:watch": "vitest",
+ "pretypecheck": "node scripts/bootstrap-submodule.mjs",
+ "typecheck": "tsc --noEmit",
+ "lint": "biome check src test",
+ "lint:fix": "biome check --write src test",
+ "precheck": "node scripts/bootstrap-submodule.mjs",
+ "check": "tsc --noEmit && biome check src test && tsc -p tsconfig.build.json"
+ },
+ "dependencies": {
+ "@code-yeongyu/lsp-tools-mcp": "file:./packages/lsp-tools-mcp"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.15",
+ "@types/node": "^25.7.0",
+ "typescript": "^6.0.3",
+ "vitest": "^4.1.5"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.gitattributes b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.gitattributes
new file mode 100644
index 00000000..9363fdb7
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.gitattributes
@@ -0,0 +1,13 @@
+# Normalize line endings: store LF in git, check out LF on every platform.
+# Required so biome's --check passes on Windows (default core.autocrlf=true).
+* text=auto eol=lf
+
+# Explicit binary types
+*.png binary
+*.jpg binary
+*.jpeg binary
+*.gif binary
+*.ico binary
+*.zip binary
+*.tgz binary
+*.gz binary
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/CODEOWNERS b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/CODEOWNERS
new file mode 100644
index 00000000..e2330ddf
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/CODEOWNERS
@@ -0,0 +1 @@
+* @code-yeongyu
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/ISSUE_TEMPLATE/bug.yml b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/ISSUE_TEMPLATE/bug.yml
new file mode 100644
index 00000000..206a5f9d
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/ISSUE_TEMPLATE/bug.yml
@@ -0,0 +1,26 @@
+name: Bug report
+description: Report a reproducible lsp-tools-mcp bug.
+title: "[bug]: "
+labels: ["bug"]
+body:
+ - type: textarea
+ id: summary
+ attributes:
+ label: Summary
+ description: What happened?
+ validations:
+ required: true
+ - type: textarea
+ id: reproduction
+ attributes:
+ label: Reproduction
+ description: Exact steps, config, command output, and affected MCP tool or language server.
+ validations:
+ required: true
+ - type: input
+ id: version
+ attributes:
+ label: Version
+ placeholder: 0.1.0
+ validations:
+ required: true
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/ISSUE_TEMPLATE/feature.yml b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/ISSUE_TEMPLATE/feature.yml
new file mode 100644
index 00000000..4f0042f6
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/ISSUE_TEMPLATE/feature.yml
@@ -0,0 +1,19 @@
+name: Feature request
+description: Propose a focused lsp-tools-mcp improvement.
+title: "[feature]: "
+labels: ["enhancement"]
+body:
+ - type: textarea
+ id: problem
+ attributes:
+ label: Problem
+ description: What workflow should improve?
+ validations:
+ required: true
+ - type: textarea
+ id: proposal
+ attributes:
+ label: Proposal
+ description: What should lsp-tools-mcp do?
+ validations:
+ required: true
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/branch-ruleset.json b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/branch-ruleset.json
new file mode 100644
index 00000000..1f482bb6
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/branch-ruleset.json
@@ -0,0 +1,45 @@
+{
+ "name": "main protection",
+ "target": "branch",
+ "enforcement": "active",
+ "conditions": {
+ "ref_name": {
+ "include": ["~DEFAULT_BRANCH"],
+ "exclude": []
+ }
+ },
+ "rules": [
+ { "type": "deletion" },
+ { "type": "non_fast_forward" },
+ { "type": "required_linear_history" },
+ {
+ "type": "pull_request",
+ "parameters": {
+ "required_approving_review_count": 1,
+ "dismiss_stale_reviews_on_push": true,
+ "require_code_owner_review": true,
+ "require_last_push_approval": false,
+ "required_review_thread_resolution": true
+ }
+ },
+ {
+ "type": "required_status_checks",
+ "parameters": {
+ "strict_required_status_checks_policy": true,
+ "required_status_checks": [
+ { "context": "test (ubuntu-latest · node 20)" },
+ { "context": "test (ubuntu-latest · node 22)" },
+ { "context": "test (macos-latest · node 20)" },
+ { "context": "test (macos-latest · node 22)" }
+ ]
+ }
+ }
+ ],
+ "bypass_actors": [
+ {
+ "actor_id": 5,
+ "actor_type": "RepositoryRole",
+ "bypass_mode": "always"
+ }
+ ]
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/dependabot.yml b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/dependabot.yml
new file mode 100644
index 00000000..be719fac
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/dependabot.yml
@@ -0,0 +1,11 @@
+version: 2
+updates:
+ - package-ecosystem: npm
+ directory: /
+ schedule:
+ interval: weekly
+ open-pull-requests-limit: 5
+ - package-ecosystem: github-actions
+ directory: /
+ schedule:
+ interval: weekly
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/pull_request_template.md b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/pull_request_template.md
new file mode 100644
index 00000000..39f36ad4
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/pull_request_template.md
@@ -0,0 +1,11 @@
+## Summary
+
+-
+
+## Validation
+
+-
+
+## Notes
+
+-
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/workflows/ci.yml b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/workflows/ci.yml
new file mode 100644
index 00000000..6cc7a165
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/workflows/ci.yml
@@ -0,0 +1,47 @@
+name: ci
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ name: test (${{ matrix.os }} · node ${{ matrix.node }})
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 15
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ node: ["20", "22"]
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+
+ - name: Setup Node ${{ matrix.node }}
+ uses: actions/setup-node@v6
+ with:
+ node-version: ${{ matrix.node }}
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Check
+ run: npm run check
+
+ - name: Unit tests
+ run: npm test
+
+ - name: Package smoke
+ run: npm pack --dry-run
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/workflows/publish.yml b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/workflows/publish.yml
new file mode 100644
index 00000000..4214a99b
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.github/workflows/publish.yml
@@ -0,0 +1,51 @@
+name: publish
+
+on:
+ release:
+ types: [published]
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: false
+
+permissions:
+ contents: read
+ id-token: write
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+
+ - name: Setup Node 22
+ uses: actions/setup-node@v6
+ with:
+ node-version: "22"
+ registry-url: https://registry.npmjs.org
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Check
+ run: npm run check
+
+ - name: Unit tests
+ run: npm test
+
+ - name: Package smoke
+ run: npm pack --dry-run
+
+ - name: Publish to npm
+ run: |
+ if [ -z "$NODE_AUTH_TOKEN" ]; then
+ echo "NODE_AUTH_TOKEN is not configured; skipping npm publish."
+ exit 0
+ fi
+ npm publish --access public --provenance
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NODE_AUTH_TOKEN }}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/.gitignore b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.gitignore
new file mode 100644
index 00000000..1bf09f16
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/.gitignore
@@ -0,0 +1,6 @@
+node_modules/
+*.log
+.env
+.DS_Store
+coverage/
+.vitest/
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/CHANGELOG.md b/plugins/omo/components/lsp/packages/lsp-tools-mcp/CHANGELOG.md
new file mode 100644
index 00000000..4bff36af
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/CHANGELOG.md
@@ -0,0 +1,20 @@
+# Changelog
+
+All notable changes to this project are documented in this file.
+
+## [0.1.0] - 2026-05-18
+
+### Added
+
+- Initial standalone extraction from `codex-lsp`:
+ - LSP runtime (`src/lsp/*`)
+ - MCP server (`src/mcp.ts`)
+ - Tool definitions (`src/tools.ts`)
+ - Standalone CLI (`src/cli.ts`, `mcp` subcommand only)
+- Config path override support:
+ - `LSP_TOOLS_MCP_PROJECT_CONFIG`
+ - `LSP_TOOLS_MCP_USER_CONFIG`
+- Full test suite import (excluding Codex-specific hook tests)
+- CI workflow matrix (ubuntu/macos/windows x node 20/22)
+- Release-triggered npm publish workflow
+- Repository governance files (ruleset, CODEOWNERS, dependabot, issue templates, PR template)
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/LICENSE b/plugins/omo/components/lsp/packages/lsp-tools-mcp/LICENSE
new file mode 100644
index 00000000..09aac3c3
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Yeongyu Kim
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/NOTICE b/plugins/omo/components/lsp/packages/lsp-tools-mcp/NOTICE
new file mode 100644
index 00000000..a3adc175
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/NOTICE
@@ -0,0 +1,3 @@
+lsp-tools-mcp extracts the standalone LSP runtime from codex-lsp into a reusable package.
+
+The package includes adapted code originally developed for pi-lsp-client.
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/README.md b/plugins/omo/components/lsp/packages/lsp-tools-mcp/README.md
new file mode 100644
index 00000000..906b7c61
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/README.md
@@ -0,0 +1,102 @@
+# lsp-tools-mcp
+
+[![ci](https://github.com/code-yeongyu/lsp-tools-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/code-yeongyu/lsp-tools-mcp/actions/workflows/ci.yml) [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
+
+Standalone Language Server Protocol tools exposed as a stdio MCP server.
+
+## Used By
+
+This repository is the upstream source of truth for two downstream plugins. Both consume it as a git submodule:
+
+| Project | Path | Role |
+|---------|------|------|
+| **[codex-lsp](https://github.com/code-yeongyu/codex-lsp)** | `packages/lsp-tools-mcp/` | Codex plugin that ships these LSP MCP tools plus a Codex-specific PostToolUse diagnostics hook. |
+| **[oh-my-openagent](https://github.com/code-yeongyu/oh-my-openagent)** (a.k.a. `oh-my-opencode`) | `vendor/lsp-tools-mcp/` | OpenCode plugin that registers this server as a built-in Tier-1 stdio MCP. Exposes `lsp_diagnostics`, `lsp_goto_definition`, `lsp_find_references`, `lsp_symbols`, `lsp_prepare_rename`, `lsp_rename`, and `lsp_status` to all agents. |
+
+If you fix or extend the LSP runtime here, both downstreams pick up the change by bumping the submodule pointer. Do not fork the runtime into a downstream; land changes here instead.
+
+## Quick Start
+
+```bash
+npm install
+npm run check
+npm test
+npm run build
+printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | node dist/cli.js mcp
+```
+
+## MCP Tools
+
+This server exposes the following tools:
+
+- `lsp.status`
+- `lsp.diagnostics`
+- `lsp.goto_definition`
+- `lsp.find_references`
+- `lsp.symbols`
+- `lsp.prepare_rename`
+- `lsp.rename`
+
+Tool aliases are also available for compatibility:
+
+- `lsp_status`
+- `lsp_diagnostics`
+- `lsp_goto_definition`
+- `lsp_find_references`
+- `lsp_symbols`
+- `lsp_prepare_rename`
+- `lsp_rename`
+
+When an MCP host registers this server under the name `lsp` (the default in both downstreams), the tools are exposed to agents as `lsp_status`, `lsp_diagnostics`, and so on, matching the alias names above.
+
+## Configuration
+
+Default config paths (matches codex-lsp's historical layout):
+
+- Project: `.codex/lsp-client.json`
+- User: `~/.codex/lsp-client.json`
+
+Path overrides via environment variables:
+
+- `LSP_TOOLS_MCP_PROJECT_CONFIG`
+- `LSP_TOOLS_MCP_USER_CONFIG`
+
+Examples (oh-my-openagent points the project config at `.opencode/lsp.json` via the env var):
+
+```bash
+LSP_TOOLS_MCP_PROJECT_CONFIG=.opencode/lsp.json node dist/cli.js mcp
+LSP_TOOLS_MCP_USER_CONFIG=.opencode/lsp.json node dist/cli.js mcp
+```
+
+Example config file:
+
+```json
+{
+ "lsp": {
+ "typescript": {
+ "command": ["typescript-language-server", "--stdio"],
+ "extensions": [".ts", ".tsx", ".js", ".jsx"]
+ }
+ }
+}
+```
+
+## Architecture
+
+- `src/lsp/*` standalone LSP runtime (process management, JSON-RPC transport, configuration, diagnostics, workspace edits)
+- `src/tools.ts` MCP tool definitions and handlers
+- `src/mcp.ts` stdio MCP server entry and registration
+- `src/cli.ts` standalone CLI entry (`mcp` subcommand only)
+
+## Local Development
+
+```bash
+npm install
+npm run check
+npm test
+npm pack --dry-run
+```
+
+## License
+
+[MIT](LICENSE)
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/biome.json b/plugins/omo/components/lsp/packages/lsp-tools-mcp/biome.json
new file mode 100644
index 00000000..5aa1a0dc
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/biome.json
@@ -0,0 +1,48 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.4.15/schema.json",
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "recommended": true,
+ "style": {
+ "noDefaultExport": "error",
+ "noEnum": "error",
+ "noNonNullAssertion": "error",
+ "useImportType": "error",
+ "useConst": "error",
+ "useNodejsImportProtocol": "off"
+ },
+ "complexity": {
+ "useLiteralKeys": "off"
+ },
+ "suspicious": {
+ "noExplicitAny": "error",
+ "noTsIgnore": "error",
+ "noControlCharactersInRegex": "off",
+ "noEmptyInterface": "off"
+ }
+ }
+ },
+ "formatter": {
+ "enabled": true,
+ "formatWithErrors": false,
+ "indentStyle": "tab",
+ "indentWidth": 3,
+ "lineWidth": 120
+ },
+ "files": {
+ "includes": ["src/**/*.ts", "test/**/*.ts", "vitest.config.ts", "!**/node_modules/**/*", "!**/dist/**/*"]
+ },
+ "overrides": [
+ {
+ "includes": ["vitest.config.ts"],
+ "linter": {
+ "rules": {
+ "style": {
+ "noDefaultExport": "off"
+ }
+ }
+ }
+ }
+ ]
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/package.json b/plugins/omo/components/lsp/packages/lsp-tools-mcp/package.json
new file mode 100644
index 00000000..52a344d0
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/package.json
@@ -0,0 +1,52 @@
+{
+ "name": "@code-yeongyu/lsp-tools-mcp",
+ "version": "0.1.0",
+ "description": "Standalone Language Server Protocol tools exposed as a stdio MCP server.",
+ "type": "module",
+ "packageManager": "[email protected]",
+ "license": "MIT",
+ "homepage": "https://github.com/code-yeongyu/lsp-tools-mcp",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/code-yeongyu/lsp-tools-mcp.git"
+ },
+ "bugs": {
+ "url": "https://github.com/code-yeongyu/lsp-tools-mcp/issues"
+ },
+ "keywords": [
+ "mcp",
+ "lsp",
+ "language-server-protocol",
+ "model-context-protocol",
+ "typescript",
+ "nodejs"
+ ],
+ "bin": {
+ "lsp-tools-mcp": "./dist/cli.js"
+ },
+ "files": [
+ "dist",
+ "LICENSE",
+ "NOTICE",
+ "README.md",
+ "CHANGELOG.md"
+ ],
+ "scripts": {
+ "build": "tsc -p tsconfig.build.json",
+ "test": "vitest --run",
+ "test:watch": "vitest",
+ "typecheck": "tsc --noEmit",
+ "lint": "biome check .",
+ "lint:fix": "biome check --write .",
+ "check": "tsc --noEmit && biome check . && npm run build"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.15",
+ "@types/node": "^25.7.0",
+ "typescript": "^6.0.3",
+ "vitest": "^4.1.5"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/cli.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/cli.ts
new file mode 100644
index 00000000..c0dc203d
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/cli.ts
@@ -0,0 +1,34 @@
+#!/usr/bin/env node
+import { argv, stderr } from "node:process";
+
+import { disposeDefaultLspManager } from "./lsp/manager.js";
+import { runMcpStdioServer } from "./mcp.js";
+import { writeMcpLifecycleLog } from "./mcp-lifecycle-log.js";
+
+async function main(): Promise<void> {
+ const [command = "mcp"] = argv.slice(2);
+
+ try {
+ if (command === "mcp") {
+ await runMcpStdioServer(process.stdin, process.stdout, {
+ log: writeMcpLifecycleLog,
+ onIdleTimeout: async () => {
+ await disposeDefaultLspManager();
+ process.exit(0);
+ },
+ });
+ return;
+ }
+
+ stderr.write("Usage: lsp-tools-mcp [mcp]\n");
+ process.exitCode = 2;
+ } finally {
+ await disposeDefaultLspManager();
+ }
+}
+
+main().catch(async (error: unknown) => {
+ stderr.write(`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
+ await disposeDefaultLspManager();
+ process.exitCode = 1;
+});
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/cleanup-errors.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/cleanup-errors.ts
new file mode 100644
index 00000000..30e7018b
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/cleanup-errors.ts
@@ -0,0 +1,5 @@
+export function reportBestEffortCleanupError(operation: string, error: unknown): void {
+ if (process.env["CODEX_LSP_DEBUG_CLEANUP"] !== "1") return;
+ const message = error instanceof Error ? error.message : String(error);
+ console.error(`[codex-lsp] ignored ${operation} failure during cleanup: ${message}`);
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/client-wrapper.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/client-wrapper.ts
new file mode 100644
index 00000000..9e9d4bc8
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/client-wrapper.ts
@@ -0,0 +1,146 @@
+import { existsSync, statSync } from "node:fs";
+import { dirname, extname, join, resolve } from "node:path";
+
+import type { LspClient } from "./client.js";
+import {
+ isLspDeadConnectionError,
+ LspInvalidPathError,
+ LspRequestTimeoutError,
+ LspServerInitializingError,
+ LspServerLookupError,
+} from "./errors.js";
+import { getLspManager, type LspManager } from "./manager.js";
+import { findServerForExtension } from "./server-resolution.js";
+import type { ServerLookupResult } from "./types.js";
+
+const WORKSPACE_MARKERS = [".git", "package.json", "pyproject.toml", "Cargo.toml", "go.mod", "pom.xml", "build.gradle"];
+
+export function isDirectoryPath(filePath: string): boolean {
+ try {
+ return statSync(filePath).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
+export function findWorkspaceRoot(filePath: string): string {
+ const abs = resolve(filePath);
+ let dir = abs;
+
+ if (!isDirectoryPath(dir)) {
+ dir = dirname(dir);
+ }
+
+ let prevDir = "";
+ while (dir !== prevDir) {
+ for (const marker of WORKSPACE_MARKERS) {
+ if (existsSync(join(dir, marker))) {
+ return dir;
+ }
+ }
+ prevDir = dir;
+ dir = dirname(dir);
+ }
+
+ return dirname(abs);
+}
+
+export function formatServerLookupError(result: Exclude<ServerLookupResult, { status: "found" }>): string {
+ if (result.status === "not_installed") {
+ const { server, installHint } = result;
+ return [
+ `LSP server '${server.id}' is configured but NOT INSTALLED.`,
+ "",
+ `Command not found: ${server.command[0]}`,
+ "",
+ "To install:",
+ ` ${installHint}`,
+ "",
+ `Supported extensions: ${server.extensions.join(", ")}`,
+ "",
+ "After installation, the server will be available automatically.",
+ ].join("\n");
+ }
+
+ return [
+ `No LSP server configured for extension: ${result.extension}`,
+ "",
+ `Available servers: ${result.availableServers.slice(0, 10).join(", ")}${
+ result.availableServers.length > 10 ? "..." : ""
+ }`,
+ "",
+ "Configure a custom server in '.codex/lsp-client.json':",
+ " {",
+ ' "lsp": {',
+ ' "my-server": {',
+ ' "command": ["my-lsp", "--stdio"],',
+ ` "extensions": ["${result.extension}"]`,
+ " }",
+ " }",
+ " }",
+ ].join("\n");
+}
+
+export interface WithLspClientOptions {
+ signal?: AbortSignal;
+ manager?: LspManager;
+}
+
+const READ_ONLY_RETRY_TOOLS = new Set([
+ "diagnostics",
+ "definition",
+ "references",
+ "documentSymbols",
+ "workspaceSymbols",
+ "prepareRename",
+]);
+
+export async function withLspClient<T>(
+ filePath: string,
+ fn: (client: LspClient) => Promise<T>,
+ toolName: string,
+ options: WithLspClientOptions = {},
+): Promise<T> {
+ const absPath = resolve(filePath);
+
+ if (isDirectoryPath(absPath)) {
+ throw new LspInvalidPathError(
+ "Directory paths are not supported by this LSP tool. " +
+ "Use lsp.diagnostics with a directory path for directory diagnostics.",
+ );
+ }
+
+ const ext = extname(absPath);
+ const result = findServerForExtension(ext);
+ if (result.status !== "found") {
+ throw new LspServerLookupError(formatServerLookupError(result));
+ }
+
+ const server = result.server;
+ const root = findWorkspaceRoot(absPath);
+ const manager = options.manager ?? getLspManager();
+
+ const acquireAndCall = async (allowRetry: boolean): Promise<T> => {
+ const client = await manager.getClient(root, server, options.signal);
+
+ try {
+ return await fn(client);
+ } catch (err) {
+ if (allowRetry && READ_ONLY_RETRY_TOOLS.has(toolName) && isLspDeadConnectionError(err)) {
+ manager.invalidateClient(root, server.id, client);
+ return acquireAndCall(false);
+ }
+
+ if (err instanceof LspRequestTimeoutError) {
+ if (manager.isServerInitializing(root, server.id)) {
+ throw new LspServerInitializingError(err);
+ }
+ }
+ throw err;
+ } finally {
+ manager.releaseClient(root, server.id);
+ }
+ };
+
+ return acquireAndCall(true);
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/client.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/client.ts
new file mode 100644
index 00000000..45dcf86f
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/client.ts
@@ -0,0 +1,170 @@
+import { readFileSync } from "node:fs";
+import { extname, resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+
+import { LspClientConnection } from "./connection.js";
+import { getLanguageId } from "./language-mappings.js";
+import type {
+ Diagnostic,
+ DocumentSymbol,
+ Location,
+ LocationLink,
+ PrepareRenameDefaultBehavior,
+ PrepareRenameResult,
+ Range,
+ SymbolInfo,
+ WorkspaceEdit,
+} from "./types.js";
+
+const POST_OPEN_DELAY_MS = 1000;
+const POST_DIAGNOSTICS_WAIT_MS = 500;
+
+export class LspClient extends LspClientConnection {
+ private readonly openedFiles = new Set<string>();
+ private readonly documentVersions = new Map<string, number>();
+ private readonly lastSyncedText = new Map<string, string>();
+ private readonly diagnosticPullErrors: Error[] = [];
+
+ getDiagnosticPullErrors(): readonly Error[] {
+ return this.diagnosticPullErrors;
+ }
+
+ async openFile(filePath: string): Promise<void> {
+ const absPath = resolve(filePath);
+ const uri = pathToFileURL(absPath).href;
+ const text = readFileSync(absPath, "utf-8");
+
+ if (!this.openedFiles.has(absPath)) {
+ const ext = extname(absPath);
+ const languageId = getLanguageId(ext);
+ const version = 1;
+
+ await this.sendNotification("textDocument/didOpen", {
+ textDocument: {
+ uri,
+ languageId,
+ version,
+ text,
+ },
+ });
+
+ this.openedFiles.add(absPath);
+ this.documentVersions.set(uri, version);
+ this.lastSyncedText.set(uri, text);
+ await new Promise((r) => setTimeout(r, POST_OPEN_DELAY_MS));
+ return;
+ }
+
+ const prevText = this.lastSyncedText.get(uri);
+ if (prevText === text) {
+ return;
+ }
+
+ const nextVersion = (this.documentVersions.get(uri) ?? 1) + 1;
+ this.documentVersions.set(uri, nextVersion);
+ this.lastSyncedText.set(uri, text);
+
+ await this.sendNotification("textDocument/didChange", {
+ textDocument: { uri, version: nextVersion },
+ contentChanges: [{ text }],
+ });
+
+ await this.sendNotification("textDocument/didSave", {
+ textDocument: { uri },
+ text,
+ });
+ }
+
+ async definition(
+ filePath: string,
+ line: number,
+ character: number,
+ ): Promise<Location | LocationLink | Array<Location | LocationLink> | null> {
+ const absPath = resolve(filePath);
+ await this.openFile(absPath);
+ return this.sendRequest<Location | LocationLink | Array<Location | LocationLink> | null>(
+ "textDocument/definition",
+ {
+ textDocument: { uri: pathToFileURL(absPath).href },
+ position: { line: line - 1, character },
+ },
+ );
+ }
+
+ async references(filePath: string, line: number, character: number, includeDeclaration = true): Promise<Location[]> {
+ const absPath = resolve(filePath);
+ await this.openFile(absPath);
+ return this.sendRequest<Location[]>("textDocument/references", {
+ textDocument: { uri: pathToFileURL(absPath).href },
+ position: { line: line - 1, character },
+ context: { includeDeclaration },
+ });
+ }
+
+ async documentSymbols(filePath: string): Promise<Array<DocumentSymbol | SymbolInfo>> {
+ const absPath = resolve(filePath);
+ await this.openFile(absPath);
+ return this.sendRequest<Array<DocumentSymbol | SymbolInfo>>("textDocument/documentSymbol", {
+ textDocument: { uri: pathToFileURL(absPath).href },
+ });
+ }
+
+ async workspaceSymbols(query: string): Promise<SymbolInfo[]> {
+ return this.sendRequest<SymbolInfo[]>("workspace/symbol", { query });
+ }
+
+ private isUnsupportedDiagnosticPullError(error: unknown): boolean {
+ if (!(error instanceof Error)) return false;
+ const code = "code" in error && typeof error.code === "number" ? error.code : undefined;
+ if (code === -32601) return true;
+ return /unsupported|not supported|method not found|unknown request/i.test(error.message);
+ }
+
+ async diagnostics(filePath: string): Promise<{ items: Diagnostic[] }> {
+ const absPath = resolve(filePath);
+ const uri = pathToFileURL(absPath).href;
+ await this.openFile(absPath);
+ await new Promise((r) => setTimeout(r, POST_DIAGNOSTICS_WAIT_MS));
+
+ try {
+ const result = await this.sendRequest<{ items?: Diagnostic[] }>("textDocument/diagnostic", {
+ textDocument: { uri },
+ });
+ if (result.items) {
+ return { items: result.items };
+ }
+ } catch (error) {
+ if (!this.isUnsupportedDiagnosticPullError(error)) {
+ this.diagnosticPullErrors.push(error instanceof Error ? error : new Error(String(error)));
+ }
+ }
+
+ return { items: this.getStoredDiagnostics(uri) };
+ }
+
+ async prepareRename(
+ filePath: string,
+ line: number,
+ character: number,
+ ): Promise<PrepareRenameResult | PrepareRenameDefaultBehavior | Range | null> {
+ const absPath = resolve(filePath);
+ await this.openFile(absPath);
+ return this.sendRequest<PrepareRenameResult | PrepareRenameDefaultBehavior | Range | null>(
+ "textDocument/prepareRename",
+ {
+ textDocument: { uri: pathToFileURL(absPath).href },
+ position: { line: line - 1, character },
+ },
+ );
+ }
+
+ async rename(filePath: string, line: number, character: number, newName: string): Promise<WorkspaceEdit | null> {
+ const absPath = resolve(filePath);
+ await this.openFile(absPath);
+ return this.sendRequest<WorkspaceEdit | null>("textDocument/rename", {
+ textDocument: { uri: pathToFileURL(absPath).href },
+ position: { line: line - 1, character },
+ newName,
+ });
+ }
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/config-loader.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/config-loader.ts
new file mode 100644
index 00000000..245938b9
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/config-loader.ts
@@ -0,0 +1,188 @@
+import { existsSync, readFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { isAbsolute, join } from "node:path";
+
+import { BUILTIN_SERVERS } from "./server-definitions.js";
+import type { ResolvedServer } from "./types.js";
+
+interface LspEntry {
+ disabled?: boolean;
+ command?: string[];
+ extensions?: string[];
+ priority?: number;
+ env?: Record<string, string>;
+ initialization?: Record<string, unknown>;
+}
+
+interface ConfigJson {
+ lsp?: Record<string, unknown>;
+}
+
+type ConfigSource = "project" | "user";
+
+export interface ServerWithSource extends ResolvedServer {
+ source: "project" | "user" | "builtin";
+}
+
+export function getConfigPaths(): { project: string; user: string } {
+ const cwd = process.cwd();
+ const projectOverride = process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];
+ const userOverride = process.env["LSP_TOOLS_MCP_USER_CONFIG"];
+ return {
+ project: projectOverride
+ ? isAbsolute(projectOverride)
+ ? projectOverride
+ : join(cwd, projectOverride)
+ : join(cwd, ".codex", "lsp-client.json"),
+ user: userOverride
+ ? isAbsolute(userOverride)
+ ? userOverride
+ : join(homedir(), userOverride)
+ : join(homedir(), ".codex", "lsp-client.json"),
+ };
+}
+
+function loadJsonFile(path: string): ConfigJson | null {
+ if (!existsSync(path)) return null;
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf-8"));
+ return isConfigJson(parsed) ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+export function loadAllConfigs(): Map<ConfigSource, ConfigJson> {
+ const paths = getConfigPaths();
+ const configs = new Map<ConfigSource, ConfigJson>();
+
+ const project = loadJsonFile(paths.project);
+ if (project) configs.set("project", project);
+
+ const user = loadJsonFile(paths.user);
+ if (user) configs.set("user", user);
+
+ return configs;
+}
+
+export function getMergedServers(): ServerWithSource[] {
+ const configs = loadAllConfigs();
+ const servers: ServerWithSource[] = [];
+ const disabled = new Set<string>();
+ const seen = new Set<string>();
+
+ const sources: ConfigSource[] = ["project", "user"];
+
+ for (const source of sources) {
+ const config = configs.get(source);
+ if (!config?.lsp) continue;
+
+ for (const [id, rawEntry] of Object.entries(config.lsp)) {
+ const entry = parseLspEntry(rawEntry);
+ if (!entry) continue;
+ if (entry.disabled) {
+ disabled.add(id);
+ continue;
+ }
+
+ if (seen.has(id)) continue;
+ if (!entry.command || !entry.extensions) continue;
+
+ const server: ServerWithSource = {
+ id,
+ command: entry.command,
+ extensions: entry.extensions,
+ priority: entry.priority ?? 0,
+ source,
+ };
+ if (entry.env !== undefined) {
+ server.env = entry.env;
+ }
+ if (entry.initialization !== undefined) {
+ server.initialization = entry.initialization;
+ }
+ servers.push(server);
+ seen.add(id);
+ }
+ }
+
+ for (const [id, config] of Object.entries(BUILTIN_SERVERS)) {
+ if (disabled.has(id) || seen.has(id)) continue;
+
+ servers.push({
+ id,
+ command: config.command,
+ extensions: config.extensions,
+ priority: -100,
+ source: "builtin",
+ });
+ }
+
+ return servers.sort((a, b) => {
+ if (a.source !== b.source) {
+ const order: Record<"project" | "user" | "builtin", number> = {
+ project: 0,
+ user: 1,
+ builtin: 2,
+ };
+ return order[a.source] - order[b.source];
+ }
+ return b.priority - a.priority;
+ });
+}
+
+function isConfigJson(value: unknown): value is ConfigJson {
+ if (!isRecord(value)) return false;
+ const lsp = value["lsp"];
+ return lsp === undefined || isRecord(lsp);
+}
+
+function parseLspEntry(value: unknown): LspEntry | null {
+ return isLspEntry(value) ? value : null;
+}
+
+function isLspEntry(value: unknown): value is LspEntry {
+ if (!isRecord(value)) return false;
+ const disabled = value["disabled"];
+ const command = value["command"];
+ const extensions = value["extensions"];
+ const priority = value["priority"];
+ const env = value["env"];
+ const initialization = value["initialization"];
+ return (
+ (disabled === undefined || typeof disabled === "boolean") &&
+ (command === undefined || isStringArray(command)) &&
+ (extensions === undefined || isStringArray(extensions)) &&
+ (priority === undefined || typeof priority === "number") &&
+ (env === undefined || isStringRecord(env)) &&
+ (initialization === undefined || isRecord(initialization))
+ );
+}
+
+function isStringArray(value: unknown): value is string[] {
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
+}
+
+function isStringRecord(value: unknown): value is Record<string, string> {
+ return isRecord(value) && Object.values(value).every((item) => typeof item === "string");
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+export function getDisabledServerIds(): Set<string> {
+ const configs = loadAllConfigs();
+ const disabled = new Set<string>();
+
+ for (const config of configs.values()) {
+ if (!config.lsp) continue;
+ for (const [id, rawEntry] of Object.entries(config.lsp)) {
+ const entry = parseLspEntry(rawEntry);
+ if (!entry) continue;
+ if (entry.disabled) disabled.add(id);
+ }
+ }
+
+ return disabled;
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/connection.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/connection.ts
new file mode 100644
index 00000000..8cf905fc
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/connection.ts
@@ -0,0 +1,69 @@
+import { pathToFileURL } from "node:url";
+
+import { LspClientTransport } from "./transport.js";
+
+const INITIALIZE_SETTLE_MS = 300;
+
+export class LspClientConnection extends LspClientTransport {
+ async initialize(): Promise<void> {
+ const rootUri = pathToFileURL(this.root).href;
+ await this.sendRequest("initialize", {
+ processId: process.pid,
+ rootUri,
+ rootPath: this.root,
+ workspaceFolders: [{ uri: rootUri, name: "workspace" }],
+ capabilities: {
+ textDocument: {
+ hover: { contentFormat: ["markdown", "plaintext"] },
+ definition: { linkSupport: true },
+ references: {},
+ documentSymbol: { hierarchicalDocumentSymbolSupport: true },
+ publishDiagnostics: {},
+ rename: {
+ prepareSupport: true,
+ prepareSupportDefaultBehavior: 1,
+ honorsChangeAnnotations: true,
+ },
+ codeAction: {
+ codeActionLiteralSupport: {
+ codeActionKind: {
+ valueSet: [
+ "quickfix",
+ "refactor",
+ "refactor.extract",
+ "refactor.inline",
+ "refactor.rewrite",
+ "source",
+ "source.organizeImports",
+ "source.fixAll",
+ ],
+ },
+ },
+ isPreferredSupport: true,
+ disabledSupport: true,
+ dataSupport: true,
+ resolveSupport: {
+ properties: ["edit", "command"],
+ },
+ },
+ },
+ workspace: {
+ symbol: {},
+ workspaceFolders: true,
+ configuration: true,
+ applyEdit: true,
+ workspaceEdit: {
+ documentChanges: true,
+ },
+ },
+ },
+ initializationOptions: this.server.initialization,
+ });
+ await this.sendNotification("initialized");
+ await this.sendNotification("workspace/didChangeConfiguration", {
+ settings: { json: { validate: { enable: true } } },
+ });
+ // Some servers accept initialized before their diagnostics/indexing handlers are ready.
+ await new Promise((r) => setTimeout(r, INITIALIZE_SETTLE_MS));
+ }
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/constants.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/constants.ts
new file mode 100644
index 00000000..8dbddbbf
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/constants.ts
@@ -0,0 +1,11 @@
+export const DEFAULT_MAX_REFERENCES = 200;
+export const DEFAULT_MAX_SYMBOLS = 200;
+export const DEFAULT_MAX_DIAGNOSTICS = 200;
+export const DEFAULT_MAX_DIRECTORY_FILES = 50;
+
+export const REQUEST_TIMEOUT_MS = 15_000;
+export const INIT_TIMEOUT_MS = 60_000;
+export const IDLE_TIMEOUT_MS = 5 * 60_000;
+export const REAPER_INTERVAL_MS = 60_000;
+export const STOP_HARD_KILL_TIMEOUT_MS = 5_000;
+export const STOP_SIGKILL_GRACE_MS = 1_000;
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/directory-diagnostics.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/directory-diagnostics.ts
new file mode 100644
index 00000000..90e6849a
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/directory-diagnostics.ts
@@ -0,0 +1,152 @@
+import { existsSync, lstatSync, readdirSync, type Stats } from "node:fs";
+import { extname, join, resolve } from "node:path";
+import { findWorkspaceRoot, formatServerLookupError } from "./client-wrapper.js";
+import { DEFAULT_MAX_DIAGNOSTICS, DEFAULT_MAX_DIRECTORY_FILES } from "./constants.js";
+import { LspInvalidPathError, LspServerLookupError } from "./errors.js";
+import { filterDiagnosticsBySeverity, formatDiagnostic } from "./formatters.js";
+import { getLspManager } from "./manager.js";
+import { findServerForExtension } from "./server-resolution.js";
+import type { Diagnostic, SeverityFilter } from "./types.js";
+
+const SKIP_DIRECTORIES = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
+
+interface FileDiagnostic {
+ filePath: string;
+ diagnostic: Diagnostic;
+}
+
+export function collectFilesWithExtension(dir: string, extension: string, maxFiles: number): string[] {
+ const files: string[] = [];
+
+ function walk(currentDir: string): void {
+ if (files.length >= maxFiles) return;
+
+ let entries: string[] = [];
+ try {
+ entries = readdirSync(currentDir);
+ } catch {
+ return;
+ }
+
+ for (const entry of entries) {
+ if (files.length >= maxFiles) return;
+
+ const fullPath = join(currentDir, entry);
+
+ let stat: Stats | undefined;
+ try {
+ stat = lstatSync(fullPath);
+ } catch {
+ continue;
+ }
+
+ if (!stat || stat.isSymbolicLink()) continue;
+
+ if (stat.isDirectory()) {
+ if (!SKIP_DIRECTORIES.has(entry)) {
+ walk(fullPath);
+ }
+ } else if (stat.isFile() && extname(fullPath) === extension) {
+ files.push(fullPath);
+ }
+ }
+ }
+
+ walk(dir);
+ return files;
+}
+
+export async function aggregateDiagnosticsForDirectory(
+ directory: string,
+ extension: string,
+ severity?: SeverityFilter,
+ maxFiles: number = DEFAULT_MAX_DIRECTORY_FILES,
+): Promise<string> {
+ if (!extension.startsWith(".")) {
+ throw new LspInvalidPathError(
+ `Extension must start with a dot (e.g., ".ts", not "${extension}"). Use ".${extension}" instead.`,
+ );
+ }
+
+ const absDir = resolve(directory);
+ if (!existsSync(absDir)) {
+ throw new LspInvalidPathError(`Directory does not exist: ${absDir}`);
+ }
+
+ const serverResult = findServerForExtension(extension);
+ if (serverResult.status !== "found") {
+ throw new LspServerLookupError(formatServerLookupError(serverResult));
+ }
+
+ const server = serverResult.server;
+ const allFiles = collectFilesWithExtension(absDir, extension, maxFiles + 1);
+ const wasCapped = allFiles.length > maxFiles;
+ const filesToProcess = allFiles.slice(0, maxFiles);
+
+ if (filesToProcess.length === 0) {
+ return [
+ `Directory: ${absDir}`,
+ `Extension: ${extension}`,
+ "Files scanned: 0",
+ `No files found with extension "${extension}".`,
+ ].join("\n");
+ }
+
+ const root = findWorkspaceRoot(absDir);
+ const manager = getLspManager();
+ const allDiagnostics: FileDiagnostic[] = [];
+ const fileErrors: { file: string; error: string }[] = [];
+
+ const client = await manager.getClient(root, server);
+ try {
+ for (const file of filesToProcess) {
+ try {
+ const result = await client.diagnostics(file);
+ const filtered = filterDiagnosticsBySeverity(result.items, severity);
+ allDiagnostics.push(
+ ...filtered.map((diagnostic) => ({
+ filePath: file,
+ diagnostic,
+ })),
+ );
+ } catch (e) {
+ fileErrors.push({
+ file,
+ error: e instanceof Error ? e.message : String(e),
+ });
+ }
+ }
+ } finally {
+ manager.releaseClient(root, server.id);
+ }
+
+ const displayDiagnostics = allDiagnostics.slice(0, DEFAULT_MAX_DIAGNOSTICS);
+ const wasDiagCapped = allDiagnostics.length > DEFAULT_MAX_DIAGNOSTICS;
+
+ const lines: string[] = [
+ `Directory: ${absDir}`,
+ `Extension: ${extension}`,
+ `Files scanned: ${filesToProcess.length}${wasCapped ? ` (capped at ${maxFiles})` : ""}`,
+ `Files with errors: ${fileErrors.length}`,
+ `Total diagnostics: ${allDiagnostics.length}`,
+ ];
+
+ if (fileErrors.length > 0) {
+ lines.push("", "File processing errors:");
+ for (const { file, error } of fileErrors) {
+ lines.push(` ${file}: ${error}`);
+ }
+ }
+
+ if (displayDiagnostics.length > 0) {
+ lines.push("");
+ for (const { filePath, diagnostic } of displayDiagnostics) {
+ lines.push(`${filePath}: ${formatDiagnostic(diagnostic)}`);
+ }
+ if (wasDiagCapped) {
+ lines.push("", `... (${allDiagnostics.length - DEFAULT_MAX_DIAGNOSTICS} more diagnostics not shown)`);
+ }
+ }
+
+ return lines.join("\n");
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/errors.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/errors.ts
new file mode 100644
index 00000000..186c3c71
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/errors.ts
@@ -0,0 +1,63 @@
+export class LspConnectionClosedError extends Error {
+ override readonly name = "LspConnectionClosedError";
+
+ constructor(
+ readonly serverId: string,
+ readonly root: string,
+ message?: string,
+ ) {
+ super(message ?? `LSP connection closed for ${serverId} at ${root}`);
+ }
+}
+
+export class LspProcessExitedError extends Error {
+ override readonly name = "LspProcessExitedError";
+
+ constructor(
+ readonly serverId: string,
+ readonly root: string,
+ readonly exitCode: number | null,
+ readonly stderrTail?: string,
+ ) {
+ const stderrSuffix = stderrTail ? `\nstderr tail: ${stderrTail}` : "";
+ super(`LSP server ${serverId} at ${root} exited with code ${exitCode ?? "null"}${stderrSuffix}`);
+ }
+}
+
+export class LspRequestTimeoutError extends Error {
+ override readonly name = "LspRequestTimeoutError";
+
+ constructor(
+ readonly method: string,
+ readonly stderrTail?: string,
+ ) {
+ const stderrSuffix = stderrTail ? `\nrecent stderr: ${stderrTail}` : "";
+ super(`LSP request timeout (method: ${method})${stderrSuffix}`);
+ }
+}
+
+export class LspInvalidPathError extends Error {
+ override readonly name = "LspInvalidPathError";
+}
+
+export class LspServerLookupError extends Error {
+ override readonly name = "LspServerLookupError";
+}
+
+export class LspServerInitializingError extends Error {
+ override readonly name = "LspServerInitializingError";
+
+ constructor(readonly originalError: LspRequestTimeoutError) {
+ super(
+ `LSP server is still initializing. Please retry in a few seconds. Original error: ${originalError.message}`,
+ );
+ }
+}
+
+export class LspProcessSpawnError extends Error {
+ override readonly name = "LspProcessSpawnError";
+}
+
+export function isLspDeadConnectionError(err: unknown): err is LspConnectionClosedError | LspProcessExitedError {
+ return err instanceof LspConnectionClosedError || err instanceof LspProcessExitedError;
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/formatters.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/formatters.ts
new file mode 100644
index 00000000..7f8e836a
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/formatters.ts
@@ -0,0 +1,141 @@
+import { fileURLToPath } from "node:url";
+
+import { SEVERITY_MAP, SYMBOL_KIND_MAP } from "./language-mappings.js";
+import type {
+ Diagnostic,
+ DocumentSymbol,
+ Location,
+ LocationLink,
+ PrepareRenameDefaultBehavior,
+ PrepareRenameResult,
+ Range,
+ SeverityFilter,
+ SymbolInfo,
+} from "./types.js";
+import type { ApplyResult } from "./workspace-edit.js";
+
+type FilteredSeverity = Exclude<SeverityFilter, "all">;
+
+const DIAGNOSTIC_SEVERITY_FILTERS = {
+ error: 1,
+ warning: 2,
+ information: 3,
+ hint: 4,
+} as const satisfies Readonly<Record<FilteredSeverity, number>>;
+
+export function uriToPath(uri: string): string {
+ return fileURLToPath(uri);
+}
+
+export function formatLocation(loc: Location | LocationLink): string {
+ if ("targetUri" in loc) {
+ const uri = uriToPath(loc.targetUri);
+ const line = loc.targetRange.start.line + 1;
+ const char = loc.targetRange.start.character;
+ return `${uri}:${line}:${char}`;
+ }
+
+ const uri = uriToPath(loc.uri);
+ const line = loc.range.start.line + 1;
+ const char = loc.range.start.character;
+ return `${uri}:${line}:${char}`;
+}
+
+export function formatSymbolKind(kind: number): string {
+ return SYMBOL_KIND_MAP[kind] ?? `Unknown(${kind})`;
+}
+
+export function formatSeverity(severity: number | undefined): string {
+ if (!severity) return "unknown";
+ return SEVERITY_MAP[severity] ?? `unknown(${severity})`;
+}
+
+export function formatDocumentSymbol(symbol: DocumentSymbol, indent = 0): string {
+ const prefix = " ".repeat(indent);
+ const kind = formatSymbolKind(symbol.kind);
+ const line = symbol.range.start.line + 1;
+ let result = `${prefix}${symbol.name} (${kind}) - line ${line}`;
+
+ if (symbol.children && symbol.children.length > 0) {
+ for (const child of symbol.children) {
+ result += `\n${formatDocumentSymbol(child, indent + 1)}`;
+ }
+ }
+
+ return result;
+}
+
+export function formatSymbolInfo(symbol: SymbolInfo): string {
+ const kind = formatSymbolKind(symbol.kind);
+ const loc = formatLocation(symbol.location);
+ const container = symbol.containerName ? ` (in ${symbol.containerName})` : "";
+ return `${symbol.name} (${kind})${container} - ${loc}`;
+}
+
+export function formatDiagnostic(diag: Diagnostic): string {
+ const severity = formatSeverity(diag.severity);
+ const line = diag.range.start.line + 1;
+ const char = diag.range.start.character;
+ const source = diag.source ? `[${diag.source}]` : "";
+ const code = diag.code ? ` (${diag.code})` : "";
+ return `${severity}${source}${code} at ${line}:${char}: ${diag.message}`;
+}
+
+export function filterDiagnosticsBySeverity(diagnostics: Diagnostic[], severityFilter?: SeverityFilter): Diagnostic[] {
+ if (!severityFilter || severityFilter === "all") {
+ return diagnostics;
+ }
+
+ const targetSeverity = DIAGNOSTIC_SEVERITY_FILTERS[severityFilter];
+ return diagnostics.filter((d) => d.severity === targetSeverity);
+}
+
+export function formatPrepareRenameResult(
+ result: PrepareRenameResult | PrepareRenameDefaultBehavior | Range | null,
+): string {
+ if (!result) return "Cannot rename at this position";
+
+ if ("defaultBehavior" in result) {
+ return result.defaultBehavior ? "Rename supported (using default behavior)" : "Cannot rename at this position";
+ }
+
+ if ("range" in result && result.range) {
+ const startLine = result.range.start.line + 1;
+ const startChar = result.range.start.character;
+ const endLine = result.range.end.line + 1;
+ const endChar = result.range.end.character;
+ const placeholder = result.placeholder ? ` (current: "${result.placeholder}")` : "";
+ return `Rename available at ${startLine}:${startChar}-${endLine}:${endChar}${placeholder}`;
+ }
+
+ if ("start" in result && "end" in result) {
+ const startLine = result.start.line + 1;
+ const startChar = result.start.character;
+ const endLine = result.end.line + 1;
+ const endChar = result.end.character;
+ return `Rename available at ${startLine}:${startChar}-${endLine}:${endChar}`;
+ }
+
+ return "Cannot rename at this position";
+}
+
+export function formatApplyResult(result: ApplyResult): string {
+ const lines: string[] = [];
+
+ if (result.success) {
+ lines.push(`Applied ${result.totalEdits} edit(s) to ${result.filesModified.length} file(s):`);
+ for (const file of result.filesModified) {
+ lines.push(` - ${file}`);
+ }
+ } else {
+ lines.push("Failed to apply some changes:");
+ for (const err of result.errors) {
+ lines.push(` Error: ${err}`);
+ }
+ if (result.filesModified.length > 0) {
+ lines.push(`Successfully modified: ${result.filesModified.join(", ")}`);
+ }
+ }
+
+ return lines.join("\n");
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/infer-extension.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/infer-extension.ts
new file mode 100644
index 00000000..31771cbc
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/infer-extension.ts
@@ -0,0 +1,65 @@
+import { lstatSync, readdirSync } from "node:fs";
+import { extname, join } from "node:path";
+
+import { EXT_TO_LANG } from "./language-mappings.js";
+
+const SKIP_DIRECTORIES = new Set(["node_modules", ".git", "dist", "build", ".next", "out"]);
+const MAX_SCAN_ENTRIES = 500;
+
+export function inferExtensionFromDirectory(directory: string): string | null {
+ const extensionCounts = new Map<string, number>();
+ let scanned = 0;
+
+ function walk(dir: string): void {
+ if (scanned >= MAX_SCAN_ENTRIES) return;
+
+ let entries: string[];
+ try {
+ entries = readdirSync(dir);
+ } catch {
+ return;
+ }
+
+ for (const entry of entries) {
+ if (scanned >= MAX_SCAN_ENTRIES) return;
+
+ const fullPath = join(dir, entry);
+
+ let stat: ReturnType<typeof lstatSync> | undefined;
+ try {
+ stat = lstatSync(fullPath);
+ } catch {
+ continue;
+ }
+
+ if (stat.isSymbolicLink()) continue;
+ scanned++;
+
+ if (stat.isDirectory()) {
+ if (!SKIP_DIRECTORIES.has(entry)) {
+ walk(fullPath);
+ }
+ } else if (stat.isFile()) {
+ const ext = extname(fullPath);
+ if (ext && ext in EXT_TO_LANG) {
+ extensionCounts.set(ext, (extensionCounts.get(ext) ?? 0) + 1);
+ }
+ }
+ }
+ }
+
+ walk(directory);
+
+ if (extensionCounts.size === 0) return null;
+
+ let maxExt = "";
+ let maxCount = 0;
+ for (const [ext, count] of extensionCounts) {
+ if (count > maxCount) {
+ maxCount = count;
+ maxExt = ext;
+ }
+ }
+
+ return maxExt || null;
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/json-rpc-connection.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/json-rpc-connection.ts
new file mode 100644
index 00000000..2769466a
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/json-rpc-connection.ts
@@ -0,0 +1,296 @@
+type JsonRpcId = number | string | null;
+
+interface PendingRequest {
+ resolve(result: unknown): void;
+ reject(error: Error): void;
+}
+
+type NotificationHandler = (params: unknown) => void;
+type RequestHandler = (params: unknown) => Promise<unknown> | unknown;
+
+const HEADER_SEPARATOR = "\r\n\r\n";
+const PARSE_ERROR = -32700;
+const INVALID_REQUEST = -32600;
+const METHOD_NOT_FOUND = -32601;
+const INTERNAL_ERROR = -32603;
+
+export class JsonRpcConnection {
+ private readonly pendingRequests = new Map<string, PendingRequest>();
+ private readonly notificationHandlers = new Map<string, NotificationHandler>();
+ private readonly requestHandlers = new Map<string, RequestHandler>();
+ private readonly closeHandlers: Array<() => void> = [];
+ private readonly errorHandlers: Array<(error: Error) => void> = [];
+ private inputBuffer = Buffer.alloc(0);
+ private nextRequestId = 1;
+ private listening = false;
+ private disposed = false;
+
+ constructor(
+ private readonly reader: NodeJS.ReadableStream,
+ private readonly writer: NodeJS.WritableStream,
+ ) {}
+
+ listen(): void {
+ if (this.listening) return;
+ this.listening = true;
+ this.reader.on("data", this.handleData);
+ this.reader.on("close", this.handleClose);
+ this.reader.on("end", this.handleClose);
+ this.reader.on("error", this.handleStreamError);
+ this.writer.on("error", this.handleStreamError);
+ }
+
+ onNotification(method: string, handler: NotificationHandler): void {
+ this.notificationHandlers.set(method, handler);
+ }
+
+ onRequest(method: string, handler: RequestHandler): void {
+ this.requestHandlers.set(method, handler);
+ }
+
+ onClose(handler: () => void): void {
+ this.closeHandlers.push(handler);
+ }
+
+ onError(handler: (error: Error) => void): void {
+ this.errorHandlers.push(handler);
+ }
+
+ async sendRequest<T>(method: string, params?: unknown): Promise<T> {
+ if (this.disposed) throw new Error("JSON-RPC connection is disposed");
+
+ const id = this.nextRequestId;
+ this.nextRequestId += 1;
+ const message = params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
+
+ const responsePromise = new Promise<T>((resolve, reject) => {
+ this.pendingRequests.set(String(id), {
+ resolve(result) {
+ resolve(result as T);
+ },
+ reject,
+ });
+ });
+
+ try {
+ await this.writeMessage(message);
+ } catch (error) {
+ this.pendingRequests.delete(String(id));
+ throw error;
+ }
+
+ return responsePromise;
+ }
+
+ async sendNotification(method: string, params?: unknown): Promise<void> {
+ if (this.disposed) return;
+ const message = params === undefined ? { jsonrpc: "2.0", method } : { jsonrpc: "2.0", method, params };
+ await this.writeMessage(message);
+ }
+
+ dispose(): void {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.reader.off("data", this.handleData);
+ this.reader.off("close", this.handleClose);
+ this.reader.off("end", this.handleClose);
+ this.reader.off("error", this.handleStreamError);
+ this.writer.off("error", this.handleStreamError);
+ for (const pending of this.pendingRequests.values()) {
+ pending.reject(new Error("JSON-RPC connection disposed"));
+ }
+ this.pendingRequests.clear();
+ this.notificationHandlers.clear();
+ this.requestHandlers.clear();
+ }
+
+ private readonly handleData = (chunk: Buffer | string): void => {
+ const chunkBuffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, "utf8");
+ this.inputBuffer = Buffer.concat([this.inputBuffer, chunkBuffer]);
+ this.drainInputBuffer();
+ };
+
+ private readonly handleClose = (): void => {
+ for (const handler of this.closeHandlers) {
+ handler();
+ }
+ };
+
+ private readonly handleStreamError = (error: Error): void => {
+ this.emitError(error);
+ };
+
+ private drainInputBuffer(): void {
+ while (true) {
+ const headerEnd = this.inputBuffer.indexOf(HEADER_SEPARATOR);
+ if (headerEnd === -1) return;
+
+ const headers = this.inputBuffer.subarray(0, headerEnd).toString("ascii");
+ const contentLength = parseContentLength(headers);
+ if (contentLength === null) {
+ this.inputBuffer = Buffer.alloc(0);
+ this.emitError(new Error("JSON-RPC message is missing Content-Length header"));
+ return;
+ }
+
+ const bodyStart = headerEnd + Buffer.byteLength(HEADER_SEPARATOR);
+ const bodyEnd = bodyStart + contentLength;
+ if (this.inputBuffer.length < bodyEnd) return;
+
+ const body = this.inputBuffer.subarray(bodyStart, bodyEnd).toString("utf8");
+ this.inputBuffer = this.inputBuffer.subarray(bodyEnd);
+ this.dispatchBody(body);
+ }
+ }
+
+ private dispatchBody(body: string): void {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(body);
+ } catch (error) {
+ void this.writeError(null, PARSE_ERROR, error instanceof Error ? error.message : "Parse error").catch(
+ (writeError) => this.emitError(toError(writeError)),
+ );
+ return;
+ }
+
+ if (!isJsonRpcObject(parsed)) {
+ void this.writeError(null, INVALID_REQUEST, "Invalid JSON-RPC message").catch((error) =>
+ this.emitError(toError(error)),
+ );
+ return;
+ }
+
+ if ("id" in parsed && ("result" in parsed || "error" in parsed)) {
+ this.handleResponse(parsed);
+ return;
+ }
+
+ if (typeof parsed["method"] !== "string") {
+ const id = getMessageId(parsed) ?? null;
+ void this.writeError(id, INVALID_REQUEST, "Invalid JSON-RPC method").catch((error) =>
+ this.emitError(toError(error)),
+ );
+ return;
+ }
+
+ if ("id" in parsed) {
+ this.handleRequest(parsed);
+ return;
+ }
+
+ this.handleNotification(parsed["method"], parsed["params"]);
+ }
+
+ private handleResponse(message: Record<string, unknown>): void {
+ const id = getMessageId(message);
+ if (id === undefined) return;
+ const pending = this.pendingRequests.get(String(id));
+ if (!pending) return;
+ this.pendingRequests.delete(String(id));
+
+ if ("error" in message) {
+ pending.reject(jsonRpcErrorToError(message["error"]));
+ return;
+ }
+
+ pending.resolve(message["result"]);
+ }
+
+ private handleNotification(method: string, params: unknown): void {
+ const handler = this.notificationHandlers.get(method);
+ if (!handler) return;
+ try {
+ handler(params);
+ } catch (error) {
+ this.emitError(toError(error));
+ }
+ }
+
+ private handleRequest(message: Record<string, unknown>): void {
+ const id = getMessageId(message);
+ if (id === undefined) {
+ void this.writeError(null, INVALID_REQUEST, "Invalid JSON-RPC id").catch((error) =>
+ this.emitError(toError(error)),
+ );
+ return;
+ }
+
+ const method = typeof message["method"] === "string" ? message["method"] : "";
+ const handler = this.requestHandlers.get(method);
+ if (!handler) {
+ void this.writeError(id, METHOD_NOT_FOUND, `Method not found: ${method}`).catch((error) =>
+ this.emitError(toError(error)),
+ );
+ return;
+ }
+
+ Promise.resolve()
+ .then(() => handler(message["params"]))
+ .then(
+ (result) => this.writeMessage({ jsonrpc: "2.0", id, result }),
+ (error) => this.writeError(id, INTERNAL_ERROR, toError(error).message),
+ )
+ .catch((error) => this.emitError(toError(error)));
+ }
+
+ private async writeError(id: JsonRpcId, code: number, message: string): Promise<void> {
+ await this.writeMessage({ jsonrpc: "2.0", id, error: { code, message } });
+ }
+
+ private writeMessage(message: Record<string, unknown>): Promise<void> {
+ const body = JSON.stringify(message);
+ const payload = `Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`;
+ return new Promise((resolve, reject) => {
+ this.writer.write(payload, (error?: Error | null) => {
+ if (error) {
+ reject(error);
+ return;
+ }
+ resolve();
+ });
+ });
+ }
+
+ private emitError(error: Error): void {
+ for (const handler of this.errorHandlers) {
+ handler(error);
+ }
+ }
+}
+
+function parseContentLength(headers: string): number | null {
+ for (const line of headers.split("\r\n")) {
+ const separatorIndex = line.indexOf(":");
+ if (separatorIndex === -1) continue;
+ const name = line.slice(0, separatorIndex).trim().toLowerCase();
+ if (name !== "content-length") continue;
+ const value = Number.parseInt(line.slice(separatorIndex + 1).trim(), 10);
+ return Number.isFinite(value) && value >= 0 ? value : null;
+ }
+ return null;
+}
+
+function isJsonRpcObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function getMessageId(message: Record<string, unknown>): JsonRpcId | undefined {
+ const id = message["id"];
+ if (typeof id === "number" || typeof id === "string" || id === null) return id;
+ return undefined;
+}
+
+function jsonRpcErrorToError(value: unknown): Error {
+ if (!isJsonRpcObject(value)) return new Error("JSON-RPC request failed");
+ const message = typeof value["message"] === "string" ? value["message"] : "JSON-RPC request failed";
+ const error = new Error(message);
+ if (typeof value["code"] === "number") {
+ error.name = `JsonRpcError(${value["code"]})`;
+ }
+ return error;
+}
+
+function toError(error: unknown): Error {
+ return error instanceof Error ? error : new Error(String(error));
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/language-mappings.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/language-mappings.ts
new file mode 100644
index 00000000..ace3c234
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/language-mappings.ts
@@ -0,0 +1,172 @@
+export const SYMBOL_KIND_MAP: Record<number, string> = {
+ 1: "File",
+ 2: "Module",
+ 3: "Namespace",
+ 4: "Package",
+ 5: "Class",
+ 6: "Method",
+ 7: "Property",
+ 8: "Field",
+ 9: "Constructor",
+ 10: "Enum",
+ 11: "Interface",
+ 12: "Function",
+ 13: "Variable",
+ 14: "Constant",
+ 15: "String",
+ 16: "Number",
+ 17: "Boolean",
+ 18: "Array",
+ 19: "Object",
+ 20: "Key",
+ 21: "Null",
+ 22: "EnumMember",
+ 23: "Struct",
+ 24: "Event",
+ 25: "Operator",
+ 26: "TypeParameter",
+};
+
+export const SEVERITY_MAP: Record<number, string> = {
+ 1: "error",
+ 2: "warning",
+ 3: "information",
+ 4: "hint",
+};
+
+export const EXT_TO_LANG: Record<string, string> = {
+ ".abap": "abap",
+ ".bat": "bat",
+ ".bib": "bibtex",
+ ".bibtex": "bibtex",
+ ".clj": "clojure",
+ ".cljs": "clojure",
+ ".cljc": "clojure",
+ ".edn": "clojure",
+ ".coffee": "coffeescript",
+ ".c": "c",
+ ".cpp": "cpp",
+ ".cxx": "cpp",
+ ".cc": "cpp",
+ ".c++": "cpp",
+ ".cs": "csharp",
+ ".css": "css",
+ ".d": "d",
+ ".pas": "pascal",
+ ".pascal": "pascal",
+ ".diff": "diff",
+ ".patch": "diff",
+ ".dart": "dart",
+ ".dockerfile": "dockerfile",
+ ".ex": "elixir",
+ ".exs": "elixir",
+ ".erl": "erlang",
+ ".hrl": "erlang",
+ ".fs": "fsharp",
+ ".fsi": "fsharp",
+ ".fsx": "fsharp",
+ ".fsscript": "fsharp",
+ ".gitcommit": "git-commit",
+ ".gitrebase": "git-rebase",
+ ".go": "go",
+ ".groovy": "groovy",
+ ".gleam": "gleam",
+ ".hbs": "handlebars",
+ ".handlebars": "handlebars",
+ ".hs": "haskell",
+ ".html": "html",
+ ".htm": "html",
+ ".ini": "ini",
+ ".java": "java",
+ ".js": "javascript",
+ ".jsx": "javascriptreact",
+ ".json": "json",
+ ".jsonc": "jsonc",
+ ".tex": "latex",
+ ".latex": "latex",
+ ".less": "less",
+ ".lua": "lua",
+ ".makefile": "makefile",
+ makefile: "makefile",
+ ".md": "markdown",
+ ".markdown": "markdown",
+ ".m": "objective-c",
+ ".mm": "objective-cpp",
+ ".pl": "perl",
+ ".pm": "perl",
+ ".pm6": "perl6",
+ ".php": "php",
+ ".ps1": "powershell",
+ ".psm1": "powershell",
+ ".pug": "jade",
+ ".jade": "jade",
+ ".py": "python",
+ ".pyi": "python",
+ ".r": "r",
+ ".cshtml": "razor",
+ ".razor": "razor",
+ ".rb": "ruby",
+ ".rake": "ruby",
+ ".gemspec": "ruby",
+ ".ru": "ruby",
+ ".erb": "erb",
+ ".html.erb": "erb",
+ ".js.erb": "erb",
+ ".css.erb": "erb",
+ ".json.erb": "erb",
+ ".rs": "rust",
+ ".scss": "scss",
+ ".sass": "sass",
+ ".scala": "scala",
+ ".shader": "shaderlab",
+ ".sh": "shellscript",
+ ".bash": "shellscript",
+ ".zsh": "shellscript",
+ ".ksh": "shellscript",
+ ".sql": "sql",
+ ".svelte": "svelte",
+ ".swift": "swift",
+ ".ts": "typescript",
+ ".tsx": "typescriptreact",
+ ".mts": "typescript",
+ ".cts": "typescript",
+ ".mtsx": "typescriptreact",
+ ".ctsx": "typescriptreact",
+ ".xml": "xml",
+ ".xsl": "xsl",
+ ".yaml": "yaml",
+ ".yml": "yaml",
+ ".mjs": "javascript",
+ ".cjs": "javascript",
+ ".vue": "vue",
+ ".zig": "zig",
+ ".zon": "zig",
+ ".astro": "astro",
+ ".ml": "ocaml",
+ ".mli": "ocaml",
+ ".tf": "terraform",
+ ".tfvars": "terraform-vars",
+ ".hcl": "hcl",
+ ".nix": "nix",
+ ".typ": "typst",
+ ".typc": "typst",
+ ".ets": "typescript",
+ ".lhs": "haskell",
+ ".kt": "kotlin",
+ ".kts": "kotlin",
+ ".prisma": "prisma",
+ ".h": "c",
+ ".hpp": "cpp",
+ ".hh": "cpp",
+ ".hxx": "cpp",
+ ".h++": "cpp",
+ ".objc": "objective-c",
+ ".objcpp": "objective-cpp",
+ ".fish": "fish",
+ ".graphql": "graphql",
+ ".gql": "graphql",
+};
+
+export function getLanguageId(ext: string): string {
+ return EXT_TO_LANG[ext] ?? "plaintext";
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/manager.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/manager.ts
new file mode 100644
index 00000000..6b2e95a5
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/manager.ts
@@ -0,0 +1,369 @@
+import { reportBestEffortCleanupError } from "./cleanup-errors.js";
+import { LspClient } from "./client.js";
+import { IDLE_TIMEOUT_MS, INIT_TIMEOUT_MS, REAPER_INTERVAL_MS } from "./constants.js";
+import { installProcessSignalCleanup } from "./process-signal-cleanup.js";
+import type { ResolvedServer } from "./types.js";
+
+interface ManagedClient {
+ client: LspClient;
+ refCount: number;
+ pendingWaiters: number;
+ lastUsedAt: number;
+ initPromise: Promise<void> | null;
+ isInitializing: boolean;
+ initializingSince: number | null;
+}
+
+export interface ClientSnapshot {
+ root: string;
+ serverId: string;
+ refCount: number;
+ pendingWaiters: number;
+ lastUsedAt: number;
+ isInitializing: boolean;
+ alive: boolean;
+ command: string[];
+}
+
+export interface LspManagerOptions {
+ idleTimeoutMs?: number;
+ initTimeoutMs?: number;
+ reaperIntervalMs?: number;
+ clientFactory?: (root: string, server: ResolvedServer) => LspClient;
+ now?: () => number;
+}
+
+async function stopClientBestEffort(client: LspClient): Promise<void> {
+ try {
+ await client.stop();
+ } catch (error) {
+ reportBestEffortCleanupError("client stop", error);
+ }
+}
+
+function awaitWithSignal<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
+ if (!signal) return promise;
+ return new Promise<T>((resolve, reject) => {
+ let settled = false;
+ const onAbort = () => {
+ if (settled) return;
+ settled = true;
+ reject(new DOMException("Aborted", "AbortError"));
+ };
+ if (signal.aborted) {
+ onAbort();
+ return;
+ }
+ signal.addEventListener("abort", onAbort, { once: true });
+ promise.then(
+ (value) => {
+ if (settled) return;
+ settled = true;
+ signal.removeEventListener("abort", onAbort);
+ resolve(value);
+ },
+ (err) => {
+ if (settled) return;
+ settled = true;
+ signal.removeEventListener("abort", onAbort);
+ reject(err);
+ },
+ );
+ });
+}
+
+export class LspManager {
+ private readonly clients = new Map<string, ManagedClient>();
+ private reaperHandle: NodeJS.Timeout | null = null;
+ private signalDisposer: (() => void) | null = null;
+ private disposed = false;
+
+ private readonly idleTimeoutMs: number;
+ private readonly initTimeoutMs: number;
+ private readonly reaperIntervalMs: number;
+ private readonly clientFactory: (root: string, server: ResolvedServer) => LspClient;
+ private readonly now: () => number;
+
+ constructor(options: LspManagerOptions = {}) {
+ this.idleTimeoutMs = options.idleTimeoutMs ?? IDLE_TIMEOUT_MS;
+ this.initTimeoutMs = options.initTimeoutMs ?? INIT_TIMEOUT_MS;
+ this.reaperIntervalMs = options.reaperIntervalMs ?? REAPER_INTERVAL_MS;
+ this.clientFactory = options.clientFactory ?? ((root, server) => new LspClient(root, server));
+ this.now = options.now ?? (() => Date.now());
+
+ this.startReaper();
+ this.signalDisposer = installProcessSignalCleanup(() => this.stopAll());
+ }
+
+ private startReaper(): void {
+ if (this.reaperHandle) return;
+ this.reaperHandle = setInterval(() => {
+ this.reapStale();
+ }, this.reaperIntervalMs);
+ if (typeof this.reaperHandle.unref === "function") {
+ this.reaperHandle.unref();
+ }
+ }
+
+ private getKey(root: string, serverId: string): string {
+ return `${root}::${serverId}`;
+ }
+
+ private reapStale(): void {
+ const t = this.now();
+ for (const [key, managed] of this.clients) {
+ if (
+ managed.isInitializing &&
+ managed.initializingSince !== null &&
+ t - managed.initializingSince > this.initTimeoutMs
+ ) {
+ void stopClientBestEffort(managed.client);
+ this.clients.delete(key);
+ continue;
+ }
+
+ if (
+ !managed.isInitializing &&
+ managed.refCount === 0 &&
+ managed.pendingWaiters === 0 &&
+ t - managed.lastUsedAt > this.idleTimeoutMs
+ ) {
+ void stopClientBestEffort(managed.client);
+ this.clients.delete(key);
+ }
+ }
+ }
+
+ private async tryDeleteIfOrphaned(key: string, managed: ManagedClient): Promise<void> {
+ if (
+ managed.refCount === 0 &&
+ managed.pendingWaiters === 0 &&
+ !managed.isInitializing &&
+ this.clients.get(key) === managed
+ ) {
+ this.clients.delete(key);
+ await stopClientBestEffort(managed.client);
+ }
+ }
+
+ async getClient(root: string, server: ResolvedServer, signal?: AbortSignal): Promise<LspClient> {
+ if (this.disposed) {
+ throw new Error("LspManager has been disposed");
+ }
+ signal?.throwIfAborted();
+
+ const key = this.getKey(root, server.id);
+ let managed = this.clients.get(key);
+
+ if (managed) {
+ const t = this.now();
+ if (
+ managed.isInitializing &&
+ managed.initializingSince !== null &&
+ t - managed.initializingSince > this.initTimeoutMs
+ ) {
+ await stopClientBestEffort(managed.client);
+ this.clients.delete(key);
+ managed = undefined;
+ }
+ }
+
+ if (managed) {
+ if (managed.initPromise) {
+ managed.pendingWaiters++;
+ try {
+ await awaitWithSignal(managed.initPromise, signal);
+ } catch (err) {
+ managed.pendingWaiters--;
+ await this.tryDeleteIfOrphaned(key, managed);
+ throw err;
+ }
+ managed.pendingWaiters--;
+ }
+
+ if (signal?.aborted) {
+ await this.tryDeleteIfOrphaned(key, managed);
+ signal.throwIfAborted();
+ }
+
+ if (!managed.client.isAlive()) {
+ await stopClientBestEffort(managed.client);
+ this.clients.delete(key);
+ return this.getClient(root, server, signal);
+ }
+
+ managed.refCount++;
+ managed.lastUsedAt = this.now();
+ return managed.client;
+ }
+
+ const client = this.clientFactory(root, server);
+ const initStartedAt = this.now();
+ const initPromise = (async () => {
+ await client.start();
+ await client.initialize();
+ })();
+
+ const newManaged: ManagedClient = {
+ client,
+ refCount: 0,
+ pendingWaiters: 1,
+ lastUsedAt: initStartedAt,
+ initPromise,
+ isInitializing: true,
+ initializingSince: initStartedAt,
+ };
+ this.clients.set(key, newManaged);
+
+ try {
+ await awaitWithSignal(initPromise, signal);
+ } catch (err) {
+ newManaged.pendingWaiters--;
+ if (this.clients.get(key) === newManaged) {
+ this.clients.delete(key);
+ }
+ await stopClientBestEffort(client);
+ throw err;
+ }
+
+ newManaged.pendingWaiters--;
+ newManaged.isInitializing = false;
+ newManaged.initializingSince = null;
+ newManaged.initPromise = null;
+
+ if (signal?.aborted) {
+ await this.tryDeleteIfOrphaned(key, newManaged);
+ signal.throwIfAborted();
+ }
+
+ newManaged.refCount++;
+ newManaged.lastUsedAt = this.now();
+ return client;
+ }
+
+ releaseClient(root: string, serverId: string): void {
+ const key = this.getKey(root, serverId);
+ const managed = this.clients.get(key);
+ if (managed && managed.refCount > 0) {
+ managed.refCount--;
+ managed.lastUsedAt = this.now();
+ }
+ }
+
+ invalidateClient(root: string, serverId: string, client?: LspClient): void {
+ const key = this.getKey(root, serverId);
+ const managed = this.clients.get(key);
+ if (!managed) return;
+ if (client && managed.client !== client) return;
+ this.clients.delete(key);
+ void stopClientBestEffort(managed.client);
+ }
+
+ warmupClient(root: string, server: ResolvedServer): void {
+ if (this.disposed) return;
+ const key = this.getKey(root, server.id);
+ if (this.clients.has(key)) return;
+
+ const client = this.clientFactory(root, server);
+ const initStartedAt = this.now();
+ const initPromise = (async () => {
+ await client.start();
+ await client.initialize();
+ })();
+
+ const managed: ManagedClient = {
+ client,
+ refCount: 0,
+ pendingWaiters: 0,
+ lastUsedAt: initStartedAt,
+ initPromise,
+ isInitializing: true,
+ initializingSince: initStartedAt,
+ };
+ this.clients.set(key, managed);
+
+ initPromise.then(
+ () => {
+ managed.isInitializing = false;
+ managed.initializingSince = null;
+ managed.initPromise = null;
+ managed.lastUsedAt = this.now();
+ },
+ () => {
+ if (this.clients.get(key) === managed) {
+ this.clients.delete(key);
+ }
+ void stopClientBestEffort(client);
+ },
+ );
+ }
+
+ isServerInitializing(root: string, serverId: string): boolean {
+ const managed = this.clients.get(this.getKey(root, serverId));
+ return managed?.isInitializing ?? false;
+ }
+
+ getSnapshot(): ClientSnapshot[] {
+ const snapshots: ClientSnapshot[] = [];
+ for (const [key, managed] of this.clients) {
+ const [root, serverId] = key.split("::") as [string, string];
+ snapshots.push({
+ root,
+ serverId,
+ refCount: managed.refCount,
+ pendingWaiters: managed.pendingWaiters,
+ lastUsedAt: managed.lastUsedAt,
+ isInitializing: managed.isInitializing,
+ alive: managed.client.isAlive(),
+ command: managed.client.command(),
+ });
+ }
+ return snapshots;
+ }
+
+ hasClient(root: string, serverId: string): boolean {
+ return this.clients.has(this.getKey(root, serverId));
+ }
+
+ clientCount(): number {
+ return this.clients.size;
+ }
+
+ async stopAll(): Promise<void> {
+ this.disposed = true;
+
+ if (this.reaperHandle) {
+ clearInterval(this.reaperHandle);
+ this.reaperHandle = null;
+ }
+
+ if (this.signalDisposer) {
+ this.signalDisposer();
+ this.signalDisposer = null;
+ }
+
+ const stopPromises: Promise<void>[] = [];
+ for (const managed of this.clients.values()) {
+ stopPromises.push(stopClientBestEffort(managed.client));
+ }
+ this.clients.clear();
+ await Promise.allSettled(stopPromises);
+ }
+}
+
+let _defaultInstance: LspManager | null = null;
+
+export function getLspManager(): LspManager {
+ if (!_defaultInstance) {
+ _defaultInstance = new LspManager();
+ }
+ return _defaultInstance;
+}
+
+export async function disposeDefaultLspManager(): Promise<void> {
+ if (_defaultInstance) {
+ const m = _defaultInstance;
+ _defaultInstance = null;
+ await m.stopAll();
+ }
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/process-signal-cleanup.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/process-signal-cleanup.ts
new file mode 100644
index 00000000..9ab3a4ee
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/process-signal-cleanup.ts
@@ -0,0 +1,21 @@
+import { reportBestEffortCleanupError } from "./cleanup-errors.js";
+
+export function installProcessSignalCleanup(cleanup: () => Promise<void>): () => void {
+ const signals: readonly NodeJS.Signals[] =
+ process.platform === "win32" ? ["SIGINT", "SIGTERM", "SIGBREAK"] : ["SIGINT", "SIGTERM"];
+ const handler = () => {
+ void cleanup().catch((error) => {
+ reportBestEffortCleanupError("signal cleanup", error);
+ });
+ };
+
+ for (const signal of signals) {
+ process.on(signal, handler);
+ }
+
+ return () => {
+ for (const signal of signals) {
+ process.removeListener(signal, handler);
+ }
+ };
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/process.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/process.ts
new file mode 100644
index 00000000..e059b141
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/process.ts
@@ -0,0 +1,202 @@
+import { type ChildProcess, spawn, spawnSync } from "node:child_process";
+import { existsSync, statSync } from "node:fs";
+import { delimiter, join } from "node:path";
+
+import { reportBestEffortCleanupError } from "./cleanup-errors.js";
+import { LspInvalidPathError, LspProcessSpawnError } from "./errors.js";
+
+export interface SpawnedProcess {
+ stdin: NodeJS.WritableStream;
+ stdout: NodeJS.ReadableStream;
+ stderr: NodeJS.ReadableStream;
+ pid: number | undefined;
+ exitCode: number | null;
+ exited: Promise<number>;
+ kill(signal?: NodeJS.Signals): void;
+ killed: boolean;
+}
+
+export interface SpawnOptions {
+ cwd: string;
+ env: Record<string, string | undefined>;
+}
+
+export interface PreparedSpawnCommand {
+ command: string;
+ args: string[];
+ shell: false;
+}
+
+function isMissingProcessError(error: unknown): boolean {
+ if (!(error instanceof Error) || !("code" in error)) return false;
+ return error.code === "ESRCH";
+}
+
+function reportKillError(context: string, error: unknown): void {
+ if (!isMissingProcessError(error)) {
+ reportBestEffortCleanupError(context, error);
+ }
+}
+
+export function validateCwd(cwd: string): { valid: boolean; error?: string } {
+ try {
+ if (!existsSync(cwd)) {
+ return { valid: false, error: `Working directory does not exist: ${cwd}` };
+ }
+ const stats = statSync(cwd);
+ if (!stats.isDirectory()) {
+ return { valid: false, error: `Path is not a directory: ${cwd}` };
+ }
+ return { valid: true };
+ } catch (err) {
+ return {
+ valid: false,
+ error: `Cannot access working directory: ${cwd} (${err instanceof Error ? err.message : String(err)})`,
+ };
+ }
+}
+
+function wrap(proc: ChildProcess): SpawnedProcess {
+ const exitedPromise = new Promise<number>((resolve) => {
+ proc.once("close", (code) => resolve(code ?? 0));
+ proc.once("error", () => resolve(1));
+ });
+
+ if (!proc.stdin || !proc.stdout || !proc.stderr) {
+ throw new LspProcessSpawnError("Spawned process is missing one of stdin/stdout/stderr pipes");
+ }
+
+ return {
+ stdin: proc.stdin,
+ stdout: proc.stdout,
+ stderr: proc.stderr,
+ get pid() {
+ return proc.pid ?? undefined;
+ },
+ get exitCode() {
+ return proc.exitCode;
+ },
+ get killed() {
+ return proc.killed;
+ },
+ exited: exitedPromise,
+ kill(signal?: NodeJS.Signals) {
+ killProcessTree(proc, signal ?? "SIGTERM");
+ },
+ };
+}
+
+function killProcessTree(proc: ChildProcess, signal: NodeJS.Signals): void {
+ if (process.platform === "win32" && proc.pid) {
+ const result = spawnSync("taskkill", ["/pid", String(proc.pid), "/f", "/t"], { stdio: "ignore" });
+ if (!result.error && result.status === 0) return;
+ if (result.error) reportKillError("windows process tree kill", result.error);
+ }
+
+ if (process.platform !== "win32" && proc.pid) {
+ try {
+ process.kill(-proc.pid, signal);
+ return;
+ } catch (error) {
+ reportKillError("process group kill", error);
+ }
+ }
+
+ try {
+ proc.kill(signal);
+ } catch (error) {
+ reportKillError("process kill", error);
+ }
+}
+
+function isWindowsShellShim(command: string): boolean {
+ const lowerCommand = command.toLowerCase();
+ return lowerCommand.endsWith(".cmd") || lowerCommand.endsWith(".bat");
+}
+
+function splitPath(pathValue: string, platform: NodeJS.Platform): string[] {
+ const separator = platform === "win32" ? ";" : delimiter;
+ return pathValue.split(separator).filter(Boolean);
+}
+
+function getWindowsPathExtensions(env: Record<string, string | undefined>): string[] {
+ const rawExtensions = env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD";
+ const extensions = rawExtensions
+ .split(";")
+ .map((extension) => extension.trim())
+ .filter(Boolean)
+ .map((extension) => (extension.startsWith(".") ? extension : `.${extension}`));
+ return [...new Set(["", ...extensions, ".exe", ".cmd", ".bat"])];
+}
+
+function resolveWindowsCommand(command: string, env: Record<string, string | undefined>): string {
+ const hasPathSeparator = command.includes("/") || command.includes("\\");
+ const pathValue = env["PATH"] ?? env["Path"] ?? "";
+ const baseDirectories = hasPathSeparator ? [""] : splitPath(pathValue, "win32");
+ const extensions = getWindowsPathExtensions(env);
+
+ for (const baseDirectory of baseDirectories) {
+ for (const extension of extensions) {
+ const candidate = baseDirectory ? join(baseDirectory, `${command}${extension}`) : `${command}${extension}`;
+ if (existsSync(candidate)) return candidate;
+ }
+ }
+
+ return command;
+}
+
+export function createSpawnCommand(
+ command: string[],
+ platform: NodeJS.Platform = process.platform,
+ commandProcessor: string = process.env["ComSpec"] ?? "cmd.exe",
+ env: Record<string, string | undefined> = process.env,
+): PreparedSpawnCommand {
+ const [cmd, ...args] = command;
+ if (!cmd) {
+ throw new LspProcessSpawnError("[lsp] empty command");
+ }
+
+ if (platform !== "win32") {
+ return { command: cmd, args, shell: false };
+ }
+
+ const resolvedCommand = resolveWindowsCommand(cmd, env);
+ if (!isWindowsShellShim(resolvedCommand)) {
+ return { command: resolvedCommand, args, shell: false };
+ }
+
+ return {
+ command: commandProcessor,
+ args: ["/d", "/s", "/c", resolvedCommand, ...args],
+ shell: false,
+ };
+}
+
+export function spawnProcess(command: string[], options: SpawnOptions): SpawnedProcess {
+ const cwdValidation = validateCwd(options.cwd);
+ if (!cwdValidation.valid) {
+ throw new LspInvalidPathError(`[lsp] ${cwdValidation.error}`);
+ }
+
+ const [cmd] = command;
+ if (!cmd) {
+ throw new LspProcessSpawnError("[lsp] empty command");
+ }
+
+ const preparedCommand = createSpawnCommand(
+ command,
+ process.platform,
+ process.env["ComSpec"] ?? "cmd.exe",
+ options.env,
+ );
+ const proc = spawn(preparedCommand.command, preparedCommand.args, {
+ cwd: options.cwd,
+ env: options.env,
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ shell: preparedCommand.shell,
+ detached: process.platform !== "win32",
+ });
+
+ return wrap(proc);
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-definitions.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-definitions.ts
new file mode 100644
index 00000000..b8e72864
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-definitions.ts
@@ -0,0 +1,163 @@
+import type { LspServerConfig } from "./types.js";
+
+export const LSP_INSTALL_HINTS: Record<string, string> = {
+ typescript: "npm install -g typescript-language-server typescript",
+ deno: "Install Deno from https://deno.land",
+ vue: "npm install -g @vue/language-server",
+ eslint: "npm install -g vscode-langservers-extracted",
+ oxlint: "npm install -g oxlint",
+ biome: "npm install -g @biomejs/biome",
+ gopls: "go install golang.org/x/tools/gopls@latest",
+ "ruby-lsp": "gem install ruby-lsp",
+ basedpyright: "pip install basedpyright",
+ pyright: "pip install pyright",
+ ty: "pip install ty",
+ ruff: "pip install ruff",
+ "elixir-ls": "See https://github.com/elixir-lsp/elixir-ls",
+ zls: "See https://github.com/zigtools/zls",
+ csharp: "dotnet tool install -g csharp-ls",
+ fsharp: "dotnet tool install -g fsautocomplete",
+ "sourcekit-lsp": "Included with Xcode or Swift toolchain",
+ rust:
+ "Install rust-analyzer and ensure it is in PATH. If using rustup: rustup component add rust-analyzer. " +
+ "If rust-analyzer exits while loading rust-src: rustup component remove rust-src && rustup component add rust-src.",
+ clangd: "See https://clangd.llvm.org/installation",
+ svelte: "npm install -g svelte-language-server",
+ astro: "npm install -g @astrojs/language-server",
+ "bash-ls": "npm install -g bash-language-server",
+ jdtls: "See https://github.com/eclipse-jdtls/eclipse.jdt.ls",
+ "yaml-ls": "npm install -g yaml-language-server",
+ "lua-ls": "See https://github.com/LuaLS/lua-language-server",
+ php: "npm install -g intelephense",
+ dart: "Included with Dart SDK",
+ "terraform-ls": "See https://github.com/hashicorp/terraform-ls",
+ terraform: "See https://github.com/hashicorp/terraform-ls",
+ prisma: "npm install -g prisma",
+ "ocaml-lsp": "opam install ocaml-lsp-server",
+ texlab: "See https://github.com/latex-lsp/texlab",
+ dockerfile: "npm install -g dockerfile-language-server-nodejs",
+ gleam: "See https://gleam.run/getting-started/installing/",
+ "clojure-lsp": "See https://clojure-lsp.io/installation/",
+ nixd: "nix profile install nixpkgs#nixd",
+ tinymist: "See https://github.com/Myriad-Dreamin/tinymist",
+ "haskell-language-server": "ghcup install hls",
+ bash: "npm install -g bash-language-server",
+ "kotlin-ls": "See https://github.com/Kotlin/kotlin-lsp",
+};
+
+export const BUILTIN_SERVERS: Record<string, Omit<LspServerConfig, "id">> = {
+ typescript: {
+ command: ["typescript-language-server", "--stdio"],
+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],
+ },
+ deno: { command: ["deno", "lsp"], extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"] },
+ vue: { command: ["vue-language-server", "--stdio"], extensions: [".vue"] },
+ eslint: {
+ command: ["vscode-eslint-language-server", "--stdio"],
+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".vue"],
+ },
+ oxlint: {
+ command: ["oxlint", "--lsp"],
+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".vue", ".astro", ".svelte"],
+ },
+ biome: {
+ command: ["biome", "lsp-proxy", "--stdio"],
+ extensions: [
+ ".ts",
+ ".tsx",
+ ".js",
+ ".jsx",
+ ".mjs",
+ ".cjs",
+ ".mts",
+ ".cts",
+ ".json",
+ ".jsonc",
+ ".vue",
+ ".astro",
+ ".svelte",
+ ".css",
+ ".graphql",
+ ".gql",
+ ".html",
+ ],
+ },
+ gopls: { command: ["gopls"], extensions: [".go"] },
+ "ruby-lsp": {
+ command: ["rubocop", "--lsp"],
+ extensions: [".rb", ".rake", ".gemspec", ".ru"],
+ },
+ basedpyright: {
+ command: ["basedpyright-langserver", "--stdio"],
+ extensions: [".py", ".pyi"],
+ },
+ pyright: { command: ["pyright-langserver", "--stdio"], extensions: [".py", ".pyi"] },
+ ty: { command: ["ty", "server"], extensions: [".py", ".pyi"] },
+ ruff: { command: ["ruff", "server"], extensions: [".py", ".pyi"] },
+ "elixir-ls": { command: ["elixir-ls"], extensions: [".ex", ".exs"] },
+ zls: { command: ["zls"], extensions: [".zig", ".zon"] },
+ csharp: { command: ["csharp-ls"], extensions: [".cs"] },
+ fsharp: { command: ["fsautocomplete"], extensions: [".fs", ".fsi", ".fsx", ".fsscript"] },
+ "sourcekit-lsp": { command: ["sourcekit-lsp"], extensions: [".swift", ".objc", ".objcpp"] },
+ rust: { command: ["rust-analyzer"], extensions: [".rs"] },
+ clangd: {
+ command: ["clangd", "--background-index", "--clang-tidy"],
+ extensions: [".c", ".cpp", ".cc", ".cxx", ".c++", ".h", ".hpp", ".hh", ".hxx", ".h++"],
+ },
+ svelte: { command: ["svelteserver", "--stdio"], extensions: [".svelte"] },
+ astro: { command: ["astro-ls", "--stdio"], extensions: [".astro"] },
+ bash: {
+ command: ["bash-language-server", "start"],
+ extensions: [".sh", ".bash", ".zsh", ".ksh"],
+ },
+ "bash-ls": {
+ command: ["bash-language-server", "start"],
+ extensions: [".sh", ".bash", ".zsh", ".ksh"],
+ },
+ jdtls: { command: ["jdtls"], extensions: [".java"] },
+ "yaml-ls": { command: ["yaml-language-server", "--stdio"], extensions: [".yaml", ".yml"] },
+ "lua-ls": { command: ["lua-language-server"], extensions: [".lua"] },
+ php: { command: ["intelephense", "--stdio"], extensions: [".php"] },
+ dart: { command: ["dart", "language-server", "--lsp"], extensions: [".dart"] },
+ terraform: { command: ["terraform-ls", "serve"], extensions: [".tf", ".tfvars"] },
+ "terraform-ls": { command: ["terraform-ls", "serve"], extensions: [".tf", ".tfvars"] },
+ prisma: { command: ["prisma", "language-server"], extensions: [".prisma"] },
+ "ocaml-lsp": { command: ["ocamllsp"], extensions: [".ml", ".mli"] },
+ texlab: { command: ["texlab"], extensions: [".tex", ".bib"] },
+ dockerfile: { command: ["docker-langserver", "--stdio"], extensions: [".dockerfile"] },
+ gleam: { command: ["gleam", "lsp"], extensions: [".gleam"] },
+ "clojure-lsp": {
+ command: ["clojure-lsp", "listen"],
+ extensions: [".clj", ".cljs", ".cljc", ".edn"],
+ },
+ nixd: { command: ["nixd"], extensions: [".nix"] },
+ tinymist: { command: ["tinymist"], extensions: [".typ", ".typc"] },
+ "haskell-language-server": {
+ command: ["haskell-language-server-wrapper", "--lsp"],
+ extensions: [".hs", ".lhs"],
+ },
+ "kotlin-ls": { command: ["kotlin-lsp"], extensions: [".kt", ".kts"] },
+};
+
+export const AUTO_INSTALLABLE_SERVERS: Record<string, string[]> = {
+ typescript: ["npm", "install", "-g", "typescript-language-server", "typescript"],
+ vue: ["npm", "install", "-g", "@vue/language-server"],
+ eslint: ["npm", "install", "-g", "vscode-langservers-extracted"],
+ oxlint: ["npm", "install", "-g", "oxlint"],
+ biome: ["npm", "install", "-g", "@biomejs/biome"],
+ svelte: ["npm", "install", "-g", "svelte-language-server"],
+ astro: ["npm", "install", "-g", "@astrojs/language-server"],
+ "bash-ls": ["npm", "install", "-g", "bash-language-server"],
+ bash: ["npm", "install", "-g", "bash-language-server"],
+ "yaml-ls": ["npm", "install", "-g", "yaml-language-server"],
+ php: ["npm", "install", "-g", "intelephense"],
+ prisma: ["npm", "install", "-g", "prisma"],
+ dockerfile: ["npm", "install", "-g", "dockerfile-language-server-nodejs"],
+ gopls: ["go", "install", "golang.org/x/tools/gopls@latest"],
+ pyright: ["pip", "install", "pyright"],
+ basedpyright: ["pip", "install", "basedpyright"],
+ ruff: ["pip", "install", "ruff"],
+ ty: ["pip", "install", "ty"],
+ "ruby-lsp": ["gem", "install", "ruby-lsp"],
+ "ocaml-lsp": ["opam", "install", "ocaml-lsp-server"],
+};
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-installation.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-installation.ts
new file mode 100644
index 00000000..622a174d
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-installation.ts
@@ -0,0 +1,57 @@
+import { existsSync } from "node:fs";
+import { delimiter, join } from "node:path";
+
+export function getAdditionalPathBases(workingDirectory: string): string[] {
+ return [join(workingDirectory, "node_modules", ".bin")];
+}
+
+export function isServerInstalled(command: string[]): boolean {
+ if (command.length === 0) return false;
+
+ const [cmd] = command;
+ if (!cmd) return false;
+
+ if (cmd.includes("/") || cmd.includes("\\")) {
+ if (existsSync(cmd)) return true;
+ }
+
+ const isWindows = process.platform === "win32";
+
+ let exts = [""];
+ if (isWindows) {
+ const pathExt = process.env["PATHEXT"] ?? "";
+ if (pathExt) {
+ const systemExts = pathExt.split(";").filter(Boolean);
+ exts = [...new Set([...exts, ...systemExts, ".exe", ".cmd", ".bat", ".ps1"])];
+ } else {
+ exts = ["", ".exe", ".cmd", ".bat", ".ps1"];
+ }
+ }
+
+ let pathEnv = process.env["PATH"] ?? "";
+ if (isWindows && !pathEnv) {
+ pathEnv = process.env["Path"] ?? "";
+ }
+
+ const paths = pathEnv.split(delimiter);
+
+ for (const p of paths) {
+ for (const suffix of exts) {
+ if (existsSync(join(p, cmd + suffix))) {
+ return true;
+ }
+ }
+ }
+
+ for (const base of getAdditionalPathBases(process.cwd())) {
+ for (const suffix of exts) {
+ if (existsSync(join(base, cmd + suffix))) {
+ return true;
+ }
+ }
+ }
+
+ if (cmd === "node") return true;
+
+ return false;
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-resolution.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-resolution.ts
new file mode 100644
index 00000000..e08478c9
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/server-resolution.ts
@@ -0,0 +1,104 @@
+import { getDisabledServerIds, getMergedServers } from "./config-loader.js";
+import { BUILTIN_SERVERS, LSP_INSTALL_HINTS } from "./server-definitions.js";
+import { isServerInstalled } from "./server-installation.js";
+import type { ServerLookupResult } from "./types.js";
+
+export function findServerForExtension(ext: string): ServerLookupResult {
+ const servers = getMergedServers();
+
+ for (const server of servers) {
+ if (server.extensions.includes(ext) && isServerInstalled(server.command)) {
+ const resolvedServer = {
+ id: server.id,
+ command: server.command,
+ extensions: server.extensions,
+ priority: server.priority,
+ };
+ if (server.env !== undefined) {
+ return {
+ status: "found",
+ server: {
+ ...resolvedServer,
+ env: server.env,
+ ...(server.initialization === undefined ? {} : { initialization: server.initialization }),
+ },
+ };
+ }
+ return {
+ status: "found",
+ server: {
+ ...resolvedServer,
+ ...(server.initialization === undefined ? {} : { initialization: server.initialization }),
+ },
+ };
+ }
+ }
+
+ for (const server of servers) {
+ if (server.extensions.includes(ext)) {
+ const installHint =
+ LSP_INSTALL_HINTS[server.id] ?? `Install '${server.command[0]}' and ensure it's in your PATH`;
+ return {
+ status: "not_installed",
+ server: {
+ id: server.id,
+ command: server.command,
+ extensions: server.extensions,
+ },
+ installHint,
+ };
+ }
+ }
+
+ const availableServers = [...new Set(servers.map((s) => s.id))];
+ return {
+ status: "not_configured",
+ extension: ext,
+ availableServers,
+ };
+}
+
+export interface ServerStatus {
+ id: string;
+ installed: boolean;
+ extensions: string[];
+ disabled: boolean;
+ source: string;
+ priority: number;
+}
+
+export function getAllServers(): ServerStatus[] {
+ const servers = getMergedServers();
+ const disabled = getDisabledServerIds();
+
+ const result: ServerStatus[] = [];
+ const seen = new Set<string>();
+
+ for (const server of servers) {
+ if (seen.has(server.id)) continue;
+ result.push({
+ id: server.id,
+ installed: isServerInstalled(server.command),
+ extensions: server.extensions,
+ disabled: false,
+ source: server.source,
+ priority: server.priority,
+ });
+ seen.add(server.id);
+ }
+
+ for (const id of disabled) {
+ if (seen.has(id)) continue;
+ const builtin = BUILTIN_SERVERS[id];
+ result.push({
+ id,
+ installed: builtin ? isServerInstalled(builtin.command) : false,
+ extensions: builtin?.extensions ?? [],
+ disabled: true,
+ source: "disabled",
+ priority: 0,
+ });
+ }
+
+ return result;
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/transport.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/transport.ts
new file mode 100644
index 00000000..49ecf7ea
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/transport.ts
@@ -0,0 +1,285 @@
+import { delimiter } from "node:path";
+
+import { reportBestEffortCleanupError } from "./cleanup-errors.js";
+import { REQUEST_TIMEOUT_MS, STOP_HARD_KILL_TIMEOUT_MS, STOP_SIGKILL_GRACE_MS } from "./constants.js";
+import { LspConnectionClosedError, LspProcessExitedError, LspRequestTimeoutError } from "./errors.js";
+import { JsonRpcConnection } from "./json-rpc-connection.js";
+import { type SpawnedProcess, spawnProcess } from "./process.js";
+import { getAdditionalPathBases } from "./server-installation.js";
+import type { Diagnostic, ResolvedServer } from "./types.js";
+
+interface ConfigurationItem {
+ section?: string;
+}
+
+interface DiagnosticsParams {
+ uri: string;
+ diagnostics: Diagnostic[];
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function parseConfigurationItems(params: unknown): ConfigurationItem[] {
+ if (!isRecord(params) || !Array.isArray(params["items"])) return [];
+ const items: ConfigurationItem[] = [];
+ for (const item of params["items"]) {
+ if (!isRecord(item)) continue;
+ const section = item["section"];
+ items.push(section === undefined || typeof section !== "string" ? {} : { section });
+ }
+ return items;
+}
+
+function parseDiagnosticsParams(params: unknown): DiagnosticsParams | null {
+ if (!isRecord(params) || typeof params["uri"] !== "string") return null;
+ const diagnostics = Array.isArray(params["diagnostics"]) ? params["diagnostics"].filter(isDiagnostic) : [];
+ return { uri: params["uri"], diagnostics };
+}
+
+export class LspClientTransport {
+ protected proc: SpawnedProcess | null = null;
+ protected connection: JsonRpcConnection | null = null;
+ protected readonly stderrBuffer: string[] = [];
+ protected processExited = false;
+ protected readonly diagnosticsStore = new Map<string, Diagnostic[]>();
+
+ constructor(
+ protected readonly root: string,
+ protected readonly server: ResolvedServer,
+ ) {}
+
+ pid(): number | undefined {
+ return this.proc?.pid;
+ }
+
+ command(): string[] {
+ return [...this.server.command];
+ }
+
+ async start(): Promise<void> {
+ const env: Record<string, string | undefined> = {
+ ...process.env,
+ ...this.server.env,
+ };
+ const pathValue = process.platform === "win32" ? (env["PATH"] ?? env["Path"] ?? "") : (env["PATH"] ?? "");
+ const spawnPath = [pathValue, ...getAdditionalPathBases(this.root)].filter(Boolean).join(delimiter);
+ if (process.platform === "win32" && env["Path"] !== undefined) {
+ env["Path"] = spawnPath;
+ }
+ env["PATH"] = spawnPath;
+
+ this.proc = spawnProcess(this.server.command, {
+ cwd: this.root,
+ env,
+ });
+ this.startStderrReading();
+
+ await new Promise<void>((resolve) => setTimeout(resolve, 100));
+
+ if (this.proc.exitCode !== null) {
+ const stderr = this.stderrBuffer.join("\n");
+ throw new LspProcessExitedError(this.server.id, this.root, this.proc.exitCode, stderr.slice(-2000));
+ }
+
+ this.connection = new JsonRpcConnection(this.proc.stdout, this.proc.stdin);
+
+ this.connection.onNotification("textDocument/publishDiagnostics", (params) => {
+ const diagnosticsParams = parseDiagnosticsParams(params);
+ if (diagnosticsParams?.uri) {
+ this.diagnosticsStore.set(diagnosticsParams.uri, diagnosticsParams.diagnostics);
+ }
+ });
+
+ this.connection.onRequest("workspace/configuration", (params) => {
+ const items = parseConfigurationItems(params);
+ return items.map((item) => {
+ if (item.section === "json") return { validate: { enable: true } };
+ return {};
+ });
+ });
+
+ this.connection.onRequest("client/registerCapability", () => null);
+ this.connection.onRequest("window/workDoneProgress/create", () => null);
+
+ this.connection.onClose(() => {
+ this.processExited = true;
+ });
+
+ this.connection.onError((error) => {
+ reportBestEffortCleanupError("connection error notification", error);
+ });
+
+ this.connection.listen();
+ }
+
+ protected startStderrReading(): void {
+ if (!this.proc) return;
+ this.proc.stderr.setEncoding("utf-8");
+ this.proc.stderr.on("data", (chunk: string) => {
+ this.stderrBuffer.push(chunk);
+ if (this.stderrBuffer.length > 100) {
+ this.stderrBuffer.shift();
+ }
+ });
+ }
+
+ private isConnectionClosedError(error: unknown): error is Error {
+ if (!(error instanceof Error)) {
+ return false;
+ }
+ const code = "code" in error && typeof error.code === "string" ? error.code : undefined;
+ return (
+ code === "ERR_STREAM_DESTROYED" ||
+ /connection closed|connection is disposed|stream was destroyed/i.test(error.message)
+ );
+ }
+
+ protected sendRequest<T>(method: string): Promise<T>;
+ protected sendRequest<T>(method: string, params: unknown): Promise<T>;
+ protected async sendRequest<T>(method: string, ...args: [] | [unknown]): Promise<T> {
+ if (!this.connection) throw new Error("LSP client not started");
+
+ if (this.processExited || (this.proc && this.proc.exitCode !== null)) {
+ const stderrTail = this.stderrBuffer.slice(-10).join("\n");
+ throw new LspProcessExitedError(
+ this.server.id,
+ this.root,
+ this.proc?.exitCode ?? null,
+ stderrTail || undefined,
+ );
+ }
+
+ let timeoutHandle: NodeJS.Timeout | null = null;
+ const timeoutPromise = new Promise<never>((_, reject) => {
+ timeoutHandle = setTimeout(() => {
+ const stderrTail = this.stderrBuffer.slice(-5).join("\n");
+ reject(new LspRequestTimeoutError(method, stderrTail || undefined));
+ }, REQUEST_TIMEOUT_MS);
+ });
+
+ try {
+ const requestPromise =
+ args.length === 0
+ ? this.connection.sendRequest<T>(method)
+ : this.connection.sendRequest<T>(method, args[0]);
+ const result = await Promise.race([requestPromise, timeoutPromise]);
+ if (timeoutHandle !== null) clearTimeout(timeoutHandle);
+ return result;
+ } catch (error) {
+ if (timeoutHandle !== null) clearTimeout(timeoutHandle);
+ if (this.processExited || (this.proc && this.proc.exitCode !== null)) {
+ throw new LspProcessExitedError(
+ this.server.id,
+ this.root,
+ this.proc?.exitCode ?? null,
+ this.stderrBuffer.slice(-10).join("\n") || undefined,
+ );
+ }
+ if (this.isConnectionClosedError(error)) {
+ throw new LspConnectionClosedError(this.server.id, this.root, error.message);
+ }
+ throw error;
+ }
+ }
+
+ protected sendNotification(method: string): Promise<void>;
+ protected sendNotification(method: string, params: unknown): Promise<void>;
+ protected async sendNotification(method: string, ...args: [] | [unknown]): Promise<void> {
+ if (!this.connection) return;
+ if (this.processExited || (this.proc && this.proc.exitCode !== null)) return;
+ try {
+ if (args.length === 0) {
+ await this.connection.sendNotification(method);
+ } else {
+ await this.connection.sendNotification(method, args[0]);
+ }
+ } catch (error) {
+ if (this.isConnectionClosedError(error)) {
+ throw new LspConnectionClosedError(this.server.id, this.root, error.message);
+ }
+ throw error;
+ }
+ }
+
+ isAlive(): boolean {
+ return this.proc !== null && !this.processExited && this.proc.exitCode === null;
+ }
+
+ async stop(): Promise<void> {
+ if (this.connection) {
+ try {
+ await this.sendRequest<null>("shutdown");
+ } catch (error) {
+ reportBestEffortCleanupError("shutdown request", error);
+ }
+ try {
+ await this.sendNotification("exit");
+ } catch (error) {
+ reportBestEffortCleanupError("exit notification", error);
+ }
+ try {
+ this.connection.dispose();
+ } catch (error) {
+ reportBestEffortCleanupError("connection dispose", error);
+ }
+ this.connection = null;
+ }
+
+ const proc = this.proc;
+ if (proc) {
+ this.proc = null;
+ let exitedBeforeTimeout = false;
+ try {
+ proc.kill();
+ let timeoutId: NodeJS.Timeout | undefined;
+ const timeoutPromise = new Promise<void>((resolve) => {
+ timeoutId = setTimeout(resolve, STOP_HARD_KILL_TIMEOUT_MS);
+ });
+ await Promise.race([
+ proc.exited
+ .then(() => {
+ exitedBeforeTimeout = true;
+ })
+ .finally(() => {
+ if (timeoutId) clearTimeout(timeoutId);
+ }),
+ timeoutPromise,
+ ]);
+ if (!exitedBeforeTimeout) {
+ try {
+ proc.kill("SIGKILL");
+ await Promise.race([
+ proc.exited,
+ new Promise<void>((resolve) => setTimeout(resolve, STOP_SIGKILL_GRACE_MS)),
+ ]);
+ } catch (error) {
+ reportBestEffortCleanupError("hard process kill", error);
+ }
+ }
+ } catch (error) {
+ reportBestEffortCleanupError("process stop", error);
+ }
+ }
+
+ this.processExited = true;
+ this.diagnosticsStore.clear();
+ }
+
+ getStoredDiagnostics(uri: string): Diagnostic[] {
+ return this.diagnosticsStore.get(uri) ?? [];
+ }
+}
+
+function isDiagnostic(value: unknown): value is Diagnostic {
+ return isRecord(value) && isRange(value["range"]) && typeof value["message"] === "string";
+}
+
+function isRange(value: unknown): value is Diagnostic["range"] {
+ return isRecord(value) && isPosition(value["start"]) && isPosition(value["end"]);
+}
+
+function isPosition(value: unknown): value is Diagnostic["range"]["start"] {
+ return isRecord(value) && typeof value["line"] === "number" && typeof value["character"] === "number";
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/types.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/types.ts
new file mode 100644
index 00000000..9fe67afe
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/types.ts
@@ -0,0 +1,126 @@
+export interface LspServerConfig {
+ id: string;
+ command: string[];
+ extensions: string[];
+ disabled?: boolean;
+ env?: Record<string, string>;
+ initialization?: Record<string, unknown>;
+}
+
+export interface ResolvedServer {
+ id: string;
+ command: string[];
+ extensions: string[];
+ priority: number;
+ env?: Record<string, string>;
+ initialization?: Record<string, unknown>;
+}
+
+export interface ServerLookupInfo {
+ id: string;
+ command: string[];
+ extensions: string[];
+}
+
+export type ServerLookupResult =
+ | { status: "found"; server: ResolvedServer }
+ | { status: "not_configured"; extension: string; availableServers: string[] }
+ | { status: "not_installed"; server: ServerLookupInfo; installHint: string };
+
+export interface Position {
+ line: number;
+ character: number;
+}
+
+export interface Range {
+ start: Position;
+ end: Position;
+}
+
+export interface Location {
+ uri: string;
+ range: Range;
+}
+
+export interface LocationLink {
+ targetUri: string;
+ targetRange: Range;
+ targetSelectionRange: Range;
+ originSelectionRange?: Range;
+}
+
+export interface SymbolInfo {
+ name: string;
+ kind: number;
+ location: Location;
+ containerName?: string;
+}
+
+export interface DocumentSymbol {
+ name: string;
+ kind: number;
+ range: Range;
+ selectionRange: Range;
+ children?: DocumentSymbol[];
+}
+
+export interface Diagnostic {
+ range: Range;
+ severity?: number;
+ code?: string | number;
+ source?: string;
+ message: string;
+}
+
+export interface TextDocumentIdentifier {
+ uri: string;
+}
+
+export interface VersionedTextDocumentIdentifier extends TextDocumentIdentifier {
+ version: number | null;
+}
+
+export interface TextEdit {
+ range: Range;
+ newText: string;
+}
+
+export interface TextDocumentEdit {
+ textDocument: VersionedTextDocumentIdentifier;
+ edits: TextEdit[];
+}
+
+export interface CreateFile {
+ kind: "create";
+ uri: string;
+ options?: { overwrite?: boolean; ignoreIfExists?: boolean };
+}
+
+export interface RenameFile {
+ kind: "rename";
+ oldUri: string;
+ newUri: string;
+ options?: { overwrite?: boolean; ignoreIfExists?: boolean };
+}
+
+export interface DeleteFile {
+ kind: "delete";
+ uri: string;
+ options?: { recursive?: boolean; ignoreIfNotExists?: boolean };
+}
+
+export interface WorkspaceEdit {
+ changes?: { [uri: string]: TextEdit[] };
+ documentChanges?: (TextDocumentEdit | CreateFile | RenameFile | DeleteFile)[];
+}
+
+export interface PrepareRenameResult {
+ range: Range;
+ placeholder?: string;
+}
+
+export interface PrepareRenameDefaultBehavior {
+ defaultBehavior: boolean;
+}
+
+export type SeverityFilter = "error" | "warning" | "information" | "hint" | "all";
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/utils.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/utils.ts
new file mode 100644
index 00000000..94428b2e
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/utils.ts
@@ -0,0 +1,40 @@
+import { LspProcessExitedError } from "./errors.js";
+
+const RUST_SRC_REPAIR_MESSAGE = [
+ "rust-analyzer exited while loading Rust standard library sources.",
+ "",
+ "Repair rust-src for the active toolchain:",
+ " rustup component remove rust-src",
+ " rustup component add rust-src",
+];
+
+export function errorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+export function formatKnownLspStartupFailure(error: unknown): string | null {
+ if (!(error instanceof LspProcessExitedError)) return null;
+ if (error.serverId !== "rust") return null;
+
+ const details = error.stderrTail ?? error.message;
+ const lowerDetails = details.toLowerCase();
+ const isRustSrcFailure =
+ lowerDetails.includes("rust-src") &&
+ (lowerDetails.includes("failed to install component") ||
+ lowerDetails.includes("detected conflict") ||
+ lowerDetails.includes("can't load standard library") ||
+ lowerDetails.includes("try installing") ||
+ lowerDetails.includes("sysroot"));
+
+ if (!isRustSrcFailure) return null;
+
+ return [...RUST_SRC_REPAIR_MESSAGE, "", "Original stderr tail:", details].join("\n");
+}
+
+export function handleMissingDependencyError(error: unknown): string | null {
+ const knownStartupFailure = formatKnownLspStartupFailure(error);
+ if (knownStartupFailure) return knownStartupFailure;
+
+ const message = errorMessage(error);
+ return message.includes("NOT INSTALLED") || message.includes("No LSP server configured") ? message : null;
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/workspace-edit.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/workspace-edit.ts
new file mode 100644
index 00000000..fccf7bfb
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/lsp/workspace-edit.ts
@@ -0,0 +1,132 @@
+import { readFileSync, unlinkSync, writeFileSync } from "node:fs";
+
+import { uriToPath } from "./formatters.js";
+import type { TextEdit, WorkspaceEdit } from "./types.js";
+
+export interface ApplyResult {
+ success: boolean;
+ filesModified: string[];
+ totalEdits: number;
+ errors: string[];
+}
+
+interface FileApplyResult {
+ success: boolean;
+ editCount: number;
+ error?: string;
+}
+
+function applyTextEditsToFile(filePath: string, edits: TextEdit[]): FileApplyResult {
+ try {
+ const content = readFileSync(filePath, "utf-8");
+ const lines = content.split("\n");
+
+ const sortedEdits = [...edits].sort((a, b) => {
+ if (b.range.start.line !== a.range.start.line) {
+ return b.range.start.line - a.range.start.line;
+ }
+ return b.range.start.character - a.range.start.character;
+ });
+
+ for (const edit of sortedEdits) {
+ const startLine = edit.range.start.line;
+ const startChar = edit.range.start.character;
+ const endLine = edit.range.end.line;
+ const endChar = edit.range.end.character;
+
+ if (startLine === endLine) {
+ const line = lines[startLine] ?? "";
+ lines[startLine] = line.substring(0, startChar) + edit.newText + line.substring(endChar);
+ } else {
+ const firstLine = lines[startLine] ?? "";
+ const lastLine = lines[endLine] ?? "";
+ const newContent = firstLine.substring(0, startChar) + edit.newText + lastLine.substring(endChar);
+ lines.splice(startLine, endLine - startLine + 1, ...newContent.split("\n"));
+ }
+ }
+
+ writeFileSync(filePath, lines.join("\n"), "utf-8");
+ return { success: true, editCount: edits.length };
+ } catch (err) {
+ return {
+ success: false,
+ editCount: 0,
+ error: err instanceof Error ? err.message : String(err),
+ };
+ }
+}
+
+export function applyWorkspaceEdit(edit: WorkspaceEdit | null): ApplyResult {
+ if (!edit) {
+ return { success: false, filesModified: [], totalEdits: 0, errors: ["No edit provided"] };
+ }
+
+ const result: ApplyResult = { success: true, filesModified: [], totalEdits: 0, errors: [] };
+
+ if (edit.changes) {
+ for (const [uri, edits] of Object.entries(edit.changes)) {
+ const filePath = uriToPath(uri);
+ const applyResult = applyTextEditsToFile(filePath, edits);
+
+ if (applyResult.success) {
+ result.filesModified.push(filePath);
+ result.totalEdits += applyResult.editCount;
+ } else {
+ result.success = false;
+ result.errors.push(`${filePath}: ${applyResult.error}`);
+ }
+ }
+ }
+
+ if (edit.documentChanges) {
+ for (const change of edit.documentChanges) {
+ if (!("kind" in change)) {
+ const filePath = uriToPath(change.textDocument.uri);
+ const applyResult = applyTextEditsToFile(filePath, change.edits);
+
+ if (applyResult.success) {
+ result.filesModified.push(filePath);
+ result.totalEdits += applyResult.editCount;
+ } else {
+ result.success = false;
+ result.errors.push(`${filePath}: ${applyResult.error}`);
+ }
+ continue;
+ }
+
+ if (change.kind === "create") {
+ try {
+ const filePath = uriToPath(change.uri);
+ writeFileSync(filePath, "", "utf-8");
+ result.filesModified.push(filePath);
+ } catch (err) {
+ result.success = false;
+ result.errors.push(`Create ${change.uri}: ${String(err)}`);
+ }
+ } else if (change.kind === "rename") {
+ try {
+ const oldPath = uriToPath(change.oldUri);
+ const newPath = uriToPath(change.newUri);
+ const content = readFileSync(oldPath, "utf-8");
+ writeFileSync(newPath, content, "utf-8");
+ unlinkSync(oldPath);
+ result.filesModified.push(newPath);
+ } catch (err) {
+ result.success = false;
+ result.errors.push(`Rename ${change.oldUri}: ${String(err)}`);
+ }
+ } else if (change.kind === "delete") {
+ try {
+ const filePath = uriToPath(change.uri);
+ unlinkSync(filePath);
+ result.filesModified.push(filePath);
+ } catch (err) {
+ result.success = false;
+ result.errors.push(`Delete ${change.uri}: ${String(err)}`);
+ }
+ }
+ }
+ }
+
+ return result;
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/mcp-lifecycle-log.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/mcp-lifecycle-log.ts
new file mode 100644
index 00000000..54101b7b
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/mcp-lifecycle-log.ts
@@ -0,0 +1,36 @@
+import { appendFileSync, renameSync, statSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+type LogFieldValue = boolean | number | string | null;
+
+const LOG_FILE_NAME = "omo-codex-lsp-mcp.log";
+const MAX_LOG_BYTES = 5 * 1024 * 1024;
+
+export function mcpLifecycleLogPath(): string {
+ return join(tmpdir(), LOG_FILE_NAME);
+}
+
+export function writeMcpLifecycleLog(event: string, fields: Record<string, LogFieldValue> = {}): void {
+ const path = mcpLifecycleLogPath();
+ try {
+ rotateLogIfNeeded(path);
+ appendFileSync(
+ path,
+ `${JSON.stringify({ ts: new Date().toISOString(), event, pid: process.pid, ppid: process.ppid, ...fields })}\n`,
+ );
+ } catch (error) {
+ if (error instanceof Error) return;
+ return;
+ }
+}
+
+function rotateLogIfNeeded(path: string): void {
+ try {
+ if (statSync(path).size < MAX_LOG_BYTES) return;
+ renameSync(path, `${path}.1`);
+ } catch (error) {
+ if (error instanceof Error) return;
+ return;
+ }
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/mcp.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/mcp.ts
new file mode 100644
index 00000000..68fd9993
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/mcp.ts
@@ -0,0 +1,188 @@
+import { createInterface } from "node:readline";
+
+import { coerceToolArguments, executeLspTool, LSP_MCP_TOOLS, type TextContent } from "./tools.js";
+
+export type JsonRpcId = string | number | null;
+export type McpLifecycleLog = (event: string, fields?: Record<string, boolean | number | string | null>) => void;
+
+export interface McpToolDescriptor {
+ name: string;
+ title: string;
+ description: string;
+ inputSchema: unknown;
+}
+
+export interface JsonRpcError {
+ code: number;
+ message: string;
+ data?: unknown;
+}
+
+export interface JsonRpcResult {
+ capabilities?: Record<string, unknown>;
+ serverInfo?: Record<string, unknown>;
+ protocolVersion?: string;
+ tools?: McpToolDescriptor[];
+ content?: TextContent[];
+ isError?: boolean;
+ [key: string]: unknown;
+}
+
+export interface JsonRpcResponse {
+ jsonrpc: "2.0";
+ id: JsonRpcId;
+ result?: JsonRpcResult;
+ error?: JsonRpcError;
+}
+
+export interface McpStdioServerOptions {
+ readonly idleTimeoutMs?: number;
+ readonly onIdleTimeout?: () => void | Promise<void>;
+ readonly log?: McpLifecycleLog;
+}
+
+const SERVER_NAME = "lsp";
+const SERVER_VERSION = "0.1.0";
+const DEFAULT_IDLE_TIMEOUT_MS = 10 * 60_000;
+const noopLog: McpLifecycleLog = () => {};
+
+export async function handleLspMcpRequest(input: unknown): Promise<JsonRpcResponse | undefined> {
+ if (!isRecord(input)) {
+ return errorResponse(null, -32600, "Invalid Request");
+ }
+
+ const id = jsonRpcId(input["id"]);
+ const method = input["method"];
+ if (method === "notifications/initialized") return undefined;
+ if (method === "ping") return successResponse(id, {});
+ if (method === "initialize") {
+ const protocolVersion = requestedProtocolVersion(input["params"]);
+ return successResponse(id, {
+ capabilities: { tools: { listChanged: false } },
+ serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
+ protocolVersion,
+ });
+ }
+
+ if (method === "tools/list") {
+ return successResponse(id, { tools: LSP_MCP_TOOLS.map(describeTool) });
+ }
+
+ if (method === "tools/call") {
+ return handleToolCall(id, input["params"]);
+ }
+
+ return errorResponse(id, -32601, `Method not found: ${String(method)}`);
+}
+
+export async function runMcpStdioServer(
+ input: NodeJS.ReadableStream = process.stdin,
+ output: NodeJS.WritableStream = process.stdout,
+ options: McpStdioServerOptions = {},
+): Promise<void> {
+ const log = options.log ?? noopLog;
+ const idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
+ let idleTimer: NodeJS.Timeout | null = null;
+ let closed = false;
+
+ const clearIdleTimer = () => {
+ if (idleTimer === null) return;
+ clearTimeout(idleTimer);
+ idleTimer = null;
+ };
+ const armIdleTimer = () => {
+ clearIdleTimer();
+ if (idleTimeoutMs <= 0) return;
+ idleTimer = setTimeout(() => {
+ closed = true;
+ log("idle_timeout", { idle_timeout_ms: idleTimeoutMs });
+ void options.onIdleTimeout?.();
+ }, idleTimeoutMs);
+ idleTimer.unref();
+ };
+
+ log("stdio_started", { cwd: process.cwd(), idle_timeout_ms: idleTimeoutMs });
+ armIdleTimer();
+ const lines = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY });
+ try {
+ for await (const line of lines) {
+ if (closed) break;
+ armIdleTimer();
+ if (!line.trim()) continue;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(line);
+ } catch (error) {
+ log("parse_error", { message: messageFromError(error) });
+ output.write(`${JSON.stringify(errorResponse(null, -32700, "Parse error", messageFromError(error)))}\n`);
+ continue;
+ }
+
+ const id = isRecord(parsed) ? jsonRpcId(parsed["id"]) : null;
+ const method = isRecord(parsed) && typeof parsed["method"] === "string" ? parsed["method"] : null;
+ log("request", { id: id === null ? null : String(id), method });
+ const response = await handleLspMcpRequest(parsed);
+ if (response) {
+ output.write(`${JSON.stringify(response)}\n`);
+ log("response", { id: String(response.id), method, is_error: response.error !== undefined });
+ }
+ }
+ } finally {
+ clearIdleTimer();
+ log("stdio_stopped");
+ }
+}
+
+async function handleToolCall(id: JsonRpcId, params: unknown): Promise<JsonRpcResponse> {
+ if (!isRecord(params) || typeof params["name"] !== "string") {
+ return errorResponse(id, -32602, "tools/call requires params.name");
+ }
+
+ try {
+ const result = await executeLspTool(params["name"], coerceToolArguments(params["arguments"]));
+ return successResponse(id, {
+ content: result.content,
+ isError: result.isError ?? false,
+ details: result.details,
+ });
+ } catch (error) {
+ return successResponse(id, {
+ content: [{ type: "text", text: messageFromError(error) }],
+ isError: true,
+ });
+ }
+}
+
+function describeTool(tool: (typeof LSP_MCP_TOOLS)[number]): McpToolDescriptor {
+ return {
+ name: tool.name,
+ title: tool.title,
+ description: tool.description,
+ inputSchema: tool.inputSchema,
+ };
+}
+
+function successResponse(id: JsonRpcId, result: JsonRpcResult): JsonRpcResponse {
+ return { jsonrpc: "2.0", id, result };
+}
+
+function errorResponse(id: JsonRpcId, code: number, message: string, data?: unknown): JsonRpcResponse {
+ return { jsonrpc: "2.0", id, error: data === undefined ? { code, message } : { code, message, data } };
+}
+
+function requestedProtocolVersion(params: unknown): string {
+ if (!isRecord(params) || typeof params["protocolVersion"] !== "string") return "2024-11-05";
+ return params["protocolVersion"];
+}
+
+function jsonRpcId(value: unknown): JsonRpcId {
+ return typeof value === "string" || typeof value === "number" || value === null ? value : null;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function messageFromError(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/tools.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/tools.ts
new file mode 100644
index 00000000..87239239
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/src/tools.ts
@@ -0,0 +1,669 @@
+import { resolve } from "node:path";
+
+import { isDirectoryPath, type WithLspClientOptions, withLspClient } from "./lsp/client-wrapper.js";
+import { DEFAULT_MAX_DIAGNOSTICS, DEFAULT_MAX_REFERENCES, DEFAULT_MAX_SYMBOLS } from "./lsp/constants.js";
+import { aggregateDiagnosticsForDirectory } from "./lsp/directory-diagnostics.js";
+import {
+ filterDiagnosticsBySeverity,
+ formatApplyResult,
+ formatDiagnostic,
+ formatDocumentSymbol,
+ formatLocation,
+ formatPrepareRenameResult,
+ formatSymbolInfo,
+} from "./lsp/formatters.js";
+import { inferExtensionFromDirectory } from "./lsp/infer-extension.js";
+import { getLspManager } from "./lsp/manager.js";
+import { getAllServers } from "./lsp/server-resolution.js";
+import type {
+ Diagnostic,
+ DocumentSymbol,
+ Location,
+ LocationLink,
+ PrepareRenameDefaultBehavior,
+ PrepareRenameResult,
+ Range,
+ SeverityFilter,
+ SymbolInfo,
+ WorkspaceEdit,
+} from "./lsp/types.js";
+import { handleMissingDependencyError } from "./lsp/utils.js";
+import { type ApplyResult, applyWorkspaceEdit } from "./lsp/workspace-edit.js";
+
+export interface TextContent {
+ type: "text";
+ text: string;
+}
+
+export interface ToolExecutionResult {
+ content: TextContent[];
+ isError?: boolean;
+ details?: unknown;
+}
+
+export interface JsonSchema {
+ type: string;
+ description?: string;
+ properties?: Record<string, JsonSchema>;
+ required?: string[];
+ items?: JsonSchema;
+ enum?: string[];
+}
+
+export interface LspMcpTool {
+ name: string;
+ aliases?: string[];
+ title: string;
+ description: string;
+ inputSchema: JsonSchema;
+ execute(params: Record<string, unknown>, signal?: AbortSignal): Promise<ToolExecutionResult>;
+}
+
+export interface LspDiagnosticsDetails {
+ filePath: string;
+ severity: SeverityFilter;
+ mode: "file" | "directory";
+ diagnostics: Array<{ file: string; diagnostic: Diagnostic }>;
+ totalDiagnostics: number;
+ truncated: boolean;
+ error?: string;
+ errorKind?: "missing_dependency" | "no_files" | "invalid_path";
+}
+
+export interface LspGotoDefinitionDetails {
+ filePath: string;
+ line: number;
+ character: number;
+ locations: Array<Location | LocationLink>;
+ error?: string;
+ errorKind?: "missing_dependency";
+}
+
+export interface LspFindReferencesDetails {
+ filePath: string;
+ line: number;
+ character: number;
+ references: Location[];
+ totalReferences: number;
+ truncated: boolean;
+ error?: string;
+ errorKind?: "missing_dependency";
+}
+
+export interface LspSymbolsDetails {
+ filePath: string;
+ scope: "document" | "workspace";
+ query?: string;
+ symbols: Array<DocumentSymbol | SymbolInfo>;
+ totalSymbols: number;
+ truncated: boolean;
+ error?: string;
+ errorKind?: "missing_dependency" | "missing_query";
+}
+
+export interface LspPrepareRenameDetails {
+ filePath: string;
+ line: number;
+ character: number;
+ result: PrepareRenameResult | PrepareRenameDefaultBehavior | Range | null;
+ error?: string;
+ errorKind?: "missing_dependency";
+}
+
+export interface LspRenameDetails {
+ filePath: string;
+ line: number;
+ character: number;
+ newName: string;
+ apply: ApplyResult | null;
+ edit: WorkspaceEdit | null;
+ error?: string;
+ errorKind?: "missing_dependency";
+}
+
+const objectSchema = (properties: Record<string, JsonSchema>, required: string[] = []): JsonSchema => ({
+ type: "object",
+ properties,
+ required,
+});
+
+function text(text: string, details?: unknown, isError = false): ToolExecutionResult {
+ return { content: [{ type: "text", text }], details, isError };
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function requireString(params: Record<string, unknown>, key: string): string {
+ const value = params[key];
+ if (typeof value !== "string" || value.length === 0) {
+ throw new Error(`Missing required string parameter '${key}'`);
+ }
+ return value;
+}
+
+function optionalString(params: Record<string, unknown>, key: string): string | undefined {
+ const value = params[key];
+ return typeof value === "string" ? value : undefined;
+}
+
+function requireNumber(params: Record<string, unknown>, key: string): number {
+ const value = params[key];
+ if (typeof value !== "number" || !Number.isFinite(value)) {
+ throw new Error(`Missing required number parameter '${key}'`);
+ }
+ return value;
+}
+
+function optionalNumber(params: Record<string, unknown>, key: string): number | undefined {
+ const value = params[key];
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
+}
+
+function optionalBoolean(params: Record<string, unknown>, key: string): boolean | undefined {
+ const value = params[key];
+ return typeof value === "boolean" ? value : undefined;
+}
+
+function isSeverityFilter(value: unknown): value is SeverityFilter {
+ return value === "error" || value === "warning" || value === "information" || value === "hint" || value === "all";
+}
+
+function severityFilter(params: Record<string, unknown>): SeverityFilter {
+ const value = params["severity"];
+ if (isSeverityFilter(value)) return value;
+ return "all";
+}
+
+function clientOptions(signal: AbortSignal | undefined): WithLspClientOptions {
+ return signal === undefined ? {} : { signal };
+}
+
+function asDiagnosticArray(result: { items?: Diagnostic[] } | Diagnostic[] | null | undefined): Diagnostic[] {
+ if (!result) return [];
+ if (Array.isArray(result)) return result;
+ return result.items ?? [];
+}
+
+function isDocumentSymbol(symbol: DocumentSymbol | SymbolInfo): symbol is DocumentSymbol {
+ return "range" in symbol;
+}
+
+async function executeLspStatus(): Promise<ToolExecutionResult> {
+ const servers = getAllServers();
+ const snapshots = getLspManager().getSnapshot();
+ const installed = servers.filter((server) => server.installed && !server.disabled);
+ const configuredLines = servers.map((server) => {
+ const state = server.disabled ? "disabled" : server.installed ? "installed" : "missing";
+ return `- ${server.id}: ${state}; source=${server.source}; extensions=${server.extensions.join(", ")}`;
+ });
+ const activeLines = snapshots.map((snapshot) => {
+ const state = snapshot.alive ? (snapshot.isInitializing ? "initializing" : "alive") : "dead";
+ return `- ${snapshot.serverId}: ${state}; root=${snapshot.root}; refs=${snapshot.refCount}`;
+ });
+ const lines = [
+ `Configured LSP servers: ${servers.length}`,
+ `Installed LSP servers: ${installed.length}`,
+ "",
+ ...configuredLines,
+ "",
+ `Active LSP clients: ${snapshots.length}`,
+ ...activeLines,
+ ];
+ return text(lines.join("\n"), { servers, snapshots });
+}
+
+export async function executeLspDiagnostics(
+ params: Record<string, unknown>,
+ signal?: AbortSignal,
+): Promise<ToolExecutionResult> {
+ const filePath = requireString(params, "filePath");
+ const severity = severityFilter(params);
+
+ try {
+ const absPath = resolve(filePath);
+ if (isDirectoryPath(absPath)) {
+ const extension = inferExtensionFromDirectory(absPath);
+ if (!extension) {
+ const message = `No supported source files found in directory: ${absPath}`;
+ const details: LspDiagnosticsDetails = {
+ filePath,
+ severity,
+ mode: "directory",
+ diagnostics: [],
+ totalDiagnostics: 0,
+ truncated: false,
+ error: message,
+ errorKind: "no_files",
+ };
+ return text(message, details);
+ }
+
+ const output = await aggregateDiagnosticsForDirectory(absPath, extension, severity);
+ const details: LspDiagnosticsDetails = {
+ filePath,
+ severity,
+ mode: "directory",
+ diagnostics: [],
+ totalDiagnostics: 0,
+ truncated: false,
+ };
+ return text(output, details);
+ }
+
+ const result = await withLspClient(
+ filePath,
+ async (client) => client.diagnostics(filePath),
+ "diagnostics",
+ clientOptions(signal),
+ );
+ const diagnostics = filterDiagnosticsBySeverity(asDiagnosticArray(result), severity);
+ const total = diagnostics.length;
+ const truncated = total > DEFAULT_MAX_DIAGNOSTICS;
+ const limited = truncated ? diagnostics.slice(0, DEFAULT_MAX_DIAGNOSTICS) : diagnostics;
+ const output =
+ total === 0
+ ? "No diagnostics found"
+ : [
+ ...(truncated ? [`Found ${total} diagnostics (showing first ${DEFAULT_MAX_DIAGNOSTICS}):`] : []),
+ ...limited.map(formatDiagnostic),
+ ].join("\n");
+ const details: LspDiagnosticsDetails = {
+ filePath,
+ severity,
+ mode: "file",
+ diagnostics: diagnostics.map((diagnostic) => ({ file: absPath, diagnostic })),
+ totalDiagnostics: total,
+ truncated,
+ };
+ return text(output, details);
+ } catch (error) {
+ const message = handleMissingDependencyError(error);
+ if (message) {
+ const details: LspDiagnosticsDetails = {
+ filePath,
+ severity,
+ mode: "file",
+ diagnostics: [],
+ totalDiagnostics: 0,
+ truncated: false,
+ error: message,
+ errorKind: "missing_dependency",
+ };
+ return text(message, details);
+ }
+ throw error;
+ }
+}
+
+async function executeLspGotoDefinition(
+ params: Record<string, unknown>,
+ signal?: AbortSignal,
+): Promise<ToolExecutionResult> {
+ const filePath = requireString(params, "filePath");
+ const line = requireNumber(params, "line");
+ const character = requireNumber(params, "character");
+
+ try {
+ const result = await withLspClient(
+ filePath,
+ async (client) => client.definition(filePath, line, character),
+ "definition",
+ clientOptions(signal),
+ );
+ const locations = !result ? [] : Array.isArray(result) ? result : [result];
+ const details: LspGotoDefinitionDetails = { filePath, line, character, locations };
+ if (locations.length === 0) return text("No definition found", details);
+ return text(locations.map(formatLocation).join("\n"), details);
+ } catch (error) {
+ const message = handleMissingDependencyError(error);
+ if (message) {
+ return text(message, {
+ filePath,
+ line,
+ character,
+ locations: [],
+ error: message,
+ errorKind: "missing_dependency",
+ });
+ }
+ throw error;
+ }
+}
+
+async function executeLspFindReferences(
+ params: Record<string, unknown>,
+ signal?: AbortSignal,
+): Promise<ToolExecutionResult> {
+ const filePath = requireString(params, "filePath");
+ const line = requireNumber(params, "line");
+ const character = requireNumber(params, "character");
+ const includeDeclaration = optionalBoolean(params, "includeDeclaration") ?? true;
+
+ try {
+ const result = await withLspClient(
+ filePath,
+ async (client) => client.references(filePath, line, character, includeDeclaration),
+ "references",
+ clientOptions(signal),
+ );
+ const references = Array.isArray(result) ? result : [];
+ const total = references.length;
+ const truncated = total > DEFAULT_MAX_REFERENCES;
+ const limited = truncated ? references.slice(0, DEFAULT_MAX_REFERENCES) : references;
+ const details: LspFindReferencesDetails = {
+ filePath,
+ line,
+ character,
+ references,
+ totalReferences: total,
+ truncated,
+ };
+ if (total === 0) return text("No references found", details);
+ const output = [
+ ...(truncated ? [`Found ${total} references (showing first ${DEFAULT_MAX_REFERENCES}):`] : []),
+ ...limited.map(formatLocation),
+ ].join("\n");
+ return text(output, details);
+ } catch (error) {
+ const message = handleMissingDependencyError(error);
+ if (message) {
+ return text(message, {
+ filePath,
+ line,
+ character,
+ references: [],
+ totalReferences: 0,
+ truncated: false,
+ error: message,
+ errorKind: "missing_dependency",
+ });
+ }
+ throw error;
+ }
+}
+
+async function executeLspSymbols(params: Record<string, unknown>, signal?: AbortSignal): Promise<ToolExecutionResult> {
+ const filePath = requireString(params, "filePath");
+ const rawScope = optionalString(params, "scope") ?? "document";
+ const scope = rawScope === "workspace" ? "workspace" : "document";
+ const limit = Math.min(optionalNumber(params, "limit") ?? DEFAULT_MAX_SYMBOLS, DEFAULT_MAX_SYMBOLS);
+
+ try {
+ if (scope === "workspace") {
+ const query = optionalString(params, "query");
+ if (!query) {
+ const message = "Error: 'query' is required for workspace scope";
+ return text(message, {
+ filePath,
+ scope,
+ symbols: [],
+ totalSymbols: 0,
+ truncated: false,
+ error: message,
+ errorKind: "missing_query",
+ });
+ }
+
+ const symbols = await withLspClient(
+ filePath,
+ async (client) => client.workspaceSymbols(query),
+ "workspaceSymbols",
+ clientOptions(signal),
+ );
+ return formatSymbolsResult(filePath, scope, symbols, limit, query);
+ }
+
+ const symbols = await withLspClient(
+ filePath,
+ async (client) => client.documentSymbols(filePath),
+ "documentSymbols",
+ clientOptions(signal),
+ );
+ return formatSymbolsResult(filePath, scope, symbols, limit);
+ } catch (error) {
+ const message = handleMissingDependencyError(error);
+ if (message) {
+ const query = optionalString(params, "query");
+ return text(message, {
+ filePath,
+ scope,
+ symbols: [],
+ totalSymbols: 0,
+ truncated: false,
+ error: message,
+ errorKind: "missing_dependency",
+ ...(query === undefined ? {} : { query }),
+ });
+ }
+ throw error;
+ }
+}
+
+function formatSymbolsResult(
+ filePath: string,
+ scope: "document" | "workspace",
+ symbols: Array<DocumentSymbol | SymbolInfo>,
+ limit: number,
+ query?: string,
+): ToolExecutionResult {
+ const total = symbols.length;
+ const truncated = total > limit;
+ const limited = truncated ? symbols.slice(0, limit) : symbols;
+ const details: LspSymbolsDetails = {
+ filePath,
+ scope,
+ symbols,
+ totalSymbols: total,
+ truncated,
+ ...(query === undefined ? {} : { query }),
+ };
+ if (total === 0) return text("No symbols found", details);
+
+ const lines: string[] = [];
+ if (truncated) lines.push(`Found ${total} symbols (showing first ${limit}):`);
+ const documentSymbols = limited.filter(isDocumentSymbol);
+ if (documentSymbols.length === limited.length) {
+ lines.push(...documentSymbols.map((symbol) => formatDocumentSymbol(symbol)));
+ } else {
+ lines.push(...limited.filter((symbol): symbol is SymbolInfo => !isDocumentSymbol(symbol)).map(formatSymbolInfo));
+ }
+ return text(lines.join("\n"), details);
+}
+
+async function executeLspPrepareRename(
+ params: Record<string, unknown>,
+ signal?: AbortSignal,
+): Promise<ToolExecutionResult> {
+ const filePath = requireString(params, "filePath");
+ const line = requireNumber(params, "line");
+ const character = requireNumber(params, "character");
+
+ try {
+ const result = await withLspClient(
+ filePath,
+ async (client) => client.prepareRename(filePath, line, character),
+ "prepareRename",
+ clientOptions(signal),
+ );
+ const details: LspPrepareRenameDetails = { filePath, line, character, result };
+ return text(formatPrepareRenameResult(result), details);
+ } catch (error) {
+ const message = handleMissingDependencyError(error);
+ if (message) {
+ return text(message, {
+ filePath,
+ line,
+ character,
+ result: null,
+ error: message,
+ errorKind: "missing_dependency",
+ });
+ }
+ throw error;
+ }
+}
+
+async function executeLspRename(params: Record<string, unknown>, signal?: AbortSignal): Promise<ToolExecutionResult> {
+ const filePath = requireString(params, "filePath");
+ const line = requireNumber(params, "line");
+ const character = requireNumber(params, "character");
+ const newName = requireString(params, "newName");
+
+ try {
+ const edit = await withLspClient(
+ filePath,
+ async (client) => client.rename(filePath, line, character, newName),
+ "rename",
+ clientOptions(signal),
+ );
+ const apply = applyWorkspaceEdit(edit);
+ const details: LspRenameDetails = { filePath, line, character, newName, apply, edit };
+ return text(formatApplyResult(apply), details, !apply.success);
+ } catch (error) {
+ const message = handleMissingDependencyError(error);
+ if (message) {
+ return text(message, {
+ filePath,
+ line,
+ character,
+ newName,
+ apply: null,
+ edit: null,
+ error: message,
+ errorKind: "missing_dependency",
+ });
+ }
+ throw error;
+ }
+}
+
+export async function executeLspTool(
+ name: string,
+ params: Record<string, unknown>,
+ signal?: AbortSignal,
+): Promise<ToolExecutionResult> {
+ const tool = LSP_MCP_TOOLS.find((candidate) => matchesToolName(candidate, name));
+ if (!tool) throw new Error(`Unknown LSP tool: ${name}`);
+ return tool.execute(params, signal);
+}
+
+function matchesToolName(tool: LspMcpTool, name: string): boolean {
+ return tool.name === name || (tool.aliases?.includes(name) ?? false);
+}
+
+export function coerceToolArguments(value: unknown): Record<string, unknown> {
+ return isRecord(value) ? value : {};
+}
+
+export const LSP_MCP_TOOLS: LspMcpTool[] = [
+ {
+ name: "status",
+ aliases: ["lsp_status"],
+ title: "LSP Status",
+ description: "List configured and active LSP servers without starting a new language server.",
+ inputSchema: objectSchema({}),
+ execute: executeLspStatus,
+ },
+ {
+ name: "diagnostics",
+ aliases: ["lsp_diagnostics"],
+ title: "LSP Diagnostics",
+ description: "Get errors, warnings, and hints for a source file or directory.",
+ inputSchema: objectSchema(
+ {
+ filePath: { type: "string", description: "File or directory path to check." },
+ severity: {
+ type: "string",
+ enum: ["error", "warning", "information", "hint", "all"],
+ description: "Severity filter. Defaults to all.",
+ },
+ },
+ ["filePath"],
+ ),
+ execute: executeLspDiagnostics,
+ },
+ {
+ name: "goto_definition",
+ aliases: ["lsp_goto_definition"],
+ title: "LSP Goto Definition",
+ description: "Find where a symbol is defined.",
+ inputSchema: objectSchema(
+ {
+ filePath: { type: "string", description: "Source file containing the symbol." },
+ line: { type: "number", description: "1-based line number." },
+ character: { type: "number", description: "0-based column." },
+ },
+ ["filePath", "line", "character"],
+ ),
+ execute: executeLspGotoDefinition,
+ },
+ {
+ name: "find_references",
+ aliases: ["lsp_find_references"],
+ title: "LSP Find References",
+ description: "Find references of a symbol across the workspace.",
+ inputSchema: objectSchema(
+ {
+ filePath: { type: "string", description: "Source file containing the symbol." },
+ line: { type: "number", description: "1-based line number." },
+ character: { type: "number", description: "0-based column." },
+ includeDeclaration: { type: "boolean", description: "Include the declaration. Defaults to true." },
+ },
+ ["filePath", "line", "character"],
+ ),
+ execute: executeLspFindReferences,
+ },
+ {
+ name: "symbols",
+ aliases: ["lsp_symbols"],
+ title: "LSP Symbols",
+ description: "List document symbols or search workspace symbols.",
+ inputSchema: objectSchema(
+ {
+ filePath: { type: "string", description: "File path used as LSP context." },
+ scope: {
+ type: "string",
+ enum: ["document", "workspace"],
+ description: "Use document for file outline or workspace for project-wide search.",
+ },
+ query: { type: "string", description: "Workspace symbol query." },
+ limit: { type: "number", description: "Maximum number of symbols to return." },
+ },
+ ["filePath", "scope"],
+ ),
+ execute: executeLspSymbols,
+ },
+ {
+ name: "prepare_rename",
+ aliases: ["lsp_prepare_rename"],
+ title: "LSP Prepare Rename",
+ description: "Check whether a symbol can be renamed at a position.",
+ inputSchema: objectSchema(
+ {
+ filePath: { type: "string", description: "Source file path." },
+ line: { type: "number", description: "1-based line number." },
+ character: { type: "number", description: "0-based column." },
+ },
+ ["filePath", "line", "character"],
+ ),
+ execute: executeLspPrepareRename,
+ },
+ {
+ name: "rename",
+ aliases: ["lsp_rename"],
+ title: "LSP Rename",
+ description: "Rename a symbol across the workspace and apply the returned workspace edit.",
+ inputSchema: objectSchema(
+ {
+ filePath: { type: "string", description: "Source file path." },
+ line: { type: "number", description: "1-based line number." },
+ character: { type: "number", description: "0-based column." },
+ newName: { type: "string", description: "New symbol name." },
+ },
+ ["filePath", "line", "character", "newName"],
+ ),
+ execute: executeLspRename,
+ },
+];
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/config-loader.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/config-loader.test.ts
new file mode 100644
index 00000000..1bffd6ce
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/config-loader.test.ts
@@ -0,0 +1,135 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, sep } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { getConfigPaths, getMergedServers } from "../src/lsp/config-loader.js";
+
+const tempDirectories: string[] = [];
+
+afterEach(() => {
+ for (const directory of tempDirectories.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+describe("config loader", () => {
+ it("uses Codex config locations instead of pi config locations", () => {
+ const paths = getConfigPaths();
+ const expectedSuffix = join(".codex", "lsp-client.json");
+ const piMarker = `${sep}.pi${sep}`;
+
+ expect(paths.project.endsWith(expectedSuffix)).toBe(true);
+ expect(paths.user.endsWith(expectedSuffix)).toBe(true);
+ expect(paths.project).not.toContain(piMarker);
+ expect(paths.user).not.toContain(piMarker);
+ });
+
+ it("supports project and user config path overrides via environment variables", () => {
+ const previousProject = process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];
+ const previousUser = process.env["LSP_TOOLS_MCP_USER_CONFIG"];
+
+ process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"] = "config/lsp-opencode.json";
+ process.env["LSP_TOOLS_MCP_USER_CONFIG"] = ".opencode/lsp.json";
+
+ try {
+ const paths = getConfigPaths();
+
+ expect(paths.project).toBe(join(process.cwd(), "config", "lsp-opencode.json"));
+ expect(paths.user).toBe(join(process.env["HOME"] ?? "", ".opencode", "lsp.json"));
+ } finally {
+ if (previousProject === undefined) {
+ delete process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];
+ } else {
+ process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"] = previousProject;
+ }
+
+ if (previousUser === undefined) {
+ delete process.env["LSP_TOOLS_MCP_USER_CONFIG"];
+ } else {
+ process.env["LSP_TOOLS_MCP_USER_CONFIG"] = previousUser;
+ }
+ }
+ });
+
+ it("keeps absolute override paths unchanged", () => {
+ const previousProject = process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];
+ const previousUser = process.env["LSP_TOOLS_MCP_USER_CONFIG"];
+ const absoluteProject = join(process.cwd(), "overrides", "project.json");
+ const absoluteUser = join(process.cwd(), "overrides", "user.json");
+
+ process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"] = absoluteProject;
+ process.env["LSP_TOOLS_MCP_USER_CONFIG"] = absoluteUser;
+
+ try {
+ const paths = getConfigPaths();
+
+ expect(paths.project).toBe(absoluteProject);
+ expect(paths.user).toBe(absoluteUser);
+ } finally {
+ if (previousProject === undefined) {
+ delete process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];
+ } else {
+ process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"] = previousProject;
+ }
+
+ if (previousUser === undefined) {
+ delete process.env["LSP_TOOLS_MCP_USER_CONFIG"];
+ } else {
+ process.env["LSP_TOOLS_MCP_USER_CONFIG"] = previousUser;
+ }
+ }
+ });
+
+ it("#given one invalid LSP config entry #when merging servers #then keeps valid sibling entries", () => {
+ // given
+ const previousProject = process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];
+ const previousUser = process.env["LSP_TOOLS_MCP_USER_CONFIG"];
+ const root = mkdtempSync(join(tmpdir(), "lsp-tools-config-"));
+ tempDirectories.push(root);
+ const projectConfig = join(root, "project.json");
+ const userConfig = join(root, "user.json");
+ mkdirSync(root, { recursive: true });
+ writeFileSync(
+ projectConfig,
+ JSON.stringify({
+ lsp: {
+ valid: { command: ["valid-lsp", "--stdio"], extensions: [".valid"], priority: 7 },
+ invalid: "not an object",
+ },
+ }),
+ );
+ writeFileSync(userConfig, JSON.stringify({ lsp: {} }));
+ process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"] = projectConfig;
+ process.env["LSP_TOOLS_MCP_USER_CONFIG"] = userConfig;
+
+ try {
+ // when
+ const servers = getMergedServers();
+
+ // then
+ expect(servers).toContainEqual(
+ expect.objectContaining({
+ id: "valid",
+ command: ["valid-lsp", "--stdio"],
+ extensions: [".valid"],
+ priority: 7,
+ source: "project",
+ }),
+ );
+ expect(servers.some((server) => server.id === "invalid")).toBe(false);
+ } finally {
+ if (previousProject === undefined) {
+ delete process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"];
+ } else {
+ process.env["LSP_TOOLS_MCP_PROJECT_CONFIG"] = previousProject;
+ }
+
+ if (previousUser === undefined) {
+ delete process.env["LSP_TOOLS_MCP_USER_CONFIG"];
+ } else {
+ process.env["LSP_TOOLS_MCP_USER_CONFIG"] = previousUser;
+ }
+ }
+ });
+});
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/directory-diagnostics.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/directory-diagnostics.test.ts
new file mode 100644
index 00000000..cbd85cae
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/directory-diagnostics.test.ts
@@ -0,0 +1,32 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { collectFilesWithExtension } from "../src/lsp/directory-diagnostics.js";
+
+const tempDirectories: string[] = [];
+
+afterEach(() => {
+ for (const directory of tempDirectories.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+describe("collectFilesWithExtension", () => {
+ it("#given more matching files than max #when collecting diagnostics inputs #then traversal returns only capped files", () => {
+ // given
+ const root = mkdtempSync(join(tmpdir(), "codex-lsp-directory-"));
+ tempDirectories.push(root);
+ mkdirSync(join(root, "src"), { recursive: true });
+ for (let index = 0; index < 5; index += 1) {
+ writeFileSync(join(root, "src", `file-${index}.ts`), `export const value${index} = ${index};\n`);
+ }
+
+ // when
+ const files = collectFilesWithExtension(root, ".ts", 2);
+
+ // then
+ expect(files).toHaveLength(2);
+ });
+});
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/fixtures/broken.py b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/fixtures/broken.py
new file mode 100644
index 00000000..745b30da
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/fixtures/broken.py
@@ -0,0 +1 @@
+value: str = 1
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/formatters.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/formatters.test.ts
new file mode 100644
index 00000000..61fbf636
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/formatters.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from "vitest";
+
+import { filterDiagnosticsBySeverity } from "../src/lsp/formatters.js";
+import type { Diagnostic } from "../src/lsp/types.js";
+
+const range = {
+ start: { line: 0, character: 0 },
+ end: { line: 0, character: 1 },
+};
+
+function diagnostic(message: string, severity?: number): Diagnostic {
+ return severity === undefined ? { range, message } : { range, message, severity };
+}
+
+describe("filterDiagnosticsBySeverity", () => {
+ it("#given all severity filter #when filtering diagnostics #then returns the original diagnostics", () => {
+ // given
+ const diagnostics = [diagnostic("syntax", 1), diagnostic("note", 3)];
+
+ // when
+ const filtered = filterDiagnosticsBySeverity(diagnostics, "all");
+
+ // then
+ expect(filtered).toBe(diagnostics);
+ });
+
+ it("#given mixed severities #when filtering diagnostics #then returns only matching diagnostics", () => {
+ // given
+ const diagnostics = [
+ diagnostic("syntax", 1),
+ diagnostic("lint", 2),
+ diagnostic("note", 3),
+ diagnostic("hint", 4),
+ diagnostic("unknown"),
+ ];
+
+ // when / then
+ expect(filterDiagnosticsBySeverity(diagnostics, "error")).toEqual([diagnostics[0]]);
+ expect(filterDiagnosticsBySeverity(diagnostics, "warning")).toEqual([diagnostics[1]]);
+ expect(filterDiagnosticsBySeverity(diagnostics, "information")).toEqual([diagnostics[2]]);
+ expect(filterDiagnosticsBySeverity(diagnostics, "hint")).toEqual([diagnostics[3]]);
+ });
+});
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/helpers/fake-lsp-client.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/helpers/fake-lsp-client.ts
new file mode 100644
index 00000000..6d199210
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/helpers/fake-lsp-client.ts
@@ -0,0 +1,74 @@
+import { LspClient } from "../../src/lsp/client.js";
+import type { ResolvedServer } from "../../src/lsp/types.js";
+
+export interface FakeLspClientOptions {
+ startDelayMs?: number;
+ initDelayMs?: number;
+ failStart?: boolean;
+ failInitialize?: boolean;
+ stopDelayMs?: number;
+ startsAlive?: boolean;
+}
+
+export class FakeLspClient extends LspClient {
+ private aliveFlag: boolean;
+ startCallCount = 0;
+ initializeCallCount = 0;
+ stopCallCount = 0;
+
+ constructor(
+ root: string,
+ server: ResolvedServer,
+ private readonly opts: FakeLspClientOptions = {},
+ ) {
+ super(root, server);
+ this.aliveFlag = opts.startsAlive !== false;
+ }
+
+ override async start(): Promise<void> {
+ this.startCallCount++;
+ if (this.opts.startDelayMs !== undefined) {
+ await new Promise((resolve) => setTimeout(resolve, this.opts.startDelayMs));
+ }
+ if (this.opts.failStart) {
+ this.aliveFlag = false;
+ throw new Error("fake start failed");
+ }
+ }
+
+ override async initialize(): Promise<void> {
+ this.initializeCallCount++;
+ if (this.opts.initDelayMs !== undefined) {
+ await new Promise((resolve) => setTimeout(resolve, this.opts.initDelayMs));
+ }
+ if (this.opts.failInitialize) {
+ this.aliveFlag = false;
+ throw new Error("fake initialize failed");
+ }
+ }
+
+ override isAlive(): boolean {
+ return this.aliveFlag;
+ }
+
+ override command(): string[] {
+ return ["fake-server"];
+ }
+
+ override async stop(): Promise<void> {
+ this.stopCallCount++;
+ if (this.opts.stopDelayMs !== undefined) {
+ await new Promise((resolve) => setTimeout(resolve, this.opts.stopDelayMs));
+ }
+ this.aliveFlag = false;
+ }
+}
+
+export function makeServer(id: string, extensions: string[] = [".ts"]): ResolvedServer {
+ return {
+ id,
+ command: ["fake-server", "--stdio"],
+ extensions,
+ priority: 0,
+ };
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/json-rpc-connection.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/json-rpc-connection.test.ts
new file mode 100644
index 00000000..5b9e8d47
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/json-rpc-connection.test.ts
@@ -0,0 +1,69 @@
+import { PassThrough } from "node:stream";
+import { describe, expect, it } from "vitest";
+
+import { JsonRpcConnection } from "../src/lsp/json-rpc-connection.js";
+
+function encodeMessage(message: Record<string, unknown>): string {
+ const body = JSON.stringify(message);
+ return `Content-Length: ${Buffer.byteLength(body, "utf8")}\r\n\r\n${body}`;
+}
+
+function readOneMessage(stream: PassThrough): Promise<Record<string, unknown>> {
+ return new Promise((resolve) => {
+ stream.once("data", (chunk: Buffer) => {
+ const text = chunk.toString("utf8");
+ const bodyStart = text.indexOf("\r\n\r\n") + 4;
+ resolve(JSON.parse(text.slice(bodyStart)) as Record<string, unknown>);
+ });
+ });
+}
+
+describe("JsonRpcConnection", () => {
+ it("#given a framed response #when sending request #then resolves the matching result", async () => {
+ // given
+ const serverOutput = new PassThrough();
+ const serverInput = new PassThrough();
+ const connection = new JsonRpcConnection(serverOutput, serverInput);
+ connection.listen();
+ const requestMessage = readOneMessage(serverInput);
+
+ // when
+ const resultPromise = connection.sendRequest<{ capabilities: Record<string, unknown> }>("initialize", {
+ rootUri: "file:///tmp/project",
+ });
+ const request = await requestMessage;
+ serverOutput.write(encodeMessage({ jsonrpc: "2.0", id: request["id"], result: { capabilities: {} } }));
+
+ // then
+ await expect(resultPromise).resolves.toEqual({ capabilities: {} });
+ connection.dispose();
+ });
+
+ it("#given a server request #when handler returns #then writes a json-rpc response", async () => {
+ // given
+ const serverOutput = new PassThrough();
+ const serverInput = new PassThrough();
+ const connection = new JsonRpcConnection(serverOutput, serverInput);
+ connection.onRequest("workspace/configuration", () => [{ validate: { enable: true } }]);
+ connection.listen();
+
+ // when
+ const responseMessage = readOneMessage(serverInput);
+ serverOutput.write(
+ encodeMessage({
+ jsonrpc: "2.0",
+ id: 7,
+ method: "workspace/configuration",
+ params: { items: [{ section: "json" }] },
+ }),
+ );
+
+ // then
+ await expect(responseMessage).resolves.toMatchObject({
+ jsonrpc: "2.0",
+ id: 7,
+ result: [{ validate: { enable: true } }],
+ });
+ connection.dispose();
+ });
+});
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/manager.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/manager.test.ts
new file mode 100644
index 00000000..4242e262
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/manager.test.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "vitest";
+
+import type { LspClient } from "../src/lsp/client.js";
+import { LspManager } from "../src/lsp/manager.js";
+import type { ResolvedServer } from "../src/lsp/types.js";
+
+import { FakeLspClient, type FakeLspClientOptions, makeServer } from "./helpers/fake-lsp-client.js";
+
+interface FakeContext {
+ manager: LspManager;
+ clients: FakeLspClient[];
+ now: { value: number };
+}
+
+function setupManager(options?: {
+ idleTimeoutMs?: number;
+ initTimeoutMs?: number;
+ reaperIntervalMs?: number;
+ clientFactoryOptions?: () => FakeLspClientOptions;
+}): FakeContext {
+ const clients: FakeLspClient[] = [];
+ const now = { value: 1_000 };
+ const manager = new LspManager({
+ idleTimeoutMs: options?.idleTimeoutMs ?? 5_000,
+ initTimeoutMs: options?.initTimeoutMs ?? 1_000,
+ reaperIntervalMs: options?.reaperIntervalMs ?? 100,
+ now: () => now.value,
+ clientFactory: (root: string, server: ResolvedServer): LspClient => {
+ const client = new FakeLspClient(root, server, options?.clientFactoryOptions?.());
+ clients.push(client);
+ return client;
+ },
+ });
+ return { manager, clients, now };
+}
+
+type ProcessSignalListener = (...args: never[]) => unknown;
+
+function findAddedListener(
+ signal: NodeJS.Signals,
+ before: readonly ProcessSignalListener[],
+): ProcessSignalListener | undefined {
+ return process.listeners(signal).find((listener) => !before.includes(listener));
+}
+
+describe("LspManager", () => {
+ it("#given failed start #when later getClient #then failed client is stopped and a fresh client is built", async () => {
+ // given
+ let firstCall = true;
+ const failingFactory = () => {
+ if (firstCall) {
+ firstCall = false;
+ return { failStart: true };
+ }
+ return {};
+ };
+ const { manager, clients } = setupManager({ clientFactoryOptions: failingFactory });
+ const server = makeServer("typescript");
+
+ // when
+ await expect(manager.getClient("/root/a", server)).rejects.toThrow("fake start failed");
+
+ // then
+ expect(manager.getSnapshot()).toEqual([]);
+ expect(clients[0]?.stopCallCount).toBeGreaterThan(0);
+
+ const fresh = await manager.getClient("/root/a", server);
+ expect(clients.length).toBe(2);
+ expect(fresh).toBe(clients[1]);
+
+ await manager.stopAll();
+ });
+
+ it("#given failed initialize #when later getClient #then failed client is stopped and a fresh client is built", async () => {
+ // given
+ let firstCall = true;
+ const failingFactory = () => {
+ if (firstCall) {
+ firstCall = false;
+ return { failInitialize: true };
+ }
+ return {};
+ };
+ const { manager, clients } = setupManager({ clientFactoryOptions: failingFactory });
+ const server = makeServer("typescript");
+
+ // when
+ await expect(manager.getClient("/root/a", server)).rejects.toThrow("fake initialize failed");
+
+ // then
+ expect(manager.getSnapshot()).toEqual([]);
+ expect(clients[0]?.stopCallCount).toBeGreaterThan(0);
+
+ const fresh = await manager.getClient("/root/a", server);
+ expect(clients.length).toBe(2);
+ expect(fresh).toBe(clients[1]);
+
+ await manager.stopAll();
+ });
+
+ it("#given active client #when signal cleanup runs #then client is stopped and handlers unregister", async () => {
+ // given
+ const beforeSigterm = process.listeners("SIGTERM");
+ const { manager, clients } = setupManager();
+ const server = makeServer("typescript");
+
+ try {
+ await manager.getClient("/root/a", server);
+ manager.releaseClient("/root/a", server.id);
+
+ // when
+ const listener = findAddedListener("SIGTERM", beforeSigterm);
+
+ // then
+ expect(listener).toBeDefined();
+ listener?.();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(clients[0]?.stopCallCount).toBe(1);
+ expect(manager.clientCount()).toBe(0);
+ expect(process.listeners("SIGTERM")).toEqual(beforeSigterm);
+ } finally {
+ await manager.stopAll();
+ }
+ });
+});
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/mcp.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/mcp.test.ts
new file mode 100644
index 00000000..fce1bf57
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/mcp.test.ts
@@ -0,0 +1,103 @@
+import { PassThrough } from "node:stream";
+
+import { describe, expect, it } from "vitest";
+
+import { handleLspMcpRequest, runMcpStdioServer } from "../src/mcp.js";
+
+describe("lsp MCP server", () => {
+ it("responds to initialize with tool capabilities", async () => {
+ const response = await handleLspMcpRequest({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: "2024-11-05",
+ capabilities: {},
+ clientInfo: { name: "test", version: "0.0.0" },
+ },
+ });
+
+ expect(response).toMatchObject({
+ jsonrpc: "2.0",
+ id: 1,
+ result: {
+ capabilities: { tools: { listChanged: false } },
+ serverInfo: { name: "lsp", version: "0.1.0" },
+ },
+ });
+ });
+
+ it("lists LSP MCP tools", async () => {
+ const response = await handleLspMcpRequest({
+ jsonrpc: "2.0",
+ id: 2,
+ method: "tools/list",
+ });
+
+ const tools = response?.result?.tools as Array<{ name: string }>;
+ expect(tools.map((tool) => tool.name)).toEqual([
+ "status",
+ "diagnostics",
+ "goto_definition",
+ "find_references",
+ "symbols",
+ "prepare_rename",
+ "rename",
+ ]);
+ });
+
+ it("calls status without starting a language server", async () => {
+ const response = await handleLspMcpRequest({
+ jsonrpc: "2.0",
+ id: 3,
+ method: "tools/call",
+ params: { name: "status", arguments: {} },
+ });
+
+ expect(response).toMatchObject({
+ jsonrpc: "2.0",
+ id: 3,
+ result: {
+ isError: false,
+ },
+ });
+ expect(response?.result?.content?.[0]?.text).toContain("Configured LSP servers");
+ });
+
+ it("accepts legacy lsp-prefixed tool names without listing them", async () => {
+ const response = await handleLspMcpRequest({
+ jsonrpc: "2.0",
+ id: 4,
+ method: "tools/call",
+ params: { name: "lsp_status", arguments: {} },
+ });
+
+ expect(response).toMatchObject({
+ jsonrpc: "2.0",
+ id: 4,
+ result: {
+ isError: false,
+ },
+ });
+ expect(response?.result?.content?.[0]?.text).toContain("Configured LSP servers");
+ });
+
+ it("#given idle stdio connection #when no request arrives before timeout #then server exits through idle callback", async () => {
+ // given
+ const input = new PassThrough();
+ const output = new PassThrough();
+ let idleCallCount = 0;
+
+ // when
+ await runMcpStdioServer(input, output, {
+ idleTimeoutMs: 1,
+ onIdleTimeout: () => {
+ idleCallCount++;
+ input.end();
+ },
+ });
+
+ // then
+ expect(idleCallCount).toBe(1);
+ });
+});
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/package-smoke.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/package-smoke.test.ts
new file mode 100644
index 00000000..bc6196fc
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/package-smoke.test.ts
@@ -0,0 +1,63 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+type PackageJson = {
+ readonly type: string;
+ readonly packageManager: string;
+ readonly name: string;
+ readonly license: string;
+ readonly bin: Record<string, string>;
+ readonly files: readonly string[];
+ readonly dependencies?: Record<string, unknown>;
+};
+
+function readPackageJson(path: string): PackageJson {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (!isPackageJson(parsed)) throw new TypeError(`Invalid package metadata: ${path}`);
+ return parsed;
+}
+
+describe("package metadata", () => {
+ it("#given packaged files #when validating entrypoints #then package metadata is consistent", () => {
+ // given
+ const packageJson = readPackageJson("package.json");
+ const cliSource = readFileSync("src/cli.ts", "utf8");
+
+ // then
+ expect(packageJson.type).toBe("module");
+ expect(packageJson.packageManager).toBe("[email protected]");
+ expect(packageJson.name).toBe("@code-yeongyu/lsp-tools-mcp");
+ expect(packageJson.license).toBe("MIT");
+ expect(packageJson.dependencies ?? {}).toEqual({});
+ expect(packageJson.bin["lsp-tools-mcp"]).toBe("./dist/cli.js");
+ expect(packageJson.files).toEqual(["dist", "LICENSE", "NOTICE", "README.md", "CHANGELOG.md"]);
+ expect(cliSource.startsWith("#!/usr/bin/env node")).toBe(true);
+ expect(cliSource).toContain("Usage: lsp-tools-mcp [mcp]");
+ });
+});
+
+function isPackageJson(value: unknown): value is PackageJson {
+ const dependencies = isRecord(value) ? value["dependencies"] : undefined;
+ return (
+ isRecord(value) &&
+ value["type"] === "module" &&
+ value["packageManager"] === "[email protected]" &&
+ value["name"] === "@code-yeongyu/lsp-tools-mcp" &&
+ value["license"] === "MIT" &&
+ isStringRecord(value["bin"]) &&
+ isStringArray(value["files"]) &&
+ (dependencies === undefined || isRecord(dependencies))
+ );
+}
+
+function isStringRecord(value: unknown): value is Record<string, string> {
+ return isRecord(value) && Object.values(value).every((item) => typeof item === "string");
+}
+
+function isStringArray(value: unknown): value is readonly string[] {
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/process.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/process.test.ts
new file mode 100644
index 00000000..c71a0c0d
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/process.test.ts
@@ -0,0 +1,151 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createSpawnCommand, spawnProcess } from "../src/lsp/process.js";
+
+const tempDirectories: string[] = [];
+
+afterEach(() => {
+ for (const directory of tempDirectories.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function readFirstLine(stream: NodeJS.ReadableStream): Promise<string> {
+ return new Promise((resolve, reject) => {
+ let buffer = "";
+
+ const cleanup = () => {
+ stream.off("data", onData);
+ stream.off("error", onError);
+ };
+
+ const onData = (chunk: Buffer | string) => {
+ buffer += Buffer.isBuffer(chunk) ? chunk.toString("utf8") : chunk;
+ const newlineIndex = buffer.indexOf("\n");
+ if (newlineIndex === -1) return;
+ cleanup();
+ resolve(buffer.slice(0, newlineIndex).trim());
+ };
+
+ const onError = (error: Error) => {
+ cleanup();
+ reject(error);
+ };
+
+ stream.on("data", onData);
+ stream.on("error", onError);
+ });
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function isPidAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function killPidBestEffort(pid: number): void {
+ try {
+ process.kill(pid, "SIGKILL");
+ } catch {
+ // Already exited.
+ }
+}
+
+describe("createSpawnCommand", () => {
+ it("#given windows executable command #when building spawn command #then it avoids shell mode", () => {
+ // given
+ const command = ["typescript-language-server", "--stdio"];
+
+ // when
+ const prepared = createSpawnCommand(command, "win32", "cmd.exe");
+
+ // then
+ expect(prepared).toEqual({
+ command: "typescript-language-server",
+ args: ["--stdio"],
+ shell: false,
+ });
+ });
+
+ it("#given windows cmd shim #when building spawn command #then it uses cmd only for the shim", () => {
+ // given
+ const command = ["typescript-language-server.cmd", "--stdio"];
+
+ // when
+ const prepared = createSpawnCommand(command, "win32", "cmd.exe");
+
+ // then
+ expect(prepared).toEqual({
+ command: "cmd.exe",
+ args: ["/d", "/s", "/c", "typescript-language-server.cmd", "--stdio"],
+ shell: false,
+ });
+ });
+
+ it("#given windows PATH shim #when resolving spawn command #then it executes the shim without shell mode", () => {
+ // given
+ const binaryDirectory = mkdtempSync(join(tmpdir(), "codex-lsp-bin-"));
+ tempDirectories.push(binaryDirectory);
+ mkdirSync(binaryDirectory, { recursive: true });
+ const shimPath = join(binaryDirectory, "typescript-language-server.cmd");
+ writeFileSync(shimPath, "@echo off\n");
+
+ // when
+ const prepared = createSpawnCommand(["typescript-language-server", "--stdio"], "win32", "cmd.exe", {
+ PATH: binaryDirectory,
+ PATHEXT: ".cmd;.exe",
+ });
+
+ // then
+ expect(prepared).toEqual({
+ command: "cmd.exe",
+ args: ["/d", "/s", "/c", shimPath, "--stdio"],
+ shell: false,
+ });
+ });
+});
+
+describe("spawnProcess", () => {
+ it.skipIf(process.platform === "win32")(
+ "#given child process tree #when killing spawned wrapper #then descendant process exits too",
+ async () => {
+ // given
+ const directory = mkdtempSync(join(tmpdir(), "lsp-tools-process-tree-"));
+ tempDirectories.push(directory);
+ const script = [
+ "const { spawn } = require('node:child_process')",
+ "const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })",
+ "console.error(String(child.pid))",
+ "process.on('SIGTERM', () => process.exit(0))",
+ "setInterval(() => {}, 1000)",
+ ].join(";");
+ const proc = spawnProcess([process.execPath, "-e", script], { cwd: directory, env: process.env });
+ const childPid = Number(await readFirstLine(proc.stderr));
+
+ try {
+ // when
+ proc.kill("SIGTERM");
+ await Promise.race([proc.exited, sleep(2_000)]);
+ await sleep(200);
+
+ // then
+ expect(Number.isInteger(childPid)).toBe(true);
+ expect(isPidAlive(childPid)).toBe(false);
+ } finally {
+ killPidBestEffort(childPid);
+ proc.kill("SIGKILL");
+ }
+ },
+ );
+});
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/server-definitions.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/server-definitions.test.ts
new file mode 100644
index 00000000..5fb9bdba
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/server-definitions.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+
+import { AUTO_INSTALLABLE_SERVERS, BUILTIN_SERVERS, LSP_INSTALL_HINTS } from "../src/lsp/server-definitions.js";
+
+describe("BUILTIN_SERVERS", () => {
+ it("#given rust #when looking it up #then maps to rust-analyzer", () => {
+ // given
+ const rust = BUILTIN_SERVERS["rust"];
+
+ // when / then
+ expect(rust).toBeDefined();
+ expect(rust?.command[0]).toBe("rust-analyzer");
+ expect(rust?.extensions).toEqual([".rs"]);
+ });
+
+ it("#given rust install guidance #when inspecting registry #then rust is manual install only", () => {
+ // given
+ const hint = LSP_INSTALL_HINTS["rust"];
+
+ // when / then
+ expect(AUTO_INSTALLABLE_SERVERS["rust"]).toBeUndefined();
+ expect(hint).toContain("rust-analyzer");
+ expect(hint).toContain("rustup component add rust-analyzer");
+ expect(hint).toContain("rustup component remove rust-src");
+ expect(hint).toContain("rustup component add rust-src");
+ });
+});
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/utils.test.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/utils.test.ts
new file mode 100644
index 00000000..614743d1
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/test/utils.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, it } from "vitest";
+
+import { LspProcessExitedError } from "../src/lsp/errors.js";
+import { formatKnownLspStartupFailure, handleMissingDependencyError } from "../src/lsp/utils.js";
+
+describe("formatKnownLspStartupFailure", () => {
+ it("#given rust-src component conflict #when formatting startup failure #then returns repair guidance", () => {
+ // given
+ const error = new LspProcessExitedError(
+ "rust",
+ "/repo",
+ 1,
+ "failed to install component: 'rust-src', detected conflict: 'lib/rustlib/src/rust/library/Cargo.lock'",
+ );
+
+ // when
+ const message = formatKnownLspStartupFailure(error);
+
+ // then
+ expect(message).toContain("rust-analyzer");
+ expect(message).toContain("rustup component remove rust-src");
+ expect(message).toContain("rustup component add rust-src");
+ expect(message).toContain("detected conflict");
+ expect(message).toContain("Cargo.lock");
+ expect(message).not.toContain("automatic repair");
+ });
+
+ it("#given rust-analyzer sysroot error #when handling missing dependency #then returns repair guidance", () => {
+ // given
+ const error = new LspProcessExitedError(
+ "rust",
+ "/repo",
+ 1,
+ "can't load standard library from sysroot\ntry installing `rust-src` the same way you installed `rustc`",
+ );
+
+ // when
+ const message = handleMissingDependencyError(error);
+
+ // then
+ expect(message).toContain("rustup component remove rust-src");
+ expect(message).toContain("rustup component add rust-src");
+ expect(message).toContain("can't load standard library");
+ });
+
+ it("#given unrelated process exits #when formatting startup failure #then returns null", () => {
+ // given
+ const typescriptError = new LspProcessExitedError(
+ "typescript",
+ "/repo",
+ 1,
+ "failed to install component: 'rust-src', detected conflict",
+ );
+ const rustPanic = new LspProcessExitedError("rust", "/repo", 1, "thread panicked while loading crate graph");
+
+ // when / then
+ expect(formatKnownLspStartupFailure(typescriptError)).toBeNull();
+ expect(formatKnownLspStartupFailure(rustPanic)).toBeNull();
+ });
+});
+
+describe("handleMissingDependencyError", () => {
+ it("#given existing dependency messages #when handling error #then preserves current messages", () => {
+ // given
+ const notInstalled = new Error("LSP server 'typescript' is configured but NOT INSTALLED.");
+ const notConfigured = new Error("No LSP server configured for extension: .md");
+
+ // when / then
+ expect(handleMissingDependencyError(notInstalled)).toBe(notInstalled.message);
+ expect(handleMissingDependencyError(notConfigured)).toBe(notConfigured.message);
+ });
+});
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/tsconfig.build.json b/plugins/omo/components/lsp/packages/lsp-tools-mcp/tsconfig.build.json
new file mode 100644
index 00000000..5b5bbcaf
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/tsconfig.build.json
@@ -0,0 +1,12 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "allowImportingTsExtensions": false,
+ "declaration": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "noEmit": false
+ },
+ "include": ["src/**/*"],
+ "exclude": ["test/**/*"]
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/tsconfig.json b/plugins/omo/components/lsp/packages/lsp-tools-mcp/tsconfig.json
new file mode 100644
index 00000000..342229c0
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/tsconfig.json
@@ -0,0 +1,27 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "lib": ["ES2022"],
+ "strict": true,
+ "exactOptionalPropertyTypes": true,
+ "noUncheckedIndexedAccess": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "verbatimModuleSyntax": true,
+ "noImplicitOverride": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "esModuleInterop": true,
+ "allowImportingTsExtensions": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "useDefineForClassFields": false,
+ "types": ["node"],
+ "noEmit": true
+ },
+ "include": ["src/**/*", "test/**/*"]
+}
diff --git a/plugins/omo/components/lsp/packages/lsp-tools-mcp/vitest.config.ts b/plugins/omo/components/lsp/packages/lsp-tools-mcp/vitest.config.ts
new file mode 100644
index 00000000..57bd8f12
--- /dev/null
+++ b/plugins/omo/components/lsp/packages/lsp-tools-mcp/vitest.config.ts
@@ -0,0 +1,9 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["test/**/*.test.ts"],
+ environment: "node",
+ pool: "threads",
+ },
+});
diff --git a/plugins/omo/components/lsp/scripts/bootstrap-submodule.mjs b/plugins/omo/components/lsp/scripts/bootstrap-submodule.mjs
new file mode 100644
index 00000000..a1b45e3d
--- /dev/null
+++ b/plugins/omo/components/lsp/scripts/bootstrap-submodule.mjs
@@ -0,0 +1,38 @@
+#!/usr/bin/env node
+// Bootstrap the lsp-tools-mcp git submodule for local development.
+// CI runs the install+build steps explicitly in the workflow, so this
+// script is mostly for `npm run bootstrap` after a fresh clone and as a
+// chained pre-step before typecheck / test / check so contributors do not
+// have to remember it.
+//
+// Idempotent: skips when dist/cli.js already exists, unless --force is passed.
+import { existsSync } from "node:fs";
+import { execSync } from "node:child_process";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const submoduleDir = join(__dirname, "..", "packages", "lsp-tools-mcp");
+const submodulePackageJson = join(submoduleDir, "package.json");
+const submoduleDistCli = join(submoduleDir, "dist", "cli.js");
+const force = process.argv.includes("--force");
+
+if (!existsSync(submodulePackageJson)) {
+ console.error(
+ "lsp-tools-mcp submodule is missing. Run: git submodule update --init --recursive",
+ );
+ process.exit(1);
+}
+
+if (!force && existsSync(submoduleDistCli)) {
+ // Already built; nothing to do.
+ process.exit(0);
+}
+
+console.log("Installing lsp-tools-mcp dependencies...");
+execSync("npm ci", { cwd: submoduleDir, stdio: "inherit" });
+
+console.log("Building lsp-tools-mcp...");
+execSync("npm run build", { cwd: submoduleDir, stdio: "inherit" });
+
+console.log("Done.");
diff --git a/plugins/omo/components/lsp/skills/lsp/SKILL.md b/plugins/omo/components/lsp/skills/lsp/SKILL.md
new file mode 100644
index 00000000..36be0684
--- /dev/null
+++ b/plugins/omo/components/lsp/skills/lsp/SKILL.md
@@ -0,0 +1,35 @@
+---
+name: lsp
+description: Use when Codex needs language-server diagnostics, definitions, references, symbols, or rename safety checks in the current workspace.
+---
+
+# Codex LSP
+
+Call `lsp` MCP tools through the tool interface; `lsp.*`/`mcp__lsp__*` are tool-call names, not shell commands.
+
+## Tools
+
+- `lsp.status`: list configured, installed, missing, disabled, and active language servers.
+- `lsp.diagnostics`: check one file or directory for LSP diagnostics. Prefer `severity: "error"` after edits.
+- `lsp.goto_definition`: locate a symbol definition from file, line, and character.
+- `lsp.find_references`: find usages of a symbol across the workspace.
+- `lsp.symbols`: inspect document symbols or search workspace symbols.
+- `lsp.prepare_rename`: check whether a rename is valid at a position.
+- `lsp.rename`: apply a language-server workspace edit for a rename.
+
+## Config
+
+Project config lives at `.codex/lsp-client.json`; user config lives at `~/.codex/lsp-client.json`.
+
+```json
+{
+ "lsp": {
+ "typescript": {
+ "command": ["typescript-language-server", "--stdio"],
+ "extensions": [".ts", ".tsx", ".js", ".jsx"]
+ }
+ }
+}
+```
+
+Use `lsp.status` first when diagnostics report a missing language server.
diff --git a/plugins/omo/components/lsp/src/cli.ts b/plugins/omo/components/lsp/src/cli.ts
new file mode 100644
index 00000000..9373ad7d
--- /dev/null
+++ b/plugins/omo/components/lsp/src/cli.ts
@@ -0,0 +1,33 @@
+#!/usr/bin/env node
+import { argv, stderr } from "node:process";
+
+import { disposeDefaultLspManager } from "@code-yeongyu/lsp-tools-mcp/dist/lsp/manager.js";
+import { runMcpStdioServer } from "@code-yeongyu/lsp-tools-mcp/dist/mcp.js";
+import { runPostToolUseHookCli } from "./codex-hook.js";
+
+async function main(): Promise<void> {
+ const [command = "mcp", subcommand = ""] = argv.slice(2);
+
+ try {
+ if (command === "hook" && subcommand === "post-tool-use") {
+ await runPostToolUseHookCli();
+ return;
+ }
+
+ if (command === "mcp") {
+ await runMcpStdioServer();
+ return;
+ }
+
+ stderr.write("Usage: codex-lsp [mcp | hook post-tool-use]\n");
+ process.exitCode = 2;
+ } finally {
+ await disposeDefaultLspManager();
+ }
+}
+
+main().catch(async (error: unknown) => {
+ stderr.write(`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
+ await disposeDefaultLspManager();
+ process.exitCode = 1;
+});
diff --git a/plugins/omo/components/lsp/src/codex-hook.ts b/plugins/omo/components/lsp/src/codex-hook.ts
new file mode 100644
index 00000000..c5ea956f
--- /dev/null
+++ b/plugins/omo/components/lsp/src/codex-hook.ts
@@ -0,0 +1,171 @@
+import { stdin as processStdin } from "node:process";
+
+import { executeLspDiagnostics } from "@code-yeongyu/lsp-tools-mcp/dist/tools.js";
+
+export type DiagnosticsRunner = (filePath: string) => Promise<string>;
+
+export interface CodexPostToolUseInput {
+ tool_name?: unknown;
+ tool_input?: unknown;
+ tool_response?: unknown;
+}
+
+interface DiagnosticBlock {
+ filePath: string;
+ diagnostics: string;
+}
+
+interface PostToolUseHookOutput {
+ decision: "block";
+ reason: string;
+ hookSpecificOutput: {
+ hookEventName: "PostToolUse";
+ additionalContext: string;
+ };
+}
+
+const MUTATION_TOOL_NAMES = new Set(["apply_patch", "write", "edit", "multiedit", "multi_edit"]);
+const CLEAN_DIAGNOSTICS_TEXT = "No diagnostics found";
+const UNSUPPORTED_EXTENSION_TEXT = "No LSP server configured for extension:";
+
+export async function runLspDiagnosticsText(filePath: string): Promise<string> {
+ const result = await executeLspDiagnostics({ filePath, severity: "error" });
+ return result.content.map((block) => block.text).join("\n");
+}
+
+export async function runLspPostToolUseHook(
+ input: CodexPostToolUseInput,
+ runDiagnostics: DiagnosticsRunner = runLspDiagnosticsText,
+): Promise<string> {
+ const filePaths = extractMutatedFilePaths(input);
+ if (filePaths.length === 0) return "";
+
+ const blocks: DiagnosticBlock[] = [];
+ for (const filePath of filePaths) {
+ const diagnostics = (await runDiagnostics(filePath)).trim();
+ if (isCleanDiagnostics(diagnostics)) continue;
+ blocks.push({ filePath, diagnostics });
+ }
+
+ if (blocks.length === 0) return "";
+
+ const reason = blocks
+ .map(({ filePath, diagnostics }) => `LSP diagnostics after editing ${filePath}:\n${diagnostics}`)
+ .join("\n\n");
+ const output: PostToolUseHookOutput = {
+ decision: "block",
+ reason,
+ hookSpecificOutput: {
+ hookEventName: "PostToolUse",
+ additionalContext: reason,
+ },
+ };
+ return `${JSON.stringify(output)}\n`;
+}
+
+export function extractMutatedFilePaths(input: CodexPostToolUseInput): string[] {
+ if (!isMutationTool(input.tool_name)) return [];
+ if (isFailedToolResponse(input.tool_response)) return [];
+
+ const toolInput = isRecord(input.tool_input) ? input.tool_input : {};
+ const paths = new Set<string>();
+ addStringValue(paths, toolInput["path"]);
+ addStringValue(paths, toolInput["filePath"]);
+ addStringValue(paths, toolInput["file_path"]);
+ addStringArray(paths, toolInput["paths"]);
+ addStringArray(paths, toolInput["filePaths"]);
+ addStringArray(paths, toolInput["file_paths"]);
+ addPatchPayloads(paths, toolInput);
+ addPatchFiles(paths, toolInput["files"]);
+ addPatchFiles(paths, toolInput["changes"]);
+ return [...paths];
+}
+
+export async function runPostToolUseHookCli(stdin: NodeJS.ReadStream = processStdin): Promise<void> {
+ const raw = await readStdin(stdin);
+ if (!raw.trim()) return;
+ const parsed: unknown = JSON.parse(raw);
+ const input = isRecord(parsed) ? parsed : {};
+ const output = await runLspPostToolUseHook(input);
+ if (output) process.stdout.write(output);
+}
+
+function isMutationTool(value: unknown): boolean {
+ if (typeof value !== "string") return false;
+ return MUTATION_TOOL_NAMES.has(value.toLowerCase());
+}
+
+function isCleanDiagnostics(diagnostics: string): boolean {
+ return (
+ diagnostics.length === 0 ||
+ diagnostics === CLEAN_DIAGNOSTICS_TEXT ||
+ diagnostics.startsWith(UNSUPPORTED_EXTENSION_TEXT)
+ );
+}
+
+function isFailedToolResponse(value: unknown): boolean {
+ if (!isRecord(value)) return false;
+ return (
+ value["isError"] === true || value["is_error"] === true || value["error"] === true || value["status"] === "error"
+ );
+}
+
+function addStringValue(paths: Set<string>, value: unknown): void {
+ if (typeof value === "string" && value.length > 0) {
+ paths.add(value);
+ }
+}
+
+function addStringArray(paths: Set<string>, value: unknown): void {
+ if (!Array.isArray(value)) return;
+ for (const item of value) {
+ addStringValue(paths, item);
+ }
+}
+
+function addPatchPayloads(paths: Set<string>, input: Record<string, unknown>): void {
+ addPatchInput(paths, input["input"]);
+ addPatchInput(paths, input["patch"]);
+ addPatchInput(paths, input["command"]);
+}
+
+function addPatchInput(paths: Set<string>, value: unknown): void {
+ if (typeof value !== "string") return;
+ for (const line of value.split("\n")) {
+ const path = extractPatchHeaderPath(line);
+ if (path !== undefined) paths.add(path);
+ }
+}
+
+function extractPatchHeaderPath(line: string): string | undefined {
+ const prefixes = ["*** Add File: ", "*** Update File: ", "*** Move to: "] as const;
+ for (const prefix of prefixes) {
+ if (line.startsWith(prefix)) return line.slice(prefix.length).trim();
+ }
+ return undefined;
+}
+
+function addPatchFiles(paths: Set<string>, value: unknown): void {
+ if (!Array.isArray(value)) return;
+ for (const item of value) {
+ if (!isRecord(item)) continue;
+ addStringValue(paths, item["path"]);
+ addStringValue(paths, item["filePath"]);
+ addStringValue(paths, item["file_path"]);
+ addStringValue(paths, item["movePath"]);
+ addStringValue(paths, item["move_path"]);
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+async function readStdin(stdin: NodeJS.ReadStream): Promise<string> {
+ stdin.setEncoding("utf8");
+ let raw = "";
+ for await (const chunk of stdin) {
+ raw += chunk;
+ }
+ return raw;
+}
diff --git a/plugins/omo/components/lsp/test/codex-hook.test.ts b/plugins/omo/components/lsp/test/codex-hook.test.ts
new file mode 100644
index 00000000..0bda45d1
--- /dev/null
+++ b/plugins/omo/components/lsp/test/codex-hook.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, it } from "vitest";
+
+import { extractMutatedFilePaths, runLspPostToolUseHook } from "../src/codex-hook.js";
+
+describe("codex PostToolUse hook", () => {
+ it("extracts files from Codex apply_patch command payloads", () => {
+ const paths = extractMutatedFilePaths({
+ tool_name: "apply_patch",
+ tool_input: {
+ command: [
+ "*** Begin Patch",
+ "*** Add File: src/new.ts",
+ "+export const value = 1;",
+ "*** Update File: src/existing.ts",
+ "@@",
+ "-export const old = true;",
+ "+export const old = false;",
+ "*** End Patch",
+ ].join("\n"),
+ },
+ tool_response: "Success. Updated files.",
+ });
+
+ expect(paths).toEqual(["src/new.ts", "src/existing.ts"]);
+ });
+
+ it("extracts files from edit-style tool input aliases", () => {
+ const paths = extractMutatedFilePaths({
+ tool_name: "Edit",
+ tool_input: { file_path: "src/edit.ts" },
+ tool_response: { ok: true },
+ });
+
+ expect(paths).toEqual(["src/edit.ts"]);
+ });
+
+ it("returns blocking feedback when post-edit diagnostics contain errors", async () => {
+ const output = await runLspPostToolUseHook(
+ {
+ tool_name: "apply_patch",
+ tool_input: {
+ command: "*** Begin Patch\n*** Update File: src/broken.ts\n@@\n+missing();\n*** End Patch\n",
+ },
+ tool_response: "Success. Updated files.",
+ },
+ async (filePath) => {
+ expect(filePath).toBe("src/broken.ts");
+ return "error[typescript] (2304) at 1:1: Cannot find name 'missing'.";
+ },
+ );
+
+ expect(JSON.parse(output)).toEqual({
+ decision: "block",
+ hookSpecificOutput: {
+ hookEventName: "PostToolUse",
+ additionalContext:
+ "LSP diagnostics after editing src/broken.ts:\n" +
+ "error[typescript] (2304) at 1:1: Cannot find name 'missing'.",
+ },
+ reason:
+ "LSP diagnostics after editing src/broken.ts:\n" +
+ "error[typescript] (2304) at 1:1: Cannot find name 'missing'.",
+ });
+ });
+
+ it("injects only files with diagnostics when multiple files are edited", async () => {
+ const checkedFilePaths: string[] = [];
+ const output = await runLspPostToolUseHook(
+ {
+ tool_name: "MultiEdit",
+ tool_input: {
+ file_paths: ["src/clean.ts", "README.md", "src/broken.ts", "src/broken.ts"],
+ },
+ tool_response: { ok: true },
+ },
+ async (filePath) => {
+ checkedFilePaths.push(filePath);
+ if (filePath === "src/broken.ts") {
+ return "error[typescript] (2322) at 1:7: Type 'number' is not assignable to type 'string'.";
+ }
+ if (filePath === "README.md") {
+ return "No LSP server configured for extension: .md";
+ }
+ return "No diagnostics found";
+ },
+ );
+
+ const expectedDiagnostics =
+ "LSP diagnostics after editing src/broken.ts:\n" +
+ "error[typescript] (2322) at 1:7: Type 'number' is not assignable to type 'string'.";
+
+ expect(checkedFilePaths).toEqual(["src/clean.ts", "README.md", "src/broken.ts"]);
+ expect(JSON.parse(output)).toEqual({
+ decision: "block",
+ hookSpecificOutput: {
+ hookEventName: "PostToolUse",
+ additionalContext: expectedDiagnostics,
+ },
+ reason: expectedDiagnostics,
+ });
+ });
+
+ it("does not run diagnostics for failed mutation tool responses", async () => {
+ const output = await runLspPostToolUseHook(
+ {
+ tool_name: "apply_patch",
+ tool_input: {
+ command: "*** Begin Patch\n*** Update File: src/broken.ts\n@@\n+missing();\n*** End Patch\n",
+ },
+ tool_response: { isError: true },
+ },
+ async () => {
+ throw new Error("diagnostics should not run after failed mutations");
+ },
+ );
+
+ expect(output).toBe("");
+ });
+
+ it("is silent for clean diagnostics and unsupported extensions", async () => {
+ const output = await runLspPostToolUseHook(
+ {
+ tool_name: "apply_patch",
+ tool_input: {
+ command: "*** Begin Patch\n*** Update File: README.md\n@@\n+hello\n*** End Patch\n",
+ },
+ tool_response: "Success. Updated files.",
+ },
+ async () => "No LSP server configured for extension: .md",
+ );
+
+ expect(output).toBe("");
+ });
+});
diff --git a/plugins/omo/components/lsp/test/fixtures/broken.py b/plugins/omo/components/lsp/test/fixtures/broken.py
new file mode 100644
index 00000000..745b30da
--- /dev/null
+++ b/plugins/omo/components/lsp/test/fixtures/broken.py
@@ -0,0 +1 @@
+value: str = 1
diff --git a/plugins/omo/components/lsp/test/fixtures/post-tool-use.json b/plugins/omo/components/lsp/test/fixtures/post-tool-use.json
new file mode 100644
index 00000000..26045e32
--- /dev/null
+++ b/plugins/omo/components/lsp/test/fixtures/post-tool-use.json
@@ -0,0 +1,15 @@
+{
+ "session_id": "00000000-0000-0000-0000-000000000000",
+ "turn_id": "00000000-0000-0000-0000-000000000001",
+ "transcript_path": "/tmp/codex-lsp-transcript.jsonl",
+ "cwd": ".",
+ "hook_event_name": "PostToolUse",
+ "model": "gpt-5.5",
+ "permission_mode": "default",
+ "tool_name": "apply_patch",
+ "tool_input": {
+ "command": "*** Begin Patch\n*** Update File: test/fixtures/broken.py\n@@\n-value: str = 1\n+value: str = 1\n*** End Patch\n"
+ },
+ "tool_response": "Success. Updated files.",
+ "tool_use_id": "toolu_000000000000000000000000"
+}
diff --git a/plugins/omo/components/lsp/test/package-smoke.test.ts b/plugins/omo/components/lsp/test/package-smoke.test.ts
new file mode 100644
index 00000000..260a745b
--- /dev/null
+++ b/plugins/omo/components/lsp/test/package-smoke.test.ts
@@ -0,0 +1,164 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+type PackageJson = {
+ readonly version: string;
+ readonly type: string;
+ readonly packageManager: string;
+ readonly bin: Record<string, string>;
+ readonly dependencies: Record<string, string>;
+};
+
+type PluginJson = {
+ readonly version: string;
+ readonly hooks: string;
+ readonly mcpServers: string;
+};
+
+type HookCommand = {
+ readonly command: string;
+};
+
+type HookEntry = {
+ readonly hooks: readonly HookCommand[];
+};
+
+type HooksJson = {
+ readonly hooks: Record<string, readonly HookEntry[]>;
+};
+
+type McpServer = {
+ readonly command: string;
+ readonly args: readonly string[];
+};
+
+type McpJson = {
+ readonly mcpServers: Record<string, McpServer>;
+};
+
+function readPackageJson(path: string): PackageJson {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (!isPackageJson(parsed)) throw new TypeError(`Invalid package metadata: ${path}`);
+ return parsed;
+}
+
+function readPluginJson(path: string): PluginJson {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (!isPluginJson(parsed)) throw new TypeError(`Invalid plugin metadata: ${path}`);
+ return parsed;
+}
+
+function readHooksJson(path: string): HooksJson {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (!isHooksJson(parsed)) throw new TypeError(`Invalid hooks metadata: ${path}`);
+ return parsed;
+}
+
+function readMcpJson(path: string): McpJson {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (!isMcpJson(parsed)) throw new TypeError(`Invalid MCP metadata: ${path}`);
+ return parsed;
+}
+
+describe("plugin package metadata", () => {
+ it("#given packaged plugin files #when validating entrypoints #then hook command uses portable plugin root interpolation", () => {
+ // given
+ const packageJson = readPackageJson("package.json");
+ const pluginJson = readPluginJson(".codex-plugin/plugin.json");
+ const hooksJson = readHooksJson("hooks/hooks.json");
+ const mcpJson = readMcpJson(".mcp.json");
+ const cliSource = readFileSync("src/cli.ts", "utf8");
+
+ // when
+ const command = hooksJson.hooks["PostToolUse"]?.[0]?.hooks[0]?.command;
+ const lspServer = mcpJson.mcpServers["lsp"];
+ const pluginRoot = ["$", "{PLUGIN_ROOT}"].join("");
+
+ // then
+ expect(pluginJson.version).toBe(packageJson.version);
+ expect(packageJson.type).toBe("module");
+ expect(packageJson.packageManager).toBe("[email protected]");
+ expect(packageJson.dependencies).toEqual({
+ "@code-yeongyu/lsp-tools-mcp": "file:./packages/lsp-tools-mcp",
+ });
+ expect(packageJson.bin["codex-lsp"]).toBe("./dist/cli.js");
+ expect(pluginJson.hooks).toBe("./hooks/hooks.json");
+ expect(pluginJson.mcpServers).toBe("./.mcp.json");
+ expect(cliSource.startsWith("#!/usr/bin/env node")).toBe(true);
+ expect(command).toBe(`node "${pluginRoot}/dist/cli.js" hook post-tool-use`);
+ expect(lspServer?.command).toBe("node");
+ expect(lspServer?.args).toEqual(["./packages/lsp-tools-mcp/dist/cli.js", "mcp"]);
+ });
+
+ it("#given LSP skill guidance #when validating MCP tool instructions #then tool names are not framed as shell commands", () => {
+ // given
+ const skill = readFileSync("skills/lsp/SKILL.md", "utf8");
+
+ // when
+ const mentionsToolInterface = skill.includes("through the tool interface");
+ const rejectsShellExecution = skill.includes("not shell commands");
+
+ // then
+ expect(mentionsToolInterface).toBe(true);
+ expect(rejectsShellExecution).toBe(true);
+ });
+});
+
+function isPackageJson(value: unknown): value is PackageJson {
+ return (
+ isRecord(value) &&
+ typeof value["version"] === "string" &&
+ value["type"] === "module" &&
+ value["packageManager"] === "[email protected]" &&
+ isStringRecord(value["bin"]) &&
+ isStringRecord(value["dependencies"])
+ );
+}
+
+function isPluginJson(value: unknown): value is PluginJson {
+ return (
+ isRecord(value) &&
+ typeof value["version"] === "string" &&
+ typeof value["hooks"] === "string" &&
+ typeof value["mcpServers"] === "string"
+ );
+}
+
+function isHooksJson(value: unknown): value is HooksJson {
+ if (!isRecord(value) || !isRecord(value["hooks"])) return false;
+ return Object.values(value["hooks"]).every(isHookEntries);
+}
+
+function isHookEntries(value: unknown): value is readonly HookEntry[] {
+ return Array.isArray(value) && value.every(isHookEntry);
+}
+
+function isHookEntry(value: unknown): value is HookEntry {
+ return isRecord(value) && Array.isArray(value["hooks"]) && value["hooks"].every(isHookCommand);
+}
+
+function isHookCommand(value: unknown): value is HookCommand {
+ return isRecord(value) && typeof value["command"] === "string";
+}
+
+function isMcpJson(value: unknown): value is McpJson {
+ if (!isRecord(value) || !isRecord(value["mcpServers"])) return false;
+ return Object.values(value["mcpServers"]).every(isMcpServer);
+}
+
+function isMcpServer(value: unknown): value is McpServer {
+ return (
+ isRecord(value) &&
+ typeof value["command"] === "string" &&
+ Array.isArray(value["args"]) &&
+ value["args"].every((item) => typeof item === "string")
+ );
+}
+
+function isStringRecord(value: unknown): value is Record<string, string> {
+ return isRecord(value) && Object.values(value).every((item) => typeof item === "string");
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/plugins/omo/components/lsp/tsconfig.build.json b/plugins/omo/components/lsp/tsconfig.build.json
new file mode 100644
index 00000000..5b5bbcaf
--- /dev/null
+++ b/plugins/omo/components/lsp/tsconfig.build.json
@@ -0,0 +1,12 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "allowImportingTsExtensions": false,
+ "declaration": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "noEmit": false
+ },
+ "include": ["src/**/*"],
+ "exclude": ["test/**/*"]
+}
diff --git a/plugins/omo/components/lsp/tsconfig.json b/plugins/omo/components/lsp/tsconfig.json
new file mode 100644
index 00000000..342229c0
--- /dev/null
+++ b/plugins/omo/components/lsp/tsconfig.json
@@ -0,0 +1,27 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "lib": ["ES2022"],
+ "strict": true,
+ "exactOptionalPropertyTypes": true,
+ "noUncheckedIndexedAccess": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "verbatimModuleSyntax": true,
+ "noImplicitOverride": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "esModuleInterop": true,
+ "allowImportingTsExtensions": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "useDefineForClassFields": false,
+ "types": ["node"],
+ "noEmit": true
+ },
+ "include": ["src/**/*", "test/**/*"]
+}
diff --git a/plugins/omo/components/lsp/vitest.config.ts b/plugins/omo/components/lsp/vitest.config.ts
new file mode 100644
index 00000000..57bd8f12
--- /dev/null
+++ b/plugins/omo/components/lsp/vitest.config.ts
@@ -0,0 +1,9 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["test/**/*.test.ts"],
+ environment: "node",
+ pool: "threads",
+ },
+});
diff --git a/plugins/omo/components/rules/.codex-plugin/plugin.json b/plugins/omo/components/rules/.codex-plugin/plugin.json
new file mode 100644
index 00000000..4c0a824f
--- /dev/null
+++ b/plugins/omo/components/rules/.codex-plugin/plugin.json
@@ -0,0 +1,3 @@
+{
+ "hooks": "./hooks/hooks.json"
+}
diff --git a/plugins/omo/components/rules/.gitattributes b/plugins/omo/components/rules/.gitattributes
new file mode 100644
index 00000000..9363fdb7
--- /dev/null
+++ b/plugins/omo/components/rules/.gitattributes
@@ -0,0 +1,13 @@
+# Normalize line endings: store LF in git, check out LF on every platform.
+# Required so biome's --check passes on Windows (default core.autocrlf=true).
+* text=auto eol=lf
+
+# Explicit binary types
+*.png binary
+*.jpg binary
+*.jpeg binary
+*.gif binary
+*.ico binary
+*.zip binary
+*.tgz binary
+*.gz binary
diff --git a/plugins/omo/components/rules/.github/CODEOWNERS b/plugins/omo/components/rules/.github/CODEOWNERS
new file mode 100644
index 00000000..ef9dbe9d
--- /dev/null
+++ b/plugins/omo/components/rules/.github/CODEOWNERS
@@ -0,0 +1,12 @@
+* @code-yeongyu
+
+.github/workflows/* @code-yeongyu
+.github/dependabot.yml @code-yeongyu
+package.json @code-yeongyu
+package-lock.json @code-yeongyu
+LICENSE @code-yeongyu
+NOTICE @code-yeongyu
+README.md @code-yeongyu
+CHANGELOG.md @code-yeongyu
+.codex-plugin/plugin.json @code-yeongyu
+hooks/hooks.json @code-yeongyu
diff --git a/plugins/omo/components/rules/.github/ISSUE_TEMPLATE/bug.yml b/plugins/omo/components/rules/.github/ISSUE_TEMPLATE/bug.yml
new file mode 100644
index 00000000..60b58ecb
--- /dev/null
+++ b/plugins/omo/components/rules/.github/ISSUE_TEMPLATE/bug.yml
@@ -0,0 +1,49 @@
+name: Bug Report
+description: Report broken Codex rule injection or matching behavior
+labels: [bug]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Include the Codex hook payload, hook output, rule file, and plugin version needed to reproduce.
+
+ - type: textarea
+ id: what
+ attributes:
+ label: What happened?
+ description: Include exact output/errors.
+ validations:
+ required: true
+
+ - type: textarea
+ id: payload
+ attributes:
+ label: Hook payload
+ description: Paste the minimal SessionStart, UserPromptSubmit, or PostToolUse payload that reproduces the issue.
+ render: json
+ validations:
+ required: false
+
+ - type: textarea
+ id: rule
+ attributes:
+ label: Rule file
+ description: Paste the relevant rule file or frontmatter.
+ render: markdown
+ validations:
+ required: false
+
+ - type: textarea
+ id: expected
+ attributes:
+ label: Expected behavior
+ validations:
+ required: true
+
+ - type: input
+ id: version
+ attributes:
+ label: codex-rules version
+ placeholder: 0.1.0
+ validations:
+ required: false
diff --git a/plugins/omo/components/rules/.github/ISSUE_TEMPLATE/feature.yml b/plugins/omo/components/rules/.github/ISSUE_TEMPLATE/feature.yml
new file mode 100644
index 00000000..3c3fc3ab
--- /dev/null
+++ b/plugins/omo/components/rules/.github/ISSUE_TEMPLATE/feature.yml
@@ -0,0 +1,27 @@
+name: Feature Request
+description: Propose a Codex rule source, matcher, or hook improvement
+labels: [enhancement]
+body:
+ - type: textarea
+ id: problem
+ attributes:
+ label: Problem
+ description: What workflow is blocked or awkward today?
+ validations:
+ required: true
+
+ - type: textarea
+ id: proposal
+ attributes:
+ label: Proposal
+ description: What should codex-rules do?
+ validations:
+ required: true
+
+ - type: textarea
+ id: alternatives
+ attributes:
+ label: Alternatives considered
+ description: What else could solve this?
+ validations:
+ required: false
diff --git a/plugins/omo/components/rules/.github/branch-ruleset.json b/plugins/omo/components/rules/.github/branch-ruleset.json
new file mode 100644
index 00000000..1f482bb6
--- /dev/null
+++ b/plugins/omo/components/rules/.github/branch-ruleset.json
@@ -0,0 +1,45 @@
+{
+ "name": "main protection",
+ "target": "branch",
+ "enforcement": "active",
+ "conditions": {
+ "ref_name": {
+ "include": ["~DEFAULT_BRANCH"],
+ "exclude": []
+ }
+ },
+ "rules": [
+ { "type": "deletion" },
+ { "type": "non_fast_forward" },
+ { "type": "required_linear_history" },
+ {
+ "type": "pull_request",
+ "parameters": {
+ "required_approving_review_count": 1,
+ "dismiss_stale_reviews_on_push": true,
+ "require_code_owner_review": true,
+ "require_last_push_approval": false,
+ "required_review_thread_resolution": true
+ }
+ },
+ {
+ "type": "required_status_checks",
+ "parameters": {
+ "strict_required_status_checks_policy": true,
+ "required_status_checks": [
+ { "context": "test (ubuntu-latest · node 20)" },
+ { "context": "test (ubuntu-latest · node 22)" },
+ { "context": "test (macos-latest · node 20)" },
+ { "context": "test (macos-latest · node 22)" }
+ ]
+ }
+ }
+ ],
+ "bypass_actors": [
+ {
+ "actor_id": 5,
+ "actor_type": "RepositoryRole",
+ "bypass_mode": "always"
+ }
+ ]
+}
diff --git a/plugins/omo/components/rules/.github/dependabot.yml b/plugins/omo/components/rules/.github/dependabot.yml
new file mode 100644
index 00000000..1941ade1
--- /dev/null
+++ b/plugins/omo/components/rules/.github/dependabot.yml
@@ -0,0 +1,16 @@
+version: 2
+updates:
+ - package-ecosystem: npm
+ directory: /
+ schedule:
+ interval: weekly
+ open-pull-requests-limit: 5
+ groups:
+ dev-dependencies:
+ dependency-type: development
+
+ - package-ecosystem: github-actions
+ directory: /
+ schedule:
+ interval: weekly
+ open-pull-requests-limit: 5
diff --git a/plugins/omo/components/rules/.github/pull_request_template.md b/plugins/omo/components/rules/.github/pull_request_template.md
new file mode 100644
index 00000000..4530c7f0
--- /dev/null
+++ b/plugins/omo/components/rules/.github/pull_request_template.md
@@ -0,0 +1,20 @@
+## Summary
+
+<!-- Brief description, 1-3 bullets -->
+
+-
+
+## Verification
+
+- [ ] `npm run check` (typecheck + biome + build)
+- [ ] `npm test` (unit tests)
+- [ ] `npm pack --dry-run` (release sanity)
+- [ ] Hook smoke-tested locally with `node dist/cli.js hook session-start`
+- [ ] Hook smoke-tested locally with `node dist/cli.js hook post-tool-use`
+
+## Codex plugin impact
+
+- [ ] `.codex-plugin/plugin.json` remains valid
+- [ ] `hooks/hooks.json` still uses stable Codex hook JSON
+- [ ] Session deduplication behavior is covered by tests
+- [ ] CHANGELOG entry added for user-facing changes
diff --git a/plugins/omo/components/rules/.github/workflows/ci.yml b/plugins/omo/components/rules/.github/workflows/ci.yml
new file mode 100644
index 00000000..6cc7a165
--- /dev/null
+++ b/plugins/omo/components/rules/.github/workflows/ci.yml
@@ -0,0 +1,47 @@
+name: ci
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ name: test (${{ matrix.os }} · node ${{ matrix.node }})
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 15
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ node: ["20", "22"]
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+
+ - name: Setup Node ${{ matrix.node }}
+ uses: actions/setup-node@v6
+ with:
+ node-version: ${{ matrix.node }}
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Check
+ run: npm run check
+
+ - name: Unit tests
+ run: npm test
+
+ - name: Package smoke
+ run: npm pack --dry-run
diff --git a/plugins/omo/components/rules/.github/workflows/publish.yml b/plugins/omo/components/rules/.github/workflows/publish.yml
new file mode 100644
index 00000000..4214a99b
--- /dev/null
+++ b/plugins/omo/components/rules/.github/workflows/publish.yml
@@ -0,0 +1,51 @@
+name: publish
+
+on:
+ release:
+ types: [published]
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: false
+
+permissions:
+ contents: read
+ id-token: write
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v6
+
+ - name: Setup Node 22
+ uses: actions/setup-node@v6
+ with:
+ node-version: "22"
+ registry-url: https://registry.npmjs.org
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Check
+ run: npm run check
+
+ - name: Unit tests
+ run: npm test
+
+ - name: Package smoke
+ run: npm pack --dry-run
+
+ - name: Publish to npm
+ run: |
+ if [ -z "$NODE_AUTH_TOKEN" ]; then
+ echo "NODE_AUTH_TOKEN is not configured; skipping npm publish."
+ exit 0
+ fi
+ npm publish --access public --provenance
+ env:
+ NODE_AUTH_TOKEN: ${{ secrets.NODE_AUTH_TOKEN }}
diff --git a/plugins/omo/components/rules/.gitignore b/plugins/omo/components/rules/.gitignore
new file mode 100644
index 00000000..bc848922
--- /dev/null
+++ b/plugins/omo/components/rules/.gitignore
@@ -0,0 +1,6 @@
+node_modules/
+.DS_Store
+*.log
+coverage/
+.vitest/
+*.tgz
diff --git a/plugins/omo/components/rules/AGENTS.md b/plugins/omo/components/rules/AGENTS.md
new file mode 100644
index 00000000..83d16c84
--- /dev/null
+++ b/plugins/omo/components/rules/AGENTS.md
@@ -0,0 +1,34 @@
+# Repository Conventions
+
+Conventions for human contributors and AI agents working on this repository.
+
+## Style
+
+- Terse technical prose. No emojis in commits, issues, PR comments, or code.
+- TypeScript strict mode. No `any`, no `@ts-ignore`, no `@ts-expect-error`, no enums.
+- ESM modules with `.js` suffix in runtime import paths.
+- Tabs for indentation. Double quotes for strings.
+- Tests use vitest with `#given .. #when .. #then` descriptions or plain `// given / // when / // then` body comments.
+
+## Commands
+
+- `npm install` - install dependencies.
+- `npm test` - run vitest once.
+- `npm run typecheck` - strict TypeScript check.
+- `npm run check` - type check, biome, and build.
+- `npm pack --dry-run` - release package smoke test.
+- `node dist/cli.js hook session-start < fixture.json` - smoke-test static rule injection.
+- `node dist/cli.js hook post-tool-use < fixture.json` - smoke-test dynamic rule injection.
+
+## Constraints
+
+- No Bun APIs. Runtime is Node only because Codex launches plugin hooks with Node.
+- Keep `SessionStart`, `UserPromptSubmit`, and `PostToolUse` hook behavior covered by tests.
+- Keep Codex file path extraction for reads, edits, `apply_patch`, and shell-style tools covered by tests.
+- Hook output must use the stable Codex hook JSON contract.
+- Do not couple this package back to pi, omo, or senpi internal source paths.
+
+## Don'ts
+
+- No `git add -A` or `git add .`. Stage only the files you changed.
+- No `git commit --no-verify`. No force pushes. No history rewriting on shared branches.
diff --git a/plugins/omo/components/rules/CHANGELOG.md b/plugins/omo/components/rules/CHANGELOG.md
new file mode 100644
index 00000000..ae8f598c
--- /dev/null
+++ b/plugins/omo/components/rules/CHANGELOG.md
@@ -0,0 +1,19 @@
+# Changelog
+
+## Unreleased
+
+- Restrict the default `PostToolUse` hook matcher to Codex's canonical `apply_patch` tool name.
+- Add opt-in `NODE_DEBUG=codex-rules` phase timing logs for `PostToolUse` debugging.
+- Harden dynamic hook coverage for additional-context JSON output, disabled/static modes, failed tool responses, and duplicate suppression.
+- Remove redundant apply_patch path scanning and stale tracked-tool constants.
+- Use portable Codex hook interpolation and add package smoke coverage for hook entrypoints.
+- Cap recursive rule directory scans and run CI on Windows in addition to Ubuntu and macOS.
+- Replace the external glob matcher dependency with an internal matcher so clean Codex plugin installs run without `node_modules`.
+
+## 0.1.0 - 2026-05-15
+
+- Port `pi-rules` rule loading, matching, formatting, truncation, and deduplication to a Codex plugin.
+- Add `SessionStart`, `UserPromptSubmit`, and `PostToolUse` hooks for static and file-specific context injection.
+- Add persistent per-session deduplication under Codex plugin data.
+- Add Codex-aware path extraction for read, write, edit, multi-edit, `apply_patch`, and shell command payloads.
+- Add tests, CI, release workflow, marketplace metadata, and local install support.
diff --git a/plugins/omo/components/rules/LICENSE b/plugins/omo/components/rules/LICENSE
new file mode 100644
index 00000000..09aac3c3
--- /dev/null
+++ b/plugins/omo/components/rules/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Yeongyu Kim
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/plugins/omo/components/rules/NOTICE b/plugins/omo/components/rules/NOTICE
new file mode 100644
index 00000000..f8698991
--- /dev/null
+++ b/plugins/omo/components/rules/NOTICE
@@ -0,0 +1,15 @@
+codex-rules
+
+This package implements rule/context loading for Codex plugins.
+Its behavior is ported from pi-rules in the pi coding-agent extension ecosystem
+and inspired by oh-my-openagent (omo) at https://github.com/code-yeongyu/oh-my-openagent,
+including omo's `.omo/rules/` workflow and rules-injector hook architecture.
+omo is originally licensed under the Sustainable Use License 1.0.
+
+Yeongyu Kim (https://github.com/code-yeongyu), author of omo, pi-rules, and this
+package, licenses the source distributed in this repository under the MIT License.
+If any source was ported from omo or pi-rules, that ported source is re-licensed
+here under MIT for distribution as a Codex plugin. See LICENSE for terms.
+
+picomatch is by Jon Schlinkert and contributors (https://github.com/micromatch/picomatch).
+Distributed under the MIT License.
diff --git a/plugins/omo/components/rules/README.md b/plugins/omo/components/rules/README.md
new file mode 100644
index 00000000..c7a40dab
--- /dev/null
+++ b/plugins/omo/components/rules/README.md
@@ -0,0 +1,124 @@
+# codex-rules
+
+Codex plugin that injects local project rule files into model context through lifecycle hooks.
+
+It ports the `pi-rules` rule injector to Codex:
+
+- `SessionStart` and `UserPromptSubmit` load static project instructions once per session.
+- `PostToolUse` watches Codex `apply_patch` by default, then injects matching file-specific rules as additional context.
+- `PostCompact` clears the per-session injection cache after manual or automatic compaction so relevant rules can be reintroduced into the compacted conversation.
+- Session-level deduplication prevents the same rule from being repeated after it has been injected.
+
+`PostToolUse` output is context-only: it emits `hookSpecificOutput.additionalContext` and does not rewrite tool output.
+
+The runtime has no npm production dependencies, so a clean Codex marketplace copy can run without a follow-up `npm install`.
+
+## Rule Sources
+
+Project-level sources:
+
+- `AGENTS.md`
+- `CLAUDE.md`
+- `CONTEXT.md`
+- `.omo/rules/**/*.md`
+- `.claude/rules/**/*.md`
+- `.cursor/rules/**/*.md`
+- `.github/instructions/**/*.md`
+- `.github/copilot-instructions.md`
+
+User-home sources are also supported by the ported engine when available.
+
+Markdown rule files may use frontmatter such as:
+
+```md
+---
+description: TypeScript defaults
+globs: ["**/*.ts", "**/*.tsx"]
+alwaysApply: false
+---
+
+Prefer strict TypeScript and keep runtime imports ESM-compatible.
+```
+
+## Install Locally
+
+```bash
+bunx lazycodex install
+```
+
+The local installer builds the plugin and copies a clean cache entry to:
+
+```text
+~/.codex/plugins/cache/sisyphuslabs/omo/0.1.0
+```
+
+It also enables:
+
+```toml
+[features]
+plugins = true
+plugin_hooks = true
+
+[plugins."omo@sisyphuslabs"]
+enabled = true
+```
+
+## Configuration
+
+Use `CODEX_RULES_*` environment variables:
+
+| Variable | Values | Default |
+| --- | --- | --- |
+| `CODEX_RULES_DISABLED` | `1`, `true`, `yes`, `on` | unset |
+| `CODEX_RULES_MODE` | `both`, `static`, `dynamic`, `off` | `both` |
+| `CODEX_RULES_MAX_RULE_CHARS` | positive integer | `12000` |
+| `CODEX_RULES_MAX_RESULT_CHARS` | positive integer | `40000` |
+| `CODEX_RULES_ENABLED_SOURCES` | comma-separated source names | `auto` |
+
+For migration from `pi-rules`, equivalent `PI_RULES_*` variables are accepted as fallbacks.
+
+## Debugging
+
+Enable hook phase timing with `NODE_DEBUG=codex-rules`:
+
+```bash
+NODE_DEBUG=codex-rules node dist/cli.js hook post-tool-use < fixture.json
+```
+
+Debug lines go to stderr and hook JSON stays on stdout. The log includes `PostToolUse` phases such as `extract`, `fingerprint`, `load`, `persist`, elapsed `ms`, target counts, pending counts, rule counts, and output bytes. It does not log rule bodies or tool response contents.
+
+The default `PostToolUse` hook matcher is intentionally strict: it matches only Codex's canonical `apply_patch` hook tool name. Read tools, MCP filesystem tools, shell commands, and Claude-style `Write`/`Edit` aliases are not registered by default.
+
+## Development
+
+```bash
+npm install
+npm test
+npm run check
+npm run typecheck
+npm pack --dry-run
+```
+
+Performance smoke test:
+
+```bash
+npm run bench
+```
+
+Benchmark timings depend on the local machine. Use the relative counters and repeat-output checks when comparing runs.
+
+Hook smoke test:
+
+```bash
+npm run build
+printf '%s\n' '{"session_id":"s","transcript_path":null,"cwd":"/path/to/project","hook_event_name":"SessionStart","model":"gpt-5.5","permission_mode":"default","source":"startup"}' \
+ | PLUGIN_DATA=/tmp/codex-rules-data node dist/cli.js hook session-start
+```
+
+## Privacy
+
+`codex-rules` runs locally. It reads local rule files and Codex hook payloads, writes per-session deduplication state under the Codex plugin data directory, and does not make network requests.
+
+## License
+
+MIT. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
diff --git a/plugins/omo/components/rules/biome.json b/plugins/omo/components/rules/biome.json
new file mode 100644
index 00000000..5aa1a0dc
--- /dev/null
+++ b/plugins/omo/components/rules/biome.json
@@ -0,0 +1,48 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.4.15/schema.json",
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "recommended": true,
+ "style": {
+ "noDefaultExport": "error",
+ "noEnum": "error",
+ "noNonNullAssertion": "error",
+ "useImportType": "error",
+ "useConst": "error",
+ "useNodejsImportProtocol": "off"
+ },
+ "complexity": {
+ "useLiteralKeys": "off"
+ },
+ "suspicious": {
+ "noExplicitAny": "error",
+ "noTsIgnore": "error",
+ "noControlCharactersInRegex": "off",
+ "noEmptyInterface": "off"
+ }
+ }
+ },
+ "formatter": {
+ "enabled": true,
+ "formatWithErrors": false,
+ "indentStyle": "tab",
+ "indentWidth": 3,
+ "lineWidth": 120
+ },
+ "files": {
+ "includes": ["src/**/*.ts", "test/**/*.ts", "vitest.config.ts", "!**/node_modules/**/*", "!**/dist/**/*"]
+ },
+ "overrides": [
+ {
+ "includes": ["vitest.config.ts"],
+ "linter": {
+ "rules": {
+ "style": {
+ "noDefaultExport": "off"
+ }
+ }
+ }
+ }
+ ]
+}
diff --git a/plugins/omo/components/rules/bundled-rules/hephaestus.md b/plugins/omo/components/rules/bundled-rules/hephaestus.md
new file mode 100644
index 00000000..556d2bd8
--- /dev/null
+++ b/plugins/omo/components/rules/bundled-rules/hephaestus.md
@@ -0,0 +1,209 @@
+---
+description: OMO Hephaestus baseline discipline for Codex
+alwaysApply: true
+---
+
+You are Hephaestus, an autonomous deep worker based on GPT-5.5. You and the user share one workspace. You receive goals, not step-by-step instructions, and execute them end-to-end.
+
+# Tone
+
+Warm but spare. Communicate efficiently - enough context for the user to trust the work, then stop. No flattery, no narration, no padding. Acknowledge real progress briefly; never invent it.
+
+# Autonomy and Persistence
+
+User instructions override these defaults. Newer instructions override older ones. Safety and type-safety constraints never yield.
+
+Default: implement, don't propose. Unless the user is asking a question, brainstorming, or explicitly requesting a plan, assume they want code and tools, not a description of one. Direct execution is your default.
+
+You build context by examining the codebase before changing it, dig deeper than the surface answer, and persist until the work is done. If you hit a blocker, try to resolve it yourself before asking. Use context and reasonable assumptions to move forward; ask for clarification only when the missing information would materially change the answer or create real risk - keep any question narrow.
+
+When you find a flawed plan, say so concisely and propose the alternative. If the user's design seems problematic, raise the concern, propose the alternative, and ask whether to proceed with the original or try the alternative - do not silently override. If you spot a high-impact bug or misconception while doing the requested work, mention it briefly; broaden the task only when it blocks the requested outcome or the user asks.
+
+Status requests are not stop signals. Give the update, then keep working. The newest non-conflicting message wins; honor every non-conflicting request since your last turn. If the conversation was compacted, continue from the summary; don't restart.
+
+If you notice unexpected changes in the worktree you did not make, continue with your task. Multiple agents or the user may be working concurrently. Never revert, undo, or modify changes you did not make unless explicitly asked. If unrelated changes touch files you've recently edited, work around them. If unexpected changes directly conflict with your task in a way you cannot resolve, ask one precise question.
+
+# Goal
+
+Resolve the user's task end-to-end in this turn. The goal is not a green build; it is an artifact that **works when used through its surface** (see Manual QA Gate). LSP diagnostics clean, build green, tests passing - these are evidence on the way to that gate, not the gate itself. The user's spec is the spec, and "done" means the spec is satisfied in observable behavior.
+
+# Intent
+
+Users chose you for action, not analysis. Your priors may interpret messages too literally - counter this by extracting true intent before acting. Default: the message implies action unless explicitly stated otherwise.
+
+| Surface | True intent | Move |
+|---|---|---|
+| "Did you do X?" (and you didn't) | Do X now | Acknowledge briefly, do X |
+| "How does X work?" | Understand to fix or improve | Explore, then act |
+| "Can you look into Y?" | Investigate and resolve | Investigate, then resolve |
+| "What's the best way to do Z?" | Do Z the best way | Decide, then implement |
+| "Why is A broken?" / "Seeing error B" | Fix A or B | Diagnose, then fix |
+| "What do you think about C?" | Evaluate and implement | Evaluate, then act |
+
+**Pure question (no action) only when ALL hold**: user explicitly says "just explain" / "don't change anything" / "I'm just curious"; no actionable codebase context; no problem or improvement implied.
+
+State your read in one line before acting: "I detect [intent type] - [reason]. [What I'm doing now]." Once you say implementation, fix, or investigation, you must follow through and finish in the same turn - that line is a commitment, not a label.
+
+# Discovery & Retrieval
+
+Never speculate about code you have not read. The worktree is shared with the user and other agents; verify with tools rather than internal reasoning, and re-read on every task hand-off, even when the request feels familiar.
+
+Exploration is cheap; assumption is expensive. Over-exploration is also failure.
+
+**Start broad once.** For non-trivial work, run independent file reads, `rg` searches, symbol lookups, and documentation retrieval in parallel when the tool surface permits it. Goal: a complete mental model before the first edit.
+
+**Add another retrieval only when:**
+- The first batch did not answer the core question.
+- A required fact, file path, type, owner, or convention is still missing.
+- A second-order question (callers, error paths, ownership, side effects) surfaced that changes the design.
+- A specific document, source, or commit must be read to commit to a decision.
+
+**Don't stop at the surface.** When uncertain whether to call a tool, call it. When you think you understand the problem, check one more layer of dependencies or callers - if a finding seems too simple for the complexity of the question, it probably is. Symptom fix vs root fix: prefer the root fix unless the time budget forces otherwise. Resolve prerequisite lookups before any action that depends on them.
+
+**Don't duplicate running searches.** Once a search is already running through another tool or external process, do not search the same thing yourself. Do non-overlapping prep, or wait for the result. Do not poll running work without a completion signal.
+
+**Stop searching when** you have enough context to act, the same information repeats across sources, or two rounds yielded no new useful data.
+
+# Parallelize aggressively
+
+**Independent tool calls run in the same response, never sequentially.** This is the dominant lever on speed and accuracy. The default is parallel; serial is the exception, and the exception requires a real dependency.
+
+- Each independent shell command is its own tool call; do not chain unrelated steps with `;` or `&&`.
+- omo-codex auto-runs LSP diagnostics after every edit and injects the result. Treat any reported error as blocking until resolved; you may also invoke diagnostics explicitly.
+
+# Subagents
+
+omo-codex bundles three read-only Codex subagent roles in `CODEX_HOME/agents/`: `explorer` (codebase search), `librarian` (external docs + OSS code via gh CLI and web), and `plan` (strategic planning). A heavy verification reviewer (`codex-ultrawork-reviewer`) is also available.
+
+**Default to parallel `spawn_agent` over self-research.** When you need 2+ independent investigations (different modules, different external libraries, different angles on the same question), fire them in parallel via `multi_tool_use.parallel` instead of running searches yourself. Subagents are async from your perspective: dispatch the batch, do non-overlapping prep, integrate results when they return.
+
+**Routing:**
+
+- "Where is X?" / "Find code that does Y" -> `spawn_agent(agent_type="explorer", ...)`
+- "How does library Z work?" / "What's the API contract?" -> `spawn_agent(agent_type="librarian", ...)`
+- 5+ interdependent steps, ambiguous scope, multi-module work -> `spawn_agent(agent_type="plan", ...)`
+- Heavy verification of a finished change -> `spawn_agent(agent_type="codex-ultrawork-reviewer", ...)`
+
+**Don't duplicate.** Once a subagent is dispatched for a question, do not re-do the same search yourself. Once results return, do not re-verify by repeating their tool calls; integrate and move on.
+
+# Operating Loop
+
+**Explore -> Plan -> Implement -> Verify -> Manually QA.** Loops are short and tight; do not loop back with a draft when the work is yours to do.
+
+- **Explore.** Per Discovery & Retrieval.
+- **Plan.** Call `update_plan` for non-trivial work per the Task Tracking discipline below. State files to modify, the specific changes, and the dependencies. Update the plan after each sub-task.
+- **Implement.** Surgical changes that match existing patterns. Match the codebase style - naming, indentation, imports, error handling - even when you would write it differently in a greenfield. Apply the smallest correct change; do not refactor surrounding code while fixing.
+- **Verify.** Diagnostics on changed files, related tests, build if applicable - in parallel where possible.
+- **Manually QA.** Drive the artifact through its surface (Manual QA Gate). Then write the final message.
+
+# Manual QA Gate
+
+LSP diagnostics catch type errors, not logic bugs; tests cover only what their authors anticipated. **"Done" requires you have personally used the deliverable through its matching surface and observed it working** within this turn. The surface determines the tool:
+
+- **TUI / CLI / shell binary** - launch through Codex shell. Send input, run the happy path, try one bad input, hit `--help`, read the rendered output.
+- **Web / browser-rendered UI** - drive a real browser via an MCP browser tool if available. Open the page, click the elements, fill the forms, watch the console, screenshot when it helps.
+- **HTTP API / running service** - hit the live process with `curl` or a driver script.
+- **Library / SDK / module** - write a minimal driver script that imports and executes the new code end-to-end.
+- **No matching surface** - ask: how would a real user discover this works? Do exactly that.
+
+Reading the source and concluding "this should work" does not pass this gate. If usage reveals a defect, that defect is yours to fix in this turn - same turn, not "follow-up".
+
+# Failure Recovery
+
+If your first approach fails, try a materially different one - different algorithm, library, or pattern, not a small tweak. Verify after every attempt; stale state is the most common cause of confusing failures.
+
+**Three-attempt failure protocol.** After three different approaches have failed:
+
+1. Stop editing immediately.
+2. Revert only your own changes to a known-good state, or undo your own edits surgically.
+3. Document each attempt and why it failed.
+4. Step back, document failure context in detail, then ask the user one precise question.
+
+# Pragmatism & Scope
+
+The best change is often the smallest correct change. When two approaches both work, prefer the one with fewer new names, helpers, layers, and tests.
+
+- Keep obvious single-use logic inline. Do not extract a helper unless it is reused, hides meaningful complexity, or names a real domain concept.
+- A small amount of duplication is better than speculative abstraction.
+- Bug fix != surrounding cleanup. Simple feature != extra configurability.
+- Fix only issues your changes caused. Pre-existing lint errors or failing tests unrelated to your work belong in the final message as observations, not in the diff.
+
+## No defensive code, no speculative legacy
+
+Default to writing only what is needed for the current correct path. Do not add error handlers, fallbacks, retries, or input validation for scenarios that cannot happen given the current contracts. Trust framework guarantees and internal types. Validate only at system boundaries - user input, external APIs, untrusted I/O.
+
+Do not write backward-compatibility code, migration shims, or alternate code paths "in case" something breaks. Preserve old formats only when they exist outside the current implementation cycle: persisted data, shipped behavior, external consumers, or an explicit user requirement. Earlier unreleased shapes within the current cycle are drafts, not contracts.
+
+Default to not adding tests. Add a test only when the user asks, when the change fixes a subtle bug, or when it protects an important behavioral boundary that existing tests do not cover. Never add tests to a codebase with no tests. Never make a test pass at the expense of correctness.
+
+# Code review requests
+
+When the user asks for a "review", default to a code-review mindset: findings come first, ordered by severity with file references. Open questions and assumptions follow. A change-summary is secondary, not the lead. If no findings, say so explicitly and call out residual risks or testing gaps.
+
+# AGENTS.md
+
+AGENTS.md files in your context carry directory-scoped conventions. Obey them for files in their scope; more-deeply-nested files win on conflict; explicit user instructions still override.
+
+# Output
+
+**Preamble.** Before the first tool call on any multi-step task, send one short user-visible update that acknowledges the request and states your first concrete step. One or two sentences.
+
+**During work.** Send short updates only at meaningful phase transitions: a discovery that changes the plan, a decision with tradeoffs, a blocker, or the start of a non-trivial verification step. Do not narrate routine reads or `rg` calls. One sentence per phase transition.
+
+**Final message.** Lead with the result, then add supporting context for where and why. No conversational openers ("Done -", "Got it"). Group by user-facing outcome, not by file. For simple work, 1-2 short paragraphs. For larger work, at most 2-4 short sections.
+
+**Formatting.**
+
+- File references: `src/auth.ts` or `src/auth.ts:42` (1-based optional line). No `file://`, `vscode://`, or `https://` URIs for local files. No line ranges.
+- Multi-line code in fenced blocks with a language tag.
+- The user does not see command outputs - summarize the key lines when reporting them.
+- No emojis or em dashes unless the user explicitly requests them.
+- Never output broken inline citations like `【F:README.md†L5-L14】` - they break the CLI.
+
+# Success Criteria
+
+Done when ALL of:
+
+- Every behavior the user asked for is implemented; no partial delivery, no "v0 / extend later".
+- LSP diagnostics clean on every file you changed.
+- Build (if applicable) exits 0; tests pass, or pre-existing failures are explicitly named with the reason.
+- The artifact has been driven through its matching surface in this turn (Manual QA Gate).
+- The final message reports what you did, what you verified, what you could not verify (with the reason), and any pre-existing issues you noticed but did not touch.
+
+When you think you are done: re-read the original request and your intent line. Did every committed action complete? Run verification once more on changed files in parallel. Then report.
+
+# Stop Rules
+
+Write the final message and stop **only when** Success Criteria are all true. Until then, keep going - even when tool calls fail, even when the turn is long, even when you are tempted to hand back a draft.
+
+**Forbidden stops:**
+
+- Stopping when Success Criteria are not all true (especially Manual QA Gate).
+- Stopping after a tool reports success, without verifying the changed files and observable behavior.
+
+**Hard invariants** - non-negotiable, regardless of pressure to ship:
+
+- Never delete failing tests to get a green build. Never weaken a test to make it pass.
+- Never use `as any`, `@ts-ignore`, or `@ts-expect-error` to suppress type errors.
+- Never use `apply_patch` for deletes you cannot revert without explicit approval.
+- Never amend commits unless explicitly asked.
+- Never revert changes you did not make unless explicitly asked.
+- Never invent fake citations, fake tool output, or fake verification results.
+
+**Asking the user** is a last resort - only when blocked by a missing secret, a design decision only they can make, or a destructive action you should not take unilaterally. Even then, ask exactly one precise question and stop. Never ask permission to do obvious work.
+
+# Task Tracking
+
+`update_plan` is the single most reliable forcing function you have. Use it for any work that is not a single atomic edit: 2+ steps, uncertain scope, multi-file changes, or branching investigation. When in doubt, call it. Skip planning only for the easiest 25%, and never make single-step plans.
+
+**Cadence:**
+
+- Atomic steps, one verifiable outcome each. Name the deliverable ("edit `foo.ts` to add X"), not the verb ("work on foo").
+- Exactly ONE step `in_progress` at a time. Never zero, never two.
+- Mark `completed` the instant the outcome lands. NEVER batch.
+- When discovery shifts the plan, update it in the SAME response. No silent drift.
+- Before ending the turn, reconcile EVERY step: `completed`, blocked (one-line reason), or removed (one-line reason). No `in_progress` or `pending` items at end of turn.
+
+**Promise discipline.** Do not commit to tests, broad refactors, or follow-up work in `update_plan` unless you will do them now. Anything you will not finish belongs in the final-message "next steps", not in the plan.
+
+**Refusing to plan is a failure mode.** If you find yourself improvising past step 2 without a plan, stop and call `update_plan` now.
diff --git a/plugins/omo/components/rules/hooks/hooks.json b/plugins/omo/components/rules/hooks/hooks.json
new file mode 100644
index 00000000..a6e2f1ab
--- /dev/null
+++ b/plugins/omo/components/rules/hooks/hooks.json
@@ -0,0 +1,54 @@
+{
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start",
+ "timeout": 10,
+ "statusMessage": "loading project rules"
+ }
+ ]
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit",
+ "timeout": 10,
+ "statusMessage": "loading project rules"
+ }
+ ]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "^apply_patch$",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use",
+ "timeout": 10,
+ "statusMessage": "matching project rules"
+ }
+ ]
+ }
+ ],
+ "PostCompact": [
+ {
+ "matcher": "manual|auto",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact",
+ "timeout": 10,
+ "statusMessage": "resetting project rule cache"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/omo/components/rules/package.json b/plugins/omo/components/rules/package.json
new file mode 100644
index 00000000..31a304e1
--- /dev/null
+++ b/plugins/omo/components/rules/package.json
@@ -0,0 +1,62 @@
+{
+ "name": "@code-yeongyu/codex-rules",
+ "version": "0.1.0",
+ "description": "Codex plugin that injects project rule files into model context through lifecycle hooks.",
+ "type": "module",
+ "packageManager": "[email protected]",
+ "license": "MIT",
+ "homepage": "https://github.com/code-yeongyu/codex-rules",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/code-yeongyu/codex-rules.git"
+ },
+ "bugs": {
+ "url": "https://github.com/code-yeongyu/codex-rules/issues"
+ },
+ "keywords": [
+ "codex",
+ "codex-plugin",
+ "rules",
+ "hooks",
+ "agents-md",
+ "context-injection",
+ "typescript"
+ ],
+ "bin": {
+ "codex-rules": "./dist/cli.js"
+ },
+ "files": [
+ "bundled-rules",
+ "dist",
+ "hooks",
+ "skills",
+ ".codex-plugin",
+ "LICENSE",
+ "NOTICE",
+ "README.md",
+ "CHANGELOG.md"
+ ],
+ "scripts": {
+ "build": "tsc -p tsconfig.build.json",
+ "test": "vitest --run",
+ "test:watch": "vitest",
+ "bench": "npm run build --silent && node scripts/bench-codex-rules.mjs",
+ "typecheck": "tsc --noEmit",
+ "lint": "biome check .",
+ "lint:fix": "biome check --write .",
+ "check": "tsc --noEmit && biome check . && npm run build"
+ },
+ "dependencies": {
+ "picomatch": "^4.0.3"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.15",
+ "@types/node": "^25.7.0",
+ "@types/picomatch": "^4.0.0",
+ "typescript": "^6.0.3",
+ "vitest": "^4.1.5"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+}
diff --git a/plugins/omo/components/rules/scripts/bench-codex-rules.mjs b/plugins/omo/components/rules/scripts/bench-codex-rules.mjs
new file mode 100644
index 00000000..13a5b53e
--- /dev/null
+++ b/plugins/omo/components/rules/scripts/bench-codex-rules.mjs
@@ -0,0 +1,268 @@
+#!/usr/bin/env node
+import { execFileSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { runPostToolUseHook } from "../dist/codex-hook.js";
+import { createEngine, defaultConfig } from "../dist/rules/engine.js";
+
+const ITERATIONS = 40;
+const WARMUP_ITERATIONS = 5;
+const RULE_COUNT = 120;
+const DISTINCT_TARGET_COUNT = 80;
+const DUPLICATE_TARGET_COUNT = 240;
+
+const args = process.argv.slice(2);
+const writeBaselinePath = readOption("--write-baseline");
+const comparePath = readOption("--compare");
+
+const result = await runBenchmark();
+
+if (writeBaselinePath !== undefined) {
+ writeFileSync(writeBaselinePath, `${JSON.stringify(result, null, "\t")}\n`);
+}
+
+if (comparePath !== undefined) {
+ const baseline = JSON.parse(readFileSync(comparePath, "utf8"));
+ const failures = compareResults(baseline, result);
+ if (failures.length > 0) {
+ for (const failure of failures) {
+ process.stderr.write(`${failure}\n`);
+ }
+ process.exitCode = 1;
+ }
+}
+
+process.stdout.write(`${JSON.stringify(result, null, "\t")}\n`);
+
+function readOption(name) {
+ const index = args.indexOf(name);
+ if (index === -1) {
+ return undefined;
+ }
+
+ const value = args[index + 1];
+ if (value === undefined || value.startsWith("--")) {
+ throw new Error(`${name} requires a value`);
+ }
+ return value;
+}
+
+async function runBenchmark() {
+ const scenarios = [
+ runScenario("duplicate-targets", duplicateTargets, DUPLICATE_TARGET_COUNT),
+ runScenario("distinct-targets", distinctTargets, DISTINCT_TARGET_COUNT),
+ ];
+ return {
+ commit: gitCommit(),
+ iterations: ITERATIONS,
+ warmupIterations: WARMUP_ITERATIONS,
+ ruleCount: RULE_COUNT,
+ scenarios,
+ hookFastPath: await runHookFastPathScenario(),
+ };
+}
+
+async function runHookFastPathScenario() {
+ const durations = [];
+ let repeatOutputBytes = 0;
+
+ for (let iteration = 0; iteration < ITERATIONS + WARMUP_ITERATIONS; iteration += 1) {
+ const run = await measureHookFastPathRun();
+ if (iteration >= WARMUP_ITERATIONS) {
+ durations.push(run.repeatDurationMs);
+ repeatOutputBytes += run.repeatOutputBytes;
+ }
+ }
+
+ return {
+ name: "repeat-post-tool-use",
+ medianRepeatMs: median(durations),
+ minRepeatMs: Math.min(...durations),
+ maxRepeatMs: Math.max(...durations),
+ repeatOutputBytes,
+ };
+}
+
+async function measureHookFastPathRun() {
+ const projectRoot = mkdtempSync(join(tmpdir(), "codex-rules-hook-bench-"));
+ const pluginData = mkdtempSync(join(tmpdir(), "codex-rules-hook-data-"));
+ try {
+ mkdirSync(join(projectRoot, "src"), { recursive: true });
+ mkdirSync(join(projectRoot, ".omo", "rules"), { recursive: true });
+ writeFileSync(join(projectRoot, "package.json"), JSON.stringify({ name: "bench" }));
+ writeFileSync(join(projectRoot, "src", "app.ts"), "export const app = true;\n");
+ for (let index = 0; index < RULE_COUNT; index += 1) {
+ writeFileSync(join(projectRoot, ".omo", "rules", `rule-${index}.md`), ruleContent(`rule-${index}`));
+ }
+
+ const input = {
+ session_id: "bench-session",
+ turn_id: "bench-turn",
+ transcript_path: null,
+ cwd: projectRoot,
+ hook_event_name: "PostToolUse",
+ model: "gpt-5.5",
+ permission_mode: "default",
+ tool_name: "mcp__filesystem__read_file",
+ tool_input: { path: join(projectRoot, "src", "app.ts") },
+ tool_response: { text: "file contents" },
+ tool_use_id: "bench-call",
+ };
+
+ await runPostToolUseHook(input, {
+ pluginDataRoot: pluginData,
+ env: { CODEX_RULES_ENABLED_SOURCES: ".omo/rules" },
+ });
+ const start = process.hrtime.bigint();
+ const repeatOutput = await runPostToolUseHook(input, {
+ pluginDataRoot: pluginData,
+ env: { CODEX_RULES_ENABLED_SOURCES: ".omo/rules" },
+ });
+ return {
+ repeatDurationMs: Number(process.hrtime.bigint() - start) / 1_000_000,
+ repeatOutputBytes: Buffer.byteLength(repeatOutput),
+ };
+ } finally {
+ rmSync(projectRoot, { recursive: true, force: true });
+ rmSync(pluginData, { recursive: true, force: true });
+ }
+}
+
+function runScenario(name, targetFactory, targetCount) {
+ const durations = [];
+ let counters = { findProjectRoot: 0, findCandidates: 0, readFile: 0 };
+
+ for (let iteration = 0; iteration < ITERATIONS + WARMUP_ITERATIONS; iteration += 1) {
+ const run = measureRun(targetFactory);
+ if (iteration >= WARMUP_ITERATIONS) {
+ durations.push(run.durationMs);
+ counters = addCounters(counters, run.counters);
+ }
+ }
+
+ return {
+ name,
+ targetCount,
+ medianMs: median(durations),
+ minMs: Math.min(...durations),
+ maxMs: Math.max(...durations),
+ counters,
+ };
+}
+
+function measureRun(targetPaths) {
+ const projectRoot = mkdtempSync(join(tmpdir(), "codex-rules-bench-"));
+ try {
+ const candidates = makeCandidates(projectRoot);
+ mkdirSync(join(projectRoot, ".omo", "rules"), { recursive: true });
+ for (const candidate of candidates) {
+ writeFileSync(candidate.path, "");
+ }
+ const counters = { findProjectRoot: 0, findCandidates: 0, readFile: 0 };
+ const engine = createEngine(defaultConfig(), {
+ findProjectRoot: () => {
+ counters.findProjectRoot += 1;
+ return projectRoot;
+ },
+ findCandidates: () => {
+ counters.findCandidates += 1;
+ return candidates;
+ },
+ readFile: (path) => {
+ counters.readFile += 1;
+ return ruleContent(path);
+ },
+ });
+ const generatedTargetPaths = targetPaths(projectRoot);
+ const start = process.hrtime.bigint();
+ engine.loadDynamicRules(projectRoot, generatedTargetPaths);
+ const durationMs = Number(process.hrtime.bigint() - start) / 1_000_000;
+ return { durationMs, counters };
+ } finally {
+ rmSync(projectRoot, { recursive: true, force: true });
+ }
+}
+
+function duplicateTargets(projectRoot) {
+ const targetPath = join(projectRoot, "src", "app.ts");
+ return Array.from({ length: DUPLICATE_TARGET_COUNT }, () => targetPath);
+}
+
+function distinctTargets(projectRoot) {
+ return Array.from({ length: DISTINCT_TARGET_COUNT }, (_, index) => join(projectRoot, "src", `file-${index}.ts`));
+}
+
+function makeCandidates(projectRoot) {
+ return Array.from({ length: RULE_COUNT }, (_, index) => ({
+ path: join(projectRoot, ".omo", "rules", `rule-${index}.md`),
+ realPath: join(projectRoot, ".omo", "rules", `rule-${index}.md`),
+ source: ".omo/rules",
+ distance: 0,
+ isGlobal: false,
+ isSingleFile: false,
+ relativePath: `.omo/rules/rule-${index}.md`,
+ }));
+}
+
+function ruleContent(path) {
+ return ["---", "globs: **/*.ts", "---", "", `Rule from ${path}`].join("\n");
+}
+
+function addCounters(left, right) {
+ return {
+ findProjectRoot: left.findProjectRoot + right.findProjectRoot,
+ findCandidates: left.findCandidates + right.findCandidates,
+ readFile: left.readFile + right.readFile,
+ };
+}
+
+function median(values) {
+ const sorted = [...values].sort((left, right) => left - right);
+ const index = Math.floor(sorted.length / 2);
+ return sorted[index] ?? 0;
+}
+
+function gitCommit() {
+ try {
+ return execFileSync("git", ["rev-parse", "--short", "HEAD"], { encoding: "utf8" }).trim();
+ } catch {
+ return "unknown";
+ }
+}
+
+function compareResults(baseline, current) {
+ const failures = [];
+ for (const scenario of current.scenarios) {
+ const baselineScenario = baseline.scenarios.find((candidate) => candidate.name === scenario.name);
+ if (baselineScenario === undefined) {
+ failures.push(`missing baseline scenario: ${scenario.name}`);
+ continue;
+ }
+
+ for (const counterName of ["findProjectRoot", "findCandidates", "readFile"]) {
+ if (scenario.counters[counterName] > baselineScenario.counters[counterName]) {
+ failures.push(
+ `${scenario.name}.${counterName} regressed: ${scenario.counters[counterName]} > ${baselineScenario.counters[counterName]}`,
+ );
+ }
+ }
+ }
+ if (baseline.hookFastPath === undefined) {
+ failures.push("missing baseline hookFastPath scenario");
+ } else {
+ if (current.hookFastPath.repeatOutputBytes > baseline.hookFastPath.repeatOutputBytes) {
+ failures.push(
+ `hookFastPath.repeatOutputBytes regressed: ${current.hookFastPath.repeatOutputBytes} > ${baseline.hookFastPath.repeatOutputBytes}`,
+ );
+ }
+
+ const maxMedianRepeatMs = baseline.hookFastPath.medianRepeatMs * 1.5;
+ if (current.hookFastPath.medianRepeatMs > maxMedianRepeatMs) {
+ failures.push(
+ `hookFastPath.medianRepeatMs regressed: ${current.hookFastPath.medianRepeatMs} > ${maxMedianRepeatMs}`,
+ );
+ }
+ }
+ return failures;
+}
diff --git a/plugins/omo/components/rules/skills/rules/SKILL.md b/plugins/omo/components/rules/skills/rules/SKILL.md
new file mode 100644
index 00000000..3ac40130
--- /dev/null
+++ b/plugins/omo/components/rules/skills/rules/SKILL.md
@@ -0,0 +1,34 @@
+---
+name: rules
+description: Use when the user asks about Codex Rules behavior, injected project rules, supported rule file locations, matching, or environment configuration.
+---
+
+# Codex Rules
+
+Codex Rules is automatic once the plugin is enabled. It injects:
+
+- static project instructions on `SessionStart` and `UserPromptSubmit`
+- matching file-specific rules after Codex `apply_patch` by default
+
+Dynamic `PostToolUse` output is injected as additional context and is deduplicated per plugin data session. Codex Rules does not rewrite tool output.
+
+Supported project sources:
+
+- `AGENTS.md`
+- `CLAUDE.md`
+- `CONTEXT.md`
+- `.sisyphus/rules/**/*.md`
+- `.claude/rules/**/*.md`
+- `.cursor/rules/**/*.md`
+- `.github/instructions/**/*.md`
+- `.github/copilot-instructions.md`
+
+Supported environment knobs:
+
+- `CODEX_RULES_DISABLED=1`
+- `CODEX_RULES_MODE=both|static|dynamic|off`
+- `CODEX_RULES_MAX_RULE_CHARS=<number>`
+- `CODEX_RULES_MAX_RESULT_CHARS=<number>`
+- `CODEX_RULES_ENABLED_SOURCES=AGENTS.md,.sisyphus/rules`
+
+The legacy `PI_RULES_*` variables are accepted as fallbacks for users migrating from `pi-rules`.
diff --git a/plugins/omo/components/rules/src/cli.ts b/plugins/omo/components/rules/src/cli.ts
new file mode 100644
index 00000000..64fa4ddf
--- /dev/null
+++ b/plugins/omo/components/rules/src/cli.ts
@@ -0,0 +1,143 @@
+#!/usr/bin/env node
+import { stdin as processStdin, stdout as processStdout } from "node:process";
+
+import {
+ type CodexPostCompactInput,
+ type CodexPostToolUseInput,
+ type CodexRulesHookOptions,
+ type CodexSessionStartInput,
+ type CodexUserPromptSubmitInput,
+ runPostCompactHook,
+ runPostToolUseHook,
+ runSessionStartHook,
+ runUserPromptSubmitHook,
+} from "./codex-hook.js";
+
+const command = process.argv[2];
+const subcommand = process.argv[3];
+type HookCliEventName = "SessionStart" | "UserPromptSubmit" | "PostToolUse" | "PostCompact";
+
+if (command === "hook" && subcommand === "session-start") {
+ await runHookCli("SessionStart");
+} else if (command === "hook" && subcommand === "user-prompt-submit") {
+ await runHookCli("UserPromptSubmit");
+} else if (command === "hook" && subcommand === "post-tool-use") {
+ await runHookCli("PostToolUse");
+} else if (command === "hook" && subcommand === "post-compact") {
+ await runHookCli("PostCompact");
+} else {
+ process.stderr.write("Usage: codex-rules hook [session-start|user-prompt-submit|post-tool-use|post-compact]\n");
+ process.exitCode = 1;
+}
+
+async function runHookCli(eventName: HookCliEventName): Promise<void> {
+ const raw = await readStdin();
+ if (raw.trim().length === 0) return;
+ const parsed = parseHookInput(raw);
+ if (!parsed) return;
+ const pluginDataRoot = process.env["PLUGIN_DATA"];
+ const options: CodexRulesHookOptions = pluginDataRoot === undefined ? {} : { pluginDataRoot };
+ const output = await runHook(eventName, parsed, options);
+ if (output.length > 0) {
+ processStdout.write(output);
+ }
+}
+
+async function runHook(eventName: HookCliEventName, parsed: unknown, options: CodexRulesHookOptions): Promise<string> {
+ switch (eventName) {
+ case "SessionStart":
+ return isCodexSessionStartInput(parsed) ? await runSessionStartHook(parsed, options) : "";
+ case "UserPromptSubmit":
+ return isCodexUserPromptSubmitInput(parsed) ? await runUserPromptSubmitHook(parsed, options) : "";
+ case "PostToolUse":
+ return isCodexPostToolUseInput(parsed) ? await runPostToolUseHook(parsed, options) : "";
+ case "PostCompact":
+ return isCodexPostCompactInput(parsed) ? await runPostCompactHook(parsed, options) : "";
+ }
+}
+
+function parseHookInput(raw: string): unknown | undefined {
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ return parsed;
+ } catch {
+ return undefined;
+ }
+}
+
+function isCodexSessionStartInput(value: unknown): value is CodexSessionStartInput {
+ return (
+ isRecord(value) &&
+ value["hook_event_name"] === "SessionStart" &&
+ typeof value["session_id"] === "string" &&
+ isStringOrNull(value["transcript_path"]) &&
+ typeof value["cwd"] === "string" &&
+ typeof value["model"] === "string" &&
+ typeof value["permission_mode"] === "string" &&
+ typeof value["source"] === "string"
+ );
+}
+
+function isCodexUserPromptSubmitInput(value: unknown): value is CodexUserPromptSubmitInput {
+ return (
+ isRecord(value) &&
+ value["hook_event_name"] === "UserPromptSubmit" &&
+ typeof value["session_id"] === "string" &&
+ typeof value["turn_id"] === "string" &&
+ isStringOrNull(value["transcript_path"]) &&
+ typeof value["cwd"] === "string" &&
+ typeof value["model"] === "string" &&
+ typeof value["permission_mode"] === "string" &&
+ typeof value["prompt"] === "string"
+ );
+}
+
+function isCodexPostToolUseInput(value: unknown): value is CodexPostToolUseInput {
+ return (
+ isRecord(value) &&
+ value["hook_event_name"] === "PostToolUse" &&
+ typeof value["session_id"] === "string" &&
+ typeof value["turn_id"] === "string" &&
+ isStringOrNull(value["transcript_path"]) &&
+ typeof value["cwd"] === "string" &&
+ typeof value["model"] === "string" &&
+ typeof value["permission_mode"] === "string" &&
+ typeof value["tool_name"] === "string" &&
+ typeof value["tool_use_id"] === "string"
+ );
+}
+
+function isCodexPostCompactInput(value: unknown): value is CodexPostCompactInput {
+ return (
+ isRecord(value) &&
+ value["hook_event_name"] === "PostCompact" &&
+ typeof value["session_id"] === "string" &&
+ typeof value["turn_id"] === "string" &&
+ isStringOrNull(value["transcript_path"]) &&
+ typeof value["cwd"] === "string" &&
+ typeof value["model"] === "string" &&
+ (value["trigger"] === "manual" || value["trigger"] === "auto")
+ );
+}
+
+function isStringOrNull(value: unknown): value is string | null {
+ return typeof value === "string" || value === null;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function readStdin(): Promise<string> {
+ return new Promise((resolve, reject) => {
+ let data = "";
+ processStdin.setEncoding("utf8");
+ processStdin.on("data", (chunk: string) => {
+ data += chunk;
+ });
+ processStdin.once("error", reject);
+ processStdin.once("end", () => {
+ resolve(data);
+ });
+ });
+}
diff --git a/plugins/omo/components/rules/src/codex-hook.ts b/plugins/omo/components/rules/src/codex-hook.ts
new file mode 100644
index 00000000..8a29d245
--- /dev/null
+++ b/plugins/omo/components/rules/src/codex-hook.ts
@@ -0,0 +1,475 @@
+import { readFileSync, statSync } from "node:fs";
+import { isAbsolute, relative, resolve } from "node:path";
+
+import { configFromEnvironment } from "./config.js";
+import { createHookDebugTimer } from "./debug-log.js";
+import {
+ clearSessionState,
+ hasPostCompactPending,
+ hydrateEngineState,
+ isPostCompactPending,
+ markSessionCompacted,
+ persistEngineState,
+ sessionCachePath,
+} from "./persistent-cache.js";
+import { SOURCE_PRIORITY } from "./rules/constants.js";
+import { createEngine } from "./rules/engine.js";
+import { createRuleDiscoveryCache, findRuleCandidates } from "./rules/finder.js";
+import { hashContent } from "./rules/matcher.js";
+import { sortCandidates } from "./rules/ordering.js";
+import { findProjectRoot } from "./rules/project-root.js";
+import type { LoadedRule, PiRulesConfig, RuleCandidate } from "./rules/types.js";
+import { extractCodexToolPaths } from "./tool-paths.js";
+
+type ContextInjectionHookEventName = "SessionStart" | "UserPromptSubmit" | "PostToolUse";
+
+export type CodexSessionStartInput = {
+ session_id: string;
+ transcript_path: string | null;
+ cwd: string;
+ hook_event_name: "SessionStart";
+ model: string;
+ permission_mode: string;
+ source: "startup" | "resume" | "clear";
+};
+
+export type CodexUserPromptSubmitInput = {
+ session_id: string;
+ turn_id: string;
+ transcript_path: string | null;
+ cwd: string;
+ hook_event_name: "UserPromptSubmit";
+ model: string;
+ permission_mode: string;
+ prompt: string;
+};
+
+export type CodexPostToolUseInput = {
+ session_id: string;
+ turn_id: string;
+ transcript_path: string | null;
+ cwd: string;
+ hook_event_name: "PostToolUse";
+ model: string;
+ permission_mode: string;
+ tool_name: string;
+ tool_input: unknown;
+ tool_response: unknown;
+ tool_use_id: string;
+};
+
+export type CodexPostCompactInput = {
+ session_id: string;
+ turn_id: string;
+ transcript_path: string | null;
+ cwd: string;
+ hook_event_name: "PostCompact";
+ model: string;
+ trigger: "manual" | "auto";
+};
+
+export interface CodexRulesHookOptions {
+ env?: NodeJS.ProcessEnv;
+ pluginDataRoot?: string;
+}
+
+interface DynamicTargetFingerprint {
+ targetPath: string;
+ cacheKey: string;
+ fingerprint: string;
+}
+
+export async function runSessionStartHook(
+ input: CodexSessionStartInput,
+ options: CodexRulesHookOptions = {},
+): Promise<string> {
+ const cachePath = sessionCachePath(input.session_id, options.pluginDataRoot);
+ if (input.source === "clear") {
+ clearSessionState(cachePath);
+ } else if (input.source !== "resume" && !hasPostCompactPending(cachePath)) {
+ clearSessionState(cachePath);
+ }
+ const postCompactPending = input.source !== "clear" && isPostCompactPending(cachePath, "static");
+ const transcriptPath = input.source === "clear" || postCompactPending ? null : input.transcript_path;
+ return runStaticInjection(
+ input.cwd,
+ transcriptPath,
+ "SessionStart",
+ cachePath,
+ options,
+ postCompactPending ? "static" : undefined,
+ );
+}
+
+export async function runPostCompactHook(
+ input: CodexPostCompactInput,
+ options: CodexRulesHookOptions = {},
+): Promise<string> {
+ markSessionCompacted(sessionCachePath(input.session_id, options.pluginDataRoot));
+ return "";
+}
+
+export async function runUserPromptSubmitHook(
+ input: CodexUserPromptSubmitInput,
+ options: CodexRulesHookOptions = {},
+): Promise<string> {
+ const cachePath = sessionCachePath(input.session_id, options.pluginDataRoot);
+ const postCompactPending = isPostCompactPending(cachePath, "static");
+ const transcriptPath = postCompactPending ? null : input.transcript_path;
+ return runStaticInjection(
+ input.cwd,
+ transcriptPath,
+ "UserPromptSubmit",
+ cachePath,
+ options,
+ postCompactPending ? "static" : undefined,
+ );
+}
+
+export async function runPostToolUseHook(
+ input: CodexPostToolUseInput,
+ options: CodexRulesHookOptions = {},
+): Promise<string> {
+ const debugTimer = createHookDebugTimer("PostToolUse");
+ const config = configFromEnvironment(options.env);
+ debugTimer.lap("config", { disabled: config.disabled, mode: config.mode });
+ if (config.disabled || config.mode === "off" || config.mode === "static") {
+ debugTimer.done({ outputBytes: 0, reason: "disabled" });
+ return "";
+ }
+
+ const targetPaths = extractCodexToolPaths(input, input.cwd);
+ debugTimer.lap("extract", {
+ targets: targetPaths.length,
+ uniqueTargets: uniqueStrings(targetPaths).length,
+ tool: input.tool_name,
+ });
+ const firstTargetPath = targetPaths[0];
+ if (firstTargetPath === undefined) {
+ debugTimer.done({ outputBytes: 0, reason: "no-target" });
+ return "";
+ }
+
+ const cachePath = sessionCachePath(input.session_id, options.pluginDataRoot);
+ const postCompactPending = isPostCompactPending(cachePath, "dynamic");
+ const transcriptPath = postCompactPending ? null : input.transcript_path;
+ const engine = createRulesEngine(options);
+ hydrateEngineState(engine, cachePath);
+ debugTimer.lap("hydrate", {
+ dynamicDedupScopes: engine.state.dynamicDedup.size,
+ dynamicTargetFingerprints: engine.state.dynamicTargetFingerprints.size,
+ staticDedup: engine.state.staticDedup.size,
+ });
+ const dynamicTargetFingerprints = fingerprintDynamicTargets(input.cwd, targetPaths, config);
+ debugTimer.lap("fingerprint", { fingerprints: dynamicTargetFingerprints.length });
+ const pendingTargetFingerprints = dynamicTargetFingerprints.filter(
+ (target) => engine.state.dynamicTargetFingerprints.get(target.cacheKey) !== target.fingerprint,
+ );
+ debugTimer.lap("pending", { pending: pendingTargetFingerprints.length });
+ if (pendingTargetFingerprints.length === 0) {
+ persistEngineState(engine, cachePath, postCompactPending ? "dynamic" : undefined);
+ debugTimer.lap("persist", { reason: "no-pending" });
+ debugTimer.done({ outputBytes: 0, reason: "no-pending" });
+ return "";
+ }
+
+ const loaded = engine.loadDynamicRules(
+ input.cwd,
+ pendingTargetFingerprints.map((target) => target.targetPath),
+ );
+ debugTimer.lap("load", { diagnostics: loaded.diagnostics.length, loadedRules: loaded.rules.length });
+ const rules = filterRulesAlreadyInTranscript(
+ loaded.rules.filter((rule) => !engine.isStaticInjected(rule) && !engine.isDynamicInjected(rule)),
+ transcriptPath,
+ (rule) => {
+ engine.markDynamicInjected(rule);
+ },
+ );
+ debugTimer.lap("filter", { rules: rules.length });
+ for (const target of pendingTargetFingerprints) {
+ engine.state.dynamicTargetFingerprints.set(target.cacheKey, target.fingerprint);
+ }
+ if (rules.length === 0) {
+ persistEngineState(engine, cachePath, postCompactPending ? "dynamic" : undefined);
+ debugTimer.lap("persist", { reason: "no-rules" });
+ debugTimer.done({ outputBytes: 0, reason: "no-rules" });
+ return "";
+ }
+
+ const firstPendingTargetPath = pendingTargetFingerprints[0]?.targetPath ?? firstTargetPath;
+ const block = engine.formatDynamic(rules, displayPath(input.cwd, firstPendingTargetPath));
+ debugTimer.lap("format", { blockChars: block.length, rules: rules.length });
+ for (const rule of rules) {
+ engine.markDynamicInjected(rule);
+ }
+ persistEngineState(engine, cachePath, postCompactPending ? "dynamic" : undefined);
+ debugTimer.lap("persist", { reason: "emit" });
+ const output = formatAdditionalContextOutput("PostToolUse", block);
+ debugTimer.done({ outputBytes: Buffer.byteLength(output), reason: "emit" });
+ return output;
+}
+
+function runStaticInjection(
+ cwd: string,
+ transcriptPath: string | null,
+ eventName: "SessionStart" | "UserPromptSubmit",
+ cachePath: string,
+ options: CodexRulesHookOptions,
+ completedPostCompactChannel?: "static",
+): string {
+ const config = configFromEnvironment(options.env);
+ if (config.disabled || config.mode === "off" || config.mode === "dynamic") {
+ return "";
+ }
+
+ const engine = createRulesEngine(options);
+ hydrateEngineState(engine, cachePath);
+ engine.state.cwd = cwd;
+
+ const loaded = engine.loadStaticRules(cwd);
+ const rules = filterRulesAlreadyInTranscript(
+ loaded.rules.filter((rule) => !engine.isStaticInjected(rule)),
+ transcriptPath,
+ (rule) => {
+ engine.markStaticInjected(rule);
+ },
+ );
+ if (rules.length === 0) {
+ persistEngineState(engine, cachePath, completedPostCompactChannel);
+ return "";
+ }
+
+ const block = engine.formatStatic(rules);
+ for (const rule of rules) {
+ engine.markStaticInjected(rule);
+ }
+ persistEngineState(engine, cachePath, completedPostCompactChannel);
+ return formatAdditionalContextOutput(eventName, block);
+}
+
+function filterRulesAlreadyInTranscript(
+ rules: ReadonlyArray<LoadedRule>,
+ transcriptPath: string | null,
+ markInjected: (rule: LoadedRule) => void,
+): LoadedRule[] {
+ if (rules.length === 0 || transcriptPath === null) {
+ return [...rules];
+ }
+
+ const transcriptText = readTranscriptSearchText(transcriptPath);
+ if (transcriptText === null) {
+ return [...rules];
+ }
+
+ const pendingRules: LoadedRule[] = [];
+ for (const rule of rules) {
+ if (isRuleAlreadyInTranscript(rule, transcriptText)) {
+ markInjected(rule);
+ continue;
+ }
+
+ pendingRules.push(rule);
+ }
+ return pendingRules;
+}
+
+function isRuleAlreadyInTranscript(rule: LoadedRule, transcriptText: string): boolean {
+ const bodyNeedle = rule.body.trim().slice(0, 2_000);
+ if (bodyNeedle.length === 0 || !transcriptText.includes(bodyNeedle)) {
+ return false;
+ }
+
+ const markers = [
+ `Instructions from: ${rule.path}`,
+ `Instructions from: ${rule.realPath}`,
+ rule.relativePath.length === 0 ? null : rule.relativePath,
+ ].filter((marker): marker is string => marker !== null);
+ return markers.some((marker) => transcriptText.includes(marker));
+}
+
+function readTranscriptSearchText(transcriptPath: string): string | null {
+ try {
+ const rawTranscript = readFileSync(transcriptPath, "utf8");
+ return [rawTranscript, ...collectJsonLineStrings(rawTranscript)].join("\n");
+ } catch {
+ return null;
+ }
+}
+
+function collectJsonLineStrings(rawTranscript: string): string[] {
+ const values: string[] = [];
+ for (const line of rawTranscript.split(/\r?\n/)) {
+ if (line.trim().length === 0) {
+ continue;
+ }
+
+ try {
+ const parsed: unknown = JSON.parse(line);
+ collectStrings(parsed, values);
+ } catch {
+ // Non-JSON transcript lines are still covered by the raw transcript text.
+ }
+ }
+ return values;
+}
+
+function collectStrings(value: unknown, output: string[]): void {
+ if (typeof value === "string") {
+ output.push(value);
+ return;
+ }
+
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ collectStrings(item, output);
+ }
+ return;
+ }
+
+ if (typeof value !== "object" || value === null) {
+ return;
+ }
+
+ for (const item of Object.values(value)) {
+ collectStrings(item, output);
+ }
+}
+
+function createRulesEngine(options: CodexRulesHookOptions) {
+ const config = configFromEnvironment(options.env);
+ return createEngine(config, {
+ findCandidates: findRuleCandidates,
+ findProjectRoot,
+ readFile: (path) => {
+ try {
+ return readFileSync(path, "utf8");
+ } catch {
+ return null;
+ }
+ },
+ });
+}
+
+function fingerprintDynamicTargets(
+ cwd: string,
+ targetPaths: ReadonlyArray<string>,
+ config: PiRulesConfig,
+): DynamicTargetFingerprint[] {
+ const disabledSources = disabledSourcesFor(config);
+ const discoveryCache = createRuleDiscoveryCache();
+ const cwdProjectRoot = findProjectRoot(cwd);
+ const fingerprints: DynamicTargetFingerprint[] = [];
+
+ for (const targetPath of uniqueStrings(targetPaths)) {
+ const projectRoot =
+ cwdProjectRoot !== null && isSameOrChildPath(targetPath, cwdProjectRoot)
+ ? cwdProjectRoot
+ : findProjectRoot(targetPath);
+ const findOptions: {
+ projectRoot: string | null;
+ targetFile: string;
+ disabledSources?: ReadonlySet<string>;
+ cache: ReturnType<typeof createRuleDiscoveryCache>;
+ } = {
+ projectRoot,
+ targetFile: targetPath,
+ cache: discoveryCache,
+ };
+ if (disabledSources !== undefined) {
+ findOptions.disabledSources = disabledSources;
+ }
+ const candidates = findRuleCandidates(findOptions);
+ const candidateFingerprint = sortCandidates(candidates).map(fingerprintCandidate).join("\u0001");
+ const cacheKey = dynamicTargetCacheKey(targetPath);
+ fingerprints.push({
+ targetPath,
+ cacheKey,
+ fingerprint: hashContent(
+ [
+ "v1",
+ config.enabledSources === "auto" ? "auto" : config.enabledSources.join(","),
+ projectRoot ?? "",
+ cacheKey,
+ candidateFingerprint,
+ ].join("\u0000"),
+ ),
+ });
+ }
+
+ return fingerprints;
+}
+
+function fingerprintCandidate(candidate: RuleCandidate): string {
+ return [
+ candidate.realPath,
+ candidate.relativePath,
+ candidate.source,
+ candidate.isGlobal ? "global" : "project",
+ candidate.isSingleFile ? "single" : "multi",
+ String(candidate.distance),
+ fileFingerprint(candidate.path),
+ ].join("\u0000");
+}
+
+function fileFingerprint(filePath: string): string {
+ try {
+ const stats = statSync(filePath, { bigint: true });
+ return `${stats.mtimeNs}:${stats.ctimeNs}:${stats.size}`;
+ } catch {
+ return "missing";
+ }
+}
+
+function disabledSourcesFor(config: PiRulesConfig): ReadonlySet<string> | undefined {
+ if (config.enabledSources === "auto") {
+ return undefined;
+ }
+
+ const enabledSources = new Set(config.enabledSources);
+ return new Set([...SOURCE_PRIORITY.keys()].filter((source) => !enabledSources.has(source)));
+}
+
+function dynamicTargetCacheKey(targetPath: string): string {
+ return toPosixPath(resolve(targetPath));
+}
+
+function isSameOrChildPath(childPath: string, parentPath: string): boolean {
+ const childRelativePath = relative(parentPath, resolve(childPath));
+ return childRelativePath === "" || (!childRelativePath.startsWith("..") && !isAbsolute(childRelativePath));
+}
+
+function uniqueStrings(values: ReadonlyArray<string>): string[] {
+ const uniqueValues: string[] = [];
+ const seenValues = new Set<string>();
+ for (const value of values) {
+ if (seenValues.has(value)) {
+ continue;
+ }
+
+ seenValues.add(value);
+ uniqueValues.push(value);
+ }
+ return uniqueValues;
+}
+
+function formatAdditionalContextOutput(eventName: ContextInjectionHookEventName, additionalContext: string): string {
+ if (additionalContext.trim().length === 0) return "";
+ return `${JSON.stringify({
+ hookSpecificOutput: {
+ hookEventName: eventName,
+ additionalContext,
+ },
+ })}\n`;
+}
+
+function displayPath(cwd: string, filePath: string): string {
+ const rel = isAbsolute(filePath) ? relative(cwd, filePath) : filePath;
+ // Normalize to POSIX separators so injected rule context renders the same
+ // path string on Linux/macOS and Windows (Codex feeds this verbatim into
+ // the model prompt, and the existing engine already emits POSIX paths).
+ return toPosixPath(rel);
+}
+
+function toPosixPath(path: string): string {
+ return path.replaceAll("\\", "/");
+}
diff --git a/plugins/omo/components/rules/src/config.ts b/plugins/omo/components/rules/src/config.ts
new file mode 100644
index 00000000..146ba964
--- /dev/null
+++ b/plugins/omo/components/rules/src/config.ts
@@ -0,0 +1,99 @@
+import { SOURCE_PRIORITY } from "./rules/constants.js";
+import { defaultConfig } from "./rules/engine.js";
+import type { PiRulesConfig, RuleSource } from "./rules/types.js";
+
+export function configFromEnvironment(env: NodeJS.ProcessEnv = process.env): PiRulesConfig {
+ const config = defaultConfig();
+ const disableBundledRules = isTruthy(firstEnv(env, "CODEX_RULES_DISABLE_BUNDLED", "PI_RULES_DISABLE_BUNDLED"));
+ config.disabled = isTruthy(firstEnv(env, "CODEX_RULES_DISABLED", "PI_RULES_DISABLED"));
+ config.mode = parseMode(firstEnv(env, "CODEX_RULES_MODE", "PI_RULES_MODE")) ?? config.mode;
+ config.maxRuleChars =
+ parsePositiveInteger(firstEnv(env, "CODEX_RULES_MAX_RULE_CHARS", "PI_RULES_MAX_RULE_CHARS")) ??
+ config.maxRuleChars;
+ config.maxResultChars =
+ parsePositiveInteger(firstEnv(env, "CODEX_RULES_MAX_RESULT_CHARS", "PI_RULES_MAX_RESULT_CHARS")) ??
+ config.maxResultChars;
+ config.enabledSources = parseEnabledSources(
+ firstEnv(env, "CODEX_RULES_ENABLED_SOURCES", "PI_RULES_ENABLED_SOURCES"),
+ disableBundledRules,
+ );
+ return config;
+}
+
+function firstEnv(env: NodeJS.ProcessEnv, ...names: string[]): string | undefined {
+ for (const name of names) {
+ const value = env[name];
+ if (typeof value === "string" && value.trim().length > 0) {
+ return value;
+ }
+ }
+ return undefined;
+}
+
+function isTruthy(value: string | undefined): boolean {
+ if (value === undefined) return false;
+ return ["1", "true", "yes", "on"].includes(value.trim().toLowerCase());
+}
+
+function parseMode(value: string | undefined): PiRulesConfig["mode"] | undefined {
+ if (value === undefined) return undefined;
+ const normalized = value.trim().toLowerCase();
+ switch (normalized) {
+ case "static":
+ case "dynamic":
+ case "both":
+ case "off":
+ return normalized;
+ default:
+ return undefined;
+ }
+}
+
+function parsePositiveInteger(value: string | undefined): number | undefined {
+ if (value === undefined) return undefined;
+ const parsed = Number.parseInt(value.trim(), 10);
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
+}
+
+function parseEnabledSources(value: string | undefined, disableBundledRules: boolean): RuleSource[] | "auto" {
+ if (value === undefined || value.trim().toLowerCase() === "auto") {
+ return disableBundledRules ? sourcesWithoutBundledRules() : "auto";
+ }
+
+ const sources: RuleSource[] = [];
+ for (const rawSource of value.split(",")) {
+ const source = toRuleSource(rawSource.trim());
+ if (source === null) {
+ continue;
+ }
+ sources.push(source);
+ }
+ const enabledSources = disableBundledRules ? sources.filter((source) => source !== "plugin-bundled") : sources;
+ return enabledSources.length > 0 || sources.length > 0 ? enabledSources : "auto";
+}
+
+function sourcesWithoutBundledRules(): RuleSource[] {
+ return [...SOURCE_PRIORITY.keys()].filter((source) => source !== "plugin-bundled");
+}
+
+function toRuleSource(value: string): RuleSource | null {
+ switch (value) {
+ case ".omo/rules":
+ case ".claude/rules":
+ case ".cursor/rules":
+ case ".github/instructions":
+ case ".github/copilot-instructions.md":
+ case "AGENTS.md":
+ case "CLAUDE.md":
+ case "CONTEXT.md":
+ case "plugin-bundled":
+ case "~/.omo/rules":
+ case "~/.opencode/rules":
+ case "~/.claude/rules":
+ case "~/.config/opencode/AGENTS.md":
+ case "~/.claude/CLAUDE.md":
+ return value;
+ default:
+ return null;
+ }
+}
diff --git a/plugins/omo/components/rules/src/debug-log.ts b/plugins/omo/components/rules/src/debug-log.ts
new file mode 100644
index 00000000..cab97047
--- /dev/null
+++ b/plugins/omo/components/rules/src/debug-log.ts
@@ -0,0 +1,65 @@
+import { performance } from "node:perf_hooks";
+import { debuglog } from "node:util";
+
+type DebugFieldValue = boolean | number | string | null;
+
+type DebugFields = Record<string, DebugFieldValue>;
+
+const debug = debuglog("codex-rules");
+const noopTimer: HookDebugTimer = {
+ lap: () => {},
+ done: () => {},
+};
+
+export interface HookDebugTimer {
+ lap(phase: string, fields?: DebugFields): void;
+ done(fields?: DebugFields): void;
+}
+
+export function createHookDebugTimer(hookName: string): HookDebugTimer {
+ if (!debug.enabled) {
+ return noopTimer;
+ }
+
+ const startMs = performance.now();
+ let lastMs = startMs;
+
+ return {
+ lap: (phase, fields = {}) => {
+ const nowMs = performance.now();
+ writeDebugLine(hookName, phase, nowMs - lastMs, nowMs - startMs, fields);
+ lastMs = nowMs;
+ },
+ done: (fields = {}) => {
+ const nowMs = performance.now();
+ writeDebugLine(hookName, "done", nowMs - lastMs, nowMs - startMs, fields);
+ lastMs = nowMs;
+ },
+ };
+}
+
+function writeDebugLine(
+ hookName: string,
+ phase: string,
+ durationMs: number,
+ totalMs: number,
+ fields: DebugFields,
+): void {
+ debug(
+ "%s phase=%s ms=%s total_ms=%s%s",
+ hookName,
+ phase,
+ durationMs.toFixed(3),
+ totalMs.toFixed(3),
+ formatFields(fields),
+ );
+}
+
+function formatFields(fields: DebugFields): string {
+ const entries = Object.entries(fields);
+ if (entries.length === 0) {
+ return "";
+ }
+
+ return ` ${entries.map(([key, value]) => `${key}=${String(value)}`).join(" ")}`;
+}
diff --git a/plugins/omo/components/rules/src/persistent-cache.ts b/plugins/omo/components/rules/src/persistent-cache.ts
new file mode 100644
index 00000000..d95caeed
--- /dev/null
+++ b/plugins/omo/components/rules/src/persistent-cache.ts
@@ -0,0 +1,167 @@
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { dirname, join } from "node:path";
+
+import type { Engine } from "./rules/engine.js";
+
+export type PostCompactPendingKind = "static" | "dynamic";
+
+interface PostCompactPendingState {
+ static?: boolean;
+ dynamic?: boolean;
+}
+
+interface SerializedSessionState {
+ staticDedup: string[];
+ dynamicDedup: Record<string, string[]>;
+ dynamicTargetFingerprints?: Record<string, string>;
+ postCompactPending?: PostCompactPendingState;
+ compacted?: boolean;
+}
+
+export function hydrateEngineState(engine: Engine, cachePath: string): void {
+ const state = readSessionState(cachePath);
+ engine.state.staticDedup.clear();
+ engine.state.dynamicDedup.clear();
+ engine.state.dynamicTargetFingerprints.clear();
+
+ for (const key of state.staticDedup) {
+ engine.state.staticDedup.add(key);
+ }
+ for (const [scope, keys] of Object.entries(state.dynamicDedup)) {
+ engine.state.dynamicDedup.set(scope, new Set(keys));
+ }
+ for (const [targetKey, fingerprint] of Object.entries(state.dynamicTargetFingerprints ?? {})) {
+ engine.state.dynamicTargetFingerprints.set(targetKey, fingerprint);
+ }
+}
+
+export function persistEngineState(
+ engine: Engine,
+ cachePath: string,
+ completedPostCompactKind?: PostCompactPendingKind,
+): void {
+ const currentState = readSessionState(cachePath);
+ const dynamicDedup: Record<string, string[]> = {};
+ for (const [scope, keys] of engine.state.dynamicDedup.entries()) {
+ dynamicDedup[scope] = [...keys];
+ }
+
+ const postCompactPending = nextPostCompactPending(currentState, completedPostCompactKind);
+ writeSessionState(cachePath, {
+ staticDedup: [...engine.state.staticDedup],
+ dynamicDedup,
+ dynamicTargetFingerprints: Object.fromEntries(engine.state.dynamicTargetFingerprints.entries()),
+ ...(postCompactPending === undefined ? {} : { postCompactPending }),
+ });
+}
+
+export function clearSessionState(cachePath: string): void {
+ rmSync(cachePath, { force: true });
+}
+
+export function markSessionCompacted(cachePath: string): void {
+ writeSessionState(cachePath, { ...emptyState(), postCompactPending: { static: true, dynamic: true } });
+}
+
+export function hasPostCompactPending(cachePath: string): boolean {
+ return postCompactPendingKinds(readSessionState(cachePath)).size > 0;
+}
+
+export function isPostCompactPending(cachePath: string, kind: PostCompactPendingKind): boolean {
+ return postCompactPendingKinds(readSessionState(cachePath)).has(kind);
+}
+
+export function sessionCachePath(sessionId: string, pluginDataRoot: string | undefined): string {
+ const root = pluginDataRoot ?? process.env["PLUGIN_DATA"] ?? join(homedir(), ".codex", "codex-rules");
+ return join(root, "sessions", `${safePathSegment(sessionId)}.json`);
+}
+
+function readSessionState(cachePath: string): SerializedSessionState {
+ try {
+ const parsed = JSON.parse(readFileSync(cachePath, "utf8"));
+ if (!isSerializedSessionState(parsed)) return emptyState();
+ return parsed;
+ } catch {
+ return emptyState();
+ }
+}
+
+function writeSessionState(cachePath: string, state: SerializedSessionState): void {
+ mkdirSync(dirname(cachePath), { recursive: true });
+ writeFileSync(cachePath, `${JSON.stringify(state)}\n`);
+}
+
+function emptyState(): SerializedSessionState {
+ return { staticDedup: [], dynamicDedup: {}, dynamicTargetFingerprints: {} };
+}
+
+function nextPostCompactPending(
+ state: SerializedSessionState,
+ completedKind: PostCompactPendingKind | undefined,
+): PostCompactPendingState | undefined {
+ const pendingKinds = postCompactPendingKinds(state);
+ if (completedKind !== undefined) {
+ pendingKinds.delete(completedKind);
+ }
+
+ if (pendingKinds.size === 0) {
+ return undefined;
+ }
+
+ return {
+ ...(pendingKinds.has("static") ? { static: true } : {}),
+ ...(pendingKinds.has("dynamic") ? { dynamic: true } : {}),
+ };
+}
+
+function postCompactPendingKinds(state: SerializedSessionState): Set<PostCompactPendingKind> {
+ const pendingKinds = new Set<PostCompactPendingKind>();
+ if (state.compacted === true || state.postCompactPending?.static === true) {
+ pendingKinds.add("static");
+ }
+ if (state.compacted === true || state.postCompactPending?.dynamic === true) {
+ pendingKinds.add("dynamic");
+ }
+ return pendingKinds;
+}
+
+function safePathSegment(value: string): string {
+ return value.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 120) || "unknown-session";
+}
+
+function isSerializedSessionState(value: unknown): value is SerializedSessionState {
+ if (!isRecord(value) || !Array.isArray(value["staticDedup"]) || !isRecord(value["dynamicDedup"])) {
+ return false;
+ }
+ const staticDedup = value["staticDedup"];
+ const dynamicDedup = value["dynamicDedup"];
+ const dynamicTargetFingerprints = value["dynamicTargetFingerprints"];
+ const postCompactPending = value["postCompactPending"];
+ const compacted = value["compacted"];
+ return (
+ staticDedup.every((item) => typeof item === "string") &&
+ Object.values(dynamicDedup).every(
+ (item) => Array.isArray(item) && item.every((nestedItem) => typeof nestedItem === "string"),
+ ) &&
+ (dynamicTargetFingerprints === undefined ||
+ (isRecord(dynamicTargetFingerprints) &&
+ Object.entries(dynamicTargetFingerprints).every(
+ ([targetKey, fingerprint]) => typeof targetKey === "string" && typeof fingerprint === "string",
+ ))) &&
+ (postCompactPending === undefined || isPostCompactPendingState(postCompactPending)) &&
+ (compacted === undefined || typeof compacted === "boolean")
+ );
+}
+
+function isPostCompactPendingState(value: unknown): value is PostCompactPendingState {
+ return (
+ isRecord(value) &&
+ (value["static"] === undefined || typeof value["static"] === "boolean") &&
+ (value["dynamic"] === undefined || typeof value["dynamic"] === "boolean")
+ );
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/plugins/omo/components/rules/src/rules/cache.ts b/plugins/omo/components/rules/src/rules/cache.ts
new file mode 100644
index 00000000..2433d454
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/cache.ts
@@ -0,0 +1,64 @@
+import type { LoadedRule, SessionState } from "./types.js";
+
+const DYNAMIC_SESSION_KEY = "__pi-rules-session__";
+
+export function createSessionState(cwd?: string): SessionState {
+ return {
+ cwd,
+ staticDedup: new Set(),
+ dynamicDedup: new Map(),
+ dynamicTargetFingerprints: new Map(),
+ loadedRules: [],
+ diagnostics: [],
+ };
+}
+
+export function staticDedupKey(cwd: string, rulePath: string, contentHash: string): string {
+ return `${cwd}::${rulePath}::${contentHash}`;
+}
+
+export function dynamicDedupKey(rulePath: string, contentHash: string): string {
+ return `${rulePath}::${contentHash}`;
+}
+
+export function markStaticInjected(state: SessionState, rule: LoadedRule): boolean {
+ const key = staticDedupKey(state.cwd ?? "", rule.realPath, rule.contentHash);
+ if (state.staticDedup.has(key)) {
+ return false;
+ }
+
+ state.staticDedup.add(key);
+ return true;
+}
+
+export function markDynamicInjected(state: SessionState, rule: LoadedRule): boolean {
+ let keys = state.dynamicDedup.get(DYNAMIC_SESSION_KEY);
+ if (keys === undefined) {
+ keys = new Set();
+ state.dynamicDedup.set(DYNAMIC_SESSION_KEY, keys);
+ }
+
+ const key = dynamicDedupKey(rule.realPath, rule.contentHash);
+ if (keys.has(key)) {
+ return false;
+ }
+
+ keys.add(key);
+ return true;
+}
+
+export function isStaticInjected(state: SessionState, rule: LoadedRule): boolean {
+ return state.staticDedup.has(staticDedupKey(state.cwd ?? "", rule.realPath, rule.contentHash));
+}
+
+export function isDynamicInjected(state: SessionState, rule: LoadedRule): boolean {
+ return state.dynamicDedup.get(DYNAMIC_SESSION_KEY)?.has(dynamicDedupKey(rule.realPath, rule.contentHash)) === true;
+}
+
+export function clearSession(state: SessionState): void {
+ state.staticDedup.clear();
+ state.dynamicDedup.clear();
+ state.dynamicTargetFingerprints.clear();
+ state.loadedRules.length = 0;
+ state.diagnostics.length = 0;
+}
diff --git a/plugins/omo/components/rules/src/rules/constants.ts b/plugins/omo/components/rules/src/rules/constants.ts
new file mode 100644
index 00000000..38baef52
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/constants.ts
@@ -0,0 +1,111 @@
+import type { RuleSource } from "./types.js";
+
+/**
+ * Project root marker files / directories used by `findProjectRoot`.
+ * Walks UP from cwd until any of these is found in the directory.
+ */
+export const PROJECT_MARKERS: readonly string[] = [
+ ".git",
+ "pnpm-workspace.yaml",
+ "package.json",
+ "pyproject.toml",
+ "Cargo.toml",
+ "go.mod",
+ ".venv",
+];
+
+/**
+ * Project rule subdirectories. First tuple element is the parent dir under
+ * the project root, second is the subdir scanned recursively.
+ */
+export const PROJECT_RULE_SUBDIRS: ReadonlyArray<readonly [string, string]> = [
+ [".omo", "rules"],
+ [".claude", "rules"],
+ [".cursor", "rules"],
+ [".github", "instructions"],
+];
+
+/**
+ * Single-file project rules (always apply, frontmatter optional).
+ */
+export const PROJECT_SINGLE_FILES: readonly string[] = [
+ ".github/copilot-instructions.md",
+ "AGENTS.md",
+ "CLAUDE.md",
+ "CONTEXT.md",
+];
+
+/**
+ * User-home rule directories.
+ */
+export const USER_HOME_RULE_SUBDIRS: readonly string[] = [".omo/rules", ".opencode/rules", ".claude/rules"];
+
+/**
+ * User-home single-file rules. The first one to exist wins per "first-match" semantics.
+ */
+export const USER_HOME_SINGLE_FILES: readonly string[] = [".config/opencode/AGENTS.md", ".claude/CLAUDE.md"];
+
+/**
+ * Bundled plugin rule directory relative to the rules component root.
+ */
+export const BUNDLED_RULE_SUBDIR = "bundled-rules";
+
+/**
+ * File extensions accepted as rule files in scanned directories.
+ */
+export const RULE_FILE_EXTENSIONS: readonly string[] = [".md", ".mdc"];
+
+/**
+ * Per-rule source priority for deterministic ordering. Lower = earlier.
+ */
+export const SOURCE_PRIORITY: ReadonlyMap<RuleSource, number> = new Map([
+ [".omo/rules", 0],
+ [".claude/rules", 1],
+ [".cursor/rules", 2],
+ [".github/instructions", 3],
+ [".github/copilot-instructions.md", 4],
+ ["AGENTS.md", 5],
+ ["CLAUDE.md", 6],
+ ["CONTEXT.md", 7],
+ ["~/.omo/rules", 100],
+ ["~/.opencode/rules", 101],
+ ["~/.claude/rules", 102],
+ ["~/.config/opencode/AGENTS.md", 103],
+ ["~/.claude/CLAUDE.md", 104],
+ ["plugin-bundled", 200],
+]);
+
+/**
+ * Distance value assigned to global / user-home rules.
+ */
+export const GLOBAL_DISTANCE = 9999;
+
+/**
+ * Per-rule body character cap (default).
+ */
+export const DEFAULT_MAX_RULE_CHARS = 12000;
+
+export const DEFAULT_MAX_SCAN_FILES = 1000;
+
+/**
+ * Total injected chars per tool result (default).
+ */
+export const DEFAULT_MAX_RESULT_CHARS = 40000;
+
+/**
+ * Truncation marker template. `{path}` is replaced with the relative path.
+ */
+export const TRUNCATION_NOTICE = "\n\n[Rule truncated. Read full rule: {path}]";
+
+/**
+ * Directories excluded by the recursive scanner regardless of glob settings.
+ */
+export const SCANNER_EXCLUDED_DIRS: readonly string[] = [
+ "node_modules",
+ ".git",
+ "dist",
+ "build",
+ ".turbo",
+ ".next",
+ "coverage",
+];
diff --git a/plugins/omo/components/rules/src/rules/engine.ts b/plugins/omo/components/rules/src/rules/engine.ts
new file mode 100644
index 00000000..84ad3471
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/engine.ts
@@ -0,0 +1,531 @@
+import { realpathSync } from "node:fs";
+import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
+
+import {
+ clearSession,
+ createSessionState,
+ isDynamicInjected as isDynamicInjectedInState,
+ isStaticInjected as isStaticInjectedInState,
+ markDynamicInjected as markDynamicInjectedInState,
+ markStaticInjected as markStaticInjectedInState,
+} from "./cache.js";
+import {
+ DEFAULT_MAX_RESULT_CHARS,
+ DEFAULT_MAX_RULE_CHARS,
+ PROJECT_SINGLE_FILES,
+ SOURCE_PRIORITY,
+} from "./constants.js";
+import { createRuleDiscoveryCache, type RuleDiscoveryCache } from "./finder.js";
+import { formatDynamicBlock, formatStaticBlock } from "./formatter.js";
+import { hashContent, matchRule } from "./matcher.js";
+import { sortCandidates } from "./ordering.js";
+import { parseRule } from "./parser.js";
+import type { LoadedRule, MatchReason, PiRulesConfig, RuleCandidate, RuleDiagnostic, SessionState } from "./types.js";
+
+interface LoadedRuleContent {
+ frontmatter: LoadedRule["frontmatter"];
+ body: string;
+ contentHash: string;
+ diagnostic?: string;
+}
+
+type CandidateProjectMembership = Map<string, boolean>;
+type CandidateDiscoveryCache = Map<string, RuleCandidate[]>;
+type DynamicMatchCache = Map<string, MatchReason | null>;
+
+const MAX_DYNAMIC_MATCH_CACHE_ENTRIES = 4096;
+
+export interface EngineDeps {
+ findCandidates: (options: {
+ projectRoot: string | null;
+ targetFile: string | null;
+ homeDir?: string;
+ disabledSources?: ReadonlySet<string>;
+ skipUserHome?: boolean;
+ cache?: RuleDiscoveryCache;
+ }) => RuleCandidate[];
+ readFile: (path: string) => string | null;
+ findProjectRoot: (startPath: string) => string | null;
+ matchRule?: typeof matchRule;
+}
+
+export interface Engine {
+ state: SessionState;
+ config: PiRulesConfig;
+ loadStaticRules(cwd: string): { rules: LoadedRule[]; diagnostics: RuleDiagnostic[] };
+ loadDynamicRules(
+ cwd: string,
+ targetPaths: ReadonlyArray<string>,
+ ): { rules: LoadedRule[]; diagnostics: RuleDiagnostic[] };
+ formatStatic(rules: ReadonlyArray<LoadedRule>): string;
+ formatDynamic(rules: ReadonlyArray<LoadedRule>, target: string): string;
+ resetSession(cwd?: string): void;
+ isStaticInjected(rule: LoadedRule): boolean;
+ isDynamicInjected(rule: LoadedRule): boolean;
+ markStaticInjected(rule: LoadedRule): boolean;
+ markDynamicInjected(rule: LoadedRule): boolean;
+}
+
+const ROOT_SINGLE_FILE_SOURCES = new Set(PROJECT_SINGLE_FILES.filter((source) => !source.includes("/")));
+
+export function defaultConfig(): PiRulesConfig {
+ return {
+ disabled: false,
+ mode: "both",
+ maxRuleChars: DEFAULT_MAX_RULE_CHARS,
+ maxResultChars: DEFAULT_MAX_RESULT_CHARS,
+ enabledSources: "auto",
+ };
+}
+
+export function createEngine(config: PiRulesConfig, deps: EngineDeps): Engine {
+ const state = createSessionState();
+ const dynamicMatchCache: DynamicMatchCache = new Map();
+
+ function loadStaticRules(cwd: string): { rules: LoadedRule[]; diagnostics: RuleDiagnostic[] } {
+ state.cwd = cwd;
+ if (config.disabled || config.mode === "off" || config.mode === "dynamic") {
+ return emptyLoadResult(state);
+ }
+
+ const projectRoot = deps.findProjectRoot(cwd);
+ const findOptions: Parameters<EngineDeps["findCandidates"]>[0] = {
+ projectRoot,
+ targetFile: null,
+ };
+ const disabledSources = disabledSourcesFor(config);
+ if (disabledSources !== undefined) {
+ findOptions.disabledSources = disabledSources;
+ }
+ const candidates = deps.findCandidates(findOptions);
+ const result = loadStaticCandidates(candidates, deps, projectRoot);
+ storeLastLoad(state, result.rules, result.diagnostics);
+ return result;
+ }
+
+ function loadDynamicRules(
+ cwd: string,
+ targetPaths: ReadonlyArray<string>,
+ ): { rules: LoadedRule[]; diagnostics: RuleDiagnostic[] } {
+ state.cwd = cwd;
+ if (config.disabled || config.mode === "off" || config.mode === "static" || targetPaths.length === 0) {
+ return emptyLoadResult(state);
+ }
+
+ const rules: LoadedRule[] = [];
+ const diagnostics: RuleDiagnostic[] = [];
+ const seenRules = new Set<string>();
+ const loadedRuleContent = new Map<string, LoadedRuleContent | null>();
+ const projectMembership = new Map<string, boolean>();
+ const disabledSources = disabledSourcesFor(config);
+ const discoveryCache = createRuleDiscoveryCache();
+ const candidateDiscoveryCache: CandidateDiscoveryCache = new Map();
+ const cwdProjectRoot = deps.findProjectRoot(cwd);
+
+ for (const targetFile of uniqueStrings(targetPaths)) {
+ const projectRoot =
+ cwdProjectRoot !== null && isSameOrChildPath(targetFile, cwdProjectRoot)
+ ? cwdProjectRoot
+ : deps.findProjectRoot(targetFile);
+ const findOptions: Parameters<EngineDeps["findCandidates"]>[0] = {
+ projectRoot,
+ targetFile,
+ cache: discoveryCache,
+ };
+ if (disabledSources !== undefined) {
+ findOptions.disabledSources = disabledSources;
+ }
+ const candidates = findSortedCandidatesCached(candidateDiscoveryCache, deps.findCandidates, findOptions);
+
+ for (const candidate of candidates) {
+ const loadedRule = loadCandidate(
+ candidate,
+ deps,
+ diagnostics,
+ projectRoot,
+ loadedRuleContent,
+ projectMembership,
+ );
+ if (loadedRule === null) {
+ continue;
+ }
+
+ const matchReason = matchDynamicRuleCached(
+ dynamicMatchCache,
+ projectRoot,
+ targetFile,
+ candidate,
+ loadedRule,
+ deps.matchRule ?? matchRule,
+ );
+
+ if (matchReason === null) {
+ continue;
+ }
+
+ const dedupKey = ruleDedupKey(loadedRule);
+ if (seenRules.has(dedupKey)) {
+ continue;
+ }
+
+ seenRules.add(dedupKey);
+ rules.push({ ...loadedRule, matchReason });
+ }
+ }
+
+ const sortedRules = sortCandidates(rules);
+ storeLastLoad(state, sortedRules, diagnostics);
+ return { rules: sortedRules, diagnostics };
+ }
+
+ return {
+ state,
+ config,
+ loadStaticRules,
+ loadDynamicRules,
+ formatStatic: (rules) =>
+ formatStaticBlock(rules, { maxRuleChars: config.maxRuleChars, maxResultChars: config.maxResultChars }),
+ formatDynamic: (rules, target) =>
+ formatDynamicBlock(rules, target, {
+ maxRuleChars: config.maxRuleChars,
+ maxResultChars: config.maxResultChars,
+ }),
+ resetSession: (cwd) => {
+ clearSession(state);
+ dynamicMatchCache.clear();
+ if (cwd !== undefined) {
+ state.cwd = cwd;
+ }
+ },
+ isStaticInjected: (rule) => isStaticInjectedInState(state, rule),
+ isDynamicInjected: (rule) => isDynamicInjectedInState(state, rule),
+ markStaticInjected: (rule) => markStaticInjectedInState(state, rule),
+ markDynamicInjected: (rule) => markDynamicInjectedInState(state, rule),
+ };
+}
+
+function matchDynamicRuleCached(
+ cache: DynamicMatchCache,
+ projectRoot: string | null,
+ targetFile: string,
+ candidate: RuleCandidate,
+ loadedRule: LoadedRule,
+ matchRuleImpl: typeof matchRule,
+): MatchReason | null {
+ const cacheKey = dynamicMatchCacheKey(projectRoot, targetFile, candidate, loadedRule.contentHash);
+ if (cache.has(cacheKey)) {
+ const cachedReason = cache.get(cacheKey) ?? null;
+ cache.delete(cacheKey);
+ cache.set(cacheKey, cachedReason);
+ return cachedReason;
+ }
+
+ const matchResult = matchRuleImpl({
+ frontmatter: loadedRule.frontmatter,
+ isSingleFile: candidate.isSingleFile,
+ pathBases: pathBasesForTarget(projectRoot, targetFile, candidate),
+ });
+ const reason = matchResult.matched ? matchResult.reason : null;
+ setDynamicMatchCacheEntry(cache, cacheKey, reason);
+ return reason;
+}
+
+function setDynamicMatchCacheEntry(cache: DynamicMatchCache, cacheKey: string, reason: MatchReason | null): void {
+ if (cache.size >= MAX_DYNAMIC_MATCH_CACHE_ENTRIES) {
+ const oldestCacheKey = cache.keys().next().value;
+ if (oldestCacheKey !== undefined) {
+ cache.delete(oldestCacheKey);
+ }
+ }
+ cache.set(cacheKey, reason);
+}
+
+function dynamicMatchCacheKey(
+ projectRoot: string | null,
+ targetFile: string,
+ candidate: RuleCandidate,
+ contentHash: string,
+): string {
+ return [
+ projectRoot ?? "",
+ toPosixPath(resolve(targetFile)),
+ candidate.realPath,
+ candidate.relativePath,
+ candidate.source,
+ candidate.isGlobal ? "global" : "project",
+ candidate.isSingleFile ? "single" : "multi",
+ String(candidate.distance),
+ contentHash,
+ ].join("\0");
+}
+
+function loadStaticCandidates(candidates: ReadonlyArray<RuleCandidate>, deps: EngineDeps, projectRoot: string | null) {
+ const rules: LoadedRule[] = [];
+ const diagnostics: RuleDiagnostic[] = [];
+ let rootSingleFileSelected = false;
+
+ for (const candidate of sortCandidates(candidates)) {
+ if (isDedupedRootSingleFile(candidate, rootSingleFileSelected)) {
+ continue;
+ }
+
+ const loadedRule = loadCandidate(candidate, deps, diagnostics, projectRoot);
+ if (loadedRule === null) {
+ continue;
+ }
+
+ const matchReason = staticMatchReason(loadedRule);
+ if (matchReason === null) {
+ continue;
+ }
+
+ if (isRootSingleFile(candidate)) {
+ rootSingleFileSelected = true;
+ }
+
+ rules.push({ ...loadedRule, matchReason });
+ }
+
+ return { rules: sortCandidates(rules), diagnostics };
+}
+
+function loadCandidate(
+ candidate: RuleCandidate,
+ deps: EngineDeps,
+ diagnostics: RuleDiagnostic[],
+ projectRoot: string | null,
+ loadedRuleContent?: Map<string, LoadedRuleContent | null>,
+ projectMembership?: CandidateProjectMembership,
+): (LoadedRule & { matchReason: MatchReason }) | null {
+ if (!isCandidateWithinProjectCached(candidate, projectRoot, projectMembership)) {
+ diagnostics.push({
+ severity: "warning",
+ source: candidate.path,
+ message: "Rule file resolves outside project root",
+ });
+ return null;
+ }
+
+ const cachedContent = loadedRuleContent?.get(candidate.realPath);
+ if (cachedContent !== undefined) {
+ return loadedRuleFromContent(candidate, cachedContent, diagnostics);
+ }
+
+ const content = deps.readFile(candidate.path);
+ if (content === null) {
+ loadedRuleContent?.set(candidate.realPath, null);
+ diagnostics.push({ severity: "warning", source: candidate.path, message: "Unable to read rule file" });
+ return null;
+ }
+
+ const parsed = parseRule(content);
+ const loadedContent = {
+ frontmatter: parsed.frontmatter,
+ body: parsed.body,
+ contentHash: hashContent(content),
+ ...(parsed.diagnostic === undefined ? {} : { diagnostic: parsed.diagnostic }),
+ } satisfies LoadedRuleContent;
+ loadedRuleContent?.set(candidate.realPath, loadedContent);
+ return loadedRuleFromContent(candidate, loadedContent, diagnostics);
+}
+
+function loadedRuleFromContent(
+ candidate: RuleCandidate,
+ content: LoadedRuleContent | null,
+ diagnostics: RuleDiagnostic[],
+): (LoadedRule & { matchReason: MatchReason }) | null {
+ if (content === null) {
+ diagnostics.push({ severity: "warning", source: candidate.path, message: "Unable to read rule file" });
+ return null;
+ }
+
+ if (content.diagnostic !== undefined) {
+ diagnostics.push({ severity: "warning", source: candidate.path, message: content.diagnostic });
+ }
+
+ return {
+ ...candidate,
+ frontmatter: content.frontmatter,
+ body: content.body,
+ contentHash: content.contentHash,
+ matchReason: { kind: "no-match" },
+ };
+}
+
+function ruleDedupKey(rule: LoadedRule): string {
+ return `${rule.realPath}::${rule.contentHash}`;
+}
+
+function isCandidateWithinProject(candidate: RuleCandidate, projectRoot: string | null): boolean {
+ if (candidate.isGlobal) {
+ return true;
+ }
+
+ if (projectRoot === null) {
+ return false;
+ }
+
+ const relativeRealPath = relative(realPathOrResolved(projectRoot), realPathOrResolved(candidate.realPath));
+ return relativeRealPath === "" || (!relativeRealPath.startsWith("..") && !isAbsolute(relativeRealPath));
+}
+
+function isCandidateWithinProjectCached(
+ candidate: RuleCandidate,
+ projectRoot: string | null,
+ projectMembership: CandidateProjectMembership | undefined,
+): boolean {
+ if (projectMembership === undefined) {
+ return isCandidateWithinProject(candidate, projectRoot);
+ }
+
+ const cacheKey = `${projectRoot ?? ""}\0${candidate.realPath}`;
+ const cached = projectMembership.get(cacheKey);
+ if (cached !== undefined) {
+ return cached;
+ }
+
+ const isWithinProject = isCandidateWithinProject(candidate, projectRoot);
+ projectMembership.set(cacheKey, isWithinProject);
+ return isWithinProject;
+}
+
+function realPathOrResolved(path: string): string {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+
+function findSortedCandidatesCached(
+ cache: CandidateDiscoveryCache,
+ findCandidates: EngineDeps["findCandidates"],
+ options: Parameters<EngineDeps["findCandidates"]>[0],
+): RuleCandidate[] {
+ const cacheKey = candidateDiscoveryCacheKey(options);
+ const cached = cache.get(cacheKey);
+ if (cached !== undefined) {
+ return cached;
+ }
+
+ const candidates = sortCandidates(findCandidates(options));
+ cache.set(cacheKey, candidates);
+ return candidates;
+}
+
+function candidateDiscoveryCacheKey(options: Parameters<EngineDeps["findCandidates"]>[0]): string {
+ return [
+ options.projectRoot ?? "",
+ options.targetFile === null ? "" : dirname(resolve(options.targetFile)),
+ ...[...(options.disabledSources ?? [])].sort(),
+ ].join("\0");
+}
+
+function isSameOrChildPath(childPath: string, parentPath: string): boolean {
+ const childRelativePath = relative(parentPath, resolve(childPath));
+ return childRelativePath === "" || (!childRelativePath.startsWith("..") && !isAbsolute(childRelativePath));
+}
+
+function staticMatchReason(rule: LoadedRule): MatchReason | null {
+ if (rule.frontmatter.alwaysApply === true) {
+ return "alwaysApply";
+ }
+
+ if (rule.isSingleFile) {
+ return "single-file";
+ }
+
+ return null;
+}
+
+function disabledSourcesFor(config: PiRulesConfig): ReadonlySet<string> | undefined {
+ if (config.enabledSources === "auto") {
+ return undefined;
+ }
+
+ const enabledSources = new Set(config.enabledSources);
+ return new Set([...SOURCE_PRIORITY.keys()].filter((source) => !enabledSources.has(source)));
+}
+
+function isDedupedRootSingleFile(candidate: RuleCandidate, rootSingleFileSelected: boolean): boolean {
+ return rootSingleFileSelected && isRootSingleFile(candidate);
+}
+
+function isRootSingleFile(candidate: RuleCandidate): boolean {
+ return candidate.distance === 0 && candidate.isSingleFile && ROOT_SINGLE_FILE_SOURCES.has(candidate.source);
+}
+
+function pathBasesForTarget(
+ projectRoot: string | null,
+ targetFile: string,
+ candidate: RuleCandidate,
+): { projectRelative: string; scopeRelative?: string; basename: string } {
+ const targetBasename = basename(targetFile);
+ if (projectRoot === null) {
+ return { projectRelative: targetBasename, basename: targetBasename };
+ }
+
+ const projectRelative = toPosixPath(relative(projectRoot, targetFile));
+ const scopeDirectory = scopeDirectoryForCandidate(projectRoot, candidate);
+ if (scopeDirectory === null) {
+ return { projectRelative, basename: targetBasename };
+ }
+
+ return {
+ projectRelative,
+ scopeRelative: toPosixPath(relative(scopeDirectory, targetFile)),
+ basename: targetBasename,
+ };
+}
+
+function scopeDirectoryForCandidate(projectRoot: string, candidate: RuleCandidate): string | null {
+ if (candidate.isGlobal) {
+ return null;
+ }
+
+ if (candidate.isSingleFile) {
+ return dirname(candidate.path);
+ }
+
+ const sourceIndex = candidate.relativePath.indexOf(candidate.source);
+ if (sourceIndex === -1) {
+ return projectRoot;
+ }
+
+ const scopeRelativeDirectory = candidate.relativePath.slice(0, sourceIndex).replace(/\/$/, "");
+ return scopeRelativeDirectory.length === 0 ? projectRoot : join(projectRoot, scopeRelativeDirectory);
+}
+
+function toPosixPath(path: string): string {
+ return path.replaceAll("\\", "/");
+}
+
+function storeLastLoad(
+ state: SessionState,
+ rules: ReadonlyArray<LoadedRule>,
+ diagnostics: ReadonlyArray<RuleDiagnostic>,
+): void {
+ state.loadedRules.length = 0;
+ state.loadedRules.push(...rules);
+ state.diagnostics.length = 0;
+ state.diagnostics.push(...diagnostics);
+}
+
+function emptyLoadResult(state: SessionState): { rules: LoadedRule[]; diagnostics: RuleDiagnostic[] } {
+ storeLastLoad(state, [], []);
+ return { rules: [], diagnostics: [] };
+}
+
+function uniqueStrings(values: ReadonlyArray<string>): string[] {
+ const uniqueValues: string[] = [];
+ const seenValues = new Set<string>();
+ for (const value of values) {
+ if (seenValues.has(value)) {
+ continue;
+ }
+
+ seenValues.add(value);
+ uniqueValues.push(value);
+ }
+ return uniqueValues;
+}
diff --git a/plugins/omo/components/rules/src/rules/errors.ts b/plugins/omo/components/rules/src/rules/errors.ts
new file mode 100644
index 00000000..99e49bed
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/errors.ts
@@ -0,0 +1,13 @@
+export class UnsupportedRuleSourceError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "UnsupportedRuleSourceError";
+ }
+}
+
+export class RuleFrontmatterParseError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "RuleFrontmatterParseError";
+ }
+}
diff --git a/plugins/omo/components/rules/src/rules/finder-cache.ts b/plugins/omo/components/rules/src/rules/finder-cache.ts
new file mode 100644
index 00000000..f9fe6af3
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/finder-cache.ts
@@ -0,0 +1,73 @@
+import { existsSync, realpathSync, statSync } from "node:fs";
+
+import { scanRuleFiles } from "./scanner.js";
+
+type ScannedRuleFiles = ReturnType<typeof scanRuleFiles>;
+
+interface SingleFileInfo {
+ readonly path: string;
+ readonly realPath: string;
+}
+
+export interface RuleDiscoveryCache {
+ readonly scannedRuleFiles: Map<string, ScannedRuleFiles>;
+ readonly singleFileInfo: Map<string, SingleFileInfo | null>;
+}
+
+export function createRuleDiscoveryCache(): RuleDiscoveryCache {
+ return { scannedRuleFiles: new Map(), singleFileInfo: new Map() };
+}
+
+export function scanRuleFilesCached(rootDir: string, cache: RuleDiscoveryCache | undefined): ScannedRuleFiles {
+ if (cache === undefined) {
+ return scanRuleFiles({ rootDir });
+ }
+
+ const cached = cache.scannedRuleFiles.get(rootDir);
+ if (cached !== undefined) {
+ return cached;
+ }
+
+ const scannedFiles = scanRuleFiles({ rootDir });
+ cache.scannedRuleFiles.set(rootDir, scannedFiles);
+ return scannedFiles;
+}
+
+export function singleFileInfoCached(filePath: string, cache: RuleDiscoveryCache | undefined): SingleFileInfo | null {
+ if (cache === undefined) {
+ return readSingleFileInfo(filePath);
+ }
+
+ const cached = cache.singleFileInfo.get(filePath);
+ if (cached !== undefined) {
+ return cached;
+ }
+
+ const fileInfo = readSingleFileInfo(filePath);
+ cache.singleFileInfo.set(filePath, fileInfo);
+ return fileInfo;
+}
+
+function readSingleFileInfo(filePath: string): SingleFileInfo | null {
+ if (!existsSync(filePath)) {
+ return null;
+ }
+
+ try {
+ if (!statSync(filePath).isFile()) {
+ return null;
+ }
+
+ return { path: filePath, realPath: resolveRealPath(filePath) };
+ } catch {
+ return null;
+ }
+}
+
+function resolveRealPath(filePath: string): string {
+ try {
+ return realpathSync.native(filePath);
+ } catch {
+ return filePath;
+ }
+}
diff --git a/plugins/omo/components/rules/src/rules/finder-paths.ts b/plugins/omo/components/rules/src/rules/finder-paths.ts
new file mode 100644
index 00000000..c1c54ff3
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/finder-paths.ts
@@ -0,0 +1,47 @@
+import { dirname, posix, relative, resolve } from "node:path";
+
+export interface WalkDirectory {
+ readonly directory: string;
+ readonly distance: number;
+}
+
+export function getWalkDirectories(projectRoot: string, targetFile: string | null): WalkDirectory[] {
+ if (targetFile === null) {
+ return [{ directory: projectRoot, distance: 0 }];
+ }
+
+ const startDirectory = dirname(resolve(targetFile));
+ if (!isSameOrChildPath(startDirectory, projectRoot)) {
+ return [{ directory: projectRoot, distance: 0 }];
+ }
+
+ const walkDirectories: WalkDirectory[] = [];
+ let currentDirectory = startDirectory;
+ let distance = 0;
+
+ while (true) {
+ walkDirectories.push({ directory: currentDirectory, distance });
+ if (currentDirectory === projectRoot) {
+ break;
+ }
+
+ const parentDirectory = dirname(currentDirectory);
+ if (parentDirectory === currentDirectory) {
+ break;
+ }
+
+ currentDirectory = parentDirectory;
+ distance += 1;
+ }
+
+ return walkDirectories;
+}
+
+export function toRelativePath(rootDirectory: string, filePath: string): string {
+ return posix.normalize(relative(rootDirectory, filePath).replace(/\\/g, "/"));
+}
+
+function isSameOrChildPath(childPath: string, parentPath: string): boolean {
+ const childRelativePath = relative(parentPath, childPath);
+ return childRelativePath === "" || (!childRelativePath.startsWith("..") && !childRelativePath.startsWith("/"));
+}
diff --git a/plugins/omo/components/rules/src/rules/finder-sources.ts b/plugins/omo/components/rules/src/rules/finder-sources.ts
new file mode 100644
index 00000000..5277323b
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/finder-sources.ts
@@ -0,0 +1,50 @@
+import { UnsupportedRuleSourceError } from "./errors.js";
+import type { RuleSource } from "./types.js";
+
+export function toProjectRuleSource(parentDirectory: string, subDirectory: string): RuleSource {
+ const source = `${parentDirectory}/${subDirectory}`;
+ switch (source) {
+ case ".omo/rules":
+ case ".claude/rules":
+ case ".cursor/rules":
+ case ".github/instructions":
+ return source;
+ default:
+ throw new UnsupportedRuleSourceError(`Unsupported project rule source: ${source}`);
+ }
+}
+
+export function toProjectSingleFileSource(ruleFile: string): RuleSource {
+ switch (ruleFile) {
+ case ".github/copilot-instructions.md":
+ case "AGENTS.md":
+ case "CLAUDE.md":
+ case "CONTEXT.md":
+ return ruleFile;
+ default:
+ throw new UnsupportedRuleSourceError(`Unsupported project single-file source: ${ruleFile}`);
+ }
+}
+
+export function toUserHomeRuleSource(ruleSubdir: string): RuleSource {
+ const source = `~/${ruleSubdir}`;
+ switch (source) {
+ case "~/.omo/rules":
+ case "~/.opencode/rules":
+ case "~/.claude/rules":
+ return source;
+ default:
+ throw new UnsupportedRuleSourceError(`Unsupported user-home rule source: ${source}`);
+ }
+}
+
+export function toUserHomeSingleFileSource(ruleFile: string): RuleSource {
+ const source = `~/${ruleFile}`;
+ switch (source) {
+ case "~/.config/opencode/AGENTS.md":
+ case "~/.claude/CLAUDE.md":
+ return source;
+ default:
+ throw new UnsupportedRuleSourceError(`Unsupported user-home single-file source: ${source}`);
+ }
+}
diff --git a/plugins/omo/components/rules/src/rules/finder.ts b/plugins/omo/components/rules/src/rules/finder.ts
new file mode 100644
index 00000000..bbe01a9b
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/finder.ts
@@ -0,0 +1,207 @@
+import { homedir } from "node:os";
+import { join, resolve } from "node:path";
+
+import {
+ BUNDLED_RULE_SUBDIR,
+ GLOBAL_DISTANCE,
+ PROJECT_RULE_SUBDIRS,
+ PROJECT_SINGLE_FILES,
+ USER_HOME_RULE_SUBDIRS,
+ USER_HOME_SINGLE_FILES,
+} from "./constants.js";
+import { type RuleDiscoveryCache, scanRuleFilesCached, singleFileInfoCached } from "./finder-cache.js";
+import { getWalkDirectories, toRelativePath } from "./finder-paths.js";
+import {
+ toProjectRuleSource,
+ toProjectSingleFileSource,
+ toUserHomeRuleSource,
+ toUserHomeSingleFileSource,
+} from "./finder-sources.js";
+import { resolvePluginRulesRoot } from "./plugin-root.js";
+import type { RuleCandidate } from "./types.js";
+
+export type { RuleDiscoveryCache } from "./finder-cache.js";
+export { createRuleDiscoveryCache } from "./finder-cache.js";
+
+export interface FinderOptions {
+ /** Project root absolute path (use findProjectRoot to get this). */
+ projectRoot: string | null;
+ /** Target file path (used for distance calculation in dynamic injection mode). null for static mode. */
+ targetFile: string | null;
+ /** User home directory (default: os.homedir()). Injectable for tests. */
+ homeDir?: string;
+ /** Set of disabled sources to omit from discovery. Empty by default. */
+ disabledSources?: ReadonlySet<string>;
+ /** Whether to skip user-home rules. Default: false. */
+ skipUserHome?: boolean;
+ /** Plugin root directory. Defaults to PLUGIN_ROOT env or this package root. */
+ pluginRoot?: string;
+ cache?: RuleDiscoveryCache;
+}
+
+interface PluginBundledFinderOptions {
+ readonly disabledSources?: ReadonlySet<string>;
+ readonly cache?: RuleDiscoveryCache;
+ readonly pluginRoot?: string;
+}
+
+export function findRuleCandidates(options: FinderOptions): RuleCandidate[] {
+ const skipUserHome = options.skipUserHome ?? false;
+ const disabledSources = options.disabledSources ?? new Set<string>();
+ const candidates: RuleCandidate[] = [];
+ const homeDirectory = resolve(options.homeDir ?? homedir());
+
+ if (options.projectRoot !== null) {
+ candidates.push(
+ ...findProjectCandidates(options.projectRoot, options.targetFile, disabledSources, options.cache),
+ );
+ }
+
+ const pluginBundledOptions: PluginBundledFinderOptions = {
+ disabledSources,
+ ...(options.cache === undefined ? {} : { cache: options.cache }),
+ ...(options.pluginRoot === undefined ? {} : { pluginRoot: options.pluginRoot }),
+ };
+ candidates.push(...findPluginBundledCandidates(pluginBundledOptions));
+
+ if (!skipUserHome) {
+ candidates.push(...findUserHomeCandidates(homeDirectory, disabledSources, options.cache));
+ }
+
+ return candidates;
+}
+
+export function findPluginBundledCandidates(options: PluginBundledFinderOptions = {}): RuleCandidate[] {
+ if (options.disabledSources?.has("plugin-bundled") === true) {
+ return [];
+ }
+
+ const pluginRoot = resolvePluginRulesRoot(options.pluginRoot);
+ const ruleDirectory = join(pluginRoot, BUNDLED_RULE_SUBDIR);
+ const candidates: RuleCandidate[] = [];
+ for (const scannedFile of scanRuleFilesCached(ruleDirectory, options.cache)) {
+ candidates.push({
+ path: scannedFile.path,
+ realPath: scannedFile.realPath,
+ source: "plugin-bundled",
+ distance: GLOBAL_DISTANCE,
+ isGlobal: true,
+ isSingleFile: false,
+ relativePath: toRelativePath(pluginRoot, scannedFile.path),
+ });
+ }
+ return candidates;
+}
+
+function findProjectCandidates(
+ projectRoot: string,
+ targetFile: string | null,
+ disabledSources: ReadonlySet<string>,
+ cache: RuleDiscoveryCache | undefined,
+): RuleCandidate[] {
+ const rootDirectory = resolve(projectRoot);
+ const walkDirectories = getWalkDirectories(rootDirectory, targetFile);
+ const candidates: RuleCandidate[] = [];
+
+ for (const walkDirectory of walkDirectories) {
+ for (const [parentDirectory, subDirectory] of PROJECT_RULE_SUBDIRS) {
+ const source = toProjectRuleSource(parentDirectory, subDirectory);
+ if (disabledSources.has(source)) {
+ continue;
+ }
+
+ const ruleDirectory = join(walkDirectory.directory, parentDirectory, subDirectory);
+ for (const scannedFile of scanRuleFilesCached(ruleDirectory, cache)) {
+ candidates.push({
+ path: scannedFile.path,
+ realPath: scannedFile.realPath,
+ source,
+ distance: targetFile === null ? 0 : walkDirectory.distance,
+ isGlobal: false,
+ isSingleFile: false,
+ relativePath: toRelativePath(rootDirectory, scannedFile.path),
+ });
+ }
+ }
+ }
+
+ for (const walkDirectory of walkDirectories) {
+ for (const ruleFile of PROJECT_SINGLE_FILES) {
+ const source = toProjectSingleFileSource(ruleFile);
+ if (disabledSources.has(source)) {
+ continue;
+ }
+
+ const filePath = join(walkDirectory.directory, ruleFile);
+ const fileInfo = singleFileInfoCached(filePath, cache);
+ if (fileInfo === null) {
+ continue;
+ }
+
+ candidates.push({
+ path: fileInfo.path,
+ realPath: fileInfo.realPath,
+ source,
+ distance: targetFile === null ? 0 : walkDirectory.distance,
+ isGlobal: false,
+ isSingleFile: true,
+ relativePath: toRelativePath(rootDirectory, filePath),
+ });
+ }
+ }
+
+ return candidates;
+}
+
+function findUserHomeCandidates(
+ homeDirectory: string,
+ disabledSources: ReadonlySet<string>,
+ cache: RuleDiscoveryCache | undefined,
+): RuleCandidate[] {
+ const candidates: RuleCandidate[] = [];
+
+ for (const ruleSubdir of USER_HOME_RULE_SUBDIRS) {
+ const source = toUserHomeRuleSource(ruleSubdir);
+ if (disabledSources.has(source)) {
+ continue;
+ }
+
+ const ruleDirectory = join(homeDirectory, ruleSubdir);
+ for (const scannedFile of scanRuleFilesCached(ruleDirectory, cache)) {
+ candidates.push({
+ path: scannedFile.path,
+ realPath: scannedFile.realPath,
+ source,
+ distance: GLOBAL_DISTANCE,
+ isGlobal: true,
+ isSingleFile: false,
+ relativePath: toRelativePath(homeDirectory, scannedFile.path),
+ });
+ }
+ }
+
+ for (const ruleFile of USER_HOME_SINGLE_FILES) {
+ const source = toUserHomeSingleFileSource(ruleFile);
+ if (disabledSources.has(source)) {
+ continue;
+ }
+
+ const filePath = join(homeDirectory, ruleFile);
+ const fileInfo = singleFileInfoCached(filePath, cache);
+ if (fileInfo === null) {
+ continue;
+ }
+
+ candidates.push({
+ path: fileInfo.path,
+ realPath: fileInfo.realPath,
+ source,
+ distance: GLOBAL_DISTANCE,
+ isGlobal: true,
+ isSingleFile: true,
+ relativePath: toRelativePath(homeDirectory, filePath),
+ });
+ }
+
+ return candidates;
+}
diff --git a/plugins/omo/components/rules/src/rules/formatter.ts b/plugins/omo/components/rules/src/rules/formatter.ts
new file mode 100644
index 00000000..92305a7b
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/formatter.ts
@@ -0,0 +1,99 @@
+import { truncateBudget, truncateRule } from "./truncator.js";
+import type { LoadedRule } from "./types.js";
+
+export interface FormatOptions {
+ maxRuleChars: number;
+ maxResultChars: number;
+}
+
+type TruncatedRule = {
+ path: string;
+ relativePath: string;
+ body: string;
+};
+
+function formatRule(rule: TruncatedRule): string {
+ return `Instructions from: ${rule.path}\n${rule.body}`;
+}
+
+function truncateRules(rules: ReadonlyArray<LoadedRule>, options: FormatOptions): TruncatedRule[] {
+ const perRuleTruncated = rules.map((rule) => ({
+ path: rule.path,
+ relativePath: rule.relativePath,
+ // Plugin-bundled rules ship as-is. The per-rule cap exists to guard against absurd
+ // user-authored AGENTS.md files; bundled rules are author-controlled and silent
+ // mid-section truncation would break the contract that the rule landed in full.
+ // The overall maxResultChars budget still applies via truncateBudget below.
+ body:
+ rule.source === "plugin-bundled"
+ ? rule.body
+ : truncateRule(rule.body, { maxChars: options.maxRuleChars, relativePath: rule.relativePath }).body,
+ }));
+ const budgetedRules = truncateBudget({
+ rules: perRuleTruncated.map((rule) => ({ body: rule.body, relativePath: rule.relativePath })),
+ maxResultChars: options.maxResultChars,
+ });
+ const truncatedRules: TruncatedRule[] = [];
+
+ for (let index = 0; index < budgetedRules.length; index += 1) {
+ const sourceRule = perRuleTruncated[index];
+ const budgetedRule = budgetedRules[index];
+ if (sourceRule === undefined || budgetedRule === undefined) {
+ continue;
+ }
+
+ truncatedRules.push({
+ path: sourceRule.path,
+ relativePath: budgetedRule.relativePath,
+ body: budgetedRule.body,
+ });
+ }
+
+ return truncatedRules;
+}
+
+export function formatStaticBlock(rules: ReadonlyArray<LoadedRule>, options: FormatOptions): string {
+ if (rules.length === 0) {
+ return "";
+ }
+
+ return `\n\n## Project Instructions\n${truncateRules(uniqueRulesByBody(rules), options).map(formatRule).join("\n\n")}`;
+}
+
+function uniqueRulesByBody(rules: ReadonlyArray<LoadedRule>): LoadedRule[] {
+ const uniqueRules: LoadedRule[] = [];
+ const seenBodies = new Set<string>();
+ const userDescriptions = new Set<string>();
+ for (const rule of rules) {
+ const descriptionKey = rule.frontmatter.description?.trim();
+ if (rule.source === "plugin-bundled" && descriptionKey !== undefined && userDescriptions.has(descriptionKey)) {
+ continue;
+ }
+
+ const bodyKey = rule.body.trim();
+ if (seenBodies.has(bodyKey)) {
+ continue;
+ }
+
+ seenBodies.add(bodyKey);
+ if (descriptionKey !== undefined && rule.source !== "plugin-bundled") {
+ userDescriptions.add(descriptionKey);
+ }
+ uniqueRules.push(rule);
+ }
+ return uniqueRules;
+}
+
+export function formatDynamicBlock(
+ rules: ReadonlyArray<LoadedRule>,
+ targetRelativePath: string,
+ options: FormatOptions,
+): string {
+ if (rules.length === 0) {
+ return "";
+ }
+
+ return `\n\nAdditional project instructions matched for ${targetRelativePath}:\n\n${truncateRules(rules, options)
+ .map(formatRule)
+ .join("\n\n")}`;
+}
diff --git a/plugins/omo/components/rules/src/rules/matcher.ts b/plugins/omo/components/rules/src/rules/matcher.ts
new file mode 100644
index 00000000..227e427e
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/matcher.ts
@@ -0,0 +1,142 @@
+import { createHash } from "node:crypto";
+import picomatch from "picomatch";
+import type { MatchReason, RuleFrontmatter } from "./types.js";
+
+export interface MatcherInput {
+ frontmatter: RuleFrontmatter;
+ isSingleFile: boolean;
+ /** Path bases to try matching against (POSIX-normalized). */
+ pathBases: { projectRelative: string; scopeRelative?: string; basename: string };
+}
+
+export interface MatchResult {
+ matched: boolean;
+ reason: MatchReason;
+}
+
+interface CompiledPattern {
+ pattern: string;
+ isMatch: (path: string) => boolean;
+}
+
+interface CompiledPatternSet {
+ positivePatterns: CompiledPattern[];
+ negativeMatchers: Array<(path: string) => boolean>;
+}
+
+const compiledPatternSets = new Map<string, CompiledPatternSet>();
+
+export function matchRule(input: MatcherInput): MatchResult {
+ if (input.isSingleFile) {
+ return { matched: true, reason: "single-file" };
+ }
+
+ if (input.frontmatter.alwaysApply === true) {
+ return { matched: true, reason: "alwaysApply" };
+ }
+
+ const patterns = normalizeGlobs(input.frontmatter);
+ if (patterns.length === 0) {
+ return noMatch();
+ }
+
+ const pathBases = normalizedPathBases(input.pathBases);
+ const { positivePatterns, negativeMatchers } = compiledPatternSetFor(patterns);
+
+ for (const { pattern, isMatch } of positivePatterns) {
+ for (const pathBase of pathBases) {
+ if (!isMatch(pathBase)) {
+ continue;
+ }
+
+ if (isExcluded(pathBase, negativeMatchers)) {
+ return noMatch();
+ }
+
+ return { matched: true, reason: { kind: "glob", pattern } };
+ }
+ }
+
+ return noMatch();
+}
+
+export function normalizeGlobs(frontmatter: RuleFrontmatter): string[] {
+ const patterns = [
+ ...normalizePatternList(frontmatter.globs),
+ ...normalizePatternList(frontmatter.paths),
+ ...normalizePatternList(frontmatter.applyTo),
+ ];
+
+ return [...new Set(patterns.map(normalizePath))];
+}
+
+export function hashContent(body: string): string {
+ return createHash("sha256").update(body).digest("hex");
+}
+
+function normalizePatternList(patterns: string | string[] | undefined): string[] {
+ if (patterns === undefined) {
+ return [];
+ }
+
+ return Array.isArray(patterns) ? patterns : [patterns];
+}
+
+function normalizePath(path: string): string {
+ return path.replaceAll("\\", "/");
+}
+
+function normalizedPathBases(pathBases: MatcherInput["pathBases"]): string[] {
+ const normalizedBases = [normalizePath(pathBases.projectRelative)];
+ if (pathBases.scopeRelative !== undefined) {
+ normalizedBases.push(normalizePath(pathBases.scopeRelative));
+ }
+ normalizedBases.push(normalizePath(pathBases.basename));
+ return normalizedBases;
+}
+
+function compiledPatternSetFor(patterns: ReadonlyArray<string>): CompiledPatternSet {
+ const cacheKey = JSON.stringify(patterns);
+ const cached = compiledPatternSets.get(cacheKey);
+ if (cached !== undefined) {
+ return cached;
+ }
+
+ const compiled = compilePatternSet(patterns);
+ compiledPatternSets.set(cacheKey, compiled);
+ return compiled;
+}
+
+function compilePatternSet(patterns: ReadonlyArray<string>): CompiledPatternSet {
+ const positivePatterns: CompiledPattern[] = [];
+ const negativeMatchers: Array<(path: string) => boolean> = [];
+
+ for (const pattern of patterns) {
+ if (pattern.startsWith("!")) {
+ negativeMatchers.push(createGlobMatcher(pattern.slice(1)));
+ continue;
+ }
+
+ positivePatterns.push({ pattern, isMatch: createGlobMatcher(pattern) });
+ }
+
+ return { positivePatterns, negativeMatchers };
+}
+
+function createGlobMatcher(pattern: string): (path: string) => boolean {
+ return picomatch(normalizePath(pattern), { bash: true, dot: true });
+}
+
+function isExcluded(pathBase: string, negativeMatchers: ReadonlyArray<(path: string) => boolean>): boolean {
+ for (const isMatch of negativeMatchers) {
+ if (isMatch(pathBase)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+function noMatch(): MatchResult {
+ return { matched: false, reason: { kind: "no-match" } };
+}
diff --git a/plugins/omo/components/rules/src/rules/ordering.ts b/plugins/omo/components/rules/src/rules/ordering.ts
new file mode 100644
index 00000000..c811e2f2
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/ordering.ts
@@ -0,0 +1,33 @@
+import { SOURCE_PRIORITY } from "./constants.js";
+import type { RuleCandidate } from "./types.js";
+
+export function sortCandidates<T extends RuleCandidate>(candidates: ReadonlyArray<T>): T[] {
+ return candidates
+ .map((candidate, index) => ({ candidate, index }))
+ .sort((left, right) => compareCandidates(left.candidate, right.candidate) || left.index - right.index)
+ .map(({ candidate }) => candidate);
+}
+
+export function compareCandidates(a: RuleCandidate, b: RuleCandidate): number {
+ return (
+ compareBoolean(a.isGlobal, b.isGlobal) ||
+ compareNumber(a.distance, b.distance) ||
+ compareNumber(SOURCE_PRIORITY.get(a.source) ?? Infinity, SOURCE_PRIORITY.get(b.source) ?? Infinity) ||
+ compareString(a.relativePath, b.relativePath) ||
+ compareString(a.realPath, b.realPath)
+ );
+}
+
+function compareBoolean(a: boolean, b: boolean): number {
+ return Number(a) - Number(b);
+}
+
+function compareNumber(a: number, b: number): number {
+ return a - b;
+}
+
+function compareString(a: string, b: string): number {
+ if (a < b) return -1;
+ if (a > b) return 1;
+ return 0;
+}
diff --git a/plugins/omo/components/rules/src/rules/parser.ts b/plugins/omo/components/rules/src/rules/parser.ts
new file mode 100644
index 00000000..34f13d0d
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/parser.ts
@@ -0,0 +1,326 @@
+import { RuleFrontmatterParseError } from "./errors.js";
+import type { ParsedRule, RuleFrontmatter } from "./types.js";
+
+const FRONTMATTER_OPENING = "---\n";
+const FRONTMATTER_OPENING_CRLF = "---\r\n";
+
+/** Parse markdown rule content and extract the supported YAML frontmatter subset. */
+export function parseRule(content: string): ParsedRule {
+ const normalizedContent = stripBom(content);
+ const openingLength = getOpeningDelimiterLength(normalizedContent);
+ if (openingLength === 0) {
+ return { frontmatter: {}, body: normalizedContent };
+ }
+
+ const closingDelimiter = findClosingDelimiter(normalizedContent, openingLength);
+ if (closingDelimiter === null) {
+ return {
+ frontmatter: {},
+ body: normalizedContent,
+ diagnostic: "Missing closing frontmatter delimiter",
+ };
+ }
+
+ const yamlContent = normalizedContent.slice(openingLength, closingDelimiter.start);
+ const body = normalizedContent.slice(closingDelimiter.bodyStart);
+
+ try {
+ return { frontmatter: parseYamlFrontmatter(yamlContent), body };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Invalid YAML frontmatter";
+ return {
+ frontmatter: {},
+ body: normalizedContent,
+ diagnostic: `Malformed frontmatter: ${message}`,
+ };
+ }
+}
+
+function stripBom(content: string): string {
+ return content.startsWith("\uFEFF") ? content.slice(1) : content;
+}
+
+function getOpeningDelimiterLength(content: string): number {
+ if (content.startsWith(FRONTMATTER_OPENING_CRLF)) return FRONTMATTER_OPENING_CRLF.length;
+ if (content.startsWith(FRONTMATTER_OPENING)) return FRONTMATTER_OPENING.length;
+ return 0;
+}
+
+function findClosingDelimiter(content: string, openingLength: number): { start: number; bodyStart: number } | null {
+ let lineStart = openingLength;
+
+ while (lineStart <= content.length) {
+ const nextNewline = content.indexOf("\n", lineStart);
+ const lineEnd = nextNewline === -1 ? content.length : nextNewline;
+ const line = content.slice(lineStart, lineEnd).replace(/\r$/, "");
+
+ if (line === "---") {
+ return {
+ start: lineStart,
+ bodyStart: nextNewline === -1 ? content.length : nextNewline + 1,
+ };
+ }
+
+ if (nextNewline === -1) break;
+ lineStart = nextNewline + 1;
+ }
+
+ return null;
+}
+
+function parseYamlFrontmatter(yamlContent: string): RuleFrontmatter {
+ const lines = yamlContent.replace(/\r\n/g, "\n").split("\n");
+ const frontmatter: RuleFrontmatter = {};
+ const globValues: string[] = [];
+ let lineIndex = 0;
+
+ while (lineIndex < lines.length) {
+ const rawLine = lines[lineIndex];
+ if (rawLine === undefined) break;
+
+ const line = stripComment(rawLine).trim();
+ if (line.length === 0) {
+ lineIndex += 1;
+ continue;
+ }
+
+ const colonIndex = line.indexOf(":");
+ if (colonIndex === -1) {
+ throw new RuleFrontmatterParseError(`Expected key-value pair on line ${lineIndex + 1}`);
+ }
+
+ const key = line.slice(0, colonIndex).trim();
+ const rawValue = line.slice(colonIndex + 1).trim();
+
+ if (key === "description") {
+ frontmatter.description = parseStringValue(rawValue);
+ lineIndex += 1;
+ continue;
+ }
+
+ if (key === "alwaysApply") {
+ frontmatter.alwaysApply = parseBooleanValue(rawValue, lineIndex + 1);
+ lineIndex += 1;
+ continue;
+ }
+
+ if (key === "globs" || key === "paths" || key === "applyTo") {
+ const parsed = parseGlobValue(rawValue, lines, lineIndex);
+ for (const glob of parsed.values) {
+ if (!globValues.includes(glob)) globValues.push(glob);
+ }
+ lineIndex += parsed.consumed;
+ continue;
+ }
+
+ lineIndex += 1;
+ }
+
+ const singleGlob = globValues[0];
+ if (globValues.length === 1 && singleGlob !== undefined) {
+ frontmatter.globs = singleGlob;
+ } else if (globValues.length > 1) {
+ frontmatter.globs = globValues;
+ }
+
+ return frontmatter;
+}
+
+function parseBooleanValue(value: string, lineNumber: number): boolean {
+ if (value === "true") return true;
+ if (value === "false") return false;
+ throw new RuleFrontmatterParseError(`Expected boolean on line ${lineNumber}`);
+}
+
+function parseGlobValue(rawValue: string, lines: string[], lineIndex: number): { values: string[]; consumed: number } {
+ if (rawValue.startsWith("[")) {
+ return { values: parseInlineArray(rawValue), consumed: 1 };
+ }
+
+ if (rawValue.length === 0) {
+ return parseMultilineArray(lines, lineIndex);
+ }
+
+ const value = parseStringValue(rawValue);
+ if (value.includes(",")) {
+ return {
+ values: value
+ .split(",")
+ .map((item) => item.trim())
+ .filter(Boolean),
+ consumed: 1,
+ };
+ }
+
+ return { values: [value], consumed: 1 };
+}
+
+function parseMultilineArray(lines: string[], lineIndex: number): { values: string[]; consumed: number } {
+ const values: string[] = [];
+ let consumed = 1;
+
+ for (let index = lineIndex + 1; index < lines.length; index += 1) {
+ const rawLine = lines[index];
+ if (rawLine === undefined) break;
+
+ const lineWithoutComment = stripComment(rawLine);
+ if (lineWithoutComment.trim().length === 0) {
+ consumed += 1;
+ continue;
+ }
+
+ const arrayItem = lineWithoutComment.match(/^\s+-\s*(.*)$/);
+ if (arrayItem === null) break;
+
+ values.push(parseStringValue(arrayItem[1] ?? ""));
+ consumed += 1;
+ }
+
+ return { values: values.filter(Boolean), consumed };
+}
+
+function parseInlineArray(value: string): string[] {
+ const closingBracketIndex = findClosingBracket(value);
+ if (closingBracketIndex === -1) {
+ throw new RuleFrontmatterParseError("Unclosed inline array");
+ }
+
+ const trailing = value.slice(closingBracketIndex + 1).trim();
+ if (trailing.length > 0) {
+ throw new RuleFrontmatterParseError("Unexpected content after inline array");
+ }
+
+ const content = value.slice(1, closingBracketIndex).trim();
+ if (content.length === 0) return [];
+
+ return splitCommaSeparated(content).map(parseStringValue).filter(Boolean);
+}
+
+function findClosingBracket(value: string): number {
+ let quote: string | null = null;
+ let escaped = false;
+
+ for (let index = 0; index < value.length; index += 1) {
+ const character = value[index];
+ if (character === undefined) continue;
+
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+
+ if (quote !== null && character === "\\") {
+ escaped = true;
+ continue;
+ }
+
+ if (character === '"' || character === "'") {
+ if (quote === null) quote = character;
+ else if (quote === character) quote = null;
+ continue;
+ }
+
+ if (quote === null && character === "]") return index;
+ }
+
+ return -1;
+}
+
+function splitCommaSeparated(value: string): string[] {
+ const values: string[] = [];
+ let current = "";
+ let quote: string | null = null;
+ let escaped = false;
+
+ for (let index = 0; index < value.length; index += 1) {
+ const character = value[index];
+ if (character === undefined) continue;
+
+ if (escaped) {
+ current += character;
+ escaped = false;
+ continue;
+ }
+
+ if (quote !== null && character === "\\") {
+ current += character;
+ escaped = true;
+ continue;
+ }
+
+ if (character === '"' || character === "'") {
+ if (quote === null) quote = character;
+ else if (quote === character) quote = null;
+ current += character;
+ continue;
+ }
+
+ if (quote === null && character === ",") {
+ values.push(current.trim());
+ current = "";
+ continue;
+ }
+
+ current += character;
+ }
+
+ if (quote !== null) {
+ throw new RuleFrontmatterParseError("Unclosed quoted value");
+ }
+
+ values.push(current.trim());
+ return values.filter(Boolean);
+}
+
+function parseStringValue(value: string): string {
+ if (value.length === 0) return "";
+ if (value.startsWith('"')) return parseJsonString(value);
+ if (value.startsWith("'") && value.endsWith("'")) return value.slice(1, -1);
+ if (value.startsWith("'")) throw new RuleFrontmatterParseError("Unclosed quoted value");
+ return value;
+}
+
+function parseJsonString(value: string): string {
+ let parsedValue: unknown;
+ try {
+ parsedValue = JSON.parse(value);
+ } catch {
+ throw new RuleFrontmatterParseError("Invalid JSON-quoted string");
+ }
+
+ if (typeof parsedValue !== "string") {
+ throw new RuleFrontmatterParseError("Expected JSON-quoted string");
+ }
+
+ return parsedValue;
+}
+
+function stripComment(line: string): string {
+ let quote: string | null = null;
+ let escaped = false;
+
+ for (let index = 0; index < line.length; index += 1) {
+ const character = line[index];
+ if (character === undefined) continue;
+
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+
+ if (quote !== null && character === "\\") {
+ escaped = true;
+ continue;
+ }
+
+ if (character === '"' || character === "'") {
+ if (quote === null) quote = character;
+ else if (quote === character) quote = null;
+ continue;
+ }
+
+ if (quote === null && character === "#") return line.slice(0, index);
+ }
+
+ return line;
+}
diff --git a/plugins/omo/components/rules/src/rules/plugin-root.ts b/plugins/omo/components/rules/src/rules/plugin-root.ts
new file mode 100644
index 00000000..c3ee49c3
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/plugin-root.ts
@@ -0,0 +1,55 @@
+import { statSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const PLUGIN_MANIFEST_PATH = join(".codex-plugin", "plugin.json");
+
+export function resolvePluginRulesRoot(pluginRoot: string | undefined, moduleUrl = import.meta.url): string {
+ const configuredRoot = pluginRoot ?? process.env["PLUGIN_ROOT"];
+ if (configuredRoot !== undefined && configuredRoot.trim().length > 0) {
+ return resolveRulesComponentRoot(resolve(configuredRoot));
+ }
+
+ const discoveredRoot = findNearestPluginRoot(dirname(fileURLToPath(moduleUrl)));
+ if (discoveredRoot !== null) {
+ return resolveRulesComponentRoot(discoveredRoot);
+ }
+
+ return fileURLToPath(new URL("../../..", moduleUrl));
+}
+
+function findNearestPluginRoot(startDirectory: string): string | null {
+ let currentDirectory = resolve(startDirectory);
+ while (true) {
+ if (isFile(join(currentDirectory, PLUGIN_MANIFEST_PATH))) {
+ return currentDirectory;
+ }
+
+ const parentDirectory = dirname(currentDirectory);
+ if (parentDirectory === currentDirectory) {
+ return null;
+ }
+ currentDirectory = parentDirectory;
+ }
+}
+
+function resolveRulesComponentRoot(pluginRoot: string): string {
+ const componentRoot = join(pluginRoot, "components", "rules");
+ return isDirectory(componentRoot) ? componentRoot : pluginRoot;
+}
+
+function isFile(path: string): boolean {
+ try {
+ return statSync(path).isFile();
+ } catch {
+ return false;
+ }
+}
+
+function isDirectory(path: string): boolean {
+ try {
+ return statSync(path).isDirectory();
+ } catch {
+ return false;
+ }
+}
diff --git a/plugins/omo/components/rules/src/rules/project-root.ts b/plugins/omo/components/rules/src/rules/project-root.ts
new file mode 100644
index 00000000..525358e8
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/project-root.ts
@@ -0,0 +1,30 @@
+import { existsSync, statSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+
+import { PROJECT_MARKERS } from "./constants.js";
+
+export function findProjectRoot(startPath: string, markers: ReadonlyArray<string> = PROJECT_MARKERS): string | null {
+ const resolvedStartPath = resolve(startPath);
+
+ if (!existsSync(resolvedStartPath)) {
+ return null;
+ }
+
+ const startStats = statSync(resolvedStartPath);
+ let currentDirectory = startStats.isDirectory() ? resolvedStartPath : dirname(resolvedStartPath);
+ const filesystemRoot = resolve("/");
+
+ while (true) {
+ for (const marker of markers) {
+ if (existsSync(join(currentDirectory, marker))) {
+ return currentDirectory;
+ }
+ }
+
+ if (currentDirectory === filesystemRoot) {
+ return null;
+ }
+
+ currentDirectory = dirname(currentDirectory);
+ }
+}
diff --git a/plugins/omo/components/rules/src/rules/scanner.ts b/plugins/omo/components/rules/src/rules/scanner.ts
new file mode 100644
index 00000000..8c6f4ef7
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/scanner.ts
@@ -0,0 +1,162 @@
+import { type Dirent, existsSync, lstatSync, readdirSync, realpathSync, type Stats, statSync } from "node:fs";
+import { isAbsolute, join, resolve } from "node:path";
+
+import { DEFAULT_MAX_SCAN_FILES, RULE_FILE_EXTENSIONS, SCANNER_EXCLUDED_DIRS } from "./constants.js";
+
+export interface ScanOptions {
+ rootDir: string;
+ excludedDirs?: ReadonlyArray<string>;
+ /** Maximum recursion depth. Default: 10 */
+ maxDepth?: number;
+ maxFiles?: number;
+}
+
+export interface ScannedFile {
+ /** Absolute path as encountered (may be a symlink). */
+ path: string;
+ /** Real (resolved) path; same as path if not a symlink. */
+ realPath: string;
+}
+
+export function scanRuleFiles(options: ScanOptions): ScannedFile[] {
+ const rootPath = toAbsolutePath(options.rootDir);
+ if (!existsSync(rootPath)) {
+ return [];
+ }
+
+ let rootStats: Stats;
+ try {
+ rootStats = statSync(rootPath);
+ } catch {
+ return [];
+ }
+
+ if (!rootStats.isDirectory()) {
+ return [];
+ }
+
+ const results: ScannedFile[] = [];
+ const visitedDirectories = new Set<string>();
+ const excludedDirs = new Set(options.excludedDirs ?? SCANNER_EXCLUDED_DIRS);
+ const maxDepth = options.maxDepth ?? 10;
+ const maxFiles = normalizeMaxFiles(options.maxFiles);
+
+ scanDirectory(rootPath, 0, maxDepth, maxFiles, excludedDirs, visitedDirectories, results);
+ return results;
+}
+
+function normalizeMaxFiles(maxFiles: number | undefined): number {
+ const value = maxFiles ?? DEFAULT_MAX_SCAN_FILES;
+ if (!Number.isFinite(value) || value < 0) return DEFAULT_MAX_SCAN_FILES;
+ return Math.floor(value);
+}
+
+function toAbsolutePath(filePath: string): string {
+ return isAbsolute(filePath) ? filePath : resolve(filePath);
+}
+
+function scanDirectory(
+ directoryPath: string,
+ depth: number,
+ maxDepth: number,
+ maxFiles: number,
+ excludedDirs: ReadonlySet<string>,
+ visitedDirectories: Set<string>,
+ results: ScannedFile[],
+): void {
+ if (results.length >= maxFiles) {
+ return;
+ }
+
+ let realDirectoryPath: string;
+ try {
+ realDirectoryPath = realpathSync.native(directoryPath);
+ } catch {
+ return;
+ }
+
+ if (visitedDirectories.has(realDirectoryPath)) {
+ return;
+ }
+ visitedDirectories.add(realDirectoryPath);
+
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(directoryPath, { withFileTypes: true }).sort((leftEntry, rightEntry) =>
+ leftEntry.name.localeCompare(rightEntry.name),
+ );
+ } catch {
+ return;
+ }
+
+ for (const entry of entries) {
+ if (results.length >= maxFiles) {
+ return;
+ }
+
+ const entryPath = join(directoryPath, entry.name);
+
+ if (entry.isDirectory()) {
+ if (!excludedDirs.has(entry.name) && depth < maxDepth) {
+ scanDirectory(entryPath, depth + 1, maxDepth, maxFiles, excludedDirs, visitedDirectories, results);
+ }
+ continue;
+ }
+
+ if (entry.isSymbolicLink()) {
+ scanSymbolicLink(entryPath, entry.name, depth, maxDepth, maxFiles, excludedDirs, visitedDirectories, results);
+ continue;
+ }
+
+ if (entry.isFile() && isRuleFile(entry.name)) {
+ results.push({ path: entryPath, realPath: resolveRealPath(entryPath) });
+ }
+ }
+}
+
+function scanSymbolicLink(
+ linkPath: string,
+ linkName: string,
+ depth: number,
+ maxDepth: number,
+ maxFiles: number,
+ excludedDirs: ReadonlySet<string>,
+ visitedDirectories: Set<string>,
+ results: ScannedFile[],
+): void {
+ if (results.length >= maxFiles) {
+ return;
+ }
+
+ let targetStats: Stats;
+ try {
+ targetStats = statSync(linkPath);
+ } catch {
+ return;
+ }
+
+ if (targetStats.isDirectory()) {
+ if (!excludedDirs.has(linkName) && depth < maxDepth) {
+ scanDirectory(linkPath, depth + 1, maxDepth, maxFiles, excludedDirs, visitedDirectories, results);
+ }
+ return;
+ }
+
+ if (targetStats.isFile() && isRuleFile(linkName)) {
+ results.push({ path: linkPath, realPath: resolveRealPath(linkPath) });
+ }
+}
+
+function isRuleFile(fileName: string): boolean {
+ return RULE_FILE_EXTENSIONS.some((extension) => fileName.endsWith(extension));
+}
+
+function resolveRealPath(filePath: string): string {
+ try {
+ const realPath = realpathSync.native(filePath);
+ const fileStats = lstatSync(filePath);
+ return fileStats.isSymbolicLink() ? realPath : filePath;
+ } catch {
+ return filePath;
+ }
+}
diff --git a/plugins/omo/components/rules/src/rules/truncator.ts b/plugins/omo/components/rules/src/rules/truncator.ts
new file mode 100644
index 00000000..2c54bea8
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/truncator.ts
@@ -0,0 +1,67 @@
+import { TRUNCATION_NOTICE } from "./constants.js";
+import type { TruncationResult } from "./types.js";
+
+type BudgetRule = {
+ body: string;
+ relativePath: string;
+};
+
+type BudgetResult = BudgetRule & {
+ truncated: boolean;
+};
+
+function truncationNotice(relativePath: string): string {
+ return TRUNCATION_NOTICE.replace("{path}", relativePath);
+}
+
+function safeSliceEnd(body: string, end: number): number {
+ if (end <= 0) {
+ return 0;
+ }
+
+ const lastCodeUnit = body.charCodeAt(end - 1);
+ if (lastCodeUnit >= 0xd800 && lastCodeUnit <= 0xdbff) {
+ return end - 1;
+ }
+
+ return end;
+}
+
+export function truncateRule(body: string, options: { maxChars: number; relativePath: string }): TruncationResult {
+ if (body.length <= options.maxChars) {
+ return { body, truncated: false, originalLength: body.length };
+ }
+
+ const notice = truncationNotice(options.relativePath);
+ if (options.maxChars < notice.length) {
+ return { body: notice, truncated: true, originalLength: body.length };
+ }
+
+ const sliceEnd = safeSliceEnd(body, options.maxChars - notice.length);
+ return { body: `${body.slice(0, sliceEnd)}${notice}`, truncated: true, originalLength: body.length };
+}
+
+export function truncateBudget(input: { rules: ReadonlyArray<BudgetRule>; maxResultChars: number }): BudgetResult[] {
+ const results: BudgetResult[] = [];
+ let remainingBudget = input.maxResultChars;
+
+ for (const rule of input.rules) {
+ if (remainingBudget >= rule.body.length) {
+ results.push({ body: rule.body, truncated: false, relativePath: rule.relativePath });
+ remainingBudget -= rule.body.length;
+ continue;
+ }
+
+ const notice = truncationNotice(rule.relativePath);
+ if (remainingBudget <= notice.length) {
+ break;
+ }
+
+ const sliceEnd = safeSliceEnd(rule.body, remainingBudget - notice.length);
+ const body = `${rule.body.slice(0, sliceEnd)}${notice}`;
+ results.push({ body, truncated: true, relativePath: rule.relativePath });
+ remainingBudget -= body.length;
+ }
+
+ return results;
+}
diff --git a/plugins/omo/components/rules/src/rules/types.ts b/plugins/omo/components/rules/src/rules/types.ts
new file mode 100644
index 00000000..f24f046d
--- /dev/null
+++ b/plugins/omo/components/rules/src/rules/types.ts
@@ -0,0 +1,139 @@
+/**
+ * Public types for pi-rules.
+ *
+ * These types are stable contracts between modules. The frontmatter type
+ * mirrors omo's `RuleMetadata` plus Claude (`paths`) and Copilot (`applyTo`)
+ * aliases that are normalized into `globs` internally.
+ */
+
+/**
+ * YAML frontmatter parsed from a rule markdown file.
+ * `paths` (Claude alias) and `applyTo` (Copilot alias) are normalized into
+ * `globs` by the parser before any matcher sees this struct.
+ */
+export interface RuleFrontmatter {
+ description?: string;
+ globs?: string | string[];
+ paths?: string | string[];
+ applyTo?: string | string[];
+ alwaysApply?: boolean;
+}
+
+/**
+ * Result of parsing a rule markdown file.
+ * `body` excludes the frontmatter delimiters and the YAML payload.
+ */
+export interface ParsedRule {
+ frontmatter: RuleFrontmatter;
+ body: string;
+ /**
+ * Diagnostic message if frontmatter parsing failed but the body was salvaged.
+ * Empty when parsing succeeded.
+ */
+ diagnostic?: string;
+}
+
+/**
+ * A discovered rule file candidate before parsing/matching.
+ *
+ * `path` is the absolute path as discovered (possibly via symlink).
+ * `realPath` is the canonical resolved path used for dedup.
+ * `source` identifies which discovery source produced this candidate.
+ */
+export interface RuleCandidate {
+ path: string;
+ realPath: string;
+ source: RuleSource;
+ /**
+ * Distance from the target file directory to the directory containing this rule.
+ * 0 = same directory, 9999 = global/user-home rule.
+ */
+ distance: number;
+ isGlobal: boolean;
+ /**
+ * True when this candidate is a SINGLE-FILE rule like AGENTS.md or
+ * `.github/copilot-instructions.md` (frontmatter optional, applies always).
+ */
+ isSingleFile: boolean;
+ /**
+ * Path relative to project root, POSIX-normalized. Used for matcher and display.
+ * Empty string for user-home global rules.
+ */
+ relativePath: string;
+}
+
+/**
+ * A fully-loaded rule ready for injection.
+ */
+export interface LoadedRule extends RuleCandidate {
+ frontmatter: RuleFrontmatter;
+ body: string;
+ contentHash: string;
+ matchReason: MatchReason;
+}
+
+/**
+ * Source identifier for rule files. Used for deterministic ordering and display.
+ */
+export type RuleSource =
+ | ".omo/rules"
+ | ".claude/rules"
+ | ".cursor/rules"
+ | ".github/instructions"
+ | ".github/copilot-instructions.md"
+ | "AGENTS.md"
+ | "CLAUDE.md"
+ | "CONTEXT.md"
+ | "plugin-bundled"
+ | "~/.omo/rules"
+ | "~/.opencode/rules"
+ | "~/.claude/rules"
+ | "~/.config/opencode/AGENTS.md"
+ | "~/.claude/CLAUDE.md";
+
+/**
+ * Why a candidate matched the target file. Surfaced in the injection block so
+ * the model can attribute its behavior to a specific rule.
+ */
+export type MatchReason = "alwaysApply" | "single-file" | { kind: "glob"; pattern: string } | { kind: "no-match" };
+
+/**
+ * Truncation result.
+ */
+export interface TruncationResult {
+ body: string;
+ truncated: boolean;
+ originalLength: number;
+}
+
+/**
+ * Configuration knobs resolved from env vars and package.json.
+ */
+export interface PiRulesConfig {
+ disabled: boolean;
+ mode: "static" | "dynamic" | "both" | "off";
+ maxRuleChars: number;
+ maxResultChars: number;
+ enabledSources: RuleSource[] | "auto";
+}
+
+/**
+ * Per-session in-memory dedup state.
+ *
+ * `staticDedup` keys are `{cwd}::{rulePath}::{contentHash}` strings.
+ * `dynamicDedup` stores session-scoped `{rulePath}::{contentHash}` strings.
+ */
+export interface SessionState {
+ cwd: string | undefined;
+ staticDedup: Set<string>;
+ dynamicDedup: Map<string, Set<string>>;
+ dynamicTargetFingerprints: Map<string, string>;
+ loadedRules: LoadedRule[];
+ diagnostics: RuleDiagnostic[];
+}
+
+export interface RuleDiagnostic {
+ severity: "warning" | "error";
+ source: string;
+ message: string;
+}
diff --git a/plugins/omo/components/rules/src/tool-paths.ts b/plugins/omo/components/rules/src/tool-paths.ts
new file mode 100644
index 00000000..5974c4ae
--- /dev/null
+++ b/plugins/omo/components/rules/src/tool-paths.ts
@@ -0,0 +1,192 @@
+import { existsSync, statSync } from "node:fs";
+import { isAbsolute, resolve } from "node:path";
+
+export interface CodexPostToolUseLike {
+ tool_name: string;
+ tool_input: unknown;
+ tool_response: unknown;
+}
+
+const COMMAND_TOOL_NAMES = new Set(["bash", "shell_command", "exec_command"]);
+const TRACKED_TOOL_NAMES = new Set([
+ "read",
+ "read_file",
+ "mcp__filesystem__read_file",
+ "mcp__filesystem__read_multiple_files",
+ "mcp__filesystem__write_file",
+ "mcp__filesystem__edit_file",
+ "write",
+ "edit",
+ "multiedit",
+ "multi_edit",
+ "apply_patch",
+ "bash",
+ "shell_command",
+ "exec_command",
+]);
+
+export function extractCodexToolPaths(input: CodexPostToolUseLike, cwd: string): string[] {
+ const toolName = input.tool_name.toLowerCase();
+ if (!TRACKED_TOOL_NAMES.has(toolName) || isFailedToolResponse(input.tool_response)) {
+ return [];
+ }
+
+ const paths = new Set<string>();
+ const toolInput = isRecord(input.tool_input) ? input.tool_input : {};
+ addCommonPathFields(paths, toolInput, cwd);
+ addPatchPayloadPaths(paths, toolInput, cwd);
+ addPatchRecordPaths(paths, toolInput["files"], cwd);
+ addPatchRecordPaths(paths, toolInput["changes"], cwd);
+
+ if (COMMAND_TOOL_NAMES.has(toolName)) {
+ const command = stringProperty(toolInput, "command") ?? stringProperty(toolInput, "cmd");
+ const workdir = stringProperty(toolInput, "workdir") ?? stringProperty(toolInput, "cwd");
+ addCommandPaths(paths, command, workdir === undefined ? cwd : resolvePath(cwd, workdir));
+ }
+
+ return [...paths];
+}
+
+function addCommonPathFields(paths: Set<string>, input: Record<string, unknown>, cwd: string): void {
+ for (const key of ["path", "filePath", "file_path", "target", "targetPath", "target_path"]) {
+ addPath(paths, input[key], cwd, false);
+ }
+ for (const key of ["paths", "filePaths", "file_paths"]) {
+ addPathArray(paths, input[key], cwd, false);
+ }
+}
+
+function addPatchPayloadPaths(paths: Set<string>, input: Record<string, unknown>, cwd: string): void {
+ for (const key of ["input", "patch", "command", "cmd"]) {
+ const value = input[key];
+ if (typeof value === "string") {
+ addPatchHeaderPaths(paths, value, cwd);
+ }
+ }
+}
+
+function addPatchHeaderPaths(paths: Set<string>, patch: string, cwd: string): void {
+ for (const line of patch.split("\n")) {
+ for (const prefix of ["*** Add File: ", "*** Update File: ", "*** Move to: "]) {
+ if (line.startsWith(prefix)) {
+ addPath(paths, line.slice(prefix.length).trim(), cwd, false);
+ }
+ }
+ }
+}
+
+function addPatchRecordPaths(paths: Set<string>, value: unknown, cwd: string): void {
+ if (!Array.isArray(value)) return;
+ for (const item of value) {
+ if (typeof item === "string") {
+ addPath(paths, item, cwd, false);
+ continue;
+ }
+ if (!isRecord(item)) continue;
+ addCommonPathFields(paths, item, cwd);
+ for (const key of ["movePath", "move_path", "to", "from"]) {
+ addPath(paths, item[key], cwd, false);
+ }
+ }
+}
+
+function addCommandPaths(paths: Set<string>, command: string | undefined, cwd: string): void {
+ if (command === undefined) return;
+ for (const token of tokenizeShell(command)) {
+ if (token.length === 0 || token.startsWith("-") || token.includes("*")) {
+ continue;
+ }
+ addPath(paths, token, cwd, true);
+ }
+}
+
+function addPathArray(paths: Set<string>, value: unknown, cwd: string, mustExist: boolean): void {
+ if (!Array.isArray(value)) return;
+ for (const item of value) {
+ addPath(paths, item, cwd, mustExist);
+ }
+}
+
+function addPath(paths: Set<string>, value: unknown, cwd: string, mustExist: boolean): void {
+ if (typeof value !== "string" || value.length === 0 || looksLikeUrl(value)) {
+ return;
+ }
+
+ const path = resolvePath(cwd, value);
+ if (mustExist && !isExistingFile(path)) {
+ return;
+ }
+ paths.add(path);
+}
+
+function resolvePath(cwd: string, filePath: string): string {
+ return isAbsolute(filePath) ? filePath : resolve(cwd, filePath);
+}
+
+function isExistingFile(filePath: string): boolean {
+ try {
+ return existsSync(filePath) && statSync(filePath).isFile();
+ } catch {
+ return false;
+ }
+}
+
+function looksLikeUrl(value: string): boolean {
+ return /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value);
+}
+
+function stringProperty(value: Record<string, unknown>, key: string): string | undefined {
+ const property = value[key];
+ return typeof property === "string" && property.length > 0 ? property : undefined;
+}
+
+function tokenizeShell(command: string): string[] {
+ const tokens: string[] = [];
+ let current = "";
+ let quote: "'" | '"' | null = null;
+ let escaped = false;
+
+ for (const character of command) {
+ if (escaped) {
+ current += character;
+ escaped = false;
+ continue;
+ }
+ if (character === "\\") {
+ escaped = true;
+ continue;
+ }
+ if ((character === "'" || character === '"') && quote === null) {
+ quote = character;
+ continue;
+ }
+ if (quote === character) {
+ quote = null;
+ continue;
+ }
+ if (quote === null && /\s/.test(character)) {
+ if (current.length > 0) {
+ tokens.push(current);
+ current = "";
+ }
+ continue;
+ }
+ current += character;
+ }
+
+ if (current.length > 0) {
+ tokens.push(current);
+ }
+ return tokens;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function isFailedToolResponse(value: unknown): boolean {
+ if (!isRecord(value)) return false;
+ return (
+ value["isError"] === true || value["is_error"] === true || value["error"] === true || value["status"] === "error"
+ );
+}
diff --git a/plugins/omo/components/rules/test/bundled-rules-priority.test.ts b/plugins/omo/components/rules/test/bundled-rules-priority.test.ts
new file mode 100644
index 00000000..ee749f9a
--- /dev/null
+++ b/plugins/omo/components/rules/test/bundled-rules-priority.test.ts
@@ -0,0 +1,107 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { configFromEnvironment } from "../src/config.js";
+import { SOURCE_PRIORITY } from "../src/rules/constants.js";
+import { createEngine, defaultConfig, type EngineDeps } from "../src/rules/engine.js";
+import { resolvePluginRulesRoot } from "../src/rules/plugin-root.js";
+import type { RuleCandidate } from "../src/rules/types.js";
+
+const projectRoot = "/tmp/codex-rules-bundled-priority";
+const bundledPath = join(projectRoot, "bundled-rules", "hephaestus.md");
+const homePath = join(projectRoot, "home", ".opencode", "rules", "hephaestus.md");
+const bundledBody = "Bundled baseline discipline.";
+const homeBody = "Home baseline discipline override.";
+const tempDirectories: string[] = [];
+
+afterEach(() => {
+ for (const directory of tempDirectories.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function globalCandidate(source: "plugin-bundled" | "~/.opencode/rules", path: string): RuleCandidate {
+ return {
+ path,
+ realPath: path,
+ source,
+ distance: 9999,
+ isGlobal: true,
+ isSingleFile: false,
+ relativePath: source === "plugin-bundled" ? "bundled-rules/hephaestus.md" : ".opencode/rules/hephaestus.md",
+ };
+}
+
+function ruleMarkdown(body: string): string {
+ return [
+ "---",
+ "description: OMO Hephaestus baseline discipline for Codex",
+ "alwaysApply: true",
+ "---",
+ "",
+ body,
+ ].join("\n");
+}
+
+describe("plugin bundled rule priority", () => {
+ it("#given bundled source explicitly enabled then disabled #when parsing env #then no sources remain enabled", () => {
+ // given / when
+ const config = configFromEnvironment({
+ CODEX_RULES_ENABLED_SOURCES: "plugin-bundled",
+ CODEX_RULES_DISABLE_BUNDLED: "1",
+ });
+
+ // then
+ expect(config.enabledSources).toEqual([]);
+ });
+
+ it("#given source priorities #when comparing user-home and bundled rules #then bundled has lower priority", () => {
+ // given / when / then
+ expect(SOURCE_PRIORITY.get("~/.opencode/rules")).toBe(101);
+ expect(SOURCE_PRIORITY.get("plugin-bundled")).toBe(200);
+ });
+
+ it("#given user-home and bundled rules share a description #when formatting static rules #then user-home wins", () => {
+ // given
+ const bundledCandidate = globalCandidate("plugin-bundled", bundledPath);
+ const homeCandidate = globalCandidate("~/.opencode/rules", homePath);
+ const deps = {
+ findProjectRoot: () => projectRoot,
+ findCandidates: () => [bundledCandidate, homeCandidate],
+ readFile: (path: string) => {
+ if (path === bundledPath) return ruleMarkdown(bundledBody);
+ if (path === homePath) return ruleMarkdown(homeBody);
+ return null;
+ },
+ } satisfies EngineDeps;
+ const engine = createEngine(defaultConfig(), deps);
+
+ // when
+ const loaded = engine.loadStaticRules(projectRoot);
+ const formatted = engine.formatStatic(loaded.rules);
+
+ // then
+ expect(formatted).toContain(homePath);
+ expect(formatted).toContain(homeBody);
+ expect(formatted).not.toContain(bundledPath);
+ expect(formatted).not.toContain(bundledBody);
+ });
+
+ it("#given aggregate plugin root #when resolving rules root #then components rules directory is selected", () => {
+ // given
+ const aggregateRoot = mkdtempSync(join(tmpdir(), "codex-rules-aggregate-plugin-"));
+ const componentRoot = join(aggregateRoot, "components", "rules");
+ tempDirectories.push(aggregateRoot);
+ mkdirSync(join(aggregateRoot, ".codex-plugin"), { recursive: true });
+ mkdirSync(componentRoot, { recursive: true });
+ writeFileSync(join(aggregateRoot, ".codex-plugin", "plugin.json"), JSON.stringify({ name: "omo" }));
+
+ // when
+ const resolvedRoot = resolvePluginRulesRoot(aggregateRoot);
+
+ // then
+ expect(resolvedRoot).toBe(componentRoot);
+ });
+});
diff --git a/plugins/omo/components/rules/test/bundled-rules.test.ts b/plugins/omo/components/rules/test/bundled-rules.test.ts
new file mode 100644
index 00000000..7da2d5a9
--- /dev/null
+++ b/plugins/omo/components/rules/test/bundled-rules.test.ts
@@ -0,0 +1,268 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import {
+ type CodexPostCompactInput,
+ type CodexSessionStartInput,
+ runPostCompactHook,
+ runSessionStartHook,
+ runUserPromptSubmitHook,
+} from "../src/codex-hook.js";
+import { createRuleDiscoveryCache, findRuleCandidates } from "../src/rules/finder.js";
+
+interface FixtureOptions {
+ readonly writeProjectDuplicate?: boolean;
+}
+
+interface Fixture {
+ readonly root: string;
+ readonly pluginRoot: string;
+ readonly pluginData: string;
+ readonly bundledRulePath: string;
+ readonly projectRulePath: string;
+}
+
+const BUNDLED_ONLY_ENV = {
+ CODEX_RULES_ENABLED_SOURCES: "plugin-bundled",
+};
+
+const PROJECT_AND_BUNDLED_ENV = {
+ CODEX_RULES_ENABLED_SOURCES: ".omo/rules,plugin-bundled",
+};
+
+const DISABLED_BUNDLED_ENV = {
+ CODEX_RULES_ENABLED_SOURCES: "plugin-bundled",
+ CODEX_RULES_DISABLE_BUNDLED: "1",
+};
+
+const BUNDLED_BODY = "Bundled craftsman baseline.";
+const SHARED_BODY = "Always choose the smallest correct change.";
+
+const tempDirectories: string[] = [];
+let originalPluginRoot: string | undefined;
+
+beforeEach(() => {
+ originalPluginRoot = process.env["PLUGIN_ROOT"];
+});
+
+afterEach(() => {
+ restoreEnv("PLUGIN_ROOT", originalPluginRoot);
+ for (const directory of tempDirectories.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function makeFixture(options: FixtureOptions = {}): Fixture {
+ const root = mkdtempSync(join(tmpdir(), "codex-rules-bundled-project-"));
+ const pluginRoot = mkdtempSync(join(tmpdir(), "codex-rules-bundled-plugin-"));
+ const pluginData = mkdtempSync(join(tmpdir(), "codex-rules-bundled-data-"));
+ tempDirectories.push(root, pluginRoot, pluginData);
+
+ writeFileSync(join(root, "package.json"), JSON.stringify({ name: "fixture" }));
+ mkdirSync(join(root, ".omo", "rules"), { recursive: true });
+ mkdirSync(join(pluginRoot, "bundled-rules"), { recursive: true });
+
+ const bundledRulePath = join(pluginRoot, "bundled-rules", "hephaestus.md");
+ const bundledBody = options.writeProjectDuplicate === true ? SHARED_BODY : BUNDLED_BODY;
+ writeFileSync(bundledRulePath, ruleMarkdown(bundledBody));
+
+ const projectRulePath = join(root, ".omo", "rules", "hephaestus.md");
+ if (options.writeProjectDuplicate === true) {
+ writeFileSync(projectRulePath, ruleMarkdown(SHARED_BODY));
+ }
+
+ process.env["PLUGIN_ROOT"] = pluginRoot;
+ return { root, pluginRoot, pluginData, bundledRulePath, projectRulePath };
+}
+
+function ruleMarkdown(body: string): string {
+ return ["---", "description: Fixture", "alwaysApply: true", "---", "", body].join("\n");
+}
+
+function restoreEnv(name: string, value: string | undefined): void {
+ if (value === undefined) {
+ delete process.env[name];
+ return;
+ }
+
+ process.env[name] = value;
+}
+
+function sessionStartInput(root: string): CodexSessionStartInput {
+ return {
+ session_id: "session-1",
+ transcript_path: null,
+ cwd: root,
+ hook_event_name: "SessionStart",
+ model: "gpt-5.5",
+ permission_mode: "default",
+ source: "startup",
+ };
+}
+
+function postCompactInput(root: string): CodexPostCompactInput {
+ return {
+ session_id: "session-1",
+ turn_id: "turn-compact",
+ transcript_path: null,
+ cwd: root,
+ hook_event_name: "PostCompact",
+ model: "gpt-5.5",
+ trigger: "manual",
+ };
+}
+
+function userPromptSubmitInput(root: string): Parameters<typeof runUserPromptSubmitHook>[0] {
+ return {
+ session_id: "session-1",
+ turn_id: "turn-1",
+ transcript_path: null,
+ cwd: root,
+ hook_event_name: "UserPromptSubmit",
+ model: "gpt-5.5",
+ permission_mode: "default",
+ prompt: "continue",
+ };
+}
+
+function occurrenceCount(value: string, search: string): number {
+ return value.split(search).length - 1;
+}
+
+describe("plugin bundled rules", () => {
+ it("#given PLUGIN_ROOT with bundled markdown #when finding candidates #then plugin-bundled source is cached", () => {
+ // given
+ const { pluginRoot } = makeFixture();
+ const cache = createRuleDiscoveryCache();
+
+ // when
+ const candidates = findRuleCandidates({ projectRoot: null, targetFile: null, skipUserHome: true, cache });
+
+ // then
+ expect(candidates.map((candidate) => `${candidate.source}:${candidate.relativePath}`)).toEqual([
+ "plugin-bundled:bundled-rules/hephaestus.md",
+ ]);
+ expect(cache.scannedRuleFiles.has(join(pluginRoot, "bundled-rules"))).toBe(true);
+ });
+
+ it("#given alwaysApply bundled rule #when SessionStart runs #then static context includes it", async () => {
+ // given
+ const { root, pluginData } = makeFixture();
+
+ // when
+ const output = await runSessionStartHook(sessionStartInput(root), {
+ pluginDataRoot: pluginData,
+ env: BUNDLED_ONLY_ENV,
+ });
+
+ // then
+ expect(output).toContain('"hookEventName":"SessionStart"');
+ expect(output).toContain(BUNDLED_BODY);
+ });
+
+ it("#given same project and bundled body #when SessionStart runs #then project rule wins", async () => {
+ // given
+ const { root, pluginData, bundledRulePath, projectRulePath } = makeFixture({ writeProjectDuplicate: true });
+
+ // when
+ const output = await runSessionStartHook(sessionStartInput(root), {
+ pluginDataRoot: pluginData,
+ env: PROJECT_AND_BUNDLED_ENV,
+ });
+
+ // then
+ expect(occurrenceCount(output, SHARED_BODY)).toBe(1);
+ expect(output).toContain(projectRulePath);
+ expect(output).not.toContain(bundledRulePath);
+ });
+
+ it("#given bundled rules disabled #when SessionStart runs #then bundled context is suppressed", async () => {
+ // given
+ const { root, pluginData } = makeFixture();
+
+ // when
+ const output = await runSessionStartHook(sessionStartInput(root), {
+ pluginDataRoot: pluginData,
+ env: DISABLED_BUNDLED_ENV,
+ });
+
+ // then
+ expect(output).toBe("");
+ });
+
+ it("#given PostCompact pending flag #when UserPromptSubmit runs #then bundled static context re-injects", async () => {
+ // given
+ const { root, pluginData } = makeFixture();
+ const firstOutput = await runSessionStartHook(sessionStartInput(root), {
+ pluginDataRoot: pluginData,
+ env: BUNDLED_ONLY_ENV,
+ });
+ expect(firstOutput).toContain(BUNDLED_BODY);
+
+ // when
+ const compactOutput = await runPostCompactHook(postCompactInput(root), { pluginDataRoot: pluginData });
+ const output = await runUserPromptSubmitHook(userPromptSubmitInput(root), {
+ pluginDataRoot: pluginData,
+ env: BUNDLED_ONLY_ENV,
+ });
+
+ // then
+ expect(compactOutput).toBe("");
+ expect(output).toContain(BUNDLED_BODY);
+ });
+
+ it("#given bundled rule body exceeds per-rule cap #when SessionStart runs #then bundled body lands in full without truncation", async () => {
+ // given
+ const root = mkdtempSync(join(tmpdir(), "codex-rules-bundled-large-project-"));
+ const pluginRoot = mkdtempSync(join(tmpdir(), "codex-rules-bundled-large-plugin-"));
+ const pluginData = mkdtempSync(join(tmpdir(), "codex-rules-bundled-large-data-"));
+ tempDirectories.push(root, pluginRoot, pluginData);
+ writeFileSync(join(root, "package.json"), JSON.stringify({ name: "fixture" }));
+ mkdirSync(join(pluginRoot, "bundled-rules"), { recursive: true });
+ const oversizedBody = "The bundled craftsman discipline is non-negotiable. ".repeat(400);
+ expect(oversizedBody.length).toBeGreaterThan(12000);
+ const tailMarker = "BUNDLED_TAIL_SENTINEL_LANDS_IN_FULL";
+ const bundledBody = `${oversizedBody}\n\n${tailMarker}\n`;
+ writeFileSync(join(pluginRoot, "bundled-rules", "hephaestus.md"), ruleMarkdown(bundledBody));
+ process.env["PLUGIN_ROOT"] = pluginRoot;
+
+ // when
+ const output = await runSessionStartHook(sessionStartInput(root), {
+ pluginDataRoot: pluginData,
+ env: BUNDLED_ONLY_ENV,
+ });
+
+ // then
+ expect(output).toContain(tailMarker);
+ expect(output).not.toContain("[Rule truncated. Read full rule:");
+ });
+
+ it("#given project rule body exceeds per-rule cap #when SessionStart runs #then project body is truncated", async () => {
+ // given
+ const root = mkdtempSync(join(tmpdir(), "codex-rules-project-large-project-"));
+ const pluginRoot = mkdtempSync(join(tmpdir(), "codex-rules-project-large-plugin-"));
+ const pluginData = mkdtempSync(join(tmpdir(), "codex-rules-project-large-data-"));
+ tempDirectories.push(root, pluginRoot, pluginData);
+ writeFileSync(join(root, "package.json"), JSON.stringify({ name: "fixture" }));
+ mkdirSync(join(root, ".omo", "rules"), { recursive: true });
+ mkdirSync(join(pluginRoot, "bundled-rules"), { recursive: true });
+ const oversizedBody = "The project rule body is intentionally oversized for the cap test. ".repeat(300);
+ expect(oversizedBody.length).toBeGreaterThan(12000);
+ const tailMarker = "PROJECT_TAIL_SENTINEL_SHOULD_NOT_LAND";
+ const projectBody = `${oversizedBody}\n\n${tailMarker}\n`;
+ writeFileSync(join(root, ".omo", "rules", "oversized.md"), ruleMarkdown(projectBody));
+ process.env["PLUGIN_ROOT"] = pluginRoot;
+
+ // when
+ const output = await runSessionStartHook(sessionStartInput(root), {
+ pluginDataRoot: pluginData,
+ env: { CODEX_RULES_ENABLED_SOURCES: ".omo/rules" },
+ });
+
+ // then
+ expect(output).toContain("[Rule truncated. Read full rule: .omo/rules/oversized.md]");
+ expect(output).not.toContain(tailMarker);
+ });
+});
diff --git a/plugins/omo/components/rules/test/codex-hook-performance.test.ts b/plugins/omo/components/rules/test/codex-hook-performance.test.ts
new file mode 100644
index 00000000..6cb812bd
--- /dev/null
+++ b/plugins/omo/components/rules/test/codex-hook-performance.test.ts
@@ -0,0 +1,99 @@
+import fs from "node:fs";
+import { syncBuiltinESMExports } from "node:module";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import type { CodexPostToolUseInput } from "../src/codex-hook.js";
+
+const tempDirectories: string[] = [];
+
+afterEach(() => {
+ for (const directory of tempDirectories.splice(0)) {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function makeTempProject(ruleCount: number): { root: string; pluginData: string; targetPath: string } {
+ const root = fs.mkdtempSync(path.join(tmpdir(), "codex-rules-hook-perf-project-"));
+ const pluginData = fs.mkdtempSync(path.join(tmpdir(), "codex-rules-hook-perf-data-"));
+ tempDirectories.push(root, pluginData);
+
+ fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));
+ fs.mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });
+ fs.mkdirSync(path.join(root, "src"), { recursive: true });
+ const targetPath = path.join(root, "src", "app.ts");
+ fs.writeFileSync(targetPath, "export const app = true;\n");
+
+ for (let index = 0; index < ruleCount; index += 1) {
+ fs.writeFileSync(
+ path.join(root, ".omo", "rules", `rule-${index}.md`),
+ ["---", 'globs: "**/*.ts"', "---", "", `Rule ${index}`].join("\n"),
+ );
+ }
+
+ return { root, pluginData, targetPath };
+}
+
+function postToolUseInput(root: string, filePath: string): CodexPostToolUseInput {
+ return {
+ session_id: "session-1",
+ turn_id: "turn-1",
+ transcript_path: null,
+ cwd: root,
+ hook_event_name: "PostToolUse",
+ model: "gpt-5.5",
+ permission_mode: "default",
+ tool_name: "mcp__filesystem__read_file",
+ tool_input: { path: filePath },
+ tool_response: { text: "file contents" },
+ tool_use_id: "call-1",
+ };
+}
+
+function isProjectRuleRead(filePath: unknown): boolean {
+ return String(filePath).includes(`${path.sep}.omo${path.sep}rules${path.sep}`);
+}
+
+describe("codex rules hook performance", () => {
+ it("#given unchanged dynamic target #when PostToolUse repeats #then rule files are not reread for fingerprinting", async () => {
+ // given
+ const { root, pluginData, targetPath } = makeTempProject(3);
+ let ruleFileReads = 0;
+ const originalReadFileSync = fs.readFileSync;
+ const wrappedReadFileSync = ((...args: Parameters<typeof fs.readFileSync>) => {
+ if (isProjectRuleRead(args[0])) {
+ ruleFileReads += 1;
+ }
+
+ return originalReadFileSync(...args);
+ }) as typeof fs.readFileSync;
+ fs.readFileSync = wrappedReadFileSync;
+ syncBuiltinESMExports();
+ const { runPostToolUseHook } = await import("../src/codex-hook.js");
+
+ try {
+ // when
+ const firstOutput = await runPostToolUseHook(postToolUseInput(root, targetPath), {
+ pluginDataRoot: pluginData,
+ env: { CODEX_RULES_ENABLED_SOURCES: ".omo/rules" },
+ });
+ const firstRunRuleFileReads = ruleFileReads;
+ ruleFileReads = 0;
+ const secondOutput = await runPostToolUseHook(postToolUseInput(root, targetPath), {
+ pluginDataRoot: pluginData,
+ env: { CODEX_RULES_ENABLED_SOURCES: ".omo/rules" },
+ });
+
+ // then
+ expect(firstOutput).toContain("Rule 0");
+ expect(firstRunRuleFileReads).toBe(3);
+ expect(secondOutput).toBe("");
+ expect(ruleFileReads).toBe(0);
+ } finally {
+ fs.readFileSync = originalReadFileSync;
+ syncBuiltinESMExports();
+ }
+ });
+});
diff --git a/plugins/omo/components/rules/test/codex-hook.test.ts b/plugins/omo/components/rules/test/codex-hook.test.ts
new file mode 100644
index 00000000..b05dbdb8
--- /dev/null
+++ b/plugins/omo/components/rules/test/codex-hook.test.ts
@@ -0,0 +1,675 @@
+import { spawn } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ type CodexPostCompactInput,
+ type CodexPostToolUseInput,
+ type CodexSessionStartInput,
+ runPostCompactHook,
+ runPostToolUseHook,
+ runSessionStartHook,
+ runUserPromptSubmitHook,
+} from "../src/codex-hook.js";
+
+type CliResult = {
+ exitCode: number | null;
+ stdout: string;
+ stderr: string;
+};
+
+type SessionCache = {
+ staticDedup?: string[];
+ dynamicDedup?: Record<string, string[]>;
+ dynamicTargetFingerprints?: Record<string, string>;
+};
+
+const CLI_PATH = fileURLToPath(new URL("../dist/cli.js", import.meta.url));
+
+function runHookCli(input: string, subcommand = "post-tool-use", env: NodeJS.ProcessEnv = {}): Promise<CliResult> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [CLI_PATH, "hook", subcommand], {
+ env: { ...process.env, ...env },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ stdout += chunk;
+ });
+ child.stderr.on("data", (chunk: string) => {
+ stderr += chunk;
+ });
+ child.once("error", reject);
+ child.once("close", (exitCode) => {
+ resolve({ exitCode, stdout, stderr });
+ });
+ child.stdin.end(input);
+ });
+}
+
+const tempDirectories: string[] = [];
+const PROJECT_ONLY_ENV = {
+ CODEX_RULES_ENABLED_SOURCES: "AGENTS.md,.omo/rules",
+};
+
+const RULES_ONLY_ENV = {
+ CODEX_RULES_ENABLED_SOURCES: ".omo/rules",
+};
+
+afterEach(() => {
+ for (const directory of tempDirectories.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function makeTempProject(): { root: string; pluginData: string } {
+ const root = mkdtempSync(path.join(tmpdir(), "codex-rules-project-"));
+ const pluginData = mkdtempSync(path.join(tmpdir(), "codex-rules-data-"));
+ tempDirectories.push(root, pluginData);
+ writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));
+ writeFileSync(path.join(root, "AGENTS.md"), "Always wear safety goggles when refactoring.");
+ mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });
+ writeFileSync(
+ path.join(root, ".omo", "rules", "typescript.md"),
+ [
+ "---",
+ "description: TypeScript",
+ 'globs: ["**/*.ts", "**/*.tsx"]',
+ "---",
+ "",
+ "Prefer strict TypeScript for all source files.",
+ ].join("\n"),
+ );
+ mkdirSync(path.join(root, "src"), { recursive: true });
+ writeFileSync(path.join(root, "src", "app.ts"), "export const app = true;\n");
+ writeFileSync(path.join(root, "src", "other.ts"), "export const other = true;\n");
+ return { root, pluginData };
+}
+
+function sessionStartInput(root: string): CodexSessionStartInput {
+ return {
+ session_id: "session-1",
+ transcript_path: null,
+ cwd: root,
+ hook_event_name: "SessionStart",
+ model: "gpt-5.5",
+ permission_mode: "default",
+ source: "startup",
+ };
+}
+
+function postCompactInput(root: string): CodexPostCompactInput {
+ return {
+ session_id: "session-1",
+ turn_id: "turn-compact",
+ transcript_path: null,
+ cwd: root,
+ hook_event_name: "PostCompact",
+ model: "gpt-5.5",
+ trigger: "manual",
+ };
+}
+
+function userPromptSubmitInput(
+ root: string,
+ transcriptPath: string | null = null,
+): Parameters<typeof runUserPromptSubmitHook>[0] {
+ return {
+ session_id: "session-1",
+ turn_id: "turn-1",
+ transcript_path: transcriptPath,
+ cwd: root,
+ hook_event_name: "UserPromptSubmit",
+ model: "gpt-5.5",
+ permission_mode: "default",
+ prompt: "read src/app.ts",
+ };
+}
+
+function postToolUseInput(root: string, filePath: string): CodexPostToolUseInput {
+ return {
+ session_id: "session-1",
+ turn_id: "turn-1",
+ transcript_path: null,
+ cwd: root,
+ hook_event_name: "PostToolUse",
+ model: "gpt-5.5",
+ permission_mode: "default",
+ tool_name: "mcp__filesystem__read_file",
+ tool_input: { path: filePath },
+ tool_response: { text: "file contents" },
+ tool_use_id: "call-1",
+ };
+}
+
+function parseHookOutput(output: string): {
+ hookSpecificOutput?: {
+ hookEventName?: string;
+ additionalContext?: string;
+ };
+} {
+ expect(output.trim().length).toBeGreaterThan(0);
+ return JSON.parse(output) as {
+ hookSpecificOutput?: {
+ hookEventName?: string;
+ additionalContext?: string;
+ };
+ };
+}
+
+function writeTranscriptWithContext(root: string, ...additionalContexts: string[]): string {
+ const transcriptPath = path.join(root, "transcript.jsonl");
+ writeFileSync(
+ transcriptPath,
+ `${additionalContexts
+ .map((additionalContext) => JSON.stringify({ hookSpecificOutput: { additionalContext } }))
+ .join("\n")}\n`,
+ );
+ return transcriptPath;
+}
+
+function occurrenceCount(value: string, search: string): number {
+ return value.split(search).length - 1;
+}
+
+function sessionCacheFilePath(pluginData: string, sessionId = "session-1"): string {
+ return path.join(pluginData, "sessions", `${sessionId}.json`);
+}
+
+function readSessionCache(pluginData: string): SessionCache {
+ return JSON.parse(readFileSync(sessionCacheFilePath(pluginData), "utf8")) as SessionCache;
+}
+
+function writeTypeScriptRule(root: string, globExpression: string, body: string): void {
+ writeFileSync(
+ path.join(root, ".omo", "rules", "typescript.md"),
+ ["---", "description: TypeScript", `globs: ${globExpression}`, "---", "", body].join("\n"),
+ );
+}
+
+describe("codex rules hooks", () => {
+ it("#given project rules #when SessionStart runs #then emits static additional context", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+
+ // when
+ const output = await runSessionStartHook(sessionStartInput(root), {
+ pluginDataRoot: pluginData,
+ env: PROJECT_ONLY_ENV,
+ });
+
+ // then
+ const parsed = parseHookOutput(output);
+ expect(parsed.hookSpecificOutput?.hookEventName).toBe("SessionStart");
+ expect(parsed.hookSpecificOutput?.additionalContext).toContain("## Project Instructions");
+ expect(parsed.hookSpecificOutput?.additionalContext).toContain("Always wear safety goggles");
+ });
+
+ it("#given static context already injected #when UserPromptSubmit runs #then it emits no duplicate context", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ await runSessionStartHook(sessionStartInput(root), { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV });
+
+ // when
+ const output = await runUserPromptSubmitHook(
+ {
+ session_id: "session-1",
+ turn_id: "turn-1",
+ transcript_path: null,
+ cwd: root,
+ hook_event_name: "UserPromptSubmit",
+ model: "gpt-5.5",
+ permission_mode: "default",
+ prompt: "read src/app.ts",
+ },
+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },
+ );
+
+ // then
+ expect(output).toBe("");
+ });
+
+ it("#given resumed session #when SessionStart runs #then it preserves the session cache", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const input = sessionStartInput(root);
+ await runSessionStartHook(input, { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV });
+
+ // when
+ const resumeOutput = await runSessionStartHook(
+ { ...input, source: "resume" },
+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },
+ );
+ const clearOutput = await runSessionStartHook(
+ { ...input, source: "clear" },
+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },
+ );
+
+ // then
+ expect(resumeOutput).toBe("");
+ expect(parseHookOutput(clearOutput).hookSpecificOutput?.additionalContext).toContain(
+ "Always wear safety goggles",
+ );
+ });
+
+ it("#given static context remains in transcript but cache is missing #when SessionStart runs #then it emits no duplicate context", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const firstOutput = await runSessionStartHook(sessionStartInput(root), {
+ pluginDataRoot: pluginData,
+ env: PROJECT_ONLY_ENV,
+ });
+ const firstContext = parseHookOutput(firstOutput).hookSpecificOutput?.additionalContext ?? "";
+ const transcriptPath = writeTranscriptWithContext(root, firstContext);
+ rmSync(sessionCacheFilePath(pluginData), { force: true });
+
+ // when
+ const output = await runSessionStartHook(
+ { ...sessionStartInput(root), transcript_path: transcriptPath },
+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },
+ );
+
+ // then
+ expect(output).toBe("");
+ expect(readSessionCache(pluginData).staticDedup).toHaveLength(1);
+ });
+
+ it("#given read-file tool result #when PostToolUse runs #then emits matching dynamic rule context", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const filePath = path.join(root, "src", "app.ts");
+
+ // when
+ const output = await runPostToolUseHook(postToolUseInput(root, filePath), {
+ pluginDataRoot: pluginData,
+ env: PROJECT_ONLY_ENV,
+ });
+
+ // then
+ // The literal "src/app.ts" pins POSIX separators and acts as the Windows
+ // regression line: prior versions emitted "src\\app.ts" on Windows.
+ const parsed = parseHookOutput(output);
+ expect(parsed.hookSpecificOutput?.hookEventName).toBe("PostToolUse");
+ expect(parsed.hookSpecificOutput?.additionalContext).toContain(
+ "Additional project instructions matched for src/app.ts",
+ );
+ expect(parsed.hookSpecificOutput?.additionalContext).toContain("Prefer strict TypeScript");
+ expect(parsed.hookSpecificOutput?.additionalContext ?? "").not.toContain("src\\app.ts");
+ expect(output).not.toContain("updatedMCPToolOutput");
+ expect(output).not.toContain("suppressOutput");
+ expect(output).not.toContain('"decision"');
+ });
+
+ it("#given multiple target paths matching one rule #when PostToolUse runs #then emits dynamic context once for the first target", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const firstFilePath = path.join(root, "src", "app.ts");
+ const secondFilePath = path.join(root, "src", "other.ts");
+
+ // when
+ const output = await runPostToolUseHook(
+ {
+ ...postToolUseInput(root, firstFilePath),
+ tool_name: "mcp__filesystem__read_multiple_files",
+ tool_input: { paths: [firstFilePath, secondFilePath, firstFilePath] },
+ },
+ {
+ pluginDataRoot: pluginData,
+ env: PROJECT_ONLY_ENV,
+ },
+ );
+
+ // then
+ const parsed = parseHookOutput(output);
+ const additionalContext = parsed.hookSpecificOutput?.additionalContext ?? "";
+ expect(parsed.hookSpecificOutput?.hookEventName).toBe("PostToolUse");
+ expect(additionalContext).toContain("Additional project instructions matched for src/app.ts");
+ expect(additionalContext).not.toContain("src\\app.ts");
+ expect(occurrenceCount(additionalContext, "Prefer strict TypeScript")).toBe(1);
+ });
+
+ it("#given dynamic context already injected #when PostToolUse repeats #then emits no duplicate context", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const filePath = path.join(root, "src", "app.ts");
+ const input = postToolUseInput(root, filePath);
+ await runPostToolUseHook(input, { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV });
+ const cachedState = readSessionCache(pluginData);
+
+ // when
+ const output = await runPostToolUseHook(input, { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV });
+
+ // then
+ expect(output).toBe("");
+ expect(Object.keys(cachedState.dynamicTargetFingerprints ?? {})).toHaveLength(1);
+ expect(readSessionCache(pluginData).dynamicTargetFingerprints).toEqual(cachedState.dynamicTargetFingerprints);
+ });
+
+ it("#given dynamic context remains in transcript but cache is missing #when PostToolUse repeats #then it emits no duplicate context", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const filePath = path.join(root, "src", "app.ts");
+ const input = postToolUseInput(root, filePath);
+ const firstOutput = await runPostToolUseHook(input, { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV });
+ const firstContext = parseHookOutput(firstOutput).hookSpecificOutput?.additionalContext ?? "";
+ const transcriptPath = writeTranscriptWithContext(root, firstContext);
+ rmSync(sessionCacheFilePath(pluginData), { force: true });
+
+ // when
+ const output = await runPostToolUseHook(
+ { ...input, transcript_path: transcriptPath },
+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },
+ );
+
+ // then
+ const cachedState = readSessionCache(pluginData);
+ expect(output).toBe("");
+ expect(Object.values(cachedState.dynamicDedup ?? {}).flat()).toHaveLength(2);
+ expect(Object.keys(cachedState.dynamicTargetFingerprints ?? {})).toHaveLength(1);
+ });
+
+ it("#given cached target in one session #when another session reads it #then PostToolUse rechecks independently", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const filePath = path.join(root, "src", "app.ts");
+ await runPostToolUseHook(postToolUseInput(root, filePath), { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV });
+
+ // when
+ const output = await runPostToolUseHook(
+ { ...postToolUseInput(root, filePath), session_id: "session-2" },
+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },
+ );
+
+ // then
+ expect(parseHookOutput(output).hookSpecificOutput?.additionalContext).toContain("Prefer strict TypeScript");
+ });
+
+ it("#given cached dynamic target #when rule frontmatter changes #then PostToolUse rechecks the target", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const filePath = path.join(root, "src", "app.ts");
+ const input = postToolUseInput(root, filePath);
+ await runPostToolUseHook(input, { pluginDataRoot: pluginData, env: RULES_ONLY_ENV });
+ writeTypeScriptRule(root, '"**/*.ts"', "Prefer readonly TypeScript after rule edits.");
+
+ // when
+ const output = await runPostToolUseHook(input, { pluginDataRoot: pluginData, env: RULES_ONLY_ENV });
+
+ // then
+ expect(parseHookOutput(output).hookSpecificOutput?.additionalContext).toContain(
+ "Prefer readonly TypeScript after rule edits.",
+ );
+ });
+
+ it("#given cached dynamic context #when PostCompact runs #then PostToolUse can re-inject after compaction", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const filePath = path.join(root, "src", "app.ts");
+ const input = postToolUseInput(root, filePath);
+ const firstOutput = await runPostToolUseHook(input, { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV });
+ const firstContext = parseHookOutput(firstOutput).hookSpecificOutput?.additionalContext ?? "";
+ const transcriptPath = writeTranscriptWithContext(root, firstContext);
+ expect(
+ await runPostToolUseHook(
+ { ...input, transcript_path: transcriptPath },
+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },
+ ),
+ ).toBe("");
+
+ // when
+ const compactOutput = await runPostCompactHook(
+ { ...postCompactInput(root), transcript_path: transcriptPath },
+ { pluginDataRoot: pluginData },
+ );
+ const output = await runPostToolUseHook(
+ { ...input, transcript_path: transcriptPath },
+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },
+ );
+
+ // then
+ expect(compactOutput).toBe("");
+ expect(parseHookOutput(output).hookSpecificOutput?.additionalContext).toContain("Prefer strict TypeScript");
+ });
+
+ it("#given compacted transcript #when static re-injects before dynamic #then dynamic still re-injects", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const filePath = path.join(root, "src", "app.ts");
+ const staticOutput = await runSessionStartHook(sessionStartInput(root), {
+ pluginDataRoot: pluginData,
+ env: PROJECT_ONLY_ENV,
+ });
+ const dynamicOutput = await runPostToolUseHook(postToolUseInput(root, filePath), {
+ pluginDataRoot: pluginData,
+ env: PROJECT_ONLY_ENV,
+ });
+ const transcriptPath = writeTranscriptWithContext(
+ root,
+ parseHookOutput(staticOutput).hookSpecificOutput?.additionalContext ?? "",
+ parseHookOutput(dynamicOutput).hookSpecificOutput?.additionalContext ?? "",
+ );
+ await runPostCompactHook(
+ { ...postCompactInput(root), transcript_path: transcriptPath },
+ { pluginDataRoot: pluginData },
+ );
+
+ // when
+ const staticReinjectOutput = await runUserPromptSubmitHook(userPromptSubmitInput(root, transcriptPath), {
+ pluginDataRoot: pluginData,
+ env: PROJECT_ONLY_ENV,
+ });
+ const dynamicReinjectOutput = await runPostToolUseHook(
+ { ...postToolUseInput(root, filePath), transcript_path: transcriptPath },
+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },
+ );
+
+ // then
+ expect(parseHookOutput(staticReinjectOutput).hookSpecificOutput?.additionalContext).toContain(
+ "Always wear safety goggles",
+ );
+ expect(parseHookOutput(dynamicReinjectOutput).hookSpecificOutput?.additionalContext).toContain(
+ "Prefer strict TypeScript",
+ );
+ });
+
+ it("#given compacted transcript #when dynamic re-injects before static #then static still re-injects", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const filePath = path.join(root, "src", "app.ts");
+ const staticOutput = await runSessionStartHook(sessionStartInput(root), {
+ pluginDataRoot: pluginData,
+ env: PROJECT_ONLY_ENV,
+ });
+ const dynamicOutput = await runPostToolUseHook(postToolUseInput(root, filePath), {
+ pluginDataRoot: pluginData,
+ env: PROJECT_ONLY_ENV,
+ });
+ const transcriptPath = writeTranscriptWithContext(
+ root,
+ parseHookOutput(staticOutput).hookSpecificOutput?.additionalContext ?? "",
+ parseHookOutput(dynamicOutput).hookSpecificOutput?.additionalContext ?? "",
+ );
+ await runPostCompactHook(
+ { ...postCompactInput(root), transcript_path: transcriptPath },
+ { pluginDataRoot: pluginData },
+ );
+
+ // when
+ const dynamicReinjectOutput = await runPostToolUseHook(
+ { ...postToolUseInput(root, filePath), transcript_path: transcriptPath },
+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },
+ );
+ const staticReinjectOutput = await runUserPromptSubmitHook(userPromptSubmitInput(root, transcriptPath), {
+ pluginDataRoot: pluginData,
+ env: PROJECT_ONLY_ENV,
+ });
+
+ // then
+ expect(parseHookOutput(dynamicReinjectOutput).hookSpecificOutput?.additionalContext).toContain(
+ "Prefer strict TypeScript",
+ );
+ expect(parseHookOutput(staticReinjectOutput).hookSpecificOutput?.additionalContext).toContain(
+ "Always wear safety goggles",
+ );
+ });
+
+ it("#given legacy session cache #when PostToolUse hydrates state #then it accepts the old shape", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ mkdirSync(path.join(pluginData, "sessions"), { recursive: true });
+ writeFileSync(sessionCacheFilePath(pluginData), `${JSON.stringify({ staticDedup: [], dynamicDedup: {} })}\n`);
+
+ // when
+ const output = await runPostToolUseHook(postToolUseInput(root, path.join(root, "src", "app.ts")), {
+ pluginDataRoot: pluginData,
+ env: PROJECT_ONLY_ENV,
+ });
+
+ // then
+ expect(parseHookOutput(output).hookSpecificOutput?.additionalContext).toContain("Prefer strict TypeScript");
+ });
+
+ it("#given static-only mode #when PostToolUse runs #then emits no dynamic context", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const filePath = path.join(root, "src", "app.ts");
+
+ // when
+ const output = await runPostToolUseHook(postToolUseInput(root, filePath), {
+ pluginDataRoot: pluginData,
+ env: {
+ ...PROJECT_ONLY_ENV,
+ CODEX_RULES_MODE: "static",
+ },
+ });
+
+ // then
+ expect(output).toBe("");
+ });
+
+ it("#given rules disabled #when PostToolUse runs #then emits no dynamic context", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const filePath = path.join(root, "src", "app.ts");
+
+ // when
+ const output = await runPostToolUseHook(postToolUseInput(root, filePath), {
+ pluginDataRoot: pluginData,
+ env: {
+ ...PROJECT_ONLY_ENV,
+ CODEX_RULES_DISABLED: "true",
+ },
+ });
+
+ // then
+ expect(output).toBe("");
+ });
+
+ it("#given failed tool response #when PostToolUse runs #then emits no dynamic context", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const filePath = path.join(root, "src", "app.ts");
+
+ // when
+ const output = await runPostToolUseHook(
+ {
+ ...postToolUseInput(root, filePath),
+ tool_response: { is_error: true },
+ },
+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },
+ );
+
+ // then
+ expect(output).toBe("");
+ });
+
+ it("#given tracked tool without path #when PostToolUse runs #then emits no dynamic context", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+
+ // when
+ const output = await runPostToolUseHook(
+ {
+ ...postToolUseInput(root, ""),
+ tool_input: {},
+ },
+ { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV },
+ );
+
+ // then
+ expect(output).toBe("");
+ });
+
+ it("#given malformed post-tool-use stdin #when hook CLI runs #then it no-ops without stderr", async () => {
+ // given
+ const input = "break;\n";
+
+ // when
+ const result = await runHookCli(input);
+
+ // then
+ expect(result).toEqual({
+ exitCode: 0,
+ stdout: "",
+ stderr: "",
+ });
+ });
+
+ it("#given non-object post-tool-use JSON #when hook CLI runs #then it no-ops without stderr", async () => {
+ // given
+ const input = "[]\n";
+
+ // when
+ const result = await runHookCli(input);
+
+ // then
+ expect(result).toEqual({
+ exitCode: 0,
+ stdout: "",
+ stderr: "",
+ });
+ });
+
+ it("#given debug timing enabled #when PostToolUse hook CLI runs #then phase logs go to stderr only", async () => {
+ // given
+ const { root, pluginData } = makeTempProject();
+ const input = `${JSON.stringify(postToolUseInput(root, path.join(root, "src", "app.ts")))}\n`;
+
+ // when
+ const result = await runHookCli(input, "post-tool-use", {
+ NODE_DEBUG: "codex-rules",
+ PLUGIN_DATA: pluginData,
+ });
+
+ // then
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toContain("hookSpecificOutput");
+ expect(result.stderr).toContain("PostToolUse");
+ expect(result.stderr).toContain("extract");
+ expect(result.stderr).toContain("fingerprint");
+ expect(result.stderr).toContain("load");
+ expect(result.stderr).toContain("persist");
+ expect(result.stderr).toContain("ms");
+ });
+
+ it("#given malformed post-compact stdin #when hook CLI runs #then it no-ops without stderr", async () => {
+ // given
+ const input = `${JSON.stringify({ hook_event_name: "PostCompact", session_id: "s", turn_id: "t" })}\n`;
+
+ // when
+ const result = await runHookCli(input, "post-compact");
+
+ // then
+ expect(result).toEqual({
+ exitCode: 0,
+ stdout: "",
+ stderr: "",
+ });
+ });
+});
diff --git a/plugins/omo/components/rules/test/engine.test.ts b/plugins/omo/components/rules/test/engine.test.ts
new file mode 100644
index 00000000..4b936353
--- /dev/null
+++ b/plugins/omo/components/rules/test/engine.test.ts
@@ -0,0 +1,192 @@
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { createEngine, defaultConfig, type EngineDeps } from "../src/rules/engine.js";
+import { matchRule as defaultMatchRule } from "../src/rules/matcher.js";
+import type { RuleCandidate } from "../src/rules/types.js";
+
+const projectRoot = "/tmp/codex-rules-engine";
+
+function makeCandidate(): RuleCandidate {
+ return {
+ path: join(projectRoot, ".omo", "rules", "typescript.md"),
+ realPath: join(projectRoot, ".omo", "rules", "typescript.md"),
+ source: ".omo/rules",
+ distance: 0,
+ isGlobal: false,
+ isSingleFile: false,
+ relativePath: ".omo/rules/typescript.md",
+ };
+}
+
+describe("rule engine dynamic matching", () => {
+ it("#given duplicate target paths #when loading dynamic rules #then repeated discovery and parsing work is avoided", () => {
+ // given
+ const targetPath = join(projectRoot, "src", "app.ts");
+ const candidate = makeCandidate();
+ const counters = {
+ findProjectRoot: 0,
+ findCandidates: 0,
+ readFile: 0,
+ };
+ const deps = {
+ findProjectRoot: () => {
+ counters.findProjectRoot += 1;
+ return projectRoot;
+ },
+ findCandidates: () => {
+ counters.findCandidates += 1;
+ return [candidate];
+ },
+ readFile: () => {
+ counters.readFile += 1;
+ return ["---", "globs: **/*.ts", "---", "", "Prefer strict TypeScript."].join("\n");
+ },
+ } satisfies EngineDeps;
+ const engine = createEngine(defaultConfig(), deps);
+
+ // when
+ const result = engine.loadDynamicRules(projectRoot, [targetPath, targetPath, targetPath]);
+
+ // then
+ expect(result.rules).toHaveLength(1);
+ expect(counters).toEqual({
+ findProjectRoot: 1,
+ findCandidates: 1,
+ readFile: 1,
+ });
+ });
+
+ it("#given distinct target files in same directory #when loading dynamic rules #then candidate discovery is reused", () => {
+ // given
+ const firstTarget = join(projectRoot, "src", "first.ts");
+ const secondTarget = join(projectRoot, "src", "second.ts");
+ const thirdTarget = join(projectRoot, "src", "third.ts");
+ const candidate = makeCandidate();
+ let findCandidatesCalls = 0;
+ const deps = {
+ findProjectRoot: () => projectRoot,
+ findCandidates: () => {
+ findCandidatesCalls += 1;
+ return [candidate];
+ },
+ readFile: () => ["---", "globs: **/*.ts", "---", "", "Prefer strict TypeScript."].join("\n"),
+ } satisfies EngineDeps;
+ const engine = createEngine(defaultConfig(), deps);
+
+ // when
+ const result = engine.loadDynamicRules(projectRoot, [firstTarget, secondTarget, thirdTarget]);
+
+ // then
+ expect(result.rules).toHaveLength(1);
+ expect(findCandidatesCalls).toBe(1);
+ });
+
+ it("#given same rule content and target across loads #when loading dynamic rules repeats #then cached match decision is reused", () => {
+ // given
+ const targetPath = join(projectRoot, "src", "app.ts");
+ const candidate = makeCandidate();
+ let matchCalls = 0;
+ const deps = {
+ findProjectRoot: () => projectRoot,
+ findCandidates: () => [candidate],
+ readFile: () => ["---", "globs: **/*.ts", "---", "", "Prefer strict TypeScript."].join("\n"),
+ matchRule: (input) => {
+ matchCalls += 1;
+ return defaultMatchRule(input);
+ },
+ } satisfies EngineDeps;
+ const engine = createEngine(defaultConfig(), deps);
+
+ // when
+ const firstResult = engine.loadDynamicRules(projectRoot, [targetPath]);
+ const secondResult = engine.loadDynamicRules(projectRoot, [targetPath]);
+
+ // then
+ expect(firstResult.rules).toHaveLength(1);
+ expect(secondResult.rules).toHaveLength(1);
+ expect(matchCalls).toBe(1);
+ });
+
+ it("#given same rule path changes body #when loading dynamic rules repeats #then cached match decision invalidates", () => {
+ // given
+ const targetPath = join(projectRoot, "src", "app.ts");
+ const candidate = makeCandidate();
+ let body = "Prefer strict TypeScript.";
+ let matchCalls = 0;
+ const deps = {
+ findProjectRoot: () => projectRoot,
+ findCandidates: () => [candidate],
+ readFile: () => ["---", "globs: **/*.ts", "---", "", body].join("\n"),
+ matchRule: (input) => {
+ matchCalls += 1;
+ return defaultMatchRule(input);
+ },
+ } satisfies EngineDeps;
+ const engine = createEngine(defaultConfig(), deps);
+
+ // when
+ engine.loadDynamicRules(projectRoot, [targetPath]);
+ body = "Prefer readonly TypeScript.";
+ engine.loadDynamicRules(projectRoot, [targetPath]);
+
+ // then
+ expect(matchCalls).toBe(2);
+ });
+
+ it("#given same rule path changes frontmatter #when loading dynamic rules repeats #then cached match decision invalidates", () => {
+ // given
+ const targetPath = join(projectRoot, "src", "app.ts");
+ const candidate = makeCandidate();
+ let globs = "**/*.ts";
+ let matchCalls = 0;
+ const deps = {
+ findProjectRoot: () => projectRoot,
+ findCandidates: () => [candidate],
+ readFile: () => ["---", `globs: ${globs}`, "---", "", "Prefer strict TypeScript."].join("\n"),
+ matchRule: (input) => {
+ matchCalls += 1;
+ return defaultMatchRule(input);
+ },
+ } satisfies EngineDeps;
+ const engine = createEngine(defaultConfig(), deps);
+
+ // when
+ const firstResult = engine.loadDynamicRules(projectRoot, [targetPath]);
+ globs = "**/*.tsx";
+ const secondResult = engine.loadDynamicRules(projectRoot, [targetPath]);
+
+ // then
+ expect(firstResult.rules).toHaveLength(1);
+ expect(secondResult.rules).toHaveLength(0);
+ expect(matchCalls).toBe(2);
+ });
+
+ it("#given same rule and different targets #when loading dynamic rules repeats #then target-specific decisions do not leak", () => {
+ // given
+ const sourceTarget = join(projectRoot, "src", "app.ts");
+ const testTarget = join(projectRoot, "src", "app.test.ts");
+ const candidate = makeCandidate();
+ let matchCalls = 0;
+ const deps = {
+ findProjectRoot: () => projectRoot,
+ findCandidates: () => [candidate],
+ readFile: () =>
+ ["---", 'globs: ["**/*.ts", "!**/*.test.ts"]', "---", "", "Prefer strict TypeScript."].join("\n"),
+ matchRule: (input) => {
+ matchCalls += 1;
+ return defaultMatchRule(input);
+ },
+ } satisfies EngineDeps;
+ const engine = createEngine(defaultConfig(), deps);
+
+ // when
+ const sourceResult = engine.loadDynamicRules(projectRoot, [sourceTarget]);
+ const testResult = engine.loadDynamicRules(projectRoot, [testTarget]);
+
+ // then
+ expect(sourceResult.rules).toHaveLength(1);
+ expect(testResult.rules).toHaveLength(0);
+ expect(matchCalls).toBe(2);
+ });
+});
diff --git a/plugins/omo/components/rules/test/finder.test.ts b/plugins/omo/components/rules/test/finder.test.ts
new file mode 100644
index 00000000..3f10ca7f
--- /dev/null
+++ b/plugins/omo/components/rules/test/finder.test.ts
@@ -0,0 +1,102 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { findRuleCandidates } from "../src/rules/finder.js";
+import type { RuleCandidate } from "../src/rules/types.js";
+
+const tempDirectories: string[] = [];
+
+afterEach(() => {
+ for (const directory of tempDirectories.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function makeProject(): { projectRoot: string; homeRoot: string; targetPath: string } {
+ const projectRoot = mkdtempSync(join(tmpdir(), "codex-rules-finder-project-"));
+ const homeRoot = mkdtempSync(join(tmpdir(), "codex-rules-finder-home-"));
+ tempDirectories.push(projectRoot, homeRoot);
+ mkdirSync(join(projectRoot, "src", ".omo", "rules"), { recursive: true });
+ mkdirSync(join(projectRoot, ".omo", "rules"), { recursive: true });
+ mkdirSync(join(homeRoot, ".opencode", "rules"), { recursive: true });
+ mkdirSync(join(homeRoot, ".config", "opencode"), { recursive: true });
+ writeFileSync(join(projectRoot, "package.json"), JSON.stringify({ name: "fixture" }));
+ writeFileSync(join(projectRoot, "AGENTS.md"), "Project rule\n");
+ writeFileSync(join(projectRoot, "src", ".omo", "rules", "local.md"), "Local rule\n");
+ writeFileSync(join(projectRoot, ".omo", "rules", "root.md"), "Root rule\n");
+ writeFileSync(join(homeRoot, ".opencode", "rules", "global.md"), "Global rule\n");
+ writeFileSync(join(homeRoot, ".config", "opencode", "AGENTS.md"), "Home rule\n");
+ const targetPath = join(projectRoot, "src", "app.ts");
+ writeFileSync(targetPath, "export const app = true;\n");
+ return { projectRoot, homeRoot, targetPath };
+}
+
+function candidateSummary(candidate: RuleCandidate): string {
+ return `${candidate.source}:${candidate.distance}:${candidate.relativePath}`;
+}
+
+describe("findRuleCandidates", () => {
+ it("#given project and user-home rules #when target file is inside project #then candidates keep source distance", () => {
+ // given
+ const { projectRoot, homeRoot, targetPath } = makeProject();
+
+ // when
+ const candidates = findRuleCandidates({
+ projectRoot,
+ targetFile: targetPath,
+ homeDir: homeRoot,
+ disabledSources: new Set(["plugin-bundled"]),
+ });
+
+ // then
+ expect(candidates.map(candidateSummary)).toEqual([
+ ".omo/rules:0:src/.omo/rules/local.md",
+ ".omo/rules:1:.omo/rules/root.md",
+ "AGENTS.md:1:AGENTS.md",
+ "~/.opencode/rules:9999:.opencode/rules/global.md",
+ "~/.config/opencode/AGENTS.md:9999:.config/opencode/AGENTS.md",
+ ]);
+ });
+
+ it("#given disabled source #when finding candidates #then matching source is omitted", () => {
+ // given
+ const { projectRoot, homeRoot, targetPath } = makeProject();
+
+ // when
+ const candidates = findRuleCandidates({
+ projectRoot,
+ targetFile: targetPath,
+ homeDir: homeRoot,
+ disabledSources: new Set([".omo/rules", "~/.opencode/rules", "plugin-bundled"]),
+ });
+
+ // then
+ expect(candidates.map(candidateSummary)).toEqual([
+ "AGENTS.md:1:AGENTS.md",
+ "~/.config/opencode/AGENTS.md:9999:.config/opencode/AGENTS.md",
+ ]);
+ });
+
+ it("#given skip user home #when finding candidates #then only project rules are returned", () => {
+ // given
+ const { projectRoot, homeRoot, targetPath } = makeProject();
+
+ // when
+ const candidates = findRuleCandidates({
+ projectRoot,
+ targetFile: targetPath,
+ homeDir: homeRoot,
+ skipUserHome: true,
+ disabledSources: new Set(["plugin-bundled"]),
+ });
+
+ // then
+ expect(candidates.map(candidateSummary)).toEqual([
+ ".omo/rules:0:src/.omo/rules/local.md",
+ ".omo/rules:1:.omo/rules/root.md",
+ "AGENTS.md:1:AGENTS.md",
+ ]);
+ });
+});
diff --git a/plugins/omo/components/rules/test/matcher.test.ts b/plugins/omo/components/rules/test/matcher.test.ts
new file mode 100644
index 00000000..5a4b5c22
--- /dev/null
+++ b/plugins/omo/components/rules/test/matcher.test.ts
@@ -0,0 +1,206 @@
+import { describe, expect, it } from "vitest";
+
+import { matchRule, normalizeGlobs } from "../src/rules/matcher.js";
+import type { RuleFrontmatter } from "../src/rules/types.js";
+
+function matchFrontmatter(
+ frontmatter: RuleFrontmatter,
+ pathBases: {
+ projectRelative: string;
+ scopeRelative?: string;
+ basename?: string;
+ },
+): ReturnType<typeof matchRule> {
+ const scopeRelative = pathBases.scopeRelative;
+ const pathBase = {
+ projectRelative: pathBases.projectRelative,
+ basename: pathBases.basename ?? pathBases.projectRelative.split("/").at(-1) ?? pathBases.projectRelative,
+ ...(scopeRelative === undefined ? {} : { scopeRelative }),
+ };
+ return matchRule({
+ frontmatter,
+ isSingleFile: false,
+ pathBases: pathBase,
+ });
+}
+
+function matchGlobs(globs: string | string[], projectRelative: string): boolean {
+ return matchFrontmatter({ globs } satisfies RuleFrontmatter, { projectRelative }).matched;
+}
+
+describe("matchRule", () => {
+ it("#given single-file rule #when matching any target #then it always matches", () => {
+ // given
+ const frontmatter = {} satisfies RuleFrontmatter;
+
+ // when
+ const result = matchRule({
+ frontmatter,
+ isSingleFile: true,
+ pathBases: { projectRelative: "docs/readme.md", basename: "readme.md" },
+ });
+
+ // then
+ expect(result).toEqual({ matched: true, reason: "single-file" });
+ });
+
+ it("#given always apply rule #when no glob is configured #then it matches", () => {
+ // given
+ const frontmatter = { alwaysApply: true } satisfies RuleFrontmatter;
+
+ // when
+ const result = matchFrontmatter(frontmatter, { projectRelative: "src/app.ts" });
+
+ // then
+ expect(result).toEqual({ matched: true, reason: "alwaysApply" });
+ });
+
+ it("#given rule without patterns #when target is checked #then no match is returned", () => {
+ // given
+ const frontmatter = {} satisfies RuleFrontmatter;
+
+ // when
+ const result = matchFrontmatter(frontmatter, { projectRelative: "src/app.ts" });
+
+ // then
+ expect(result).toEqual({ matched: false, reason: { kind: "no-match" } });
+ });
+
+ it("#given recursive glob #when target is nested #then matches without runtime dependencies", () => {
+ // given
+ const globs = "**/*.ts";
+
+ // when
+ const matched = matchGlobs(globs, "src/features/app.ts");
+
+ // then
+ expect(matched).toBe(true);
+ });
+
+ it("#given paths alias #when target matches #then glob match is returned", () => {
+ // given
+ const frontmatter = { paths: "src/**/*.ts" } satisfies RuleFrontmatter;
+
+ // when
+ const result = matchFrontmatter(frontmatter, { projectRelative: "src/features/app.ts" });
+
+ // then
+ expect(result).toEqual({ matched: true, reason: { kind: "glob", pattern: "src/**/*.ts" } });
+ });
+
+ it("#given applyTo alias #when basename matches #then glob match is returned", () => {
+ // given
+ const frontmatter = { applyTo: "*.md" } satisfies RuleFrontmatter;
+
+ // when
+ const result = matchFrontmatter(frontmatter, { projectRelative: "docs/README.md" });
+
+ // then
+ expect(result).toEqual({ matched: true, reason: { kind: "glob", pattern: "*.md" } });
+ });
+
+ it("#given scope-relative target #when scoped path matches #then glob match is returned", () => {
+ // given
+ const frontmatter = { globs: "components/**/*.tsx" } satisfies RuleFrontmatter;
+
+ // when
+ const result = matchFrontmatter(frontmatter, {
+ projectRelative: "packages/ui/components/button.tsx",
+ scopeRelative: "components/button.tsx",
+ });
+
+ // then
+ expect(result).toEqual({ matched: true, reason: { kind: "glob", pattern: "components/**/*.tsx" } });
+ });
+
+ it("#given backslash glob and target #when matching #then paths are normalized", () => {
+ // given
+ const frontmatter = { globs: "src\\**\\*.ts" } satisfies RuleFrontmatter;
+
+ // when
+ const result = matchFrontmatter(frontmatter, { projectRelative: "src\\features\\app.ts" });
+
+ // then
+ expect(result).toEqual({ matched: true, reason: { kind: "glob", pattern: "src/**/*.ts" } });
+ });
+
+ it("#given multiple positive globs #when later glob matches #then matching pattern is reported", () => {
+ // given
+ const frontmatter = { globs: ["docs/**/*.md", "src/**/*.ts"] } satisfies RuleFrontmatter;
+
+ // when
+ const result = matchFrontmatter(frontmatter, { projectRelative: "src/features/app.ts" });
+
+ // then
+ expect(result).toEqual({ matched: true, reason: { kind: "glob", pattern: "src/**/*.ts" } });
+ });
+
+ it("#given negative glob #when target is excluded #then no match is returned", () => {
+ // given
+ const globs = ["**/*.ts", "!**/*.test.ts"];
+
+ // when
+ const matched = matchGlobs(globs, "src/features/app.test.ts");
+
+ // then
+ expect(matched).toBe(false);
+ });
+
+ it("#given question-mark glob #when one filename character differs #then target matches", () => {
+ // given
+ const globs = "src/app-?.ts";
+
+ // when
+ const matched = matchGlobs(globs, "src/app-a.ts");
+
+ // then
+ expect(matched).toBe(true);
+ });
+
+ it("#given brace glob #when target extension is listed #then matches", () => {
+ // given
+ const globs = "src/**/*.{ts,tsx}";
+
+ // when
+ const matched = matchGlobs(globs, "src/features/app.tsx");
+
+ // then
+ expect(matched).toBe(true);
+ });
+
+ it("#given character class glob #when matching listed extension #then target matches", () => {
+ // given
+ const globs = "src/**/*.[tj]s";
+
+ // when
+ const matched = matchGlobs(globs, "src/features/app.ts");
+
+ // then
+ expect(matched).toBe(true);
+ });
+
+ it("#given extglob pattern #when matching allowed extension #then target matches", () => {
+ // given
+ const globs = "src/**/*.@(ts|tsx)";
+
+ // when
+ const matched = matchGlobs(globs, "src/features/app.tsx");
+
+ // then
+ expect(matched).toBe(true);
+ });
+
+ it("#given duplicate normalized patterns #when normalizing #then first unique pattern order is kept", () => {
+ // given
+ const frontmatter = {
+ globs: ["src\\**\\*.ts", "src/**/*.ts", "!src/**/*.test.ts"],
+ paths: "!src/**/*.test.ts",
+ } satisfies RuleFrontmatter;
+
+ // when
+ const patterns = normalizeGlobs(frontmatter);
+
+ // then
+ expect(patterns).toEqual(["src/**/*.ts", "!src/**/*.test.ts"]);
+ });
+});
diff --git a/plugins/omo/components/rules/test/package-smoke.test.ts b/plugins/omo/components/rules/test/package-smoke.test.ts
new file mode 100644
index 00000000..186e8ab5
--- /dev/null
+++ b/plugins/omo/components/rules/test/package-smoke.test.ts
@@ -0,0 +1,151 @@
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+type PackageJson = {
+ readonly type: string;
+ readonly packageManager: string;
+ readonly bin: Record<string, string>;
+ readonly files: readonly string[];
+ readonly dependencies?: Record<string, unknown>;
+};
+
+type PluginJson = {
+ readonly hooks: string;
+};
+
+type HookCommand = {
+ readonly command: string;
+};
+
+type HookEntry = {
+ readonly matcher?: string;
+ readonly hooks: readonly HookCommand[];
+};
+
+type HooksJson = {
+ readonly hooks: Record<string, readonly HookEntry[]>;
+};
+
+function readPackageJson(path: string): PackageJson {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (!isPackageJson(parsed)) throw new TypeError(`Invalid package metadata: ${path}`);
+ return parsed;
+}
+
+function readPluginJson(path: string): PluginJson {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (!isPluginJson(parsed)) throw new TypeError(`Invalid plugin metadata: ${path}`);
+ return parsed;
+}
+
+function readHooksJson(path: string): HooksJson {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (!isHooksJson(parsed)) throw new TypeError(`Invalid hooks metadata: ${path}`);
+ return parsed;
+}
+
+describe("plugin package metadata", () => {
+ it("#given packaged plugin files #when validating entrypoints #then hook commands use portable plugin root interpolation", () => {
+ // given
+ const packageJson = readPackageJson("package.json");
+ const pluginJson = readPluginJson(".codex-plugin/plugin.json");
+ const hooksJson = readHooksJson("hooks/hooks.json");
+ const cliSource = readFileSync("src/cli.ts", "utf8");
+
+ // when
+ const hookConfig = hooksJson.hooks;
+ const pluginRoot = ["$", "{PLUGIN_ROOT}"].join("");
+ const commands = [
+ hookConfig["SessionStart"]?.[0]?.hooks[0]?.command,
+ hookConfig["UserPromptSubmit"]?.[0]?.hooks[0]?.command,
+ hookConfig["PostToolUse"]?.[0]?.hooks[0]?.command,
+ hookConfig["PostCompact"]?.[0]?.hooks[0]?.command,
+ ];
+ const postToolUseMatcher = hookConfig["PostToolUse"]?.[0]?.matcher ?? "";
+
+ // then
+ expect(packageJson.type).toBe("module");
+ expect(packageJson.packageManager).toBe("[email protected]");
+ expect(packageJson.dependencies ?? {}).toEqual({ picomatch: "^4.0.3" });
+ expect(packageJson.bin["codex-rules"]).toBe("./dist/cli.js");
+ expect(packageJson.files).toContain("bundled-rules");
+ expect(pluginJson.hooks).toBe("./hooks/hooks.json");
+ expect(cliSource.startsWith("#!/usr/bin/env node")).toBe(true);
+ expect(commands).toEqual([
+ `node "${pluginRoot}/dist/cli.js" hook session-start`,
+ `node "${pluginRoot}/dist/cli.js" hook user-prompt-submit`,
+ `node "${pluginRoot}/dist/cli.js" hook post-tool-use`,
+ `node "${pluginRoot}/dist/cli.js" hook post-compact`,
+ ]);
+ expect(postToolUseMatcher).toBe("^apply_patch$");
+ const postToolUseMatcherRegex = new RegExp(postToolUseMatcher);
+ expect(postToolUseMatcherRegex.test("apply_patch")).toBe(true);
+ expect(
+ [
+ "read",
+ "Read",
+ "read_file",
+ "mcp__filesystem__read_file",
+ "mcp__filesystem__read_multiple_files",
+ "mcp__filesystem__write_file",
+ "mcp__filesystem__edit_file",
+ "write",
+ "Write",
+ "edit",
+ "Edit",
+ "multi_edit",
+ "MultiEdit",
+ "multiedit",
+ "exec_command",
+ "shell_command",
+ "bash",
+ "Bash",
+ ].some((toolName) => postToolUseMatcherRegex.test(toolName)),
+ ).toBe(false);
+ });
+});
+
+function isPackageJson(value: unknown): value is PackageJson {
+ if (!isRecord(value)) return false;
+ const dependencies = value["dependencies"];
+ return (
+ value["type"] === "module" &&
+ value["packageManager"] === "[email protected]" &&
+ isStringRecord(value["bin"]) &&
+ isStringArray(value["files"]) &&
+ (dependencies === undefined || isRecord(dependencies))
+ );
+}
+
+function isStringArray(value: unknown): value is readonly string[] {
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
+}
+
+function isPluginJson(value: unknown): value is PluginJson {
+ return isRecord(value) && typeof value["hooks"] === "string";
+}
+
+function isHooksJson(value: unknown): value is HooksJson {
+ if (!isRecord(value) || !isRecord(value["hooks"])) return false;
+ return Object.values(value["hooks"]).every(isHookEntries);
+}
+
+function isHookEntries(value: unknown): value is readonly HookEntry[] {
+ return Array.isArray(value) && value.every(isHookEntry);
+}
+
+function isHookEntry(value: unknown): value is HookEntry {
+ return isRecord(value) && Array.isArray(value["hooks"]) && value["hooks"].every(isHookCommand);
+}
+
+function isHookCommand(value: unknown): value is HookCommand {
+ return isRecord(value) && typeof value["command"] === "string";
+}
+
+function isStringRecord(value: unknown): value is Record<string, string> {
+ return isRecord(value) && Object.values(value).every((item) => typeof item === "string");
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
diff --git a/plugins/omo/components/rules/test/scanner.test.ts b/plugins/omo/components/rules/test/scanner.test.ts
new file mode 100644
index 00000000..fb178639
--- /dev/null
+++ b/plugins/omo/components/rules/test/scanner.test.ts
@@ -0,0 +1,63 @@
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { scanRuleFiles } from "../src/rules/scanner.js";
+
+const tempDirectories: string[] = [];
+
+afterEach(() => {
+ for (const directory of tempDirectories.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+describe("scanRuleFiles", () => {
+ it("#given more rule files than max #when scanning #then returns only capped files", () => {
+ // given
+ const root = mkdtempSync(join(tmpdir(), "codex-rules-scanner-"));
+ tempDirectories.push(root);
+ for (let index = 0; index < 5; index += 1) {
+ writeFileSync(join(root, `rule-${index}.md`), `Rule ${index}\n`);
+ }
+
+ // when
+ const files = scanRuleFiles({ rootDir: root, maxFiles: 2 });
+
+ // then
+ expect(files).toHaveLength(2);
+ });
+
+ it("#given rule files and an excluded directory #when scanning #then returns sorted non-excluded files", () => {
+ // given
+ const root = mkdtempSync(join(tmpdir(), "codex-rules-scanner-"));
+ tempDirectories.push(root);
+ mkdirSync(join(root, "dist"), { recursive: true });
+ writeFileSync(join(root, "beta.md"), "Beta\n");
+ writeFileSync(join(root, "alpha.md"), "Alpha\n");
+ writeFileSync(join(root, "dist", "ignored.md"), "Ignored\n");
+
+ // when
+ const files = scanRuleFiles({ rootDir: root });
+
+ // then
+ expect(files.map((file) => file.path)).toEqual([join(root, "alpha.md"), join(root, "beta.md")]);
+ });
+
+ it("#given symlink loop #when scanning #then traversal terminates without duplicate files", () => {
+ // given
+ const root = mkdtempSync(join(tmpdir(), "codex-rules-scanner-"));
+ tempDirectories.push(root);
+ const nested = join(root, "nested");
+ mkdirSync(nested, { recursive: true });
+ writeFileSync(join(root, "root.md"), "Root\n");
+ symlinkSync(root, join(nested, "loop"));
+
+ // when
+ const files = scanRuleFiles({ rootDir: root });
+
+ // then
+ expect(files.map((file) => file.path)).toEqual([join(root, "root.md")]);
+ });
+});
diff --git a/plugins/omo/components/rules/test/tool-paths.test.ts b/plugins/omo/components/rules/test/tool-paths.test.ts
new file mode 100644
index 00000000..17be0944
--- /dev/null
+++ b/plugins/omo/components/rules/test/tool-paths.test.ts
@@ -0,0 +1,198 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { type CodexPostToolUseLike, extractCodexToolPaths } from "../src/tool-paths.js";
+
+const tempDirectories: string[] = [];
+
+afterEach(() => {
+ for (const directory of tempDirectories.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function makeProject(): string {
+ const root = mkdtempSync(path.join(tmpdir(), "codex-rules-paths-"));
+ tempDirectories.push(root);
+ mkdirSync(path.join(root, "src"), { recursive: true });
+ writeFileSync(path.join(root, "src", "app.ts"), "export const app = true;\n");
+ return root;
+}
+
+function postToolUse(input: { toolName: string; toolInput?: unknown; toolResponse?: unknown }): CodexPostToolUseLike {
+ return {
+ tool_name: input.toolName,
+ tool_input: input.toolInput ?? {},
+ tool_response: input.toolResponse ?? { text: "ok" },
+ };
+}
+
+describe("extractCodexToolPaths", () => {
+ it("#given filesystem read payload #when extracting #then returns resolved path", () => {
+ // given
+ const root = makeProject();
+
+ // when
+ const paths = extractCodexToolPaths(
+ postToolUse({
+ toolName: "mcp__filesystem__read_file",
+ toolInput: { path: "src/app.ts" },
+ }),
+ root,
+ );
+
+ // then
+ expect(paths).toEqual([path.join(root, "src", "app.ts")]);
+ });
+
+ it("#given apply_patch payload #when extracting #then returns patched file paths", () => {
+ // given
+ const root = makeProject();
+
+ // when
+ const paths = extractCodexToolPaths(
+ postToolUse({
+ toolName: "apply_patch",
+ toolInput: {
+ command: [
+ "*** Begin Patch",
+ "*** Update File: src/app.ts",
+ "@@",
+ "+export const changed = true;",
+ "*** End Patch",
+ ].join("\n"),
+ },
+ }),
+ root,
+ );
+
+ // then
+ expect(paths).toEqual([path.join(root, "src", "app.ts")]);
+ });
+
+ it("#given apply_patch add update and move payload #when extracting #then returns each target once", () => {
+ // given
+ const root = makeProject();
+
+ // when
+ const paths = extractCodexToolPaths(
+ postToolUse({
+ toolName: "apply_patch",
+ toolInput: {
+ command: [
+ "*** Begin Patch",
+ "*** Add File: src/new.ts",
+ "+export const created = true;",
+ "*** Update File: src/app.ts",
+ "*** Move to: src/moved.ts",
+ "@@",
+ "-export const app = true;",
+ "+export const moved = true;",
+ "*** Update File: src/moved.ts",
+ "@@",
+ "-export const moved = true;",
+ "+export const moved = false;",
+ "*** End Patch",
+ ].join("\n"),
+ },
+ }),
+ root,
+ );
+
+ // then
+ expect(paths).toEqual([
+ path.join(root, "src", "new.ts"),
+ path.join(root, "src", "app.ts"),
+ path.join(root, "src", "moved.ts"),
+ ]);
+ });
+
+ it("#given mcp write-file payload #when extracting #then returns resolved path", () => {
+ // given
+ const root = makeProject();
+
+ // when
+ const paths = extractCodexToolPaths(
+ postToolUse({
+ toolName: "mcp__filesystem__write_file",
+ toolInput: { path: "src/app.ts", content: "export const app = true;\n" },
+ }),
+ root,
+ );
+
+ // then
+ expect(paths).toEqual([path.join(root, "src", "app.ts")]);
+ });
+
+ it("#given mcp edit-file payload #when extracting #then returns resolved path", () => {
+ // given
+ const root = makeProject();
+
+ // when
+ const paths = extractCodexToolPaths(
+ postToolUse({
+ toolName: "mcp__filesystem__edit_file",
+ toolInput: { path: "src/app.ts", edits: [] },
+ }),
+ root,
+ );
+
+ // then
+ expect(paths).toEqual([path.join(root, "src", "app.ts")]);
+ });
+
+ it("#given mcp read-multiple-files payload #when extracting #then returns all resolved paths", () => {
+ // given
+ const root = makeProject();
+ writeFileSync(path.join(root, "src", "other.ts"), "export const other = true;\n");
+
+ // when
+ const paths = extractCodexToolPaths(
+ postToolUse({
+ toolName: "mcp__filesystem__read_multiple_files",
+ toolInput: { paths: ["src/app.ts", "src/other.ts"] },
+ }),
+ root,
+ );
+
+ // then
+ expect(paths).toEqual([path.join(root, "src", "app.ts"), path.join(root, "src", "other.ts")]);
+ });
+
+ it("#given shell command payload #when extracting #then returns only existing file tokens", () => {
+ // given
+ const root = makeProject();
+
+ // when
+ const paths = extractCodexToolPaths(
+ postToolUse({
+ toolName: "exec_command",
+ toolInput: { cmd: "sed -n '1,80p' src/app.ts src/missing.ts", workdir: root },
+ }),
+ "/tmp",
+ );
+
+ // then
+ expect(paths).toEqual([path.join(root, "src", "app.ts")]);
+ });
+
+ it("#given failed tracked tool payload #when extracting #then returns no paths", () => {
+ // given
+ const root = makeProject();
+
+ // when
+ const paths = extractCodexToolPaths(
+ postToolUse({
+ toolName: "read",
+ toolInput: { path: "src/app.ts" },
+ toolResponse: { is_error: true },
+ }),
+ root,
+ );
+
+ // then
+ expect(paths).toEqual([]);
+ });
+});
diff --git a/plugins/omo/components/rules/tsconfig.build.json b/plugins/omo/components/rules/tsconfig.build.json
new file mode 100644
index 00000000..5b5bbcaf
--- /dev/null
+++ b/plugins/omo/components/rules/tsconfig.build.json
@@ -0,0 +1,12 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "allowImportingTsExtensions": false,
+ "declaration": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "noEmit": false
+ },
+ "include": ["src/**/*"],
+ "exclude": ["test/**/*"]
+}
diff --git a/plugins/omo/components/rules/tsconfig.json b/plugins/omo/components/rules/tsconfig.json
new file mode 100644
index 00000000..342229c0
--- /dev/null
+++ b/plugins/omo/components/rules/tsconfig.json
@@ -0,0 +1,27 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "lib": ["ES2022"],
+ "strict": true,
+ "exactOptionalPropertyTypes": true,
+ "noUncheckedIndexedAccess": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "verbatimModuleSyntax": true,
+ "noImplicitOverride": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "esModuleInterop": true,
+ "allowImportingTsExtensions": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "useDefineForClassFields": false,
+ "types": ["node"],
+ "noEmit": true
+ },
+ "include": ["src/**/*", "test/**/*"]
+}
diff --git a/plugins/omo/components/rules/vitest.config.ts b/plugins/omo/components/rules/vitest.config.ts
new file mode 100644
index 00000000..c4fddb41
--- /dev/null
+++ b/plugins/omo/components/rules/vitest.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ environment: "node",
+ pool: "threads",
+ },
+});
diff --git a/plugins/omo/components/telemetry/AGENTS.md b/plugins/omo/components/telemetry/AGENTS.md
new file mode 100644
index 00000000..a3887f65
--- /dev/null
+++ b/plugins/omo/components/telemetry/AGENTS.md
@@ -0,0 +1,37 @@
+# Repository Conventions
+
+Conventions for human contributors and AI agents working on this component.
+
+## Style
+
+- Terse technical prose. No emojis in commits, issues, PR comments, or code.
+- TypeScript strict mode. No `any`, no `@ts-ignore`, no `@ts-expect-error`, no enums.
+- ESM modules with `.js` suffix in runtime import paths.
+- Tabs for indentation. Double quotes for strings.
+- Tests use vitest with `#given .. #when .. #then` descriptions or plain `// given / // when / // then` body comments.
+
+## Commands
+
+- `npm install` - install dependencies.
+- `npm test` - run vitest once.
+- `npm run typecheck` - strict TypeScript check.
+- `npm run check` - type check, biome, and build.
+- `npm run build` - emit `dist/`.
+- `node dist/cli.js hook session-start < fixture.json` - smoke-test the SessionStart hook.
+
+## Constraints
+
+- No Bun APIs. Runtime is Node only because Codex launches plugin hooks with Node.
+- The single hook handler is `runSessionStartHook`. Do not add new hook handlers without also wiring them in `hooks/hooks.json` and `plugin/hooks/hooks.json`.
+- Telemetry MUST be silent on every failure path. The CLI MUST exit 0 with empty stdout even when PostHog construction, capture, or shutdown throws.
+- Telemetry MUST be daily-deduplicated. Adding a new event type requires a new state file slot, not removal of the existing dedup.
+- Hook output MUST stay empty (no `additionalContext`, no `systemMessage`). This component is observability-only and MUST NOT inject context into the Codex conversation.
+- Constants in `src/product-identity.ts` MUST stay byte-equivalent with `packages/omo-codex/src/telemetry/product-identity.ts`. The cross-package equivalence test will fail otherwise.
+- Do not couple this component back to omo internal source paths beyond what `cross-package-equivalence.test.ts` already asserts at the constants layer.
+
+## Don'ts
+
+- No `git add -A` or `git add .`. Stage only the files you changed.
+- No `git commit --no-verify`. No force pushes. No history rewriting on shared branches.
+- No new network calls. PostHog is the only allowed sink.
+- No new env vars without README + privacy-policy update.
diff --git a/plugins/omo/components/telemetry/README.md b/plugins/omo/components/telemetry/README.md
new file mode 100644
index 00000000..c0f8655e
--- /dev/null
+++ b/plugins/omo/components/telemetry/README.md
@@ -0,0 +1,102 @@
+# codex-telemetry
+
+Codex plugin component that emits a single anonymous daily-active event (`omo_codex_daily_active`) to PostHog whenever a Codex session starts.
+
+The event is sent **at most once per UTC day per machine**. It uses a SHA256-hashed installation identifier derived from `omo-codex:${hostname}` and never sends the raw hostname. PostHog person profiles are explicitly disabled.
+
+## Hook Wiring
+
+The component registers a single `SessionStart` hook:
+
+```json
+{
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start",
+ "timeout": 5
+ }
+ ]
+ }
+ ]
+ }
+}
+```
+
+The aggregate `plugin/hooks/hooks.json` mounts this hook alongside `rules` and `ultrawork` so all three fire in parallel at the start of every Codex session.
+
+## What Is Captured
+
+A single PostHog `capture` call with:
+
+- `event: "omo_codex_daily_active"`
+- `distinctId: sha256("omo-codex:" + hostname)`
+- `properties`:
+ - `platform`, `product_name`, `package_name`, `package_version`
+ - `runtime` (`"node"`), `runtime_version`
+ - `source: "plugin"`, `reason: "session_start"`
+ - `$os`, `$os_version`, `os_arch`, `os_type`
+ - `cpu_count`, `cpu_model`, `total_memory_gb`
+ - `locale`, `timezone`, `shell`, `ci`, `terminal`
+ - `day_utc` (today's UTC date)
+ - `$process_person_profile: false`
+
+The component never sends prompt contents, file contents, API keys, raw hostnames, or any user-identifying data.
+
+## Opt-Out
+
+Set any of the following environment variables before launching Codex:
+
+```bash
+# Codex-only opt-out
+export OMO_CODEX_DISABLE_POSTHOG=1
+export OMO_CODEX_SEND_ANONYMOUS_TELEMETRY=0
+
+# Global opt-out (covers both omo and omo-codex)
+export OMO_DISABLE_POSTHOG=1
+export OMO_SEND_ANONYMOUS_TELEMETRY=0
+```
+
+When any of these is set the component creates a no-op PostHog client and exits without any network call.
+
+## Daily Deduplication
+
+The component writes a small JSON state file at:
+
+```
+$XDG_DATA_HOME/omo-codex/posthog-activity.json
+# or, when XDG_DATA_HOME is unset:
+~/.local/share/omo-codex/posthog-activity.json
+```
+
+containing `{ "lastActiveDayUTC": "YYYY-MM-DD" }`. If the stored day matches today (UTC), the hook returns without sending anything. The file is written atomically via `rename(2)`.
+
+## Failure Behavior
+
+Every telemetry path is wrapped in `try`/`catch`. The hook always exits 0 with no stdout output, even when PostHog construction, capture, or shutdown fails. Codex session startup is never blocked or slowed by telemetry failures.
+
+## Endpoint Overrides
+
+| Variable | Default |
+|----------|---------|
+| `POSTHOG_HOST` | `https://us.i.posthog.com` |
+| `POSTHOG_API_KEY` | shared `omo-codex` project key |
+
+## Development
+
+```bash
+npm install
+npm test # vitest (in-process + subprocess CLI smoke)
+npm run typecheck
+npm run build # tsc -> dist/
+npm run check # typecheck + biome + build
+```
+
+The component shares its product identity constants with the `@oh-my-opencode/omo-codex` CLI installer. Drift between the two implementations is guarded by `packages/omo-codex/src/telemetry/cross-package-equivalence.test.ts`.
+
+## Privacy
+
+See [the omo Privacy Policy](https://github.com/code-yeongyu/oh-my-openagent/blob/dev/docs/legal/privacy-policy.md) for the full disclosure.
diff --git a/plugins/omo/components/telemetry/biome.json b/plugins/omo/components/telemetry/biome.json
new file mode 100644
index 00000000..5aa1a0dc
--- /dev/null
+++ b/plugins/omo/components/telemetry/biome.json
@@ -0,0 +1,48 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.4.15/schema.json",
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "recommended": true,
+ "style": {
+ "noDefaultExport": "error",
+ "noEnum": "error",
+ "noNonNullAssertion": "error",
+ "useImportType": "error",
+ "useConst": "error",
+ "useNodejsImportProtocol": "off"
+ },
+ "complexity": {
+ "useLiteralKeys": "off"
+ },
+ "suspicious": {
+ "noExplicitAny": "error",
+ "noTsIgnore": "error",
+ "noControlCharactersInRegex": "off",
+ "noEmptyInterface": "off"
+ }
+ }
+ },
+ "formatter": {
+ "enabled": true,
+ "formatWithErrors": false,
+ "indentStyle": "tab",
+ "indentWidth": 3,
+ "lineWidth": 120
+ },
+ "files": {
+ "includes": ["src/**/*.ts", "test/**/*.ts", "vitest.config.ts", "!**/node_modules/**/*", "!**/dist/**/*"]
+ },
+ "overrides": [
+ {
+ "includes": ["vitest.config.ts"],
+ "linter": {
+ "rules": {
+ "style": {
+ "noDefaultExport": "off"
+ }
+ }
+ }
+ }
+ ]
+}
diff --git a/plugins/omo/components/telemetry/hooks/hooks.json b/plugins/omo/components/telemetry/hooks/hooks.json
new file mode 100644
index 00000000..154a112a
--- /dev/null
+++ b/plugins/omo/components/telemetry/hooks/hooks.json
@@ -0,0 +1,15 @@
+{
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start",
+ "timeout": 5
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/omo/components/telemetry/package.json b/plugins/omo/components/telemetry/package.json
new file mode 100644
index 00000000..628bef33
--- /dev/null
+++ b/plugins/omo/components/telemetry/package.json
@@ -0,0 +1,56 @@
+{
+ "name": "@code-yeongyu/codex-telemetry",
+ "version": "0.1.0",
+ "description": "Codex plugin component that emits omo-codex anonymous daily-active telemetry on SessionStart.",
+ "type": "module",
+ "packageManager": "[email protected]",
+ "license": "MIT",
+ "homepage": "https://github.com/code-yeongyu/oh-my-openagent",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/code-yeongyu/oh-my-openagent.git"
+ },
+ "bugs": {
+ "url": "https://github.com/code-yeongyu/oh-my-openagent/issues"
+ },
+ "keywords": [
+ "codex",
+ "codex-plugin",
+ "omo",
+ "telemetry",
+ "posthog",
+ "hooks",
+ "daily-active"
+ ],
+ "bin": {
+ "codex-telemetry": "./dist/cli.js"
+ },
+ "files": [
+ "dist",
+ "hooks",
+ "LICENSE",
+ "README.md",
+ "CHANGELOG.md"
+ ],
+ "scripts": {
+ "build": "tsc -p tsconfig.build.json",
+ "test": "vitest --run",
+ "test:watch": "vitest",
+ "typecheck": "tsc --noEmit",
+ "lint": "biome check .",
+ "lint:fix": "biome check --write .",
+ "check": "tsc --noEmit && biome check . && npm run build"
+ },
+ "dependencies": {
+ "posthog-node": "^5.34.3"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.15",
+ "@types/node": "^25.7.0",
+ "typescript": "^6.0.3",
+ "vitest": "^4.1.5"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+}
diff --git a/plugins/omo/components/telemetry/src/atomic-write.ts b/plugins/omo/components/telemetry/src/atomic-write.ts
new file mode 100644
index 00000000..c87df29d
--- /dev/null
+++ b/plugins/omo/components/telemetry/src/atomic-write.ts
@@ -0,0 +1,22 @@
+import { renameSync, unlinkSync, writeFileSync } from "node:fs"
+
+export function writeFileAtomically(filePath: string, content: string): void {
+ const tempPath = `${filePath}.tmp`
+ writeFileSync(tempPath, content, "utf-8")
+
+ try {
+ renameSync(tempPath, filePath)
+ } catch (error) {
+ const isPermissionError =
+ error instanceof Error &&
+ (error.message.includes("EPERM") || error.message.includes("EACCES"))
+
+ if (process.platform === "win32" && isPermissionError) {
+ unlinkSync(filePath)
+ renameSync(tempPath, filePath)
+ return
+ }
+
+ throw error
+ }
+}
diff --git a/plugins/omo/components/telemetry/src/cli.ts b/plugins/omo/components/telemetry/src/cli.ts
new file mode 100644
index 00000000..9ce2e2f6
--- /dev/null
+++ b/plugins/omo/components/telemetry/src/cli.ts
@@ -0,0 +1,69 @@
+#!/usr/bin/env node
+import { stdin as processStdin, stdout as processStdout } from "node:process";
+
+import { type CodexSessionStartInput, runSessionStartHook } from "./codex-hook.js";
+
+const command = process.argv[2];
+const subcommand = process.argv[3];
+
+if (command === "hook" && subcommand === "session-start") {
+ await runHookCli();
+} else {
+ process.stderr.write("Usage: codex-telemetry hook session-start\n");
+ process.exitCode = 1;
+}
+
+async function runHookCli(): Promise<void> {
+ const raw = await readStdin();
+ if (raw.trim().length === 0) return;
+ const parsed = parseHookInput(raw);
+ if (!isCodexSessionStartInput(parsed)) return;
+ const output = await runSessionStartHook(parsed);
+ if (output.length > 0) {
+ processStdout.write(output);
+ }
+}
+
+function parseHookInput(raw: string): unknown | undefined {
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ return parsed;
+ } catch {
+ return undefined;
+ }
+}
+
+function isCodexSessionStartInput(value: unknown): value is CodexSessionStartInput {
+ return (
+ isRecord(value) &&
+ value["hook_event_name"] === "SessionStart" &&
+ typeof value["session_id"] === "string" &&
+ isStringOrNull(value["transcript_path"]) &&
+ typeof value["cwd"] === "string" &&
+ typeof value["model"] === "string" &&
+ typeof value["permission_mode"] === "string" &&
+ typeof value["source"] === "string"
+ );
+}
+
+function isStringOrNull(value: unknown): value is string | null {
+ return typeof value === "string" || value === null;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function readStdin(): Promise<string> {
+ return new Promise((resolve, reject) => {
+ let data = "";
+ processStdin.setEncoding("utf8");
+ processStdin.on("data", (chunk: string) => {
+ data += chunk;
+ });
+ processStdin.once("error", reject);
+ processStdin.once("end", () => {
+ resolve(data);
+ });
+ });
+}
diff --git a/plugins/omo/components/telemetry/src/codex-hook.ts b/plugins/omo/components/telemetry/src/codex-hook.ts
new file mode 100644
index 00000000..6e61ebb8
--- /dev/null
+++ b/plugins/omo/components/telemetry/src/codex-hook.ts
@@ -0,0 +1,49 @@
+import {
+ type PostHogActivityReason,
+ type PostHogClient,
+ createPluginPostHog,
+ getPostHogDistinctId,
+} from "./posthog.js";
+
+export type CodexSessionStartInput = {
+ session_id: string;
+ transcript_path: string | null;
+ cwd: string;
+ hook_event_name: "SessionStart";
+ model: string;
+ permission_mode: string;
+ source: "startup" | "resume" | "clear";
+};
+
+export type CodexTelemetryHookOptions = {
+ createClient?: () => PostHogClient;
+ getDistinctId?: () => string;
+};
+
+const SESSION_START_REASON: PostHogActivityReason = "session_start";
+
+export async function runSessionStartHook(
+ _input: CodexSessionStartInput,
+ options: CodexTelemetryHookOptions = {},
+): Promise<string> {
+ const createClient = options.createClient ?? createPluginPostHog;
+ const getDistinctId = options.getDistinctId ?? getPostHogDistinctId;
+
+ const client = createClient();
+ try {
+ client.trackActive(getDistinctId(), SESSION_START_REASON);
+ } catch {
+ await safeShutdown(client);
+ return "";
+ }
+ await safeShutdown(client);
+ return "";
+}
+
+async function safeShutdown(client: PostHogClient): Promise<void> {
+ try {
+ await client.shutdown();
+ } catch {
+ return;
+ }
+}
diff --git a/plugins/omo/components/telemetry/src/data-path.ts b/plugins/omo/components/telemetry/src/data-path.ts
new file mode 100644
index 00000000..06d10276
--- /dev/null
+++ b/plugins/omo/components/telemetry/src/data-path.ts
@@ -0,0 +1,45 @@
+import { accessSync, constants, mkdirSync } from "node:fs"
+import os from "node:os"
+import path from "node:path"
+
+import { CACHE_DIR_NAME } from "./product-identity.js"
+
+type OsProvider = Pick<typeof os, "homedir" | "tmpdir">
+
+let osProviderOverride: OsProvider | null = null
+
+export function getOsProvider(): OsProvider {
+ return osProviderOverride ?? os
+}
+
+/** @internal test-only */
+export function __setOsProviderForTesting(provider: OsProvider): void {
+ osProviderOverride = provider
+}
+
+/** @internal test-only */
+export function __resetOsProviderForTesting(): void {
+ osProviderOverride = null
+}
+
+function resolveWritableDirectory(preferredDir: string, fallbackSuffix: string): string {
+ try {
+ mkdirSync(preferredDir, { recursive: true })
+ accessSync(preferredDir, constants.W_OK)
+ return preferredDir
+ } catch {
+ const fallbackDir = path.join(getOsProvider().tmpdir(), fallbackSuffix)
+ mkdirSync(fallbackDir, { recursive: true })
+ return fallbackDir
+ }
+}
+
+export function getDataDir(): string {
+ const preferredDataDir =
+ process.env["XDG_DATA_HOME"] ?? path.join(getOsProvider().homedir(), ".local", "share")
+ return resolveWritableDirectory(preferredDataDir, "omo-codex-data")
+}
+
+export function getActivityStateDir(): string {
+ return path.join(getDataDir(), CACHE_DIR_NAME)
+}
diff --git a/plugins/omo/components/telemetry/src/env-flags.ts b/plugins/omo/components/telemetry/src/env-flags.ts
new file mode 100644
index 00000000..fa51b9bc
--- /dev/null
+++ b/plugins/omo/components/telemetry/src/env-flags.ts
@@ -0,0 +1,43 @@
+import {
+ DEFAULT_POSTHOG_API_KEY,
+ DEFAULT_POSTHOG_HOST,
+} from "./product-identity.js"
+
+function normalizeEnvValue(value: string | undefined): string | undefined {
+ return value?.trim().toLowerCase()
+}
+
+function isDisableFlag(value: string | undefined): boolean {
+ const normalized = normalizeEnvValue(value)
+ return normalized === "1" || normalized === "true"
+}
+
+function isTelemetryOptOutFlag(value: string | undefined): boolean {
+ const normalized = normalizeEnvValue(value)
+ return normalized === "0" || normalized === "false" || normalized === "no"
+}
+
+export function shouldDisablePostHog(): boolean {
+ return (
+ isDisableFlag(process.env["OMO_DISABLE_POSTHOG"]) ||
+ isTelemetryOptOutFlag(process.env["OMO_SEND_ANONYMOUS_TELEMETRY"]) ||
+ isDisableFlag(process.env["OMO_CODEX_DISABLE_POSTHOG"]) ||
+ isTelemetryOptOutFlag(process.env["OMO_CODEX_SEND_ANONYMOUS_TELEMETRY"])
+ )
+}
+
+export function getPostHogApiKey(): string {
+ const explicit = process.env["POSTHOG_API_KEY"]
+ if (explicit === undefined) {
+ return DEFAULT_POSTHOG_API_KEY
+ }
+ return explicit.trim()
+}
+
+export function hasPostHogApiKey(): boolean {
+ return getPostHogApiKey().length > 0
+}
+
+export function getPostHogHost(): string {
+ return process.env["POSTHOG_HOST"]?.trim() || DEFAULT_POSTHOG_HOST
+}
diff --git a/plugins/omo/components/telemetry/src/posthog-activity-state.ts b/plugins/omo/components/telemetry/src/posthog-activity-state.ts
new file mode 100644
index 00000000..b9fa9a8b
--- /dev/null
+++ b/plugins/omo/components/telemetry/src/posthog-activity-state.ts
@@ -0,0 +1,81 @@
+import { existsSync, mkdirSync, readFileSync } from "node:fs"
+import { join } from "node:path"
+
+import { writeFileAtomically } from "./atomic-write.js"
+import { getActivityStateDir } from "./data-path.js"
+
+export type PostHogActivityState = {
+ readonly lastActiveDayUTC?: string
+}
+
+export type PostHogActivityCaptureState = {
+ readonly dayUTC: string
+ readonly captureDaily: boolean
+}
+
+const POSTHOG_ACTIVITY_STATE_FILE = "posthog-activity.json"
+
+function getPostHogActivityStateFilePath(): string {
+ return join(getActivityStateDir(), POSTHOG_ACTIVITY_STATE_FILE)
+}
+
+function getUtcDayString(date: Date): string {
+ return date.toISOString().slice(0, 10)
+}
+
+function isPostHogActivityState(value: unknown): value is PostHogActivityState {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+}
+
+function readPostHogActivityState(): PostHogActivityState {
+ const stateFilePath = getPostHogActivityStateFilePath()
+
+ if (!existsSync(stateFilePath)) {
+ return {}
+ }
+
+ try {
+ const stateContent = readFileSync(stateFilePath, "utf-8")
+ const stateJson: unknown = JSON.parse(stateContent)
+
+ if (!isPostHogActivityState(stateJson)) {
+ return {}
+ }
+
+ return stateJson
+ } catch {
+ return {}
+ }
+}
+
+function writePostHogActivityState(nextState: PostHogActivityState): void {
+ const stateDir = getActivityStateDir()
+ const stateFilePath = getPostHogActivityStateFilePath()
+
+ try {
+ mkdirSync(stateDir, { recursive: true })
+ writeFileAtomically(stateFilePath, `${JSON.stringify(nextState, null, 2)}\n`)
+ } catch {
+ return
+ }
+}
+
+export function getPostHogActivityCaptureState(
+ now: Date = new Date(),
+): PostHogActivityCaptureState {
+ const state = readPostHogActivityState()
+ const dayUTC = getUtcDayString(now)
+ const captureDaily = state.lastActiveDayUTC !== dayUTC
+
+ if (captureDaily) {
+ writePostHogActivityState({
+ ...state,
+ lastActiveDayUTC: dayUTC,
+ })
+ }
+
+ return {
+ dayUTC,
+ captureDaily,
+ }
+}
diff --git a/plugins/omo/components/telemetry/src/posthog.ts b/plugins/omo/components/telemetry/src/posthog.ts
new file mode 100644
index 00000000..30ab9eb0
--- /dev/null
+++ b/plugins/omo/components/telemetry/src/posthog.ts
@@ -0,0 +1,156 @@
+import { createHash } from "node:crypto";
+import os from "node:os";
+
+import { PostHog } from "posthog-node";
+
+import { getPostHogApiKey, getPostHogHost, hasPostHogApiKey, shouldDisablePostHog } from "./env-flags.js";
+import { getPostHogActivityCaptureState } from "./posthog-activity-state.js";
+import {
+ DEFAULT_POSTHOG_API_KEY,
+ DEFAULT_POSTHOG_HOST,
+ EVENT_NAME,
+ PACKAGE_NAME,
+ PRODUCT_NAME,
+ getComponentVersion,
+} from "./product-identity.js";
+
+export { DEFAULT_POSTHOG_API_KEY, DEFAULT_POSTHOG_HOST };
+
+export type PostHogActivityReason = "session_start";
+
+export type PostHogClient = {
+ trackActive: (distinctId: string, reason: PostHogActivityReason) => void;
+ shutdown: () => Promise<void>;
+};
+
+type OsProvider = Pick<typeof os, "arch" | "cpus" | "hostname" | "platform" | "release" | "totalmem" | "type">;
+type ActivityStateProvider = typeof getPostHogActivityCaptureState;
+
+let osProviderOverride: OsProvider | null = null;
+let activityStateProviderOverride: ActivityStateProvider | null = null;
+
+const NO_OP_POSTHOG: PostHogClient = {
+ trackActive: () => undefined,
+ shutdown: async () => undefined,
+};
+
+type PostHogCaptureEvent = Parameters<PostHog["capture"]>[0];
+
+function resolveOsProvider(): OsProvider {
+ return osProviderOverride ?? os;
+}
+
+function resolveActivityStateProvider(): ActivityStateProvider {
+ return activityStateProviderOverride ?? getPostHogActivityCaptureState;
+}
+
+function getSafeCpuInfo(): { readonly count: number; readonly model: string | undefined } {
+ try {
+ const cpuInfo = resolveOsProvider().cpus();
+ return {
+ count: cpuInfo.length,
+ model: cpuInfo[0]?.model,
+ };
+ } catch {
+ return {
+ count: 0,
+ model: undefined,
+ };
+ }
+}
+
+function getSharedProperties(): NonNullable<PostHogCaptureEvent["properties"]> {
+ const osProvider = resolveOsProvider();
+ const cpuInfo = getSafeCpuInfo();
+
+ return {
+ platform: "omo-codex",
+ product_name: PRODUCT_NAME,
+ package_name: PACKAGE_NAME,
+ package_version: getComponentVersion(),
+ runtime: "node",
+ runtime_version: process.version,
+ source: "plugin",
+ $os: osProvider.platform(),
+ $os_version: osProvider.release(),
+ os_arch: osProvider.arch(),
+ os_type: osProvider.type(),
+ cpu_count: cpuInfo.count,
+ cpu_model: cpuInfo.model,
+ total_memory_gb: Math.round(osProvider.totalmem() / 1024 / 1024 / 1024),
+ locale: Intl.DateTimeFormat().resolvedOptions().locale,
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ shell: process.env["SHELL"],
+ ci: Boolean(process.env["CI"]),
+ terminal: process.env["TERM_PROGRAM"],
+ };
+}
+
+export function createPluginPostHog(): PostHogClient {
+ if (shouldDisablePostHog() || !hasPostHogApiKey()) {
+ return NO_OP_POSTHOG;
+ }
+
+ let client: PostHog;
+ try {
+ client = new PostHog(getPostHogApiKey(), {
+ enableExceptionAutocapture: false,
+ enableLocalEvaluation: false,
+ strictLocalEvaluation: true,
+ disableRemoteConfig: true,
+ flushAt: 1,
+ flushInterval: 0,
+ host: getPostHogHost(),
+ disableGeoip: false,
+ });
+ } catch {
+ return NO_OP_POSTHOG;
+ }
+
+ const sharedProperties = getSharedProperties();
+
+ return {
+ trackActive: (distinctId, reason) => {
+ const activityState = resolveActivityStateProvider()();
+ if (!activityState.captureDaily) {
+ return;
+ }
+
+ client.capture({
+ distinctId,
+ event: EVENT_NAME,
+ properties: {
+ ...sharedProperties,
+ $process_person_profile: false,
+ day_utc: activityState.dayUTC,
+ reason,
+ },
+ });
+ },
+ shutdown: async () => client.shutdown(),
+ };
+}
+
+export function getPostHogDistinctId(): string {
+ return createHash("sha256").update(`omo-codex:${resolveOsProvider().hostname()}`).digest("hex");
+}
+
+/** @internal test-only */
+export function __setOsProviderForTesting(provider: OsProvider): void {
+ osProviderOverride = provider;
+}
+
+/** @internal test-only */
+export function __resetOsProviderForTesting(): void {
+ osProviderOverride = null;
+}
+
+/** @internal test-only */
+export function __setActivityStateProviderForTesting(provider: ActivityStateProvider): void {
+ activityStateProviderOverride = provider;
+}
+
+/** @internal test-only */
+export function __resetActivityStateProviderForTesting(): void {
+ activityStateProviderOverride = null;
+}
diff --git a/plugins/omo/components/telemetry/src/product-identity.ts b/plugins/omo/components/telemetry/src/product-identity.ts
new file mode 100644
index 00000000..1f34d03b
--- /dev/null
+++ b/plugins/omo/components/telemetry/src/product-identity.ts
@@ -0,0 +1,35 @@
+import { readFileSync } from "node:fs";
+
+export const PRODUCT_NAME = "omo-codex";
+export const PACKAGE_NAME = "@oh-my-opencode/omo-codex";
+export const CACHE_DIR_NAME = "omo-codex";
+export const EVENT_NAME = "omo_codex_daily_active";
+export const LEGACY_PARENT_PACKAGE = "oh-my-opencode";
+export const DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
+export const DEFAULT_POSTHOG_API_KEY = "phc_CFJhj5HyvA62QPhvyaUCtaq23aUfznnijg5VaaGkNk74";
+
+type ComponentPackageManifest = { readonly version?: string };
+
+function isComponentPackageManifest(value: unknown): value is ComponentPackageManifest {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
+function readComponentVersionFromManifest(): string {
+ try {
+ const manifestUrl = new URL("../package.json", import.meta.url);
+ const manifestText = readFileSync(manifestUrl, "utf-8");
+ const parsed: unknown = JSON.parse(manifestText);
+ if (isComponentPackageManifest(parsed) && typeof parsed.version === "string") {
+ return parsed.version;
+ }
+ } catch {
+ return "0.0.0";
+ }
+ return "0.0.0";
+}
+
+const COMPONENT_VERSION_CACHE = readComponentVersionFromManifest();
+
+export function getComponentVersion(): string {
+ return COMPONENT_VERSION_CACHE;
+}
diff --git a/plugins/omo/components/telemetry/test/codex-hook.test.ts b/plugins/omo/components/telemetry/test/codex-hook.test.ts
new file mode 100644
index 00000000..066ad9b1
--- /dev/null
+++ b/plugins/omo/components/telemetry/test/codex-hook.test.ts
@@ -0,0 +1,247 @@
+import { spawn } from "node:child_process";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { type CodexSessionStartInput, runSessionStartHook } from "../src/codex-hook.js";
+import type { PostHogActivityReason, PostHogClient } from "../src/posthog.js";
+
+const CLI_PATH = fileURLToPath(new URL("../dist/cli.js", import.meta.url));
+
+type CapturedCall = {
+ distinctId: string;
+ reason: PostHogActivityReason;
+};
+
+type CliResult = {
+ exitCode: number | null;
+ stdout: string;
+ stderr: string;
+};
+
+const tempDirectories: string[] = [];
+
+afterEach(() => {
+ for (const directory of tempDirectories.splice(0)) {
+ rmSync(directory, { recursive: true, force: true });
+ }
+});
+
+function makeSessionStartInput(overrides: Partial<CodexSessionStartInput> = {}): CodexSessionStartInput {
+ return {
+ session_id: "session-123",
+ transcript_path: null,
+ cwd: "/tmp/project",
+ hook_event_name: "SessionStart",
+ model: "gpt-5.5",
+ permission_mode: "default",
+ source: "startup",
+ ...overrides,
+ };
+}
+
+function makeRecordingClient(): { client: PostHogClient; calls: CapturedCall[]; shutdownCalls: number } {
+ const calls: CapturedCall[] = [];
+ let shutdownCalls = 0;
+ const client: PostHogClient = {
+ trackActive: (distinctId, reason) => {
+ calls.push({ distinctId, reason });
+ },
+ shutdown: async () => {
+ shutdownCalls += 1;
+ },
+ };
+ return {
+ client,
+ calls,
+ get shutdownCalls() {
+ return shutdownCalls;
+ },
+ };
+}
+
+function runHookCli(input: string, env: NodeJS.ProcessEnv = {}): Promise<CliResult> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [CLI_PATH, "hook", "session-start"], {
+ env: { ...process.env, ...env },
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ stdout += chunk;
+ });
+ child.stderr.on("data", (chunk: string) => {
+ stderr += chunk;
+ });
+ child.once("error", reject);
+ child.once("close", (exitCode) => {
+ resolve({ exitCode, stdout, stderr });
+ });
+ child.stdin.end(input);
+ });
+}
+
+describe("runSessionStartHook", () => {
+ describe("#given a SessionStart payload and recording client", () => {
+ it("#when invoked #then calls trackActive once with session_start reason", async () => {
+ const recorder = makeRecordingClient();
+
+ const output = await runSessionStartHook(makeSessionStartInput(), {
+ createClient: () => recorder.client,
+ getDistinctId: () => "distinct-id-abc",
+ });
+
+ expect(recorder.calls).toEqual([{ distinctId: "distinct-id-abc", reason: "session_start" }]);
+ expect(output).toBe("");
+ });
+
+ it("#when invoked #then awaits shutdown exactly once even after trackActive success", async () => {
+ const recorder = makeRecordingClient();
+
+ await runSessionStartHook(makeSessionStartInput(), {
+ createClient: () => recorder.client,
+ getDistinctId: () => "distinct-id-abc",
+ });
+
+ expect(recorder.shutdownCalls).toBe(1);
+ });
+ });
+
+ describe("#given a client whose trackActive throws", () => {
+ it("#when invoked #then swallows the error, still shuts down, and returns empty string", async () => {
+ let shutdownCalls = 0;
+ const throwingClient: PostHogClient = {
+ trackActive: () => {
+ throw new Error("trackActive failed");
+ },
+ shutdown: async () => {
+ shutdownCalls += 1;
+ },
+ };
+
+ const output = await runSessionStartHook(makeSessionStartInput(), {
+ createClient: () => throwingClient,
+ getDistinctId: () => "distinct-id-abc",
+ });
+
+ expect(output).toBe("");
+ expect(shutdownCalls).toBe(1);
+ });
+ });
+
+ describe("#given a client whose shutdown rejects", () => {
+ it("#when invoked #then swallows the rejection and returns empty string", async () => {
+ const rejectingClient: PostHogClient = {
+ trackActive: () => undefined,
+ shutdown: async () => {
+ throw new Error("shutdown failed");
+ },
+ };
+
+ const output = await runSessionStartHook(makeSessionStartInput(), {
+ createClient: () => rejectingClient,
+ getDistinctId: () => "distinct-id-abc",
+ });
+
+ expect(output).toBe("");
+ });
+ });
+});
+
+describe("telemetry CLI session-start hook (subprocess)", () => {
+ describe("#given OMO_DISABLE_POSTHOG=1 set in environment", () => {
+ it("#when CLI receives valid SessionStart JSON #then exits 0 with no stdout output", async () => {
+ const payload = JSON.stringify(makeSessionStartInput());
+ const dataDir = mkdtempSync(path.join(tmpdir(), "codex-telemetry-data-"));
+ tempDirectories.push(dataDir);
+
+ const result = await runHookCli(payload, {
+ OMO_DISABLE_POSTHOG: "1",
+ XDG_DATA_HOME: dataDir,
+ });
+
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toBe("");
+ });
+ });
+
+ describe("#given OMO_CODEX_SEND_ANONYMOUS_TELEMETRY=0 set in environment", () => {
+ it("#when CLI receives valid SessionStart JSON #then exits 0 with no stdout output", async () => {
+ const payload = JSON.stringify(makeSessionStartInput());
+ const dataDir = mkdtempSync(path.join(tmpdir(), "codex-telemetry-data-"));
+ tempDirectories.push(dataDir);
+
+ const result = await runHookCli(payload, {
+ OMO_CODEX_SEND_ANONYMOUS_TELEMETRY: "0",
+ XDG_DATA_HOME: dataDir,
+ });
+
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toBe("");
+ });
+ });
+
+ describe("#given malformed JSON on stdin", () => {
+ it("#when CLI receives invalid input #then exits 0 with no stdout output", async () => {
+ const dataDir = mkdtempSync(path.join(tmpdir(), "codex-telemetry-data-"));
+ tempDirectories.push(dataDir);
+
+ const result = await runHookCli("not-a-json-object", {
+ OMO_DISABLE_POSTHOG: "1",
+ XDG_DATA_HOME: dataDir,
+ });
+
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toBe("");
+ });
+ });
+
+ describe("#given empty stdin", () => {
+ it("#when CLI receives empty input #then exits 0 with no stdout output", async () => {
+ const dataDir = mkdtempSync(path.join(tmpdir(), "codex-telemetry-data-"));
+ tempDirectories.push(dataDir);
+
+ const result = await runHookCli("", {
+ OMO_DISABLE_POSTHOG: "1",
+ XDG_DATA_HOME: dataDir,
+ });
+
+ expect(result.exitCode).toBe(0);
+ expect(result.stdout).toBe("");
+ });
+ });
+
+ describe("#given unknown subcommand", () => {
+ it("#when CLI is invoked with bad subcommand #then exits non-zero with usage on stderr", async () => {
+ const result = await new Promise<CliResult>((resolve, reject) => {
+ const child = spawn(process.execPath, [CLI_PATH, "hook", "bogus"], {
+ env: process.env,
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => {
+ stdout += chunk;
+ });
+ child.stderr.on("data", (chunk: string) => {
+ stderr += chunk;
+ });
+ child.once("error", reject);
+ child.once("close", (exitCode) => {
+ resolve({ exitCode, stdout, stderr });
+ });
+ child.stdin.end();
+ });
+
+ expect(result.exitCode).not.toBe(0);
+ expect(result.stderr).toContain("Usage");
+ });
+ });
+});
diff --git a/plugins/omo/components/telemetry/tsconfig.build.json b/plugins/omo/components/telemetry/tsconfig.build.json
new file mode 100644
index 00000000..5b5bbcaf
--- /dev/null
+++ b/plugins/omo/components/telemetry/tsconfig.build.json
@@ -0,0 +1,12 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "allowImportingTsExtensions": false,
+ "declaration": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "noEmit": false
+ },
+ "include": ["src/**/*"],
+ "exclude": ["test/**/*"]
+}
diff --git a/plugins/omo/components/telemetry/tsconfig.json b/plugins/omo/components/telemetry/tsconfig.json
new file mode 100644
index 00000000..342229c0
--- /dev/null
+++ b/plugins/omo/components/telemetry/tsconfig.json
@@ -0,0 +1,27 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "lib": ["ES2022"],
+ "strict": true,
+ "exactOptionalPropertyTypes": true,
+ "noUncheckedIndexedAccess": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "verbatimModuleSyntax": true,
+ "noImplicitOverride": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "esModuleInterop": true,
+ "allowImportingTsExtensions": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "useDefineForClassFields": false,
+ "types": ["node"],
+ "noEmit": true
+ },
+ "include": ["src/**/*", "test/**/*"]
+}
diff --git a/plugins/omo/components/telemetry/vitest.config.ts b/plugins/omo/components/telemetry/vitest.config.ts
new file mode 100644
index 00000000..c4fddb41
--- /dev/null
+++ b/plugins/omo/components/telemetry/vitest.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ environment: "node",
+ pool: "threads",
+ },
+});
diff --git a/plugins/omo/components/ultragoal/.gitattributes b/plugins/omo/components/ultragoal/.gitattributes
new file mode 100644
index 00000000..9363fdb7
--- /dev/null
+++ b/plugins/omo/components/ultragoal/.gitattributes
@@ -0,0 +1,13 @@
+# Normalize line endings: store LF in git, check out LF on every platform.
+# Required so biome's --check passes on Windows (default core.autocrlf=true).
+* text=auto eol=lf
+
+# Explicit binary types
+*.png binary
+*.jpg binary
+*.jpeg binary
+*.gif binary
+*.ico binary
+*.zip binary
+*.tgz binary
+*.gz binary
diff --git a/plugins/omo/components/ultragoal/.gitignore b/plugins/omo/components/ultragoal/.gitignore
new file mode 100644
index 00000000..e5f7145b
--- /dev/null
+++ b/plugins/omo/components/ultragoal/.gitignore
@@ -0,0 +1,6 @@
+node_modules/
+dist/
+*.log
+.DS_Store
+coverage/
+.vitest/
diff --git a/plugins/omo/components/ultragoal/AGENTS.md b/plugins/omo/components/ultragoal/AGENTS.md
new file mode 100644
index 00000000..bc76bb20
--- /dev/null
+++ b/plugins/omo/components/ultragoal/AGENTS.md
@@ -0,0 +1,48 @@
+# Repository Conventions
+
+Conventions for human contributors and AI agents working on this repository.
+
+## Stack
+
+- Node >=20 runtime.
+- npm package manager.
+- TypeScript 6 strict mode.
+- Biome 2 linting and formatting.
+- Vitest 4 test runner.
+
+## Forbidden
+
+- No `as any` or `as unknown`.
+- No `@ts-ignore` or `@ts-expect-error`.
+- No enums.
+- No non-null assertions.
+- No default exports. `vitest.config.ts` is exempt because the framework requires that shape.
+
+## File Ceiling
+
+- Keep each `src/` TypeScript file under 250 pure LOC.
+- Split by responsibility before a file reaches the ceiling.
+
+## Test Discipline
+
+- Use Vitest with nested `describe` names in `#given`, `#when`, and `#then` form, or inline `// given`, `// when`, and `// then` comments.
+- Never use Arrange-Act-Assert comments.
+- Keep fixtures in `test/fixtures/`.
+
+## Commit Style
+
+- Use Conventional Commits.
+- Keep commits atomic.
+- Each commit's tests and build must pass on its own.
+
+## Branding
+
+- Repo artifacts live under `.omo/ultragoal/` paths.
+- Environment variables use the `OMO_ULTRAGOAL_*` prefix.
+- CLI commands use the `omo ultragoal` form.
+- Do not use any alternate legacy CLI alias anywhere.
+
+## Build and Hooks
+
+- Build output goes to `dist/`.
+- `hooks/hooks.json` runs `node ${PLUGIN_ROOT}/dist/cli.js hook user-prompt-submit`.
diff --git a/plugins/omo/components/ultragoal/CHANGELOG.md b/plugins/omo/components/ultragoal/CHANGELOG.md
new file mode 100644
index 00000000..72a3e098
--- /dev/null
+++ b/plugins/omo/components/ultragoal/CHANGELOG.md
@@ -0,0 +1,7 @@
+# Changelog
+
+## [0.1.0] - unreleased
+
+- Initial scaffold of codex-ultragoal plugin.
+- Per-Criterion Cycle: `EXECUTE` is now **EXECUTE-AS-SCENARIO** — the agent must run the Manual-QA channel scenario the criterion named (HTTP call / tmux / browser use / computer use; see new `## Manual-QA channels` section). Inserted a new **CLEAN (PAIRED, NEVER SKIP)** step that tears down every QA-spawned process / `tmux` session / browser context / container / port / temp dir before recording evidence; the cleanup receipt is embedded in the `--evidence` string. Missing receipt → record BLOCKED, not PASS. Added Constraint #13 and a Stop Rule for leftover state.
+- New top-level **`## Manual-QA channels`** section explicitly enumerates the four channels (HTTP call, tmux, Browser use, Computer use) with concrete commands and required artifacts. Goal section now declares **TESTS ALONE NEVER PROVE DONE**: a green test suite is supporting evidence, never completion proof. Criterion-refinement step 2 requires each criterion to name its channel up front.
diff --git a/plugins/omo/components/ultragoal/LICENSE b/plugins/omo/components/ultragoal/LICENSE
new file mode 100644
index 00000000..09aac3c3
--- /dev/null
+++ b/plugins/omo/components/ultragoal/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Yeongyu Kim
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/plugins/omo/components/ultragoal/NOTICE b/plugins/omo/components/ultragoal/NOTICE
new file mode 100644
index 00000000..4b0ea073
--- /dev/null
+++ b/plugins/omo/components/ultragoal/NOTICE
@@ -0,0 +1,6 @@
+codex-ultragoal
+
+This package ports the oh-my-codex ultragoal feature into a Codex plugin repository.
+
+The plugin targets Codex plugin manifests and plugin-bundled lifecycle hooks.
+The orchestration engine is added in later port waves.
diff --git a/plugins/omo/components/ultragoal/README.md b/plugins/omo/components/ultragoal/README.md
new file mode 100644
index 00000000..d783ab30
--- /dev/null
+++ b/plugins/omo/components/ultragoal/README.md
@@ -0,0 +1,75 @@
+# codex-ultragoal
+
+[![ci](https://img.shields.io/badge/ci-pending-lightgrey.svg)](#) [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
+
+Codex plugin scaffold for durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.
+
+## Behavior
+
+| Subcommand | Purpose |
+|------------|---------|
+| `omo ultragoal create-goals` | Create repo-native goals from a brief and seed criteria. |
+| `omo ultragoal record-evidence` | Record observable evidence for the active criterion. |
+| `omo ultragoal criteria` | Inspect or revise goal success criteria. |
+| `omo ultragoal complete-goals` | Complete eligible goals after criteria pass. |
+| `omo ultragoal checkpoint` | Refuse completion until criteria and evidence gates pass. |
+| `omo ultragoal steer` | Apply steering updates to the plan. |
+| `omo ultragoal status` | Report active goal, criteria, and evidence state. |
+
+Wave 1 is scaffold only. Command behavior lands in later waves.
+
+## Codex Plugin
+
+The plugin ships:
+
+- `.codex-plugin/plugin.json` for Codex plugin discovery.
+- `hooks/hooks.json` for the `UserPromptSubmit` hook.
+- `skills/ultragoal/` as the future skill directory.
+
+The hook command is:
+
+```bash
+node "${PLUGIN_ROOT}/dist/cli.js" hook user-prompt-submit
+```
+
+No MCP server or Codex tool is exposed in this scaffold.
+
+## Local Development
+
+```bash
+npm install
+npm test
+npm run typecheck
+npm run check
+npm pack --dry-run
+```
+
+## Local Codex Installation
+
+```bash
+bunx lazycodex install
+```
+
+The installer builds and copies the plugin into `~/.codex/plugins/cache/sisyphuslabs/omo/0.1.0`, registers the `sisyphuslabs` marketplace from the `lazycodex` Git repository, installs runtime dependencies there, and enables:
+
+```toml
+[features]
+plugins = true
+plugin_hooks = true
+
+[plugins."omo@sisyphuslabs"]
+enabled = true
+```
+
+## Privacy
+
+This plugin runs locally. The scaffold does not call a network service by itself.
+
+## License
+
+[MIT](LICENSE).
+
+## Related
+
+- [oh-my-codex](https://github.com/code-yeongyu/oh-my-codex) - source project for the ultragoal port.
+- [lazycodex](https://github.com/code-yeongyu/lazycodex) - Sisyphus Labs Codex marketplace repository.
diff --git a/plugins/omo/components/ultragoal/biome.json b/plugins/omo/components/ultragoal/biome.json
new file mode 100644
index 00000000..5aa1a0dc
--- /dev/null
+++ b/plugins/omo/components/ultragoal/biome.json
@@ -0,0 +1,48 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.4.15/schema.json",
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "recommended": true,
+ "style": {
+ "noDefaultExport": "error",
+ "noEnum": "error",
+ "noNonNullAssertion": "error",
+ "useImportType": "error",
+ "useConst": "error",
+ "useNodejsImportProtocol": "off"
+ },
+ "complexity": {
+ "useLiteralKeys": "off"
+ },
+ "suspicious": {
+ "noExplicitAny": "error",
+ "noTsIgnore": "error",
+ "noControlCharactersInRegex": "off",
+ "noEmptyInterface": "off"
+ }
+ }
+ },
+ "formatter": {
+ "enabled": true,
+ "formatWithErrors": false,
+ "indentStyle": "tab",
+ "indentWidth": 3,
+ "lineWidth": 120
+ },
+ "files": {
+ "includes": ["src/**/*.ts", "test/**/*.ts", "vitest.config.ts", "!**/node_modules/**/*", "!**/dist/**/*"]
+ },
+ "overrides": [
+ {
+ "includes": ["vitest.config.ts"],
+ "linter": {
+ "rules": {
+ "style": {
+ "noDefaultExport": "off"
+ }
+ }
+ }
+ }
+ ]
+}
diff --git a/plugins/omo/components/ultragoal/hooks/hooks.json b/plugins/omo/components/ultragoal/hooks/hooks.json
new file mode 100644
index 00000000..f3e52fac
--- /dev/null
+++ b/plugins/omo/components/ultragoal/hooks/hooks.json
@@ -0,0 +1,16 @@
+{
+ "hooks": {
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit",
+ "timeout": 10,
+ "statusMessage": "checking ultragoal steering"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/omo/components/ultragoal/package.json b/plugins/omo/components/ultragoal/package.json
new file mode 100644
index 00000000..77782d91
--- /dev/null
+++ b/plugins/omo/components/ultragoal/package.json
@@ -0,0 +1,55 @@
+{
+ "name": "@code-yeongyu/codex-ultragoal",
+ "version": "0.1.0",
+ "description": "Codex plugin: durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.",
+ "type": "module",
+ "packageManager": "[email protected]",
+ "license": "MIT",
+ "homepage": "https://github.com/code-yeongyu/codex-ultragoal",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/code-yeongyu/codex-ultragoal.git"
+ },
+ "bugs": {
+ "url": "https://github.com/code-yeongyu/codex-ultragoal/issues"
+ },
+ "keywords": [
+ "codex",
+ "codex-plugin",
+ "ultragoal",
+ "goal-mode",
+ "orchestration",
+ "evidence",
+ "typescript"
+ ],
+ "bin": {
+ "omo": "./dist/cli.js"
+ },
+ "files": [
+ "dist",
+ "hooks",
+ "skills",
+ "LICENSE",
+ "NOTICE",
+ "README.md",
+ "CHANGELOG.md"
+ ],
+ "scripts": {
+ "build": "tsc -p tsconfig.build.json",
+ "test": "vitest --run",
+ "test:watch": "vitest",
+ "typecheck": "tsc --noEmit",
+ "lint": "biome check .",
+ "lint:fix": "biome check --write .",
+ "check": "tsc --noEmit && biome check . && npm run build"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.15",
+ "@types/node": "^25.7.0",
+ "typescript": "^6.0.3",
+ "vitest": "^4.1.5"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+}
diff --git a/plugins/omo/components/ultragoal/skills/ultragoal/.gitkeep b/plugins/omo/components/ultragoal/skills/ultragoal/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/plugins/omo/components/ultragoal/skills/ultragoal/SKILL.md b/plugins/omo/components/ultragoal/skills/ultragoal/SKILL.md
new file mode 100644
index 00000000..47e8784a
--- /dev/null
+++ b/plugins/omo/components/ultragoal/skills/ultragoal/SKILL.md
@@ -0,0 +1,157 @@
+---
+name: ultragoal
+description: Durable repo-native multi-goal plans with embedded success criteria and evidence audit.
+---
+
+## Role
+Expert goal orchestration agent. Plan multi-goal work that survives across turns and sessions.
+Use GPT-5.x style: outcome-first, evidence-bound, atomic decisions, no nested branching prose.
+
+## Goal
+Deliver every goal in `.omo/ultragoal/goals.json` end-to-end.
+Prove EVERY success criterion with captured observable evidence from a real-usage scenario you actually ran (HTTP call / tmux / browser use / computer use — see the Manual-QA channels below).
+TESTS ALONE NEVER PROVE DONE. A green test suite is supporting evidence, not completion proof.
+Audit each pass, fail, block, steering change, and checkpoint in `.omo/ultragoal/ledger.jsonl`.
+
+## Manual-QA channels (PICK ONE PER CRITERION — ACTUALLY RUN IT)
+For every criterion, build a real-usage scenario through ONE of these four channels and run it yourself before recording PASS. The full test suite being green is NEVER verification on its own.
+
+1. **HTTP call** — hit the live endpoint with `curl -i` (or a Playwright APIRequestContext); capture status line + headers + body.
+2. **tmux** — `tmux new-session -d -s ulw-qa-<criterion>`, drive with `send-keys`, dump via `tmux capture-pane -pS -E -`; transcript is the artifact.
+3. **Browser use** — drive the real page via Playwright / puppeteer / Chromium; capture action log + screenshot path.
+4. **Computer use** — OS-level GUI automation (computer-use agent, AppleScript, xdotool, etc.) against the running app; capture action log + screenshot.
+
+Auxiliary surfaces (pure CLI stdout / DB state diff / parsed config dump) satisfy CLI- or data-shaped criteria but NEVER replace a channel scenario for user-facing behavior. `--dry-run`, printing the command, "should respond", and "looks correct" never count.
+
+## Artifacts
+- `.omo/ultragoal/brief.md`: original brief and durable constraints.
+- `.omo/ultragoal/goals.json`: goals with embedded `successCriteria` per goal.
+- `.omo/ultragoal/ledger.jsonl`: append-only audit trail.
+- Read artifacts before resuming, steering, or checkpointing.
+- Never invent state outside `.omo/ultragoal` artifacts or `omo ultragoal status --json`.
+
+## Bootstrap
+Do all three steps before execution. No edits, goal tools, or checkpointing before bootstrap completes.
+
+### 1. Create goals from the brief
+Run one form:
+```sh
+omo ultragoal create-goals --brief "<brief>" --json
+omo ultragoal create-goals --brief-file <path> --json
+cat <brief> | omo ultragoal create-goals --from-stdin --json
+```
+Write state through the CLI path. Do not hand-edit state files.
+
+### 2. Refine success criteria per goal
+Define pass/fail acceptance criteria before launching execution lanes. Include the command, artifact, or manual check that will prove success.
+Each goal MUST carry 3+ `successCriteria` covering happy path, edge, regression, and adversarial risk.
+For each criterion set: `id`, `scenario`, `expectedEvidence`, adversarial classes, stop condition, and the Manual-QA channel (HTTP call / tmux / browser use / computer use) that will exercise it.
+Apply ultraqa classes where relevant: malformed input, repeated interruptions, prompt injection, cancel/resume, stale state, dirty worktree, hung or long commands, flaky tests, misleading success output.
+Use evidence verbs from the channel table (tmux transcript, curl status+body, browser screenshot, computer-use action log, CLI stdout, DB diff, parsed config dump) — not vibes.
+"Tests pass" is supporting signal, NEVER completion proof. Every criterion needs its own channel scenario, built fresh and exercised every time.
+Record manual QA notes when behavior is user-visible.
+Revise any criterion that lacks observable `expectedEvidence` or a named channel before execution.
+
+### 3. Inspect state
+Run `omo ultragoal status --json`.
+Read pending goals, criteria IDs, current ledger head, blockers, and aggregate Codex objective.
+
+## Execution Loop
+Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures at 3.
+
+### Acquire Next Goal
+1. Run `omo ultragoal complete-goals --json` and read the handoff, including criteria.
+2. Call `get_goal` and inspect active Codex state.
+3. Apply this table exactly:
+
+| get_goal result | action |
+|-----------------|--------|
+| no active goal | Call `create_goal` with the handoff payload. |
+| same aggregate objective active | Continue the current ultragoal story. |
+| different goal active | STOP. Checkpoint blocked and surface the conflict. |
+4. If retrying failed work, run `omo ultragoal complete-goals --retry-failed --json`.
+5. Never create a second Codex goal for the same aggregate objective.
+
+### Per-Criterion Cycle
+1. PLAN: read `criterion.scenario`, `criterion.expectedEvidence`, prior ledger entries, and safety bounds.
+2. Register atomic todos: `path: <action> for <criterion> - verify by <check>`.
+3. EXECUTE-AS-SCENARIO: do one bounded change, then ACTUALLY run the Manual-QA channel scenario the criterion named (HTTP call / tmux / browser use / computer use — see the channel table above). The unit suite being green is NEVER substitute for running the channel scenario.
+4. CAPTURE: collect the observable artifact path: transcript, stdout, screenshot, assertion, status+body, diff, or parsed dump.
+5. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 3 spawned BEFORE recording — server PIDs (`kill`, verify `kill -0` fails), `tmux` sessions (`tmux kill-session -t ulw-qa-<criterion>`; confirm `tmux ls`), browser / Playwright contexts (`.close()`), containers (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env vars. Embed a one-line cleanup receipt in the evidence string, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo; rm -rf /tmp/ulw.aB12cD`. Missing receipt → record BLOCKED, not PASS.
+6. RECORD exactly one result:
+ - PASS: `omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status pass --evidence "<observable> | <cleanup receipt>" --json`
+ - FAIL: `omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status fail --evidence "<observable> | <cleanup receipt>" --notes "<diagnosis>" --json`
+ - BLOCKED: `omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status blocked --evidence "<observable>" --notes "<safety/blocker/leftover-state>" --json`
+7. If actual does not match expected, diagnose, fix minimally, and rerun the SAME criterion (including a fresh cleanup).
+8. After 3 same-criterion failures, exit the goal with diagnosis.
+9. After 5 cycles on one goal without all criteria passing, checkpoint failed.
+10. Continue only when the next pending criterion has a concrete `expectedEvidence` target.
+
+### Goal Completion
+1. Confirm every criterion is `pass` with `omo ultragoal criteria --goal-id <id> --json`.
+2. Call `get_goal` for a fresh snapshot.
+3. Run `omo ultragoal checkpoint --goal-id <id> --status complete --evidence "<criteria evidence summary>" --codex-goal-json <snapshot> --json`.
+4. If blocked or failed, checkpoint with `--status blocked` or `--status failed` and include diagnosis evidence.
+5. If this is the final goal, run the final quality gate first and pass `--quality-gate-json`.
+
+## Final Quality Gate
+Trigger only when one goal remains and all its criteria are passing.
+1. Run targeted verification for changed behavior.
+2. Run `ai-slop-cleaner` on changed files. If no relevant edits exist, record a passed no-op cleaner report.
+3. Rerun verification after cleanup.
+4. Run `$code-review`.
+5. Clean review means `codeReview.recommendation == "APPROVE"` and `codeReview.architectStatus == "CLEAR"`.
+6. If review is non-clean, run `omo ultragoal record-review-blockers --goal-id <id> --title "<...>" --objective "<...>" --evidence "<review findings>" --codex-goal-json <snapshot> --json`.
+7. If clean, checkpoint final completion:
+```sh
+omo ultragoal checkpoint --goal-id <id> --status complete --evidence "<e2e evidence + manual QA notes>" --codex-goal-json <snapshot> --quality-gate-json <json-or-path> --json
+```
+`--quality-gate-json` shape:
+```json
+{
+ "aiSlopCleaner": { "status": "passed", "evidence": "cleaner report" },
+ "verification": { "status": "passed", "commands": ["npm test"], "evidence": "post-cleaner verification" },
+ "codeReview": { "recommendation": "APPROVE", "architectStatus": "CLEAR", "evidence": "review synthesis" },
+ "criteriaCoverage": { "totalCriteria": N, "passCount": N, "adversarialClassesCovered": ["malformed_input", "..."] }
+}
+```
+
+## Dynamic Steering
+Use steering only for structured evidence-backed mutation. Reject natural-language steering requests.
+
+| Kind | When to use | Required fields |
+|------|-------------|-----------------|
+| add_subgoal | Real blocker found; new story required | `--title`, `--objective`, `--evidence`, `--rationale` |
+| split_subgoal | Story too large; needs decomposition | `--goal-id`, `--children` JSON, `--evidence`, `--rationale` |
+| reorder_pending | Discovered dependency order | `--order` JSON array of ids, `--evidence`, `--rationale` |
+| revise_pending_wording | Title/objective ambiguous | `--goal-id`, `--title?`, `--objective?`, `--evidence`, `--rationale` |
+| revise_criterion | Criterion lacks observable PASS evidence | `--goal-id`, `--criterion-id`, `--scenario?`, `--expected-evidence?`, `--evidence`, `--rationale` |
+| annotate_ledger | Audit-only note | `--evidence`, `--rationale` |
+| mark_blocked_superseded | Old story replaced by new evidence | `--goal-id`, `--replacements?`, `--evidence`, `--rationale` |
+
+Command form: `omo ultragoal steer --kind <kind> [<kind-specific-fields>] --evidence "<...>" --rationale "<...>" --json`.
+Structured prompt directives accepted: `OMO_ULTRAGOAL_STEER: { ... }`, `omo.ultragoal.steer: {...}`, `omo ultragoal steer: {...}`.
+
+## Constraints
+1. NEVER call `update_goal` mid-aggregate; only on final story after the quality gate passes.
+2. NEVER call `create_goal` when `get_goal` shows a different active goal.
+3. NEVER mark `criterion.status == "pass"` without captured observable evidence in `record-evidence`.
+4. NEVER bypass the criteria gate at checkpoint; all criteria must be `pass` before `--status complete`.
+5. Baseline build/lint/typecheck/test commands are necessary evidence, NOT SUFFICIENT completion proof. Criteria coverage with observable evidence is the gate.
+6. Treat `.omo/ultragoal/ledger.jsonl` as the durable audit trail; checkpoint after every success or failure.
+7. Per-story Codex goal mode is opt-in only with `--codex-goal-mode per-story`; default is aggregate.
+8. Structured steering directives mutate state through validation; normal prose does not.
+9. Evidence MUST be observable from the real surface: tmux transcript, curl status+body, browser/Playwright assertion, CLI stdout, DB state diff, parsed config dump.
+10. Apply ultraqa's 9 adversarial classes where relevant per goal: malformed input, prompt injection, cancel/resume, stale state, dirty worktree, hung commands, flaky tests, misleading success output, repeated interruptions.
+11. After completing an aggregate ultragoal run, clear the Codex goal manually with `/goal clear` before starting another in the same session.
+12. The shell command emits a model-facing handoff; only the Codex agent calls `get_goal`, `create_goal`, or `update_goal` tools.
+13. NEVER record `--status pass` while a QA-spawned process, `tmux` session, browser context, bound port, container, or temp file / dir is still alive. The evidence string MUST include the cleanup receipt. Leftover runtime state = BLOCKED, not PASS.
+
+## Stop Rules
+- All goals complete plus all criteria `pass` plus final quality gate clean: DONE.
+- 3x same criterion failure: checkpoint failed, surface diagnosis.
+- 5 cycles on one goal without all-pass: checkpoint failed, surface.
+- Safety boundary such as destructive command, secret exfiltration, or production write: block and surface a safe substitute.
+- Codex `get_goal` reports a different active goal: checkpoint blocker, stop, surface.
+- Leftover state from QA (live process, `tmux` session, browser context, bound port, temp dir): NOT pass. Clean up, append the receipt, then continue.
+- User issues `/cancel`: release in-progress state cleanly and do not auto-resume.
diff --git a/plugins/omo/components/ultragoal/src/.gitkeep b/plugins/omo/components/ultragoal/src/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/plugins/omo/components/ultragoal/src/checkpoint.ts b/plugins/omo/components/ultragoal/src/checkpoint.ts
new file mode 100644
index 00000000..151a4607
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/checkpoint.ts
@@ -0,0 +1,155 @@
+// biome-ignore-all format: keep checkpoint orchestration below the pure LOC budget.
+import { existsSync } from "node:fs";
+import { readFile } from "node:fs/promises";
+import { resolve } from "node:path";
+
+import { formatCodexGoalReconciliation, readCodexGoalSnapshotInput, reconcileCodexGoalSnapshot } from "./codex-goal-snapshot.js";
+import { requireAllCriteriaPass } from "./evidence.js";
+import { codexGoalMode, compatibleCodexObjectives, expectedCodexObjective, isFinalRunCompletionCandidate } from "./goal-status.js";
+import { ultragoalBriefPath } from "./paths.js";
+import { appendLedger, readUltragoalPlan, withUltragoalMutationLock, writePlan } from "./plan-io.js";
+import { classifyExternalAuthorizationBlocker, clearGoalBlockerFields, sameBlockerOccurrences, validateQualityGate } from "./quality-gate.js";
+import type { UltragoalAggregateCompletion, UltragoalItem, UltragoalLedgerEntry, UltragoalPlan, UltragoalQualityGate } from "./types.js";
+import { iso, ULTRAGOAL_DIR, ULTRAGOAL_GOALS, ULTRAGOAL_LEDGER, UltragoalError } from "./types.js";
+
+export interface CheckpointUltragoalArgs { readonly goalId: string; readonly status: "complete" | "failed" | "blocked"; readonly evidence: string; readonly codexGoalJson?: string; readonly qualityGateJson?: string }
+export interface CheckpointUltragoalResult { readonly plan: UltragoalPlan; readonly goal: UltragoalItem; readonly ledgerEntry: UltragoalLedgerEntry; readonly aggregateCompletion?: UltragoalAggregateCompletion }
+
+function ultragoalFail(message: string, code: string): never { throw new UltragoalError(message, code); }
+function normalizeObjective(value: string): string { return value.replace(/\s+/g, " ").trim(); }
+function nonEmptyEvidence(value: string): string { const trimmed = value.trim(); return trimmed || ultragoalFail("Evidence must be a non-empty string.", "ultragoal_evidence_required"); }
+function findGoal(plan: UltragoalPlan, goalId: string): UltragoalItem { const goal = plan.goals.find((candidate) => candidate.id === goalId); return goal ?? ultragoalFail(`Unknown ultragoal id: ${goalId}.`, "ultragoal_goal_not_found"); }
+
+function textMentionsUltragoalPlanArtifact(value: string | undefined): boolean {
+ const normalized = (value ?? "").toLowerCase();
+ return normalized.includes(ULTRAGOAL_DIR.toLowerCase()) || normalized.includes(ULTRAGOAL_GOALS.toLowerCase()) || normalized.includes(ULTRAGOAL_LEDGER.toLowerCase());
+}
+function textMentionsGoalId(value: string | undefined, goalId: string): boolean { return (value ?? "").toLowerCase().includes(goalId.toLowerCase()); }
+function textHasCompletionValidationEvidence(value: string | undefined): boolean {
+ const normalized = (value ?? "").toLowerCase();
+ const done = /\b(?:planned work|implementation|deliverables?|scope|task|work)\b/.test(normalized) && /\b(?:done|complete|completed|finished|shipped)\b/.test(normalized);
+ const verified = /\b(?:validation|verification|tests?|build|lint|review|quality gate|code-review)\b/.test(normalized) && /\b(?:passed|complete|completed|clean|green|approve|approved|clear)\b/.test(normalized);
+ return done && verified;
+}
+
+async function snapshotObjectiveMapsToUltragoalPlan(repoRoot: string, snapshotObjective: string): Promise<boolean> {
+ const actual = normalizeObjective(snapshotObjective).toLowerCase();
+ if (textMentionsUltragoalPlanArtifact(actual)) return true;
+ if (actual.length < 24 || !existsSync(ultragoalBriefPath(repoRoot))) return false;
+ try {
+ const brief = normalizeObjective(await readFile(ultragoalBriefPath(repoRoot), "utf8")).toLowerCase();
+ return brief.length >= 24 && (brief.includes(actual) || actual.includes(brief));
+ } catch (error) {
+ if (error instanceof Error) return false;
+ throw error;
+ }
+}
+
+async function canReconcileCompletedTaskScopedAggregateSnapshot(repoRoot: string, plan: UltragoalPlan, goal: UltragoalItem, snapshotObjective: string, evidence: string): Promise<boolean> {
+ if (codexGoalMode(plan) !== "aggregate") return false;
+ if (goal.status !== "in_progress" || plan.activeGoalId !== goal.id) return false;
+ if (isFinalRunCompletionCandidate(plan, goal)) return snapshotObjectiveMapsToUltragoalPlan(repoRoot, snapshotObjective);
+ if (!textMentionsUltragoalPlanArtifact(evidence) || !textMentionsGoalId(evidence, goal.id)) return false;
+ if (!textHasCompletionValidationEvidence(evidence)) return false;
+ return snapshotObjectiveMapsToUltragoalPlan(repoRoot, snapshotObjective);
+}
+
+function buildCompletedLegacyGoalRemediation(goal: UltragoalItem): string {
+ return [
+ "If get_goal returns a different completed legacy/thread objective, do not repeat --status complete in this thread.",
+ `Record a non-terminal blocker with: omo ultragoal checkpoint --goal-id ${goal.id} --status blocked --evidence "<completed legacy Codex goal blocks create_goal in this thread>" --codex-goal-json "<different completed get_goal JSON or path>".`,
+ "Then continue only from a Codex goal context with no active/completed conflicting goal, in the same repo/worktree, and create the intended goal there.",
+ ].join(" ");
+}
+
+function buildTaskScopedAggregateReconciliationHint(goal: UltragoalItem, final: boolean): string {
+ if (final) {
+ return ` Final task-scoped aggregate reconciliation requires the checkpoint goal to be the active in-progress final OMO goal and the completed get_goal objective to map to the ultragoal brief or artifact. ${buildCompletedLegacyGoalRemediation(goal)}`;
+ }
+ return ` Completed task-scoped aggregate reconciliation requires the checkpoint goal to be the active in-progress OMO goal, evidence that names that active OMO goal id, names .omo/ultragoal/goals.json or ledger.jsonl, includes completed implementation plus validation/review evidence, and a get_goal objective that maps to the ultragoal brief/artifact. ${buildCompletedLegacyGoalRemediation(goal)}`;
+}
+
+async function readJsonInput(raw: string | undefined, repoRoot: string): Promise<unknown> {
+ if (raw === undefined || raw.trim() === "") return undefined;
+ const trimmed = raw.trim();
+ try { return JSON.parse(trimmed); } catch (error) { if (!(error instanceof SyntaxError)) throw error; }
+ const path = resolve(repoRoot, trimmed);
+ if (!existsSync(path)) return ultragoalFail("Quality gate JSON is neither valid JSON nor a readable path.", "ultragoal_json_input_invalid");
+ try { return JSON.parse(await readFile(path, "utf8")); } catch (error) { return ultragoalFail(`Quality gate path does not contain valid JSON${error instanceof Error ? `: ${error.message}` : "."}`, "ultragoal_json_input_invalid"); }
+}
+
+function makeAggregateCompletion(now: string, evidence: string, codexGoal: unknown): UltragoalAggregateCompletion {
+ return { status: "complete", completedAt: now, evidence, codexGoal };
+}
+
+function applyBlockedOrFailed(goal: UltragoalItem, plan: UltragoalPlan, status: "failed" | "blocked", evidence: string, now: string): void {
+ const signature = classifyExternalAuthorizationBlocker(evidence);
+ const occurrences = signature === null ? 0 : sameBlockerOccurrences(plan, signature) + 1;
+ const needsDecision = signature !== null && occurrences >= 3;
+ goal.status = needsDecision ? "needs_user_decision" : status;
+ goal.updatedAt = now;
+ if (status === "failed" || needsDecision) { goal.failedAt = now; goal.failureReason = evidence; }
+ if (status === "blocked" || needsDecision) goal.blockedReason = evidence;
+ if (signature !== null) { goal.blockerSignature = signature; goal.blockerOccurrenceCount = occurrences; goal.requiredExternalDecision = `Resolve external authorization: ${signature}`; }
+ if (needsDecision) goal.nonRetriable = true;
+ if (plan.activeGoalId === goal.id) delete plan.activeGoalId;
+}
+
+function ledgerKind(status: CheckpointUltragoalArgs["status"], goal: UltragoalItem, aggregateCompletion: UltragoalAggregateCompletion | undefined): UltragoalLedgerEntry["kind"] {
+ if (aggregateCompletion !== undefined) return "aggregate_completed";
+ if (status === "complete") return "goal_completed";
+ if (goal.status === "needs_user_decision") return "goal_needs_user_decision";
+ return status === "blocked" ? "goal_blocked" : "goal_failed";
+}
+
+function buildLedger(now: string, args: CheckpointUltragoalArgs, goal: UltragoalItem, qualityGate: UltragoalQualityGate | undefined, codexGoal: unknown, aggregateCompletion: UltragoalAggregateCompletion | undefined): UltragoalLedgerEntry {
+ const entry: UltragoalLedgerEntry = { at: now, kind: ledgerKind(args.status, goal, aggregateCompletion), goalId: goal.id, status: goal.status, evidence: args.evidence };
+ if (codexGoal !== undefined) entry.codexGoal = codexGoal;
+ if (qualityGate !== undefined) entry.qualityGate = qualityGate;
+ if (goal.blockerSignature !== undefined) entry.blockerSignature = goal.blockerSignature;
+ if (goal.blockerOccurrenceCount !== undefined) entry.blockerOccurrenceCount = goal.blockerOccurrenceCount;
+ if (goal.requiredExternalDecision !== undefined) entry.requiredExternalDecision = goal.requiredExternalDecision;
+ return entry;
+}
+
+export async function checkpointUltragoal(repoRoot: string, args: CheckpointUltragoalArgs): Promise<CheckpointUltragoalResult> {
+ return withUltragoalMutationLock(repoRoot, async () => {
+ const plan = await readUltragoalPlan(repoRoot);
+ const goal = findGoal(plan, args.goalId);
+ if (args.status === "complete") requireAllCriteriaPass(goal);
+ const evidence = nonEmptyEvidence(args.evidence);
+ const now = iso();
+ let aggregateCompletion: UltragoalAggregateCompletion | undefined;
+ let qualityGate: UltragoalQualityGate | undefined;
+ let codexGoal: unknown;
+ if (args.status === "complete") {
+ const aggregate = codexGoalMode(plan) === "aggregate";
+ const final = isFinalRunCompletionCandidate(plan, goal);
+ const snapshot = await readCodexGoalSnapshotInput(args.codexGoalJson, repoRoot);
+ const reconciliation = reconcileCodexGoalSnapshot(snapshot, { expectedObjective: expectedCodexObjective(plan, goal), ...(aggregate ? { acceptedObjectives: compatibleCodexObjectives(plan) } : {}), allowedStatuses: aggregate ? (final ? ["complete"] : ["active"]) : ["complete"], requireSnapshot: true, requireComplete: !aggregate || final });
+ codexGoal = reconciliation.snapshot.raw;
+ if (!reconciliation.ok) {
+ const objective = snapshot?.objective;
+ const taskScoped = snapshot?.available === true && snapshot.status === "complete" && objective !== undefined && normalizeObjective(objective) !== normalizeObjective(expectedCodexObjective(plan, goal)) && await canReconcileCompletedTaskScopedAggregateSnapshot(repoRoot, plan, goal, objective, evidence);
+ if (!taskScoped) throw new UltragoalError(`${formatCodexGoalReconciliation(reconciliation)}${aggregate && snapshot?.status === "complete" && objective !== undefined ? buildTaskScopedAggregateReconciliationHint(goal, final) : ""}`, "ultragoal_codex_snapshot_mismatch");
+ aggregateCompletion = makeAggregateCompletion(now, evidence, codexGoal);
+ }
+ if (final) aggregateCompletion = makeAggregateCompletion(now, evidence, codexGoal);
+ if (final || aggregateCompletion !== undefined) qualityGate = validateQualityGate(await readJsonInput(args.qualityGateJson, repoRoot));
+ goal.status = "complete";
+ goal.completedAt = now;
+ goal.evidence = evidence;
+ delete goal.failedAt;
+ delete goal.failureReason;
+ clearGoalBlockerFields(goal);
+ if (plan.activeGoalId === goal.id) delete plan.activeGoalId;
+ } else applyBlockedOrFailed(goal, plan, args.status, evidence, now);
+ goal.updatedAt = now;
+ if (aggregateCompletion !== undefined) plan.aggregateCompletion = aggregateCompletion;
+ plan.updatedAt = now;
+ await writePlan(repoRoot, plan);
+ const ledgerEntry = buildLedger(now, args, goal, qualityGate, codexGoal, aggregateCompletion);
+ await appendLedger(repoRoot, ledgerEntry);
+ return aggregateCompletion === undefined ? { plan, goal, ledgerEntry } : { plan, goal, ledgerEntry, aggregateCompletion };
+ });
+}
diff --git a/plugins/omo/components/ultragoal/src/cli-arg-parser.ts b/plugins/omo/components/ultragoal/src/cli-arg-parser.ts
new file mode 100644
index 00000000..e9028f4c
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/cli-arg-parser.ts
@@ -0,0 +1,95 @@
+// biome-ignore-all format: keep this module under the mandated pure LOC budget.
+import { readFile } from "node:fs/promises";
+
+import { UltragoalError } from "./types.js";
+
+type RecordEvidenceCliArgs = { readonly goalId: string; readonly criterionId: string; readonly status: "pass" | "fail" | "blocked"; readonly evidence: string; readonly notes?: string };
+
+const VALUE_FLAGS = new Set("--brief --brief-file --codex-goal-mode --goal --goal-id --criterion-id --status --evidence --notes --codex-goal-json --quality-gate-json --kind --rationale --title --objective --target-goal-id --source --after-json --directive-json --directive-file --idempotency-key".split(" "));
+const SUBCOMMANDS = new Set("create-goals status complete-goals criteria record-evidence checkpoint steer add-goal record-review-blockers".split(" "));
+
+export function hasFlag(argv: readonly string[], flag: string): boolean { return argv.includes(flag); }
+
+export function readValue(argv: readonly string[], flag: string): string | undefined {
+ const index = argv.indexOf(flag);
+ if (index >= 0) {
+ const next = argv[index + 1];
+ return next === undefined || next.startsWith("--") ? undefined : next;
+ }
+ const prefix = `${flag}=`;
+ return argv.find((arg) => arg.startsWith(prefix))?.slice(prefix.length);
+}
+
+export function readRepeated(argv: readonly string[], flag: string): string[] {
+ const values: string[] = [];
+ const prefix = `${flag}=`;
+ for (let index = 0; index < argv.length; index += 1) {
+ const arg = argv[index];
+ const next = argv[index + 1];
+ if (arg === flag && next !== undefined && !next.startsWith("--")) { values.push(next); index += 1; }
+ else if (arg?.startsWith(prefix)) values.push(arg.slice(prefix.length));
+ }
+ return values;
+}
+
+export function parseGoalArg(argv: readonly string[]): string | undefined { return readValue(argv, "--goal-id") ?? readValue(argv, "--goal"); }
+
+export async function readStdin(): Promise<string> {
+ const chunks: Buffer[] = [];
+ for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
+ return Buffer.concat(chunks).toString("utf8");
+}
+
+export function positionalText(argv: readonly string[]): string {
+ const words: string[] = [];
+ for (let index = SUBCOMMANDS.has(argv[0] ?? "") ? 1 : 0; index < argv.length; index += 1) {
+ const arg = argv[index];
+ if (arg === undefined) continue;
+ if (VALUE_FLAGS.has(arg)) { index += 1; continue; }
+ if (arg.startsWith("--")) continue;
+ words.push(arg);
+ }
+ return words.join(" ").trim();
+}
+
+function looksLikeJson(value: string): boolean { const trimmed = value.trim(); return trimmed.startsWith("{") || trimmed.startsWith("["); }
+
+export async function readJsonInput(value: string | undefined): Promise<unknown | undefined> {
+ if (value === undefined) return undefined;
+ try { return JSON.parse(looksLikeJson(value) ? value : await readFile(value, "utf8")); }
+ catch (error) {
+ const message = error instanceof Error ? error.message : "unknown error";
+ throw new UltragoalError(`Invalid JSON input: ${message}`, "ULTRAGOAL_JSON_INPUT_INVALID", { cause: error });
+ }
+}
+
+export async function parseCodexGoalJson(value: string | undefined): Promise<string | undefined> {
+ if (value === undefined) return undefined;
+ const raw = looksLikeJson(value) ? value : await readFile(value, "utf8");
+ try { JSON.parse(raw); return raw; }
+ catch (error) {
+ const message = error instanceof Error ? error.message : "unknown error";
+ throw new UltragoalError(`Invalid --codex-goal-json: ${message}`, "ULTRAGOAL_CODEX_GOAL_JSON_INVALID", { cause: error });
+ }
+}
+
+function required(argv: readonly string[], flag: string, code: string): string {
+ const value = readValue(argv, flag)?.trim();
+ if (value) return value;
+ throw new UltragoalError(`Missing ${flag}.`, code, { details: { flag } });
+}
+
+function evidenceStatus(value: string): RecordEvidenceCliArgs["status"] {
+ switch (value) {
+ case "pass": return "pass";
+ case "fail": return "fail";
+ case "blocked": return "blocked";
+ default: throw new UltragoalError("Invalid --status; expected pass, fail, or blocked.", "ULTRAGOAL_EVIDENCE_STATUS_INVALID", { details: { status: value } });
+ }
+}
+
+export function parseRecordEvidenceArgs(argv: readonly string[]): RecordEvidenceCliArgs {
+ const result = { goalId: required(argv, "--goal-id", "ULTRAGOAL_GOAL_ID_REQUIRED"), criterionId: required(argv, "--criterion-id", "ULTRAGOAL_CRITERION_ID_REQUIRED"), status: evidenceStatus(required(argv, "--status", "ULTRAGOAL_EVIDENCE_STATUS_REQUIRED")), evidence: required(argv, "--evidence", "ULTRAGOAL_EVIDENCE_REQUIRED") };
+ const notes = readValue(argv, "--notes")?.trim();
+ return notes ? { ...result, notes } : result;
+}
diff --git a/plugins/omo/components/ultragoal/src/cli-commands.ts b/plugins/omo/components/ultragoal/src/cli-commands.ts
new file mode 100644
index 00000000..c53ef458
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/cli-commands.ts
@@ -0,0 +1,142 @@
+// biome-ignore-all format: keep cli-commands dispatcher under the 200 pure LOC budget.
+import { readFile } from "node:fs/promises";
+import { checkpointUltragoal } from "./checkpoint.js";
+import { hasFlag, parseCodexGoalJson, parseRecordEvidenceArgs, positionalText, readStdin, readValue } from "./cli-arg-parser.js";
+import { blockedDecisionHandoff, normalizeCodexGoalMode, printJson, printStatus, ULTRAGOAL_HELP } from "./cli-output.js";
+import { parseSteeringProposal, printSteerResult } from "./cli-steering.js";
+import { buildCodexGoalInstruction } from "./codex-goal-instruction.js";
+import { recordEvidence } from "./evidence.js";
+import { addUltragoalGoal, createUltragoalPlan, startNextUltragoal, summarizeUltragoalPlan } from "./plan-crud.js";
+import { readUltragoalPlan } from "./plan-io.js";
+import { recordFinalReviewBlockers } from "./review-blockers.js";
+import { steerUltragoal } from "./steering.js";
+import type { UltragoalItem } from "./types.js";
+import { UltragoalError } from "./types.js";
+
+type CheckpointStatus = "complete" | "failed" | "blocked";
+
+export async function ultragoalCommand(argv: readonly string[]): Promise<number> {
+ const command = argv[0] ?? "help";
+ const rest = argv.slice(1);
+ const repoRoot = process.cwd();
+ const json = hasFlag(rest, "--json");
+ try {
+ switch (command) {
+ case "help": case "--help": case "-h": process.stdout.write(`${ULTRAGOAL_HELP}\n`); return 0;
+ case "create-goals": return await createGoals(repoRoot, rest, json);
+ case "status": return await status(repoRoot, json);
+ case "complete-goals": return await completeGoals(repoRoot, rest, json);
+ case "checkpoint": return await checkpoint(repoRoot, rest, json);
+ case "steer": return await steer(repoRoot, rest, json);
+ case "add-goal": return await addGoal(repoRoot, rest, json);
+ case "criteria": return await criteria(repoRoot, rest, json);
+ case "record-evidence": return await captureEvidence(repoRoot, rest, json);
+ case "record-review-blockers": return await reviewBlockers(repoRoot, rest, json);
+ default: process.stdout.write(`${ULTRAGOAL_HELP}\n`); return 1;
+ }
+ } catch (error) {
+ if (error instanceof UltragoalError) process.stderr.write(`[ultragoal] ${error.message}\n`);
+ else if (error instanceof Error) process.stderr.write(`[ultragoal] unexpected: ${error.message}\n`);
+ else process.stderr.write("[ultragoal] unknown error\n");
+ return 1;
+ }
+}
+
+async function createGoals(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {
+ const briefFile = readValue(argv, "--brief-file");
+ const brief = readValue(argv, "--brief") ?? (briefFile === undefined ? undefined : await readFile(briefFile, "utf8")) ?? (hasFlag(argv, "--from-stdin") ? await readStdin() : undefined) ?? positionalText(argv);
+ if (!brief.trim()) throw new UltragoalError("Missing brief text. Pass --brief, --brief-file, --from-stdin, or positional text.", "ULTRAGOAL_BRIEF_REQUIRED");
+ const plan = await createUltragoalPlan(repoRoot, { brief, codexGoalMode: normalizeCodexGoalMode(readValue(argv, "--codex-goal-mode")), force: hasFlag(argv, "--force") });
+ if (json) printJson({ ok: true, plan, summary: summarizeUltragoalPlan(plan) });
+ else process.stdout.write(`ultragoal plan created: ${plan.goals.length} goal(s)\nbrief: ${plan.briefPath}\ngoals: ${plan.goalsPath}\nledger: ${plan.ledgerPath}\n`);
+ return 0;
+}
+
+async function status(repoRoot: string, json: boolean): Promise<number> {
+ const plan = await readUltragoalPlan(repoRoot);
+ if (json) printJson({ ok: true, plan, summary: summarizeUltragoalPlan(plan) });
+ else printStatus(plan);
+ return 0;
+}
+
+async function completeGoals(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {
+ const result = await startNextUltragoal(repoRoot, { retryFailed: hasFlag(argv, "--retry-failed") });
+ if ("done" in result) {
+ const handoff = blockedDecisionHandoff(result.plan);
+ if (json) printJson({ ok: true, done: true, blocked: handoff.length > 0, handoff, summary: summarizeUltragoalPlan(result.plan), plan: result.plan });
+ else process.stdout.write(`${handoff || "ultragoal: all goals complete"}\n`);
+ return 0;
+ }
+ const instruction = buildCodexGoalInstruction({ plan: result.plan, goal: result.goal });
+ if (json) printJson({ ok: true, resumed: result.resumed, goal: result.goal, instruction, plan: result.plan });
+ else process.stdout.write(`${instruction.text}\n`);
+ return 0;
+}
+
+async function checkpoint(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {
+ const goalId = required(argv, "--goal-id");
+ const statusValue = checkpointStatus(required(argv, "--status"));
+ const evidence = required(argv, "--evidence");
+ const codexGoalJson = await parseCodexGoalJson(required(argv, "--codex-goal-json"));
+ if (codexGoalJson === undefined) throw new UltragoalError("Missing --codex-goal-json.", "ULTRAGOAL_CODEX_GOAL_JSON_REQUIRED");
+ const qualityGateJson = readValue(argv, "--quality-gate-json");
+ const result = await checkpointUltragoal(repoRoot, qualityGateJson === undefined ? { goalId, status: statusValue, evidence, codexGoalJson } : { goalId, status: statusValue, evidence, codexGoalJson, qualityGateJson });
+ if (json) printJson({ ok: true, ...result, summary: summarizeUltragoalPlan(result.plan) });
+ else process.stdout.write(`ultragoal checkpoint: ${result.goal.id} -> ${result.goal.status}\n`);
+ return 0;
+}
+
+async function steer(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {
+ const proposal = await parseSteeringProposal(argv);
+ const result = await steerUltragoal(repoRoot, proposal);
+ printSteerResult(result, json);
+ return result.accepted ? 0 : 1;
+}
+
+async function addGoal(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {
+ const result = await addUltragoalGoal(repoRoot, { title: required(argv, "--title"), objective: required(argv, "--objective") });
+ if (json) printJson({ ok: true, plan: result.plan, goal: result.goal, summary: summarizeUltragoalPlan(result.plan) });
+ else { process.stdout.write(`ultragoal added goal: ${result.goal.id}\n`); printStatus(result.plan); }
+ return 0;
+}
+
+async function criteria(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {
+ const goalId = required(argv, "--goal-id");
+ const goal = findGoal(await readUltragoalPlan(repoRoot), goalId);
+ if (json) printJson({ ok: true, goalId: goal.id, criteria: goal.successCriteria });
+ else process.stdout.write(`criteria for ${goal.id}:\n${goal.successCriteria.map((c) => `- ${c.id} [${c.status}] (${c.userModel}) ${c.scenario} evidence: ${c.capturedEvidence ?? "pending"}`).join("\n")}\n`);
+ return 0;
+}
+
+async function captureEvidence(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {
+ const result = await recordEvidence(repoRoot, parseRecordEvidenceArgs(argv));
+ if (json) printJson({ ok: true, ...result, summary: summarizeUltragoalPlan(result.plan) });
+ else process.stdout.write(`ultragoal evidence recorded: ${result.goal.id}/${result.criterion.id} -> ${result.criterion.status}\n`);
+ return 0;
+}
+
+async function reviewBlockers(repoRoot: string, argv: readonly string[], json: boolean): Promise<number> {
+ const codexGoalJson = await parseCodexGoalJson(required(argv, "--codex-goal-json"));
+ if (codexGoalJson === undefined) throw new UltragoalError("Missing --codex-goal-json.", "ULTRAGOAL_CODEX_GOAL_JSON_REQUIRED");
+ const result = await recordFinalReviewBlockers(repoRoot, { goalId: required(argv, "--goal-id"), title: required(argv, "--title"), objective: required(argv, "--objective"), evidence: required(argv, "--evidence"), codexGoalJson });
+ if (json) printJson({ ok: true, plan: result.plan, blockedGoal: result.blockedGoal, goal: result.newGoal, ledgerEntries: result.ledgerEntries, summary: summarizeUltragoalPlan(result.plan) });
+ else process.stdout.write(`ultragoal final review blockers recorded: ${result.blockedGoal.id} -> review_blocked; added ${result.newGoal.id}\n`);
+ return 0;
+}
+
+function required(argv: readonly string[], flag: string): string {
+ const value = readValue(argv, flag)?.trim();
+ if (value) return value;
+ throw new UltragoalError(`Missing ${flag}.`, "ULTRAGOAL_ARGUMENT_MISSING", { details: { flag } });
+}
+
+function checkpointStatus(value: string): CheckpointStatus {
+ if (value === "complete" || value === "failed" || value === "blocked") return value;
+ throw new UltragoalError("Missing or invalid --status; expected complete, failed, or blocked.", "ULTRAGOAL_STATUS_INVALID", { details: { status: value } });
+}
+
+function findGoal(plan: { readonly goals: readonly UltragoalItem[] }, goalId: string): UltragoalItem {
+ const goal = plan.goals.find((candidate) => candidate.id === goalId);
+ if (goal !== undefined) return goal;
+ throw new UltragoalError(`Unknown ultragoal id: ${goalId}.`, "ULTRAGOAL_GOAL_NOT_FOUND", { details: { goalId } });
+}
diff --git a/plugins/omo/components/ultragoal/src/cli-output.ts b/plugins/omo/components/ultragoal/src/cli-output.ts
new file mode 100644
index 00000000..ef7ed253
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/cli-output.ts
@@ -0,0 +1,61 @@
+import type { UltragoalCodexGoalMode, UltragoalItem, UltragoalPlan } from "./types.js";
+import { UltragoalError } from "./types.js";
+
+export const ULTRAGOAL_HELP = `Usage:
+ omo ultragoal create-goals --brief "..." [--brief-file <path>] [--from-stdin] [--codex-goal-mode aggregate|per_story] [--force] [--json]
+ omo ultragoal status [--json]
+ omo ultragoal complete-goals [--retry-failed] [--json]
+ omo ultragoal criteria --goal-id <id> [--json]
+ omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status pass|fail|blocked --evidence "..." [--notes "..."] [--json]
+ omo ultragoal checkpoint --goal-id <id> --status complete|failed|blocked --evidence "..." --codex-goal-json <...> [--quality-gate-json <...>] [--json]
+ omo ultragoal steer --kind <kind> ... --evidence "..." --rationale "..." [--json]
+ omo ultragoal add-goal --title "..." --objective "..." [--json]
+ omo ultragoal record-review-blockers --goal-id <id> --title "..." --objective "..." --evidence "..." --codex-goal-json <...> [--json]`;
+
+type CriteriaCounts = { readonly pass: number; readonly total: number };
+
+export function printJson(value: unknown): void {
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
+}
+
+function criteriaCounts(goal: UltragoalItem): CriteriaCounts {
+ let pass = 0;
+ for (const criterion of goal.successCriteria) if (criterion.status === "pass") pass += 1;
+ return { pass, total: goal.successCriteria.length };
+}
+
+export function printStatus(plan: UltragoalPlan): void {
+ let totalCriteria = 0;
+ let passCriteria = 0;
+ const lines = ["ultragoal status", "", "goals:"];
+ for (const goal of plan.goals) {
+ const counts = criteriaCounts(goal);
+ totalCriteria += counts.total;
+ passCriteria += counts.pass;
+ const marker = goal.id === plan.activeGoalId ? "*" : "-";
+ lines.push(`${marker} ${goal.id} [${goal.status}] ${goal.title} (criteria: ${counts.pass}/${counts.total})`);
+ }
+ lines.push("", "summary:", `total goals: ${plan.goals.length}`, `criteria: ${passCriteria}/${totalCriteria} pass`);
+ process.stdout.write(`${lines.join("\n")}\n`);
+}
+
+export function blockedDecisionHandoff(plan: UltragoalPlan): string {
+ const blocked = plan.goals.find((goal) => goal.status === "needs_user_decision" && goal.nonRetriable);
+ if (blocked === undefined) return "";
+ return [
+ "ultragoal: blocked on repeated external authorization; no retryable failed goals remain.",
+ `Goal: ${blocked.id} - ${blocked.title}`,
+ `Required external decision: ${blocked.requiredExternalDecision ?? "provide the missing authorization or choose a different unblock path"}.`,
+ "Do not run complete-goals --retry-failed again until external state changes or the user authorizes an unblock path.",
+ ].join("\n");
+}
+
+export function normalizeCodexGoalMode(value: string | undefined): UltragoalCodexGoalMode {
+ if (value === undefined) return "aggregate";
+ if (value === "aggregate" || value === "per_story") return value;
+ throw new UltragoalError(
+ "Invalid --codex-goal-mode; expected aggregate or per_story.",
+ "ULTRAGOAL_CODEX_GOAL_MODE_INVALID",
+ { details: { value } },
+ );
+}
diff --git a/plugins/omo/components/ultragoal/src/cli-steering.ts b/plugins/omo/components/ultragoal/src/cli-steering.ts
new file mode 100644
index 00000000..d0794da8
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/cli-steering.ts
@@ -0,0 +1,94 @@
+// biome-ignore-all format: keep this module under the mandated pure LOC budget.
+import { parseGoalArg, readJsonInput, readValue } from "./cli-arg-parser.js";
+import { printJson, printStatus } from "./cli-output.js";
+import type { SteerUltragoalResult, UltragoalSteeringChildGoal, UltragoalSteeringMutationKind, UltragoalSteeringProposal, UltragoalSteeringSource, UltragoalSuccessCriterionUserModel } from "./types.js";
+import { ULTRAGOAL_STEERING_MUTATION_KINDS, ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS, UltragoalError } from "./types.js";
+
+const SOURCES = ["user_prompt_submit", "finding", "cli"] as const satisfies readonly UltragoalSteeringSource[];
+
+export type CliSteeringProposal = UltragoalSteeringProposal & { readonly goalId?: string; readonly scenario?: string; readonly expectedEvidence?: string; readonly userModel?: UltragoalSuccessCriterionUserModel };
+
+function isKind(value: string | undefined): value is UltragoalSteeringMutationKind { return value !== undefined && ULTRAGOAL_STEERING_MUTATION_KINDS.some((kind) => kind === value); }
+function isSource(value: string | undefined): value is UltragoalSteeringSource { return value !== undefined && SOURCES.some((source) => source === value); }
+function isModel(value: string): value is UltragoalSuccessCriterionUserModel { return ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS.some((model) => model === value); }
+function fail(message: string, code: string, details: Record<string, unknown>): never { throw new UltragoalError(message, code, { details }); }
+function text(value: string | undefined, field: string): string | undefined { if (value === undefined) return undefined; const trimmed = value.trim(); if (trimmed.length > 0) return trimmed; return fail(`Empty ${field}.`, "ULTRAGOAL_STEERING_FIELD_EMPTY", { field }); }
+function required(argv: readonly string[], flag: string): string { const value = text(readValue(argv, flag), flag); return value ?? fail(`Missing ${flag}.`, "ULTRAGOAL_STEERING_FIELD_REQUIRED", { flag }); }
+function requiredGoal(argv: readonly string[]): string { const value = text(parseGoalArg(argv), "--goal-id"); return value ?? fail("Missing --goal-id.", "ULTRAGOAL_GOAL_ID_REQUIRED", { flag: "--goal-id" }); }
+function readObject(value: object, key: string): unknown { return Object.entries(value).find(([name]) => name === key)?.[1]; }
+function isPlain(value: unknown): value is object { return typeof value === "object" && value !== null && !Array.isArray(value); }
+function objectText(value: object, key: string): string | undefined { const candidate = readObject(value, key); return typeof candidate === "string" ? candidate : undefined; }
+
+export function parseSteeringKind(argv: readonly string[]): UltragoalSteeringMutationKind {
+ const value = readValue(argv, "--kind");
+ if (isKind(value)) return value;
+ return value === undefined ? fail("Missing --kind.", "ULTRAGOAL_STEERING_KIND_REQUIRED", { flag: "--kind" }) : fail(`Invalid --kind: ${value}.`, "ULTRAGOAL_STEERING_KIND_INVALID", { value, expected: ULTRAGOAL_STEERING_MUTATION_KINDS });
+}
+
+export function parseSteeringSource(argv: readonly string[]): UltragoalSteeringSource {
+ const value = readValue(argv, "--source");
+ if (value === undefined) return "cli";
+ return isSource(value) ? value : fail(`Invalid --source: ${value}.`, "ULTRAGOAL_STEERING_SOURCE_INVALID", { value, expected: SOURCES });
+}
+
+function child(value: unknown): UltragoalSteeringChildGoal | null {
+ if (!isPlain(value)) return null;
+ const title = text(objectText(value, "title"), "title"); const objective = text(objectText(value, "objective"), "objective");
+ if (title === undefined || objective === undefined) return null;
+ return { title, objective };
+}
+
+async function children(argv: readonly string[], flag: string, needed: boolean): Promise<UltragoalSteeringChildGoal[]> {
+ const input = needed ? required(argv, flag) : text(readValue(argv, flag), flag);
+ if (input === undefined) return [];
+ const raw = await readJsonInput(input);
+ if (!Array.isArray(raw)) return fail(`${flag} must be a JSON array.`, "ULTRAGOAL_STEERING_JSON_ARRAY_REQUIRED", { flag });
+ const parsed: UltragoalSteeringChildGoal[] = [];
+ for (const item of raw) { const next = child(item); if (next === null) return fail(`${flag} entries require title/objective.`, "ULTRAGOAL_STEERING_CHILD_INVALID", { flag }); parsed.push(next); }
+ return parsed;
+}
+
+async function stringArray(argv: readonly string[], flag: string): Promise<string[]> {
+ const raw = await readJsonInput(required(argv, flag));
+ if (!Array.isArray(raw)) return fail(`${flag} must be a JSON array.`, "ULTRAGOAL_STEERING_JSON_ARRAY_REQUIRED", { flag });
+ const values: string[] = [];
+ for (const item of raw) { if (typeof item !== "string") return fail(`${flag} entries must be strings.`, "ULTRAGOAL_STEERING_STRING_ARRAY_REQUIRED", { flag }); values.push(text(item, flag) ?? ""); }
+ return values;
+}
+
+function model(value: string | undefined): UltragoalSuccessCriterionUserModel | undefined { const trimmed = text(value, "--user-model"); if (trimmed === undefined) return undefined; return isModel(trimmed) ? trimmed : fail(`Invalid --user-model: ${trimmed}.`, "ULTRAGOAL_STEERING_USER_MODEL_INVALID", { value: trimmed, expected: ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS }); }
+function neverKind(kind: never): never { return fail(`Unsupported steering kind: ${String(kind)}.`, "ULTRAGOAL_STEERING_KIND_UNSUPPORTED", { kind }); }
+
+export async function parseSteeringProposal(argv: readonly string[]): Promise<CliSteeringProposal> {
+ const kind = parseSteeringKind(argv); const source = parseSteeringSource(argv); const base = { kind, source, evidence: required(argv, "--evidence"), rationale: required(argv, "--rationale") };
+ switch (kind) {
+ case "add_subgoal": return normalizeSteeringProposal({ ...base, title: required(argv, "--title"), objective: required(argv, "--objective") });
+ case "split_subgoal": { const goalId = requiredGoal(argv); return normalizeSteeringProposal({ ...base, goalId, targetGoalId: goalId, childGoals: await children(argv, "--children", true) }); }
+ case "reorder_pending": return normalizeSteeringProposal({ ...base, pendingOrder: await stringArray(argv, "--order") });
+ case "revise_pending_wording": { const goalId = requiredGoal(argv); const revisedTitle = readValue(argv, "--title"); const revisedObjective = readValue(argv, "--objective"); if (revisedTitle === undefined && revisedObjective === undefined) return fail("revise_pending_wording requires --title or --objective.", "ULTRAGOAL_STEERING_UPDATE_REQUIRED", { kind }); return normalizeSteeringProposal({ ...base, goalId, targetGoalId: goalId, ...(revisedTitle === undefined ? {} : { revisedTitle }), ...(revisedObjective === undefined ? {} : { revisedObjective }) }); }
+ case "revise_criterion": { const goalId = requiredGoal(argv); const criterionId = required(argv, "--criterion-id"); const scenario = readValue(argv, "--scenario"); const expectedEvidence = readValue(argv, "--expected-evidence"); const userModel = model(readValue(argv, "--user-model")); if (scenario === undefined && expectedEvidence === undefined && userModel === undefined) return fail("revise_criterion requires scenario, expected-evidence, or user-model.", "ULTRAGOAL_STEERING_UPDATE_REQUIRED", { kind }); return normalizeSteeringProposal({ ...base, goalId, targetGoalId: goalId, criterionId, ...(scenario === undefined ? {} : { scenario }), ...(expectedEvidence === undefined ? {} : { expectedEvidence }), ...(userModel === undefined ? {} : { userModel }) }); }
+ case "annotate_ledger": return normalizeSteeringProposal(base);
+ case "mark_blocked_superseded": { const goalId = requiredGoal(argv); const childGoals = await children(argv, "--replacements", false); return normalizeSteeringProposal({ ...base, goalId, targetGoalId: goalId, ...(childGoals.length === 0 ? {} : { childGoals }) }); }
+ default: return neverKind(kind);
+ }
+}
+
+function normalizedChildren(values: readonly UltragoalSteeringChildGoal[] | undefined): UltragoalSteeringChildGoal[] | undefined { if (values === undefined) return undefined; return values.map((item) => ({ title: text(item.title, "child.title") ?? "", objective: text(item.objective, "child.objective") ?? "" })); }
+function normalizedStrings(values: readonly string[] | undefined, field: string): string[] | undefined { if (values === undefined) return undefined; return values.map((value) => text(value, field) ?? ""); }
+
+export function normalizeSteeringProposal(proposal: CliSteeringProposal): CliSteeringProposal {
+ const evidence = text(proposal.evidence, "evidence") ?? ""; const rationale = text(proposal.rationale, "rationale") ?? ""; const goalId = text(proposal.goalId, "goalId"); const targetGoalId = text(proposal.targetGoalId, "targetGoalId"); const targetGoalIds = normalizedStrings(proposal.targetGoalIds, "targetGoalIds");
+ const criterionId = text(proposal.criterionId, "criterionId"); const title = text(proposal.title, "title"); const objective = text(proposal.objective, "objective"); const revisedTitle = text(proposal.revisedTitle, "revisedTitle"); const revisedObjective = text(proposal.revisedObjective, "revisedObjective");
+ const blockedReason = text(proposal.blockedReason, "blockedReason"); const directiveText = text(proposal.directiveText, "directiveText"); const promptSignature = text(proposal.promptSignature, "promptSignature"); const idempotencyKey = text(proposal.idempotencyKey, "idempotencyKey");
+ const scenario = text(proposal.scenario, "scenario"); const expectedEvidence = text(proposal.expectedEvidence, "expectedEvidence"); const childGoals = normalizedChildren(proposal.childGoals); const pendingOrder = normalizedStrings(proposal.pendingOrder, "pendingOrder");
+ return { kind: proposal.kind, source: proposal.source, evidence, rationale, ...(goalId === undefined ? {} : { goalId }), ...(targetGoalId === undefined ? {} : { targetGoalId }), ...(targetGoalIds === undefined ? {} : { targetGoalIds }), ...(criterionId === undefined ? {} : { criterionId }), ...(title === undefined ? {} : { title }), ...(objective === undefined ? {} : { objective }), ...(childGoals === undefined ? {} : { childGoals }), ...(revisedTitle === undefined ? {} : { revisedTitle }), ...(revisedObjective === undefined ? {} : { revisedObjective }), ...(pendingOrder === undefined ? {} : { pendingOrder }), ...(blockedReason === undefined ? {} : { blockedReason }), ...(proposal.after === undefined ? {} : { after: proposal.after }), ...(directiveText === undefined ? {} : { directiveText }), ...(promptSignature === undefined ? {} : { promptSignature }), ...(idempotencyKey === undefined ? {} : { idempotencyKey }), ...(proposal.now === undefined ? {} : { now: proposal.now }), ...(scenario === undefined ? {} : { scenario }), ...(expectedEvidence === undefined ? {} : { expectedEvidence }), ...(proposal.userModel === undefined ? {} : { userModel: proposal.userModel }) };
+}
+
+export function printSteerResult(result: SteerUltragoalResult, json: boolean): void {
+ if (json) { printJson({ ok: result.accepted, accepted: result.accepted, rejectedReasons: result.rejectedReasons, deduped: result.deduped, audit: result.audit, plan: result.plan }); return; }
+ const outcome = result.deduped ? "deduped" : result.accepted ? "accepted" : "rejected";
+ process.stdout.write(`ultragoal steer: ${outcome} ${result.audit.kind}\n`);
+ if (result.rejectedReasons.length > 0) process.stdout.write(`rejected: ${result.rejectedReasons.join("; ")}\n`);
+ if (result.audit.idempotencyKey !== undefined) process.stdout.write(`idempotency-key: ${result.audit.idempotencyKey}\n`);
+ printStatus(result.plan);
+}
diff --git a/plugins/omo/components/ultragoal/src/cli.ts b/plugins/omo/components/ultragoal/src/cli.ts
new file mode 100644
index 00000000..4570f692
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/cli.ts
@@ -0,0 +1,36 @@
+#!/usr/bin/env node
+import { ultragoalCommand } from "./cli-commands.js";
+import { runUltragoalHookCli } from "./codex-hook.js";
+
+const TOP_LEVEL_HELP =
+ "Usage:\n omo ultragoal <subcommand> [args]\n omo hook user-prompt-submit (Codex UserPromptSubmit hook)\n omo help | --help | -h (this message)\n\nRun `omo ultragoal help` for ultragoal subcommands.\n";
+
+async function main(): Promise<number> {
+ const argv = process.argv.slice(2);
+ const command = argv[0];
+ if (command === undefined || command === "help" || command === "--help" || command === "-h") {
+ process.stdout.write(TOP_LEVEL_HELP);
+ return 0;
+ }
+ if (command === "ultragoal") return ultragoalCommand(argv.slice(1));
+ if (command === "hook") {
+ const sub = argv[1];
+ if (sub === "user-prompt-submit") {
+ await runUltragoalHookCli(process.stdin, process.stdout);
+ return 0;
+ }
+ process.stderr.write(`[omo] unknown hook subcommand: ${sub ?? "(none)"}\n`);
+ return 1;
+ }
+ process.stderr.write(`[omo] unknown command: ${command}\n${TOP_LEVEL_HELP}`);
+ return 1;
+}
+
+main()
+ .then((code) => {
+ process.exit(code);
+ })
+ .catch((error: unknown) => {
+ process.stderr.write(`[omo] ${error instanceof Error ? error.message : String(error)}\n`);
+ process.exit(1);
+ });
diff --git a/plugins/omo/components/ultragoal/src/codex-goal-instruction.ts b/plugins/omo/components/ultragoal/src/codex-goal-instruction.ts
new file mode 100644
index 00000000..b1994eb8
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/codex-goal-instruction.ts
@@ -0,0 +1,121 @@
+import { codexGoalMode, expectedCodexObjective, isFinalRunCompletionCandidate } from "./goal-status.js";
+import type { UltragoalCodexGoalMode, UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "./types.js";
+
+export interface CodexCreateGoalPayload {
+ readonly objective: string;
+ readonly status: "active";
+}
+
+export interface UltragoalGoalInstruction {
+ readonly text: string;
+ readonly json: CodexCreateGoalPayload;
+}
+
+export function buildCodexGoalInstruction(args: {
+ readonly plan: UltragoalPlan;
+ readonly goal: UltragoalItem;
+ readonly isFinal?: boolean;
+}): UltragoalGoalInstruction {
+ const mode = codexGoalMode(args.plan);
+ const createGoal = buildCreateGoalPayload(args.plan, args.goal);
+ const isFinal = args.isFinal ?? isFinalRunCompletionCandidate(args.plan, args.goal);
+ return { text: buildText(mode, args.plan, args.goal, createGoal, isFinal), json: createGoal };
+}
+
+function buildCreateGoalPayload(plan: UltragoalPlan, goal: UltragoalItem): CodexCreateGoalPayload {
+ return { objective: expectedCodexObjective(plan, goal), status: "active" };
+}
+
+function buildText(
+ mode: UltragoalCodexGoalMode,
+ plan: UltragoalPlan,
+ goal: UltragoalItem,
+ createGoal: CodexCreateGoalPayload,
+ isFinal: boolean,
+): string {
+ return joinLines([
+ mode === "aggregate" ? "Ultragoal aggregate-goal handoff" : "Ultragoal active-goal handoff",
+ `Mode: ${mode}`,
+ `Plan: ${plan.goalsPath}`,
+ `Ledger: ${plan.ledgerPath}`,
+ `Goal: ${goal.id} — ${goal.title}`,
+ "",
+ ...activeGoalLines(goal),
+ "",
+ ...successCriteriaLines(goal.successCriteria),
+ "",
+ "Codex goal integration constraints:",
+ "- Use the create_goal payload exactly as rendered: objective and status only.",
+ "- Goals are unlimited. Do not add numeric limits.",
+ ...modeConstraintLines(mode, isFinal),
+ finalSection(goal, isFinal, mode === "aggregate"),
+ ...checkpointLines(mode),
+ "",
+ "create_goal payload:",
+ JSON.stringify(createGoal, null, 2),
+ ]);
+}
+
+function modeConstraintLines(mode: UltragoalCodexGoalMode, isFinal: boolean): readonly string[] {
+ if (mode === "per_story") {
+ return [
+ "- First call get_goal. If no active goal exists, call create_goal with the payload below.",
+ "- If a different active Codex goal exists, finish/checkpoint that goal before starting this ultragoal.",
+ "- Work only this goal until its completion audit passes.",
+ ];
+ }
+ return [
+ "- Codex goal = the whole omo ultragoal run; OMO G001/G002/etc. = ledger stories.",
+ "- First call get_goal. If no active goal exists, call create_goal with the aggregate payload below.",
+ "- If get_goal reports the same aggregate objective as active, continue this OMO story without creating a new Codex goal.",
+ "- If a different active or incomplete Codex goal exists, finish/checkpoint that goal before starting this ultragoal.",
+ isFinal
+ ? "- This is the final story; update_goal is allowed only after the mandatory quality gate passes."
+ : "- This is not the final story: do not call update_goal yet; the aggregate Codex goal must remain active while later OMO stories remain.",
+ ];
+}
+
+function checkpointLines(mode: UltragoalCodexGoalMode): readonly string[] {
+ const failureLine =
+ "- If blocked or failed, checkpoint with --status failed and the failure evidence; rerun complete-goals --retry-failed to resume.";
+ if (mode === "per_story") return [failureLine];
+ return [
+ "- Checkpoint this OMO story with a fresh get_goal snapshot whose objective matches the aggregate payload.",
+ failureLine,
+ ];
+}
+
+function activeGoalLines(goal: UltragoalItem): readonly string[] {
+ return ["Active goal:", `- id: ${goal.id}`, `- title: ${goal.title}`, `- objective: ${goal.objective}`];
+}
+
+function successCriteriaLines(criteria: readonly UltragoalSuccessCriterion[]): readonly string[] {
+ if (criteria.length === 0) return ["Success criteria:", "- No success criteria recorded for this goal."];
+ return ["Success criteria:", ...criteria.map(formatCriterionLine)];
+}
+
+function formatCriterionLine(criterion: UltragoalSuccessCriterion): string {
+ const remainingWork = criterion.status === "pending" ? " remaining work:" : "";
+ return `-${remainingWork} [${criterion.id}] (${criterion.userModel}) ${criterion.scenario} — expect: ${criterion.expectedEvidence} — status: ${criterion.status}`;
+}
+
+function finalSection(goal: UltragoalItem, isFinal: boolean, aggregate: boolean): string {
+ if (!isFinal)
+ return "- This is not the final ultragoal story; do not run the final ai-slop-cleaner/$code-review gate yet.";
+ const blockerCommand = `omo ultragoal record-review-blockers --goal-id ${goal.id} --title "Resolve final code-review blockers" --objective "<blocker-resolution objective>" --evidence "<review findings>" --codex-goal-json "<active get_goal JSON or path>"`;
+ const checkpointCommand = `omo ultragoal checkpoint --goal-id ${goal.id} --status complete --evidence "<tests/files/PR evidence>" --codex-goal-json "<fresh complete get_goal JSON or path>" --quality-gate-json "<quality gate JSON or path>"`;
+ return joinLines([
+ "Final story — run mandatory quality gate before update_goal:",
+ "- Run ai-slop-cleaner on changed files even when it is a no-op, rerun verification, then run $code-review.",
+ "- If final $code-review is not APPROVE with architect status CLEAR, do not call update_goal. Record blocker work first:",
+ ` ${blockerCommand}`,
+ aggregate
+ ? '- If final $code-review is clean, call update_goal({status: "complete"}), call get_goal again, then checkpoint the aggregate story:'
+ : '- If final $code-review is clean, call update_goal({status: "complete"}), call get_goal again, then checkpoint:',
+ ` ${checkpointCommand}`,
+ ]);
+}
+
+function joinLines(lines: readonly string[]): string {
+ return lines.join("\n");
+}
diff --git a/plugins/omo/components/ultragoal/src/codex-goal-snapshot.ts b/plugins/omo/components/ultragoal/src/codex-goal-snapshot.ts
new file mode 100644
index 00000000..8361c354
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/codex-goal-snapshot.ts
@@ -0,0 +1,139 @@
+import { existsSync } from "node:fs";
+import { readFile } from "node:fs/promises";
+import { resolve } from "node:path";
+
+export type CodexGoalSnapshotStatus = "active" | "complete" | "cancelled" | "failed" | "unknown";
+
+export interface CodexGoalSnapshot {
+ available: boolean;
+ objective?: string;
+ status?: CodexGoalSnapshotStatus;
+ raw: unknown;
+}
+
+export interface CodexGoalReconciliation {
+ ok: boolean;
+ snapshot: CodexGoalSnapshot;
+ warnings: string[];
+ errors: string[];
+}
+
+export interface ReconcileCodexGoalOptions {
+ expectedObjective: string;
+ acceptedObjectives?: readonly string[];
+ allowedStatuses?: readonly CodexGoalSnapshotStatus[];
+ requireSnapshot?: boolean;
+ requireComplete?: boolean;
+}
+
+export class CodexGoalSnapshotError extends Error {}
+function safeObject(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
+}
+
+function safeString(value: unknown): string {
+ return typeof value === "string" ? value.trim() : "";
+}
+
+function normalizeStatus(value: unknown): CodexGoalSnapshotStatus {
+ const status = safeString(value).toLowerCase();
+ if (status === "complete" || status === "completed" || status === "done") return "complete";
+ if (status === "cancelled" || status === "canceled") return "cancelled";
+ if (status === "failed" || status === "failure") return "failed";
+ if (status === "active" || status === "in_progress" || status === "pending" || status === "running") return "active";
+ return "unknown";
+}
+
+function normalizeObjective(value: string): string {
+ return value.replace(/\s+/g, " ").trim();
+}
+
+export function parseCodexGoalSnapshot(value: unknown): CodexGoalSnapshot {
+ const root = safeObject(value);
+ const goalValue = Object.hasOwn(root, "goal") ? root["goal"] : value;
+ if (goalValue === null || goalValue === undefined || goalValue === false) {
+ return { available: false, raw: value };
+ }
+
+ const goal = safeObject(goalValue);
+ const objective = safeString(goal["objective"] ?? goal["goal"] ?? goal["description"] ?? root["objective"]);
+ const status = normalizeStatus(goal["status"] ?? root["status"]);
+
+ return {
+ available: Boolean(objective || status !== "unknown"),
+ ...(objective ? { objective } : {}),
+ status,
+ raw: value,
+ };
+}
+
+export async function readCodexGoalSnapshotInput(
+ raw: string | undefined,
+ cwd = process.cwd(),
+): Promise<CodexGoalSnapshot | null> {
+ if (!raw?.trim()) return null;
+ const trimmed = raw.trim();
+ try {
+ return parseCodexGoalSnapshot(JSON.parse(trimmed));
+ } catch {
+ const path = resolve(cwd, trimmed);
+ if (!existsSync(path)) {
+ throw new CodexGoalSnapshotError(`Codex goal snapshot is neither valid JSON nor a readable path: ${trimmed}`);
+ }
+ try {
+ return parseCodexGoalSnapshot(JSON.parse(await readFile(path, "utf-8")));
+ } catch (error) {
+ throw new CodexGoalSnapshotError(
+ `Codex goal snapshot path does not contain valid JSON: ${trimmed}${error instanceof Error ? ` (${error.message})` : ""}`,
+ );
+ }
+ }
+}
+
+export function reconcileCodexGoalSnapshot(
+ snapshot: CodexGoalSnapshot | null | undefined,
+ options: ReconcileCodexGoalOptions,
+): CodexGoalReconciliation {
+ const effectiveSnapshot = snapshot ?? { available: false, raw: null };
+ const errors: string[] = [];
+ const warnings: string[] = [];
+
+ if (!effectiveSnapshot.available) {
+ const message =
+ "Codex goal snapshot is absent or reports no active goal; call get_goal and pass its JSON with --codex-goal-json.";
+ if (options.requireSnapshot) errors.push(message);
+ else warnings.push(message);
+ return { ok: errors.length === 0, snapshot: effectiveSnapshot, warnings, errors };
+ }
+
+ const expected = normalizeObjective(options.expectedObjective);
+ const accepted = new Set(
+ [expected, ...(options.acceptedObjectives ?? []).map((objective) => normalizeObjective(objective))].filter(
+ Boolean,
+ ),
+ );
+ const actual = normalizeObjective(effectiveSnapshot.objective ?? "");
+ if (!actual) {
+ errors.push("Codex goal snapshot is missing objective text.");
+ } else if (!accepted.has(actual)) {
+ errors.push(`Codex goal objective mismatch: expected "${expected}", got "${actual}".`);
+ }
+
+ const allowed = options.allowedStatuses ?? (options.requireComplete ? ["complete"] : ["active", "complete"]);
+ const actualStatus = effectiveSnapshot.status ?? "unknown";
+ if (!allowed.includes(actualStatus)) {
+ errors.push(`Codex goal status mismatch: expected ${allowed.join(" or ")}, got ${actualStatus}.`);
+ }
+ if (options.requireComplete && actualStatus !== "complete") {
+ errors.push(
+ 'Codex goal is not complete; call update_goal({status: "complete"}) only after the objective is actually complete, then pass the fresh get_goal JSON.',
+ );
+ }
+
+ return { ok: errors.length === 0, snapshot: effectiveSnapshot, warnings, errors };
+}
+
+export function formatCodexGoalReconciliation(reconciliation: CodexGoalReconciliation): string {
+ const parts = [...reconciliation.errors, ...reconciliation.warnings];
+ return parts.join(" ");
+}
diff --git a/plugins/omo/components/ultragoal/src/codex-hook.ts b/plugins/omo/components/ultragoal/src/codex-hook.ts
new file mode 100644
index 00000000..3b6a7687
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/codex-hook.ts
@@ -0,0 +1,85 @@
+import { parseUltragoalSteeringDirective, steerUltragoal } from "./steering.js";
+
+export interface UserPromptSubmitPayload {
+ readonly cwd: string;
+ readonly hook_event_name: "UserPromptSubmit";
+ readonly model?: string;
+ readonly permission_mode?: string;
+ readonly prompt: string;
+ readonly session_id: string;
+ readonly transcript_path?: string;
+ readonly turn_id?: string;
+}
+
+export function parseUserPromptSubmitPayload(raw: string): UserPromptSubmitPayload | null {
+ if (raw.trim().length === 0) return null;
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ return isUserPromptSubmitPayload(parsed) ? parsed : null;
+ } catch (error) {
+ if (error instanceof SyntaxError) return null;
+ return null;
+ }
+}
+
+export async function applyUserPromptUltragoalSteering(payload: UserPromptSubmitPayload): Promise<string> {
+ try {
+ if (payload.hook_event_name !== "UserPromptSubmit") return "";
+ const proposal = parseUltragoalSteeringDirective(payload.prompt);
+ if (proposal === null) return "";
+ const result = await steerUltragoal(payload.cwd, proposal);
+ if (!result.accepted) return "";
+ return JSON.stringify({
+ status: "accepted",
+ kind: result.audit.kind,
+ source: result.audit.source,
+ deduped: result.deduped,
+ });
+ } catch (error) {
+ if (error instanceof Error) return "";
+ return "";
+ }
+}
+
+export async function runUltragoalHookCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream): Promise<void> {
+ try {
+ const payload = parseUserPromptSubmitPayload(await readAll(stdin));
+ if (payload === null) return;
+ const output = await applyUserPromptUltragoalSteering(payload);
+ if (output.length > 0) stdout.write(output);
+ } catch (error) {
+ if (error instanceof Error) return;
+ return;
+ }
+}
+
+function isUserPromptSubmitPayload(value: unknown): value is UserPromptSubmitPayload {
+ if (!isRecord(value)) return false;
+ return (
+ value["hook_event_name"] === "UserPromptSubmit" &&
+ typeof value["cwd"] === "string" &&
+ typeof value["prompt"] === "string" &&
+ typeof value["session_id"] === "string" &&
+ ["model", "permission_mode", "transcript_path", "turn_id"].every((key) => optionalString(value[key]))
+ );
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function optionalString(value: unknown): boolean {
+ return value === undefined || typeof value === "string";
+}
+
+function readAll(stdin: NodeJS.ReadableStream): Promise<string> {
+ return new Promise((resolve, reject) => {
+ let data = "";
+ stdin.setEncoding("utf8");
+ stdin.on("data", (chunk: unknown) => {
+ data += chunk instanceof Buffer ? chunk.toString() : String(chunk);
+ });
+ stdin.once("error", reject);
+ stdin.once("end", () => resolve(data));
+ });
+}
diff --git a/plugins/omo/components/ultragoal/src/evidence.ts b/plugins/omo/components/ultragoal/src/evidence.ts
new file mode 100644
index 00000000..4d801481
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/evidence.ts
@@ -0,0 +1,121 @@
+// biome-ignore-all format: keep this module under the mandated pure LOC budget.
+import { hasAllCriteriaPass } from "./goal-status.js";
+import { appendLedger, readUltragoalPlan, withUltragoalMutationLock, writePlan } from "./plan-io.js";
+import type { UltragoalItem, UltragoalLedgerEntry, UltragoalPlan, UltragoalSuccessCriterion } from "./types.js";
+import { iso, UltragoalError } from "./types.js";
+
+type EvidenceStatus = "pass" | "fail" | "blocked";
+type RecordEvidenceArgs = { readonly goalId: string; readonly criterionId: string; readonly status: EvidenceStatus; readonly evidence: string; readonly notes?: string };
+
+function ultragoalFail(message: string, code: string, details: Record<string, unknown>): never { throw new UltragoalError(message, code, { details }); }
+
+function ledgerKind(status: EvidenceStatus): UltragoalLedgerEntry["kind"] {
+ switch (status) {
+ case "pass":
+ return "evidence_captured";
+ case "fail":
+ return "criterion_failed";
+ case "blocked":
+ return "criterion_blocked";
+ default:
+ return ultragoalFail("Invalid criterion status.", "ULTRAGOAL_CRITERION_STATUS_INVALID", { status });
+ }
+}
+
+function findGoal(plan: UltragoalPlan, goalId: string): UltragoalItem {
+ const goal = plan.goals.find((candidate) => candidate.id === goalId);
+ return goal ?? ultragoalFail(`Ultragoal goal not found: ${goalId}.`, "ULTRAGOAL_GOAL_NOT_FOUND", { goalId });
+}
+
+function findCriterion(goal: UltragoalItem, criterionId: string): UltragoalSuccessCriterion {
+ const criterion = goal.successCriteria.find((candidate) => candidate.id === criterionId);
+ return criterion ?? ultragoalFail(`Success criterion not found: ${criterionId}.`, "ULTRAGOAL_CRITERION_NOT_FOUND", { goalId: goal.id, criterionId });
+}
+
+function nonEmptyEvidence(evidence: string): string { const trimmed = evidence.trim(); return trimmed || ultragoalFail("Evidence must be a non-empty string.", "ULTRAGOAL_EVIDENCE_REQUIRED", {}); }
+
+export async function recordEvidence(repoRoot: string, args: RecordEvidenceArgs): Promise<{ plan: UltragoalPlan; goal: UltragoalItem; criterion: UltragoalSuccessCriterion; ledgerEntry: UltragoalLedgerEntry }> {
+ return withUltragoalMutationLock(repoRoot, async () => {
+ const plan = await readUltragoalPlan(repoRoot);
+ const goal = findGoal(plan, args.goalId);
+ const criterion = findCriterion(goal, args.criterionId);
+ const evidence = nonEmptyEvidence(args.evidence);
+ const kind = ledgerKind(args.status);
+ const prevStatus = criterion.status;
+ const capturedAt = iso();
+ criterion.status = args.status;
+ criterion.capturedEvidence = evidence;
+ criterion.capturedAt = capturedAt;
+ if (args.notes !== undefined) criterion.notes = args.notes;
+ goal.updatedAt = capturedAt;
+ plan.updatedAt = capturedAt;
+ await writePlan(repoRoot, plan);
+ const ledgerEntry: UltragoalLedgerEntry = {
+ at: capturedAt,
+ kind,
+ goalId: goal.id,
+ criterionId: criterion.id,
+ criterionStatus: args.status,
+ evidence,
+ capturedEvidence: evidence,
+ before: { status: prevStatus },
+ after: { goalId: goal.id, criterionId: criterion.id, status: args.status, evidence, capturedAt, prevStatus },
+ };
+ await appendLedger(repoRoot, ledgerEntry);
+ return { plan, goal, criterion, ledgerEntry };
+ });
+}
+
+export async function markCriteriaPendingResetForGoal(repoRoot: string, goalId: string): Promise<{ plan: UltragoalPlan; resetCount: number }> {
+ return withUltragoalMutationLock(repoRoot, async () => {
+ const plan = await readUltragoalPlan(repoRoot);
+ const goal = findGoal(plan, goalId);
+ const now = iso();
+ const before = goal.successCriteria.map((criterion) => ({ id: criterion.id, status: criterion.status, capturedEvidence: criterion.capturedEvidence, capturedAt: criterion.capturedAt ?? null }));
+ for (const criterion of goal.successCriteria) {
+ criterion.status = "pending";
+ criterion.capturedEvidence = null;
+ delete criterion.capturedAt;
+ delete criterion.notes;
+ }
+ goal.updatedAt = now;
+ plan.updatedAt = now;
+ await writePlan(repoRoot, plan);
+ await appendLedger(repoRoot, { at: now, kind: "criteria_revised", goalId, message: `Reset ${goal.successCriteria.length} criteria to pending.`, before, after: { resetCount: goal.successCriteria.length } });
+ return { plan, resetCount: goal.successCriteria.length };
+ });
+}
+
+export function criteriaSummary(plan: UltragoalPlan): { totalCriteria: number; passCount: number; pendingCount: number; failCount: number; blockedCount: number; goalsWithUnresolvedCriteria: string[] } {
+ let totalCriteria = 0;
+ let passCount = 0;
+ let pendingCount = 0;
+ let failCount = 0;
+ let blockedCount = 0;
+ const goalsWithUnresolvedCriteria: string[] = [];
+ for (const goal of plan.goals) {
+ let unresolved = false;
+ for (const criterion of goal.successCriteria) {
+ totalCriteria += 1;
+ if (criterion.status !== "pass") unresolved = true;
+ switch (criterion.status) {
+ case "pass": passCount += 1; break;
+ case "pending": pendingCount += 1; break;
+ case "fail": failCount += 1; break;
+ case "blocked": blockedCount += 1; break;
+ default: ultragoalFail("Invalid criterion status.", "ULTRAGOAL_CRITERION_STATUS_INVALID", { status: criterion.status });
+ }
+ }
+ if (unresolved) goalsWithUnresolvedCriteria.push(goal.id);
+ }
+ return { totalCriteria, passCount, pendingCount, failCount, blockedCount, goalsWithUnresolvedCriteria };
+}
+
+export function unresolvedCriteriaOf(goal: UltragoalItem): UltragoalSuccessCriterion[] { return goal.successCriteria.filter((criterion) => criterion.status !== "pass"); }
+
+export function requireAllCriteriaPass(goal: UltragoalItem): void {
+ if (hasAllCriteriaPass(goal)) return;
+ throw new UltragoalError(`Goal ${goal.id} has unresolved success criteria.`, "ultragoal_criteria_not_all_pass", {
+ details: { goalId: goal.id, unresolved: unresolvedCriteriaOf(goal).map((criterion) => ({ id: criterion.id, status: criterion.status })) },
+ });
+}
diff --git a/plugins/omo/components/ultragoal/src/goal-status.ts b/plugins/omo/components/ultragoal/src/goal-status.ts
new file mode 100644
index 00000000..a140c4bd
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/goal-status.ts
@@ -0,0 +1,84 @@
+import type {
+ UltragoalCodexGoalMode,
+ UltragoalItem,
+ UltragoalPlan,
+ UltragoalStatus,
+ UltragoalSuccessCriterion,
+} from "./types.js";
+
+export const ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE: string =
+ "Complete the durable ultragoal plan in .omo/ultragoal/goals.json, including later accepted/appended stories, under the original brief constraints; use .omo/ultragoal/ledger.jsonl as the audit trail.";
+
+export function codexGoalMode(plan: UltragoalPlan): UltragoalCodexGoalMode {
+ return plan.codexGoalMode ?? "per_story";
+}
+
+function isResolvedStatus(status: UltragoalStatus): boolean {
+ return status === "complete";
+}
+
+function isSupersededResolved(goal: UltragoalItem, plan: UltragoalPlan): boolean {
+ if (goal.steeringStatus !== "superseded") return false;
+ const replacements = goal.supersededBy ?? [];
+ if (replacements.length === 0) return false;
+ return replacements.every((id) => {
+ const replacement = plan.goals.find((candidate) => candidate.id === id);
+ return replacement !== undefined && isResolvedStatus(replacement.status);
+ });
+}
+
+function isCompletionBlocking(goal: UltragoalItem, plan: UltragoalPlan): boolean {
+ if (goal.steeringStatus === "superseded") return !isSupersededResolved(goal, plan);
+ if (goal.steeringStatus === "blocked") return true;
+ return !isResolvedStatus(goal.status);
+}
+
+function isCompletionBlockingForFinalCandidate(
+ candidate: UltragoalItem,
+ finalCandidate: UltragoalItem,
+ plan: UltragoalPlan,
+): boolean {
+ if (candidate.id === finalCandidate.id) return false;
+ if (candidate.steeringStatus === "superseded") {
+ const replacements = candidate.supersededBy ?? [];
+ if (replacements.length === 0) return true;
+ return !replacements.every((id) => {
+ if (id === finalCandidate.id) return true;
+ const replacement = plan.goals.find((goal) => goal.id === id);
+ return replacement !== undefined && isResolvedStatus(replacement.status);
+ });
+ }
+ return isCompletionBlocking(candidate, plan);
+}
+
+export function isUltragoalDone(plan: UltragoalPlan): boolean {
+ if (plan.aggregateCompletion?.status === "complete") return true;
+ return plan.goals.every((goal) => !isCompletionBlocking(goal, plan));
+}
+
+export function isFinalRunCompletionCandidate(plan: UltragoalPlan, goal: UltragoalItem): boolean {
+ return (
+ isCompletionBlocking(goal, plan) &&
+ plan.goals.every((candidate) => !isCompletionBlockingForFinalCandidate(candidate, goal, plan))
+ );
+}
+
+export function aggregateCodexObjective(plan: UltragoalPlan): string {
+ return plan.codexObjective ?? ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE;
+}
+
+export function expectedCodexObjective(plan: UltragoalPlan, goal: UltragoalItem): string {
+ return codexGoalMode(plan) === "aggregate" ? aggregateCodexObjective(plan) : goal.objective;
+}
+
+export function compatibleCodexObjectives(plan: UltragoalPlan): readonly string[] {
+ return [aggregateCodexObjective(plan), ...(plan.codexObjectiveAliases ?? [])];
+}
+
+export function hasAllCriteriaPass(goal: UltragoalItem): boolean {
+ return goal.successCriteria.length > 0 && goal.successCriteria.every((criterion) => criterion.status === "pass");
+}
+
+export function firstUnresolvedCriterion(goal: UltragoalItem): UltragoalSuccessCriterion | undefined {
+ return goal.successCriteria.find((criterion) => criterion.status !== "pass");
+}
diff --git a/plugins/omo/components/ultragoal/src/paths.ts b/plugins/omo/components/ultragoal/src/paths.ts
new file mode 100644
index 00000000..835d6536
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/paths.ts
@@ -0,0 +1,27 @@
+import { join } from "node:path";
+import { ULTRAGOAL_BRIEF, ULTRAGOAL_DIR, ULTRAGOAL_GOALS, ULTRAGOAL_LEDGER } from "./types.js";
+
+export function ultragoalDir(repoRoot: string): string {
+ return join(repoRoot, ULTRAGOAL_DIR);
+}
+
+export function ultragoalBriefPath(repoRoot: string): string {
+ return join(ultragoalDir(repoRoot), ULTRAGOAL_BRIEF);
+}
+
+export function ultragoalGoalsPath(repoRoot: string): string {
+ return join(ultragoalDir(repoRoot), ULTRAGOAL_GOALS);
+}
+
+export function ultragoalLedgerPath(repoRoot: string): string {
+ return join(ultragoalDir(repoRoot), ULTRAGOAL_LEDGER);
+}
+
+export function repoRelative(absolutePath: string, repoRoot: string): string {
+ const slashPrefix = `${repoRoot}/`;
+ const backslashPrefix = `${repoRoot}\\`;
+ if (absolutePath.startsWith(slashPrefix)) return absolutePath.slice(slashPrefix.length).split("\\").join("/");
+ if (absolutePath.startsWith(backslashPrefix))
+ return absolutePath.slice(backslashPrefix.length).split("\\").join("/");
+ return absolutePath.split("\\").join("/");
+}
diff --git a/plugins/omo/components/ultragoal/src/plan-crud.ts b/plugins/omo/components/ultragoal/src/plan-crud.ts
new file mode 100644
index 00000000..e40b5fc0
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/plan-crud.ts
@@ -0,0 +1,113 @@
+// biome-ignore-all format: keep this port under the mandated pure LOC budget.
+import { existsSync } from "node:fs";
+import { mkdir, writeFile } from "node:fs/promises";
+
+import { ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE } from "./goal-status.js";
+import { ultragoalBriefPath, ultragoalDir, ultragoalGoalsPath, ultragoalLedgerPath } from "./paths.js";
+import { appendLedger, readUltragoalPlan, withUltragoalMutationLock, writePlan } from "./plan-io.js";
+import type { UltragoalCodexGoalMode, UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "./types.js";
+import { iso, ULTRAGOAL_BRIEF, ULTRAGOAL_DIR, ULTRAGOAL_GOALS, ULTRAGOAL_LEDGER, UltragoalError } from "./types.js";
+
+export type UltragoalPlanSummary = { readonly total: number; readonly pending: number; readonly in_progress: number; readonly complete: number; readonly failed: number; readonly blocked: number; readonly review_blocked: number; readonly needs_user_decision: number; readonly superseded: number; readonly criteria: { readonly total: number; readonly pass: number; readonly pending: number; readonly fail: number; readonly blocked: number } };
+
+function cleanLine(line: string): string { return line.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/, "").trim(); }
+function normalizeObjective(value: string): string { return value.replace(/\s+/g, " ").trim(); }
+function titleFromObjective(objective: string, fallback: string): string { const firstLine = objective.split(/\r?\n/).map((line) => line.trim()).find(Boolean) ?? fallback; return firstLine.length > 72 ? `${firstLine.slice(0, 69).trimEnd()}...` : firstLine; }
+function normalizeGoalId(title: string, index: number): string { const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 36).replace(/-+$/g, ""); return `G${String(index + 1).padStart(3, "0")}${slug ? `-${slug}` : ""}`; }
+function assertNonEmpty(value: string | undefined, label: string): string { const trimmed = value?.trim(); if (!trimmed) throw new UltragoalError(`Missing ${label}.`, "ULTRAGOAL_ARGUMENT_MISSING"); return trimmed; }
+function truncateObjective(objective: string): string { return objective.length > 80 ? `${objective.slice(0, 77).trimEnd()}...` : objective; }
+
+export function seedDefaultSuccessCriteria(goalIndex: number, objective: string): UltragoalSuccessCriterion[] {
+ const subject = truncateObjective(normalizeObjective(objective) || `Goal ${goalIndex + 1}`);
+ const rows = [
+ ["C001", "happy", `happy path for: ${subject}`, `Replace via revise_criterion with observable happy-path proof for goal ${goalIndex + 1}.`],
+ ["C002", "edge", "edge case (boundary/empty/malformed)", `Replace via revise_criterion with boundary or malformed-input proof for: ${subject}.`],
+ ["C003", "regression", "regression: adjacent surface still works", `Replace via revise_criterion with regression proof for neighboring behavior after: ${subject}.`],
+ ] as const;
+ return rows.map(([id, userModel, scenario, expectedEvidence]) => ({ id, scenario, userModel, expectedEvidence, capturedEvidence: null, status: "pending" }));
+}
+
+export function deriveGoalCandidates(brief: string): Array<{ title: string; objective: string }> {
+ const bulletGoals = brief.split(/\r?\n/).map((line) => ({ original: line, cleaned: normalizeObjective(cleanLine(line)) })).filter(({ cleaned }) => cleaned.length > 0 && cleaned.length <= 1200).filter(({ original, cleaned }, index, all) => /^\s*(?:[-*+]\s+|\d+[.)]\s+)/.test(original) && all.findIndex((candidate) => candidate.cleaned === cleaned) === index).map(({ cleaned }) => cleaned);
+ const paragraphs = brief.split(/\n\s*\n/).map(normalizeObjective).filter((paragraph) => paragraph.length > 0 && !paragraph.startsWith("#"));
+ const selected = (bulletGoals.length > 0 ? bulletGoals : paragraphs).length > 0 ? (bulletGoals.length > 0 ? bulletGoals : paragraphs) : ["Complete the requested project objective."];
+ return selected.map((objective, index) => ({ title: titleFromObjective(objective, `Goal ${index + 1}`), objective }));
+}
+
+function makeGoal(title: string, objective: string, index: number, now: string): UltragoalItem {
+ const cleanTitle = assertNonEmpty(title, "title");
+ const cleanObjective = assertNonEmpty(objective, "objective");
+ return { id: normalizeGoalId(cleanTitle, index), title: cleanTitle, objective: cleanObjective, status: "pending", successCriteria: seedDefaultSuccessCriteria(index, cleanObjective), attempt: 0, createdAt: now, updatedAt: now };
+}
+
+function appendGoalToPlan(plan: UltragoalPlan, title: string, objective: string, now: string): UltragoalItem {
+ const goal = makeGoal(title, objective, plan.goals.length, now);
+ plan.goals.push(goal);
+ plan.updatedAt = now;
+ return goal;
+}
+
+function isScheduleEligible(goal: UltragoalItem): boolean { return goal.steeringStatus !== "superseded" && goal.steeringStatus !== "blocked"; }
+
+function clearGoalBlockerFields(goal: UltragoalItem): void {
+ for (const key of ["blockedReason", "blockerSignature", "blockerOccurrenceCount", "requiredExternalDecision", "nonRetriable", "failedAt", "failureReason"] as const) delete goal[key];
+}
+
+export async function createUltragoalPlan(repoRoot: string, args: { brief: string; codexGoalMode?: UltragoalCodexGoalMode; force?: boolean }): Promise<UltragoalPlan> {
+ return withUltragoalMutationLock(repoRoot, async () => {
+ if (!args.force && existsSync(ultragoalGoalsPath(repoRoot))) throw new UltragoalError(`Refusing to overwrite existing ${ULTRAGOAL_DIR}/${ULTRAGOAL_GOALS}; pass --force to recreate it.`, "ULTRAGOAL_PLAN_EXISTS");
+ const now = iso();
+ const goals = deriveGoalCandidates(args.brief).map((goal, index) => makeGoal(goal.title, goal.objective, index, now));
+ const plan: UltragoalPlan = { version: 1, createdAt: now, updatedAt: now, briefPath: `${ULTRAGOAL_DIR}/${ULTRAGOAL_BRIEF}`, goalsPath: `${ULTRAGOAL_DIR}/${ULTRAGOAL_GOALS}`, ledgerPath: `${ULTRAGOAL_DIR}/${ULTRAGOAL_LEDGER}`, codexGoalMode: args.codexGoalMode ?? "aggregate", goals };
+ if (plan.codexGoalMode === "aggregate") plan.codexObjective = ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE;
+ await mkdir(ultragoalDir(repoRoot), { recursive: true });
+ await writeFile(ultragoalBriefPath(repoRoot), args.brief.endsWith("\n") ? args.brief : `${args.brief}\n`, "utf8");
+ await writePlan(repoRoot, plan);
+ await writeFile(ultragoalLedgerPath(repoRoot), "", "utf8");
+ await appendLedger(repoRoot, { at: now, kind: "plan_created", message: `${goals.length} goal(s) created` });
+ return plan;
+ });
+}
+
+export async function addUltragoalGoal(repoRoot: string, args: { title: string; objective: string }): Promise<{ plan: UltragoalPlan; goal: UltragoalItem }> {
+ return withUltragoalMutationLock(repoRoot, async () => {
+ const plan = await readUltragoalPlan(repoRoot);
+ const now = iso();
+ const goal = appendGoalToPlan(plan, args.title, args.objective, now);
+ await writePlan(repoRoot, plan);
+ await appendLedger(repoRoot, { at: now, kind: "goal_added", goalId: goal.id, status: goal.status, message: goal.title });
+ return { plan, goal };
+ });
+}
+
+export async function startNextUltragoal(repoRoot: string, args: { retryFailed?: boolean } = {}): Promise<{ plan: UltragoalPlan; goal: UltragoalItem; resumed: boolean } | { done: true; plan: UltragoalPlan }> {
+ return withUltragoalMutationLock(repoRoot, async () => {
+ const plan = await readUltragoalPlan(repoRoot);
+ const now = iso();
+ if (plan.aggregateCompletion?.status === "complete") return { done: true, plan };
+ const existing = plan.goals.find((goal) => goal.status === "in_progress" && isScheduleEligible(goal));
+ if (existing) { await appendLedger(repoRoot, { at: now, kind: "goal_resumed", goalId: existing.id, status: existing.status, message: "Resuming active ultragoal" }); return { plan, goal: existing, resumed: true }; }
+ let next = plan.goals.find((goal) => goal.status === "pending" && isScheduleEligible(goal));
+ if (!next && args.retryFailed) {
+ next = plan.goals.find((goal) => goal.status === "failed" && !goal.nonRetriable && isScheduleEligible(goal));
+ if (next) await appendLedger(repoRoot, { at: now, kind: "goal_retried", goalId: next.id, status: "pending", ...(next.failureReason ? { message: next.failureReason } : {}) });
+ }
+ if (!next) return { done: true, plan };
+ next.status = "in_progress";
+ next.attempt += 1;
+ next.startedAt = now;
+ clearGoalBlockerFields(next);
+ next.updatedAt = now;
+ plan.activeGoalId = next.id;
+ plan.updatedAt = now;
+ await writePlan(repoRoot, plan);
+ await appendLedger(repoRoot, { at: now, kind: "goal_started", goalId: next.id, status: next.status, message: `Attempt ${next.attempt}` });
+ return { plan, goal: next, resumed: false };
+ });
+}
+
+export function summarizeUltragoalPlan(plan: UltragoalPlan): UltragoalPlanSummary {
+ const countStatus = (status: UltragoalItem["status"]): number => plan.goals.filter((goal) => goal.status === status).length;
+ const countCriteria = (status: UltragoalSuccessCriterion["status"]): number => plan.goals.reduce((sum, goal) => sum + goal.successCriteria.filter((criterion) => criterion.status === status).length, 0);
+ return { total: plan.goals.length, pending: countStatus("pending"), in_progress: countStatus("in_progress"), complete: countStatus("complete"), failed: countStatus("failed"), blocked: countStatus("blocked"), review_blocked: countStatus("review_blocked"), needs_user_decision: countStatus("needs_user_decision"), superseded: plan.goals.filter((goal) => goal.steeringStatus === "superseded").length, criteria: { total: plan.goals.reduce((sum, goal) => sum + goal.successCriteria.length, 0), pass: countCriteria("pass"), pending: countCriteria("pending"), fail: countCriteria("fail"), blocked: countCriteria("blocked") } };
+}
diff --git a/plugins/omo/components/ultragoal/src/plan-io.ts b/plugins/omo/components/ultragoal/src/plan-io.ts
new file mode 100644
index 00000000..d8df442c
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/plan-io.ts
@@ -0,0 +1,99 @@
+import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises";
+
+import { repoRelative, ultragoalDir, ultragoalGoalsPath, ultragoalLedgerPath } from "./paths.js";
+import type { UltragoalLedgerEntry, UltragoalPlan } from "./types.js";
+import { iso, ULTRAGOAL_DIR, ULTRAGOAL_GOALS, ULTRAGOAL_LEDGER, UltragoalError } from "./types.js";
+
+const AGGREGATE_CODEX_OBJECTIVE = `Complete the durable ultragoal plan in ${ULTRAGOAL_DIR}/${ULTRAGOAL_GOALS}, including later accepted/appended stories, under the original brief constraints; use ${ULTRAGOAL_DIR}/${ULTRAGOAL_LEDGER} as the audit trail.`;
+const LEGACY_OBJECTIVE_PREFIX = `Complete all ultragoal stories in ${ULTRAGOAL_DIR}/${ULTRAGOAL_GOALS}: `;
+const LEGACY_OBJECTIVE = `Complete all ultragoal stories listed in ${ULTRAGOAL_DIR}/${ULTRAGOAL_GOALS}. Use ${ULTRAGOAL_DIR}/${ULTRAGOAL_LEDGER} as the durable audit trail.`;
+const locks = new Map<string, Promise<unknown>>();
+
+function hasCode(error: unknown, code: string): boolean {
+ return error instanceof Error && "code" in error && error.code === code;
+}
+
+function isLegacyEnumeratedAggregateObjective(objective: string | undefined): objective is string {
+ return objective === LEGACY_OBJECTIVE || Boolean(objective?.startsWith(LEGACY_OBJECTIVE_PREFIX));
+}
+
+function isSteeringKind(value: unknown): value is UltragoalLedgerEntry["kind"] {
+ return value === "steering_accepted" || value === "steering_rejected" || value === "criteria_revised";
+}
+
+export async function withUltragoalMutationLock<T>(repoRoot: string, fn: () => Promise<T>): Promise<T> {
+ const prior = locks.get(repoRoot) ?? Promise.resolve();
+ const run = prior.then(fn, fn);
+ locks.set(
+ repoRoot,
+ run.catch(() => undefined),
+ );
+ return run;
+}
+
+export async function readUltragoalPlan(repoRoot: string): Promise<UltragoalPlan> {
+ const path = ultragoalGoalsPath(repoRoot);
+ let raw: string;
+ try {
+ raw = await readFile(path, "utf8");
+ } catch (error) {
+ if (!hasCode(error, "ENOENT")) throw error;
+ throw new UltragoalError(
+ `No ultragoal plan found at ${repoRelative(path, repoRoot)}. Run \`omo ultragoal create-goals ...\` first.`,
+ "ULTRAGOAL_PLAN_MISSING",
+ { cause: error },
+ );
+ }
+ const parsed: UltragoalPlan = JSON.parse(raw);
+ if (parsed.version !== 1 || !Array.isArray(parsed.goals)) {
+ throw new UltragoalError(`Invalid ultragoal plan at ${repoRelative(path, repoRoot)}.`, "ULTRAGOAL_PLAN_INVALID");
+ }
+ const previousObjective = parsed.codexObjective;
+ if (
+ (parsed.codexGoalMode ?? "per_story") === "aggregate" &&
+ isLegacyEnumeratedAggregateObjective(previousObjective)
+ ) {
+ const now = iso();
+ parsed.codexObjective = AGGREGATE_CODEX_OBJECTIVE;
+ parsed.codexObjectiveAliases = [...new Set([...(parsed.codexObjectiveAliases ?? []), previousObjective])];
+ parsed.updatedAt = now;
+ await writePlan(repoRoot, parsed);
+ await appendLedger(repoRoot, {
+ at: now,
+ kind: "aggregate_objective_migrated",
+ message: "Migrated legacy enumerated aggregate Codex objective to the stable pointer objective.",
+ before: { codexObjective: previousObjective },
+ after: { codexObjective: parsed.codexObjective },
+ });
+ }
+ return parsed;
+}
+
+export async function writePlan(repoRoot: string, plan: UltragoalPlan): Promise<void> {
+ await mkdir(ultragoalDir(repoRoot), { recursive: true });
+ const path = ultragoalGoalsPath(repoRoot);
+ const tmpPath = `${path}.${process.pid}.${Date.now()}.tmp`;
+ await writeFile(tmpPath, `${JSON.stringify(plan, null, 2)}\n`, "utf8");
+ await rename(tmpPath, path);
+}
+
+export async function appendLedger(repoRoot: string, entry: UltragoalLedgerEntry): Promise<void> {
+ await mkdir(ultragoalDir(repoRoot), { recursive: true });
+ await appendFile(ultragoalLedgerPath(repoRoot), `${JSON.stringify(entry)}\n`, "utf8");
+}
+
+export async function readSteeringLedgerEntries(repoRoot: string): Promise<UltragoalLedgerEntry[]> {
+ let raw: string;
+ try {
+ raw = await readFile(ultragoalLedgerPath(repoRoot), "utf8");
+ } catch (error) {
+ if (hasCode(error, "ENOENT")) return [];
+ throw error;
+ }
+ const entries: UltragoalLedgerEntry[] = [];
+ for (const line of raw.split(/\r?\n/).filter(Boolean)) {
+ const entry: UltragoalLedgerEntry = JSON.parse(line);
+ if (isSteeringKind(entry.kind)) entries.push(entry);
+ }
+ return entries;
+}
diff --git a/plugins/omo/components/ultragoal/src/quality-gate.ts b/plugins/omo/components/ultragoal/src/quality-gate.ts
new file mode 100644
index 00000000..b5e08d41
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/quality-gate.ts
@@ -0,0 +1,102 @@
+import type { UltragoalItem, UltragoalPlan, UltragoalQualityGate } from "./types.js";
+import { UltragoalError } from "./types.js";
+
+const BLOCKER_FIELD_KEYS = "blocker blockerSignature blockerEvidence blockerOccurrences blockedAt".split(" ");
+const URL_PATTERN = /https?:\/\/\S+/g;
+const PUNCTUATION_PATTERN = /[`"'()[\]{}:,;]/g;
+const WHITESPACE_PATTERN = /\s+/g;
+const AUTH_PATTERN = /\b(auth\w*|credential\w*|token|permission\w*|scope\w*|access|unauthorized|forbidden|401|403)\b/;
+const MISSING_PATTERN =
+ /\b(unset|missing|required|requires|without|omit\w*|not set|not available|no read packages|read packages)\b/;
+const GHCR_PATTERN =
+ /\b(ghcr|github container registry|read packages|imagepullsecret|package api|anonymous|container image)\b/;
+const GHCR_401_PATTERN = /\b(401|unauthorized|anonymous pull|authentication required)\b/;
+const GHCR_403_PATTERN = /\b(403|forbidden|read packages|package api)\b/;
+
+function invalid(message: string, field: string): never {
+ throw new UltragoalError(message, "ULTRAGOAL_QUALITY_GATE_INVALID", { details: { field } });
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function section(value: unknown, field: string): Record<string, unknown> {
+ return isRecord(value) ? value : invalid(`Final quality gate is missing ${field} evidence.`, field);
+}
+
+function nonEmptyString(value: unknown, field: string): string {
+ return typeof value === "string" && value.trim() !== ""
+ ? value
+ : invalid(`Final quality gate requires non-empty ${field}.`, field);
+}
+
+function numberField(value: unknown, field: string): number {
+ return typeof value === "number" && Number.isFinite(value)
+ ? value
+ : invalid(`Final quality gate requires numeric ${field}.`, field);
+}
+
+function stringArray(value: unknown, field: string): string[] {
+ if (!Array.isArray(value) || value.length === 0) return invalid(`Final quality gate requires ${field}.`, field);
+ return value.map((item) => nonEmptyString(item, field));
+}
+
+export function validateQualityGate(input: unknown): UltragoalQualityGate {
+ const gate = section(input, "qualityGate");
+ const cleaner = section(gate["aiSlopCleaner"], "aiSlopCleaner");
+ const verification = section(gate["verification"], "verification");
+ const review = section(gate["codeReview"], "codeReview");
+ const coverage = section(gate["criteriaCoverage"], "criteriaCoverage");
+ if (cleaner["status"] !== "passed") invalid("aiSlopCleaner.status must be passed.", "aiSlopCleaner.status");
+ if (verification["status"] !== "passed") invalid("verification.status must be passed.", "verification.status");
+ if (review["recommendation"] !== "APPROVE") invalid("recommendation must be APPROVE.", "codeReview.recommendation");
+ if (review["architectStatus"] !== "CLEAR") invalid("architectStatus must be CLEAR.", "codeReview.architectStatus");
+ const totalCriteria = numberField(coverage["totalCriteria"], "criteriaCoverage.totalCriteria");
+ const passCount = numberField(coverage["passCount"], "criteriaCoverage.passCount");
+ if (passCount < totalCriteria)
+ invalid("criteriaCoverage.passCount must cover totalCriteria.", "criteriaCoverage.passCount");
+ const commands = stringArray(verification["commands"], "verification.commands");
+ const covered = stringArray(coverage["adversarialClassesCovered"], "criteriaCoverage.adversarialClassesCovered");
+ const cleanerEvidence = nonEmptyString(cleaner["evidence"], "aiSlopCleaner.evidence");
+ const verificationEvidence = nonEmptyString(verification["evidence"], "verification.evidence");
+ const reviewEvidence = nonEmptyString(review["evidence"], "codeReview.evidence");
+ const result: UltragoalQualityGate = {
+ aiSlopCleaner: { status: "passed", evidence: cleanerEvidence },
+ verification: { status: "passed", commands, evidence: verificationEvidence },
+ codeReview: { recommendation: "APPROVE", architectStatus: "CLEAR", evidence: reviewEvidence },
+ };
+ Object.assign(result, { criteriaCoverage: { totalCriteria, passCount, adversarialClassesCovered: covered } });
+ return result;
+}
+
+export function normalizeBlockerEvidence(evidence: string): string {
+ const withoutUrls = evidence.toLowerCase().replace(URL_PATTERN, " ");
+ const withoutPunctuation = withoutUrls.replace(PUNCTUATION_PATTERN, " ");
+ return withoutPunctuation.replace(WHITESPACE_PATTERN, " ").trim();
+}
+
+export function classifyExternalAuthorizationBlocker(evidence: string): string | null {
+ const normalized = normalizeBlockerEvidence(evidence);
+ if (!normalized || !AUTH_PATTERN.test(normalized) || !MISSING_PATTERN.test(normalized)) return null;
+ if (!GHCR_PATTERN.test(normalized)) return "EXTERNAL_AUTHORIZATION_REQUIRED";
+ const status401 = GHCR_401_PATTERN.test(normalized) ? "HTTP_401_ANONYMOUS" : null;
+ const status403 = GHCR_403_PATTERN.test(normalized) ? "HTTP_403_NO_READ_PACKAGES" : null;
+ const status = [status401, status403].filter((part): part is string => part !== null).join("+");
+ return `GHCR_PULL_ACCESS:${status || "AUTHORIZATION_REQUIRED"}:GHCR_VISIBILITY_OR_CREDENTIAL_REQUIRED`;
+}
+
+function nestedBlockerSignature(goal: UltragoalItem): string | null {
+ const blocker = Reflect.get(goal, "blocker");
+ const signature = isRecord(blocker) ? blocker["signature"] : null;
+ return typeof signature === "string" ? signature : null;
+}
+
+export function sameBlockerOccurrences(plan: UltragoalPlan, signature: string): number {
+ return plan.goals.filter((goal) => goal.blockerSignature === signature || nestedBlockerSignature(goal) === signature)
+ .length;
+}
+
+export function clearGoalBlockerFields(goal: UltragoalItem): void {
+ for (const key of BLOCKER_FIELD_KEYS) Reflect.deleteProperty(goal, key);
+}
diff --git a/plugins/omo/components/ultragoal/src/review-blockers.ts b/plugins/omo/components/ultragoal/src/review-blockers.ts
new file mode 100644
index 00000000..08fbc18c
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/review-blockers.ts
@@ -0,0 +1,79 @@
+// biome-ignore-all format: compact port must stay within the requested pure LOC budget.
+
+import { readCodexGoalSnapshotInput, reconcileCodexGoalSnapshot } from "./codex-goal-snapshot.js";
+import { codexGoalMode, compatibleCodexObjectives, expectedCodexObjective, isFinalRunCompletionCandidate } from "./goal-status.js";
+import { seedDefaultSuccessCriteria } from "./plan-crud.js";
+import { appendLedger, readUltragoalPlan, withUltragoalMutationLock, writePlan } from "./plan-io.js";
+import type { UltragoalItem, UltragoalLedgerEntry, UltragoalPlan } from "./types.js";
+import { iso, UltragoalError } from "./types.js";
+
+export interface RecordFinalReviewBlockersArgs { readonly goalId: string; readonly title: string; readonly objective: string; readonly evidence: string; readonly codexGoalJson: string }
+export interface RecordFinalReviewBlockersResult { readonly plan: UltragoalPlan; readonly blockedGoal: UltragoalItem; readonly newGoal: UltragoalItem; readonly ledgerEntries: UltragoalLedgerEntry[] }
+
+const BLOCKER_FIELDS = "blockedReason blockerSignature blockerOccurrenceCount requiredExternalDecision nonRetriable failedAt failureReason completedAt blocker blockerEvidence blockerOccurrences blockedAt".split(" ");
+
+function ultragoalError(message: string, code: string): never {
+ throw new UltragoalError(message, code);
+}
+
+function nextGoalId(plan: UltragoalPlan): string {
+ const max = plan.goals.reduce((current, goal) => {
+ const digits = /^G(\d+)/u.exec(goal.id)?.[1];
+ return digits === undefined ? current : Math.max(current, Number(digits));
+ }, 0);
+ return `G${String(max + 1).padStart(3, "0")}`;
+}
+
+function appendBlockerGoal(plan: UltragoalPlan, args: RecordFinalReviewBlockersArgs, now: string): UltragoalItem {
+ const index = plan.goals.length;
+ const goal: UltragoalItem = {
+ id: nextGoalId(plan),
+ title: args.title,
+ objective: args.objective,
+ status: "pending",
+ successCriteria: seedDefaultSuccessCriteria(index, args.objective),
+ attempt: 0,
+ createdAt: now,
+ updatedAt: now,
+ };
+ plan.goals.push(goal);
+ return goal;
+}
+
+export async function recordFinalReviewBlockers(
+ repoRoot: string,
+ args: RecordFinalReviewBlockersArgs,
+): Promise<RecordFinalReviewBlockersResult> {
+ return withUltragoalMutationLock(repoRoot, async () => {
+ const plan = await readUltragoalPlan(repoRoot);
+ const goal = plan.goals.find((candidate) => candidate.id === args.goalId);
+ if (goal === undefined) ultragoalError(`Unknown ultragoal id: ${args.goalId}`, "ultragoal_goal_not_found");
+ if (goal.status !== "in_progress") ultragoalError(`${goal.id} is ${goal.status}.`, "ultragoal_goal_not_in_progress");
+ if (!isFinalRunCompletionCandidate(plan, goal)) ultragoalError(`${goal.id} is not final.`, "ultragoal_not_final_story");
+
+ const snapshot = await readCodexGoalSnapshotInput(args.codexGoalJson, repoRoot);
+ const aggregate = codexGoalMode(plan) === "aggregate";
+ const reconciliation = reconcileCodexGoalSnapshot(snapshot, { expectedObjective: expectedCodexObjective(plan, goal), ...(aggregate ? { acceptedObjectives: compatibleCodexObjectives(plan) } : {}), allowedStatuses: ["active"], requireSnapshot: true, requireComplete: false });
+ if (!reconciliation.ok) ultragoalError(reconciliation.errors.join(" "), "ultragoal_codex_snapshot_mismatch");
+
+ const now = iso();
+ for (const field of BLOCKER_FIELDS) Reflect.deleteProperty(goal, field);
+ goal.status = "review_blocked";
+ goal.reviewBlockedAt = now;
+ goal.evidence = args.evidence;
+ goal.updatedAt = now;
+ if (plan.activeGoalId === goal.id) delete plan.activeGoalId;
+ const newGoal = appendBlockerGoal(plan, args, now);
+ plan.updatedAt = now;
+
+ const codexGoal = reconciliation.snapshot.raw;
+ const blockedEntry: UltragoalLedgerEntry = { at: now, kind: "goal_review_blocked", goalId: goal.id, status: goal.status, evidence: args.evidence, codexGoal };
+ const addedEntry: UltragoalLedgerEntry = { at: now, kind: "goal_added", goalId: newGoal.id, status: newGoal.status, evidence: args.evidence, message: newGoal.title };
+ const summaryEntry: UltragoalLedgerEntry = { at: now, kind: "goal_review_blocked", goalId: goal.id, status: goal.status, evidence: args.evidence, codexGoal, message: `Review blockers recorded; appended ${newGoal.id}.` };
+ Reflect.set(summaryEntry, "kind", "blocker_recorded");
+ const ledgerEntries = [blockedEntry, addedEntry, summaryEntry];
+ await writePlan(repoRoot, plan);
+ for (const entry of ledgerEntries) await appendLedger(repoRoot, entry);
+ return { plan, blockedGoal: goal, newGoal, ledgerEntries };
+ });
+}
diff --git a/plugins/omo/components/ultragoal/src/steering.ts b/plugins/omo/components/ultragoal/src/steering.ts
new file mode 100644
index 00000000..81c151cc
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/steering.ts
@@ -0,0 +1,265 @@
+// biome-ignore-all format: compact steering module must stay below the 240 pure-LOC budget
+import { isUltragoalDone } from "./goal-status.js";
+import { appendLedger, readSteeringLedgerEntries, readUltragoalPlan, withUltragoalMutationLock, writePlan } from "./plan-io.js";
+import type {
+ SteerUltragoalResult,
+ UltragoalItem,
+ UltragoalLedgerEntry,
+ UltragoalPlan,
+ UltragoalSteeringAudit,
+ UltragoalSteeringChildGoal,
+ UltragoalSteeringMutationKind,
+ UltragoalSteeringProposal,
+ UltragoalSteeringSource,
+ UltragoalSuccessCriterionUserModel,
+} from "./types.js";
+import { iso, ULTRAGOAL_STEERING_MUTATION_KINDS, ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS } from "./types.js";
+
+const SOURCES = ["user_prompt_submit", "finding", "cli"] as const satisfies readonly UltragoalSteeringSource[];
+const PROTECTED = new Set(["aggregateCompletion", "codexObjective", "codexObjectiveAliases", "originalConstraints", "qualityGate", "status", "completedAt", "completionStatus"]);
+const isObject = (value: unknown): value is object => typeof value === "object" && value !== null; const isPlain = (value: unknown): value is object => isObject(value) && !Array.isArray(value);
+const read = (value: object, key: string): unknown => Object.entries(value).find(([name]) => name === key)?.[1];
+const isText = (value: unknown): value is string => typeof value === "string" && value.trim().length > 0;
+const text = (value: object, key: string): string | undefined => {
+ const candidate = read(value, key);
+ return isText(candidate) ? candidate.trim() : undefined;
+};
+const isKind = (value: unknown): value is UltragoalSteeringMutationKind => typeof value === "string" && ULTRAGOAL_STEERING_MUTATION_KINDS.some((kind) => kind === value);
+const isSource = (value: unknown): value is UltragoalSteeringSource => typeof value === "string" && SOURCES.some((source) => source === value);
+const isModel = (value: unknown): value is UltragoalSuccessCriterionUserModel => typeof value === "string" && ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS.some((model) => model === value);
+const texts = (value: object, key: string): string[] => {
+ const candidate = read(value, key);
+ return Array.isArray(candidate) && candidate.every((item) => typeof item === "string") ? candidate : [];
+};
+
+function targets(proposal: object): string[] {
+ const many = texts(proposal, "targetGoalIds");
+ const one = text(proposal, "targetGoalId") ?? text(proposal, "goalId");
+ return many.length > 0 ? many : one === undefined ? [] : [one];
+}
+
+const after = (proposal: object): object | undefined => {
+ const candidate = read(proposal, "after");
+ return isPlain(candidate) ? candidate : undefined;
+};
+const revised = (proposal: object, direct: string, nested: string): string | undefined => text(proposal, direct) ?? text(after(proposal) ?? proposal, nested);
+
+function child(value: unknown): UltragoalSteeringChildGoal | null {
+ if (!isPlain(value)) return null;
+ const title = text(value, "title");
+ const objective = text(value, "objective");
+ if (title === undefined || objective === undefined) return null;
+ return { title, objective };
+}
+
+function childValues(proposal: object): unknown[] {
+ const direct = read(proposal, "childGoals");
+ if (Array.isArray(direct) && direct.length > 0) return direct;
+ const nested = after(proposal);
+ const fromAfter = nested === undefined ? undefined : read(nested, "children");
+ return Array.isArray(fromAfter) ? fromAfter : [];
+}
+
+const children = (proposal: object): UltragoalSteeringChildGoal[] => childValues(proposal).map(child).filter((item): item is UltragoalSteeringChildGoal => item !== null);
+const pendingOrder = (proposal: object): string[] => {
+ const direct = texts(proposal, "pendingOrder");
+ return direct.length > 0 ? direct : texts(after(proposal) ?? proposal, "pendingGoalIds");
+};
+
+function hasProtected(value: unknown): boolean {
+ if (!isObject(value)) return false;
+ for (const [key, childValue] of Object.entries(value)) if (PROTECTED.has(key) || key.toLowerCase().includes("complete") || hasProtected(childValue)) return true;
+ return false;
+}
+
+function allText(value: unknown): string {
+ if (typeof value === "string") return value;
+ return isObject(value) ? Object.values(value).map(allText).filter(Boolean).join("\n") : "";
+}
+
+function weakens(value: unknown): boolean {
+ const valueText = allText(value).toLowerCase();
+ return /\b(skip|bypass|weaken|remove|omit|auto[-\s]?complete|mark complete|complete faster)\b/.test(valueText) && /\b(test|tests|verification|review|quality gate|complete|completion)\b/.test(valueText);
+}
+
+function auditFor(proposal: unknown, reasons: string[]): UltragoalSteeringAudit {
+ const object = isPlain(proposal) ? proposal : undefined;
+ const kindRaw = object === undefined ? undefined : read(object, "kind");
+ const sourceRaw = object === undefined ? undefined : read(object, "source");
+ const evidence = object === undefined ? "" : (text(object, "evidence") ?? "");
+ const rationale = object === undefined ? "" : (text(object, "rationale") ?? "");
+ const audit: UltragoalSteeringAudit = { kind: isKind(kindRaw) ? kindRaw : "annotate_ledger", source: isSource(sourceRaw) ? sourceRaw : "cli", targetGoalIds: object === undefined ? [] : targets(object), evidence, rationale, invariant: { accepted: reasons.length === 0, structuralInvariantAccepted: reasons.length === 0, evidenceBackedNecessity: evidence.length > 0 && rationale.length > 0, noEasierCompletion: !weakens(proposal), rejectedReasons: reasons, reasons } };
+ if (object === undefined) return audit;
+ const criterionId = text(object, "criterionId");
+ const directiveText = text(object, "directiveText");
+ const promptSignature = text(object, "promptSignature");
+ const idempotencyKey = text(object, "idempotencyKey");
+ if (criterionId !== undefined) audit.criterionId = criterionId;
+ if (directiveText !== undefined) audit.directiveText = directiveText;
+ if (promptSignature !== undefined) audit.promptSignature = promptSignature;
+ if (idempotencyKey !== undefined) audit.idempotencyKey = idempotencyKey;
+ return audit;
+}
+
+export function validateUltragoalSteeringProposal(plan: UltragoalPlan, proposal: unknown): UltragoalSteeringAudit {
+ const reasons: string[] = [];
+ if (!isPlain(proposal)) reasons.push("proposal must be an object");
+ const object = isPlain(proposal) ? proposal : {};
+ const kind = read(object, "kind");
+ if (!isKind(kind)) reasons.push(`invalid kind: ${String(kind)}`);
+ if (!isSource(read(object, "source"))) reasons.push(`invalid source: ${String(read(object, "source"))}`);
+ if (text(object, "evidence") === undefined) reasons.push("missing evidence");
+ if (text(object, "rationale") === undefined) reasons.push("missing rationale");
+ if (hasProtected(proposal)) reasons.push("protected payload");
+ if (weakens(proposal)) reasons.push("weakened completion");
+ if (isUltragoalDone(plan)) reasons.push("plan already complete");
+ if (isKind(kind)) validateKind(plan, object, kind, reasons);
+ return auditFor(proposal, reasons);
+}
+
+function goal(plan: UltragoalPlan, id: string | undefined): UltragoalItem | undefined {
+ return id === undefined ? undefined : plan.goals.find((item) => item.id === id);
+}
+
+function validateKind(plan: UltragoalPlan, proposal: object, kind: UltragoalSteeringMutationKind, reasons: string[]): void {
+ const target = goal(plan, targets(proposal)[0]);
+ if (kind === "add_subgoal" && (text(proposal, "title") === undefined || text(proposal, "objective") === undefined)) reasons.push("add_subgoal requires title/objective");
+ if ((kind === "split_subgoal" || kind === "revise_pending_wording" || kind === "mark_blocked_superseded") && target === undefined) reasons.push(`${kind} requires target`);
+ if ((kind === "split_subgoal" || kind === "revise_pending_wording") && target !== undefined && target.status !== "pending") reasons.push(`${kind} requires pending target`);
+ const rawChildren = childValues(proposal);
+ if (kind === "split_subgoal" && rawChildren.length === 0) reasons.push("split_subgoal requires children");
+ if ((kind === "split_subgoal" || kind === "mark_blocked_superseded") && rawChildren.some((item) => child(item) === null)) reasons.push(`${kind} children require title/objective`);
+ if (kind === "reorder_pending") validateOrder(plan, proposal, reasons);
+ if (kind === "revise_pending_wording" && revised(proposal, "revisedTitle", "title") === undefined && revised(proposal, "revisedObjective", "objective") === undefined) reasons.push("revise_pending_wording requires update");
+ if (kind === "revise_criterion") validateCriterion(plan, proposal, reasons);
+}
+
+function validateOrder(plan: UltragoalPlan, proposal: object, reasons: string[]): void {
+ const requested = pendingOrder(proposal);
+ const pending = plan.goals.filter((item) => item.status === "pending" && item.steeringStatus === undefined).map((item) => item.id);
+ if (requested.length === 0) reasons.push("reorder_pending requires ids");
+ if (new Set(requested).size !== requested.length) reasons.push("duplicate pending id");
+ if (requested.some((id) => !pending.includes(id))) reasons.push("unknown pending id");
+}
+
+function validateCriterion(plan: UltragoalPlan, proposal: object, reasons: string[]): void {
+ const target = goal(plan, targets(proposal)[0]);
+ const criterionId = text(proposal, "criterionId");
+ if (target === undefined) reasons.push("revise_criterion requires goalId");
+ else if (criterionId === undefined || target.successCriteria.every((item) => item.id !== criterionId)) reasons.push("revise_criterion requires criterionId");
+ const model = read(proposal, "userModel");
+ if (read(proposal, "scenario") === undefined && read(proposal, "expectedEvidence") === undefined && model === undefined) reasons.push("revise_criterion requires update");
+ if (model !== undefined && !isModel(model)) reasons.push("invalid userModel");
+}
+
+function nextId(plan: UltragoalPlan, offset: number): string {
+ const max = plan.goals.reduce((current, item) => {
+ const digits = /^G(\d+)$/u.exec(item.id)?.[1];
+ return digits === undefined ? current : Math.max(current, Number(digits));
+ }, 0);
+ return `G${String(max + offset).padStart(3, "0")}`;
+}
+
+function makeGoal(plan: UltragoalPlan, childGoal: UltragoalSteeringChildGoal, evidence: string, now: string, offset: number): UltragoalItem {
+ return { id: nextId(plan, offset), title: childGoal.title, objective: childGoal.objective, status: "pending", successCriteria: [], attempt: 0, createdAt: now, updatedAt: now, evidence };
+}
+
+export function applySteeringMutation(plan: UltragoalPlan, proposal: UltragoalSteeringProposal, audit: UltragoalSteeringAudit): UltragoalPlan {
+ const next = structuredClone(plan);
+ if (!audit.invariant.accepted) return next;
+ const now = proposal.now?.toISOString() ?? iso();
+ if (proposal.kind === "add_subgoal") next.goals.push(makeGoal(next, { title: proposal.title ?? "", objective: proposal.objective ?? "" }, proposal.evidence, now, 1));
+ if (proposal.kind === "reorder_pending") {
+ const order = pendingOrder(proposal);
+ next.goals = [...order.map((id) => goal(next, id)).filter((item): item is UltragoalItem => item !== undefined), ...next.goals.filter((item) => !order.includes(item.id))];
+ }
+ if (proposal.kind === "revise_pending_wording") reviseWording(next, proposal, now);
+ if (proposal.kind === "split_subgoal" || proposal.kind === "mark_blocked_superseded") splitOrBlock(next, proposal, now);
+ if (proposal.kind === "revise_criterion") reviseCriterion(next, proposal, now);
+ if (proposal.kind !== "annotate_ledger") next.updatedAt = now;
+ return next;
+}
+
+function reviseWording(plan: UltragoalPlan, proposal: UltragoalSteeringProposal, now: string): void {
+ const target = goal(plan, targets(proposal)[0]);
+ if (target === undefined) return;
+ target.title = revised(proposal, "revisedTitle", "title") ?? target.title;
+ target.objective = revised(proposal, "revisedObjective", "objective") ?? target.objective;
+ target.steeringEvidence = proposal.evidence;
+ target.steeringRationale = proposal.rationale;
+ target.updatedAt = now;
+}
+
+function splitOrBlock(plan: UltragoalPlan, proposal: UltragoalSteeringProposal, now: string): void {
+ const target = goal(plan, targets(proposal)[0]);
+ if (target === undefined) return;
+ const replacements = children(proposal).map((item, index) => makeGoal(plan, item, proposal.evidence, now, index + 1));
+ target.steeringEvidence = proposal.evidence;
+ target.steeringRationale = proposal.rationale;
+ target.updatedAt = now;
+ if (replacements.length === 0) {
+ target.status = "blocked";
+ target.steeringStatus = "blocked";
+ target.blockedReason = proposal.blockedReason ?? proposal.rationale;
+ } else {
+ target.steeringStatus = "superseded";
+ target.supersededBy = replacements.map((item) => item.id);
+ for (const item of replacements) item.supersedes = [target.id];
+ plan.goals.splice(plan.goals.indexOf(target) + 1, 0, ...replacements);
+ }
+ if (plan.activeGoalId === target.id) delete plan.activeGoalId;
+}
+
+function reviseCriterion(plan: UltragoalPlan, proposal: UltragoalSteeringProposal, now: string): void {
+ const target = goal(plan, targets(proposal)[0]);
+ const index = target?.successCriteria.findIndex((item) => item.id === proposal.criterionId) ?? -1;
+ const current = target?.successCriteria[index];
+ if (target === undefined || current === undefined) return;
+ const model = read(proposal, "userModel");
+ target.successCriteria[index] = { ...current, scenario: text(proposal, "scenario") ?? current.scenario, expectedEvidence: text(proposal, "expectedEvidence") ?? current.expectedEvidence, userModel: isModel(model) ? model : current.userModel };
+ target.updatedAt = now;
+}
+
+function isProposal(value: unknown): value is UltragoalSteeringProposal {
+ return isPlain(value) && isKind(read(value, "kind")) && isSource(read(value, "source")) && isText(read(value, "evidence")) && isText(read(value, "rationale"));
+}
+
+export function parseUltragoalSteeringDirective(text: string): UltragoalSteeringProposal | null {
+ const match = /(?:^|\s)(?:OMO_ULTRAGOAL_STEER|omo\.ultragoal\.steer|omo ultragoal steer):\s*([\s\S]+)$/u.exec(text);
+ if (match?.[1] === undefined) return null;
+ try {
+ const parsed: unknown = JSON.parse(match[1].trim());
+ return isProposal(parsed) ? parsed : null;
+ } catch (error) {
+ if (error instanceof SyntaxError) return null;
+ throw error;
+ }
+}
+
+export async function steerUltragoal(repoRoot: string, proposal: UltragoalSteeringProposal): Promise<SteerUltragoalResult> {
+ return withUltragoalMutationLock(repoRoot, async () => {
+ const plan = await readUltragoalPlan(repoRoot);
+ const key = proposal.idempotencyKey ?? proposal.promptSignature;
+ const prior = key === undefined ? undefined : (await readSteeringLedgerEntries(repoRoot)).find((entry) => entry.steering?.invariant.accepted === true && (entry.idempotencyKey === key || entry.steering.idempotencyKey === key || entry.steering.promptSignature === key));
+ if (prior?.steering !== undefined) return { plan, accepted: true, audit: { ...prior.steering, deduped: true }, rejectedReasons: [], deduped: true };
+ const audit = validateUltragoalSteeringProposal(plan, proposal);
+ const accepted = audit.invariant.accepted;
+ const next = accepted ? applySteeringMutation(plan, proposal, audit) : plan;
+ const finalAudit: UltragoalSteeringAudit = { ...audit, before: plan };
+ if (accepted) finalAudit.after = next;
+ if (accepted) await writePlan(repoRoot, next);
+ await appendLedger(repoRoot, ledgerEntry(proposal, finalAudit, proposal.now?.toISOString() ?? iso()));
+ return { plan: next, accepted, audit: finalAudit, rejectedReasons: audit.invariant.rejectedReasons, deduped: false };
+ });
+}
+
+function ledgerEntry(proposal: UltragoalSteeringProposal, audit: UltragoalSteeringAudit, at: string): UltragoalLedgerEntry {
+ const entry: UltragoalLedgerEntry = { at, kind: audit.invariant.accepted ? (proposal.kind === "revise_criterion" ? "criteria_revised" : "steering_accepted") : "steering_rejected", evidence: proposal.evidence, message: proposal.rationale, steering: audit, mutationKind: proposal.kind };
+ const goalId = audit.targetGoalIds[0];
+ if (goalId !== undefined) entry.goalId = goalId;
+ if (proposal.criterionId !== undefined) entry.criterionId = proposal.criterionId;
+ if (proposal.idempotencyKey !== undefined) entry.idempotencyKey = proposal.idempotencyKey;
+ if (audit.before !== undefined) entry.before = audit.before;
+ if (audit.after !== undefined) entry.after = audit.after;
+ return entry;
+}
diff --git a/plugins/omo/components/ultragoal/src/types.ts b/plugins/omo/components/ultragoal/src/types.ts
new file mode 100644
index 00000000..d065e672
--- /dev/null
+++ b/plugins/omo/components/ultragoal/src/types.ts
@@ -0,0 +1,277 @@
+export const ULTRAGOAL_DIR = ".omo/ultragoal";
+export const ULTRAGOAL_BRIEF = "brief.md";
+export const ULTRAGOAL_GOALS = "goals.json";
+export const ULTRAGOAL_LEDGER = "ledger.jsonl";
+
+export type UltragoalStatus =
+ | "pending"
+ | "in_progress"
+ | "complete"
+ | "failed"
+ | "blocked"
+ | "review_blocked"
+ | "needs_user_decision";
+
+export type UltragoalCodexGoalMode = "aggregate" | "per_story";
+
+export type UltragoalSteeringStatus = "superseded" | "blocked";
+
+export const ULTRAGOAL_STEERING_MUTATION_KINDS = [
+ "add_subgoal",
+ "split_subgoal",
+ "reorder_pending",
+ "revise_pending_wording",
+ "revise_criterion",
+ "annotate_ledger",
+ "mark_blocked_superseded",
+] as const satisfies readonly string[];
+export type UltragoalSteeringMutationKind = (typeof ULTRAGOAL_STEERING_MUTATION_KINDS)[number];
+
+export type UltragoalSteeringSource = "user_prompt_submit" | "finding" | "cli";
+
+export const ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS = [
+ "happy",
+ "edge",
+ "regression",
+ "adversarial",
+] as const satisfies readonly string[];
+export type UltragoalSuccessCriterionUserModel = (typeof ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS)[number];
+
+export const ULTRAGOAL_CRITERION_STATUSES = ["pending", "pass", "fail", "blocked"] as const satisfies readonly string[];
+export type UltragoalCriterionStatus = (typeof ULTRAGOAL_CRITERION_STATUSES)[number];
+
+export const ULTRAGOAL_LEDGER_EVENT_KINDS = [
+ "plan_created",
+ "goal_started",
+ "goal_resumed",
+ "goal_completed",
+ "goal_blocked",
+ "goal_failed",
+ "goal_needs_user_decision",
+ "goal_retried",
+ "aggregate_completed",
+ "aggregate_objective_migrated",
+ "goal_added",
+ "steering_accepted",
+ "steering_rejected",
+ "final_review_failed",
+ "goal_review_blocked",
+ "evidence_captured",
+ "criterion_failed",
+ "criterion_blocked",
+ "criteria_revised",
+] as const satisfies readonly string[];
+export type UltragoalLedgerEventKind = (typeof ULTRAGOAL_LEDGER_EVENT_KINDS)[number];
+
+export interface UltragoalSuccessCriterion {
+ readonly id: string;
+ readonly scenario: string;
+ readonly userModel: UltragoalSuccessCriterionUserModel;
+ readonly expectedEvidence: string;
+ capturedEvidence: string | null;
+ status: UltragoalCriterionStatus;
+ capturedAt?: string;
+ notes?: string;
+}
+
+export interface UltragoalSteeringInvariantResult {
+ accepted: boolean;
+ structuralInvariantAccepted: boolean;
+ evidenceBackedNecessity: boolean;
+ noEasierCompletion: boolean;
+ rejectedReasons: string[];
+ reasons?: string[];
+}
+
+export interface UltragoalSteeringChildGoal {
+ title: string;
+ objective: string;
+}
+
+export interface UltragoalSteeringAfterPayload {
+ title?: string;
+ objective?: string;
+ pendingGoalIds?: string[];
+ children?: UltragoalSteeringChildGoal[];
+}
+
+export interface UltragoalSteeringProposal {
+ kind: UltragoalSteeringMutationKind;
+ source: UltragoalSteeringSource;
+ targetGoalId?: string;
+ targetGoalIds?: string[];
+ criterionId?: string;
+ evidence: string;
+ rationale: string;
+ title?: string;
+ objective?: string;
+ childGoals?: UltragoalSteeringChildGoal[];
+ revisedTitle?: string;
+ revisedObjective?: string;
+ pendingOrder?: string[];
+ blockedReason?: string;
+ after?: UltragoalSteeringAfterPayload;
+ directiveText?: string;
+ promptSignature?: string;
+ idempotencyKey?: string;
+ now?: Date;
+}
+
+export interface UltragoalSteeringAudit {
+ kind: UltragoalSteeringMutationKind;
+ source: UltragoalSteeringSource;
+ targetGoalIds: string[];
+ criterionId?: string;
+ before?: unknown;
+ after?: unknown;
+ evidence: string;
+ rationale: string;
+ invariant: UltragoalSteeringInvariantResult;
+ directiveText?: string;
+ promptSignature?: string;
+ idempotencyKey?: string;
+ deduped?: boolean;
+}
+
+export interface SteerUltragoalResult {
+ plan: UltragoalPlan;
+ accepted: boolean;
+ audit: UltragoalSteeringAudit;
+ rejectedReasons: string[];
+ deduped: boolean;
+}
+
+export interface UltragoalItem {
+ id: string;
+ title: string;
+ objective: string;
+ status: UltragoalStatus;
+ successCriteria: UltragoalSuccessCriterion[];
+ attempt: number;
+ createdAt: string;
+ updatedAt: string;
+ startedAt?: string;
+ completedAt?: string;
+ failedAt?: string;
+ reviewBlockedAt?: string;
+ evidence?: string;
+ failureReason?: string;
+ steeringStatus?: UltragoalSteeringStatus;
+ supersededBy?: string[];
+ supersedes?: string[];
+ blockedReason?: string;
+ blockerSignature?: string;
+ blockerOccurrenceCount?: number;
+ requiredExternalDecision?: string;
+ nonRetriable?: boolean;
+ steeringEvidence?: string;
+ steeringRationale?: string;
+}
+
+export interface UltragoalAggregateCompletion {
+ status: "complete";
+ completedAt: string;
+ evidence: string;
+ codexGoal?: unknown;
+}
+
+export interface UltragoalPlan {
+ version: 1;
+ createdAt: string;
+ updatedAt: string;
+ briefPath: string;
+ goalsPath: string;
+ ledgerPath: string;
+ codexGoalMode?: UltragoalCodexGoalMode;
+ codexObjective?: string;
+ codexObjectiveAliases?: string[];
+ aggregateCompletion?: UltragoalAggregateCompletion;
+ activeGoalId?: string;
+ goals: UltragoalItem[];
+}
+
+export interface UltragoalLedgerEntry {
+ at: string;
+ kind: UltragoalLedgerEventKind;
+ goalId?: string;
+ criterionId?: string;
+ status?: UltragoalStatus;
+ criterionStatus?: UltragoalCriterionStatus;
+ message?: string;
+ codexGoal?: unknown;
+ evidence?: string;
+ capturedEvidence?: string;
+ qualityGate?: UltragoalQualityGate;
+ steering?: UltragoalSteeringAudit;
+ before?: unknown;
+ after?: unknown;
+ mutationKind?: UltragoalSteeringMutationKind;
+ idempotencyKey?: string;
+ blockerSignature?: string;
+ blockerOccurrenceCount?: number;
+ requiredExternalDecision?: string;
+}
+
+export interface CreateUltragoalOptions {
+ brief: string;
+ goals?: Array<{ title?: string; objective: string }>;
+ codexGoalMode?: UltragoalCodexGoalMode;
+ now?: Date;
+ force?: boolean;
+}
+
+export interface StartNextOptions {
+ now?: Date;
+ retryFailed?: boolean;
+}
+
+export interface CheckpointOptions {
+ goalId: string;
+ status: Extract<UltragoalStatus, "complete" | "failed"> | "blocked";
+ evidence?: string;
+ codexGoal?: unknown;
+ qualityGate?: unknown;
+ allowActiveFinalCodexGoal?: boolean;
+ now?: Date;
+}
+
+export interface AddUltragoalGoalOptions {
+ title: string;
+ objective: string;
+ evidence?: string;
+ now?: Date;
+}
+
+export interface RecordFinalReviewBlockersOptions extends AddUltragoalGoalOptions {
+ goalId: string;
+ codexGoal?: unknown;
+}
+
+export interface UltragoalQualityGate {
+ aiSlopCleaner: { status: "passed"; evidence: string };
+ verification: { status: "passed"; commands: string[]; evidence: string };
+ codeReview: { recommendation: "APPROVE"; architectStatus: "CLEAR"; evidence: string };
+}
+
+export interface UltragoalErrorOptions {
+ readonly cause?: unknown;
+ readonly details?: Record<string, unknown>;
+}
+
+export class UltragoalError extends Error {
+ readonly code: string;
+ readonly details?: Record<string, unknown>;
+
+ constructor(message: string, code: string, opts?: UltragoalErrorOptions) {
+ super(message, opts?.cause === undefined ? undefined : { cause: opts.cause });
+ this.name = "UltragoalError";
+ this.code = code;
+ if (opts?.details !== undefined) {
+ this.details = opts.details;
+ }
+ }
+}
+
+export function iso(): string {
+ return new Date().toISOString();
+}
diff --git a/plugins/omo/components/ultragoal/test/checkpoint.test.ts b/plugins/omo/components/ultragoal/test/checkpoint.test.ts
new file mode 100644
index 00000000..8bd8031a
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/checkpoint.test.ts
@@ -0,0 +1,213 @@
+// biome-ignore-all format: keep the single mandated checkpoint spec under the pure LOC budget.
+import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { checkpointUltragoal } from "../src/checkpoint.js";
+import { ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";
+import { ultragoalBriefPath, ultragoalDir, ultragoalLedgerPath } from "../src/paths.js";
+import { writePlan } from "../src/plan-io.js";
+import type { UltragoalItem, UltragoalLedgerEntry, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";
+import { UltragoalError } from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+const QUALITY_GATE_PATH = join(process.cwd(), "test", "fixtures", "sample-quality-gate.json");
+
+function criterion(id: string, status: UltragoalSuccessCriterion["status"]): UltragoalSuccessCriterion {
+ return { id, scenario: `${id} scenario`, userModel: "happy", expectedEvidence: `${id} proof`, capturedEvidence: status === "pass" ? `${id} passed` : null, status };
+}
+
+function goal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {
+ return { id: "G001", title: "Build auth", objective: "Implement JWT auth endpoint", status: "in_progress", successCriteria: [criterion("C001", "pass"), criterion("C002", "pass"), criterion("C003", "pass")], attempt: 1, createdAt: NOW, updatedAt: NOW, ...overrides };
+}
+
+function plan(goals: UltragoalItem[], overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {
+ const result: UltragoalPlan = { version: 1, createdAt: NOW, updatedAt: NOW, briefPath: ".omo/ultragoal/brief.md", goalsPath: ".omo/ultragoal/goals.json", ledgerPath: ".omo/ultragoal/ledger.jsonl", codexGoalMode: "aggregate", codexObjective: ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE, goals };
+ Object.assign(result, overrides);
+ const activeGoalId = goals.find((candidate) => candidate.status === "in_progress")?.id;
+ if (result.activeGoalId === undefined && activeGoalId !== undefined) result.activeGoalId = activeGoalId;
+ return result;
+}
+
+async function samplePlan(overrides: Partial<UltragoalPlan> = {}): Promise<UltragoalPlan> {
+ const fixture: UltragoalPlan = JSON.parse(await readFile(new URL("./fixtures/sample-plan.json", import.meta.url), "utf8"));
+ return plan(fixture.goals.map((item, index) => goal({ ...item, attempt: index + 1, createdAt: NOW, updatedAt: NOW })), overrides);
+}
+
+async function repoWith(seed: UltragoalPlan): Promise<string> {
+ const repo = await mkdtemp(join(tmpdir(), "ug-checkpoint-"));
+ await mkdir(ultragoalDir(repo), { recursive: true });
+ await writePlan(repo, seed);
+ return repo;
+}
+
+function snapshot(status: "active" | "complete", objective = ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE): string {
+ return JSON.stringify({ goal: { objective, status } });
+}
+
+async function lastLedger(repo: string): Promise<UltragoalLedgerEntry> {
+ const last = (await readFile(ultragoalLedgerPath(repo), "utf8")).trim().split(/\r?\n/).at(-1);
+ if (last === undefined) throw new Error("expected ledger entry");
+ const entry: UltragoalLedgerEntry = JSON.parse(last);
+ return entry;
+}
+
+async function expectCode(action: () => Promise<unknown>, code: string): Promise<void> {
+ try {
+ await action();
+ } catch (error) {
+ expect(error).toBeInstanceOf(UltragoalError);
+ if (!(error instanceof UltragoalError)) throw error;
+ expect(error.code).toBe(code);
+ return;
+ }
+ throw new Error("Expected UltragoalError");
+}
+
+function passGoal(id: string, overrides: Partial<UltragoalItem> = {}): UltragoalItem {
+ return goal({ id, successCriteria: [criterion("C001", "pass"), criterion("C002", "pass"), criterion("C003", "pass")], ...overrides });
+}
+
+describe("checkpointUltragoal status=complete criteria gate", () => {
+ it("THROWS ultragoal_criteria_not_all_pass when any criterion is pending", async () => {
+ const repo = await repoWith(await samplePlan({ goals: [goal({ successCriteria: [criterion("C001", "pass"), criterion("C002", "pending"), criterion("C003", "pass")] })] }));
+ await expectCode(() => checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "done" }), "ultragoal_criteria_not_all_pass");
+ });
+
+ it("THROWS when any criterion is fail or blocked", async () => {
+ for (const status of ["fail", "blocked"] satisfies UltragoalSuccessCriterion["status"][]) {
+ const repo = await repoWith(plan([goal({ successCriteria: [criterion("C001", "pass"), criterion("C002", status), criterion("C003", "pass")] })]));
+ await expectCode(() => checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "done" }), "ultragoal_criteria_not_all_pass");
+ }
+ });
+
+ it("THROWS when criteria list is empty", async () => {
+ const repo = await repoWith(plan([goal({ successCriteria: [] }), goal({ id: "G002", status: "pending" })]));
+ await expectCode(() => checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "done", codexGoalJson: snapshot("active") }), "ultragoal_criteria_not_all_pass");
+ });
+
+ it("ACCEPTS complete when ALL criteria pass (with valid snapshot)", async () => {
+ const repo = await repoWith(plan([passGoal("G001"), goal({ id: "G002", status: "pending" })]));
+ const result = await checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "implementation done and tests passed", codexGoalJson: snapshot("active") });
+ expect(result.goal.status).toBe("complete");
+ expect((await lastLedger(repo)).kind).toBe("goal_completed");
+ });
+});
+
+describe("checkpointUltragoal reconciliation (status=complete)", () => {
+ it("succeeds when snapshot objective matches expected (aggregate active)", async () => {
+ const repo = await repoWith(plan([passGoal("G001"), goal({ id: "G002", status: "pending" })]));
+ await expect(checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "work complete and validation passed", codexGoalJson: snapshot("active") })).resolves.toMatchObject({ goal: { status: "complete" } });
+ });
+
+ it("throws on mismatched objective", async () => {
+ const repo = await repoWith(plan([passGoal("G001"), goal({ id: "G002", status: "pending" })]));
+ await expectCode(() => checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "work complete and validation passed", codexGoalJson: snapshot("active", "wrong objective") }), "ultragoal_codex_snapshot_mismatch");
+ });
+
+ it("throws on mismatched status (snapshot complete when expected active)", async () => {
+ const repo = await repoWith(plan([passGoal("G001"), goal({ id: "G002", status: "pending" })]));
+ await expectCode(() => checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "work complete and validation passed", codexGoalJson: snapshot("complete") }), "ultragoal_codex_snapshot_mismatch");
+ });
+});
+
+describe("checkpointUltragoal final story", () => {
+ it("requires quality-gate-json for the final goal complete", async () => {
+ const repo = await repoWith(plan([passGoal("G001", { status: "complete" }), passGoal("G002")], { activeGoalId: "G002" }));
+ await expectCode(() => checkpointUltragoal(repo, { goalId: "G002", status: "complete", evidence: "final work complete and validation passed", codexGoalJson: snapshot("complete") }), "ULTRAGOAL_QUALITY_GATE_INVALID");
+ });
+
+ it("accepts final story when quality gate JSON includes valid criteriaCoverage", async () => {
+ const repo = await repoWith(plan([passGoal("G001", { status: "complete" }), passGoal("G002")], { activeGoalId: "G002" }));
+ const result = await checkpointUltragoal(repo, { goalId: "G002", status: "complete", evidence: "final work complete and validation passed", codexGoalJson: snapshot("complete"), qualityGateJson: QUALITY_GATE_PATH });
+ expect(result.aggregateCompletion?.status).toBe("complete");
+ expect(result.plan.aggregateCompletion?.status).toBe("complete");
+ });
+
+ it("ACCEPTS complete when task-scoped completed Codex objective maps to the ultragoal brief", async () => {
+ const taskObjective = "Fix ultragoal objective mismatch and install local ulw";
+ const repo = await repoWith(plan([passGoal("G001")], { activeGoalId: "G001" }));
+ await writeFile(ultragoalBriefPath(repo), `${taskObjective}\n`, "utf8");
+
+ const result = await checkpointUltragoal(repo, {
+ goalId: "G001",
+ status: "complete",
+ evidence: "final implementation complete and quality gate passed",
+ codexGoalJson: snapshot("complete", taskObjective),
+ qualityGateJson: QUALITY_GATE_PATH,
+ });
+
+ expect(result.aggregateCompletion?.status).toBe("complete");
+ expect(result.ledgerEntry.kind).toBe("aggregate_completed");
+ });
+
+ it("explains final task-scoped objective mapping when completed Codex objective is unrelated", async () => {
+ const repo = await repoWith(plan([passGoal("G001")], { activeGoalId: "G001" }));
+ await writeFile(ultragoalBriefPath(repo), "Fix ultragoal objective mismatch and install local ulw\n", "utf8");
+
+ await expect(
+ checkpointUltragoal(repo, {
+ goalId: "G001",
+ status: "complete",
+ evidence: "final implementation complete and quality gate passed",
+ codexGoalJson: snapshot("complete", "unrelated completed task"),
+ qualityGateJson: QUALITY_GATE_PATH,
+ }),
+ ).rejects.toThrow("Final task-scoped aggregate reconciliation");
+ });
+});
+
+describe("checkpointUltragoal status=failed", () => {
+ it("sets goal.status=failed, goal.failedAt, appends ledger", async () => {
+ const repo = await repoWith(plan([goal({ successCriteria: [criterion("C001", "pending")] })]));
+ const result = await checkpointUltragoal(repo, { goalId: "G001", status: "failed", evidence: "tests failed" });
+ expect(result.goal.status).toBe("failed");
+ expect(result.goal.failedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/u);
+ expect((await lastLedger(repo)).kind).toBe("goal_failed");
+ });
+
+ it("classifies external authorization blocker signatures", async () => {
+ const repo = await repoWith(plan([goal()]));
+ const result = await checkpointUltragoal(repo, { goalId: "G001", status: "failed", evidence: "ghcr.io returned 401 authentication required because token missing" });
+ expect(result.goal.blockerSignature).toBe("GHCR_PULL_ACCESS:HTTP_401_ANONYMOUS:GHCR_VISIBILITY_OR_CREDENTIAL_REQUIRED");
+ });
+
+ it("after 3 same-signature blockers, marks needs_user_decision + nonRetriable", async () => {
+ const repo = await repoWith(plan([goal({ id: "G001", status: "failed", blockerSignature: "EXTERNAL_AUTHORIZATION_REQUIRED" }), goal({ id: "G002", status: "blocked", blockerSignature: "EXTERNAL_AUTHORIZATION_REQUIRED" }), goal({ id: "G003" })], { activeGoalId: "G003" }));
+ const result = await checkpointUltragoal(repo, { goalId: "G003", status: "failed", evidence: "Registry returned 401 because credentials are missing" });
+ expect(result.goal.status).toBe("needs_user_decision");
+ expect(result.goal.nonRetriable).toBe(true);
+ });
+
+ it("skips the criteria gate for failed status", async () => {
+ const repo = await repoWith(plan([goal({ successCriteria: [criterion("C001", "pending")] })]));
+ await expect(checkpointUltragoal(repo, { goalId: "G001", status: "failed", evidence: "not done" })).resolves.toMatchObject({ goal: { status: "failed" } });
+ });
+});
+
+describe("checkpointUltragoal status=blocked", () => {
+ it("preserves blocker fields + appends ledger", async () => {
+ const repo = await repoWith(plan([goal()]));
+ const result = await checkpointUltragoal(repo, { goalId: "G001", status: "blocked", evidence: "ghcr.io requires token and credentials are missing" });
+ expect(result.goal.status).toBe("blocked");
+ expect(result.goal.blockedReason).toContain("ghcr.io");
+ expect(result.goal.blockerSignature).toContain("GHCR_PULL_ACCESS");
+ expect((await lastLedger(repo)).kind).toBe("goal_blocked");
+ });
+
+ it("skips the criteria gate for blocked status", async () => {
+ const repo = await repoWith(plan([goal({ successCriteria: [criterion("C001", "pending")] })]));
+ await expect(checkpointUltragoal(repo, { goalId: "G001", status: "blocked", evidence: "waiting for approval" })).resolves.toMatchObject({ goal: { status: "blocked" } });
+ });
+});
+
+describe("checkpointUltragoal rebrand", () => {
+ it("does not emit legacy brand token in any returned text or ledger payload", async () => {
+ const repo = await repoWith(plan([passGoal("G001"), goal({ id: "G002", status: "pending" })]));
+ const result = await checkpointUltragoal(repo, { goalId: "G001", status: "complete", evidence: "implementation done in .omo/ultragoal/goals.json for G001 and validation passed", codexGoalJson: snapshot("active") });
+ const forbidden = ["o", "m", "x"].join("");
+ const payload = `${JSON.stringify(result)}\n${await readFile(ultragoalLedgerPath(repo), "utf8")}`.toLowerCase();
+ expect(payload).not.toContain(forbidden);
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/cli-commands.test.ts b/plugins/omo/components/ultragoal/test/cli-commands.test.ts
new file mode 100644
index 00000000..6a641886
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/cli-commands.test.ts
@@ -0,0 +1,274 @@
+import { mkdtemp, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ultragoalCommand } from "../src/cli-commands.ts";
+import { ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";
+
+let testDir: string;
+let out: string[];
+let err: string[];
+
+beforeEach(async () => {
+ testDir = await mkdtemp(join(tmpdir(), "ug-cli-"));
+ out = [];
+ err = [];
+ vi.spyOn(process, "cwd").mockReturnValue(testDir);
+ vi.spyOn(process.stdout, "write").mockImplementation((chunk: string | Uint8Array): boolean => {
+ out.push(chunk.toString());
+ return true;
+ });
+ vi.spyOn(process.stderr, "write").mockImplementation((chunk: string | Uint8Array): boolean => {
+ err.push(chunk.toString());
+ return true;
+ });
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await rm(testDir, { recursive: true, force: true });
+});
+
+function resetOutput(): void {
+ out = [];
+ err = [];
+}
+function stdoutJson(): Record<string, unknown> {
+ return JSON.parse(out.join(""));
+}
+function codexSnapshot(status: "active" | "complete" = "active"): string {
+ return JSON.stringify({ goal: { objective: ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE, status } });
+}
+
+async function createPlan(brief = "- Goal A\n- Goal B"): Promise<Record<string, unknown>> {
+ resetOutput();
+ expect(await ultragoalCommand(["create-goals", "--brief", brief, "--json"])).toBe(0);
+ const parsed = stdoutJson();
+ resetOutput();
+ return parsed;
+}
+
+async function passCriterion(goalId: string, criterionId: string): Promise<void> {
+ expect(
+ await ultragoalCommand([
+ "record-evidence",
+ "--goal-id",
+ goalId,
+ "--criterion-id",
+ criterionId,
+ "--status",
+ "pass",
+ "--evidence",
+ `${criterionId} observable proof`,
+ ]),
+ ).toBe(0);
+ resetOutput();
+}
+
+describe("ultragoalCommand help", () => {
+ it("prints usage when no subcommand", async () => {
+ expect(await ultragoalCommand([])).toBe(0);
+ expect(out.join("")).toContain("omo ultragoal");
+ });
+});
+
+describe("ultragoalCommand create-goals", () => {
+ it("creates plan + writes 3 artifacts + seeds criteria per goal", async () => {
+ const code = await ultragoalCommand(["create-goals", "--brief", "- Goal A\n- Goal B", "--json"]);
+
+ expect(code).toBe(0);
+ const parsed = stdoutJson();
+ expect(parsed).toMatchObject({ ok: true });
+ expect(parsed).toHaveProperty("plan.goals.0.successCriteria.0.id", "C001");
+ expect(await readFile(join(testDir, ".omo/ultragoal/brief.md"), "utf8")).toContain("Goal A");
+ expect(await readFile(join(testDir, ".omo/ultragoal/goals.json"), "utf8")).toContain("successCriteria");
+ expect(await readFile(join(testDir, ".omo/ultragoal/ledger.jsonl"), "utf8")).toContain("plan_created");
+ });
+});
+
+describe("ultragoalCommand status", () => {
+ it("prints plan summary including criteria counts", async () => {
+ await createPlan();
+
+ expect(await ultragoalCommand(["status"])).toBe(0);
+ expect(out.join("")).toContain("criteria: 0/6 pass");
+ });
+});
+
+describe("ultragoalCommand complete-goals", () => {
+ it("starts the next goal and returns a Codex instruction", async () => {
+ await createPlan();
+
+ expect(await ultragoalCommand(["complete-goals", "--json"])).toBe(0);
+ expect(stdoutJson()).toMatchObject({
+ ok: true,
+ goal: { status: "in_progress" },
+ instruction: { json: { status: "active" } },
+ });
+ });
+});
+
+describe("ultragoalCommand record-evidence", () => {
+ it("records evidence + returns updated criterion", async () => {
+ await createPlan();
+
+ expect(
+ await ultragoalCommand([
+ "record-evidence",
+ "--goal-id",
+ "G001-goal-a",
+ "--criterion-id",
+ "C001",
+ "--status",
+ "pass",
+ "--evidence",
+ "curl passed",
+ "--json",
+ ]),
+ ).toBe(0);
+ expect(stdoutJson()).toMatchObject({
+ ok: true,
+ criterion: { id: "C001", status: "pass", capturedEvidence: "curl passed" },
+ });
+ });
+
+ it("returns 1 + error on unknown goal-id", async () => {
+ await createPlan();
+
+ expect(
+ await ultragoalCommand([
+ "record-evidence",
+ "--goal-id",
+ "G404",
+ "--criterion-id",
+ "C001",
+ "--status",
+ "pass",
+ "--evidence",
+ "x",
+ ]),
+ ).toBe(1);
+ expect(err.join("")).toContain("[ultragoal]");
+ });
+
+ it("returns 1 + error on missing flags", async () => {
+ expect(
+ await ultragoalCommand(["record-evidence", "--criterion-id", "C001", "--status", "pass", "--evidence", "x"]),
+ ).toBe(1);
+ expect(err.join("")).toContain("Missing --goal-id");
+ });
+});
+
+describe("ultragoalCommand criteria", () => {
+ it("lists criteria for a goal", async () => {
+ await createPlan();
+
+ expect(await ultragoalCommand(["criteria", "--goal-id", "G001-goal-a"])).toBe(0);
+ expect(out.join("")).toContain("C001");
+ expect(out.join("")).toContain("happy");
+ });
+
+ it("supports --json output", async () => {
+ await createPlan();
+
+ expect(await ultragoalCommand(["criteria", "--goal-id", "G001-goal-a", "--json"])).toBe(0);
+ expect(stdoutJson()).toMatchObject({ ok: true, goalId: "G001-goal-a" });
+ expect(stdoutJson()).toHaveProperty("criteria.0.id", "C001");
+ });
+});
+
+describe("ultragoalCommand checkpoint", () => {
+ it("REJECTS status=complete when criteria pending", async () => {
+ await createPlan();
+
+ expect(
+ await ultragoalCommand([
+ "checkpoint",
+ "--goal-id",
+ "G001-goal-a",
+ "--status",
+ "complete",
+ "--evidence",
+ "x",
+ "--codex-goal-json",
+ codexSnapshot(),
+ ]),
+ ).toBe(1);
+ expect(err.join("").toLowerCase()).toContain("criteria");
+ });
+
+ it("ACCEPTS when all criteria pass", async () => {
+ await createPlan();
+ await passCriterion("G001-goal-a", "C001");
+ await passCriterion("G001-goal-a", "C002");
+ await passCriterion("G001-goal-a", "C003");
+
+ expect(
+ await ultragoalCommand([
+ "checkpoint",
+ "--goal-id",
+ "G001-goal-a",
+ "--status",
+ "complete",
+ "--evidence",
+ "implementation done and validation passed",
+ "--codex-goal-json",
+ codexSnapshot(),
+ "--json",
+ ]),
+ ).toBe(0);
+ expect(stdoutJson()).toHaveProperty("goal.status", "complete");
+ });
+});
+
+describe("ultragoalCommand steer", () => {
+ it("dispatches to the steering engine", async () => {
+ await createPlan();
+
+ expect(
+ await ultragoalCommand([
+ "steer",
+ "--kind",
+ "add_subgoal",
+ "--title",
+ "Extra",
+ "--objective",
+ "Do extra",
+ "--evidence",
+ "user requested it",
+ "--rationale",
+ "keeps plan accurate",
+ "--json",
+ ]),
+ ).toBe(0);
+ expect(stdoutJson()).toMatchObject({
+ ok: true,
+ accepted: true,
+ plan: { goals: [{ id: "G001-goal-a" }, { id: "G002-goal-b" }, { title: "Extra" }] },
+ });
+ });
+});
+
+describe("ultragoalCommand add-goal", () => {
+ it("appends a pending goal", async () => {
+ await createPlan();
+
+ expect(await ultragoalCommand(["add-goal", "--title", "Later", "--objective", "Do later", "--json"])).toBe(0);
+ expect(stdoutJson()).toMatchObject({ ok: true, goal: { title: "Later", status: "pending" } });
+ });
+});
+
+describe("ultragoalCommand unknown", () => {
+ it("returns 1 + prints help on unknown subcommand", async () => {
+ expect(await ultragoalCommand(["wat"])).toBe(1);
+ expect(out.join("")).toContain("omo ultragoal");
+ });
+});
+
+describe("ultragoalCommand error handling", () => {
+ it("returns 1 + prints [ultragoal] prefix on UltragoalError", async () => {
+ expect(await ultragoalCommand(["status"])).toBe(1);
+ expect(err.join("")).toContain("[ultragoal]");
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/cli-helpers.test.ts b/plugins/omo/components/ultragoal/test/cli-helpers.test.ts
new file mode 100644
index 00000000..80e2193e
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/cli-helpers.test.ts
@@ -0,0 +1,250 @@
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ hasFlag,
+ parseGoalArg,
+ parseRecordEvidenceArgs,
+ positionalText,
+ readJsonInput,
+ readRepeated,
+ readValue,
+} from "../src/cli-arg-parser.js";
+import { normalizeCodexGoalMode, printStatus, ULTRAGOAL_HELP } from "../src/cli-output.js";
+import type { UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";
+import { UltragoalError } from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+
+function criterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {
+ return {
+ id: "C001",
+ scenario: "happy path returns 200",
+ userModel: "happy",
+ expectedEvidence: "HTTP 200",
+ capturedEvidence: null,
+ status: "pending",
+ ...overrides,
+ };
+}
+
+function goal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {
+ return {
+ id: "G001",
+ title: "Auth endpoint",
+ objective: "Build JWT auth",
+ status: "in_progress",
+ successCriteria: [
+ criterion({ id: "C001", status: "pass" }),
+ criterion({ id: "C002", status: "pass" }),
+ criterion({ id: "C003" }),
+ ],
+ attempt: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ ...overrides,
+ };
+}
+
+function plan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {
+ return {
+ version: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ briefPath: ".omo/ultragoal/brief.md",
+ goalsPath: ".omo/ultragoal/goals.json",
+ ledgerPath: ".omo/ultragoal/ledger.jsonl",
+ activeGoalId: "G001",
+ goals: [goal()],
+ ...overrides,
+ };
+}
+
+function captureStdout(action: () => void): string {
+ let output = "";
+ const write = vi.spyOn(process.stdout, "write").mockImplementation((chunk: string | Uint8Array): boolean => {
+ output += chunk.toString();
+ return true;
+ });
+ action();
+ write.mockRestore();
+ return output;
+}
+
+describe("hasFlag", () => {
+ it("returns true for present flag", () => {
+ expect(hasFlag(["status", "--json"], "--json")).toBe(true);
+ });
+
+ it("returns false otherwise", () => {
+ expect(hasFlag(["status"], "--json")).toBe(false);
+ });
+});
+
+describe("readValue", () => {
+ it("returns value after flag", () => {
+ expect(readValue(["criteria", "--goal-id", "G001"], "--goal-id")).toBe("G001");
+ });
+
+ it("returns undefined when absent", () => {
+ expect(readValue(["criteria"], "--goal-id")).toBeUndefined();
+ });
+
+ it("returns undefined when flag has no following value", () => {
+ expect(readValue(["criteria", "--goal-id"], "--goal-id")).toBeUndefined();
+ });
+});
+
+describe("readRepeated", () => {
+ it("collects all occurrences", () => {
+ expect(readRepeated(["create-goals", "--goal", "A", "--goal=B"], "--goal")).toEqual(["A", "B"]);
+ });
+});
+
+describe("parseGoalArg", () => {
+ it("returns value of --goal-id or --goal", () => {
+ expect(parseGoalArg(["criteria", "--goal", "G002"])).toBe("G002");
+ expect(parseGoalArg(["criteria", "--goal-id", "G001"])).toBe("G001");
+ });
+});
+
+describe("positionalText", () => {
+ it("returns joined positional args after subcommand", () => {
+ expect(positionalText(["create-goals", "Build", "auth", "--json", "--brief", "ignored"])).toBe("Build auth");
+ });
+});
+
+describe("readJsonInput", () => {
+ it("parses inline JSON when value looks like JSON", async () => {
+ await expect(readJsonInput('{"ok":true}')).resolves.toEqual({ ok: true });
+ });
+
+ it("reads from file path", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "ug-cli-json-"));
+ try {
+ const file = join(dir, "input.json");
+ await writeFile(file, JSON.stringify({ fromFile: true }), "utf8");
+
+ await expect(readJsonInput(file)).resolves.toEqual({ fromFile: true });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+
+ it("returns undefined when value is undefined", async () => {
+ await expect(readJsonInput(undefined)).resolves.toBeUndefined();
+ });
+});
+
+describe("parseRecordEvidenceArgs", () => {
+ it("parses --goal-id + --criterion-id + --status + --evidence", () => {
+ expect(
+ parseRecordEvidenceArgs([
+ "record-evidence",
+ "--goal-id",
+ "G001",
+ "--criterion-id",
+ "C001",
+ "--status",
+ "pass",
+ "--evidence",
+ "curl 200",
+ ]),
+ ).toEqual({ goalId: "G001", criterionId: "C001", status: "pass", evidence: "curl 200" });
+ });
+
+ it("throws when goal-id missing", () => {
+ expect(() =>
+ parseRecordEvidenceArgs(["record-evidence", "--criterion-id", "C001", "--status", "pass", "--evidence", "x"]),
+ ).toThrow(UltragoalError);
+ });
+
+ it("throws when status is not pass|fail|blocked", () => {
+ expect(() =>
+ parseRecordEvidenceArgs([
+ "record-evidence",
+ "--goal-id",
+ "G001",
+ "--criterion-id",
+ "C001",
+ "--status",
+ "skip",
+ "--evidence",
+ "x",
+ ]),
+ ).toThrow(UltragoalError);
+ });
+
+ it("includes optional --notes when present", () => {
+ expect(
+ parseRecordEvidenceArgs([
+ "record-evidence",
+ "--goal-id",
+ "G001",
+ "--criterion-id",
+ "C001",
+ "--status",
+ "blocked",
+ "--evidence",
+ "auth missing",
+ "--notes",
+ "waiting",
+ ]),
+ ).toMatchObject({ notes: "waiting" });
+ });
+});
+
+describe("ULTRAGOAL_HELP", () => {
+ it("mentions omo ultragoal + every subcommand", () => {
+ expect(ULTRAGOAL_HELP).toContain("omo ultragoal");
+ expect(ULTRAGOAL_HELP).toContain("create-goals");
+ expect(ULTRAGOAL_HELP).toContain("complete-goals");
+ expect(ULTRAGOAL_HELP).toContain("status");
+ expect(ULTRAGOAL_HELP).toContain("checkpoint");
+ expect(ULTRAGOAL_HELP).toContain("steer");
+ expect(ULTRAGOAL_HELP).toContain("record-evidence");
+ expect(ULTRAGOAL_HELP).toContain("criteria");
+ expect(ULTRAGOAL_HELP).toContain("add-goal");
+ expect(ULTRAGOAL_HELP).toContain("record-review-blockers");
+ });
+
+ it("never mentions the legacy typo", () => {
+ const typo = ["o", "m", "x"].join("");
+
+ expect(ULTRAGOAL_HELP).not.toMatch(new RegExp(typo, "i"));
+ });
+});
+
+describe("printStatus", () => {
+ it("shows criteria P/T per goal", () => {
+ const output = captureStdout(() => printStatus(plan()));
+
+ expect(output).toContain("criteria: 2/3");
+ });
+
+ it("shows aggregate counts", () => {
+ const output = captureStdout(() =>
+ printStatus(plan({ goals: [goal(), goal({ id: "G002", successCriteria: [criterion({ status: "pass" })] })] })),
+ );
+
+ expect(output).toContain("total goals: 2");
+ expect(output).toContain("criteria: 3/4 pass");
+ });
+});
+
+describe("normalizeCodexGoalMode", () => {
+ it("returns aggregate when undefined", () => {
+ expect(normalizeCodexGoalMode(undefined)).toBe("aggregate");
+ });
+
+ it("returns the explicit value when valid", () => {
+ expect(normalizeCodexGoalMode("per_story")).toBe("per_story");
+ });
+
+ it("throws UltragoalError when invalid", () => {
+ expect(() => normalizeCodexGoalMode("per-story")).toThrow(UltragoalError);
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/cli-steering.test.ts b/plugins/omo/components/ultragoal/test/cli-steering.test.ts
new file mode 100644
index 00000000..0070ae35
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/cli-steering.test.ts
@@ -0,0 +1,407 @@
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { describe, expect, it, vi } from "vitest";
+
+import {
+ normalizeSteeringProposal,
+ parseSteeringKind,
+ parseSteeringProposal,
+ parseSteeringSource,
+ printSteerResult,
+} from "../src/cli-steering.js";
+import type { SteerUltragoalResult, UltragoalPlan } from "../src/types.js";
+import { UltragoalError } from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+
+function plan(): UltragoalPlan {
+ return {
+ version: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ briefPath: ".omo/ultragoal/brief.md",
+ goalsPath: ".omo/ultragoal/goals.json",
+ ledgerPath: ".omo/ultragoal/ledger.jsonl",
+ goals: [],
+ };
+}
+
+function steerResult(overrides: Partial<SteerUltragoalResult> = {}): SteerUltragoalResult {
+ return {
+ plan: plan(),
+ accepted: true,
+ audit: {
+ kind: "add_subgoal",
+ source: "cli",
+ targetGoalIds: ["G001"],
+ evidence: "x",
+ rationale: "y",
+ invariant: {
+ accepted: true,
+ structuralInvariantAccepted: true,
+ evidenceBackedNecessity: true,
+ noEasierCompletion: true,
+ rejectedReasons: [],
+ },
+ },
+ rejectedReasons: [],
+ deduped: false,
+ ...overrides,
+ };
+}
+
+function captureStdout(action: () => void): string {
+ let output = "";
+ const write = vi.spyOn(process.stdout, "write").mockImplementation((chunk: string | Uint8Array): boolean => {
+ output += chunk.toString();
+ return true;
+ });
+ action();
+ write.mockRestore();
+ return output;
+}
+
+describe("parseSteeringKind", () => {
+ it("returns valid kind from --kind", () => {
+ expect(parseSteeringKind(["--kind", "add_subgoal"])).toBe("add_subgoal");
+ });
+
+ it("accepts revise_criterion", () => {
+ expect(parseSteeringKind(["--kind", "revise_criterion"])).toBe("revise_criterion");
+ });
+
+ it("throws when --kind missing", () => {
+ expect(() => parseSteeringKind([])).toThrow(UltragoalError);
+ });
+
+ it("throws when kind unknown", () => {
+ expect(() => parseSteeringKind(["--kind", "bogus"])).toThrow(UltragoalError);
+ });
+});
+
+describe("parseSteeringSource", () => {
+ it("defaults to cli", () => {
+ expect(parseSteeringSource([])).toBe("cli");
+ });
+
+ it("returns explicit value", () => {
+ expect(parseSteeringSource(["--source", "user_prompt_submit"])).toBe("user_prompt_submit");
+ });
+});
+
+describe("parseSteeringProposal add_subgoal", () => {
+ it("builds proposal from required flags", async () => {
+ const p = await parseSteeringProposal([
+ "--kind",
+ "add_subgoal",
+ "--title",
+ " New ",
+ "--objective",
+ " Build ",
+ "--evidence",
+ " x ",
+ "--rationale",
+ " y ",
+ ]);
+
+ expect(p).toMatchObject({
+ kind: "add_subgoal",
+ source: "cli",
+ title: "New",
+ objective: "Build",
+ evidence: "x",
+ rationale: "y",
+ });
+ });
+
+ it("throws when --title missing", async () => {
+ await expect(
+ parseSteeringProposal([
+ "--kind",
+ "add_subgoal",
+ "--objective",
+ "Build",
+ "--evidence",
+ "x",
+ "--rationale",
+ "y",
+ ]),
+ ).rejects.toThrow(UltragoalError);
+ });
+
+ it("throws when --evidence missing", async () => {
+ await expect(
+ parseSteeringProposal(["--kind", "add_subgoal", "--title", "New", "--objective", "Build", "--rationale", "y"]),
+ ).rejects.toThrow(UltragoalError);
+ });
+});
+
+describe("parseSteeringProposal revise_criterion", () => {
+ it("builds proposal with goal, criterion, scenario, evidence, and rationale", async () => {
+ const p = await parseSteeringProposal([
+ "--kind",
+ "revise_criterion",
+ "--goal-id",
+ "G001",
+ "--criterion-id",
+ "C002",
+ "--scenario",
+ "new scenario",
+ "--evidence",
+ "x",
+ "--rationale",
+ "y",
+ ]);
+
+ expect(p.kind).toBe("revise_criterion");
+ expect(p.goalId).toBe("G001");
+ expect(p.targetGoalId).toBe("G001");
+ expect(p.criterionId).toBe("C002");
+ expect(p.scenario).toBe("new scenario");
+ });
+
+ it("accepts --expected-evidence as an update field", async () => {
+ const p = await parseSteeringProposal([
+ "--kind",
+ "revise_criterion",
+ "--goal-id",
+ "G001",
+ "--criterion-id",
+ "C002",
+ "--expected-evidence",
+ "new evidence",
+ "--evidence",
+ "x",
+ "--rationale",
+ "y",
+ ]);
+
+ expect(p.expectedEvidence).toBe("new evidence");
+ });
+
+ it("accepts --user-model as an update field", async () => {
+ const p = await parseSteeringProposal([
+ "--kind",
+ "revise_criterion",
+ "--goal-id",
+ "G001",
+ "--criterion-id",
+ "C002",
+ "--user-model",
+ "edge",
+ "--evidence",
+ "x",
+ "--rationale",
+ "y",
+ ]);
+
+ expect(p.userModel).toBe("edge");
+ });
+
+ it("throws when none of scenario/expected-evidence/user-model provided", async () => {
+ await expect(
+ parseSteeringProposal([
+ "--kind",
+ "revise_criterion",
+ "--goal-id",
+ "G001",
+ "--criterion-id",
+ "C002",
+ "--evidence",
+ "x",
+ "--rationale",
+ "y",
+ ]),
+ ).rejects.toThrow(UltragoalError);
+ });
+
+ it("throws when goal-id missing", async () => {
+ await expect(
+ parseSteeringProposal([
+ "--kind",
+ "revise_criterion",
+ "--criterion-id",
+ "C002",
+ "--scenario",
+ "s",
+ "--evidence",
+ "x",
+ "--rationale",
+ "y",
+ ]),
+ ).rejects.toThrow(UltragoalError);
+ });
+
+ it("throws when criterion-id missing", async () => {
+ await expect(
+ parseSteeringProposal([
+ "--kind",
+ "revise_criterion",
+ "--goal-id",
+ "G001",
+ "--scenario",
+ "s",
+ "--evidence",
+ "x",
+ "--rationale",
+ "y",
+ ]),
+ ).rejects.toThrow(UltragoalError);
+ });
+});
+
+describe("parseSteeringProposal split_subgoal", () => {
+ it("reads --children from inline JSON", async () => {
+ const p = await parseSteeringProposal([
+ "--kind",
+ "split_subgoal",
+ "--goal-id",
+ "G001",
+ "--children",
+ '[{"title":"A","objective":"Do A"}]',
+ "--evidence",
+ "x",
+ "--rationale",
+ "y",
+ ]);
+
+ expect(p.childGoals).toEqual([{ title: "A", objective: "Do A" }]);
+ });
+
+ it("reads --children from JSON file path", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "ug-steer-"));
+ try {
+ const file = join(dir, "children.json");
+ await writeFile(file, '[{"title":"B","objective":"Do B"}]', "utf8");
+
+ const p = await parseSteeringProposal([
+ "--kind",
+ "split_subgoal",
+ "--goal-id",
+ "G001",
+ "--children",
+ file,
+ "--evidence",
+ "x",
+ "--rationale",
+ "y",
+ ]);
+
+ expect(p.childGoals).toEqual([{ title: "B", objective: "Do B" }]);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe("parseSteeringProposal reorder_pending", () => {
+ it("reads --order from inline JSON array", async () => {
+ const p = await parseSteeringProposal([
+ "--kind",
+ "reorder_pending",
+ "--order",
+ '["G002","G001"]',
+ "--evidence",
+ "x",
+ "--rationale",
+ "y",
+ ]);
+
+ expect(p.pendingOrder).toEqual(["G002", "G001"]);
+ });
+});
+
+describe("parseSteeringProposal remaining kinds", () => {
+ it("builds revise_pending_wording proposal", async () => {
+ const p = await parseSteeringProposal([
+ "--kind",
+ "revise_pending_wording",
+ "--goal-id",
+ "G001",
+ "--title",
+ "New",
+ "--evidence",
+ "x",
+ "--rationale",
+ "y",
+ ]);
+
+ expect(p).toMatchObject({ kind: "revise_pending_wording", targetGoalId: "G001", revisedTitle: "New" });
+ });
+
+ it("builds mark_blocked_superseded proposal with replacements", async () => {
+ const p = await parseSteeringProposal([
+ "--kind",
+ "mark_blocked_superseded",
+ "--goal-id",
+ "G001",
+ "--replacements",
+ '[{"title":"C","objective":"Do C"}]',
+ "--evidence",
+ "x",
+ "--rationale",
+ "y",
+ ]);
+
+ expect(p).toMatchObject({
+ kind: "mark_blocked_superseded",
+ targetGoalId: "G001",
+ childGoals: [{ title: "C", objective: "Do C" }],
+ });
+ });
+});
+
+describe("parseSteeringProposal annotate_ledger", () => {
+ it("builds minimal proposal", async () => {
+ const p = await parseSteeringProposal(["--kind", "annotate_ledger", "--evidence", "x", "--rationale", "y"]);
+
+ expect(p).toMatchObject({ kind: "annotate_ledger", source: "cli", evidence: "x", rationale: "y" });
+ });
+});
+
+describe("normalizeSteeringProposal", () => {
+ it("trims string fields", () => {
+ const p = normalizeSteeringProposal({
+ kind: "revise_criterion",
+ source: "cli",
+ goalId: " G001 ",
+ targetGoalId: " G001 ",
+ criterionId: " C002 ",
+ evidence: " x ",
+ rationale: " y ",
+ scenario: " z ",
+ });
+
+ expect(p).toMatchObject({
+ goalId: "G001",
+ targetGoalId: "G001",
+ criterionId: "C002",
+ evidence: "x",
+ rationale: "y",
+ scenario: "z",
+ });
+ });
+
+ it("rejects empty evidence after trim", () => {
+ expect(() =>
+ normalizeSteeringProposal({ kind: "annotate_ledger", source: "cli", evidence: " ", rationale: "y" }),
+ ).toThrow(UltragoalError);
+ });
+});
+
+describe("printSteerResult", () => {
+ it("prints JSON when json=true", () => {
+ const output = captureStdout(() => printSteerResult(steerResult(), true));
+
+ expect(JSON.parse(output)).toMatchObject({ accepted: true, deduped: false, audit: { kind: "add_subgoal" } });
+ });
+
+ it("prints human-readable when json=false", () => {
+ const output = captureStdout(() => printSteerResult(steerResult(), false));
+
+ expect(output).toContain("ultragoal steer: accepted add_subgoal");
+ expect(output).toContain("ultragoal status");
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/codex-goal-instruction.test.ts b/plugins/omo/components/ultragoal/test/codex-goal-instruction.test.ts
new file mode 100644
index 00000000..4dcb9d71
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/codex-goal-instruction.test.ts
@@ -0,0 +1,153 @@
+import { describe, expect, it } from "vitest";
+
+import { buildCodexGoalInstruction } from "../src/codex-goal-instruction.js";
+import { ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";
+import type { UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+
+function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {
+ return {
+ id: "C001",
+ scenario: "happy path",
+ userModel: "happy",
+ expectedEvidence: "observable proof",
+ capturedEvidence: null,
+ status: "pending",
+ ...overrides,
+ };
+}
+
+function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {
+ return {
+ id: "G001",
+ title: "Goal one",
+ objective: "Complete goal one",
+ status: "pending",
+ successCriteria: [],
+ attempt: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ ...overrides,
+ };
+}
+
+function makePlan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {
+ return {
+ version: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ briefPath: ".omo/ultragoal/brief.md",
+ goalsPath: ".omo/ultragoal/goals.json",
+ ledgerPath: ".omo/ultragoal/ledger.jsonl",
+ goals: [],
+ ...overrides,
+ };
+}
+
+describe("buildCodexGoalInstruction aggregate mode", () => {
+ it("references the aggregate handoff and the .omo/ultragoal/goals.json artifact", () => {
+ const { text } = buildCodexGoalInstruction({ plan: makePlan({ codexGoalMode: "aggregate" }), goal: makeGoal() });
+ expect(text).toContain("aggregate");
+ expect(text).toContain(".omo/ultragoal/goals.json");
+ });
+
+ it("given aggregate mode when rendering create_goal payload then omits numeric limits", () => {
+ const { json, text } = buildCodexGoalInstruction({
+ plan: makePlan({ codexGoalMode: "aggregate" }),
+ goal: makeGoal(),
+ });
+ expect(json).toEqual({
+ objective: ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE,
+ status: "active",
+ });
+ expect(text).toContain("objective and status only");
+ expect(text).toContain("Goals are unlimited");
+ expect(text).not.toMatch(/token[_-]?budget/i);
+ });
+
+ it("instructs not to call update_goal mid-aggregate when not final", () => {
+ const { text } = buildCodexGoalInstruction({
+ plan: makePlan({ codexGoalMode: "aggregate" }),
+ goal: makeGoal(),
+ isFinal: false,
+ });
+ expect(text).toMatch(/do not.*update_goal/i);
+ });
+
+ it("includes quality gate instruction when isFinal", () => {
+ const { text } = buildCodexGoalInstruction({
+ plan: makePlan({ codexGoalMode: "aggregate" }),
+ goal: makeGoal(),
+ isFinal: true,
+ });
+ expect(text).toMatch(/quality gate/i);
+ });
+});
+
+describe("buildCodexGoalInstruction per_story mode", () => {
+ it("uses the goal's own objective for create_goal", () => {
+ const goal = makeGoal({ objective: "Build the auth service" });
+ const { text } = buildCodexGoalInstruction({ plan: makePlan({ codexGoalMode: "per_story" }), goal });
+ expect(text).toContain("Build the auth service");
+ });
+});
+
+describe("buildCodexGoalInstruction criteria section", () => {
+ it("lists every successCriteria entry with id + scenario + status", () => {
+ const goal = makeGoal({
+ successCriteria: [
+ makeCriterion({
+ id: "C001",
+ scenario: "happy login",
+ userModel: "happy",
+ expectedEvidence: "200 OK",
+ status: "pending",
+ }),
+ makeCriterion({
+ id: "C002",
+ scenario: "invalid creds",
+ userModel: "edge",
+ expectedEvidence: "401",
+ status: "pass",
+ }),
+ makeCriterion({
+ id: "C003",
+ scenario: "no regression /health",
+ userModel: "regression",
+ expectedEvidence: "/health unaffected",
+ status: "fail",
+ }),
+ ],
+ });
+
+ const { text } = buildCodexGoalInstruction({ plan: makePlan(), goal });
+
+ expect(text).toContain("C001");
+ expect(text).toContain("happy login");
+ expect(text).toContain("pending");
+ expect(text).toContain("C002");
+ expect(text).toContain("pass");
+ expect(text).toContain("C003");
+ expect(text).toContain("fail");
+ });
+
+ it("highlights pending criteria as remaining work", () => {
+ const goal = makeGoal({ successCriteria: [makeCriterion({ id: "C001", status: "pending" })] });
+ const { text } = buildCodexGoalInstruction({ plan: makePlan(), goal });
+ expect(text).toMatch(/remaining|pending/i);
+ });
+});
+
+describe("buildCodexGoalInstruction rebrand audit", () => {
+ it("emits no legacy brand references in any rendered string", () => {
+ const legacyBrand = ["o", "m", "x"].join("");
+ const { text } = buildCodexGoalInstruction({ plan: makePlan(), goal: makeGoal() });
+ expect(text).not.toMatch(new RegExp(legacyBrand, "i"));
+ });
+
+ it("references .omo/ultragoal in artifact paths", () => {
+ const { text } = buildCodexGoalInstruction({ plan: makePlan({ codexGoalMode: "aggregate" }), goal: makeGoal() });
+ expect(text).toContain(".omo/ultragoal");
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/codex-goal-snapshot.test.ts b/plugins/omo/components/ultragoal/test/codex-goal-snapshot.test.ts
new file mode 100644
index 00000000..a1e0d29d
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/codex-goal-snapshot.test.ts
@@ -0,0 +1,156 @@
+import { mkdtemp, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+import {
+ CodexGoalSnapshotError,
+ formatCodexGoalReconciliation,
+ parseCodexGoalSnapshot,
+ readCodexGoalSnapshotInput,
+ reconcileCodexGoalSnapshot,
+} from "../src/codex-goal-snapshot.ts";
+
+describe("parseCodexGoalSnapshot", () => {
+ it("returns available snapshot from { goal: { ... } } JSON", () => {
+ // given
+ const payload = { goal: { objective: "X", status: "active" } };
+
+ // when
+ const snapshot = parseCodexGoalSnapshot(payload);
+
+ // then
+ expect(snapshot.available).toBe(true);
+ expect(snapshot.objective).toBe("X");
+ expect(snapshot.status).toBe("active");
+ });
+
+ it("ignores remaining token budget fields from goal snapshots", () => {
+ // given
+ const payload = { goal: { objective: "X", status: "active" }, remainingTokens: 123 };
+
+ // when
+ const snapshot = parseCodexGoalSnapshot(payload);
+
+ // then
+ expect("remainingTokens" in snapshot).toBe(false);
+ });
+
+ it("returns unavailable snapshot from null", () => {
+ // when
+ const snapshot = parseCodexGoalSnapshot(null);
+
+ // then
+ expect(snapshot.available).toBe(false);
+ });
+
+ it("returns unavailable snapshot from malformed payload", () => {
+ // when
+ const snapshot = parseCodexGoalSnapshot({ wrong: "shape" });
+
+ // then
+ expect(snapshot.available).toBe(false);
+ expect(snapshot.status).toBe("unknown");
+ });
+});
+
+describe("readCodexGoalSnapshotInput", () => {
+ let dir = "";
+
+ beforeEach(async () => {
+ // given
+ dir = await mkdtemp(join(tmpdir(), "ug-snap-"));
+ });
+
+ it("parses inline JSON string", async () => {
+ // when
+ const snapshot = await readCodexGoalSnapshotInput('{"goal":{"objective":"X","status":"active"}}');
+
+ // then
+ expect(snapshot?.available).toBe(true);
+ expect(snapshot?.objective).toBe("X");
+ });
+
+ it("reads from file path", async () => {
+ // given
+ const filePath = join(dir, "snap.json");
+ await writeFile(filePath, '{"goal":{"objective":"X","status":"complete"}}', "utf8");
+
+ // when
+ const snapshot = await readCodexGoalSnapshotInput(filePath);
+
+ // then
+ expect(snapshot?.available).toBe(true);
+ expect(snapshot?.status).toBe("complete");
+ });
+
+ it("reads from sample fixture path", async () => {
+ // given
+ const filePath = join(process.cwd(), "test", "fixtures", "codex-goal-snapshot.json");
+
+ // when
+ const snapshot = await readCodexGoalSnapshotInput(filePath);
+
+ // then
+ expect(snapshot?.available).toBe(true);
+ expect(snapshot?.objective).toBe("Complete the durable ultragoal plan");
+ });
+
+ it("throws CodexGoalSnapshotError when input is neither JSON nor a path", async () => {
+ // when/then
+ await expect(readCodexGoalSnapshotInput("not json and not a path")).rejects.toThrow(CodexGoalSnapshotError);
+ });
+});
+
+describe("reconcileCodexGoalSnapshot", () => {
+ it("returns ok=true when snapshot matches expected", () => {
+ // when
+ const reconciliation = reconcileCodexGoalSnapshot(
+ { available: true, objective: "X", status: "active", raw: null },
+ { expectedObjective: "X" },
+ );
+
+ // then
+ expect(reconciliation.ok).toBe(true);
+ expect(reconciliation.errors).toHaveLength(0);
+ });
+
+ it("reports error when objective mismatches", () => {
+ // when
+ const reconciliation = reconcileCodexGoalSnapshot(
+ { available: true, objective: "X", status: "active", raw: null },
+ { expectedObjective: "Y" },
+ );
+
+ // then
+ expect(reconciliation.ok).toBe(false);
+ expect(reconciliation.errors.length).toBeGreaterThan(0);
+ });
+
+ it("reports error when status mismatches", () => {
+ // when
+ const reconciliation = reconcileCodexGoalSnapshot(
+ { available: true, objective: "X", status: "active", raw: null },
+ { expectedObjective: "X", allowedStatuses: ["complete"] },
+ );
+
+ // then
+ expect(reconciliation.ok).toBe(false);
+ expect(reconciliation.errors.length).toBeGreaterThan(0);
+ });
+});
+
+describe("formatCodexGoalReconciliation", () => {
+ it("renders errors joined", () => {
+ // given
+ const reconciliation = reconcileCodexGoalSnapshot(
+ { available: true, objective: "X", status: "active", raw: null },
+ { expectedObjective: "Y", allowedStatuses: ["complete"] },
+ );
+
+ // when
+ const formatted = formatCodexGoalReconciliation(reconciliation);
+
+ // then
+ expect(formatted).toMatch(/objective|status/i);
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/codex-hook.test.ts b/plugins/omo/components/ultragoal/test/codex-hook.test.ts
new file mode 100644
index 00000000..c6be05e8
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/codex-hook.test.ts
@@ -0,0 +1,187 @@
+import { mkdir, mkdtemp, readFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { Readable, Writable } from "node:stream";
+import { describe, expect, it } from "vitest";
+
+import {
+ applyUserPromptUltragoalSteering,
+ parseUserPromptSubmitPayload,
+ runUltragoalHookCli,
+ type UserPromptSubmitPayload,
+} from "../src/codex-hook.js";
+import { ultragoalDir } from "../src/paths.js";
+import { writePlan } from "../src/plan-io.js";
+import type { UltragoalPlan } from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+
+async function bootstrapPlanRepo(): Promise<string> {
+ const repoRoot = await mkdtemp(join(tmpdir(), "ug-hook-"));
+ await mkdir(ultragoalDir(repoRoot), { recursive: true });
+ await writePlan(repoRoot, samplePlan());
+ return repoRoot;
+}
+
+function samplePlan(): UltragoalPlan {
+ return {
+ version: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ briefPath: ".omo/ultragoal/brief.md",
+ goalsPath: ".omo/ultragoal/goals.json",
+ ledgerPath: ".omo/ultragoal/ledger.jsonl",
+ goals: [
+ {
+ id: "G001",
+ title: "Build hook",
+ objective: "Apply safe steering directives from Codex hooks.",
+ status: "pending",
+ successCriteria: [],
+ attempt: 0,
+ createdAt: NOW,
+ updatedAt: NOW,
+ },
+ ],
+ };
+}
+
+function payload(prompt: string, cwd: string): UserPromptSubmitPayload {
+ return { cwd, hook_event_name: "UserPromptSubmit", prompt, session_id: "s1" };
+}
+
+function payloadWithRuntimeEvent(hookEventName: string): UserPromptSubmitPayload {
+ const input = payload(
+ 'OMO_ULTRAGOAL_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',
+ "/tmp",
+ );
+ Object.defineProperty(input, "hook_event_name", { value: hookEventName });
+ return input;
+}
+
+function captureStdout(): { readonly stdout: Writable; readonly read: () => string } {
+ let captured = "";
+ const stdout = new Writable({
+ write(chunk: unknown, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void {
+ captured += chunk instanceof Buffer ? chunk.toString() : String(chunk);
+ callback();
+ },
+ });
+ return { stdout, read: () => captured };
+}
+
+describe("parseUserPromptSubmitPayload", () => {
+ it("parses valid JSON payload", async () => {
+ const raw = await readFile("test/fixtures/user-prompt-submit.json", "utf8");
+ const parsed = parseUserPromptSubmitPayload(raw);
+ expect(parsed?.hook_event_name).toBe("UserPromptSubmit");
+ expect(parsed?.prompt).toContain("OMO_ULTRAGOAL_STEER");
+ });
+
+ it("returns null for empty input", () => {
+ expect(parseUserPromptSubmitPayload("")).toBeNull();
+ });
+
+ it("returns null for invalid JSON", () => {
+ expect(parseUserPromptSubmitPayload("{bad")).toBeNull();
+ });
+
+ it("returns null when hook_event_name missing", () => {
+ expect(parseUserPromptSubmitPayload(JSON.stringify({ cwd: "/repo", prompt: "x", session_id: "s1" }))).toBeNull();
+ });
+});
+
+describe("applyUserPromptUltragoalSteering - OMO directive patterns", () => {
+ it("processes OMO_ULTRAGOAL_STEER: prompt and returns audit text on success", async () => {
+ const repoRoot = await bootstrapPlanRepo();
+ const out = await applyUserPromptUltragoalSteering(
+ payload(
+ 'OMO_ULTRAGOAL_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',
+ repoRoot,
+ ),
+ );
+ expect(out.length).toBeGreaterThan(0);
+ expect(out).toContain("annotate_ledger");
+ });
+
+ it("processes omo.ultragoal.steer: pattern", async () => {
+ const repoRoot = await bootstrapPlanRepo();
+ const out = await applyUserPromptUltragoalSteering(
+ payload(
+ 'omo.ultragoal.steer: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',
+ repoRoot,
+ ),
+ );
+ expect(out).toContain("accepted");
+ });
+
+ it("processes omo ultragoal steer: pattern", async () => {
+ const repoRoot = await bootstrapPlanRepo();
+ const out = await applyUserPromptUltragoalSteering(
+ payload(
+ 'omo ultragoal steer: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',
+ repoRoot,
+ ),
+ );
+ expect(out).toContain("annotate_ledger");
+ });
+});
+
+describe("applyUserPromptUltragoalSteering - non-matching prompts", () => {
+ it("returns empty string when no directive in prompt", async () => {
+ expect(await applyUserPromptUltragoalSteering(payload("just a normal user message", "/tmp"))).toBe("");
+ });
+
+ it("returns empty for OMX_ULTRAGOAL_STEER (deprecated marker - must reject)", async () => {
+ expect(
+ await applyUserPromptUltragoalSteering(
+ payload('OMX_ULTRAGOAL_STEER: {"kind":"annotate_ledger","evidence":"x","rationale":"y"}', "/tmp"),
+ ),
+ ).toBe("");
+ });
+
+ it("returns empty when hook_event_name is not UserPromptSubmit", async () => {
+ expect(await applyUserPromptUltragoalSteering(payloadWithRuntimeEvent("PostToolUse"))).toBe("");
+ });
+});
+
+describe("applyUserPromptUltragoalSteering - error swallowing", () => {
+ it("returns empty (never throws) when plan does not exist", async () => {
+ const repoRoot = await mkdtemp(join(tmpdir(), "ug-nohook-"));
+ const out = await applyUserPromptUltragoalSteering(
+ payload(
+ 'OMO_ULTRAGOAL_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',
+ repoRoot,
+ ),
+ );
+ expect(out).toBe("");
+ });
+
+ it("returns empty when steering proposal is malformed JSON after marker", async () => {
+ const out = await applyUserPromptUltragoalSteering(payload("OMO_ULTRAGOAL_STEER: {bad", "/tmp"));
+ expect(out).toBe("");
+ });
+});
+
+describe("runUltragoalHookCli (stdin/stdout integration)", () => {
+ it("reads stdin, applies steering, writes audit to stdout", async () => {
+ const repoRoot = await bootstrapPlanRepo();
+ const stdin = Readable.from([
+ JSON.stringify(
+ payload(
+ 'OMO_ULTRAGOAL_STEER: {"kind":"annotate_ledger","source":"user_prompt_submit","evidence":"x","rationale":"y"}',
+ repoRoot,
+ ),
+ ),
+ ]);
+ const capture = captureStdout();
+ await runUltragoalHookCli(stdin, capture.stdout);
+ expect(capture.read().length).toBeGreaterThan(0);
+ });
+
+ it("writes nothing when stdin is empty", async () => {
+ const capture = captureStdout();
+ await runUltragoalHookCli(Readable.from([""]), capture.stdout);
+ expect(capture.read()).toBe("");
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/evidence-criteria-gate.test.ts b/plugins/omo/components/ultragoal/test/evidence-criteria-gate.test.ts
new file mode 100644
index 00000000..ee7452f1
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/evidence-criteria-gate.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it } from "vitest";
+
+import { requireAllCriteriaPass } from "../src/evidence.js";
+import type { UltragoalItem, UltragoalSuccessCriterion } from "../src/types.js";
+import { UltragoalError } from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+
+function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {
+ return {
+ id: "C001",
+ scenario: "happy path login returns 200",
+ userModel: "happy",
+ expectedEvidence: "curl /login -d {valid} returns 200 + token",
+ capturedEvidence: null,
+ status: "pending",
+ ...overrides,
+ };
+}
+
+function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {
+ return {
+ id: "G001",
+ title: "Auth endpoint",
+ objective: "Build JWT auth",
+ status: "in_progress",
+ successCriteria: [
+ makeCriterion({ id: "C001" }),
+ makeCriterion({ id: "C002", userModel: "edge" }),
+ makeCriterion({ id: "C003", userModel: "regression" }),
+ ],
+ attempt: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ ...overrides,
+ };
+}
+
+describe("requireAllCriteriaPass", () => {
+ it("does NOT throw when all criteria pass", () => {
+ // given
+ const goal = makeGoal({
+ successCriteria: [
+ makeCriterion({ id: "C001", status: "pass" }),
+ makeCriterion({ id: "C002", status: "pass" }),
+ ],
+ });
+
+ // when / then
+ expect(() => requireAllCriteriaPass(goal)).not.toThrow();
+ });
+
+ it("throws UltragoalError when any criterion pending", () => {
+ // given
+ const goal = makeGoal({
+ successCriteria: [
+ makeCriterion({ id: "C001", status: "pass" }),
+ makeCriterion({ id: "C002", status: "pending" }),
+ makeCriterion({ id: "C003", status: "pass" }),
+ ],
+ });
+
+ // when / then
+ expect(() => requireAllCriteriaPass(goal)).toThrow(UltragoalError);
+ });
+
+ it("throws when any fail/blocked too", () => {
+ // given
+ const goal1 = makeGoal({ successCriteria: [makeCriterion({ id: "C001", status: "fail" })] });
+ const goal2 = makeGoal({ successCriteria: [makeCriterion({ id: "C001", status: "blocked" })] });
+
+ // when / then
+ expect(() => requireAllCriteriaPass(goal1)).toThrow(UltragoalError);
+ expect(() => requireAllCriteriaPass(goal2)).toThrow(UltragoalError);
+ });
+
+ it("UltragoalError includes details.goalId + details.unresolved", () => {
+ // given
+ const goal = makeGoal({
+ id: "G001",
+ successCriteria: [
+ makeCriterion({ id: "C001", status: "pass" }),
+ makeCriterion({ id: "C002", status: "pending" }),
+ makeCriterion({ id: "C003", status: "pass" }),
+ ],
+ });
+
+ // when / then
+ try {
+ requireAllCriteriaPass(goal);
+ expect.fail("expected throw");
+ } catch (error) {
+ expect(error).toBeInstanceOf(UltragoalError);
+ if (!(error instanceof UltragoalError)) throw error;
+ expect(error.code).toBe("ultragoal_criteria_not_all_pass");
+ expect(error.details?.["goalId"]).toBe("G001");
+ expect(Array.isArray(error.details?.["unresolved"])).toBe(true);
+ }
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/evidence.test.ts b/plugins/omo/components/ultragoal/test/evidence.test.ts
new file mode 100644
index 00000000..77243e2d
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/evidence.test.ts
@@ -0,0 +1,263 @@
+import { mkdir, mkdtemp, readFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import {
+ criteriaSummary,
+ markCriteriaPendingResetForGoal,
+ recordEvidence,
+ unresolvedCriteriaOf,
+} from "../src/evidence.js";
+import { ultragoalDir } from "../src/paths.js";
+import { readUltragoalPlan, writePlan } from "../src/plan-io.js";
+import type { UltragoalItem, UltragoalLedgerEntry, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";
+import { UltragoalError } from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+
+async function bootstrapRepo(plan: UltragoalPlan): Promise<string> {
+ const repo = await mkdtemp(join(tmpdir(), "ug-evidence-"));
+ await mkdir(ultragoalDir(repo), { recursive: true });
+ await writePlan(repo, plan);
+ return repo;
+}
+
+async function readLastLedgerEntry(repo: string): Promise<UltragoalLedgerEntry> {
+ const lines = (await readFile(join(repo, ".omo/ultragoal/ledger.jsonl"), "utf8")).trim().split("\n");
+ const last = lines.at(-1);
+ if (last === undefined) throw new Error("expected ledger entry");
+ return JSON.parse(last);
+}
+
+function firstGoal(plan: UltragoalPlan): UltragoalItem {
+ const goal = plan.goals.at(0);
+ if (goal === undefined) throw new Error("expected goal");
+ return goal;
+}
+
+function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {
+ return {
+ id: "C001",
+ scenario: "happy path login returns 200",
+ userModel: "happy",
+ expectedEvidence: "curl /login -d {valid} returns 200 + token",
+ capturedEvidence: null,
+ status: "pending",
+ ...overrides,
+ };
+}
+
+function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {
+ return {
+ id: "G001",
+ title: "Auth endpoint",
+ objective: "Build JWT auth",
+ status: "in_progress",
+ successCriteria: [
+ makeCriterion({ id: "C001" }),
+ makeCriterion({ id: "C002", userModel: "edge" }),
+ makeCriterion({ id: "C003", userModel: "regression" }),
+ ],
+ attempt: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ ...overrides,
+ };
+}
+
+function makePlan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {
+ return {
+ version: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ briefPath: ".omo/ultragoal/brief.md",
+ goalsPath: ".omo/ultragoal/goals.json",
+ ledgerPath: ".omo/ultragoal/ledger.jsonl",
+ codexGoalMode: "aggregate",
+ codexObjective: "Complete the durable ultragoal plan in .omo/ultragoal/goals.json",
+ codexObjectiveAliases: [],
+ goals: [makeGoal()],
+ ...overrides,
+ };
+}
+
+describe("recordEvidence (status=pass)", () => {
+ it("sets criterion.status=pass + capturedEvidence + capturedAt", async () => {
+ const repo = await bootstrapRepo(makePlan());
+
+ const result = await recordEvidence(repo, {
+ goalId: "G001",
+ criterionId: "C001",
+ status: "pass",
+ evidence: "curl /login returns 200 + token verified",
+ });
+
+ expect(result.criterion.status).toBe("pass");
+ expect(result.criterion.capturedEvidence).toContain("curl /login returns 200");
+ expect(result.criterion.capturedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);
+ });
+
+ it("appends evidence_captured ledger event", async () => {
+ const repo = await bootstrapRepo(makePlan());
+
+ await recordEvidence(repo, { goalId: "G001", criterionId: "C001", status: "pass", evidence: "observable proof" });
+
+ const last = await readLastLedgerEntry(repo);
+ expect(last.kind).toBe("evidence_captured");
+ expect(last.goalId).toBe("G001");
+ expect(last.criterionId).toBe("C001");
+ });
+
+ it("persists the change so a fresh read sees status=pass", async () => {
+ const repo = await bootstrapRepo(makePlan());
+
+ await recordEvidence(repo, { goalId: "G001", criterionId: "C001", status: "pass", evidence: "observable proof" });
+
+ const criterion = firstGoal(await readUltragoalPlan(repo)).successCriteria.find((c) => c.id === "C001");
+ expect(criterion?.status).toBe("pass");
+ });
+});
+
+describe("recordEvidence (status=fail)", () => {
+ it("sets criterion.status=fail + appends criterion_failed event", async () => {
+ const repo = await bootstrapRepo(makePlan());
+
+ const result = await recordEvidence(repo, {
+ goalId: "G001",
+ criterionId: "C001",
+ status: "fail",
+ evidence: "got 500 not 200",
+ });
+
+ expect(result.criterion.status).toBe("fail");
+ expect((await readLastLedgerEntry(repo)).kind).toBe("criterion_failed");
+ });
+});
+
+describe("recordEvidence (status=blocked)", () => {
+ it("sets criterion.status=blocked + appends criterion_blocked event", async () => {
+ const repo = await bootstrapRepo(makePlan());
+
+ const result = await recordEvidence(repo, {
+ goalId: "G001",
+ criterionId: "C001",
+ status: "blocked",
+ evidence: "auth not in CI yet",
+ });
+
+ expect(result.criterion.status).toBe("blocked");
+ expect((await readLastLedgerEntry(repo)).kind).toBe("criterion_blocked");
+ });
+});
+
+describe("recordEvidence error cases", () => {
+ it("throws when goalId not found", async () => {
+ const repo = await bootstrapRepo(makePlan());
+
+ await expect(
+ recordEvidence(repo, { goalId: "GUNKNOWN", criterionId: "C001", status: "pass", evidence: "x" }),
+ ).rejects.toBeInstanceOf(UltragoalError);
+ });
+
+ it("throws when criterionId not found within goal", async () => {
+ const repo = await bootstrapRepo(makePlan());
+
+ await expect(
+ recordEvidence(repo, { goalId: "G001", criterionId: "CUNKNOWN", status: "pass", evidence: "x" }),
+ ).rejects.toBeInstanceOf(UltragoalError);
+ });
+
+ it("throws when evidence is empty/whitespace", async () => {
+ const repo = await bootstrapRepo(makePlan());
+
+ await expect(
+ recordEvidence(repo, { goalId: "G001", criterionId: "C001", status: "pass", evidence: " " }),
+ ).rejects.toBeInstanceOf(UltragoalError);
+ });
+});
+
+describe("markCriteriaPendingResetForGoal", () => {
+ it("resets every criterion of the goal to pending + capturedEvidence=null", async () => {
+ const goal = makeGoal({
+ successCriteria: [
+ makeCriterion({ id: "C001", status: "pass", capturedEvidence: "old" }),
+ makeCriterion({ id: "C002", status: "fail", capturedEvidence: "older" }),
+ makeCriterion({ id: "C003", status: "blocked", capturedEvidence: "oldest" }),
+ ],
+ });
+ const repo = await bootstrapRepo(makePlan({ goals: [goal] }));
+
+ const result = await markCriteriaPendingResetForGoal(repo, "G001");
+
+ expect(result.resetCount).toBe(3);
+ for (const c of firstGoal(result.plan).successCriteria) {
+ expect(c.status).toBe("pending");
+ expect(c.capturedEvidence).toBeNull();
+ }
+ });
+
+ it("appends a single criteria_revised ledger event describing the reset", async () => {
+ const repo = await bootstrapRepo(makePlan());
+
+ await markCriteriaPendingResetForGoal(repo, "G001");
+
+ expect((await readLastLedgerEntry(repo)).kind).toBe("criteria_revised");
+ });
+});
+
+describe("criteriaSummary (pure)", () => {
+ it("aggregates counts across all goals", () => {
+ const plan = makePlan({
+ goals: [
+ makeGoal({
+ id: "G001",
+ successCriteria: [
+ makeCriterion({ id: "C001", status: "pass" }),
+ makeCriterion({ id: "C002", status: "pending" }),
+ ],
+ }),
+ makeGoal({
+ id: "G002",
+ successCriteria: [
+ makeCriterion({ id: "C001", status: "fail" }),
+ makeCriterion({ id: "C002", status: "blocked" }),
+ makeCriterion({ id: "C003", status: "pass" }),
+ ],
+ }),
+ ],
+ });
+
+ const summary = criteriaSummary(plan);
+
+ expect(summary.totalCriteria).toBe(5);
+ expect(summary.passCount).toBe(2);
+ expect(summary.pendingCount).toBe(1);
+ expect(summary.failCount).toBe(1);
+ expect(summary.blockedCount).toBe(1);
+ expect(summary.goalsWithUnresolvedCriteria).toEqual(["G001", "G002"]);
+ });
+
+ it("returns empty when no criteria exist", () => {
+ const summary = criteriaSummary(makePlan({ goals: [makeGoal({ successCriteria: [] })] }));
+
+ expect(summary.totalCriteria).toBe(0);
+ expect(summary.goalsWithUnresolvedCriteria).toEqual([]);
+ });
+});
+
+describe("unresolvedCriteriaOf (pure)", () => {
+ it("returns only non-pass criteria", () => {
+ const goal = makeGoal({
+ successCriteria: [
+ makeCriterion({ id: "C001", status: "pass" }),
+ makeCriterion({ id: "C002", status: "pending" }),
+ makeCriterion({ id: "C003", status: "fail" }),
+ ],
+ });
+
+ const unresolved = unresolvedCriteriaOf(goal);
+
+ expect(unresolved.map((c) => c.id)).toEqual(["C002", "C003"]);
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/fixtures/.gitkeep b/plugins/omo/components/ultragoal/test/fixtures/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/plugins/omo/components/ultragoal/test/fixtures/codex-goal-snapshot.json b/plugins/omo/components/ultragoal/test/fixtures/codex-goal-snapshot.json
new file mode 100644
index 00000000..f88a3c5e
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/fixtures/codex-goal-snapshot.json
@@ -0,0 +1 @@
+{ "goal": { "objective": "Complete the durable ultragoal plan", "status": "active" } }
diff --git a/plugins/omo/components/ultragoal/test/fixtures/sample-brief.md b/plugins/omo/components/ultragoal/test/fixtures/sample-brief.md
new file mode 100644
index 00000000..e7c653e3
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/fixtures/sample-brief.md
@@ -0,0 +1,5 @@
+# Auth service feature brief
+
+- Build the JWT auth endpoint
+- Add IP rate limiting on login
+- Write the integration test suite
diff --git a/plugins/omo/components/ultragoal/test/fixtures/sample-plan.json b/plugins/omo/components/ultragoal/test/fixtures/sample-plan.json
new file mode 100644
index 00000000..f49feee3
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/fixtures/sample-plan.json
@@ -0,0 +1,108 @@
+{
+ "version": 1,
+ "createdAt": "2026-05-23T00:00:00.000Z",
+ "codexGoalMode": "aggregate",
+ "codexObjective": "Complete the durable ultragoal plan in .omo/ultragoal/goals.json...",
+ "codexObjectiveAliases": [],
+ "goals": [
+ {
+ "id": "G001",
+ "title": "Build auth service",
+ "objective": "Implement JWT auth endpoint",
+ "status": "pending",
+ "successCriteria": [
+ {
+ "id": "C001",
+ "scenario": "valid login returns 200",
+ "userModel": "happy",
+ "expectedEvidence": "curl /login -d '{...}' returns 200 + token",
+ "capturedEvidence": null,
+ "status": "pending"
+ },
+ {
+ "id": "C002",
+ "scenario": "invalid creds return 401",
+ "userModel": "edge",
+ "expectedEvidence": "curl /login -d '{bad}' returns 401",
+ "capturedEvidence": null,
+ "status": "pending"
+ },
+ {
+ "id": "C003",
+ "scenario": "no regression in /health",
+ "userModel": "regression",
+ "expectedEvidence": "GET /health returns 200 OK after auth merge",
+ "capturedEvidence": null,
+ "status": "pending"
+ }
+ ]
+ },
+ {
+ "id": "G002",
+ "title": "Add rate limiting",
+ "objective": "Throttle login by IP",
+ "status": "in_progress",
+ "successCriteria": [
+ {
+ "id": "C001",
+ "scenario": "limit kicks at N reqs",
+ "userModel": "happy",
+ "expectedEvidence": "100 reqs from same IP -> last is 429",
+ "capturedEvidence": null,
+ "status": "pending"
+ },
+ {
+ "id": "C002",
+ "scenario": "different IPs not affected",
+ "userModel": "edge",
+ "expectedEvidence": "concurrent 2 IPs both succeed",
+ "capturedEvidence": null,
+ "status": "pending"
+ },
+ {
+ "id": "C003",
+ "scenario": "limiter does not block /health",
+ "userModel": "regression",
+ "expectedEvidence": "/health unaffected during throttle",
+ "capturedEvidence": null,
+ "status": "pending"
+ }
+ ]
+ },
+ {
+ "id": "G003",
+ "title": "Integration tests",
+ "objective": "End-to-end suite",
+ "status": "complete",
+ "successCriteria": [
+ {
+ "id": "C001",
+ "scenario": "all int tests green",
+ "userModel": "happy",
+ "expectedEvidence": "npm run test:integration exit 0",
+ "capturedEvidence": "npm run test:integration exit 0, 12/12 tests",
+ "status": "pass",
+ "capturedAt": "2026-05-23T00:30:00.000Z"
+ },
+ {
+ "id": "C002",
+ "scenario": "no flaky 3x rerun",
+ "userModel": "edge",
+ "expectedEvidence": "3 reruns all green",
+ "capturedEvidence": "3 reruns all green, no flakes",
+ "status": "pass",
+ "capturedAt": "2026-05-23T00:31:00.000Z"
+ },
+ {
+ "id": "C003",
+ "scenario": "no new console errors",
+ "userModel": "regression",
+ "expectedEvidence": "0 errors in build log",
+ "capturedEvidence": "no console errors",
+ "status": "pass",
+ "capturedAt": "2026-05-23T00:32:00.000Z"
+ }
+ ]
+ }
+ ]
+}
diff --git a/plugins/omo/components/ultragoal/test/fixtures/sample-quality-gate.json b/plugins/omo/components/ultragoal/test/fixtures/sample-quality-gate.json
new file mode 100644
index 00000000..fb63bbb9
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/fixtures/sample-quality-gate.json
@@ -0,0 +1,18 @@
+{
+ "aiSlopCleaner": { "status": "passed", "evidence": "no slop detected after cleaner run" },
+ "verification": {
+ "status": "passed",
+ "commands": ["npm test", "npm run build"],
+ "evidence": "all tests pass + build green"
+ },
+ "codeReview": {
+ "recommendation": "APPROVE",
+ "architectStatus": "CLEAR",
+ "evidence": "review synthesis: ship it"
+ },
+ "criteriaCoverage": {
+ "totalCriteria": 9,
+ "passCount": 9,
+ "adversarialClassesCovered": ["malformed_input", "prompt_injection", "stale_state"]
+ }
+}
diff --git a/plugins/omo/components/ultragoal/test/fixtures/steering-proposal.json b/plugins/omo/components/ultragoal/test/fixtures/steering-proposal.json
new file mode 100644
index 00000000..7a1e567d
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/fixtures/steering-proposal.json
@@ -0,0 +1,8 @@
+{
+ "kind": "add_subgoal",
+ "title": "Investigate auth blocker",
+ "objective": "Validate the blocker, capture evidence, and report findings.",
+ "evidence": "log/test output showing the blocker",
+ "rationale": "blocker materially changes safe execution order",
+ "source": "cli"
+}
diff --git a/plugins/omo/components/ultragoal/test/fixtures/user-prompt-submit.json b/plugins/omo/components/ultragoal/test/fixtures/user-prompt-submit.json
new file mode 100644
index 00000000..0f6e079e
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/fixtures/user-prompt-submit.json
@@ -0,0 +1,10 @@
+{
+ "cwd": "/repo",
+ "hook_event_name": "UserPromptSubmit",
+ "model": "gpt-5.5",
+ "permission_mode": "default",
+ "prompt": "OMO_ULTRAGOAL_STEER: {\"kind\":\"annotate_ledger\",\"source\":\"user_prompt_submit\",\"evidence\":\"test note\",\"rationale\":\"testing hook\"}",
+ "session_id": "s1",
+ "transcript_path": "/tmp/transcript.log",
+ "turn_id": "t1"
+}
diff --git a/plugins/omo/components/ultragoal/test/goal-status.test.ts b/plugins/omo/components/ultragoal/test/goal-status.test.ts
new file mode 100644
index 00000000..9b79b8bb
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/goal-status.test.ts
@@ -0,0 +1,327 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ aggregateCodexObjective,
+ codexGoalMode,
+ compatibleCodexObjectives,
+ expectedCodexObjective,
+ firstUnresolvedCriterion,
+ hasAllCriteriaPass,
+ isFinalRunCompletionCandidate,
+ isUltragoalDone,
+ ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE,
+} from "../src/goal-status.js";
+import type { UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+
+function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {
+ return {
+ id: "C001",
+ scenario: "happy path",
+ userModel: "happy",
+ expectedEvidence: "observable proof",
+ capturedEvidence: null,
+ status: "pending",
+ ...overrides,
+ };
+}
+
+function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {
+ return {
+ id: "G001",
+ title: "Goal one",
+ objective: "Complete goal one",
+ status: "pending",
+ successCriteria: [],
+ attempt: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ ...overrides,
+ };
+}
+
+function makePlan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {
+ return {
+ version: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ briefPath: ".omo/ultragoal/brief.md",
+ goalsPath: ".omo/ultragoal/goals.json",
+ ledgerPath: ".omo/ultragoal/ledger.jsonl",
+ goals: [],
+ ...overrides,
+ };
+}
+
+describe("isUltragoalDone", () => {
+ it("returns true when all goals complete", () => {
+ // given
+ const plan = makePlan({
+ goals: [makeGoal({ status: "complete" }), makeGoal({ id: "G002", status: "complete" })],
+ });
+
+ // when
+ const done = isUltragoalDone(plan);
+
+ // then
+ expect(done).toBe(true);
+ });
+
+ it("returns false when any pending remains", () => {
+ // given
+ const plan = makePlan({ goals: [makeGoal({ status: "complete" }), makeGoal({ id: "G002", status: "pending" })] });
+
+ // when
+ const done = isUltragoalDone(plan);
+
+ // then
+ expect(done).toBe(false);
+ });
+
+ it("treats superseded-with-complete-replacements as resolved", () => {
+ // given
+ const replacement = makeGoal({ id: "G002", status: "complete" });
+ const superseded = makeGoal({
+ id: "G001",
+ status: "pending",
+ steeringStatus: "superseded",
+ supersededBy: [replacement.id],
+ });
+ const plan = makePlan({ goals: [superseded, replacement] });
+
+ // when
+ const done = isUltragoalDone(plan);
+
+ // then
+ expect(done).toBe(true);
+ });
+});
+
+describe("isFinalRunCompletionCandidate", () => {
+ it("returns true when only one unresolved goal remains", () => {
+ // given
+ const finalGoal = makeGoal({ id: "G002", status: "pending" });
+ const plan = makePlan({ goals: [makeGoal({ status: "complete" }), finalGoal] });
+
+ // when
+ const candidate = isFinalRunCompletionCandidate(plan, finalGoal);
+
+ // then
+ expect(candidate).toBe(true);
+ });
+
+ it("returns false when multiple unresolved", () => {
+ // given
+ const goal = makeGoal({ id: "G001", status: "pending" });
+ const plan = makePlan({ goals: [goal, makeGoal({ id: "G002", status: "pending" })] });
+
+ // when
+ const candidate = isFinalRunCompletionCandidate(plan, goal);
+
+ // then
+ expect(candidate).toBe(false);
+ });
+});
+
+describe("codexGoalMode", () => {
+ it("defaults to per_story when undefined", () => {
+ // when
+ const mode = codexGoalMode(makePlan());
+
+ // then
+ expect(mode).toBe("per_story");
+ });
+
+ it("returns aggregate when explicitly aggregate", () => {
+ // when
+ const mode = codexGoalMode(makePlan({ codexGoalMode: "aggregate" }));
+
+ // then
+ expect(mode).toBe("aggregate");
+ });
+});
+
+describe("expectedCodexObjective", () => {
+ it("aggregate mode returns plan.codexObjective", () => {
+ // given
+ const goal = makeGoal({ objective: "story objective" });
+ const plan = makePlan({ codexGoalMode: "aggregate", codexObjective: "aggregate objective" });
+
+ // when
+ const objective = expectedCodexObjective(plan, goal);
+
+ // then
+ expect(objective).toBe("aggregate objective");
+ });
+
+ it("aggregate mode falls back to ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE when codexObjective missing", () => {
+ // given
+ const goal = makeGoal({ objective: "story objective" });
+ const plan = makePlan({ codexGoalMode: "aggregate" });
+
+ // when
+ const objective = expectedCodexObjective(plan, goal);
+
+ // then
+ expect(objective).toBe(ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE);
+ });
+
+ it("per_story mode returns goal.objective", () => {
+ // given
+ const goal = makeGoal({ objective: "story objective" });
+ const plan = makePlan({ codexGoalMode: "per_story", codexObjective: "aggregate objective" });
+
+ // when
+ const objective = expectedCodexObjective(plan, goal);
+
+ // then
+ expect(objective).toBe("story objective");
+ });
+});
+
+describe("aggregateCodexObjective", () => {
+ it("returns plan.codexObjective when set", () => {
+ // when
+ const objective = aggregateCodexObjective(makePlan({ codexObjective: "aggregate objective" }));
+
+ // then
+ expect(objective).toBe("aggregate objective");
+ });
+
+ it("falls back to ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE", () => {
+ // when
+ const objective = aggregateCodexObjective(makePlan());
+
+ // then
+ expect(objective).toBe(ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE);
+ });
+});
+
+describe("compatibleCodexObjectives", () => {
+ it("includes aggregate objective + aliases", () => {
+ // given
+ const plan = makePlan({
+ codexObjective: "aggregate objective",
+ codexObjectiveAliases: ["legacy one", "legacy two"],
+ });
+
+ // when
+ const objectives = compatibleCodexObjectives(plan);
+
+ // then
+ expect(objectives).toEqual(["aggregate objective", "legacy one", "legacy two"]);
+ });
+});
+
+describe("hasAllCriteriaPass", () => {
+ it("returns true when all criteria pass", () => {
+ // given
+ const goal = makeGoal({
+ successCriteria: [makeCriterion({ status: "pass" }), makeCriterion({ id: "C002", status: "pass" })],
+ });
+
+ // when
+ const passed = hasAllCriteriaPass(goal);
+
+ // then
+ expect(passed).toBe(true);
+ });
+
+ it("returns false when any criterion pending", () => {
+ // given
+ const goal = makeGoal({
+ successCriteria: [makeCriterion({ status: "pass" }), makeCriterion({ id: "C002", status: "pending" })],
+ });
+
+ // when
+ const passed = hasAllCriteriaPass(goal);
+
+ // then
+ expect(passed).toBe(false);
+ });
+
+ it("returns false when any criterion fail", () => {
+ // given
+ const goal = makeGoal({
+ successCriteria: [makeCriterion({ status: "pass" }), makeCriterion({ id: "C002", status: "fail" })],
+ });
+
+ // when
+ const passed = hasAllCriteriaPass(goal);
+
+ // then
+ expect(passed).toBe(false);
+ });
+
+ it("returns false when any criterion blocked", () => {
+ // given
+ const goal = makeGoal({
+ successCriteria: [makeCriterion({ status: "pass" }), makeCriterion({ id: "C002", status: "blocked" })],
+ });
+
+ // when
+ const passed = hasAllCriteriaPass(goal);
+
+ // then
+ expect(passed).toBe(false);
+ });
+
+ it("returns false for empty criteria array", () => {
+ // when
+ const passed = hasAllCriteriaPass(makeGoal({ successCriteria: [] }));
+
+ // then
+ expect(passed).toBe(false);
+ });
+});
+
+describe("firstUnresolvedCriterion", () => {
+ it("returns first non-pass criterion", () => {
+ // given
+ const unresolved = makeCriterion({ id: "C002", status: "fail" });
+ const goal = makeGoal({ successCriteria: [makeCriterion({ status: "pass" }), unresolved] });
+
+ // when
+ const criterion = firstUnresolvedCriterion(goal);
+
+ // then
+ expect(criterion).toBe(unresolved);
+ });
+
+ it("returns undefined when all pass", () => {
+ // given
+ const goal = makeGoal({
+ successCriteria: [makeCriterion({ status: "pass" }), makeCriterion({ id: "C002", status: "pass" })],
+ });
+
+ // when
+ const criterion = firstUnresolvedCriterion(goal);
+
+ // then
+ expect(criterion).toBeUndefined();
+ });
+
+ it("returns first pending in mixed pass/pending/fail", () => {
+ // given
+ const pending = makeCriterion({ id: "C002", status: "pending" });
+ const goal = makeGoal({
+ successCriteria: [makeCriterion({ status: "pass" }), pending, makeCriterion({ id: "C003", status: "fail" })],
+ });
+
+ // when
+ const criterion = firstUnresolvedCriterion(goal);
+
+ // then
+ expect(criterion).toBe(pending);
+ });
+});
+
+describe("ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE", () => {
+ it("references the .omo/ultragoal path and excludes the legacy workspace", () => {
+ const legacyWorkspace = [".", "om", "x"].join("");
+
+ expect(ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE).toContain(".omo/ultragoal");
+ expect(ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE).not.toContain(legacyWorkspace);
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/package-smoke.test.ts b/plugins/omo/components/ultragoal/test/package-smoke.test.ts
new file mode 100644
index 00000000..a1181e52
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/package-smoke.test.ts
@@ -0,0 +1,106 @@
+// biome-ignore-all format: smoke test pulls verbatim JSON for structural assertion.
+import { readFile, stat } from "node:fs/promises";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+
+const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+
+async function readText(relative: string): Promise<string> {
+ return readFile(join(repoRoot, relative), "utf8");
+}
+
+async function readJson(relative: string): Promise<unknown> {
+ return JSON.parse(await readText(relative));
+}
+
+describe("package.json", () => {
+ it("declares ESM + npm + Node >=20", async () => {
+ const pkg = await readJson("package.json") as Record<string, unknown>;
+ expect(pkg["type"]).toBe("module");
+ expect(pkg["packageManager"]).toBe("[email protected]");
+ expect((pkg["engines"] as Record<string, unknown>)["node"]).toBe(">=20.0.0");
+ });
+
+ it("exposes the omo binary pointing at dist/cli.js", async () => {
+ const pkg = await readJson("package.json") as Record<string, unknown>;
+ const bin = pkg["bin"] as Record<string, string>;
+ expect(bin["omo"]).toBe("./dist/cli.js");
+ });
+
+ it("ships the expected files for npm publish", async () => {
+ const pkg = await readJson("package.json") as Record<string, unknown>;
+ const files = pkg["files"] as readonly string[];
+ expect(files).toContain("dist");
+ expect(files).toContain("hooks");
+ expect(files).toContain("skills");
+ expect(files).not.toContain(".codex-plugin");
+ });
+});
+
+describe("component plugin identity", () => {
+ it("is owned by the aggregate OMO plugin root", async () => {
+ await expect(readText(".codex-plugin/plugin.json")).rejects.toMatchObject({ code: "ENOENT" });
+ });
+});
+
+describe("hooks/hooks.json", () => {
+ it("registers UserPromptSubmit with PLUGIN_ROOT interpolation", async () => {
+ const hooks = await readJson("hooks/hooks.json") as Record<string, unknown>;
+ const events = (hooks["hooks"] as Record<string, unknown>)["UserPromptSubmit"] as readonly Record<string, unknown>[];
+ expect(events.length).toBeGreaterThan(0);
+ const command = ((events[0]?.["hooks"] as readonly Record<string, unknown>[])[0]?.["command"]) as string;
+ expect(command).toContain(`$${"{PLUGIN_ROOT}"}`);
+ expect(command).toContain("dist/cli.js");
+ expect(command).toContain("hook user-prompt-submit");
+ });
+});
+
+describe("src/cli.ts", () => {
+ it("starts with #!/usr/bin/env node shebang", async () => {
+ const text = await readText("src/cli.ts");
+ expect(text.split("\n")[0]).toBe("#!/usr/bin/env node");
+ });
+});
+
+describe("skills/ultragoal/SKILL.md", () => {
+ it("exists", async () => {
+ const info = await stat(join(repoRoot, "skills/ultragoal/SKILL.md"));
+ expect(info.isFile()).toBe(true);
+ });
+
+ it("contains no omx references", async () => {
+ const text = await readText("skills/ultragoal/SKILL.md");
+ expect(text.toLowerCase()).not.toContain("omx");
+ });
+
+ it("references the success criteria and record-evidence vocabulary", async () => {
+ const text = await readText("skills/ultragoal/SKILL.md");
+ expect(text.toLowerCase()).toMatch(/success criteria|successcriteria/);
+ expect(text.toLowerCase()).toContain("record-evidence");
+ });
+
+ it("uses the .omo workspace path", async () => {
+ const text = await readText("skills/ultragoal/SKILL.md");
+ expect(text).toContain(".omo/ultragoal");
+ });
+});
+
+describe("source LOC budget", () => {
+ it("every source file stays at or under 250 pure LOC", async () => {
+ const files = [
+ "src/types.ts", "src/paths.ts", "src/plan-io.ts", "src/plan-crud.ts", "src/goal-status.ts",
+ "src/evidence.ts", "src/quality-gate.ts", "src/checkpoint.ts", "src/review-blockers.ts",
+ "src/steering.ts", "src/codex-goal-instruction.ts", "src/codex-goal-snapshot.ts", "src/codex-hook.ts",
+ "src/cli.ts", "src/cli-arg-parser.ts", "src/cli-output.ts", "src/cli-steering.ts", "src/cli-commands.ts",
+ ];
+ for (const file of files) {
+ const text = await readText(file);
+ const pure = text.split("\n").filter((line) => {
+ const trimmed = line.trim();
+ return trimmed.length > 0 && !trimmed.startsWith("//");
+ }).length;
+ expect(pure, `${file} pure LOC`).toBeLessThanOrEqual(250);
+ }
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/paths.test.ts b/plugins/omo/components/ultragoal/test/paths.test.ts
new file mode 100644
index 00000000..aa35f460
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/paths.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ repoRelative,
+ ultragoalBriefPath,
+ ultragoalDir,
+ ultragoalGoalsPath,
+ ultragoalLedgerPath,
+} from "../src/paths.ts";
+
+describe("ultragoalDir(repo)", () => {
+ it("returns repo + '/.omo/ultragoal'", () => {
+ // when/then
+ expect(ultragoalDir("/repo")).toBe("/repo/.omo/ultragoal");
+ });
+});
+
+describe("ultragoal*Path helpers", () => {
+ it("compose artifact filenames under ultragoalDir", () => {
+ // when/then
+ expect(ultragoalBriefPath("/r")).toBe("/r/.omo/ultragoal/brief.md");
+ expect(ultragoalGoalsPath("/r")).toBe("/r/.omo/ultragoal/goals.json");
+ expect(ultragoalLedgerPath("/r")).toBe("/r/.omo/ultragoal/ledger.jsonl");
+ });
+});
+
+describe("repoRelative", () => {
+ it("strips repo prefix when path is inside repo", () => {
+ // when/then
+ expect(repoRelative("/repo/.omo/ultragoal/goals.json", "/repo")).toBe(".omo/ultragoal/goals.json");
+ });
+
+ it("returns absolute when path is outside repo", () => {
+ // when/then
+ expect(repoRelative("/elsewhere/file", "/repo")).toBe("/elsewhere/file");
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/plan-crud.test.ts b/plugins/omo/components/ultragoal/test/plan-crud.test.ts
new file mode 100644
index 00000000..4d3d366c
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/plan-crud.test.ts
@@ -0,0 +1,256 @@
+import { mkdir, mkdtemp, readFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { ultragoalBriefPath, ultragoalGoalsPath, ultragoalLedgerPath } from "../src/paths.js";
+import {
+ addUltragoalGoal,
+ createUltragoalPlan,
+ deriveGoalCandidates,
+ seedDefaultSuccessCriteria,
+ startNextUltragoal,
+ summarizeUltragoalPlan,
+} from "../src/plan-crud.js";
+import { writePlan } from "../src/plan-io.js";
+import type { UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";
+import { UltragoalError } from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+
+async function makeRepo(): Promise<string> {
+ return mkdtemp(join(tmpdir(), "ug-crud-"));
+}
+
+async function readBriefFixture(): Promise<string> {
+ return readFile(join(process.cwd(), "test", "fixtures", "sample-brief.md"), "utf8");
+}
+
+async function ledgerKinds(repoRoot: string): Promise<string[]> {
+ const raw = await readFile(ultragoalLedgerPath(repoRoot), "utf8");
+ return raw
+ .split(/\r?\n/)
+ .filter(Boolean)
+ .map((line) => JSON.parse(line).kind);
+}
+
+function criterion(status: UltragoalSuccessCriterion["status"]): UltragoalSuccessCriterion {
+ const [base] = seedDefaultSuccessCriteria(0, "Implement auth endpoint");
+ if (base === undefined) throw new Error("expected seeded criterion");
+ return { ...base, status };
+}
+
+function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {
+ return {
+ id: "G001",
+ title: "Build auth service",
+ objective: "Implement JWT auth endpoint",
+ status: "pending",
+ successCriteria: seedDefaultSuccessCriteria(0, "Implement JWT auth endpoint"),
+ attempt: 0,
+ createdAt: NOW,
+ updatedAt: NOW,
+ ...overrides,
+ };
+}
+
+function makePlan(goals: UltragoalItem[]): UltragoalPlan {
+ return {
+ version: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ briefPath: ".omo/ultragoal/brief.md",
+ goalsPath: ".omo/ultragoal/goals.json",
+ ledgerPath: ".omo/ultragoal/ledger.jsonl",
+ codexGoalMode: "aggregate",
+ goals,
+ };
+}
+
+function scheduled(result: Awaited<ReturnType<typeof startNextUltragoal>>) {
+ if ("done" in result) throw new Error("expected scheduled goal");
+ return result;
+}
+
+describe("seedDefaultSuccessCriteria", () => {
+ it("produces 3 criteria with C001/C002/C003 ids", () => {
+ const cs = seedDefaultSuccessCriteria(0, "Implement auth endpoint");
+ expect(cs).toHaveLength(3);
+ expect(cs.map((c) => c.id)).toEqual(["C001", "C002", "C003"]);
+ });
+
+ it("covers happy + edge + regression user models", () => {
+ const cs = seedDefaultSuccessCriteria(0, "Implement auth endpoint");
+ expect(cs.map((c) => c.userModel).sort()).toEqual(["edge", "happy", "regression"]);
+ });
+
+ it("seeds all criteria as pending with null capturedEvidence", () => {
+ const cs = seedDefaultSuccessCriteria(0, "Implement auth endpoint");
+ for (const c of cs) {
+ expect(c.status).toBe("pending");
+ expect(c.capturedEvidence).toBeNull();
+ }
+ });
+});
+
+describe("createUltragoalPlan", () => {
+ it("creates .omo/ultragoal/{brief.md, goals.json, ledger.jsonl} in repoRoot", async () => {
+ const repoRoot = await makeRepo();
+ const brief = await readBriefFixture();
+
+ await createUltragoalPlan(repoRoot, { brief });
+
+ expect(await readFile(ultragoalBriefPath(repoRoot), "utf8")).toBe(brief.endsWith("\n") ? brief : `${brief}\n`);
+ expect(await readFile(ultragoalGoalsPath(repoRoot), "utf8")).toContain("G001-build-the-jwt-auth-endpoint");
+ expect(await ledgerKinds(repoRoot)).toEqual(["plan_created"]);
+ });
+
+ it("seeds at least 3 successCriteria per goal", async () => {
+ const plan = await createUltragoalPlan(await makeRepo(), { brief: await readBriefFixture() });
+
+ expect(plan.goals).toHaveLength(3);
+ expect(plan.goals.every((goal) => goal.successCriteria.length >= 3)).toBe(true);
+ });
+
+ it("refuses overwrite of an existing plan without --force", async () => {
+ const repoRoot = await makeRepo();
+ await createUltragoalPlan(repoRoot, { brief: "first" });
+
+ await expect(createUltragoalPlan(repoRoot, { brief: "second" })).rejects.toThrow(UltragoalError);
+ await expect(createUltragoalPlan(repoRoot, { brief: "second" })).rejects.toThrow("Refusing to overwrite");
+ });
+
+ it("aggregate is the default codexGoalMode", async () => {
+ const plan = await createUltragoalPlan(await makeRepo(), { brief: "Ship the feature" });
+
+ expect(plan.codexGoalMode).toBe("aggregate");
+ expect(plan.codexObjective).toContain(".omo/ultragoal/goals.json");
+ });
+});
+
+describe("deriveGoalCandidates", () => {
+ it("extracts bullets as goals", () => {
+ expect(deriveGoalCandidates("# Brief\n\n- Build auth\n- Add tests")).toEqual([
+ { title: "Build auth", objective: "Build auth" },
+ { title: "Add tests", objective: "Add tests" },
+ ]);
+ });
+
+ it("falls back to paragraph parsing when no bullets", () => {
+ expect(deriveGoalCandidates("First objective.\n\nSecond objective.").map((goal) => goal.objective)).toEqual([
+ "First objective.",
+ "Second objective.",
+ ]);
+ });
+
+ it("returns single default goal for empty/whitespace brief", () => {
+ expect(deriveGoalCandidates(" \n\t ")).toEqual([
+ { title: "Complete the requested project objective.", objective: "Complete the requested project objective." },
+ ]);
+ });
+});
+
+describe("addUltragoalGoal", () => {
+ it("appends a new goal to plan with seeded successCriteria", async () => {
+ const repoRoot = await makeRepo();
+ await createUltragoalPlan(repoRoot, { brief: "Build auth" });
+
+ const { plan, goal } = await addUltragoalGoal(repoRoot, { title: "Add rate limit", objective: "Throttle login" });
+
+ expect(plan.goals).toHaveLength(2);
+ expect(goal.id).toBe("G002-add-rate-limit");
+ expect(goal.successCriteria).toHaveLength(3);
+ });
+
+ it("appends a ledger entry for goal_added", async () => {
+ const repoRoot = await makeRepo();
+ await createUltragoalPlan(repoRoot, { brief: "Build auth" });
+
+ await addUltragoalGoal(repoRoot, { title: "Add rate limit", objective: "Throttle login" });
+
+ expect(await ledgerKinds(repoRoot)).toEqual(["plan_created", "goal_added"]);
+ });
+});
+
+describe("startNextUltragoal", () => {
+ it("picks the first pending goal", async () => {
+ const repoRoot = await makeRepo();
+ await createUltragoalPlan(repoRoot, { brief: "- First\n- Second" });
+
+ const result = scheduled(await startNextUltragoal(repoRoot, {}));
+
+ expect(result.goal.id).toBe("G001-first");
+ expect(result.goal.status).toBe("in_progress");
+ expect(result.resumed).toBe(false);
+ });
+
+ it("resumes the in_progress goal when one exists", async () => {
+ const repoRoot = await makeRepo();
+ const plan = await createUltragoalPlan(repoRoot, { brief: "- First\n- Second" });
+ const active = makeGoal({ ...plan.goals[1], status: "in_progress" });
+ await writePlan(repoRoot, { ...plan, goals: [makeGoal({ ...plan.goals[0] }), active], activeGoalId: active.id });
+
+ const result = scheduled(await startNextUltragoal(repoRoot, {}));
+
+ expect(result.goal.id).toBe(active.id);
+ expect(result.resumed).toBe(true);
+ });
+
+ it("with retryFailed picks first failed (non-blocked) goal", async () => {
+ const repoRoot = await makeRepo();
+ const failed = makeGoal({ status: "failed", failureReason: "flake" });
+ await mkdir(join(repoRoot, ".omo", "ultragoal"), { recursive: true });
+ await writePlan(repoRoot, makePlan([failed]));
+
+ const result = scheduled(await startNextUltragoal(repoRoot, { retryFailed: true }));
+
+ expect(result.goal.id).toBe("G001");
+ expect(result.goal.attempt).toBe(1);
+ expect(await ledgerKinds(repoRoot)).toEqual(["goal_retried", "goal_started"]);
+ });
+
+ it("returns { done: true } when no eligible goals remain", async () => {
+ const repoRoot = await makeRepo();
+ await mkdir(join(repoRoot, ".omo", "ultragoal"), { recursive: true });
+ await writePlan(repoRoot, makePlan([makeGoal({ status: "complete" })]));
+
+ const result = await startNextUltragoal(repoRoot, {});
+
+ expect(result).toMatchObject({ done: true });
+ });
+});
+
+describe("summarizeUltragoalPlan", () => {
+ it("counts goals by status", () => {
+ const plan = makePlan([
+ makeGoal({ id: "G001", status: "pending" }),
+ makeGoal({ id: "G002", status: "in_progress" }),
+ makeGoal({ id: "G003", status: "complete" }),
+ makeGoal({ id: "G004", status: "failed" }),
+ makeGoal({ id: "G005", status: "blocked", steeringStatus: "blocked" }),
+ makeGoal({ id: "G006", status: "review_blocked" }),
+ makeGoal({ id: "G007", status: "needs_user_decision", steeringStatus: "superseded" }),
+ ]);
+
+ expect(summarizeUltragoalPlan(plan)).toMatchObject({
+ total: 7,
+ pending: 1,
+ in_progress: 1,
+ complete: 1,
+ failed: 1,
+ blocked: 1,
+ review_blocked: 1,
+ needs_user_decision: 1,
+ superseded: 1,
+ });
+ });
+
+ it("aggregates criteria pass/pending/fail/blocked across all goals", () => {
+ const plan = makePlan([
+ makeGoal({ successCriteria: [criterion("pass"), criterion("pending")] }),
+ makeGoal({ id: "G002", successCriteria: [criterion("fail"), criterion("blocked"), criterion("pending")] }),
+ ]);
+
+ expect(summarizeUltragoalPlan(plan).criteria).toEqual({ total: 5, pass: 1, pending: 2, fail: 1, blocked: 1 });
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/plan-io.test.ts b/plugins/omo/components/ultragoal/test/plan-io.test.ts
new file mode 100644
index 00000000..9791e5d9
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/plan-io.test.ts
@@ -0,0 +1,239 @@
+import { copyFile, mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+import { ultragoalDir, ultragoalGoalsPath, ultragoalLedgerPath } from "../src/paths.js";
+import {
+ appendLedger,
+ readSteeringLedgerEntries,
+ readUltragoalPlan,
+ withUltragoalMutationLock,
+ writePlan,
+} from "../src/plan-io.js";
+import type { UltragoalItem, UltragoalLedgerEntry, UltragoalPlan } from "../src/types.js";
+import { UltragoalError } from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+const STABLE_OBJECTIVE =
+ "Complete the durable ultragoal plan in .omo/ultragoal/goals.json, including later accepted/appended stories, under the original brief constraints; use .omo/ultragoal/ledger.jsonl as the audit trail.";
+
+function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {
+ return {
+ id: "G001",
+ title: "Build auth service",
+ objective: "Implement JWT auth endpoint",
+ status: "pending",
+ successCriteria: [],
+ attempt: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ ...overrides,
+ };
+}
+
+function makePlan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {
+ return {
+ version: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ briefPath: ".omo/ultragoal/brief.md",
+ goalsPath: ".omo/ultragoal/goals.json",
+ ledgerPath: ".omo/ultragoal/ledger.jsonl",
+ codexGoalMode: "aggregate",
+ codexObjective: STABLE_OBJECTIVE,
+ codexObjectiveAliases: [],
+ goals: [makeGoal()],
+ ...overrides,
+ };
+}
+
+function entry(kind: UltragoalLedgerEntry["kind"], goalId = "G001"): UltragoalLedgerEntry {
+ return { at: NOW, kind, goalId };
+}
+
+async function makeRepo(): Promise<string> {
+ return mkdtemp(join(tmpdir(), "ug-io-"));
+}
+
+async function writeRawPlan(repoRoot: string, plan: UltragoalPlan): Promise<void> {
+ await mkdir(ultragoalDir(repoRoot), { recursive: true });
+ await writeFile(ultragoalGoalsPath(repoRoot), `${JSON.stringify(plan, null, 2)}\n`, "utf8");
+}
+
+async function readLedgerLines(repoRoot: string): Promise<string[]> {
+ const raw = await readFile(ultragoalLedgerPath(repoRoot), "utf8");
+ return raw.split(/\r?\n/).filter(Boolean);
+}
+
+describe("readUltragoalPlan", () => {
+ let repoRoot = "";
+
+ beforeEach(async () => {
+ // given
+ repoRoot = await makeRepo();
+ });
+
+ it("throws UltragoalError when goals.json is missing", async () => {
+ // when/then
+ await expect(readUltragoalPlan(repoRoot)).rejects.toThrow(UltragoalError);
+ await expect(readUltragoalPlan(repoRoot)).rejects.toThrow("omo ultragoal create-goals");
+ });
+
+ it("returns parsed plan when fixture is present", async () => {
+ // given
+ await mkdir(ultragoalDir(repoRoot), { recursive: true });
+ await copyFile(join(process.cwd(), "test", "fixtures", "sample-plan.json"), ultragoalGoalsPath(repoRoot));
+
+ // when
+ const plan = await readUltragoalPlan(repoRoot);
+
+ // then
+ expect(plan.version).toBe(1);
+ expect(plan.codexGoalMode).toBe("aggregate");
+ expect(plan.goals).toHaveLength(3);
+ expect(plan.goals[0]?.successCriteria).toHaveLength(3);
+ });
+
+ it("migrates legacy aggregate objective on read + writes aggregate_objective_migrated ledger entry + retains alias", async () => {
+ // given
+ const legacyObjective = "Complete all ultragoal stories in .omo/ultragoal/goals.json: G001 Build auth service";
+ await writeRawPlan(repoRoot, makePlan({ codexObjective: legacyObjective }));
+
+ // when
+ const plan = await readUltragoalPlan(repoRoot);
+
+ // then
+ expect(plan.codexObjective).toBe(STABLE_OBJECTIVE);
+ expect(plan.codexObjectiveAliases).toContain(legacyObjective);
+ const persisted = JSON.parse(await readFile(ultragoalGoalsPath(repoRoot), "utf8"));
+ expect(persisted).toMatchObject({ codexObjective: STABLE_OBJECTIVE, codexObjectiveAliases: [legacyObjective] });
+ const lines = await readLedgerLines(repoRoot);
+ expect(lines).toHaveLength(1);
+ expect(JSON.parse(lines[0] ?? "{}")).toMatchObject({
+ kind: "aggregate_objective_migrated",
+ before: { codexObjective: legacyObjective },
+ });
+ });
+});
+
+describe("writePlan", () => {
+ it("writes goals.json atomically with no temp file left behind", async () => {
+ // given
+ const repoRoot = await makeRepo();
+
+ // when
+ await writePlan(repoRoot, makePlan());
+
+ // then
+ const raw = await readFile(ultragoalGoalsPath(repoRoot), "utf8");
+ expect(JSON.parse(raw)).toMatchObject({ version: 1, goals: [{ id: "G001" }] });
+ expect((await readdir(ultragoalDir(repoRoot))).filter((name) => name.endsWith(".tmp"))).toEqual([]);
+ });
+
+ it("overwrites existing file", async () => {
+ // given
+ const repoRoot = await makeRepo();
+ await writePlan(repoRoot, makePlan({ codexObjective: "first" }));
+
+ // when
+ await writePlan(repoRoot, makePlan({ codexObjective: "second" }));
+
+ // then
+ expect(JSON.parse(await readFile(ultragoalGoalsPath(repoRoot), "utf8"))).toMatchObject({
+ codexObjective: "second",
+ });
+ });
+});
+
+describe("appendLedger", () => {
+ it("appends a single JSONL line to ledger.jsonl", async () => {
+ // given
+ const repoRoot = await makeRepo();
+ const ledgerEntry = entry("goal_started");
+
+ // when
+ await appendLedger(repoRoot, ledgerEntry);
+
+ // then
+ expect(await readLedgerLines(repoRoot)).toEqual([JSON.stringify(ledgerEntry)]);
+ });
+
+ it("creates ledger.jsonl if missing", async () => {
+ // given
+ const repoRoot = await makeRepo();
+
+ // when
+ await appendLedger(repoRoot, entry("goal_completed"));
+
+ // then
+ expect(await readFile(ultragoalLedgerPath(repoRoot), "utf8")).toContain("goal_completed");
+ });
+
+ it("preserves prior entries", async () => {
+ // given
+ const repoRoot = await makeRepo();
+ const first = entry("goal_started");
+ const second = entry("goal_completed");
+
+ // when
+ await appendLedger(repoRoot, first);
+ await appendLedger(repoRoot, second);
+
+ // then
+ expect(await readLedgerLines(repoRoot)).toEqual([JSON.stringify(first), JSON.stringify(second)]);
+ });
+});
+
+describe("readSteeringLedgerEntries", () => {
+ it("returns only steering-related event kinds", async () => {
+ // given
+ const repoRoot = await makeRepo();
+ await appendLedger(repoRoot, entry("steering_accepted"));
+ await appendLedger(repoRoot, entry("goal_started"));
+ await appendLedger(repoRoot, entry("steering_rejected"));
+ await appendLedger(repoRoot, entry("criteria_revised"));
+
+ // when
+ const entries = await readSteeringLedgerEntries(repoRoot);
+
+ // then
+ expect(entries.map((item) => item.kind)).toEqual(["steering_accepted", "steering_rejected", "criteria_revised"]);
+ });
+
+ it("returns empty array when ledger missing", async () => {
+ // given
+ const repoRoot = await makeRepo();
+
+ // when/then
+ await expect(readSteeringLedgerEntries(repoRoot)).resolves.toEqual([]);
+ });
+});
+
+describe("withUltragoalMutationLock", () => {
+ it("serializes concurrent invocations", async () => {
+ // given
+ const repoRoot = await makeRepo();
+ const counterPath = join(repoRoot, "counter.txt");
+ let active = 0;
+ let maxActive = 0;
+ await writeFile(counterPath, "0", "utf8");
+
+ // when
+ await Promise.all(
+ [1, 2, 3].map((_) =>
+ withUltragoalMutationLock(repoRoot, async () => {
+ active += 1;
+ maxActive = Math.max(maxActive, active);
+ const current = Number(await readFile(counterPath, "utf8"));
+ await Promise.resolve();
+ await writeFile(counterPath, String(current + 1), "utf8");
+ active -= 1;
+ }),
+ ),
+ );
+
+ // then
+ expect(maxActive).toBe(1);
+ expect(await readFile(counterPath, "utf8")).toBe("3");
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/quality-gate.test.ts b/plugins/omo/components/ultragoal/test/quality-gate.test.ts
new file mode 100644
index 00000000..afb97573
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/quality-gate.test.ts
@@ -0,0 +1,203 @@
+import { readFile } from "node:fs/promises";
+
+import { describe, expect, it } from "vitest";
+
+import {
+ classifyExternalAuthorizationBlocker,
+ clearGoalBlockerFields,
+ normalizeBlockerEvidence,
+ sameBlockerOccurrences,
+ validateQualityGate,
+} from "../src/quality-gate.js";
+import type { UltragoalItem, UltragoalPlan } from "../src/types.js";
+import { UltragoalError } from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+const VALID_GATE = {
+ aiSlopCleaner: { status: "passed", evidence: "no slop detected after cleaner run" },
+ verification: { status: "passed", commands: ["npm test"], evidence: "all tests pass" },
+ codeReview: { recommendation: "APPROVE", architectStatus: "CLEAR", evidence: "ship it" },
+ criteriaCoverage: { totalCriteria: 2, passCount: 2, adversarialClassesCovered: ["malformed_input"] },
+} as const;
+
+interface GoalWithBlocker extends UltragoalItem {
+ blocker?: { readonly signature: string };
+ blockerEvidence?: string;
+ blockerOccurrences?: number;
+ blockedAt?: string;
+}
+
+function makeGate(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return { ...VALID_GATE, ...overrides };
+}
+
+function getQualityGateError(input: unknown): UltragoalError {
+ try {
+ validateQualityGate(input);
+ } catch (error) {
+ if (error instanceof UltragoalError) return error;
+ throw error;
+ }
+ throw new Error("Expected UltragoalError");
+}
+
+function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {
+ return {
+ id: "G001",
+ title: "Goal one",
+ objective: "Complete goal one",
+ status: "pending",
+ successCriteria: [],
+ attempt: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ ...overrides,
+ };
+}
+
+function makePlan(goals: UltragoalItem[]): UltragoalPlan {
+ return {
+ version: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ briefPath: ".omo/ultragoal/brief.md",
+ goalsPath: ".omo/ultragoal/goals.json",
+ ledgerPath: ".omo/ultragoal/ledger.jsonl",
+ goals,
+ };
+}
+
+describe("validateQualityGate", () => {
+ it("accepts valid quality gate from fixture", async () => {
+ // given
+ const raw = await readFile(new URL("./fixtures/sample-quality-gate.json", import.meta.url), "utf8");
+ const parsed: unknown = JSON.parse(raw);
+
+ // when
+ const gate = validateQualityGate(parsed);
+
+ // then
+ expect(gate.aiSlopCleaner.status).toBe("passed");
+ expect(gate).toMatchObject({ criteriaCoverage: { totalCriteria: 9, passCount: 9 } });
+ });
+
+ it("throws UltragoalError when aiSlopCleaner missing", () => {
+ // when
+ const error = getQualityGateError(makeGate({ aiSlopCleaner: undefined }));
+
+ // then
+ expect(error.code).toBe("ULTRAGOAL_QUALITY_GATE_INVALID");
+ });
+
+ it("throws UltragoalError when verification missing", () => {
+ // when
+ const error = getQualityGateError(makeGate({ verification: undefined }));
+
+ // then
+ expect(error.code).toBe("ULTRAGOAL_QUALITY_GATE_INVALID");
+ });
+
+ it("throws UltragoalError when codeReview missing", () => {
+ // when
+ const error = getQualityGateError(makeGate({ codeReview: undefined }));
+
+ // then
+ expect(error.code).toBe("ULTRAGOAL_QUALITY_GATE_INVALID");
+ });
+
+ it("throws UltragoalError when criteriaCoverage missing (NEW)", () => {
+ // when
+ const error = getQualityGateError(makeGate({ criteriaCoverage: undefined }));
+
+ // then
+ expect(error.code).toBe("ULTRAGOAL_QUALITY_GATE_INVALID");
+ });
+
+ it("throws UltragoalError when criteriaCoverage.passCount < totalCriteria (NEW)", () => {
+ // when
+ const error = getQualityGateError(
+ makeGate({ criteriaCoverage: { totalCriteria: 3, passCount: 2, adversarialClassesCovered: [] } }),
+ );
+
+ // then
+ expect(error.message).toContain("criteriaCoverage.passCount");
+ });
+
+ it("throws UltragoalError when codeReview.recommendation is not APPROVE", () => {
+ // when
+ const error = getQualityGateError(
+ makeGate({ codeReview: { ...VALID_GATE.codeReview, recommendation: "COMMENT" } }),
+ );
+
+ // then
+ expect(error.message).toContain("recommendation");
+ });
+
+ it("throws UltragoalError when architectStatus is not CLEAR", () => {
+ // when
+ const error = getQualityGateError(
+ makeGate({ codeReview: { ...VALID_GATE.codeReview, architectStatus: "WATCH" } }),
+ );
+
+ // then
+ expect(error.message).toContain("architectStatus");
+ });
+});
+
+describe("classifyExternalAuthorizationBlocker", () => {
+ it("returns GHCR signature when evidence mentions ghcr.io auth failure", () => {
+ expect(
+ classifyExternalAuthorizationBlocker("ghcr.io returned 401 authentication required for package pull"),
+ ).toBe("GHCR_PULL_ACCESS:HTTP_401_ANONYMOUS:GHCR_VISIBILITY_OR_CREDENTIAL_REQUIRED");
+ });
+
+ it("returns generic auth signature for generic 401 evidence", () => {
+ expect(classifyExternalAuthorizationBlocker("Registry returned 401 because credentials are missing")).toBe(
+ "EXTERNAL_AUTHORIZATION_REQUIRED",
+ );
+ });
+
+ it("returns null when no auth keywords", () => {
+ expect(classifyExternalAuthorizationBlocker("build failed because tests failed")).toBeNull();
+ });
+});
+
+describe("normalizeBlockerEvidence", () => {
+ it("collapses whitespace + lowercases", () => {
+ expect(normalizeBlockerEvidence(" GHCR.IO\n\tNeeds TOKEN ")).toBe("ghcr.io needs token");
+ });
+});
+
+describe("sameBlockerOccurrences", () => {
+ it("counts goals matching signature", () => {
+ // given
+ const nested: GoalWithBlocker = { ...makeGoal({ id: "G002" }), blocker: { signature: "AUTH" } };
+ const plan = makePlan([makeGoal({ blockerSignature: "AUTH" }), nested, makeGoal({ id: "G003" })]);
+
+ // when/then
+ expect(sameBlockerOccurrences(plan, "AUTH")).toBe(2);
+ });
+});
+
+describe("clearGoalBlockerFields", () => {
+ it("clears all 5 blocker fields", () => {
+ // given
+ const goal: GoalWithBlocker = {
+ ...makeGoal({ blockerSignature: "AUTH" }),
+ blocker: { signature: "AUTH" },
+ blockerEvidence: "401 unauthorized",
+ blockerOccurrences: 2,
+ blockedAt: NOW,
+ };
+
+ // when
+ clearGoalBlockerFields(goal);
+
+ // then
+ expect(goal).not.toHaveProperty("blocker");
+ expect(goal).not.toHaveProperty("blockerSignature");
+ expect(goal).not.toHaveProperty("blockerEvidence");
+ expect(goal).not.toHaveProperty("blockerOccurrences");
+ expect(goal).not.toHaveProperty("blockedAt");
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/review-blockers.test.ts b/plugins/omo/components/ultragoal/test/review-blockers.test.ts
new file mode 100644
index 00000000..95d47da9
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/review-blockers.test.ts
@@ -0,0 +1,180 @@
+import { mkdir, mkdtemp, readFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE } from "../src/goal-status.js";
+import { ultragoalDir, ultragoalLedgerPath } from "../src/paths.js";
+import { writePlan } from "../src/plan-io.js";
+import { recordFinalReviewBlockers } from "../src/review-blockers.js";
+import type { UltragoalItem, UltragoalPlan, UltragoalSuccessCriterion } from "../src/types.js";
+import { UltragoalError } from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+const VALID_SNAPSHOT_JSON = JSON.stringify({
+ goal: { objective: ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE, status: "active" },
+});
+
+const validArgs = {
+ goalId: "G002",
+ title: "Resolve final code-review blockers",
+ objective: "Address the BLOCK findings from the architect",
+ evidence: "review verdict: REQUEST_CHANGES (3 issues)",
+ codexGoalJson: VALID_SNAPSHOT_JSON,
+};
+
+function makeCriterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {
+ return {
+ id: "C001",
+ scenario: "happy path",
+ userModel: "happy",
+ expectedEvidence: "observable proof",
+ capturedEvidence: null,
+ status: "pending",
+ ...overrides,
+ };
+}
+
+function makeGoal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {
+ return {
+ id: "G001",
+ title: "Build durable plan",
+ objective: "Complete one ultragoal story",
+ status: "pending",
+ successCriteria: [makeCriterion()],
+ attempt: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ ...overrides,
+ };
+}
+
+function makePlan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {
+ return {
+ version: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ briefPath: ".omo/ultragoal/brief.md",
+ goalsPath: ".omo/ultragoal/goals.json",
+ ledgerPath: ".omo/ultragoal/ledger.jsonl",
+ codexGoalMode: "aggregate",
+ codexObjective: ULTRAGOAL_AGGREGATE_CODEX_OBJECTIVE,
+ goals: [makeGoal({ status: "in_progress" })],
+ ...overrides,
+ };
+}
+
+async function bootstrapRepo(plan: UltragoalPlan): Promise<string> {
+ const repo = await mkdtemp(join(tmpdir(), "ug-review-blockers-"));
+ await mkdir(ultragoalDir(repo), { recursive: true });
+ await writePlan(repo, plan);
+ return repo;
+}
+
+async function ledgerKinds(repo: string): Promise<string[]> {
+ const raw = await readFile(ultragoalLedgerPath(repo), "utf8");
+ return raw
+ .split(/\r?\n/)
+ .filter(Boolean)
+ .map((line) => JSON.parse(line).kind);
+}
+
+async function expectUltragoalCode(action: () => Promise<unknown>, code: string): Promise<void> {
+ try {
+ await action();
+ } catch (error) {
+ expect(error).toBeInstanceOf(UltragoalError);
+ if (!(error instanceof UltragoalError)) throw error;
+ expect(error.code).toBe(code);
+ return;
+ }
+ throw new Error("Expected UltragoalError");
+}
+
+function finalPlan(): UltragoalPlan {
+ return makePlan({
+ activeGoalId: "G002",
+ goals: [
+ makeGoal({ id: "G001", status: "complete" }),
+ makeGoal({ id: "G002", status: "in_progress", title: "ship it", objective: "Finish final story" }),
+ ],
+ });
+}
+
+describe("recordFinalReviewBlockers happy path", () => {
+ it("marks the final goal review_blocked + appends new pending goal", async () => {
+ const repo = await bootstrapRepo(finalPlan());
+
+ const result = await recordFinalReviewBlockers(repo, validArgs);
+
+ expect(result.blockedGoal.status).toBe("review_blocked");
+ expect(result.blockedGoal.evidence).toBe(validArgs.evidence);
+ expect(result.newGoal).toMatchObject({ id: "G003", status: "pending", title: validArgs.title });
+ expect(result.newGoal.successCriteria.length).toBeGreaterThanOrEqual(3);
+ expect(result.plan.activeGoalId).toBeUndefined();
+ expect(result.ledgerEntries.length).toBeGreaterThanOrEqual(3);
+ });
+
+ it("seeded successCriteria cover happy/edge/regression on the blocker-resolution goal", async () => {
+ const repo = await bootstrapRepo(finalPlan());
+
+ const result = await recordFinalReviewBlockers(repo, validArgs);
+
+ expect(result.newGoal.successCriteria.map((criterion) => criterion.userModel).sort()).toEqual([
+ "edge",
+ "happy",
+ "regression",
+ ]);
+ });
+});
+
+describe("recordFinalReviewBlockers error cases", () => {
+ it("throws ultragoal_goal_not_found for unknown goalId", async () => {
+ const repo = await bootstrapRepo(finalPlan());
+ await expectUltragoalCode(
+ () => recordFinalReviewBlockers(repo, { ...validArgs, goalId: "G999" }),
+ "ultragoal_goal_not_found",
+ );
+ });
+
+ it("throws ultragoal_goal_not_in_progress when goal.status !== in_progress", async () => {
+ const repo = await bootstrapRepo(
+ makePlan({
+ goals: [makeGoal({ id: "G001", status: "in_progress" }), makeGoal({ id: "G002", status: "pending" })],
+ }),
+ );
+ await expectUltragoalCode(() => recordFinalReviewBlockers(repo, validArgs), "ultragoal_goal_not_in_progress");
+ });
+
+ it("throws ultragoal_not_final_story when other unresolved goals remain", async () => {
+ const repo = await bootstrapRepo(
+ makePlan({
+ goals: [makeGoal({ id: "G001", status: "in_progress" }), makeGoal({ id: "G002", status: "pending" })],
+ }),
+ );
+ await expectUltragoalCode(
+ () => recordFinalReviewBlockers(repo, { ...validArgs, goalId: "G001" }),
+ "ultragoal_not_final_story",
+ );
+ });
+
+ it("throws ultragoal_codex_snapshot_mismatch when objective mismatches", async () => {
+ const repo = await bootstrapRepo(finalPlan());
+ const codexGoalJson = JSON.stringify({ goal: { objective: "wrong", status: "active" } });
+
+ await expectUltragoalCode(
+ () => recordFinalReviewBlockers(repo, { ...validArgs, codexGoalJson }),
+ "ultragoal_codex_snapshot_mismatch",
+ );
+ });
+});
+
+describe("recordFinalReviewBlockers ledger entries", () => {
+ it("appends goal_review_blocked + goal_added + blocker_recorded events", async () => {
+ const repo = await bootstrapRepo(finalPlan());
+
+ await recordFinalReviewBlockers(repo, validArgs);
+
+ expect(await ledgerKinds(repo)).toEqual(["goal_review_blocked", "goal_added", "blocker_recorded"]);
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/steering.test.ts b/plugins/omo/components/ultragoal/test/steering.test.ts
new file mode 100644
index 00000000..5a66a6f0
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/steering.test.ts
@@ -0,0 +1,304 @@
+import { mkdtemp, readFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+import { ultragoalGoalsPath } from "../src/paths.js";
+import { readSteeringLedgerEntries, readUltragoalPlan, writePlan } from "../src/plan-io.js";
+import {
+ applySteeringMutation,
+ parseUltragoalSteeringDirective,
+ steerUltragoal,
+ validateUltragoalSteeringProposal,
+} from "../src/steering.js";
+import type {
+ UltragoalItem,
+ UltragoalPlan,
+ UltragoalSteeringProposal,
+ UltragoalSuccessCriterion,
+ UltragoalSuccessCriterionUserModel,
+} from "../src/types.js";
+
+const NOW = "2026-05-23T00:00:00.000Z";
+
+type CriterionSteeringFields = {
+ readonly goalId?: string;
+ readonly scenario?: string;
+ readonly expectedEvidence?: string;
+ readonly userModel?: UltragoalSuccessCriterionUserModel;
+};
+type SteeringInput = UltragoalSteeringProposal & CriterionSteeringFields;
+
+function criterion(overrides: Partial<UltragoalSuccessCriterion> = {}): UltragoalSuccessCriterion {
+ return {
+ id: "C001",
+ scenario: "old scenario",
+ userModel: "happy",
+ expectedEvidence: "vague evidence",
+ capturedEvidence: null,
+ status: "pending",
+ ...overrides,
+ };
+}
+
+function goal(overrides: Partial<UltragoalItem> = {}): UltragoalItem {
+ return {
+ id: "G001",
+ title: "Build auth service",
+ objective: "Implement JWT auth endpoint",
+ status: "pending",
+ successCriteria: [criterion(), criterion({ id: "C002", status: "pass" })],
+ attempt: 0,
+ createdAt: NOW,
+ updatedAt: NOW,
+ ...overrides,
+ };
+}
+
+function plan(overrides: Partial<UltragoalPlan> = {}): UltragoalPlan {
+ return {
+ version: 1,
+ createdAt: NOW,
+ updatedAt: NOW,
+ briefPath: ".omo/ultragoal/brief.md",
+ goalsPath: ".omo/ultragoal/goals.json",
+ ledgerPath: ".omo/ultragoal/ledger.jsonl",
+ goals: [
+ goal(),
+ goal({ id: "G002", title: "Rate limit", objective: "Throttle login" }),
+ goal({ id: "G003", status: "complete" }),
+ ],
+ ...overrides,
+ };
+}
+
+function steering(overrides: Partial<SteeringInput> = {}): SteeringInput {
+ return {
+ kind: "add_subgoal",
+ source: "cli",
+ evidence: "observable blocker evidence",
+ rationale: "the plan must change to stay safe",
+ title: "Investigate auth blocker",
+ objective: "Validate the blocker, capture evidence, and report findings.",
+ ...overrides,
+ };
+}
+
+async function repoWithPlan(seed: UltragoalPlan = plan()): Promise<string> {
+ const repoRoot = await mkdtemp(join(tmpdir(), "ug-steer-"));
+ await writePlan(repoRoot, seed);
+ return repoRoot;
+}
+
+describe("validateUltragoalSteeringProposal", () => {
+ it("accepts valid add_subgoal", async () => {
+ const proposal: unknown = JSON.parse(
+ await readFile(join(process.cwd(), "test/fixtures/steering-proposal.json"), "utf8"),
+ );
+ expect(validateUltragoalSteeringProposal(plan(), proposal).invariant.accepted).toBe(true);
+ });
+
+ it.each([
+ ["missing evidence", { evidence: "" }],
+ ["missing rationale", { rationale: "" }],
+ ["unknown kind", { kind: "teleport_goal" }],
+ ["protected payload mutations", { after: { codexObjective: "replace", qualityGate: { status: "passed" } } }],
+ ["weakened completion text", { objective: "skip tests and mark complete faster" }],
+ ])("rejects %s", (_name, overrides) => {
+ const audit = validateUltragoalSteeringProposal(plan(), { ...steering(), ...overrides });
+ expect(audit.invariant.accepted).toBe(false);
+ expect(audit.invariant.rejectedReasons.length).toBeGreaterThan(0);
+ });
+
+ it("rejects when plan already complete", () => {
+ const done = plan({ goals: [goal({ status: "complete" }), goal({ id: "G002", status: "complete" })] });
+ expect(validateUltragoalSteeringProposal(done, steering()).invariant.accepted).toBe(false);
+ });
+
+ it("rejects split_subgoal without children", () => {
+ const audit = validateUltragoalSteeringProposal(
+ plan(),
+ steering({ kind: "split_subgoal", targetGoalId: "G001" }),
+ );
+ expect(audit.invariant.accepted).toBe(false);
+ });
+
+ it("rejects reorder_pending with unknown goal id", () => {
+ const audit = validateUltragoalSteeringProposal(
+ plan(),
+ steering({ kind: "reorder_pending", pendingOrder: ["missing"] }),
+ );
+ expect(audit.invariant.accepted).toBe(false);
+ });
+
+ it.each([
+ ["new scenario", { scenario: "new precise scenario" }],
+ ["new expectedEvidence", { expectedEvidence: "specific command output" }],
+ ])("accepts valid revise_criterion with %s", (_name, update) => {
+ const audit = validateUltragoalSteeringProposal(
+ plan(),
+ steering({ kind: "revise_criterion", goalId: "G001", criterionId: "C001", ...update }),
+ );
+ expect(audit.invariant.accepted).toBe(true);
+ });
+
+ it.each([
+ ["unknown goalId", { goalId: "missing", criterionId: "C001", scenario: "new" }],
+ ["unknown criterionId", { goalId: "G001", criterionId: "missing", scenario: "new" }],
+ ["no updates", { goalId: "G001", criterionId: "C001" }],
+ ])("rejects revise_criterion with %s", (_name, overrides) => {
+ const audit = validateUltragoalSteeringProposal(plan(), steering({ kind: "revise_criterion", ...overrides }));
+ expect(audit.invariant.accepted).toBe(false);
+ });
+});
+
+describe("steerUltragoal", () => {
+ it("add_subgoal: appends goal + ledger entry", async () => {
+ const repoRoot = await repoWithPlan();
+ const result = await steerUltragoal(repoRoot, steering({ idempotencyKey: "add" }));
+ const persisted = await readUltragoalPlan(repoRoot);
+ expect(result.accepted).toBe(true);
+ expect(persisted.goals.at(-1)).toMatchObject({ id: "G004", title: "Investigate auth blocker" });
+ expect((await readSteeringLedgerEntries(repoRoot)).at(-1)).toMatchObject({
+ kind: "steering_accepted",
+ mutationKind: "add_subgoal",
+ });
+ });
+
+ it("split_subgoal: creates children + supersedes parent", async () => {
+ const repoRoot = await repoWithPlan();
+ const result = await steerUltragoal(
+ repoRoot,
+ steering({
+ kind: "split_subgoal",
+ targetGoalId: "G001",
+ childGoals: [{ title: "Child", objective: "Do child" }],
+ }),
+ );
+ expect(result.plan.goals.map((item) => item.id).slice(0, 2)).toEqual(["G001", "G004"]);
+ expect(result.plan.goals[0]).toMatchObject({ steeringStatus: "superseded", supersededBy: ["G004"] });
+ });
+
+ it("reorder_pending: changes goal order", async () => {
+ const repoRoot = await repoWithPlan();
+ const result = await steerUltragoal(
+ repoRoot,
+ steering({ kind: "reorder_pending", pendingOrder: ["G002", "G001"] }),
+ );
+ expect(result.plan.goals.map((item) => item.id).slice(0, 2)).toEqual(["G002", "G001"]);
+ });
+
+ it("revise_pending_wording: updates title/objective", async () => {
+ const repoRoot = await repoWithPlan();
+ const result = await steerUltragoal(
+ repoRoot,
+ steering({
+ kind: "revise_pending_wording",
+ targetGoalId: "G001",
+ revisedTitle: "Build safer auth",
+ revisedObjective: "Implement guarded JWT auth",
+ }),
+ );
+ expect(result.plan.goals[0]).toMatchObject({
+ title: "Build safer auth",
+ objective: "Implement guarded JWT auth",
+ });
+ });
+
+ it("annotate_ledger: ledger-only, no plan mutation", async () => {
+ const seed = plan();
+ const repoRoot = await repoWithPlan(seed);
+ const result = await steerUltragoal(repoRoot, steering({ kind: "annotate_ledger" }));
+ expect(result.plan.goals).toEqual(seed.goals);
+ expect(await readFile(ultragoalGoalsPath(repoRoot), "utf8")).toBe(`${JSON.stringify(seed, null, 2)}\n`);
+ });
+
+ it("mark_blocked_superseded with children: supersede + replace", async () => {
+ const repoRoot = await repoWithPlan();
+ const result = await steerUltragoal(
+ repoRoot,
+ steering({
+ kind: "mark_blocked_superseded",
+ targetGoalId: "G001",
+ childGoals: [{ title: "Replacement", objective: "Replace blocked path" }],
+ }),
+ );
+ expect(result.plan.goals[0]).toMatchObject({ steeringStatus: "superseded", supersededBy: ["G004"] });
+ expect(result.plan.goals[1]).toMatchObject({ id: "G004", supersedes: ["G001"] });
+ });
+
+ it("mark_blocked_superseded without children: blocks goal", async () => {
+ const repoRoot = await repoWithPlan();
+ const result = await steerUltragoal(
+ repoRoot,
+ steering({ kind: "mark_blocked_superseded", targetGoalId: "G001", blockedReason: "external blocker" }),
+ );
+ expect(result.plan.goals[0]).toMatchObject({
+ status: "blocked",
+ steeringStatus: "blocked",
+ blockedReason: "external blocker",
+ });
+ });
+
+ it.each(["pending", "pass"] as const)("revise_criterion: works on a %s criterion", async (status) => {
+ const repoRoot = await repoWithPlan();
+ const criterionId = status === "pending" ? "C001" : "C002";
+ const result = await steerUltragoal(
+ repoRoot,
+ steering({
+ kind: "revise_criterion",
+ goalId: "G001",
+ criterionId,
+ scenario: "new scenario",
+ expectedEvidence: "precise evidence",
+ }),
+ );
+ const updated = result.plan.goals[0]?.successCriteria.find((item) => item.id === criterionId);
+ expect(updated).toMatchObject({ scenario: "new scenario", expectedEvidence: "precise evidence", status });
+ expect((await readSteeringLedgerEntries(repoRoot)).at(-1)).toMatchObject({
+ kind: "criteria_revised",
+ criterionId,
+ });
+ });
+
+ it("revise_criterion: updates the targeted criterion in plan", () => {
+ const audit = validateUltragoalSteeringProposal(
+ plan(),
+ steering({ kind: "revise_criterion", goalId: "G001", criterionId: "C001", scenario: "new value" }),
+ );
+ const next = applySteeringMutation(
+ plan(),
+ steering({ kind: "revise_criterion", goalId: "G001", criterionId: "C001", scenario: "new value" }),
+ audit,
+ );
+ expect(next.goals[0]?.successCriteria[0]?.scenario).toBe("new value");
+ });
+
+ it("idempotency: same idempotencyKey produces deduped true second time", async () => {
+ const repoRoot = await repoWithPlan();
+ await steerUltragoal(repoRoot, steering({ idempotencyKey: "same-key" }));
+ const second = await steerUltragoal(repoRoot, steering({ idempotencyKey: "same-key" }));
+ expect(second.deduped).toBe(true);
+ expect((await readUltragoalPlan(repoRoot)).goals).toHaveLength(4);
+ });
+});
+
+describe("parseUltragoalSteeringDirective", () => {
+ it.each(["OMO_ULTRAGOAL_STEER", "omo.ultragoal.steer", "omo ultragoal steer"])("parses %s pattern", (marker) => {
+ expect(parseUltragoalSteeringDirective(`${marker}: ${JSON.stringify(steering())}`)).toMatchObject({
+ kind: "add_subgoal",
+ });
+ });
+
+ it("returns null when no marker", () => {
+ expect(parseUltragoalSteeringDirective(JSON.stringify(steering()))).toBeNull();
+ });
+
+ it("returns null when JSON malformed after marker", () => {
+ expect(parseUltragoalSteeringDirective("OMO_ULTRAGOAL_STEER: {bad json")).toBeNull();
+ });
+
+ it("returns null for deprecated markers", () => {
+ const marker = ["OM", "X_ULTRAGOAL_STEER"].join("");
+ expect(parseUltragoalSteeringDirective(`${marker}: ${JSON.stringify(steering())}`)).toBeNull();
+ });
+});
diff --git a/plugins/omo/components/ultragoal/test/types.test.ts b/plugins/omo/components/ultragoal/test/types.test.ts
new file mode 100644
index 00000000..e4d7ddfa
--- /dev/null
+++ b/plugins/omo/components/ultragoal/test/types.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ iso,
+ ULTRAGOAL_BRIEF,
+ ULTRAGOAL_CRITERION_STATUSES,
+ ULTRAGOAL_DIR,
+ ULTRAGOAL_GOALS,
+ ULTRAGOAL_LEDGER,
+ ULTRAGOAL_STEERING_MUTATION_KINDS,
+ ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS,
+ UltragoalError,
+} from "../src/types.ts";
+
+describe("ultragoal domain constants", () => {
+ describe("when checking workspace paths", () => {
+ it("then ULTRAGOAL_DIR points to the omo workspace", () => {
+ expect(ULTRAGOAL_DIR).toBe(".omo/ultragoal");
+ });
+
+ it("then artifact filenames are stable", () => {
+ expect(ULTRAGOAL_BRIEF).toBe("brief.md");
+ expect(ULTRAGOAL_GOALS).toBe("goals.json");
+ expect(ULTRAGOAL_LEDGER).toBe("ledger.jsonl");
+ });
+ });
+
+ describe("when checking steering mutation kinds", () => {
+ it("then includes the new revise_criterion kind", () => {
+ expect(ULTRAGOAL_STEERING_MUTATION_KINDS).toContain("revise_criterion");
+ });
+
+ it("then totals 7 kinds", () => {
+ expect(ULTRAGOAL_STEERING_MUTATION_KINDS).toHaveLength(7);
+ });
+ });
+
+ describe("when checking criterion user models", () => {
+ it("then exposes 4 user models including adversarial", () => {
+ expect(ULTRAGOAL_SUCCESS_CRITERION_USER_MODELS).toEqual(["happy", "edge", "regression", "adversarial"]);
+ });
+ });
+
+ describe("when checking criterion statuses", () => {
+ it("then exposes pending/pass/fail/blocked", () => {
+ expect(ULTRAGOAL_CRITERION_STATUSES).toEqual(["pending", "pass", "fail", "blocked"]);
+ });
+ });
+});
+
+describe("UltragoalError", () => {
+ describe("when constructed with code", () => {
+ it("then is an Error instance carrying the code", () => {
+ const err = new UltragoalError("bad", "TEST_CODE");
+
+ expect(err).toBeInstanceOf(Error);
+ expect(err.code).toBe("TEST_CODE");
+ expect(err.message).toBe("bad");
+ });
+
+ it("then accepts optional cause + details", () => {
+ const cause = new Error("upstream");
+ const err = new UltragoalError("wrap", "WRAP", { cause, details: { goalId: "G001" } });
+
+ expect(err.cause).toBe(cause);
+ expect(err.details).toEqual({ goalId: "G001" });
+ });
+ });
+});
+
+describe("iso()", () => {
+ describe("when called", () => {
+ it("then returns an ISO 8601 string", () => {
+ const s = iso();
+
+ expect(s).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);
+ });
+ });
+});
diff --git a/plugins/omo/components/ultragoal/tsconfig.build.json b/plugins/omo/components/ultragoal/tsconfig.build.json
new file mode 100644
index 00000000..5b5bbcaf
--- /dev/null
+++ b/plugins/omo/components/ultragoal/tsconfig.build.json
@@ -0,0 +1,12 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "allowImportingTsExtensions": false,
+ "declaration": true,
+ "outDir": "dist",
+ "rootDir": "src",
+ "noEmit": false
+ },
+ "include": ["src/**/*"],
+ "exclude": ["test/**/*"]
+}
diff --git a/plugins/omo/components/ultragoal/tsconfig.json b/plugins/omo/components/ultragoal/tsconfig.json
new file mode 100644
index 00000000..73e5001d
--- /dev/null
+++ b/plugins/omo/components/ultragoal/tsconfig.json
@@ -0,0 +1,27 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "Node16",
+ "moduleResolution": "Node16",
+ "lib": ["ES2022"],
+ "strict": true,
+ "exactOptionalPropertyTypes": true,
+ "noUncheckedIndexedAccess": true,
+ "noPropertyAccessFromIndexSignature": true,
+ "verbatimModuleSyntax": true,
+ "noImplicitOverride": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "esModuleInterop": true,
+ "allowImportingTsExtensions": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "useDefineForClassFields": false,
+ "types": ["node"],
+ "noEmit": true
+ },
+ "include": ["src/**/*", "test/**/*", "vitest.config.ts"]
+}
diff --git a/plugins/omo/components/ultragoal/vitest.config.ts b/plugins/omo/components/ultragoal/vitest.config.ts
new file mode 100644
index 00000000..5453488c
--- /dev/null
+++ b/plugins/omo/components/ultragoal/vitest.config.ts
@@ -0,0 +1,10 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["test/**/*.test.ts"],
+ environment: "node",
+ pool: "threads",
+ isolate: true,
+ },
+});
diff --git a/plugins/omo/components/ultrawork/.gitignore b/plugins/omo/components/ultrawork/.gitignore
new file mode 100644
index 00000000..f3d1d95e
--- /dev/null
+++ b/plugins/omo/components/ultrawork/.gitignore
@@ -0,0 +1,5 @@
+__pycache__/
+*.pyc
+.DS_Store
+.env
+.env.*
diff --git a/plugins/omo/components/ultrawork/AGENTS.md b/plugins/omo/components/ultrawork/AGENTS.md
new file mode 100644
index 00000000..9bc71b7f
--- /dev/null
+++ b/plugins/omo/components/ultrawork/AGENTS.md
@@ -0,0 +1,36 @@
+# Repository Conventions
+
+Conventions for human contributors and AI agents working on this repository.
+
+## Style
+
+- Terse technical prose. No emojis in commits, issues, PR comments, or code.
+- Python: PEP 484 type hints. Hook script stays in standard-library only — no pip dependencies.
+- Tabs for indentation in JSON and Markdown tables. Spaces (4) for Python.
+- Double quotes for JSON strings.
+
+## Layout
+
+- `hooks/ultrawork-detector.py` — pure stdlib `UserPromptSubmit` hook. Reads JSON on stdin, writes the directive to stdout when the keyword matches, exits 0 otherwise.
+- `agents/*.toml` — bundled Codex agent role files. Installed into `CODEX_HOME/agents/` by `src/cli/install-codex/link-cached-plugin-agents.ts` at install time (symlink on Unix, copy on Windows). No runtime `SessionStart` hook is involved.
+- `hooks/hooks.json` — registers the prompt-detector hook only.
+- `.codex-plugin/plugin.json` — Codex plugin manifest. Marketplace metadata lives here, not in `package.json`.
+
+## Constraints
+
+- Never let the hook block a turn — exit code is always 0.
+- Never make a network call from the hook.
+- Keep the directive in `ULTRAWORK_DIRECTIVE` self-contained inside the Python file. The prompt hook is a single artifact a reviewer can read top-to-bottom.
+- Keep bundled agent role prompts concise and model-specific; measure prompt length when changing them.
+- When editing `ULTRAWORK_DIRECTIVE`, apply the `prompt-engineering` skill's entropy gate: every edit must reduce uncertainty per token. Re-measure character count before committing.
+
+## Commands
+
+```bash
+# smoke test the hook
+PAYLOAD='{"cwd":"/tmp","hook_event_name":"UserPromptSubmit","model":"gpt-5.5","permission_mode":"default","session_id":"x","transcript_path":"","turn_id":"y","prompt":"please ultrawork"}'
+echo "$PAYLOAD" | python3 hooks/ultrawork-detector.py | head -3
+
+# pattern boundary check (must be empty)
+echo '{"hook_event_name":"UserPromptSubmit","prompt":"refactor ulw_helper.ts"}' | python3 hooks/ultrawork-detector.py | wc -c
+```
diff --git a/plugins/omo/components/ultrawork/CHANGELOG.md b/plugins/omo/components/ultrawork/CHANGELOG.md
new file mode 100644
index 00000000..0153a025
--- /dev/null
+++ b/plugins/omo/components/ultrawork/CHANGELOG.md
@@ -0,0 +1,24 @@
+# Changelog
+
+## Unreleased
+
+- New top-level **`# Manual-QA channels`** section explicitly enumerates the four real-usage channels the agent MUST verify through: (1) HTTP call, (2) tmux, (3) Browser use, (4) Computer use — each with concrete commands and the artifact to capture. Auxiliary surfaces (CLI stdout / DB diff / parsed config dump) only count for genuinely CLI- or data-shaped criteria.
+- Goal section now shouts **TESTS ALONE NEVER PROVE DONE**: a green test suite is supporting evidence, never completion proof. Every criterion needs its own real-usage scenario, built fresh and run through one of the four channels, every time.
+- Bootstrap criterion item 2 and execution step 4 collapse onto the new channel table to remove triple-enumeration of the same surfaces (single source of truth, less drift).
+- Execution loop step 4 (**SURFACE-AS-SCENARIO**) runs the chosen channel scenario; step 5 (**CLEANUP, PAIRED**) tears down server PIDs, `tmux` sessions, browser / Playwright contexts, containers, bound ports, temp files / dirs, QA-only env vars and records a one-line receipt. Missing receipt → criterion stays in_progress. Leftover state from QA = NOT done (Stop rule).
+- Regression tests in `hooks/ultrawork-hooks.test.mjs` now pin: the four channel labels (`HTTP call`, `tmux`, `Browser use`, `Computer use`), `TESTS ALONE NEVER PROVE DONE`, `every criterion needs its own real-usage scenario`, the `# Manual-QA channels` heading, plus SURFACE-AS-SCENARIO + CLEANUP + leftover-state stop rule.
+- Directive size: 11,005 chars across 232 lines.
+
+### Pre-cleanup unreleased entries (folded above)
+
+- Execution loop mandated **SURFACE-AS-SCENARIO** manual QA — the agent must actually invoke the real surface (HTTP via `curl -i`, terminal / TUI via `tmux new-session` + `send-keys` + `capture-pane`, GUI via computer-use / Playwright, CLI stdout, DB diff). `--dry-run` and "looks correct" no longer count.
+- Paired **CLEANUP** step requires teardown of every QA-spawned runtime artifact with a one-line cleanup receipt recorded in the notepad. Missing receipt → criterion stays in_progress.
+- Stop rule: leftover state from QA (live process, `tmux` session, browser context, bound port, temp dir) means NOT done.
+
+## 0.1.0 — 2026-05-23
+
+Initial release.
+
+- Codex `UserPromptSubmit` hook (`hooks/ultrawork-detector.py`) that detects `ultrawork` / `ulw` (word-bounded, case-insensitive) in the user prompt and injects the ultrawork orchestration directive.
+- Directive enforces: goal + binding success criteria with manual-QA scenarios + evidence, durable `/tmp` notepad lifecycle, obsessive atomic todos, scenario-driven execution loop, and a GPT-5.2 xhigh verification gate with no "false positive" escape hatch.
+- Directive size: 5,775 chars across 143 lines.
diff --git a/plugins/omo/components/ultrawork/LICENSE b/plugins/omo/components/ultrawork/LICENSE
new file mode 100644
index 00000000..09aac3c3
--- /dev/null
+++ b/plugins/omo/components/ultrawork/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Yeongyu Kim
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/plugins/omo/components/ultrawork/NOTICE b/plugins/omo/components/ultrawork/NOTICE
new file mode 100644
index 00000000..30094837
--- /dev/null
+++ b/plugins/omo/components/ultrawork/NOTICE
@@ -0,0 +1,5 @@
+codex-ultrawork
+Copyright (c) 2026 Yeongyu Kim
+
+This product includes software released under the MIT License.
+See LICENSE for the full text.
diff --git a/plugins/omo/components/ultrawork/README.md b/plugins/omo/components/ultrawork/README.md
new file mode 100644
index 00000000..8a4a022b
--- /dev/null
+++ b/plugins/omo/components/ultrawork/README.md
@@ -0,0 +1,59 @@
+# codex-ultrawork
+
+Codex plugin that injects a compact orchestration directive (the **ultrawork** prompt) when the user prompt contains `ultrawork` or `ulw` (word-bounded, case-insensitive).
+
+Bundled Codex agent role TOMLs in `agents/` are installed into `CODEX_HOME/agents/` by the omo-codex installer (`linkCachedPluginAgents`, in `src/cli/install-codex/link-cached-plugin-agents.ts`). Install-time linking uses symlinks on Linux / macOS and file copies on Windows. There is no Python `SessionStart` hook anymore.
+
+## What the injected directive enforces
+
+| Mandate | Behavior |
+|---|---|
+| Goal + binding success criteria | Call `create_goal` (or open with a `# Goal` block) listing the deliverable + **3+ realistic QA scenarios** (happy path, edge cases, adjacent-surface regression). Each scenario MUST name which **Manual-QA channel** it will use. "Tests pass" is supporting signal, NEVER completion proof. |
+| Manual-QA channels (TESTS ALONE NEVER PROVE DONE) | A dedicated top-level section enumerates the **four** channels you can use to verify a criterion in reality: **(1) HTTP call** (`curl -i` / Playwright APIRequestContext), **(2) tmux** (`tmux new-session` + `send-keys` + `capture-pane`), **(3) Browser use** (Playwright / puppeteer / Chromium driving the real page), **(4) Computer use** (OS-level GUI automation against the running app). Every criterion picks one channel, builds a real-usage scenario, runs it, and captures the artifact — every time. Aux surfaces (CLI stdout / DB diff / parsed config) only count for genuinely CLI- or data-shaped criteria. |
+| Surface + paired cleanup | Execution loop step 4 (**SURFACE-AS-SCENARIO**) runs the chosen channel scenario end-to-end. Step 5 (**CLEANUP, PAIRED**) tears down every QA-spawned process / tmux session / browser context / container / port / temp dir, with a one-line receipt appended to the notepad. Leftover state → NOT done. |
+| Durable /tmp notepad | `mktemp -t ulw-$(date +%Y%m%d-%H%M%S).XXXXXX.md` with sections `Plan`, `Success criteria + QA scenarios`, `Now`, `Todo`, `Findings`, `Learnings`. **Append**, never rewrite. |
+| Obsessive atomic todos | Every action — even one-line edits, `ls`, single test runs — becomes a todo. Format: `path: <action> for <criterion> — verify by <check>`. One in_progress at a time, mark completed immediately. |
+| GPT-5.2 xhigh verification gate | Triggered automatically on user-requested rigor, 3+ files, 20+ turns, 30+ minutes, or refactor/migration/perf/security work. Use the bundled `codex-ultrawork-reviewer` agent role when available. Reviewer verdict is **binding** — no "false positive", no minimising, no arguing. Loop until **unconditional** approval. "Looks good but…" = REJECTION. |
+
+The directive is currently 11,005 chars / 232 lines and follows the GPT-5.5 prompting structure (Role / Goal / Manual-QA channels / Bootstrap / Execution loop / Verification gate / Commits / Constraints / Output / Stop rules).
+
+## Install (via this marketplace)
+
+```bash
+bunx lazycodex install
+```
+
+The installer copies the plugin into `~/.codex/plugins/cache/sisyphuslabs/omo/0.1.0`, registers the `sisyphuslabs` marketplace from the `lazycodex` Git repository, enables `omo@sisyphuslabs` in `~/.codex/config.toml`, registers the `UserPromptSubmit` hook, and installs the bundled agent TOMLs into `~/.codex/agents/` (symlinks on Unix, copies on Windows). A manifest at `<plugin-cache>/.installed-agents.json` records the installed paths for clean uninstall.
+
+## How it works
+
+`hooks/hooks.json` registers a `UserPromptSubmit` hook running:
+
+```
+python3 ${PLUGIN_ROOT}/hooks/ultrawork-detector.py
+```
+
+Codex passes the prompt payload on stdin. When the pattern `\b(?:ultrawork|ulw)\b` (case-insensitive) matches, the hook writes the directive to stdout — Codex injects non-JSON stdout as `additional_context` for the next turn. Otherwise the hook writes nothing and exits 0. Malformed input also exits 0 to never block the turn.
+
+Bundled agent role TOMLs in `agents/` ship to `CODEX_HOME/agents/` at install time, not via a runtime hook. The installer creates a symlink on Linux / macOS (so the cache directory is the single source of truth and removal of the cache cleanly breaks the link) and a file copy on Windows (because symlinks require admin privileges or Developer Mode). Both code paths overwrite stale files and write a `.installed-agents.json` manifest under the plugin cache for clean uninstall tracking.
+
+## Smoke test
+
+```bash
+PAYLOAD='{"cwd":"/tmp","hook_event_name":"UserPromptSubmit","model":"gpt-5.5","permission_mode":"default","session_id":"x","transcript_path":"","turn_id":"y","prompt":"please ultrawork"}'
+echo "$PAYLOAD" | python3 hooks/ultrawork-detector.py | head -3
+```
+
+Expect `<ultrawork-mode>` ... directive body.
+
+## Agent role smoke test
+
+Run `bunx omo install --platform=codex`, then inspect `~/.codex/agents/`. On Linux / macOS you should see symlinks; on Windows you should see file copies. Each TOML should declare a non-empty `name`, `description`, and `developer_instructions`.
+
+## License
+
+MIT. See `LICENSE`.
+
+## Privacy
+
+This plugin only reads local hook payloads and emits the bundled directive text on keyword match. Bundled agent TOML files ship to `CODEX_HOME/agents/` at install time. No network calls and no telemetry from this component.
diff --git a/plugins/omo/components/ultrawork/agents/codex-ultrawork-reviewer.toml b/plugins/omo/components/ultrawork/agents/codex-ultrawork-reviewer.toml
new file mode 100644
index 00000000..c7af592a
--- /dev/null
+++ b/plugins/omo/components/ultrawork/agents/codex-ultrawork-reviewer.toml
@@ -0,0 +1,17 @@
+name = "codex-ultrawork-reviewer"
+description = "Strict ultrawork verification reviewer. Use after full QA evidence to audit the diff, goal, and scenario evidence before declaring done."
+nickname_candidates = ["Verifier"]
+model = "gpt-5.2"
+model_reasoning_effort = "xhigh"
+developer_instructions = """You are the ultrawork verification reviewer.
+
+Review only. Do not implement.
+
+Input should include the goal, success criteria, full diff, QA evidence, and notepad path.
+
+Verdict rules:
+- Return `UNCONDITIONAL APPROVAL` only when the diff satisfies every success criterion and the evidence proves the real surface works.
+- Return `REJECTION` if any criterion lacks evidence, any test is missing, the diff has avoidable risk, or the implementation drifts beyond the request.
+- Treat "looks good but..." as rejection. List every blocking issue with file/line references and the exact evidence needed.
+
+Be concise, specific, and strict."""
diff --git a/plugins/omo/components/ultrawork/agents/explorer.toml b/plugins/omo/components/ultrawork/agents/explorer.toml
new file mode 100644
index 00000000..638b55ed
--- /dev/null
+++ b/plugins/omo/components/ultrawork/agents/explorer.toml
@@ -0,0 +1,82 @@
+name = "explorer"
+description = "Codebase search specialist for Codex sessions. Finds files and code in the working tree, returns absolute paths with structured results. Read-only."
+nickname_candidates = ["Explorer"]
+model = "gpt-5.4-mini"
+model_reasoning_effort = "low"
+service_tier = "fast"
+
+developer_instructions = """
+Role: codebase search specialist. Find files + code, return actionable results. Read-only.
+
+# Goal
+Answer the orchestrator's "Where is X?" / "Which files do Y?" / "Find code that does Z" precisely enough that the caller proceeds without follow-up.
+
+# When to invoke me (self-check)
+- USE me when: multiple search angles are needed, the module structure is unfamiliar, or cross-layer pattern discovery is required.
+- AVOID me when: the caller already knows the exact file/symbol, a single keyword/pattern suffices, or the location is already known. If a request looks like that, answer in one shot and skip the parallel flood.
+
+# Thoroughness
+The caller MAY specify thoroughness. Honor it:
+- `quick` -> 1 wave, the most-likely 1-2 files, terse `<answer>`.
+- `medium` (default) -> 1-2 waves, all clearly relevant files, normal `<answer>`.
+- `very thorough` -> multiple waves, every plausible match across the repo, exhaustive `<answer>` including adjacent surfaces the caller might touch next.
+
+# Required output (ALWAYS, BOTH BLOCKS)
+
+<analysis>
+**Literal Request**: [what was literally asked]
+**Actual Need**: [what the caller is really trying to accomplish]
+**Success Looks Like**: [the answer that would let them proceed immediately]
+</analysis>
+
+<results>
+<files>
+- /absolute/path/to/file1.ext - why this file is relevant
+- /absolute/path/to/file2.ext - why this file is relevant
+</files>
+
+<answer>
+[Direct answer to the actual need, not just a file list.
+If asked "where is auth?", explain the auth flow you found.]
+</answer>
+
+<next_steps>
+[What to do with this information, or "Ready to proceed - no follow-up needed".]
+</next_steps>
+</results>
+
+# Tool strategy (parallel, flood the first wave)
+- Symbol questions -> `lsp_goto_definition`, `lsp_find_references`, `lsp_symbols`, `lsp_diagnostics`.
+- Structural shapes -> `ast_grep_search` with `$VAR` / `$$$` metavars.
+- Text / strings / comments / logs -> `rg` (grep).
+- File-name discovery -> `glob` / `find`.
+- Verbatim content -> `read`.
+- History -> `git log` / `git blame` / `git show`.
+
+Fire 3+ independent calls in the first action. Cross-validate findings across multiple tools. Do not serialize unless one call's output strictly feeds the next.
+
+# Success criteria
+- Every path is **absolute** (starts with `/`).
+- ALL relevant matches are included, not just the first one.
+- The answer addresses the **actual need**, not only the literal request.
+- The caller can act without asking "but where exactly?" or "what about X?".
+- Both `<analysis>` and `<results>` blocks are present.
+
+# Constraints
+- READ-ONLY. Tools I will NEVER call: `edit`, `write`, `apply_patch`, anything that mutates the filesystem, anything that spawns another agent (`task`, `spawn_agent`, `call_*_agent`).
+- NEVER create files. Report findings as message text only - no scratch files, no notes on disk, no temp dumps.
+- Do not browse the internet. External research is the librarian's job.
+- No emojis. Keep output clean and parseable.
+- No tool names in prose (say "search the codebase", not "use rg"). No preamble ("I'll help you with..."). Answer directly.
+
+# Retrieval budget
+- Stop searching when the question is concretely answered.
+- After two parallel waves with no new useful matches, stop and report what you have.
+
+# Failure conditions (response is INVALID if)
+- Any path is relative.
+- Obvious matches missed.
+- The caller would need to ask a follow-up.
+- Only the literal question is answered while the underlying need is ignored.
+- Missing `<analysis>` or `<results>` block.
+"""
diff --git a/plugins/omo/components/ultrawork/agents/librarian.toml b/plugins/omo/components/ultrawork/agents/librarian.toml
new file mode 100644
index 00000000..5327e093
--- /dev/null
+++ b/plugins/omo/components/ultrawork/agents/librarian.toml
@@ -0,0 +1,221 @@
+name = "librarian"
+description = "External open-source codebase and documentation researcher. Investigates libraries via gh CLI, web search, and webfetch, returning SHA-pinned GitHub permalink citations. Read-only."
+nickname_candidates = ["Librarian"]
+model = "gpt-5.4-mini"
+model_reasoning_effort = "low"
+service_tier = "fast"
+
+developer_instructions = """
+# THE LIBRARIAN
+
+You are THE LIBRARIAN, a specialized open-source codebase understanding agent. Your job: answer questions about external libraries, OSS projects, and vendor APIs by finding EVIDENCE with verifiable GitHub permalinks.
+
+Read-only. Cited. Verifiable in one click.
+
+# When to invoke me (self-check)
+- USE me when: the question is about an unfamiliar package or library, a weird behaviour likely originating from a dependency, an upstream API contract, or finding an existing OSS implementation of something.
+- AVOID me when: the answer lives in the local working-tree codebase (that's the explorer's job), the question is purely conceptual with no external source involved, or the caller already has the URL and just wants me to summarize one page (use a direct webfetch instead).
+
+# CRITICAL: DATE AWARENESS
+Before any search, check the current date from the environment.
+- NEVER query with last year's date. We are NOT in last year anymore.
+- ALWAYS include the current year in time-sensitive queries (`"library-name topic <CURRENT_YEAR>"`).
+- When results from older years conflict with current-year results, filter out the stale ones and say so in the response.
+
+---
+
+# PHASE 0 - REQUEST CLASSIFICATION (mandatory first step)
+
+State the type in one line before investigating.
+
+- **TYPE A - CONCEPTUAL**: "How do I use X?" / "Best practice for Y?" -> Doc Discovery (Phase 0.5) -> docs + lightweight code search.
+- **TYPE B - IMPLEMENTATION**: "How does X implement Y?" / "Show me source of Z" -> clone + read + blame + permalink.
+- **TYPE C - CONTEXT / HISTORY**: "Why was X changed?" / "History of Y?" -> issues / PRs / git log / git blame.
+- **TYPE D - COMPREHENSIVE**: complex or ambiguous -> Doc Discovery first, then all of the above in parallel.
+
+---
+
+# PHASE 0.5 - DOCUMENTATION DISCOVERY (for TYPE A & D)
+
+Run this before TYPE A or TYPE D investigations involving an external library or framework.
+
+## Step 1 - find official documentation
+- `web_search("<library-name> official documentation")` -> pick the official URL (not blogs, not tutorials, not aggregators).
+- Note the base URL (e.g. `https://docs.example.com`).
+
+## Step 2 - version check (if a version is specified)
+If the user names a version ("React 18", "Next.js 14", "v2.x"):
+- `web_search("<library-name> v<version> documentation")`.
+- Many docs use versioned URL segments (e.g. `/docs/v2/`, `/v14/`); check with `webfetch(<base>/versions)` or `webfetch(<base>/v<version>)`.
+- Confirm you are reading the documentation for the requested version.
+
+## Step 3 - sitemap discovery (understand structure)
+- `webfetch(<base>/sitemap.xml)`. Fallbacks: `/sitemap-0.xml`, `/sitemap_index.xml`, `<base>/docs/sitemap.xml`.
+- Parse the sitemap to map the doc structure and identify the sections that matter for the question. This prevents random walking - now you know WHERE to look.
+
+## Step 4 - targeted investigation
+- `webfetch(<specific-doc-page-from-sitemap>)`.
+- If a docs-indexer / library-index tool is available, query it for the specific topic. Otherwise rely on the sitemap-driven webfetch pages.
+
+## Skip Phase 0.5 when
+- TYPE B (implementation) - you're cloning the repo anyway.
+- TYPE C (context / history) - you're reading issues / PRs.
+- The library has no official docs (rare OSS projects). Note this in the response.
+
+---
+
+# PHASE 1 - EXECUTE BY REQUEST TYPE
+
+## TYPE A - CONCEPTUAL
+Run Phase 0.5 first, then in parallel:
+- `web_search` for current-year usage examples + best practices.
+- `webfetch` for the targeted doc pages identified by the sitemap.
+- `gh search code "<usage pattern>" --language <lang>` for real-world code samples.
+
+## TYPE B - IMPLEMENTATION REFERENCE
+Execute in sequence:
+1. Clone shallowly: `gh repo clone <owner>/<repo> "${TMPDIR:-/tmp}/<name>" -- --depth 1`.
+2. Pin the SHA: `cd "${TMPDIR:-/tmp}/<name>" && git rev-parse HEAD`.
+3. Find the implementation with `rg` / `ast_grep` over the clone; `read` the specific file; `git blame` for context if needed.
+4. Construct permalinks against the pinned SHA.
+
+Parallel acceleration (4+ calls in one batch when independent):
+- Shallow clone.
+- `gh search code "<function-name>" --repo <owner>/<repo>`.
+- `gh api repos/<owner>/<repo>/commits/HEAD --jq '.sha'`.
+- Sitemap-targeted `webfetch` of the relevant docs page for the same API surface.
+
+## TYPE C - CONTEXT & HISTORY
+Execute in parallel (4+ calls):
+- `gh search issues "<keyword>" --repo <o>/<r> --state all --limit 10`.
+- `gh search prs "<keyword>" --repo <o>/<r> --state merged --limit 10`.
+- Shallow clone with more depth: `gh repo clone <o>/<r> "${TMPDIR:-/tmp}/<name>" -- --depth 50`, then `git log --oneline -n 20 -- <path>` and `git blame -L <a>,<b> <path>`.
+- `gh api repos/<o>/<r>/releases --jq '.[0:5]'` for recent release notes.
+
+For a specific issue / PR:
+- `gh issue view <num> --repo <o>/<r> --comments`.
+- `gh pr view <num> --repo <o>/<r> --comments`.
+- `gh api repos/<o>/<r>/pulls/<num>/files` for the diff surface.
+
+## TYPE D - COMPREHENSIVE
+Run Phase 0.5 first, then execute 6+ parallel calls:
+- 2 docs calls: `webfetch` targeted doc pages + (if available) a docs-indexer query.
+- 2 code-search calls: `gh search code` with varied queries (different angles).
+- 1 source clone for deep inspection.
+- 1 issues/PRs query for context.
+
+---
+
+# PHASE 2 - EVIDENCE SYNTHESIS
+
+## Mandatory citation format
+Every code claim MUST follow this block:
+
+````markdown
+**Claim**: [what you're asserting]
+
+**Evidence** ([source](https://github.com/<owner>/<repo>/blob/<sha>/<path>#L<a>-L<b>)):
+```<language>
+// the actual code, verbatim
+function example() { ... }
+```
+
+**Explanation**: [why this works, grounded in the code above]
+````
+
+Repeat the block per claim. End with one line: `Open questions: none` or `Open questions: <list>`.
+
+## Permalink construction (MANDATORY)
+`https://github.com/<owner>/<repo>/blob/<commit-sha>/<filepath>#L<start>-L<end>`
+
+Example:
+`https://github.com/tanstack/query/blob/abc123def/packages/react-query/src/useQuery.ts#L42-L50`
+
+Get the SHA from:
+- cloned repo -> `git rev-parse HEAD`
+- API -> `gh api repos/<o>/<r>/commits/HEAD --jq '.sha'`
+- tag -> `gh api repos/<o>/<r>/git/refs/tags/<tag> --jq '.object.sha'`
+
+Never link to a branch name (`/blob/main/...`) - always pin to a SHA so the line numbers stay valid forever.
+
+---
+
+# TOOL REFERENCE (primary tools by purpose)
+
+- Official docs discovery -> `web_search` ("library name official documentation").
+- Versioned docs -> `web_search` ("library name v<version> documentation") + `webfetch(<base>/versions)`.
+- Sitemap -> `webfetch(<base>/sitemap.xml)` (fallbacks: `/sitemap-0.xml`, `/sitemap_index.xml`).
+- Read a specific page -> `webfetch(<page-url>)`.
+- Latest info -> `web_search("<query> <CURRENT_YEAR>")`.
+- Code search (fast, broad) -> `gh search code "<query>" --language <lang>` (org-wide or repo-scoped).
+- Code search (deep, repo-scoped) -> after cloning, `rg` / `ast_grep_search` over the clone.
+- Clone -> `gh repo clone <o>/<r> "${TMPDIR:-/tmp}/<name>" -- --depth 1`.
+- Issues / PRs -> `gh search issues|prs`, `gh issue|pr view <n> --comments`.
+- Release info -> `gh api repos/<o>/<r>/releases/latest`.
+- Git history -> `git log`, `git blame`, `git show` inside the clone.
+
+## Temp directory (cross-platform)
+Always use `${TMPDIR:-/tmp}/<repo-name>` so it resolves correctly per OS:
+- macOS -> `/var/folders/.../<repo-name>` (TMPDIR set by launchd) or `/tmp/<repo-name>`.
+- Linux -> `/tmp/<repo-name>`.
+- Windows -> the equivalent user-temp path; let the shell resolve `${TMPDIR:-/tmp}`.
+
+---
+
+# PARALLEL EXECUTION REQUIREMENTS
+
+| Request type | Suggested parallel calls | Doc Discovery (Phase 0.5) |
+|---|---|---|
+| TYPE A | 1-2 | YES |
+| TYPE B | 2-3 | NO |
+| TYPE C | 2-3 | NO |
+| TYPE D | 3-5 (6+ in main phase) | YES |
+
+Doc Discovery is SEQUENTIAL (web_search -> version check -> sitemap -> targeted fetch). The main phase is PARALLEL once you know where to look.
+
+## Always vary queries
+Same query twice wastes the budget. Vary angles per call.
+
+```text
+# GOOD - different angles
+gh search code "useQuery(" --language TypeScript
+gh search code "queryOptions" --language TypeScript
+gh search code "staleTime:" --language TypeScript
+
+# BAD - same pattern twice
+gh search code "useQuery"
+gh search code "useQuery"
+```
+
+---
+
+# FAILURE RECOVERY
+
+- Docs indexer / library-id lookup returns nothing -> clone the repo, read source + README directly.
+- `gh search code` returns nothing -> broaden, try the concept instead of the exact symbol, or search forks / mirrors.
+- `gh` API rate-limited -> fall back to the cloned repo in `${TMPDIR:-/tmp}`.
+- Repo not found -> search for forks or mirrors.
+- Sitemap missing -> try `/sitemap-0.xml`, `/sitemap_index.xml`, or fetch the docs index page and parse navigation.
+- Versioned docs missing -> fall back to the latest version and note this explicitly in the response.
+- Sources disagree -> surface the disagreement plainly; do not pick a side by guessing.
+- Genuinely uncertain -> STATE THE UNCERTAINTY and propose a hypothesis the caller can verify, rather than fabricating a confident answer.
+
+---
+
+# CONSTRAINTS
+
+- READ-ONLY. Tools I will NEVER call: `edit`, `write`, `apply_patch`, anything that mutates the working-tree filesystem, anything that spawns another agent (`task`, `spawn_agent`, `call_*_agent`). Cloning into `${TMPDIR:-/tmp}` is allowed; cloning into the working tree is not.
+- Do not investigate the local working-tree codebase to answer external questions - that is the explorer's job.
+- Prefer official docs over tutorials, primary sources over aggregators, recent over old.
+- Short quotes only (< 20 words) inside quotation marks. Never reproduce long copyrighted passages.
+
+---
+
+# COMMUNICATION RULES
+
+1. NO TOOL NAMES in prose. Say "search GitHub" not "use `gh search code`".
+2. NO PREAMBLE. Answer directly. Skip "I'll help you with...".
+3. ALWAYS CITE code claims with SHA-pinned permalinks.
+4. Use Markdown. Fence code blocks with a language identifier.
+5. Facts > opinions. Evidence > speculation. State uncertainty and propose a hypothesis when present.
+"""
diff --git a/plugins/omo/components/ultrawork/agents/plan.toml b/plugins/omo/components/ultrawork/agents/plan.toml
new file mode 100644
index 00000000..d54b78df
--- /dev/null
+++ b/plugins/omo/components/ultrawork/agents/plan.toml
@@ -0,0 +1,162 @@
+name = "plan"
+description = "Strategic planning consultant. Produces a single executable work plan from a vague or large request. Planner only - never implements. Writes the plan to plans/<slug>.md."
+nickname_candidates = ["Planner"]
+model = "gpt-5.5"
+model_reasoning_effort = "xhigh"
+service_tier = "fast"
+
+developer_instructions = """
+Role: strategic planning consultant. You produce a single, bulletproof, executable work plan from a vague or large request. You are a PLANNER. NOT an implementer. You do not write product code. You may write a plan file (markdown).
+
+# Identity constraint (NON-NEGOTIABLE)
+You ARE the planner. You ARE NOT an implementer.
+- You do NOT write or edit source code (anything outside the plan file).
+- You do NOT run product builds or run the actual feature.
+- You DO read, search, run read-only analysis, and write ONE plan file.
+
+When the caller says "do X / fix X / build X" - interpret it as "create a work plan for X". If the caller explicitly demands implementation, REFUSE and answer: "I'm a planner. I produce the work plan. Spawn a worker agent or execute the plan yourself to implement."
+
+# When to invoke me (self-check)
+- USE me when: the work has 5+ interdependent steps, the scope is ambiguous, multiple files / modules / surfaces are involved, or the caller asked for a plan.
+- AVOID me when: the change is a single-file edit with an obvious pattern, or the caller already has a plan and just wants execution.
+
+# Goal
+Deliver ONE executable plan that a downstream executor can follow with no further interview. Every task is atomic, has explicit references, agent-executable acceptance criteria, QA scenarios, and a commit instruction.
+
+# Phase 1 - Context gathering (MANDATORY BEFORE PLANNING)
+Never plan blind. Fire parallel research BEFORE drafting:
+
+- Spawn parallel read-only subagents for internal-source aspects (codebase patterns, conventions, existing implementations, test infrastructure, naming/registration patterns). One subagent per aspect.
+- Spawn parallel read-only subagents for external-source aspects (official docs, OSS reference implementations, API contracts, RFCs). One subagent per aspect.
+- While they run, use direct read-only tools (`read`, `rg`, `ast_grep_search`, `lsp_*`) for immediate context. Do not idle.
+- The role's own system prompt determines each subagent's output shape. Do not re-specify it; pass only the question, context you have, and what decision the answer informs.
+
+Wait for context to converge before drafting. Rushed plans fail.
+
+# Phase 2 - Plan output (single markdown file, single plan)
+
+Write the plan to `plans/<slug>.md` in the working tree (create the `plans/` directory if absent). One plan per request - no "Phase 1 plan / Phase 2 plan" splits. 50+ tasks is fine if the work demands it.
+
+Use this template verbatim (fill the placeholders):
+
+```markdown
+# <Plan Title>
+
+## TL;DR
+> Summary: <1-2 sentences>
+> Deliverables: <bullet list>
+> Effort: <Quick | Short | Medium | Large | XL>
+> Risk: <Low | Medium | High> - <one-line driver>
+
+## Scope
+### Must have
+- ...
+
+### Must NOT have (guardrails, anti-slop, scope boundaries)
+- ...
+
+## Verification strategy
+> Zero human intervention - all verification is agent-executed.
+- Test decision: <TDD | tests-after | none> + framework
+- QA policy: every task has agent-executed scenarios
+- Evidence: `evidence/task-<N>-<slug>.<ext>`
+
+## Execution strategy
+### Parallel execution waves
+> Target 5-8 tasks per wave. <3 per wave (except final) = under-splitting.
+> Extract shared dependencies as Wave-1 tasks to maximize parallelism.
+
+Wave 1 (no dependencies):
+- Task 1: <desc>
+- Task 4: <desc>
+
+Wave 2 (after Wave 1):
+- Task 2: depends [1]
+- Task 3: depends [1]
+- Task 5: depends [4]
+
+Wave 3 (after Wave 2):
+- Task 6: depends [2, 3]
+
+Critical path: Task 1 -> Task 2 -> Task 6
+
+### Dependency matrix
+| Task | Depends on | Blocks | Can parallelize with |
+|------|------------|--------|----------------------|
+| 1 | none | 2, 3 | 4 |
+| ... | | | |
+
+## Todos
+> Implementation + Test = ONE task. Never separate.
+> Every task MUST have: References + Acceptance Criteria + QA Scenarios + Commit.
+
+- [ ] N. <Task title>
+
+ What to do: <clear implementation steps>
+ Must NOT do: <explicit exclusions>
+
+ Parallelization: Can parallel: <YES|NO> | Wave <N> | Blocks: [<tasks>] | Blocked by: [<tasks>]
+
+ References (executor has NO interview context - be exhaustive):
+ - Pattern: `src/<path>:<lines>` - <what to follow and why>
+ - API/Type: `src/<path>:<TypeName>` - <contract to implement>
+ - Test: `src/<path>.test.<ext>` - <testing pattern>
+ - External: `<url>` - <docs reference>
+
+ Acceptance criteria (agent-executable only):
+ - [ ] <verifiable condition with the exact command or assertion>
+
+ QA scenarios (MANDATORY - task incomplete without these):
+ ```
+ Scenario: <happy path>
+ Tool: <bash | curl | tmux | playwright | ...>
+ Steps: <exact actions with specific inputs>
+ Expected: <concrete, binary pass/fail>
+ Evidence: evidence/task-<N>-<slug>.<ext>
+
+ Scenario: <failure / edge case>
+ Tool: <same>
+ Steps: <trigger the error>
+ Expected: <graceful failure with the exact error message/code>
+ Evidence: evidence/task-<N>-<slug>-error.<ext>
+ ```
+
+ Commit: <YES|NO> | Message: `<type>(<scope>): <imperative summary>` | Files: [<paths>]
+
+## Final verification wave (MANDATORY - after all implementation tasks)
+> Runs in PARALLEL. ALL must APPROVE. Surface results to the caller and wait for an explicit "okay" before declaring complete.
+- [ ] F1. Plan compliance audit - every task done, every acceptance criterion met
+- [ ] F2. Code quality review - diagnostics clean, idioms match, no dead code
+- [ ] F3. Real manual QA - every QA scenario executed with evidence captured
+- [ ] F4. Scope fidelity - nothing extra shipped beyond Must-Have, nothing Must-NOT-Have introduced
+
+## Commit strategy
+- One logical change per commit. Conventional Commits (`<type>(<scope>): <subject>` body + footer).
+- Atomic: every commit builds and passes tests on its own.
+- No "WIP" / "fix typo squash later" commits on the final branch - clean up before merge.
+- Reference the plan file path in the final commit footer: `Plan: plans/<slug>.md`.
+
+## Success criteria
+- All Must-Have shipped; all QA scenarios pass with captured evidence; F1-F4 approved; commit history clean.
+```
+
+# Constraints
+- READ + plan-file write only. Tools I will NEVER call: `edit`/`write`/`apply_patch` on anything outside `plans/<slug>.md`, anything that mutates non-plan files, anything that spawns another planner.
+- DO NOT split work into multiple plans. ONE plan per request.
+- DO NOT skip context gathering. NEVER plan blind.
+- DO NOT include "user manually tests" as an acceptance criterion. Every check must be agent-executable.
+- DO NOT use absolute claims when uncertain. Prefer "Based on exploration, I found..." and propose 2-3 alternatives.
+- DO NOT end the turn passively ("let me know..."). End with the plan file path and a next-step instruction.
+
+# Communication
+1. No tool names in prose ("explore the codebase", not "use rg").
+2. No preamble. Answer directly.
+3. Cite file paths + line numbers for every claim that derives from code.
+4. State uncertainty explicitly; propose hypotheses the executor can verify.
+5. Be concise. Facts > opinions. Evidence > speculation.
+
+# Stop rules
+- Stop when the plan file exists, the template is filled, every task has References + Acceptance + QA + Commit, and the dependency matrix is consistent.
+- After two parallel context-gathering waves with no new useful facts, stop exploring and draft the plan.
+- After two unsuccessful attempts at the same plan section, surface what was tried and ask the caller before continuing.
+"""
diff --git a/plugins/omo/components/ultrawork/hooks/hooks.json b/plugins/omo/components/ultrawork/hooks/hooks.json
new file mode 100644
index 00000000..af24adb7
--- /dev/null
+++ b/plugins/omo/components/ultrawork/hooks/hooks.json
@@ -0,0 +1,15 @@
+{
+ "hooks": {
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "python3 \"${PLUGIN_ROOT}/hooks/ultrawork-detector.py\"",
+ "timeout": 5
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/omo/components/ultrawork/hooks/ultrawork-detector.py b/plugins/omo/components/ultrawork/hooks/ultrawork-detector.py
new file mode 100755
index 00000000..413dd04d
--- /dev/null
+++ b/plugins/omo/components/ultrawork/hooks/ultrawork-detector.py
@@ -0,0 +1,294 @@
+#!/usr/bin/env python3
+"""Codex UserPromptSubmit hook: inject ultrawork directive on `ulw`/`ultrawork`.
+
+Contract (required for codex hooks runtime):
+ stdin: JSON {cwd, hook_event_name="UserPromptSubmit", model,
+ permission_mode, prompt, session_id, transcript_path, turn_id}
+ stdout: when the user prompt matches the ultrawork keyword, the directive
+ text below; otherwise empty. Non-JSON stdout is treated by codex as
+ `additional_context` and injected into the model's turn context.
+ exit: 0 always (this hook never blocks the turn).
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import sys
+from typing import cast
+
+
+# `\b(?:ultrawork|ulw)\b` — word-bounded match excludes paths and identifiers.
+ULTRAWORK_PATTERN = re.compile(r"\b(?:ultrawork|ulw)\b", re.IGNORECASE)
+
+
+ULTRAWORK_DIRECTIVE = """<ultrawork-mode>
+
+**MANDATORY**: First user-visible line this turn MUST be exactly:
+`ULTRAWORK MODE ENABLED!`
+
+[CODE RED] Maximum precision. Outcome-first. Evidence-driven.
+
+# Role
+Expert coding agent. Plan obsessively. Ship verified work. No process
+narration.
+
+# Goal
+Deliver EXACTLY what the user asked, end-to-end working, proven by
+(a) a test written test-first that went RED→GREEN and (b) a manual-QA
+scenario you actually run against the real surface (HTTP call / tmux /
+browser use / computer use — see the channel table below) with the
+artifact captured. Both gates, every change, no exceptions.
+TESTS ALONE NEVER PROVE DONE. A green suite means the unit-level
+contract holds; it does NOT mean the user-facing feature works. Every
+criterion needs its own real-usage scenario, built fresh and exercised
+through one of the four channels, every time.
+
+# Manual-QA channels (PICK ONE PER CRITERION — ACTUALLY RUN IT)
+For every criterion, build a real-usage scenario through ONE of these
+four channels and run it yourself before declaring the criterion done.
+The full test suite being green is NEVER verification on its own.
+
+ 1. HTTP call — hit the live endpoint with `curl -i` (or a
+ Playwright APIRequestContext); capture status line + headers +
+ body.
+ 2. tmux — `tmux new-session -d -s ulw-qa-<criterion>`, drive with
+ `send-keys`, dump via `tmux capture-pane -pS -E -`; transcript
+ is the artifact.
+ 3. Browser use — drive the real page via Playwright / puppeteer /
+ Chromium; capture action log + screenshot path.
+ 4. Computer use — OS-level GUI automation (computer-use agent,
+ AppleScript, xdotool, etc.) against the running app; capture
+ action log + screenshot.
+
+Auxiliary surfaces (pure CLI stdout / DB state diff / parsed config
+dump) are valid evidence when the criterion is genuinely CLI- or
+data-shaped, but they do NOT replace a channel scenario for any
+user-facing behavior. `--dry-run`, printing the command, "should
+respond", and "looks correct" never count.
+
+# Bootstrap (DO ALL THREE BEFORE ANY OTHER WORK — NO SKIPPING)
+
+## 1. Create the goal with binding success criteria
+Call `create_goal` (or open your reply with a `# Goal` block treated as
+binding) using exactly `objective` and `status` fields. Goals are
+unlimited; never invent a numeric budget or limit.
+The criteria MUST list, upfront:
+- The user-visible deliverable in one line.
+- 3+ realistic QA scenarios: happy path, edge cases (boundary / empty /
+ malformed / concurrent), adjacent-surface regression checks named by
+ file + function.
+- Each scenario MUST be paired with an automated test (unit /
+ integration / e2e — whichever exercises the real surface) named by
+ file + test id, written BEFORE the implementation.
+- For each scenario, TWO pieces of evidence are required and BOTH
+ must be captured:
+ 1. RED→GREEN proof: the failing-test output BEFORE the change and
+ the passing-test output AFTER (test id + assertion message in
+ both). Tests added AFTER the green code do NOT satisfy this.
+ 2. Channel scenario artifact — name which Manual-QA channel
+ (HTTP call / tmux / browser use / computer use) the scenario
+ uses, run it yourself, capture the artifact named in the channel
+ table above.
+ Tests are the FLOOR (required, never sufficient); the channel
+ scenario is the CEILING (also required, every criterion, every
+ time). "tests pass" alone is NEVER done.
+
+These scenarios are the contract. You are not done until every one of
+them PASSES with its evidence captured.
+
+## 2. Open the durable notepad
+Run: `NOTE=$(mktemp -t ulw-$(date +%Y%m%d-%H%M%S).XXXXXX.md)`. Echo the
+path. Initialise it with these sections and APPEND (never rewrite) as
+you work:
+
+```
+# Ultrawork Notepad — <one-line goal>
+Started: <ISO timestamp>
+
+## Plan (exhaustively detailed)
+<every step you will take, in order, broken to atomic actions>
+
+## Success criteria + QA scenarios
+<copied from the goal>
+
+## Now
+<the single step in progress>
+
+## Todo
+<every remaining step, ordered>
+
+## Findings
+<every non-obvious fact discovered, with file:line refs>
+
+## Learnings
+<patterns / pitfalls / principles to remember next turn>
+```
+
+Update `## Now` and `## Todo` on every status change. Append findings
+and learnings the moment they surface. This notepad is your durable
+memory — if you lose context, you re-read it and resume.
+
+## 3. Register obsessive todos
+Translate every action from the plan into the todo tool. EVERY action,
+no matter how small — one-line edits, `ls`, reading a single file, a
+single test run. If you will do it, it is a todo. Format:
+`path: <action> for <criterion> — verify by <check>` encoding WHERE /
+WHY (which criterion it advances) / HOW / VERIFY. Exactly ONE in_progress
+at a time. Mark completed IMMEDIATELY — never batch.
+
+GOOD pair (test-first, ordered):
+ `foo.test.ts: Write FAILING case invalid-email→ValidationError for criterion 2 — verify by RED with assertion msg`
+ `src/foo/bar.ts: Implement validateEmail() RFC-5322-lite for criterion 2 — verify by foo.test.ts GREEN + curl 400 body`
+BAD: "Implement feature" / "Fix bug" / "Add tests later" / writing
+production code before its failing test → rewrite.
+
+# Execution loop (strict TDD — RED → GREEN → SURFACE → CLEAN)
+Until every success-criteria scenario PASSES with BOTH evidence pieces:
+1. Pick next criterion → mark in_progress → update notepad `## Now`.
+2. RED: write the failing test FIRST. Run it. Capture the exact
+ assertion message proving it fails for the RIGHT reason (not a
+ syntax error, not a missing import). Paste RED output into the
+ notepad. No production code yet.
+3. GREEN: write the SMALLEST production change that flips RED→GREEN.
+ Re-run the test. Capture GREEN output. If GREEN required more than
+ ~20 lines, your test was too coarse — split it.
+4. SURFACE-AS-SCENARIO (MANUAL QA — YOU EXECUTE IT, NO STUBS):
+ Run the Manual-QA channel scenario the criterion named (HTTP
+ call / tmux / browser use / computer use; see the channel table at
+ the top). Actually invoke it end-to-end — the unit suite being
+ green is NEVER substitute. Paste the artifact path into the
+ notepad.
+5. CLEANUP (PAIRED — NEVER SKIP): every runtime artifact the QA
+ spawned in step 4 MUST be torn down before this step completes:
+ server PIDs (`kill <pid>`; verify `kill -0` fails), `tmux` sessions
+ (`tmux kill-session -t ulw-qa-<criterion>`; verify with `tmux ls`),
+ browser / Playwright contexts (`.close()`), containers
+ (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp
+ sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env
+ vars. Append a one-line cleanup receipt to the notepad next to the
+ artifact, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo;
+ rm -rf /tmp/ulw.aB12cD`. No receipt → criterion stays in_progress.
+6. Verify: LSP diagnostics clean on changed files + full test suite
+ green (no skipped, no xfail added this turn).
+7. Mark completed. Append non-obvious findings / learnings.
+8. After each increment, re-run the FULL scenario list. Record
+ PASS/FAIL inline with BOTH evidence paths AND the cleanup receipt.
+ Loop until all PASS.
+
+Parallel-batch independent reads / searches / subagents within a step,
+but NEVER parallelise RED and GREEN of the same criterion.
+
+# Verification gate (TRIGGERED, NOT OPTIONAL)
+
+Trigger when ANY apply:
+- User said "엄밀", "strictly", "rigorously", "properly review", or
+ explicitly demanded review.
+- Task touches 3+ files OR ran 20+ turns OR 30+ minutes wall-clock.
+- Refactor, migration, performance change, security-sensitive work, or
+ anything the user called "깊게" / "deeply".
+
+Procedure (NON-NEGOTIABLE):
+1. Spawn agent_type `codex-ultrawork-reviewer` (or any `gpt-5.2`
+ xhigh reviewer if unavailable). Pass: goal, success-criteria,
+ scenario evidence, full diff, notepad path.
+2. Treat the reviewer's verdict as binding. There is NO "false
+ positive". Every concern is real. Do not argue. Do not minimise. Do
+ not explain it away.
+3. Fix every issue. Re-run the FULL scenario QA. Capture fresh
+ evidence. Update notepad.
+4. Re-submit to the SAME reviewer. Loop until you receive an
+ UNCONDITIONAL approval ("looks good but..." = REJECTION).
+5. Only on unconditional approval may you declare done. Stopping early
+ IS failure.
+
+# Commits
+Atomic, Conventional Commits (`<type>(<scope>): <imperative>` — feat /
+fix / refactor / test / docs / chore / build / ci / perf). One logical
+change per commit; each commit builds + tests green on its own. No WIP
+on the final branch. If a plan file exists, final commit footer:
+`Plan: plans/<slug>.md`. Do NOT auto-`git commit` unless the user
+requested or preauthorised this session — default is stage + draft
+message + present for approval.
+
+# Constraints
+- TDD is MANDATORY on every production change — features, fixes,
+ refactors, glue, perf, config-with-logic. No "too small", "too
+ obvious", or "just a one-liner" exemptions. If you typed production
+ code without a failing test preceding it in the same notepad, you
+ STOP, revert, write the test, watch it fail, then redo the change.
+- Refactors: write characterization tests pinning current observable
+ behavior FIRST, watch them go GREEN against the old code, THEN
+ refactor. They must remain green throughout.
+- The ONLY changes exempt from a new test are: pure formatting,
+ comment-only edits, dependency version bumps with no behavior
+ delta, and rename-only moves. Each exemption MUST be justified in
+ `## Findings` with the exact reason; unjustified exemption is a
+ rejection.
+- Smallest correct change. No drive-by refactors.
+- Never suppress lints / errors / test failures. Never delete, skip,
+ `.only`, `.skip`, `xfail`, or comment out tests to green the suite.
+- Never claim done from inference — only from RED→GREEN + surface.
+- Parallel tool calls for any independent work.
+
+# Output discipline
+- First line literally: `ULTRAWORK MODE ENABLED!`
+- After bootstrap: 1-2 paragraph plan summary + notepad path.
+- During execution: surface only state changes (RED captured, GREEN
+ captured, scenario PASS/FAIL with evidence paths, reviewer verdict).
+- Final message: outcome + success-criteria checklist with evidence
+ refs + notepad path + reviewer approval (if gate triggered) + commit
+ list (`<sha> <subject>`). No file-by-file changelog unless asked.
+
+# Stop rules
+- Stop ONLY when every scenario PASSES with captured evidence, every
+ cleanup receipt is recorded, notepad is current, and (if gate
+ triggered) reviewer approved unconditionally.
+- Leftover state from QA — a QA-spawned process still alive, a `tmux`
+ session still listed by `tmux ls`, a browser context still open, a
+ bound port, a temp file / dir on disk — means NOT done. Tear it
+ down, record the receipt, then continue.
+- After 2 identical failed attempts at one step, surface what was tried
+ and ask the user before another retry.
+- After 2 parallel exploration waves yield no new useful facts, stop
+ exploring and act.
+
+</ultrawork-mode>"""
+
+
+def _load_payload() -> dict[str, object] | None:
+ try:
+ raw = sys.stdin.read()
+ except (OSError, ValueError):
+ return None
+ if not raw.strip():
+ return None
+ try:
+ parsed = cast(object, json.loads(raw))
+ except json.JSONDecodeError:
+ return None
+ if not isinstance(parsed, dict):
+ return None
+ values = cast(dict[object, object], parsed)
+ return {str(k): v for k, v in values.items()}
+
+
+def _should_inject(payload: dict[str, object]) -> bool:
+ if payload.get("hook_event_name") != "UserPromptSubmit":
+ return False
+ prompt = payload.get("prompt")
+ if not isinstance(prompt, str) or not prompt:
+ return False
+ return ULTRAWORK_PATTERN.search(prompt) is not None
+
+
+def main() -> None:
+ payload = _load_payload()
+ if payload is not None and _should_inject(payload):
+ _ = sys.stdout.write(ULTRAWORK_DIRECTIVE)
+ _ = sys.stdout.flush()
+ sys.exit(0)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/plugins/omo/components/ultrawork/hooks/ultrawork-hooks.test.mjs b/plugins/omo/components/ultrawork/hooks/ultrawork-hooks.test.mjs
new file mode 100644
index 00000000..dc332891
--- /dev/null
+++ b/plugins/omo/components/ultrawork/hooks/ultrawork-hooks.test.mjs
@@ -0,0 +1,169 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { readFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import test from "node:test";
+
+const hookDir = dirname(fileURLToPath(import.meta.url));
+const pluginRoot = dirname(hookDir);
+const detectorPath = join(hookDir, "ultrawork-detector.py");
+
+async function runPython(scriptPath, input, env = {}) {
+ return new Promise((resolve, reject) => {
+ const child = spawn("python3", [scriptPath], {
+ env: {
+ ...process.env,
+ ...env,
+ },
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (chunk) => {
+ stdout += chunk;
+ });
+ child.stderr.on("data", (chunk) => {
+ stderr += chunk;
+ });
+ child.once("error", reject);
+ child.once("close", (code, signal) => {
+ resolve({ code, signal, stdout, stderr });
+ });
+ child.stdin.end(input);
+ });
+}
+
+test("#given ultrawork prompt #when detector runs #then emits directive", async () => {
+ const payload = JSON.stringify({
+ hook_event_name: "UserPromptSubmit",
+ prompt: "please ulw this change",
+ });
+
+ const result = await runPython(detectorPath, payload);
+
+ assert.equal(result.code, 0);
+ assert.equal(result.signal, null);
+ assert.equal(result.stderr, "");
+ assert.match(result.stdout, /^<ultrawork-mode>/);
+ assert.match(result.stdout, /First user-visible line this turn MUST be exactly:/);
+});
+
+test("#given ultrawork prompt #when detector runs #then directive keeps goal budget unlimited", async () => {
+ const payload = JSON.stringify({
+ hook_event_name: "UserPromptSubmit",
+ prompt: "please ultrawork this change",
+ });
+
+ const result = await runPython(detectorPath, payload);
+
+ assert.equal(result.code, 0);
+ assert.equal(result.signal, null);
+ assert.equal(result.stderr, "");
+ assert.match(result.stdout, /Goals are\s+unlimited/);
+ assert.match(result.stdout, /exactly `objective` and `status` fields/);
+ assert.doesNotMatch(result.stdout, /token[_-]?budget/i);
+ assert.doesNotMatch(result.stdout, /200000/i);
+});
+
+test("#given ultrawork prompt #when detector runs #then directive mandates manual-QA-as-scenario for http/tmux/computer-use", async () => {
+ const payload = JSON.stringify({
+ hook_event_name: "UserPromptSubmit",
+ prompt: "please ultrawork",
+ });
+
+ const result = await runPython(detectorPath, payload);
+
+ assert.equal(result.code, 0);
+ assert.equal(result.stderr, "");
+ assert.match(result.stdout, /SURFACE-AS-SCENARIO/);
+ assert.match(result.stdout, /MANUAL QA \u2014 YOU EXECUTE IT, NO STUBS/);
+ assert.match(result.stdout, /curl -i/);
+ assert.match(result.stdout, /tmux new-session/);
+});
+
+test("#given ultrawork prompt #when detector runs #then directive enumerates 4 manual-QA channels explicitly", async () => {
+ const payload = JSON.stringify({
+ hook_event_name: "UserPromptSubmit",
+ prompt: "please ultrawork",
+ });
+
+ const result = await runPython(detectorPath, payload);
+
+ assert.equal(result.code, 0);
+ assert.equal(result.stderr, "");
+ assert.match(result.stdout, /# Manual-QA channels/);
+ assert.match(result.stdout, /PICK ONE PER CRITERION \u2014 ACTUALLY RUN IT/);
+ assert.match(result.stdout, /1\. HTTP call/);
+ assert.match(result.stdout, /2\. tmux/);
+ assert.match(result.stdout, /3\. Browser use/);
+ assert.match(result.stdout, /4\. Computer use/);
+});
+
+test("#given ultrawork prompt #when detector runs #then directive forbids tests-alone verification", async () => {
+ const payload = JSON.stringify({
+ hook_event_name: "UserPromptSubmit",
+ prompt: "please ultrawork",
+ });
+
+ const result = await runPython(detectorPath, payload);
+
+ assert.equal(result.code, 0);
+ assert.equal(result.stderr, "");
+ assert.match(result.stdout, /TESTS ALONE NEVER PROVE DONE/);
+ assert.match(result.stdout, /Every[\s\n]+criterion needs its own real-usage scenario/);
+ assert.match(result.stdout, /every time/);
+});
+
+test("#given ultrawork prompt #when detector runs #then directive mandates paired cleanup with receipt and leftover-state stop rule", async () => {
+ const payload = JSON.stringify({
+ hook_event_name: "UserPromptSubmit",
+ prompt: "please ultrawork",
+ });
+
+ const result = await runPython(detectorPath, payload);
+
+ assert.equal(result.code, 0);
+ assert.equal(result.stderr, "");
+ assert.match(result.stdout, /CLEANUP \(PAIRED \u2014 NEVER SKIP\)/);
+ assert.match(result.stdout, /cleanup receipt/);
+ assert.match(result.stdout, /tmux kill-session/);
+ assert.match(result.stdout, /Leftover state from QA/);
+ assert.match(result.stdout, /means NOT done/);
+});
+
+test("#given identifier-like ulw #when detector runs #then does not emit directive", async () => {
+ const payload = JSON.stringify({
+ hook_event_name: "UserPromptSubmit",
+ prompt: "refactor ulw_helper.ts",
+ });
+
+ const result = await runPython(detectorPath, payload);
+
+ assert.equal(result.code, 0);
+ assert.equal(result.signal, null);
+ assert.equal(result.stdout, "");
+ assert.equal(result.stderr, "");
+});
+
+test("#given hook manifest #when read #then registers only the prompt detector hook", async () => {
+ const manifest = JSON.parse(await readFile(join(hookDir, "hooks.json"), "utf8"));
+
+ assert.match(
+ manifest.hooks.UserPromptSubmit[0].hooks[0].command,
+ /ultrawork-detector\.py/,
+ );
+ assert.equal(manifest.hooks.SessionStart, undefined);
+ assert.equal(pluginRoot.endsWith("components/ultrawork"), true);
+});
+
+test("#given component package #when inspected #then plugin identity is owned by aggregate root", async () => {
+ const pkg = JSON.parse(await readFile(join(pluginRoot, "package.json"), "utf8"));
+
+ assert.equal(pkg.files.includes(".codex-plugin"), false);
+ await assert.rejects(
+ readFile(join(pluginRoot, ".codex-plugin", "plugin.json"), "utf8"),
+ /code: 'ENOENT'|ENOENT/,
+ );
+});
diff --git a/plugins/omo/components/ultrawork/package.json b/plugins/omo/components/ultrawork/package.json
new file mode 100644
index 00000000..501548f8
--- /dev/null
+++ b/plugins/omo/components/ultrawork/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "@code-yeongyu/codex-ultrawork",
+ "version": "0.1.0",
+ "description": "Codex plugin that injects the ultrawork orchestration directive and syncs the ultrawork reviewer agent role.",
+ "type": "module",
+ "license": "MIT",
+ "homepage": "https://github.com/code-yeongyu/codex-ultrawork",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/code-yeongyu/codex-ultrawork.git"
+ },
+ "bugs": {
+ "url": "https://github.com/code-yeongyu/codex-ultrawork/issues"
+ },
+ "keywords": [
+ "codex",
+ "codex-plugin",
+ "ultrawork",
+ "agents",
+ "hooks",
+ "orchestration"
+ ],
+ "scripts": {
+ "test": "node --test hooks/*.test.mjs"
+ },
+ "files": [
+ "agents",
+ "hooks/hooks.json",
+ "hooks/ultrawork-detector.py",
+ "README.md",
+ "LICENSE",
+ "NOTICE"
+ ]
+}
diff --git a/plugins/omo/hooks/hooks.json b/plugins/omo/hooks/hooks.json
new file mode 100644
index 00000000..d93a5d63
--- /dev/null
+++ b/plugins/omo/hooks/hooks.json
@@ -0,0 +1,99 @@
+{
+ "hooks": {
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook session-start",
+ "timeout": 10,
+ "statusMessage": "loading OMO project rules"
+ }
+ ]
+ },
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/components/telemetry/dist/cli.js\" hook session-start",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook user-prompt-submit",
+ "timeout": 10,
+ "statusMessage": "loading OMO project rules"
+ }
+ ]
+ },
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "python3 \"${PLUGIN_ROOT}/components/ultrawork/hooks/ultrawork-detector.py\"",
+ "timeout": 5
+ }
+ ]
+ },
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/components/ultragoal/dist/cli.js\" hook user-prompt-submit",
+ "timeout": 10,
+ "statusMessage": "checking OMO ultragoal steering"
+ }
+ ]
+ }
+ ],
+ "PostToolUse": [
+ {
+ "matcher": "^(apply_patch|write|Write|edit|Edit|multi_edit|multiedit|MultiEdit)$",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/components/comment-checker/dist/cli.js\" hook post-tool-use",
+ "timeout": 30,
+ "statusMessage": "checking OMO comments"
+ },
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-tool-use",
+ "timeout": 60,
+ "statusMessage": "checking OMO LSP diagnostics"
+ }
+ ]
+ },
+ {
+ "matcher": "^apply_patch$",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-tool-use",
+ "timeout": 10,
+ "statusMessage": "matching OMO project rules"
+ }
+ ]
+ }
+ ],
+ "PostCompact": [
+ {
+ "matcher": "manual|auto",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-compact",
+ "timeout": 10,
+ "statusMessage": "resetting OMO project rule cache"
+ }
+ ]
+ }
+ ]
+ }
+}
diff --git a/plugins/omo/package-lock.json b/plugins/omo/package-lock.json
new file mode 100644
index 00000000..40f69866
--- /dev/null
+++ b/plugins/omo/package-lock.json
@@ -0,0 +1,1706 @@
+{
+ "name": "@code-yeongyu/omo-codex-plugin",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@code-yeongyu/omo-codex-plugin",
+ "version": "0.1.0",
+ "workspaces": [
+ "components/comment-checker",
+ "components/rules",
+ "components/lsp",
+ "components/lsp/packages/lsp-tools-mcp",
+ "components/telemetry",
+ "components/ultragoal",
+ "components/ultrawork"
+ ]
+ },
+ "components/comment-checker": {
+ "name": "@code-yeongyu/codex-comment-checker",
+ "version": "0.1.1",
+ "license": "MIT",
+ "bin": {
+ "codex-comment-checker": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.15",
+ "@types/node": "^25.7.0",
+ "typescript": "^6.0.3",
+ "vitest": "^4.1.5"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ },
+ "optionalDependencies": {
+ "@code-yeongyu/comment-checker": "^0.8.0"
+ }
+ },
+ "components/lsp": {
+ "name": "@code-yeongyu/codex-lsp",
+ "version": "0.2.0",
+ "license": "MIT",
+ "dependencies": {
+ "@code-yeongyu/lsp-tools-mcp": "file:./packages/lsp-tools-mcp"
+ },
+ "bin": {
+ "codex-lsp": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.15",
+ "@types/node": "^25.7.0",
+ "typescript": "^6.0.3",
+ "vitest": "^4.1.5"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "components/lsp/packages/lsp-tools-mcp": {
+ "name": "@code-yeongyu/lsp-tools-mcp",
+ "version": "0.1.0",
+ "license": "MIT",
+ "bin": {
+ "lsp-tools-mcp": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.15",
+ "@types/node": "^25.7.0",
+ "typescript": "^6.0.3",
+ "vitest": "^4.1.5"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "components/rules": {
+ "name": "@code-yeongyu/codex-rules",
+ "version": "0.1.0",
+ "license": "MIT",
+ "dependencies": {
+ "picomatch": "^4.0.3"
+ },
+ "bin": {
+ "codex-rules": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.15",
+ "@types/node": "^25.7.0",
+ "@types/picomatch": "^4.0.0",
+ "typescript": "^6.0.3",
+ "vitest": "^4.1.5"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "components/telemetry": {
+ "name": "@code-yeongyu/codex-telemetry",
+ "version": "0.1.0",
+ "license": "MIT",
+ "dependencies": {
+ "posthog-node": "^5.34.3"
+ },
+ "bin": {
+ "codex-telemetry": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.15",
+ "@types/node": "^25.7.0",
+ "typescript": "^6.0.3",
+ "vitest": "^4.1.5"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "components/ultragoal": {
+ "name": "@code-yeongyu/codex-ultragoal",
+ "version": "0.1.0",
+ "license": "MIT",
+ "bin": {
+ "omo": "dist/cli.js"
+ },
+ "devDependencies": {
+ "@biomejs/biome": "2.4.15",
+ "@types/node": "^25.7.0",
+ "typescript": "^6.0.3",
+ "vitest": "^4.1.5"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "components/ultrawork": {
+ "name": "@code-yeongyu/codex-ultrawork",
+ "version": "0.1.0",
+ "license": "MIT"
+ },
+ "node_modules/@biomejs/biome": {
+ "version": "2.4.15",
+ "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.4.15.tgz",
+ "integrity": "sha512-j5VH3a/h/HXTKBM50MDMxRCzkeLv9S2XJcW2WgnZT1+xyisi+0bISrXR82gCX+8S9lvK0skEvHJRN+3Ktr2hlw==",
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "bin": {
+ "biome": "bin/biome"
+ },
+ "engines": {
+ "node": ">=14.21.3"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/biome"
+ },
+ "optionalDependencies": {
+ "@biomejs/cli-darwin-arm64": "2.4.15",
+ "@biomejs/cli-darwin-x64": "2.4.15",
+ "@biomejs/cli-linux-arm64": "2.4.15",
+ "@biomejs/cli-linux-arm64-musl": "2.4.15",
+ "@biomejs/cli-linux-x64": "2.4.15",
+ "@biomejs/cli-linux-x64-musl": "2.4.15",
+ "@biomejs/cli-win32-arm64": "2.4.15",
+ "@biomejs/cli-win32-x64": "2.4.15"
+ }
+ },
+ "node_modules/@biomejs/cli-darwin-arm64": {
+ "version": "2.4.15",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.4.15.tgz",
+ "integrity": "sha512-rF3PPqLq1yoST79zaQbDjVJwsuIeci/O+9bgNmC5QpgOqz6aqYuzA4abyAGx+mgyiDXn4A049xAN8gijbuR1Qg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=14.21.3"
+ }
+ },
+ "node_modules/@biomejs/cli-darwin-x64": {
+ "version": "2.4.15",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.4.15.tgz",
+ "integrity": "sha512-/5KHXYMfSJs1fNXiX30xFtI8JcCFV6zaVVLxOa0M2sfqBKHkpQhRTv94yxQWxeTY2lzo2OuTlNvPC+hDQt2wcQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=14.21.3"
+ }
+ },
+ "node_modules/@biomejs/cli-linux-arm64": {
+ "version": "2.4.15",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.4.15.tgz",
+ "integrity": "sha512-owaAMZD/T4LrD0ELNCk0Km3qrRHuM0X6EAyVE1FSqGY0rbLoiDLrO4Us2tllm6cAeB2Ioa9C2C08NZPdr8+0Ug==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT OR Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=14.21.3"
+ }
+ },
+ "node_modules/@biomejs/cli-linux-arm64-musl": {
+ "version": "2.4.15",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.4.15.tgz",
+ "integrity": "sha512-ZPcxznxm0pogHBLZhYntyR3sR+MrZjqJIKEr7ZqVen0Rl+P/4upVmfYXjftizi9RoqZntg33fv/1fbdhbYXpEQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT OR Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=14.21.3"
+ }
+ },
+ "node_modules/@biomejs/cli-linux-x64": {
+ "version": "2.4.15",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.4.15.tgz",
+ "integrity": "sha512-0jj7THz12GbUOLmMibktK6DZjqz2zV64KFxyBtcFTKPiiOIY0a7vns1elpO1dERvxpsZ5ik0oFfz0oGwFde1+g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT OR Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=14.21.3"
+ }
+ },
+ "node_modules/@biomejs/cli-linux-x64-musl": {
+ "version": "2.4.15",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.4.15.tgz",
+ "integrity": "sha512-CNq/9W38SYSH023lfcQ4KKU8K0YX8T//FZUhcgtMMRABDojx5XsMV7jlweAvGSl389wJQB29Qo6Zb/a+jdvt+w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT OR Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=14.21.3"
+ }
+ },
+ "node_modules/@biomejs/cli-win32-arm64": {
+ "version": "2.4.15",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.4.15.tgz",
+ "integrity": "sha512-ouhkYdlhp/1GghEJPdWwD/Vi3gQ1nFxuSpMolWsbq3Lsq3QUR4jl6UdhhscdCugKU5vOEuMiJhvKj66O0OCq+w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=14.21.3"
+ }
+ },
+ "node_modules/@biomejs/cli-win32-x64": {
+ "version": "2.4.15",
+ "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.4.15.tgz",
+ "integrity": "sha512-zBrGq5mx5wwpnow4+2BxUvleDM+GNd4sLbPaMapsSLQLD0NGRCquqPBTgN+7XkUteHvj7M+BstuI8tmnV7+HgQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT OR Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=14.21.3"
+ }
+ },
+ "node_modules/@code-yeongyu/codex-comment-checker": {
+ "resolved": "components/comment-checker",
+ "link": true
+ },
+ "node_modules/@code-yeongyu/codex-lsp": {
+ "resolved": "components/lsp",
+ "link": true
+ },
+ "node_modules/@code-yeongyu/codex-rules": {
+ "resolved": "components/rules",
+ "link": true
+ },
+ "node_modules/@code-yeongyu/codex-telemetry": {
+ "resolved": "components/telemetry",
+ "link": true
+ },
+ "node_modules/@code-yeongyu/codex-ultragoal": {
+ "resolved": "components/ultragoal",
+ "link": true
+ },
+ "node_modules/@code-yeongyu/codex-ultrawork": {
+ "resolved": "components/ultrawork",
+ "link": true
+ },
+ "node_modules/@code-yeongyu/comment-checker": {
+ "version": "0.8.0",
+ "resolved": "https://registry.npmjs.org/@code-yeongyu/comment-checker/-/comment-checker-0.8.0.tgz",
+ "integrity": "sha512-Ret0qHtgDhEemQYNduqSyaihFWJSOKae4YW3sUHS680G8K57CsRUkK6Gs4kbzDuWqiNUYs254+qu5hZZZSEKUA==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "bin": {
+ "comment-checker": "cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@code-yeongyu/lsp-tools-mcp": {
+ "resolved": "components/lsp/packages/lsp-tools-mcp",
+ "link": true
+ },
+ "node_modules/@emnapi/core": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz",
+ "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.2.1",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.10.0",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz",
+ "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@emnapi/wasi-threads": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz",
+ "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.5.5",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
+ "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@napi-rs/wasm-runtime": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz",
+ "integrity": "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@tybys/wasm-util": "^0.10.1"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "peerDependencies": {
+ "@emnapi/core": "^1.7.1",
+ "@emnapi/runtime": "^1.7.1"
+ }
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.132.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.132.0.tgz",
+ "integrity": "sha512-FESMOxil5Se014ui/Eq8fT5uHJo6nIRwH0PfJrZJXs6Gek3ZVFOrpUv3YIZT20m+extU98Hg1Ym72U58rlsxUQ==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ }
+ },
+ "node_modules/@posthog/core": {
+ "version": "1.29.9",
+ "resolved": "https://registry.npmjs.org/@posthog/core/-/core-1.29.9.tgz",
+ "integrity": "sha512-DjvuIyBZ2Z/gBhtZlITlM2D8PlnMsHSQ1D78dbUYoVsgGguvanpJTobZObjLlFkybyvfZFYkpoJkFNI/2Pw4IQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@posthog/types": "1.376.0"
+ }
+ },
+ "node_modules/@posthog/types": {
+ "version": "1.376.0",
+ "resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.376.0.tgz",
+ "integrity": "sha512-gbFfxCuZDs/D4QZMwdE+smD1jsuqgGpS6yKGHZZ19foxMy8RYHsU1E47iG1b88n/uN02fAabLibVwuxLtq8juw==",
+ "license": "MIT"
+ },
+ "node_modules/@rolldown/binding-android-arm64": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.2.tgz",
+ "integrity": "sha512-ZS4D1JPGn/MYQN/SYDWftIE/nVsM8j/AFOYEzAoOE2O3NktQOZru+/vYXGbR/qtdLdIfGCP0lcoJiYVzsEz+iQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-arm64": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.2.tgz",
+ "integrity": "sha512-vdFA9+C/rekyGce7WqHs/xoT0ioZEWaOFyZLIV1mEeNFaFDUQrPIo8Vs2GvJ6eetb3rzDUtUBgzto3ExpXJB3w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-x64": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.2.tgz",
+ "integrity": "sha512-BewSOwTHazv77DTYiAZXSqqKZ4KP/KonFisDMVU7PImxoWfB2aepnPhd2E4SWz3zDzYgDNbs6jBmTdgNnF02GA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-freebsd-x64": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.2.tgz",
+ "integrity": "sha512-m41o7M0YWtUdqk61Tb+jnKb2rN++iRdIASlExkUoKfIAH30DOHCB8fVLzSUpbWHHU8esmEioY62PxzexE8MBuA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.2.tgz",
+ "integrity": "sha512-jcojB9H7W/jS29pMKWAK1N+fU99vXodHDTatS3b3y/XSOCiHo0kkA74pL3jJmkoQtYpOCxDvaKs1fo2Ij/1X5w==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.2.tgz",
+ "integrity": "sha512-1jn6qDU5iiOgFgygDzKUuKP0maTi0/f1+sBLgvij/76C77Nm3ts6ufz9Bjg5q5dduxiUIxtq86JIoBvo1xQ4Ig==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-musl": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.2.tgz",
+ "integrity": "sha512-QVLO/czFMdoMFSqlX3bcswcJNm/23r+qoa/jgtmFc/qEp6/jXmIkDjF/XIo8dPfGaiwy1xfQn8o77L79GeXFgw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.2.tgz",
+ "integrity": "sha512-hgO5Abm0w5UL6FEa2iFnZqo2KlK7TQ5QhV5x09hujBf7t5KzHQ1VmfPuTpqRy/rNlSxua3eWH374xxiVrP+lcA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.2.tgz",
+ "integrity": "sha512-fy8rXxuYEu602abC8MUNaPjYLIFzReOaEIEMKMUa0rFEUxNpVXhs15KSSQ4qlqSaM7B6rcj9rDZgADh/IGDzLQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-gnu": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.2.tgz",
+ "integrity": "sha512-0+bOkiQ779+r1WpoHOWHqncvyySci0vKph+myNDYb+im6meJAzHQXay6oEgnkHuUGouM1LKTZwqKpBow6Kj7CQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-musl": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.2.tgz",
+ "integrity": "sha512-mjSkrzZK5Qsl0a9d1JgILOiuZOSDTVdKENcSXBoqbzSrspLR/4/IRVDo5wd2GgZjNss/viBFJdeq+j7qH2nypw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-openharmony-arm64": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.2.tgz",
+ "integrity": "sha512-1v5vHasdfQAZoEHakBV72LIFAC9JjnymsiKxp+GEr/ma3+NJCPSaYK+qavInOovJkgwFrs7GccX2d6IgDA3Z5w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-wasm32-wasi": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.2.tgz",
+ "integrity": "sha512-mb1VobWn6NheziTk5/WEaR6AKVbrwT5sOi6C7zk3gy/pD1qtJfU1j4PgTo2NJnOtbL9Dl3Aeei8w9jJ7qC2jZQ==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/core": "1.10.0",
+ "@emnapi/runtime": "1.10.0",
+ "@napi-rs/wasm-runtime": "^1.1.4"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.2.tgz",
+ "integrity": "sha512-SqKonF56vA/L2yHwHYcEp2P34URpOZ7d1fS635cTkpDnUtEGdUbhI6NzsPdqeSWvAAeGDrxjWjNmibDIdFf9/A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-x64-msvc": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.2.tgz",
+ "integrity": "sha512-v7qRI7gXLRINcOGXt+7YmAZ6iFuyZVMIoXAxhd8oP+DR9dLfL9GfNIx7PLMxmhZdvq8waUJBQiWN9EKNy+TRBQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@standard-schema/spec": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
+ "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@tybys/wasm-util": {
+ "version": "0.10.2",
+ "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz",
+ "integrity": "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "25.9.1",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.1.tgz",
+ "integrity": "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": ">=7.24.0 <7.24.7"
+ }
+ },
+ "node_modules/@types/picomatch": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/@types/picomatch/-/picomatch-4.0.3.tgz",
+ "integrity": "sha512-iG0T6+nYJ9FAPmx9SsUlnwcq1ZVRuCXcVEvWnntoPlrOpwtSTKNDC9uVAxTsC3PUvJ+99n4RpAcNgBbHX3JSnQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@vitest/expect": {
+ "version": "4.1.7",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.7.tgz",
+ "integrity": "sha512-1R+tw0ortHEbZDGMymm+pN7/AFQ/RkFFdtd7EN+VBpynKmLbP8A3rpEXdshBJ7+8hQ9zBJh/i1s0yKNtxAnU7w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@standard-schema/spec": "^1.1.0",
+ "@types/chai": "^5.2.2",
+ "@vitest/spy": "4.1.7",
+ "@vitest/utils": "4.1.7",
+ "chai": "^6.2.2",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "4.1.7",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.7.tgz",
+ "integrity": "sha512-vY7nuamKgfvpA1Koa3oYIw/k7D6kZnpGyNMZW8loow2bsBYla1TFdqTaXncWdRn4pgwNs+90RhnXhJScDwQeJA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "4.1.7",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.21"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "4.1.7",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.7.tgz",
+ "integrity": "sha512-umgCarTOYQWIaDMvGDRZij+6b9oVeLIyJzfN+AS88e0ZOU3QTgNNSTtjQOpcvWr3np1N0j4WgZj+sb3oYBDscw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "4.1.7",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.7.tgz",
+ "integrity": "sha512-BapjmAQ2aI78WdMEfeUWivnfVzB+VPGwWRQcJE0OUq7qEeEcBsCSf+0T5iREBNE5nBb4wA5Ya0W6IA+sghdEFw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "4.1.7",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "4.1.7",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.7.tgz",
+ "integrity": "sha512-ZacLzja+TmJeZ1h14xW2FB/WpeimUD3haBXQPyJqxvo8jQTmfeA8zv58mtjN2C7EHXZDYVcVYdYmAxjkWVvKCw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.7",
+ "@vitest/utils": "4.1.7",
+ "magic-string": "^0.30.21",
+ "pathe": "^2.0.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "4.1.7",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.7.tgz",
+ "integrity": "sha512-kbkI5LMWakyuTIvs6fUJ5qdIVb1XVKsYJAT4OJ938cHMROYMSfmoQdZy0aaAnjbbc8F61vkoTqz/Az+/HiIu5Q==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "4.1.7",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.7.tgz",
+ "integrity": "sha512-T532WBu791cBxJlCl6SO+J14l81DQx6uQHm1bQbmCDY7nqlEIgkza/UFnSBNaUtSf41unldDFjdOBYEQC4b5Hw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "4.1.7",
+ "convert-source-map": "^2.0.0",
+ "tinyrainbow": "^3.1.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/chai": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/convert-source-map": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
+ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/es-module-lexer": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.1.0.tgz",
+ "integrity": "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",
+ "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/lightningcss": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
+ "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "detect-libc": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ },
+ "optionalDependencies": {
+ "lightningcss-android-arm64": "1.32.0",
+ "lightningcss-darwin-arm64": "1.32.0",
+ "lightningcss-darwin-x64": "1.32.0",
+ "lightningcss-freebsd-x64": "1.32.0",
+ "lightningcss-linux-arm-gnueabihf": "1.32.0",
+ "lightningcss-linux-arm64-gnu": "1.32.0",
+ "lightningcss-linux-arm64-musl": "1.32.0",
+ "lightningcss-linux-x64-gnu": "1.32.0",
+ "lightningcss-linux-x64-musl": "1.32.0",
+ "lightningcss-win32-arm64-msvc": "1.32.0",
+ "lightningcss-win32-x64-msvc": "1.32.0"
+ }
+ },
+ "node_modules/lightningcss-android-arm64": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz",
+ "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-arm64": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz",
+ "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-x64": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz",
+ "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-freebsd-x64": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz",
+ "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm-gnueabihf": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz",
+ "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-gnu": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz",
+ "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-musl": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz",
+ "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-gnu": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz",
+ "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-musl": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz",
+ "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-arm64-msvc": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz",
+ "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-x64-msvc": {
+ "version": "1.32.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz",
+ "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.12",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
+ "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/obug": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz",
+ "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT"
+ },
+ "node_modules/pathe": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
+ "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.4",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
+ "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.15",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
+ "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.12",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/posthog-node": {
+ "version": "5.35.2",
+ "resolved": "https://registry.npmjs.org/posthog-node/-/posthog-node-5.35.2.tgz",
+ "integrity": "sha512-YwzkogTUrsFeUnJJH17p3zoZBFaHIh6swYoLV4Ic5pmd8fIVTz8w7NsHR7eWmJlqYe/+Hqo1acGN1jclNUbz3A==",
+ "license": "MIT",
+ "dependencies": {
+ "@posthog/core": "1.29.9"
+ },
+ "engines": {
+ "node": "^20.20.0 || >=22.22.0"
+ },
+ "peerDependencies": {
+ "rxjs": "^7.0.0"
+ },
+ "peerDependenciesMeta": {
+ "rxjs": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/rolldown": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.2.tgz",
+ "integrity": "sha512-oZx5zVDtVB44AW3eaifgDml1gWRDZGvjcfdxonE4swNPG98PrrXjaO/KrnUjzlMnztCCRVlUueA1kCXhARGk6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@oxc-project/types": "=0.132.0",
+ "@rolldown/pluginutils": "^1.0.0"
+ },
+ "bin": {
+ "rolldown": "bin/cli.mjs"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "optionalDependencies": {
+ "@rolldown/binding-android-arm64": "1.0.2",
+ "@rolldown/binding-darwin-arm64": "1.0.2",
+ "@rolldown/binding-darwin-x64": "1.0.2",
+ "@rolldown/binding-freebsd-x64": "1.0.2",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.0.2",
+ "@rolldown/binding-linux-arm64-gnu": "1.0.2",
+ "@rolldown/binding-linux-arm64-musl": "1.0.2",
+ "@rolldown/binding-linux-ppc64-gnu": "1.0.2",
+ "@rolldown/binding-linux-s390x-gnu": "1.0.2",
+ "@rolldown/binding-linux-x64-gnu": "1.0.2",
+ "@rolldown/binding-linux-x64-musl": "1.0.2",
+ "@rolldown/binding-openharmony-arm64": "1.0.2",
+ "@rolldown/binding-wasm32-wasi": "1.0.2",
+ "@rolldown/binding-win32-arm64-msvc": "1.0.2",
+ "@rolldown/binding-win32-x64-msvc": "1.0.2"
+ }
+ },
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/std-env": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.1.0.tgz",
+ "integrity": "sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyexec": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.2.2.tgz",
+ "integrity": "sha512-M/Q0B2cp4K7kynaT/vnED1j8TlLY+Pp7C6Wl2bl/7u/F0mUVwdyOpwomQb8JpYLitHUssAJRmLZdMCGsrx7i+g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.16",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.16.tgz",
+ "integrity": "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tinyrainbow": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz",
+ "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "dev": true,
+ "license": "0BSD",
+ "optional": true
+ },
+ "node_modules/typescript": {
+ "version": "6.0.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
+ "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "7.24.6",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz",
+ "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vite": {
+ "version": "8.0.14",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.14.tgz",
+ "integrity": "sha512-s4BJJ+5y1pYL6Otw51FHhVJQhPnuRinKig64g/1+EUNaJsd3gCKdD31IPFvswUgW9/60QT9oFHbZHbQK5imcxw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lightningcss": "^1.32.0",
+ "picomatch": "^4.0.4",
+ "postcss": "^8.5.15",
+ "rolldown": "1.0.2",
+ "tinyglobby": "^0.2.16"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "@vitejs/devtools": "^0.1.18",
+ "esbuild": "^0.27.0 || ^0.28.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "@vitejs/devtools": {
+ "optional": true
+ },
+ "esbuild": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vitest": {
+ "version": "4.1.7",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.7.tgz",
+ "integrity": "sha512-flYyaFd2CgoCoU+0UKt3pxksgC+S02iTDN0n3LtqaMeXsI9SBcdNujc2k0DeFLzUn/0k538yNjOSdwgCqcrwJA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "4.1.7",
+ "@vitest/mocker": "4.1.7",
+ "@vitest/pretty-format": "4.1.7",
+ "@vitest/runner": "4.1.7",
+ "@vitest/snapshot": "4.1.7",
+ "@vitest/spy": "4.1.7",
+ "@vitest/utils": "4.1.7",
+ "es-module-lexer": "^2.0.0",
+ "expect-type": "^1.3.0",
+ "magic-string": "^0.30.21",
+ "obug": "^2.1.1",
+ "pathe": "^2.0.3",
+ "picomatch": "^4.0.3",
+ "std-env": "^4.0.0-rc.1",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^1.0.2",
+ "tinyglobby": "^0.2.15",
+ "tinyrainbow": "^3.1.0",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "4.1.7",
+ "@vitest/browser-preview": "4.1.7",
+ "@vitest/browser-webdriverio": "4.1.7",
+ "@vitest/coverage-istanbul": "4.1.7",
+ "@vitest/coverage-v8": "4.1.7",
+ "@vitest/ui": "4.1.7",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ }
+ }
+}
diff --git a/plugins/omo/package.json b/plugins/omo/package.json
new file mode 100644
index 00000000..5b88cc7d
--- /dev/null
+++ b/plugins/omo/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "@code-yeongyu/omo-codex-plugin",
+ "version": "0.1.0",
+ "description": "Aggregate Codex plugin root for OMO components.",
+ "type": "module",
+ "packageManager": "[email protected]",
+ "private": true,
+ "workspaces": [
+ "components/comment-checker",
+ "components/rules",
+ "components/lsp",
+ "components/lsp/packages/lsp-tools-mcp",
+ "components/telemetry",
+ "components/ultragoal",
+ "components/ultrawork"
+ ],
+ "scripts": {
+ "build": "node scripts/sync-skills.mjs && node ../scripts/sync-telemetry-component.mjs && npm run build --workspaces --if-present",
+ "check": "npm run build && npm test",
+ "sync:skills": "node scripts/sync-skills.mjs",
+ "test": "node --test test/*.test.mjs"
+ }
+}
diff --git a/plugins/omo/scripts/sync-skills.mjs b/plugins/omo/scripts/sync-skills.mjs
new file mode 100644
index 00000000..6ba2923a
--- /dev/null
+++ b/plugins/omo/scripts/sync-skills.mjs
@@ -0,0 +1,74 @@
+#!/usr/bin/env node
+import { cp, mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const root = dirname(dirname(fileURLToPath(import.meta.url)));
+const sharedSkillsRoot = join(root, "..", "..", "shared-skills", "skills");
+const skillsRoot = join(root, "skills");
+const skillSources = [
+ ["comment-checker", "components/comment-checker/skills/comment-checker"],
+ ["lsp", "components/lsp/skills/lsp"],
+ ["rules", "components/rules/skills/rules"],
+ ["ultragoal", "components/ultragoal/skills/ultragoal"],
+];
+
+const opencodeOnlyOrchestrationPattern = /\b(?:call_omo_agent|background_output|team_[a-z_]+|task)\s*\(/;
+
+const codexHarnessToolCompatibility = `## Codex Harness Tool Compatibility
+
+This skill may include examples copied from the OpenCode harness. In Codex, do not call OpenCode-only tools such as \`call_omo_agent(...)\`, \`task(...)\`, \`background_output(...)\`, or \`team_*(...)\` literally. Translate those examples to Codex native tools:
+
+| OpenCode example | Codex tool to use |
+| --- | --- |
+| \`call_omo_agent(subagent_type="explore", ...)\` | \`spawn_agent(agent_type="explorer", task_name="...", message="...")\` |
+| \`call_omo_agent(subagent_type="librarian", ...)\` | \`spawn_agent(agent_type="librarian", task_name="...", message="...")\` |
+| \`task(subagent_type="plan", ...)\` | \`spawn_agent(agent_type="plan", task_name="...", message="...")\` |
+| \`task(subagent_type="oracle", ...)\` for final verification | \`spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...")\` |
+| \`task(category="...", ...)\` for implementation or QA | \`spawn_agent(agent_type="worker", task_name="...", message="...")\` |
+| \`background_output(task_id="...")\` | \`wait_agent(...)\` to wait for subagent completion and mailbox updates |
+| \`team_*(...)\` | Use Codex native subagents plus \`send_message\`, \`followup_task\`, \`wait_agent\`, and \`close_agent\` |
+
+When translating \`load_skills=[...]\`, include the requested skill names in the spawned agent's \`message\`. If a code block below conflicts with this section, this section wins.
+
+`;
+
+function insertCodexCompatibilityGuidance(content) {
+ if (!opencodeOnlyOrchestrationPattern.test(content)) return content;
+ if (content.includes("## Codex Harness Tool Compatibility")) return content;
+
+ const frontmatterMatch = content.match(/^---\n[\s\S]*?\n---\n+/);
+ if (!frontmatterMatch) {
+ return `${codexHarnessToolCompatibility}${content}`;
+ }
+
+ return `${frontmatterMatch[0]}${codexHarnessToolCompatibility}${content.slice(frontmatterMatch[0].length)}`;
+}
+
+async function adaptSkillForCodex(skillName) {
+ const skillPath = join(skillsRoot, skillName, "SKILL.md");
+ const content = await readFile(skillPath, "utf8");
+ const adapted = insertCodexCompatibilityGuidance(content);
+ if (adapted !== content) {
+ await writeFile(skillPath, adapted, "utf8");
+ }
+}
+
+await rm(skillsRoot, { recursive: true, force: true });
+await mkdir(skillsRoot, { recursive: true });
+
+for (const [name, source] of skillSources) {
+ await cp(join(root, source), join(skillsRoot, name), { recursive: true });
+ await adaptSkillForCodex(name);
+}
+
+const sharedSkillEntries = await readdir(sharedSkillsRoot, { withFileTypes: true });
+const sharedSkillNames = sharedSkillEntries
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => entry.name)
+ .sort();
+
+for (const skillName of sharedSkillNames) {
+ await cp(join(sharedSkillsRoot, skillName), join(skillsRoot, skillName), { recursive: true });
+ await adaptSkillForCodex(skillName);
+}
diff --git a/plugins/omo/skills/ai-slop-remover/SKILL.md b/plugins/omo/skills/ai-slop-remover/SKILL.md
new file mode 100644
index 00000000..d3fd536b
--- /dev/null
+++ b/plugins/omo/skills/ai-slop-remover/SKILL.md
@@ -0,0 +1,142 @@
+---
+name: ai-slop-remover
+description: "Removes AI-generated code smells from a SINGLE file while preserving functionality. For multiple files, call in PARALLEL per file."
+---
+You are an expert code refactorer specializing in removing AI-generated "slop" patterns while STRICTLY preserving functionality.
+
+**INPUT**: Exactly ONE file path. If multiple paths provided, REJECT and instruct to call this agent in parallel.
+
+---
+
+## DETECTION CRITERIA (Specific)
+
+### 1. Obvious Comments (EXCLUDE: BDD comments like #given, #when, #then, #when/then)
+
+**REMOVE**:
+- Comments restating the code: `x += 1 # increment x`
+- Docstrings on trivial methods: `"""Returns the name."""` for `def get_name(): return self.name`
+- Section dividers: `# ===== HELPER FUNCTIONS =====`
+- Commented-out code blocks
+- `# TODO: future enhancement` without concrete plan
+- `# Note: this is important` without explaining WHY
+
+**KEEP**:
+- Comments explaining WHY (business logic, edge cases, workarounds)
+- Links to issues/tickets: `# See SPR-1234`
+- Non-obvious algorithm explanations
+- Regex explanations
+- Matches to existing code style
+
+### 2. Over-Defensive Code
+
+**REMOVE**:
+- Null checks for values that CANNOT be None (e.g., Django request in view)
+- `if x is not None and x.attr is not None:` when x is guaranteed
+- Try-except around code that can't raise (e.g., dict literal access)
+- `isinstance()` checks for statically typed parameters
+- Default values for required parameters: `def foo(x: str = "")` when empty string is invalid
+- Backward-compat shims: `_old_name = new_name # deprecated`
+- `# removed` or `# deleted` comments for removed code
+- Re-exports of unused items
+- Verbose, duplicated, or redundant code / test cases
+
+**KEEP**:
+- Validation at system boundaries (user input, external API responses)
+- Error handling for I/O operations
+- Null checks for nullable DB fields
+- assertions in test code to matching type expectations
+
+### 3. Spaghetti Nesting (2+ levels deep)
+
+**REFACTOR**:
+- Nested if-else chains -> early returns / guard clauses
+- `if x: if y: if z:` -> `if not x: return` / `if not y: return`
+- Nested loops with conditionals -> extract to helper OR use comprehensions
+- Complex ternary `a if b else (c if d else e)` -> explicit if-else
+
+---
+
+## PROCESS
+
+### Step 1: Read & Analyze
+Read the file. Identify ALL slop instances with line numbers.
+
+### Step 2: Deep Consideration (CRITICAL)
+For EACH identified issue, think:
+- **Functionality Impact**: Will removing this change behavior? If ANY doubt, SKIP.
+- **Test Coverage**: Are there tests that might break? If uncertain, SKIP.
+- **Context Dependency**: Is this "slop" actually necessary for this specific codebase? (e.g., defensive code for known flaky external API)
+- **Readability Trade-off**: Will removal make code LESS readable? If yes, SKIP.
+
+**RULE**: When in doubt, DO NOT CHANGE. False negatives are better than breaking code.
+
+### Step 3: Execute Changes
+Make changes using Edit tool. One logical change at a time.
+
+### Step 4: Detailed Report
+
+**OUTPUT FORMAT**:
+
+```
+## AI Slop Removed: {filename}
+
+### Analysis Summary
+- Total issues found: N
+- Issues fixed: M
+- Issues skipped (safety): K
+
+### Changes Made
+
+#### Change 1: [Category] Line X-Y
+**Before**: [original code snippet]
+**After**: [modified code snippet]
+**Why this is slop**: [Explain why this pattern is problematic]
+**Why safe to remove**: [Explain why functionality is preserved]
+**Impact**: None - purely cosmetic improvement
+
+---
+
+### Skipped Issues (Preserved for Safety)
+
+#### Skipped 1: Line X
+**Reason**: [Why you chose not to change this]
+
+### Summary
+- Removed N obvious comments
+- Simplified M defensive patterns
+- Flattened K nested structures
+- Preserved L patterns that looked like slop but serve purpose
+```
+
+---
+
+## SAFETY RULES
+
+1. **NEVER remove error handling for I/O, network, or file operations**
+2. **NEVER simplify validation for user input or external data**
+3. **NEVER change public API signatures**
+4. **NEVER remove type hints (even redundant-looking ones)**
+5. **If a pattern appears in multiple places, it might be intentional - ASK before bulk removal**
+6. **Preserve all BDD test comments (#given, #when, #then)**
+
+When finished, your report should be detailed enough that a reviewer can understand EXACTLY what changed and feel confident the changes are safe.
+
+---
+
+## WHEN NO SLOP FOUND
+
+If the file is clean, report:
+
+```
+## AI Slop Analysis: {filename}
+
+### Result: No AI Slop Detected
+
+This file is clean. Here's why:
+
+**Comments**: N comments found, all explain WHY not WHAT
+**Defensive Code**: Null checks present are appropriate (e.g., checks external API response)
+**Code Structure**: Maximum nesting depth acceptable, early returns used appropriately
+
+**Conclusion**: This code appears to be human-written or well-reviewed AI code. No changes needed.
+```
\ No newline at end of file
diff --git a/plugins/omo/skills/comment-checker/SKILL.md b/plugins/omo/skills/comment-checker/SKILL.md
new file mode 100644
index 00000000..7ce77101
--- /dev/null
+++ b/plugins/omo/skills/comment-checker/SKILL.md
@@ -0,0 +1,16 @@
+---
+name: comment-checker
+description: Use when Codex needs to understand or respond to automatic comment-checker feedback emitted after an edit-like PostToolUse hook.
+---
+
+# Codex Comment Checker
+
+The plugin registers a `PostToolUse` hook for successful `apply_patch`, `write`, `edit`, `multi_edit`, and `multiedit` calls.
+
+When comment-checker reports a warning after a patch, Codex receives blocking feedback and should fix or explain the flagged comment before moving on.
+
+## Scope
+
+- No MCP tool is exposed.
+- Non-edit tools are ignored by this plugin.
+- Missing checker binaries emit no hook output so normal Codex work can continue.
diff --git a/plugins/omo/skills/debugging/SKILL.md b/plugins/omo/skills/debugging/SKILL.md
new file mode 100644
index 00000000..9aacfa3e
--- /dev/null
+++ b/plugins/omo/skills/debugging/SKILL.md
@@ -0,0 +1,116 @@
+---
+name: debugging
+description: "MUST USE for any real runtime debugging across ANY language or binary — crashes, silent failures, wrong responses, stuck processes, memory leaks, async misbehavior, unexplained timing, reverse engineering. Runs a hypothesis-driven loop: form ≥3 hypotheses, investigate in parallel, after 2 failed rounds spawn Oracles from orthogonal angles, confirm root cause, lock with a failing test, fix minimally, QA by actually USING the system, scrub artifacts. The actual HOW lives in `references/` — READ THEM. Triggers: 'debug this', 'why is X not working', 'hanging', 'attach a debugger', 'reverse engineer', 'pwndbg', 'gdb', 'lldb', 'node inspect', 'tsx debug', 'pdb', 'dlv', 'delve', 'rust-gdb', 'set a breakpoint', 'context 터진다', '왜 응답이 비어', '디버거 붙여서', '디버깅해봐', '이거 왜 이래', 'trace this bug', 'reproduce and fix', 'silent failure', 'HTTP 200 but empty', '왜 멈춰', '바이너리 까봐', '리버싱', '플레이라이트'."
+---
+
+# Debugging
+
+You are a hypothesis-driven debugger. Two disciplines apply regardless of language, runtime, or whether you have source:
+
+1. **Runtime truth beats code reading.** Every claim about why the bug happens must come from observed state — never from a plausible story spun from reading code.
+2. **Leave no trace.** Debugging creates artifacts. Every artifact is journaled and removed before you call the task done.
+
+The rest of this file is a map. **The knowledge is in `references/`.** This file cannot teach you how to debug — it can only tell you which reference will, for your exact situation.
+
+---
+
+# 🚨 READ THE REFERENCES. THIS IS NOT OPTIONAL.
+
+> **This skill is intentionally small.** Ninety percent of what you need to know lives in `references/`. If you skim this file and start working without opening the references, you will reattach a debugger the wrong way, miss a silent-failure pattern you've never seen before, waste an hour on a source-map gotcha, or invent a worse version of a tool that already solves your problem.
+>
+> **Every reference below is mandatory when its scenario applies.** "I know this language" is not an exemption. The references exist because every runtime and every specialist tool has at least one gotcha that silently wastes hours, and you will not know which gotcha until you read the file.
+>
+> **The gate rule**: before you run a command from a given reference's domain, you must have read that reference in this session. Re-reading across sessions is cheap. Guessing is expensive.
+
+---
+
+## Runtime Setup — MANDATORY READING BEFORE ATTACHING
+
+The methodology is language-agnostic. The commands to launch, attach, breakpoint, and inspect are not. **Open the matching reference before Phase 0. Not during. Not after.**
+
+| Your runtime is… | Open this before attaching anything | Non-negotiable because… |
+|---|---|---|
+| Python (CPython, pytest, asyncio, Django, FastAPI) | 📖 **[references/runtimes/python.md](references/runtimes/python.md)** | pdb vs ipdb vs debugpy vs pytest --pdb all have different attach semantics. Async code needs special breakpoint handling. Wrappers like `poetry run` swallow flags. |
+| Node.js / tsx / ts-node / Bun / Deno (running source) | 📖 **[references/runtimes/node.md](references/runtimes/node.md)** | `tsx` + `node inspect` CLI has a **silent source-map failure** — breakpoints by line number do not fire. You will not notice unless you read this first. |
+| Rust (cargo, tokio, panics) | 📖 **[references/runtimes/rust.md](references/runtimes/rust.md)** | Release builds strip symbols. Tokio tasks need `tokio-console`. The borrow checker makes `dbg!` the faster tool most of the time. |
+| Go (goroutines, dlv, pprof, race) | 📖 **[references/runtimes/go.md](references/runtimes/go.md)** | Goroutine leaks and recovered panics are silent by default. `dlv` has a specific port convention. `go test -race` is the first thing to run, not the last. |
+| Native binary / stripped C/C++ / no source | 📖 **[references/runtimes/native-binary.md](references/runtimes/native-binary.md)** | The workflow (triage → dynamic → static → scripted repro) is counterintuitive if you've never done it. `strings -n 8` silently drops short interpolations like `${x}` — read bytes directly for any extraction that matters. macOS adds SIP / Mach-O / lldb specifics that don't apply on Linux. |
+| **Bundled-app binary** (Bun SEA, Node SEA, Deno compile, pkg, nexe, Electron, Tauri, PyInstaller) | 📖 **[references/runtimes/bundled-js-binary.md](references/runtimes/bundled-js-binary.md)** | These look like Mach-O / ELF but their *high-level* source is recoverable with the right per-bundler tool — Ghidra is overkill. Source-format reality varies: Bun/pkg/nexe/Electron-asar are usually plaintext; Node SEA with code-cache, PyInstaller `.pyc`, and Deno eszip need extra tooling; Tauri's Rust core still needs native-binary.md. Workflow: identify bundler → locate bundle → extract with the bundler-specific tool → grep. |
+
+**If you cannot honestly say you just opened the reference for your runtime, open it now.**
+
+> 🚨 **Native binary vs bundled binary — check before committing**: `file ./target` calls them both Mach-O / ELF. The 30-second discriminator is `du -h ./target` (50 MB+ suspect bundled) plus `strings -n 12 ./target | rg -iE 'bun|node_modules|webpack|esbuild|deno|pkg/lib|electron|pyinstaller|nexe|NODE_SEA_FUSE|tauri'`. If hits → bundled-js-binary.md. If clean → native-binary.md.
+
+---
+
+## Specialist Tools — ACTIVELY USE WHEN THE SCENARIO FITS
+
+These are not "optional extras". They are the correct tool in their domain, and anything else is slower and less reliable. **If the bug fits the domain, you MUST use the tool. Read the reference first to know how.**
+
+| Tool | Use when | Reference |
+|---|---|---|
+| **Playwright CLI** | Any browser-served web UI bug. Any flow that requires clicking/typing/navigating. Any "works locally, breaks in prod" where the browser or viewport is the variable. **For Phase 8 QA of any browser product, you MUST drive a real browser via Playwright — not curl, not imagination.** | 📖 **[references/tools/playwright-cli.md](references/tools/playwright-cli.md)** |
+| **Ghidra** | Any binary without trustworthy source — third-party closed libs, malware, vendored binaries whose behavior contradicts docs, CTF, firmware. **Use Ghidra's decompiler before `strings`/`objdump` guessing. It turns machine code into readable C.** | 📖 **[references/tools/ghidra.md](references/tools/ghidra.md)** |
+| **pwndbg** | Any native binary debugging session. It is GDB with the useful views (registers, stack, disasm, heap) always visible. **If you'd reach for plain `gdb`, reach for `pwndbg` instead — it is strictly a superset.** | 📖 **[references/tools/pwndbg.md](references/tools/pwndbg.md)** |
+| **pwntools** | Any time you need a reproducible interaction with a binary or network service — crafted payloads, exploit automation, fuzz harness, CTF scripting. | 📖 **[references/tools/pwntools.md](references/tools/pwntools.md)** |
+
+**Failing to use these tools in their domain is a process failure, not a stylistic choice.** If the bug is in a browser and you did Phase 8 without Playwright, you are doing it wrong. If the bug is in a stripped binary and you read hex with `xxd`, you are doing it wrong. The references tell you how. Read them.
+
+---
+
+## The Phase Loop — READ THE REFERENCE FOR THE PHASE YOU ARE ENTERING
+
+Each phase has exactly one reference. Read it as you enter the phase — not in advance, not from memory. The references are self-contained and short.
+
+| # | Phase | 📖 Open this when entering |
+|---|---|---|
+| 0 | **Environment assessment** — know the runtime, ports, symbols, env vars, watchers before attaching | [references/methodology/00-setup.md](references/methodology/00-setup.md) |
+| 1 | **Journal setup** — single `.debug-journal.md` tracks every artifact for guaranteed revert | [references/methodology/00-setup.md](references/methodology/00-setup.md) |
+| 2 | **Hypothesis formation** — minimum three, across orthogonal axes, each with distinguishing evidence | [references/methodology/02-investigate.md](references/methodology/02-investigate.md) |
+| 3 | **Parallel investigation** — team mode `debug-squad` when enabled, async subagents otherwise | [references/methodology/02-investigate.md](references/methodology/02-investigate.md) |
+| 4 | **Oracle Triple** — after 2 consecutive failed rounds, spawn three Oracles with orthogonal framings and synthesize | [references/methodology/04-oracle-triple.md](references/methodology/04-oracle-triple.md) |
+| 5 | **User decision escalation** — only when evidence exhausted and the call has policy implications | [references/methodology/05-escalate.md](references/methodology/05-escalate.md) |
+| 6 | **Root cause confirmation** — confirmed only when toggling the suspected cause toggles the bug | [references/methodology/06-fix.md](references/methodology/06-fix.md) |
+| 7 | **TDD fix** — red test first, minimal green, no scope expansion | [references/methodology/06-fix.md](references/methodology/06-fix.md) |
+| 8 | **Manual QA** — actually use the system (tmux for CLI, Playwright for browser, real curl for API, real repro for binary) | [references/methodology/08-qa.md](references/methodology/08-qa.md) |
+| 9 | **Cleanup** — walk the journal, revert every artifact, verify `git diff` shows only fix + test | [references/methodology/09-cleanup.md](references/methodology/09-cleanup.md) |
+| 10 | **Final verification** — four evidence gates before declaring done | [references/methodology/09-cleanup.md](references/methodology/09-cleanup.md) |
+
+**Phase references are short by design.** Reading one takes a minute. Skipping one costs an hour.
+
+### Cross-cutting methodology references
+
+These are not phases — read them when the situation calls for them:
+
+| Situation | Reference |
+|---|---|
+| You cannot run the actual operation (paid API, blocked network, missing hardware) but still need runtime evidence | 📖 **[references/methodology/partial-runtime-evidence.md](references/methodology/partial-runtime-evidence.md)** |
+| You're about to declare an extraction / audit / reverse-engineering task done and want a skeptical pass | 📖 **[references/methodology/partial-runtime-evidence.md#verification-oracle-pattern-for-non-debug-tasks](references/methodology/partial-runtime-evidence.md#verification-oracle-pattern-for-non-debug-tasks)** (Verification Oracle is *not* the same as Oracle Triple — read the file) |
+
+---
+
+## Non-Negotiable Safety Invariants
+
+<safety>
+1. **Runtime state is the only source of truth.** A hypothesis without an observed value is a guess. Do not fix guesses.
+2. **Every debug artifact is journaled before it is created.** Journal-then-modify, not modify-then-remember-maybe.
+3. **Never ship a fix without a failing-first test.** Red→green transition required, or the fix is unverified.
+4. **Never declare done on type-check/compile alone.** Types catch declaration bugs. Only running the actual user scenario catches the actual user bug.
+5. **Never ask the user a question that runtime evidence can already answer.** Escalation is for genuine ambiguity.
+6. **Never silently swallow errors while debugging.** If the system swallows errors, that is often the bug itself. Make them loud temporarily; restore at cleanup.
+7. **Never `git commit` from inside this skill.** Commits belong to `/git-master` after the user confirms the fix.
+8. **Never attach without having read the runtime reference.** The gate rule.
+</safety>
+
+---
+
+## What to Do Right Now
+
+1. Read the user's bug description.
+2. Identify the runtime.
+3. **Open `references/runtimes/<runtime>.md`.** Read it.
+4. Identify which specialist tools apply. **Open each matching `references/tools/*.md`.** Read them.
+5. Open `references/methodology/00-setup.md` and start Phase 0.
+6. Follow the phase loop. Read each methodology reference as you enter the phase.
+
+**The references are the skill. This file is an index.**
diff --git a/plugins/omo/skills/debugging/references/methodology/00-setup.md b/plugins/omo/skills/debugging/references/methodology/00-setup.md
new file mode 100644
index 00000000..14fd08cf
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/methodology/00-setup.md
@@ -0,0 +1,108 @@
+# Phase 0 + 1 — Environment Assessment & Journal Setup
+
+Before a debugger touches anything, you need a map of what's running and a ledger of what you'll touch. Skipping either phase is how debug sessions turn into "why is my repo dirty a week later" sessions.
+
+---
+
+## Phase 0 — Environment Assessment
+
+Map the ground truth before you attach. Attaching the wrong way wastes the first hour.
+
+### 1. Identify the runtime
+
+Read the actual manifest file, don't guess from extensions:
+
+- Python → `pyproject.toml`, `requirements*.txt`, `setup.py`, `uv.lock`, `.python-version`
+- Node → `package.json` (check `scripts`, check `engines`, check `type: module`)
+- Rust → `Cargo.toml`, `rust-toolchain*`
+- Go → `go.mod`, `go.sum`
+- Native / mixed → `Makefile`, `CMakeLists.txt`, the binary itself (`file <path>`)
+
+### 2. Load the matching runtime reference
+
+The moment you know the runtime, open `references/runtimes/<runtime>.md`. The commands in this phase (and every phase after) are runtime-specific. The shape of the answers is the same; the commands are not.
+
+### 3. Gather observable environment state
+
+The shape of the answers you need (commands in the runtime reference):
+
+| Question | Why it matters |
+|---|---|
+| What binary/interpreter/runtime actually launches the process? | Determines debugger flag plumbing. Wrappers (`tsx`, `poetry run`, `cargo run`, `bun`, supervisor scripts) change how flags propagate. |
+| Is there already a debug-relevant port in use, or another instance of the service running? | Either attach to it or kill it deliberately — never silently compete. |
+| Are symbols / source maps / debug info present and correct? | This determines whether breakpoints land on the right lines. Compiled-but-not-debug builds, stripped binaries, and incomplete source maps all silently misplace breakpoints. |
+| Does the code path require env vars, config files, or auth tokens to reach the bug? | Missing env often produces early-return paths that masquerade as the bug itself. |
+| Is there an existing failing test or known repro? | Prefer amplifying an existing repro over inventing one. |
+| Are watchers (file watchers, hot reloaders, supervisors) going to restart the process mid-session? | If yes, turn them off before attaching. Restarts drop inspector connections and invalidate breakpoints. |
+
+### 4. Gate check
+
+If any answer is "I'm not sure", you are not ready for Phase 1. Investigate until certain. Guessing here cascades into false-positive hypotheses in Phase 2.
+
+---
+
+## Phase 1 — Journal Setup
+
+Open **one** journal file at the project root: `.debug-journal.md`. Single source of truth for every artifact this skill creates. The contract with the user that you can undo everything.
+
+### Exclude from git (don't pollute the committed ignore list)
+
+```bash
+grep -qx '.debug-journal.md' .git/info/exclude || echo '.debug-journal.md' >> .git/info/exclude
+```
+
+`.git/info/exclude` is per-clone and not committed — perfect for local-session artifacts.
+
+### Journal template
+
+```markdown
+# Debug Journal — <short bug name>
+Started: <ISO timestamp>
+Goal: <one-sentence user request>
+
+## Environment snapshot (Phase 0)
+- Runtime: <language + version + launcher>
+- Entry: <command that starts the process>
+- Ports / sockets: <app=..., debugger=..., etc>
+- Git HEAD: <sha>, working tree clean? <yes/no>
+- References read: <list the files from references/ you loaded — proves you did the gate>
+
+## Hypotheses
+1. [STATUS] <hypothesis> — distinguishing evidence: <what would confirm/refute> — if true, fix is: <two words>
+2. ...
+
+## Failed hypothesis round counter
+- Round 1: <result>
+- Round 2: <result>
+<!-- At 2 consecutive failures, invoke Oracle Triple (see 04-oracle-triple.md). -->
+
+## Artifacts to revert
+<!-- Every temp edit, tmux session, fixture, env override, saved debugger session goes here
+ BEFORE it is created. The rule is journal-then-modify. -->
+- [ ] `src/foo.py` — added `breakpoint()` on 2 lines. Revert: `git checkout src/foo.py`
+- [ ] tmux session `debug-server`. Kill: `tmux kill-session -t debug-server`
+- [ ] `/tmp/debug-payload.json`. Remove: `rm /tmp/debug-payload.json`
+- [ ] env var in current shell: `FOO_BASE_URL=...`. Unset when done.
+- [ ] GDB session save: `~/ghidra-projects/scratch.gzf`. Remove if not promoting.
+
+## Findings
+<!-- Append observed values here with timestamp. Verbatim only, no paraphrasing. -->
+
+## Oracle Triple (if invoked)
+<!-- One subsection per Oracle round, with the synthesized new hypothesis set. -->
+
+## Final fix
+<!-- File paths + test path. Filled during Phase 7. -->
+```
+
+### The journal-then-modify rule
+
+Before any modification to the repo, shell, or system state, append to "Artifacts to revert" first. This one discipline is what prevents debug sessions from becoming git cleanup sessions.
+
+If you catch yourself about to run a command that creates a file, opens a port, or modifies source — stop, journal the intended artifact with its revert command, then run the command. Not the other way around.
+
+### Why a single journal (not scattered TODO comments)
+
+- One `git checkout`, one `rm`, one `tmux kill-session` list — simple Phase 9 walk.
+- Survives interruptions. If you get pulled away mid-session, the next agent (or you later) can continue or revert without guessing.
+- Prevents the most common failure: leaving `console.log`/`print()`/`dbg!` scattered across the tree.
diff --git a/plugins/omo/skills/debugging/references/methodology/02-investigate.md b/plugins/omo/skills/debugging/references/methodology/02-investigate.md
new file mode 100644
index 00000000..5a01c301
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/methodology/02-investigate.md
@@ -0,0 +1,130 @@
+# Phase 2 + 3 — Hypothesis Formation & Parallel Investigation
+
+One hypothesis is a hunch. Three hypotheses is a decision. Investigation is how you turn the decision into runtime evidence.
+
+---
+
+## Phase 2 — Hypothesis Formation (Minimum Three)
+
+### Why three, not one
+
+A single hypothesis creates confirmation bias: you'll read runtime state looking for evidence that confirms it and unconsciously discount contradictions. Three hypotheses force you to design queries that *distinguish* between them, which is the only way runtime evidence becomes decisive.
+
+### Generate across orthogonal axes
+
+If your three hypotheses are all variations of "the handler has a bug", you don't actually have three hypotheses. Span the space:
+
+| Axis | Example framing |
+|---|---|
+| **User-code logic** | "The handler early-returns because condition X is unexpectedly true" |
+| **Library/SDK behavior** | "The third-party client swallows the error and returns a stub" |
+| **Environment/config** | "The env var is read at module-load time before it gets populated, so it's empty" |
+| **Async/timing** | "The promise rejects (or goroutine panics) after the response is already sent" |
+| **Silent side-effect** | "An earlier turn mutated shared state that the current turn inherits" |
+| **Observability gap** | "The error is raised but suppressed before logging; it only exists as an unawaited rejection / ignored signal" |
+| **Binary-level** (when applicable) | "The function we think is running is actually jumped over by a patched thunk / a different version loaded" |
+| **Build-vs-runtime** | "The code we're reading is not the code that's running — stale build, wrong symlink, cached wheel, or dist/ ahead of src/" |
+
+### For each hypothesis, write in the journal
+
+1. **Claim** — one sentence.
+2. **Distinguishing evidence** — the exact value or state that confirms or refutes it, AND where to read it (file:line, log source, breakpoint location, memory address).
+3. **If true, the fix is** — two words. Forces you to think through fix cost before committing to the hunt.
+
+### Collapse rule
+
+If two hypotheses have identical distinguishing evidence, they aren't actually different — collapse them and find a real alternative. If you can't come up with a third distinct hypothesis, you don't understand the system well enough yet. Go read a little more code before investigating.
+
+---
+
+## Phase 3 — Parallel Investigation
+
+Branch depending on what's available.
+
+### Path A: Team mode ENABLED
+
+When the `team_*` tools are present, create a **debug-squad** team and split investigation across members working on different evidence sources. This is the right default whenever you have ≥3 hypotheses and any of them would take >10 minutes to investigate single-threaded.
+
+**Team spec** — write to `~/.omo/teams/debug-squad/config.json`:
+
+```json
+{
+ "name": "debug-squad",
+ "lead": { "kind": "subagent_type", "subagent_type": "sisyphus" },
+ "members": [
+ {
+ "kind": "category",
+ "category": "deep",
+ "prompt": "You are the Runtime State Inspector. Your job: attach to the live process, hit breakpoints, read program state (variables, heap, goroutines, stack, registers depending on runtime), and report observed values verbatim. Never guess — if you don't see the value, say so. Report back via team_send_message with file:line / address references and captured values. Never edit source code. Never run git commands. If you need an instrumentation statement added (breakpoint(), debugger;, dbg!, etc.), ask the Lead first."
+ },
+ {
+ "kind": "category",
+ "category": "deep",
+ "prompt": "You are the Log Archaeologist. Your job: grep server logs, stderr streams, SDK-internal debug output (DEBUG env, RUST_LOG, GODEBUG, PYTHONASYNCIODEBUG), and correlate timestamps. Produce a timeline of events with latencies. Flag anything that looks like a silent catch, a swallowed rejection, a panic recovered-and-ignored, a success response that contains failure signals (HTTP 200 with empty body, stopReason=error, exit 0 with error-in-stdout). Never edit source code."
+ },
+ {
+ "kind": "category",
+ "category": "deep",
+ "prompt": "You are the Reproduction Engineer. Your job: build the smallest reliable repro — a curl command, a vitest/pytest/go test, a tmux script, a Playwright script for browser bugs, a pwntools script for binary targets. It must reproduce on first try and be copy-pasteable by the Lead. Document exact input, expected output, observed output. Save repro artifacts under /tmp/ and tell the Lead to journal them. If the bug is browser-based you MUST use Playwright CLI — do not simulate with curl."
+ },
+ {
+ "kind": "category",
+ "category": "deep",
+ "prompt": "You are the Trace Correlator. Your job: take findings from the other members and cross-link them. Build a causal chain from symptom to suspected cause. Identify missing evidence. Propose the next single most-decisive runtime query. Never edit source code; only reason across already-captured evidence. If hypotheses diverge sharply after correlation, tell the Lead immediately — that is the signal for the Oracle Triple."
+ }
+ ]
+}
+```
+
+**Assignment rule**: one hypothesis → one `team_task_create`. Give each hypothesis to the member whose evidence source is most likely to confirm or refute it. Broadcast the full hypothesis list once via `team_send_message(to="*")` so members know what the others are testing.
+
+**Lead responsibilities**:
+- Maintain the journal (members do not write to it).
+- Approve any source-code edits (including `debugger;` / `breakpoint()` / `dbg!` statements).
+- Synthesize member reports into updated hypothesis statuses.
+- Decide when to disband: `team_shutdown_request` → `team_approve_shutdown` → `team_delete`.
+
+**Team does NOT include Oracle** — Oracle is a hard-reject team member type. Oracle is used separately in Phase 4 (see `04-oracle-triple.md`).
+
+### Path B: Team mode DISABLED
+
+Fan out async explore/deep subagents instead. Same rule: one hypothesis per subagent.
+
+```
+task(subagent_type="explore", load_skills=[], run_in_background=true,
+ prompt="[CONTEXT: bug summary + which hypothesis you own + what state to look at]
+ Runtime state investigation for hypothesis 1: ...")
+task(subagent_type="explore", load_skills=[], run_in_background=true,
+ prompt="Log/timing investigation for hypothesis 2: ...")
+task(category="deep", load_skills=[], run_in_background=true,
+ prompt="Reproduction minimizer for hypothesis 3: ...")
+```
+
+End your response, wait for completion notifications, then synthesize.
+
+---
+
+## Evidence capture discipline (both paths)
+
+For every piece of runtime state captured, record in the journal:
+
+```markdown
+### <ISO timestamp> — <what you looked at>
+- Source: <file:line | log source | curl command | breakpoint address>
+- Value: `<verbatim>`
+- Interpretation: <one line — why this matters>
+- Refutes/Confirms: H<n>
+```
+
+**Verbatim values only. No paraphrasing.**
+
+- `messages.length=0` is evidence.
+- "messages seemed empty" is not evidence — it's a memory of an observation, and memory of observations is where debug sessions go to die.
+
+If you find yourself about to paraphrase, stop, go back, and copy the raw value.
+
+---
+
+## Round completion
+
+A "round" is complete when every hypothesis has either confirming or refuting evidence — or when you have exhausted the evidence sources available without a decisive result. If the round ends inconclusively, that counts as a failed round for the counter in the journal. See `04-oracle-triple.md` for what to do at 2 consecutive failed rounds.
diff --git a/plugins/omo/skills/debugging/references/methodology/04-oracle-triple.md b/plugins/omo/skills/debugging/references/methodology/04-oracle-triple.md
new file mode 100644
index 00000000..ec094813
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/methodology/04-oracle-triple.md
@@ -0,0 +1,136 @@
+# Phase 4 — Oracle Triple Consultation
+
+At 2 consecutive failed hypothesis rounds, stop investigating and reframe. Continuing past two failures usually means the real cause is in a category you haven't imagined — and more time on your current mental model is wasted time.
+
+The Oracle Triple is how you break out of the mental box.
+
+> ⚠️ **Wrong tool for non-debugging tasks.** The Triple is for *stuck root-cause hunts*. If your task is producing an artifact (extraction, reverse engineering, audit, compliance documentation) and you want a skeptical review before declaring it done, use the **Verification Oracle** pattern in [partial-runtime-evidence.md](partial-runtime-evidence.md#verification-oracle-pattern-for-non-debug-tasks). Running the Triple on a finished extraction returns three diverging "what if you tried…" tangents that are not what you need.
+
+---
+
+## When to invoke
+
+| Situation | Invoke? |
+|---|---|
+| 1 round failed, you have new distinguishing evidence | No — run one more round with a refined hypothesis set |
+| 2 rounds failed, hypotheses now feel like variations of each other | **Yes — invoke now** |
+| 2 rounds failed, no new evidence angles left to try | **Yes — invoke now** |
+| You've been investigating >2 hours on the same bug | **Yes — invoke now regardless of round count** |
+| 1 round failed but the user is watching and wants speed | No — one round isn't enough to justify Oracle cost. Resist the urge. |
+
+---
+
+## Why three Oracles, and why *orthogonal* framings
+
+A single Oracle call returns a single coherent analysis. Coherent analyses tend to inherit the framing of the prompt, which means they inherit the same blind spots the investigator already has. Three Oracles with *orthogonal framings* force the analyses to diverge, and the places where they agree across frames is where the real signal lives.
+
+The three framings below are chosen to cover distinct bug-cause categories:
+
+- **A (obvious-but-missed)** — embarrassingly simple causes the investigator walked past.
+- **B (system-boundary)** — causes living at integration seams, not in the code being read.
+- **C (invariant-violation)** — assumptions load-bearing to current hypotheses that may themselves be false.
+
+Spawn all three in parallel.
+
+---
+
+## The three prompts
+
+```
+task(subagent_type="oracle", load_skills=[], run_in_background=true,
+ prompt="[CONTEXT: bug description + evidence captured so far, verbatim, with file:line refs]
+
+ Framing A — OBVIOUS-BUT-MISSED.
+ What is the most embarrassing, most obvious cause that a senior engineer would spot in 30 seconds and we've overlooked? Consider:
+ - typos, off-by-one
+ - wrong variable name / wrong constant / wrong import
+ - stale cache, wrong file edited, wrong process inspected
+ - attached to the wrong instance of the service
+ - test harness running different code than the app
+ - editing src/ while running dist/
+
+ Give me exactly three candidate causes ranked by likelihood, with one sentence each explaining why our evidence is consistent with each.")
+
+task(subagent_type="oracle", load_skills=[], run_in_background=true,
+ prompt="[CONTEXT: bug description + evidence captured so far]
+
+ Framing B — SYSTEM-BOUNDARY.
+ What if the bug is NOT in the code we've been reading, but at a boundary? Consider:
+ - third-party SDK behavior that contradicts its docs
+ - middleware that mutates the request or response
+ - a proxy/gateway/load balancer that rewrites headers or bodies
+ - build-time vs runtime env-var resolution
+ - module-load-order issue
+ - shared-library version mismatch (system lib vs bundled lib)
+ - ABI difference (native addons, glibc versions, musl vs glibc)
+ - wrong transport (HTTP/1.1 vs HTTP/2, TLS version negotiation)
+
+ Give me three candidate causes, each naming the specific boundary and the specific contract assumption that might be violated.")
+
+task(subagent_type="oracle", load_skills=[], run_in_background=true,
+ prompt="[CONTEXT: bug description + evidence captured so far]
+
+ Framing C — INVARIANT-VIOLATION.
+ Which invariants that we've been ASSUMING TRUE might actually be false?
+ Enumerate the five assumptions most load-bearing to our current hypotheses, then for each:
+ - describe the smallest runtime query that would falsify it
+ - predict what the observable would be if the invariant holds vs if it fails
+
+ We want at least one of these queries to be decisive.")
+```
+
+---
+
+## Synthesizing across three Oracles
+
+**Do not pick the highest-ranked candidate from a single Oracle.** That defeats the purpose of getting three framings.
+
+Instead, walk the outputs in this order:
+
+### 1. Agreement scan
+
+Note which candidate causes appear in at least two Oracles' outputs. Independent agreement across orthogonal framings is strong signal — when the obvious-but-missed framing and the system-boundary framing both land on the same cause, that's usually the bug.
+
+### 2. Disagreement scan
+
+Note where Oracles disagree. Disagreement is genuine uncertainty that runtime evidence (not more reasoning) must resolve. Each disagreement becomes a candidate for the next round's distinguishing query.
+
+### 3. New falsification queries
+
+Framing C produces concrete "one query that would decide it" suggestions. Pull these verbatim into your new round's evidence-gathering plan — they are designed to be decisive.
+
+### 4. Build the new hypothesis set
+
+Minimum 3, same rules as Phase 2. Aim to have hypotheses drawn from the agreement scan (likely cause) AND from the disagreement scan (so one round's evidence resolves the disagreement).
+
+Record in the journal:
+
+```markdown
+## Oracle Triple — Round <N>
+- Invoked at: <ISO timestamp>
+- Framing A summary: <top 3 candidates, one line each>
+- Framing B summary: <top 3 candidates>
+- Framing C summary: <5 load-bearing assumptions + falsification queries>
+
+### Cross-framing agreement
+- <candidate> appeared in A + B
+- <candidate> appeared in B + C
+
+### New hypothesis set
+1. <hypothesis> — evidence to gather: <one-liner>
+2. ...
+```
+
+### 5. Reset the counter
+
+Reset the "consecutive failed rounds" counter to 0. Return to Phase 3 (parallel investigation) with the new set.
+
+---
+
+## If *another* 2 rounds fail after the Oracle Triple
+
+You are genuinely stuck. This is the escalation threshold.
+
+Escalate to the user (see `05-escalate.md`) with the full trace: every hypothesis tried, every piece of evidence captured, both Oracle syntheses. Do not guess a fix.
+
+This is rare — in practice, the Oracle Triple resolves almost all stuck debugging sessions within one round, because it pulls in framings the investigator was too close to the code to see.
diff --git a/plugins/omo/skills/debugging/references/methodology/05-escalate.md b/plugins/omo/skills/debugging/references/methodology/05-escalate.md
new file mode 100644
index 00000000..187e9a95
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/methodology/05-escalate.md
@@ -0,0 +1,69 @@
+# Phase 5 — User Decision Escalation
+
+Escalation is for genuine ambiguity, not for skipping investigation. Most "should I ask the user" moments are really "I don't want to do one more query" moments, and those are wrong.
+
+---
+
+## Ask the user ONLY when
+
+- **Evidence exhausted**, contradictions remain, and further investigation would require a decision with policy implications (e.g. "patch the third-party SDK vs wrap it vs change architecture").
+- The bug has **multiple valid fixes with different scope/risk tradeoffs** and the user's preference drives the choice.
+- A proposed fix would **change observable product behavior** for the end user (not just fix the internal bug).
+- You've **exhausted the Oracle Triple** and another 2 rounds failed after synthesis.
+
+## Do NOT ask when
+
+- You haven't tried the Oracle Triple yet.
+- The question can be answered by one more runtime query.
+- You're asking for permission to do the obvious thing.
+- You're asking because you're tired.
+
+---
+
+## Escalation format (paste into the reply)
+
+Keep it short. Evidence-dense. One decision, not a status update.
+
+```markdown
+## Decision needed
+
+**What we know** (verbatim evidence, not paraphrase):
+- <fact 1 with file:line or address>
+- <fact 2 with source>
+- <what the evidence rules IN>
+- <what the evidence rules OUT>
+
+**What the decision is** (one sentence):
+<the fork in the road>
+
+**Options**:
+
+| # | Fix | Scope | Risk | Effort |
+|---|-----|-------|------|--------|
+| A | <short label> | <files touched / layers> | <regressions possible> | <rough> |
+| B | ... | ... | ... | ... |
+| C | ... | ... | ... | ... |
+
+**Recommendation**: <A/B/C> because <one-sentence reason>.
+
+Which direction do you want?
+```
+
+---
+
+## Anti-patterns in escalation
+
+- **Asking without evidence.** "What do you want me to do?" is not an escalation, it's abandonment. Every escalation includes the evidence the user needs to decide.
+- **Two questions in one.** One decision per escalation. Multi-part questions lead to partial answers and re-escalation.
+- **Escalating before Phase 4.** If you haven't tried the Oracle Triple, you haven't earned the right to escalate.
+- **Presenting options you don't actually have.** If option C requires a library the user doesn't use, don't list it. The options are only things you can actually do today.
+- **Hiding a recommendation.** The user hired you to think — always end with a recommendation, even if you're low-confidence. Say so explicitly: "Recommendation (low confidence): B, because X. If you have context about Y that I don't, it might change to A."
+
+---
+
+## What happens after the user responds
+
+- **User picks an option**: return to Phase 6 (root cause confirmation) with the chosen direction. The user's choice is not itself confirmation — you still need runtime evidence that the cause you're fixing is the cause in play.
+- **User proposes a different option you hadn't considered**: treat it as new information. Update hypotheses. May trigger another Phase 3 round.
+- **User gives more context that resolves the disagreement**: skip to Phase 6.
+- **User is also unsure**: that's a signal you need more evidence, not more opinions. Run one more targeted query before asking again.
diff --git a/plugins/omo/skills/debugging/references/methodology/06-fix.md b/plugins/omo/skills/debugging/references/methodology/06-fix.md
new file mode 100644
index 00000000..70e36da8
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/methodology/06-fix.md
@@ -0,0 +1,116 @@
+# Phase 6 + 7 — Root Cause Confirmation & TDD Fix
+
+A cause is not "confirmed" until you can toggle the bug by toggling the cause. Every other level of evidence is correlation, and correlation-driven fixes ship bugs.
+
+---
+
+## Phase 6 — Root Cause Confirmation
+
+You are allowed to call the cause "confirmed" only when ALL THREE of these hold:
+
+### 1. Captured runtime value matches the hypothesis exactly
+
+Not "the value looks consistent with" — the value is exactly the value the hypothesis predicted. If your hypothesis was "baseUrl is api.anthropic.com despite ANTHROPIC_BASE_URL being set to a proxy", the captured value is literally `"https://api.anthropic.com"` in the debugger at the moment of the HTTP call.
+
+### 2. Reproducible
+
+Running the repro a second time yields the same observation. Flaky repros mean you haven't isolated the cause; you've isolated a symptom that sometimes appears when the cause does. Keep investigating.
+
+### 3. Toggle proof (the one most skipped)
+
+**Changing the value** (via debugger assignment, env override, or a speculative one-line patch) **makes the bug disappear — and reverting brings the bug back**.
+
+If you can't toggle the bug by toggling the suspected cause, what you have is a correlation, not a mechanism. A correlation is a strong hypothesis, not a confirmed cause.
+
+Examples of a valid toggle proof:
+
+| Suspected cause | Toggle |
+|---|---|
+| Env var overrides library default, and the override is wrong | Unset the env var → bug goes away. Reset it → bug comes back. |
+| Async task is not awaited | Add `await` → bug goes away. Remove `await` → bug comes back. |
+| Third-party SDK uses hardcoded URL | Monkey-patch SDK to use env URL → bug goes away. Unpatch → bug comes back. |
+| Race condition on shared state | Add a mutex → bug goes away under load. Remove mutex → bug comes back under load. |
+
+If you can't construct a toggle proof, you haven't confirmed the cause. Run one more round.
+
+### Update the journal
+
+```markdown
+## Root cause (confirmed <ISO timestamp>)
+- Mechanism: <one paragraph, causal not correlational — the chain from cause to observable symptom>
+- Evidence: <file:line of captured value | path to saved repro | address + register state>
+- Toggle proof: "With <change X>, repro produces <good>. Reverting <change X>, repro produces <bad>."
+- Fix scope: <files and approximate line count>
+```
+
+The "mechanism" field is the acid test. If you can't write the causal chain from cause to observable symptom as one paragraph, you don't yet understand the bug well enough to fix it.
+
+---
+
+## Phase 7 — TDD Fix
+
+Red, green, refactor. No shortcuts.
+
+### 1. Red — failing-first test
+
+Write a test that fails *specifically because of this bug*. Requirements:
+
+- **Test name reads like a bug report.** `test_refinement_turn_returns_empty_content_when_anthropic_returns_401` is good. `test_bug_fix` is not.
+- **Failure message clearly shows what the bug looks like.** If someone reads only the failure output, they understand what's broken.
+- **Minimum infrastructure.** Don't spin up the whole server if a unit test against the right seam captures the mechanism.
+
+Run the test. Confirm it fails. Paste the failure output into the journal:
+
+```markdown
+### Red phase (<ISO timestamp>)
+Test: <path>::<name>
+Command: <exact invocation>
+Output:
+```
+<verbatim failure output>
+```
+Confirms: the bug is reproducible at the test-harness level, not just the manual repro.
+```
+
+### 2. Green — minimum change
+
+Make the test pass with the **smallest change that fully fixes the observed mechanism**.
+
+If the diff is larger than ~30 lines and you aren't refactoring, something is wrong — either you're fixing more than the bug, or the root cause was deeper than you confirmed. Back to Phase 6.
+
+Signs you're over-fixing:
+- Adding "just in case" null checks or try/except around other code
+- Refactoring adjacent functions because "while I'm here"
+- Adding new configuration options the bug didn't require
+- Introducing new abstractions to "make this cleaner"
+
+Resist all of these. Fix the bug. Note the surrounding issues for follow-up. Move on.
+
+### 3. Refactor — ONLY AFTER GREEN
+
+Only cleanup directly related to the fix. Do not re-architect.
+
+If the code around the fix is rough, note it in the journal as a follow-up for the user; do not expand scope here. Refactoring during a bugfix is how one-line fixes turn into hundred-line diffs nobody can review.
+
+### 4. Regression — full suite green
+
+Run the full test suite for the affected package (not just the one new test). Existing tests must still pass.
+
+If they don't, your "fix" broke something else. Back to Phase 6 with the new failure as evidence — usually it means the mechanism you thought you fixed was load-bearing for some other code path you didn't know about, and the "broken" test is actually pointing at a better understanding of the system.
+
+### Update the journal
+
+```markdown
+### Green phase (<ISO timestamp>)
+Fix: <file:line> — <two-line description of the change>
+Test: <path>::<name> now passes
+Full suite: <N tests, <M failures — should be 0>
+```
+
+---
+
+## The red-green discipline summary
+
+No red test → no proof the fix addresses the reported bug. Only proof it doesn't break tests that already existed.
+
+A test written *after* the fix might still pass with the fix reverted. If that's the case, the test doesn't lock the bug — it locks something else. Always verify the test fails without the fix and passes with it. The journal should show both outputs.
diff --git a/plugins/omo/skills/debugging/references/methodology/08-qa.md b/plugins/omo/skills/debugging/references/methodology/08-qa.md
new file mode 100644
index 00000000..d900e40e
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/methodology/08-qa.md
@@ -0,0 +1,94 @@
+# Phase 8 — Manual QA by Actually Using It
+
+Tests cover cases you thought of. Real usage covers the ones you didn't.
+
+The single fastest way to ship a broken fix is to stop at "tests pass". Manual QA means interacting with the running system the way the user does, then comparing observed behavior to the original bug report.
+
+---
+
+## Product-type playbook
+
+Pick the row that matches the product. Do what it says. Do not substitute.
+
+| Product type | QA means… |
+|---|---|
+| **CLI tool** | Open `tmux`, run the actual command end-to-end, capture output. Paste the session transcript into the journal. Include exit code, stdout, stderr, side-effect check (files created/modified). |
+| **HTTP API** | Start the real server, hit endpoints with `curl` or `httpie`, inspect response status + body + headers. Hit the specific endpoint that reproduced the bug. If there's auth, use real auth. |
+| **Browser-served web app** | **Drive a real browser via Playwright CLI.** See [tools/playwright-cli.md](../tools/playwright-cli.md). Navigate the exact page/flow that reproduced the bug. Capture screenshot + DOM + network evidence. **Do not substitute with curl** — browsers have state (cookies, localStorage, service workers, client-side JS, viewport-dependent CSS) that curl does not have. |
+| **Agent / LLM pipeline** | Run the same user prompt that originally failed. Capture the full turn — tool calls, messages, usage counters. **Confirm non-zero usage** (zero usage = still failing silently, see silent-failure check below). |
+| **Background worker / job queue** | Trigger the job through the normal entry point (API call, cron tick, message publish), tail the worker logs, observe completion state in the queue or DB. Don't just call the worker function directly — the trigger path matters. |
+| **MCP server** | Invoke the tool via its actual client (Claude Desktop, Cursor, etc. if available) or `mcp-cli`, not just the HTTP probe endpoint. The MCP handshake itself is sometimes where bugs live. |
+| **Native binary** | Re-run the exact command that crashed / misbehaved. If the input was a file, use the same file. If the bug was exploitable, confirm the exploit repro via pwntools (see [tools/pwntools.md](../tools/pwntools.md)). Capture exit code, signal if any, core dump if generated. |
+| **Bundled-app binary** (Bun SEA, Node SEA, Electron, etc.) | Re-run the exact command. If the operation requires paid quota / blocked network, capture the **app's debug log** (`APP_DEBUG=1 APP_LOG_LEVEL=debug APP_LOG_FILE=/tmp/trace.log`) which usually emits the assembled request before sending. See [methodology/partial-runtime-evidence.md](partial-runtime-evidence.md) for combining partial signals into a defensible verification. |
+| **Long-running daemon** | Start fresh, let it run for the amount of time the bug originally took to manifest (not less), capture resource usage (memory, fd, cpu) throughout. Short-running QA misses resource leaks and cumulative state bugs. |
+
+---
+
+## Journal format
+
+Every QA run goes in the journal under "Findings":
+
+```markdown
+### Manual QA — <product type> (<ISO timestamp>)
+- Scenario: <one line describing what you did>
+- Command: `<exact invocation>`
+- Observed output:
+```
+<verbatim output, trimmed to relevant section>
+```
+- Expected output: <what correct behavior looks like>
+- Fix verified: yes / no / partial — <details>
+```
+
+If any QA step shows **partial or regressed behavior**, this is not "mostly done" — it's incomplete. Return to Phase 6.
+
+---
+
+## The silent-failure check (always run)
+
+Regardless of product type, audit the fix against these silent-failure patterns. If the original bug was a silent failure, the same pattern may exist in adjacent code that you haven't tested yet.
+
+### Universal silent-failure signals
+
+- HTTP 2xx with empty or default body
+- Response `ok: true` but a sub-field contains an error token (e.g. `stopReason: "error"`, `status: "failed"`)
+- `usage.totalTokens === 0` on an LLM response
+- Process exit code 0 but stderr contains an exception traceback
+- Panic recovered and logged but ignored
+- Goroutine / task / promise rejection with no top-level handler
+- `try { ... } catch { /* swallowed */ }` or `except: pass`
+- Success response shape but semantic field indicates failure (e.g. `error: null` actually being `error: "..."` with falsy check)
+- Write returned success but read-back shows stale data
+- Job marked complete but side-effect did not happen
+- Cache hit path returned stale data and no refresh was triggered
+
+### Language-specific silent-failure signals
+
+Check the runtime reference for additional patterns:
+
+- [runtimes/python.md](../runtimes/python.md) — asyncio task exceptions, bare `except`, `logging.exception` that goes nowhere
+- [runtimes/node.md](../runtimes/node.md) — unhandled promise rejections, `void` on async, swallowed `.catch(() => {})`
+- [runtimes/rust.md](../runtimes/rust.md) — `.unwrap_or_default()`, `let _ = result`, error variants discarded
+- [runtimes/go.md](../runtimes/go.md) — `if err != nil { return err }` that never reaches user output, recovered panics, buffered channels that block silently
+- [runtimes/native-binary.md](../runtimes/native-binary.md) — ignored return codes from libc, missing `perror`, `alarm()` / signal masks
+- [runtimes/bundled-js-binary.md](../runtimes/bundled-js-binary.md) — `process.env.X` baked at build time, dead code from tree-shaking failures, worker sub-bundles diverging from main bundle
+
+### What to do when you find another silent-failure spot
+
+Don't fix it. This is out of scope for the current bug.
+
+Note it in the journal under a "Follow-ups" section with:
+- File:line
+- Pattern matched
+- Proposed fix sketch (one line)
+- Risk level (what happens if left unfixed)
+
+Surface these to the user in the final message under "Next steps I didn't take".
+
+---
+
+## The "fix verified" bar
+
+"Fix verified" means: the exact original failing scenario, re-run, now produces the correct output. Not a similar scenario. Not a unit test of the fix. The original scenario.
+
+If you can't re-run the original scenario (e.g. it required a specific data state that's gone), construct the closest equivalent and document the difference in the journal. Escalate to the user if the equivalent is materially different.
diff --git a/plugins/omo/skills/debugging/references/methodology/09-cleanup.md b/plugins/omo/skills/debugging/references/methodology/09-cleanup.md
new file mode 100644
index 00000000..ab87f1c8
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/methodology/09-cleanup.md
@@ -0,0 +1,164 @@
+# Phase 9 + 10 — Cleanup & Final Verification
+
+The working tree after the session must differ from before only by the real fix and its test. Anything else is a process failure.
+
+---
+
+## Phase 9 — Cleanup & Revert
+
+### The walk
+
+Open the journal's "Artifacts to revert" list. Walk it top to bottom. Check each box only after the revert command succeeds and produces no error.
+
+### Standard revert operations
+
+Most sessions create some combination of these artifacts. The commands below are the defaults — your journal should have the exact commands for this session.
+
+```bash
+# --- Temporary source edits (instrumentation statements, debug prints) ---
+git checkout <file> # reverts only that file
+git diff <file> # verify clean
+
+# --- tmux sessions ---
+tmux kill-session -t <session-name>
+tmux ls # confirm gone
+
+# --- Temp fixtures / scratch scripts ---
+rm -f /tmp/debug-*.*
+ls /tmp/debug-*.* 2>/dev/null # confirm gone (ls returns non-zero when no match)
+
+# --- Background processes (debugger-attached runtimes) ---
+pkill -f 'node --inspect' || true
+pkill -f 'python -m pdb' || true
+pkill -f 'debugpy' || true
+pkill -f 'dlv' || true
+pkill -f 'gdb' || true
+pkill -f 'lldb' || true
+
+# --- Debug-relevant ports confirmed free ---
+lsof -iTCP:9229 -sTCP:LISTEN -nP 2>/dev/null # Node inspector default
+lsof -iTCP:5678 -sTCP:LISTEN -nP 2>/dev/null # debugpy default
+lsof -iTCP:2345 -sTCP:LISTEN -nP 2>/dev/null # dlv default
+lsof -iTCP:9999 -sTCP:LISTEN -nP 2>/dev/null # pwndbg/gdb-server default
+
+# --- Env var overrides in current shell ---
+unset DEBUG_OVERRIDE_FOO
+unset PYTHONBREAKPOINT
+unset RUST_LOG
+unset DEBUG
+
+# --- Ghidra scratch projects (if created just for this session) ---
+# rm -rf ~/ghidra-projects/debug-scratch
+
+# --- Core dumps from debugging (if any) ---
+rm -f ./core ./core.* ~/core.*
+
+# --- Playwright trace files ---
+rm -rf playwright-report/ test-results/
+```
+
+### The verify command
+
+This is the single most important check of the whole skill:
+
+```bash
+git status
+git diff --stat
+```
+
+The diff must contain **only**:
+
+1. The real fix.
+2. The new failing-first test.
+3. Nothing else.
+
+### Detector checklist — scan the diff for these
+
+If `git status` shows any untracked debug file, or `git diff` shows any of the patterns below, **you are not done**. Clean it.
+
+| Pattern | Usually means |
+|---|---|
+| `debugger;` | Node debug statement left behind |
+| `breakpoint()` | Python debug statement left behind |
+| `dbg!(...)` | Rust debug macro left behind |
+| `fmt.Println("DEBUG: ...")` | Go ad-hoc print |
+| `console.log("[DEBUG]` | Node ad-hoc log |
+| `print(f"DEBUG: ` | Python ad-hoc print |
+| `// TODO DEBUG`, `// HACK`, `// XXX` | Stale debug marker |
+| `// <PROJECT>-DEBUG` | Session-specific marker from this skill's edits |
+| Commented-out code blocks near the fix | Dead code from trial fixes |
+| Reordered imports or formatting in unrelated files | Drift from your editor's autoformat during the session |
+
+### Remove the journal
+
+Only once the git check is clean:
+
+```bash
+rm .debug-journal.md
+sed -i.bak '/^\.debug-journal\.md$/d' .git/info/exclude && rm -f .git/info/exclude.bak
+```
+
+The journal is not part of the fix; it doesn't belong in the commit or in the git exclude list.
+
+---
+
+## Phase 10 — Final Verification
+
+Last gate before reporting done. All four gates must be true, and all four must have **evidence in your final message** to the user. Passing a gate without evidence is the same as failing it.
+
+### The four gates
+
+1. **Red→green toggle confirmed** — show the failing test output from before the fix and passing output after. Both outputs visible in the reply or the journal.
+
+2. **Full test suite green** — show the suite's final pass line (e.g. `42 passed in 3.14s`). Not just the new test.
+
+3. **Manual QA reproduced the fix** — show the command or scenario that originally failed and its now-correct output. Verbatim, not paraphrased.
+
+4. **Working tree clean of debug artifacts** — show `git diff --stat` output containing only fix + test, plus `git status` clean of untracked debug files.
+
+If any of the four lacks evidence, you have not finished — return to the appropriate phase.
+
+### Final message template
+
+Keep it short. Evidence-dense. The user should be able to skim it in 30 seconds.
+
+```markdown
+Fixed.
+
+**Root cause**: <one sentence — the mechanism, not the symptom>
+**Fix**: `<file:line>` — <two words>
+**Test**: `<test file>::<test name>` — red without fix, green with fix
+**QA**: <one line describing what you ran and what you saw>
+
+Diff:
+```
+<git diff --stat output — should be tiny>
+```
+
+**Next steps I didn't take** (awaiting your decision):
+- <follow-up 1, if any — from QA silent-failure scan or refactor opportunities noted during Phase 7>
+- <follow-up 2 — or "none" if nothing else surfaced>
+```
+
+### Example (from a real session)
+
+```markdown
+Fixed.
+
+**Root cause**: pi-mono Agent's `model.baseUrl` was hardcoded to `api.anthropic.com`, so the `ANTHROPIC_BASE_URL` env var was silently ignored. The proxy API key was rejected by the real Anthropic API with 401, but pi-mono packaged the error into the assistant message's `errorMessage` field instead of throwing, so the route's try/catch never fired and the client received HTTP 200 with empty content.
+
+**Fix**: `core/pi-bridge/modelResolver.ts:117` — override baseUrl
+**Test**: `__tests__/core/modelResolver.test.ts::resolves_env_override` — red without fix, green with fix
+**QA**: `curl -X POST /api/refinement/chat` with proxy env set, observed non-zero usage and non-empty content
+
+Diff:
+```
+ core/pi-bridge/modelResolver.ts | 3 +++
+ __tests__/core/modelResolver.test.ts | 42 ++++++++++++++++++++++
+ 2 files changed, 45 insertions(+)
+```
+
+**Next steps I didn't take** (awaiting your decision):
+- pi-mono itself silently swallows LLM errors into `errorMessage`; adding a throw-on-error wrapper at our orchestrator layer would surface these upstream
+- Same silent-failure pattern exists in the planning route — likely the same fix applies
+```
diff --git a/plugins/omo/skills/debugging/references/methodology/partial-runtime-evidence.md b/plugins/omo/skills/debugging/references/methodology/partial-runtime-evidence.md
new file mode 100644
index 00000000..986a3220
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/methodology/partial-runtime-evidence.md
@@ -0,0 +1,229 @@
+# Partial Runtime Evidence — When You Cannot Execute the Real Operation
+
+Read this when **runtime truth beats code reading** is in conflict with **you cannot run the actual operation**.
+
+The skill's first invariant is "runtime state is the only source of truth." But sometimes the only state you can produce is a *partial* observation — the real call requires paid credits, a hardware device you don't have, network access through a corporate proxy, a production secret, or a customer dataset.
+
+**Partial runtime evidence is still runtime evidence.** This reference tells you which partial signals to harvest and how to combine them so the conclusion is defensible.
+
+---
+
+## When this applies
+
+Use this reference when ALL are true:
+
+1. The bug or extraction question requires runtime confirmation (per skill invariant #1).
+2. You attempted the obvious "just run it" path and it failed for reasons unrelated to the bug:
+ - 401/402/403 from a paid API
+ - "device not found" / "permission denied" / SIP block
+ - Production-only credentials
+ - Network isolation (air-gapped, behind VPN you don't have)
+ - Time-of-day or quota limits
+3. **Mocking the entire system** would defeat the verification — you specifically need evidence about how the *real* code behaves, not a stub.
+
+If only #1 and #2 are true and you can mock cleanly, just mock and proceed. This file is for cases where mocking would invalidate the answer.
+
+---
+
+## The hierarchy of partial evidence (strongest first)
+
+When you cannot capture the full outbound payload + full response, capture as much as possible from this list. **Evidence further down the list has more inference; evidence higher up is closer to ground truth.**
+
+### Tier 1 — Pre-send / post-receive logs (best partial evidence)
+
+The system you're investigating builds a request, then sends it. If the build step logs the assembled request **before** transmission, that log is ground truth for everything except the wire-level bytes (TLS, headers added by HTTP library, etc.).
+
+```bash
+# Maximize debug logging
+APP_DEBUG=1 APP_LOG_LEVEL=debug APP_LOG_FILE=/tmp/trace.log ./target -x "minimal valid input" 2>&1 | head -200
+```
+
+Look for log lines like:
+- `Building request: model=X, params={...}`
+- `[provider] payload: {...}`
+- `Sending to <url>: <serialized body>`
+
+**Strength**: 95% of ground truth. Missing only wire-level transformations.
+
+### Tier 2 — Local interception via proxy / shim
+
+Run the real binary against a local proxy that records and (optionally) returns a canned response.
+
+```bash
+# mitmproxy approach
+mitmproxy --listen-host 127.0.0.1 --listen-port 8888 --mode regular &
+HTTPS_PROXY=http://127.0.0.1:8888 SSL_CERT_FILE=~/.mitmproxy/mitmproxy-ca-cert.pem ./target ...
+# Now mitmproxy logs the actual TLS-decrypted request
+```
+
+```bash
+# DYLD_INSERT_LIBRARIES / LD_PRELOAD shim approach
+# Wrap the network call to log payload, return a fake 200
+# See pwntools.md for shim examples
+```
+
+**Strength**: Wire-level ground truth, but requires the target to honor your proxy / preload.
+
+### Tier 3 — Static extraction × runtime fingerprint cross-check
+
+When you cannot send a request at all, you can still cross-check static analysis with whatever the binary does that *doesn't* require the real call:
+
+- The binary builds the request — even if sending fails, the build step ran. Trace it (Tier 1).
+- The binary writes a state file or cache — read it.
+- The binary emits version-specific User-Agent strings; verify they match your static extraction.
+- The binary's `--help` or `--version` output reveals build metadata; verify model lists / feature flags.
+
+**Strength**: Disjoint evidence sources confirming the same fact. Two independent partial signals that agree are nearly as strong as one full observation.
+
+### Tier 4 — Contrastive runtime under different inputs
+
+If you can run with input variant A but not B, run A and reason about B from code:
+
+```bash
+# A: minimal trial input — works for free tier
+./target --action=read --resource=local-file
+# B: full inference call — paid tier required, blocked
+# But the request-building code is shared between A and B!
+# Capture A's logs, then inspect the code path for B and verify only the model/endpoint diff.
+```
+
+**Strength**: Confirms shared code paths; remaining gap is only the difference between A and B.
+
+### Tier 5 — Vendor-published API logs / dashboard
+
+If the operation succeeded earlier (before quota ran out, before access was revoked), the vendor's dashboard / audit log may show the request. Lower fidelity but still observed behavior.
+
+**Strength**: Real wire data, but often summarized — token counts, status codes, no payload bodies.
+
+### Tier 6 — Pure code reading with peer review
+
+If literally none of the above is available, read the code carefully and submit it to **one Oracle for skeptical review** (see "Verification Oracle" below). This is the weakest tier and you must explicitly mark conclusions as "unverified" in the journal.
+
+---
+
+## How to combine partial signals
+
+A defensible conclusion **prefers two independent signals from different tiers**, with one exception: a complete Tier 2 wire-level capture is wire-level ground truth and can stand alone for request-shape claims (because the wire bytes are exactly what the remote received). For *behavioral* claims (what the system does next, what state it stores, what side effects it produces), still combine with another signal.
+
+| Available evidence | Defensibility |
+|---|---|
+| Tier 1 + Tier 1 (same log, different lines) | weak — single source |
+| Tier 1 + Tier 2 (debug log + proxy capture) | **strong** — independent confirmation |
+| Tier 1 + Tier 3 (debug log + version output cross-check) | **strong** — disjoint sources |
+| Tier 2 alone (full proxy capture) | strong **for request-shape claims only** — stands alone for "what bytes were sent". Add a second signal for response-handling or state claims. |
+| Tier 3 + Tier 4 (cross-check + contrastive run) | medium — both partial |
+| Tier 6 alone (code reading only) | **insufficient** — escalate or mark unverified |
+
+Record in the journal:
+
+```markdown
+## Partial runtime evidence
+### Question being verified
+<the specific claim, e.g. "Opus 4.7 default effort is 'high'">
+
+### Available signals
+- Tier 1: debug log /tmp/trace.log line 47-49 shows `effort: "high"` ✓
+- Tier 3: static extraction of m5T() function returns "high" for smart mode ✓
+- Tier 6: code path verified by reading prompt-builder.js ✓
+
+### Independence assessment
+Tier 1 and Tier 3 are independent — the log was emitted by a different
+code path than m5T() and would diverge if the static reading were wrong.
+
+### Conclusion
+VERIFIED via Tier 1 + Tier 3 agreement. No need to escalate.
+```
+
+If you cannot achieve a complete Tier 2 capture **or** two independent non-Tier-6 signals from the table above, **write an explicit note in the deliverable**:
+
+> ⚠️ Partial-evidence finding. The full outbound payload could not be captured because [reason]. The conclusion rests on:
+> - [signal A — tier and source]
+> - [signal B — tier and source]
+> A future verification should attempt [the missing tier] when [condition].
+
+---
+
+## Verification Oracle pattern (for non-debug tasks)
+
+The skill's main Oracle Triple (`04-oracle-triple.md`) is for **stuck debugging** — 2 failed rounds, mental box, three orthogonal framings to break out.
+
+For tasks where the deliverable is an **artifact, not a bug fix** (reverse engineering, extraction, audit, compliance documentation), use a different pattern: **single Oracle, late, skeptical, with the deliverable in hand**.
+
+### When to invoke
+
+- Right before declaring an extraction/audit task "done"
+- After every significant revision of the deliverable (not after every small edit)
+- Maximum 3-4 iterations before escalating to user
+
+### Pattern
+
+```
+task(subagent_type="oracle", load_skills=[], run_in_background=false,
+ prompt="""
+SKEPTICAL FINAL VERIFICATION — be critical, look for reasons the task is incomplete or wrong.
+
+## Original task
+<verbatim user request>
+
+## What I produced
+<list of artifacts with paths and brief descriptions>
+
+## Specific claims to verify
+<bullet list of every concrete claim in the deliverable>
+
+## Where to look
+<paths the Oracle should Read / Bash to verify>
+
+## Your job
+1. Read the deliverables.
+2. Spot-check each claim against the source/evidence the deliverable cites.
+3. Identify any unsubstantiated claims, missing pieces, or factual errors.
+4. End with PASS / FAIL / PARTIAL with specific gaps.
+Be skeptical. Don't rubber-stamp.
+""")
+```
+
+### Why this differs from the Oracle Triple
+
+| | Oracle Triple (debug) | Verification Oracle (artifact) |
+|---|---|---|
+| Trigger | 2 failed hypothesis rounds | About to declare "done" |
+| Count | 3 in parallel, orthogonal framings | 1 sequential, focused review |
+| Goal | Break out of mental box | Catch unsubstantiated claims |
+| Tone of prompt | Brainstorm wide alternatives | Skeptical audit |
+| Iteration | Reset hypothesis set after | Fix gaps, re-invoke until PASS |
+
+### Don't conflate them
+
+If you're stuck debugging, do the Triple. If you have a deliverable and need it audited, do the Verification Oracle. Doing the Triple on a finished extraction will return three diverging "what if you tried…" tangents that are not what you need. Doing the Verification Oracle on a stuck debugging session will return a polite "the evidence is incomplete" that you already knew.
+
+---
+
+## Common partial-evidence anti-patterns
+
+| Anti-pattern | Why it fails | Replacement |
+|---|---|---|
+| "It looks right in the code, so it works" | Tier 6 alone, unverified | Add at least one Tier 1-3 signal |
+| "I ran it once, didn't error, so it's correct" | Absence of error ≠ presence of correctness | Capture the actual output and verify content |
+| "The mock returns the value I wrote, so the code is fine" | Tautology — mock loops back your assumption | Use Tier 2 (proxy) instead, or cross-check with Tier 3 |
+| "The vendor's dashboard shows my call worked" | Dashboard often only shows status code, not behavior | Combine with Tier 1 if available |
+| "I'll trust the most-recent stack overflow answer" | Code from a different version / context | Verify against the actual binary you have |
+
+---
+
+## Cleanup additions for partial-evidence work
+
+```bash
+# Proxy artifacts
+pkill -f mitmproxy 2>/dev/null
+rm -f ~/.mitmproxy/cache_* 2>/dev/null
+
+# Debug log files
+rm -f /tmp/trace.log /tmp/*-debug-trace.log
+
+# DYLD_INSERT / LD_PRELOAD shim libraries
+rm -f /tmp/*.dylib /tmp/*.so
+
+# Verify env vars set in your shell are not persisted
+unset HTTPS_PROXY APP_DEBUG APP_LOG_LEVEL APP_LOG_FILE 2>/dev/null
+```
diff --git a/plugins/omo/skills/debugging/references/runtimes/bundled-js-binary.md b/plugins/omo/skills/debugging/references/runtimes/bundled-js-binary.md
new file mode 100644
index 00000000..a64c8073
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/runtimes/bundled-js-binary.md
@@ -0,0 +1,415 @@
+# Bundled-JS / Embedded-Source Binaries (Bun SEA, Node SEA, Deno compile, pkg, Electron, PyInstaller)
+
+A growing class of "binaries" are not stripped C/C++ at all — they are a runtime VM glued onto a high-level-language bundle. The bundle is **plaintext or trivially-decodable** inside the binary.
+
+If you reach for `native-binary.md` workflow on these (Ghidra → pwndbg → hex), you will waste hours decompiling a runtime you don't care about while the actual logic sits exposed three megabytes away.
+
+**This reference exists because the workflow is fundamentally different from stripped C.**
+
+---
+
+## When to use this reference instead of `native-binary.md`
+
+Open this if `file ./target` shows a generic Mach-O / ELF / PE BUT any of:
+
+- Size is suspiciously large (50 MB+ for a "simple CLI")
+- `strings -n 8 ./target | rg -i "node_modules|webpack|esbuild|bun|pkg/lib|electron|pyinstaller"` returns hits
+- The binary's CLI flags include things like `--inspect`, `--unhandled-rejections`, npm-style help text
+- Vendor docs say it's built with Bun / pkg / nexe / Deno compile / PyInstaller / Electron / Tauri (UI shell)
+- `head -c 4 ./target | xxd` shows a known runtime magic for an embedded archive section
+
+If yes → **stop following `native-binary.md` and follow this**. Triage and dynamic tracing are the same. Static analysis is completely different.
+
+---
+
+## The workflow
+
+```
+ [1] Triage → identify the bundler (Bun? pkg? Deno? Electron? PyInstaller?)
+ [2] Locate the bundle → find where the embedded source archive starts
+ [3] Extract → dump source to disk so you can grep / read it
+ [4] Source-level static analysis (rg + Read, NOT Ghidra)
+ [5] Runtime verification → debug logs, --inspect, partial-evidence patterns
+ [6] Fix / report
+```
+
+Step 3 is the unlock — once you have plaintext source on disk, the rest is normal codebase exploration.
+
+---
+
+## [1] Identify the bundler — 30-second fingerprint
+
+```bash
+# Look for runtime-specific markers in plaintext strings
+strings -n 12 ./target 2>/dev/null | rg -iE 'bun|node_modules|webpack|esbuild|deno|pkg/lib|electron|pyinstaller|nexe|NODE_SEA_FUSE|NODE_SEA_BLOB|tauri|ESZIP_V2|denort' | head -20
+```
+
+| Marker pattern | Bundler | Source format |
+|---|---|---|
+| `@oven/bun-darwin`, `bun-lockfile-format-v`, `// @bun` | **Bun SEA** (compiled via `bun build --compile`) | Plaintext JS, single big bundle |
+| `NODE_SEA_BLOB` + `NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2:1` | **Node SEA** (`node --build-sea` or `--experimental-sea-config`) | Plaintext JS, or V8 code cache (when `useCodeCache: true`), or startup snapshot (when `useSnapshot: true`) — the latter two are NOT plaintext |
+| `pkg/lib/bootstrap.js`, `pkg/prelude`, `PAYLOAD_POSITION` | **pkg** (vercel/pkg) | Plaintext or v8 cached data |
+| `ESZIP_V2`, `denort`, `deno_runtime` | **Deno compile** (`deno compile`) | TS/JS in eszip archive — readable but needs `eszip` crate to walk; not pure plaintext |
+| `Electron`, `app.asar`, `chrome.dll`, `Squirrel.Mac` | **Electron** | `app.asar` archive (TAR-like with JSON header). Source is plaintext JS once extracted |
+| `PyInstaller`, `pyz`, `_MEIPASS`, `pyi-os-utils` | **PyInstaller** | Compressed `.pyc` bytecode — needs `pyinstxtractor` + `decompyle3` to recover Python source |
+| `nexe-`, `nexe_compile`, `:::nexe::` | **nexe** | Plaintext JS appended to node binary |
+| `Tauri`, `tao`, `wry`, `tauri::generate_context` | **Tauri** (Rust shell + JS UI) | **Two worlds**: JS frontend in resource section is extractable here; Rust commands / core logic are native and require [native-binary.md](native-binary.md) |
+
+If multiple match (e.g. Tauri + Bun): the outer shell is the first one (Tauri/Electron). The inner JS is the second one's format. **For Tauri specifically, expect to use both this reference (for the UI bundle) and `native-binary.md` (for the Rust binary side).**
+
+> **Source-format reality check**: only Bun SEA, pkg (when not using `--public-packages`), nexe, and Electron `.asar` are reliably plaintext. Node SEA with code-cache or snapshot, PyInstaller `.pyc`, and Deno eszip require additional tooling. Don't assume `strings` will find readable code — verify the bundler first.
+
+---
+
+## [2] Locate the bundle
+
+### Bun SEA — JS is just embedded plaintext
+
+The JS source is concatenated into the binary as a giant template literal / string. No decoding needed.
+
+```bash
+# Verify by searching for typical JS bundle markers
+strings -n 8 ./target | rg "function|var |let |const |async function" | head -5
+
+# Find where the bundle starts (look for "use strict" or banner comment)
+LC_ALL=C grep -aob '"use strict"' ./target | head -5
+LC_ALL=C grep -aob '#!/usr/bin/env bun' ./target | head -5
+```
+
+### Node SEA — `NODE_SEA_BLOB` resource/segment + activated fuse
+
+Per the [Node.js SEA docs](https://nodejs.org/api/single-executable-applications.html), a Node-built SEA contains:
+- A resource (PE), section in `NODE_SEA` segment (Mach-O), or note (ELF) named `NODE_SEA_BLOB`
+- The fuse string `NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2:1` (with trailing `:1` indicating injected; `:0` means a copy of the node binary that has not yet had a blob injected)
+
+```bash
+# Confirm it is a SEA at all
+LC_ALL=C grep -aob 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2:1' ./target | head -1
+
+# Find the blob resource/section
+LC_ALL=C grep -aob 'NODE_SEA_BLOB' ./target | head
+
+# On Mach-O, inspect the segment directly
+otool -l ./target | grep -A4 'NODE_SEA'
+```
+
+The blob format is documented but non-trivial to walk by hand. For extraction, **use postject in reverse** (carve the section bytes) or read the blob via `node:sea` API from inside a debug build of the same binary. Plain `strings` will get you the embedded JS only when the SEA was built without `useCodeCache` and without `useSnapshot` — both of those replace plaintext with V8 cache data or startup snapshot bytes.
+
+`node --build-sea sea-config.json` and `node --experimental-sea-config sea-config.json` *generate* SEA blobs; neither inspects an existing executable.
+
+### Deno compile — eszip archive section
+
+```bash
+# Deno-compile binaries embed an eszip v2 archive
+LC_ALL=C grep -aob 'ESZIP_V2' ./target | head -3
+# Also confirm the runtime
+LC_ALL=C grep -aob 'denort' ./target | head -1
+```
+
+To extract, use the `eszip` Rust crate (or the `@deno/eszip` JS port) to parse the archive after carving it out at the offset above. There is no stable Deno CLI flag that inspects compiled-executable eszip contents as of 2026-04 — `deno info` only works on source files.
+
+### pkg — `PAYLOAD_POSITION` marker
+
+```bash
+LC_ALL=C grep -aob 'PAYLOAD_POSITION' ./target | head
+LC_ALL=C grep -aob 'pkg/prelude' ./target | head
+```
+
+For source extraction, use the `pkg-extract` tooling community projects or carve based on the offset reported by the `PAYLOAD_POSITION:<n>` value.
+
+### Electron — `app.asar` is usually a separate file
+
+Most Electron apps ship `app.asar` next to the binary, not embedded inside. Extract it with the official tool:
+
+```bash
+# macOS layout
+ls -la /Applications/MyApp.app/Contents/Resources/app.asar
+npx @electron/asar extract app.asar ./extracted/
+# or older:
+npx asar extract app.asar ./extracted/
+```
+
+For single-file builds where the asar is embedded inside the executable, **do not pattern-match arbitrary 4-byte sequences** (the asar format starts with a Pickle-encoded uint32 header size + JSON metadata, and the same bytes appear elsewhere in any binary). Instead, use a Pickle-aware extractor that validates the JSON header before claiming a match — the `asar` npm package's programmatic `extractAll()` API does this. Carve the asar bytes by scanning for a candidate Pickle header (4-byte size + 4-byte payload size + `{"files":` prefix), validate the JSON parses, then feed the carved buffer to `extractAll()`.
+
+### PyInstaller — use `pyinstxtractor`, NOT runtime self-extraction
+
+```bash
+# Recover the embedded archive without running the binary
+python3 pyinstxtractor.py ./target
+# Output: ./target_extracted/ with .pyc files
+
+# Decompile the .pyc files back to Python source
+decompyle3 ./target_extracted/main.pyc # Python 3.7+
+uncompyle6 ./target_extracted/main.pyc # older Python
+```
+
+If `pyinstxtractor` cannot read the archive (e.g. non-standard PyInstaller version), use the official `pyi-archive_viewer` tool that ships with PyInstaller. Avoid the "run-the-binary-and-snoop-`/tmp/_MEI*`" approach: it only catches what runs in the time window between `_MEIPASS` extraction and cleanup, and it executes potentially untrusted code.
+
+---
+
+## [3] Extract source to disk — DO NOT skip this
+
+**The single biggest mistake** with bundled-JS reverse engineering is trying to read the source out of `strings` output or `xxd` dumps. You will lose data. See "Gotchas" below.
+
+### For Bun SEA / nexe / single-string-blob bundlers
+
+Read the binary as bytes, find the JS section, save to a `.js` file:
+
+```python
+# extract_bundled_js.py
+import sys
+
+if len(sys.argv) < 2:
+ raise SystemExit("usage: extract_bundled_js.py <target>")
+
+with open(sys.argv[1], 'rb') as f:
+ data = f.read()
+
+markers = [b'// @bun', b'"use strict"', b"'use strict'", b'#!/usr/bin/env']
+start = -1
+for m in markers:
+ p = data.find(m)
+ if p != -1 and (start == -1 or p < start):
+ start = p
+
+if start == -1:
+ raise SystemExit(
+ "no bundle marker found — binary may not be Bun/nexe, "
+ "or markers were stripped. Try strings(1) for hints."
+ )
+
+# Heuristic end: look for a long null run AFTER start.
+# This is a heuristic, NOT a guarantee. Verify the tail of the output
+# looks like JS (closing braces, EOF) before trusting it.
+end = data.find(b'\x00' * 1024, start)
+if end == -1:
+ end = len(data)
+
+bundle = data[start:end]
+print(f'Extracted {len(bundle)} bytes from offset {start} to {end}', file=sys.stderr)
+sys.stdout.buffer.write(bundle)
+```
+
+```bash
+python3 extract_bundled_js.py ./target > extracted-bundle.js
+wc -c extracted-bundle.js
+# Sanity check the tail is JS, not random binary
+tail -c 200 extracted-bundle.js
+```
+
+### For PyInstaller
+
+Use `pyinstxtractor` then `uncompyle6` / `decompyle3` on the `.pyc` files.
+
+### For Electron .asar
+
+```bash
+npx asar extract app.asar ./extracted/
+# Now ./extracted/ has a normal node_modules + your source layout
+```
+
+### For Deno compile
+
+Use the `eszip` Rust crate or the `@deno/eszip` JS port to walk the archive after carving the eszip section out at the offset reported by the `ESZIP_V2` magic search. There is no stable Deno CLI as of 2026-04 that inspects compiled-binary eszip contents directly.
+
+---
+
+## [4] Source-level static analysis — `rg` + `Read`, not Ghidra
+
+Once you have the source on disk, treat it as a normal codebase:
+
+```bash
+# Find function definitions
+rg -n "^function |^const \w+ = (function|\(.*\) =>)" extracted-bundle.js | head
+
+# Find specific behavior
+rg -n "claude-opus-4-7|reasoning_effort|api_key" extracted-bundle.js
+
+# Resolve minified identifiers — they show up as `var XYZ="value"`
+rg -aoP 'var \w+="[^"]+"' extracted-bundle.js | head -50
+```
+
+For minified bundles, use a template-literal-aware parser to extract specific functions or template strings. Example skeleton:
+
+```python
+def find_template_end(data, start):
+ """Walk a JS template literal preserving ${...} interpolation depth.
+ Returns position of closing backtick."""
+ i = start
+ while i < len(data):
+ c = data[i:i+1]
+ if c == b'\\':
+ i += 2; continue
+ if c == b'$' and data[i+1:i+2] == b'{':
+ depth = 1; i += 2
+ while i < len(data) and depth > 0:
+ cc = data[i:i+1]
+ if cc == b'\\': i += 2; continue
+ if cc == b'`':
+ j = find_template_end(data, i+1)
+ i = j + 1; continue
+ if cc == b'{': depth += 1
+ elif cc == b'}': depth -= 1
+ elif cc in (b'"', b"'"):
+ q = cc; i += 1
+ while i < len(data) and data[i:i+1] != q:
+ if data[i:i+1] == b'\\': i += 2
+ else: i += 1
+ i += 1; continue
+ i += 1
+ continue
+ if c == b'`': return i
+ i += 1
+ return -1
+```
+
+For function-body extraction, **track the parameter list separately** before tracking body braces. The naive approach mis-counts destructuring `function f({a, b, ...c})` as the body `{` and exits early.
+
+---
+
+## [5] Runtime verification
+
+You usually cannot single-step JS inside a Bun-compiled binary the way you would with `node --inspect`. Workarounds:
+
+### Bun-compiled
+
+Bun's inspector takes `--inspect[=<host>:<port>[/<prefix>]]` on the command line. For env-var control of compiled binaries, the form is the same minus the leading `--`:
+
+```bash
+# Default port (6499) auto-prefix
+./target --inspect
+# → ws://localhost:6499/<auto-prefix> (paste into https://debug.bun.sh)
+
+# Explicit host:port[/prefix]
+./target --inspect=localhost:9229/dbg
+# Or via env var (if --inspect cannot be passed)
+BUN_INSPECT=localhost:9229/dbg ./target
+```
+
+**For HTTP request tracing without an interactive debugger** (highest-value Bun-specific runtime evidence):
+
+```bash
+# Print every fetch() / node:http request as a curl command + full headers/body
+BUN_CONFIG_VERBOSE_FETCH=curl ./target ...
+
+# Or just print the request/response without curl-format
+BUN_CONFIG_VERBOSE_FETCH=true ./target ...
+```
+
+Plus generic env-var-based debug logging if the app supports it:
+
+```bash
+APP_DEBUG=1 APP_LOG_LEVEL=debug APP_LOG_FILE=/tmp/trace.log ./target
+```
+
+### Node SEA / pkg / nexe
+```bash
+# These usually accept --inspect since they are real Node
+./target --inspect
+# Then chrome://inspect or node --inspect-brk
+```
+
+### Electron
+```bash
+./target.app/Contents/MacOS/target --inspect=9229 --remote-debugging-port=9223
+# Renderer process is at chrome://inspect, main process via the inspector port
+```
+
+### When you cannot make a real call
+The target's API may require credentials, network access, or paid quota you don't have. **You are not stuck** — see [methodology/partial-runtime-evidence.md](../methodology/partial-runtime-evidence.md) for the fallback patterns.
+
+---
+
+## ⚠️ Gotchas — read these before extracting
+
+### G1. `strings -n N` silently drops short identifier interpolations
+
+`strings` outputs runs of printable characters of length **≥ N**. Default is 4 on most systems; many references (including older versions of `native-binary.md`) recommend `-n 8` for less noise.
+
+**With `-n 8`, short template-literal interpolations like `${x}`, `${i}`, `${R}` are silently dropped** because they are 4 chars surrounded by non-printable bytes (newlines or section padding). The result looks like:
+
+```text
+expected: <INSTRUCTIONS>\n${x}\n</INSTRUCTIONS>
+strings: <INSTRUCTIONS>\n</INSTRUCTIONS> ← ${x} is gone, no warning
+```
+
+A consumer reading the strings output would conclude the template is empty.
+
+**Mitigation**:
+1. Use `strings` only for **fingerprinting** (Phase 1 triage), never as the source of extracted text.
+2. For actual extraction, **read the binary as bytes** with `python3 -c "open('./target','rb').read()"` and grep / parse from there.
+3. If you must use `strings`, try `strings -n 1 -t x ./target` and post-filter — but byte-level reads are still more reliable.
+
+### G2. Stale cached binary ≠ latest features
+
+Bundled-app installers often check a remote version and skip download if a cached binary exists. If you reverse-engineered an old version and the user reports behavior you don't see in the source, **re-run the installer** (or fetch the version manifest manually) before assuming the source is current.
+
+```bash
+# Example pattern - varies by tool
+curl -fsSL https://example.com/install.sh | head -50 # find version-fetch URL
+curl -fsSL https://static.example.com/cli/cli-version.txt
+./your-tool --version
+# Compare. If different, re-install.
+```
+
+### G3. APFS / NTFS case-insensitivity silently overwrites files
+
+When extracting many minified function bodies (`cVR`, `CVR`, `dpr`, `DPR`, …) and saving each to its own file, **macOS APFS and Windows NTFS treat `cVR.txt` and `CVR.txt` as the same file**. The second write silently overwrites the first.
+
+**Mitigation**: prefix filenames with something case-distinguishing, e.g. `mode-cVR.txt`, `mode-CVR.txt`, or use a hash suffix.
+
+### G4. Bun's runtime adds 30-50 MB of unrelated symbols
+
+A 70 MB Bun-compiled binary is **mostly Bun runtime** (~50 MB) plus your app (~20 MB). When fingerprinting, you will see thousands of strings like `tree-sitter-typescript`, `react-native-stylex` etc. that the user's actual app doesn't use — these are package names baked into Bun's package-resolution data.
+
+**Mitigation**: when grepping for "what does this app do?", filter out runtime noise:
+```bash
+strings -n 8 ./target | rg -v 'node_modules|@oven/bun|package-lock|tree-sitter|ffmpeg-installer' | head
+```
+
+### G5. Source maps usually NOT shipped
+
+Bundled apps strip source maps for production. Variable names are minified to `T`, `R`, `a`, `r`, etc. Treat the bundle like an obfuscated codebase: identify constants by tracing assignments (`var T="actual-name"`) and resolve interpolations manually.
+
+### G6. The "extract" file is not legally redistributable
+
+If reverse-engineering proprietary software, the extracted source is the vendor's IP. Use it for understanding behavior, **never commit it to git**, never post snippets in public issues. Cleanup your `extracted-bundle.js` files in Phase 9.
+
+---
+
+## Silent-failure patterns specific to bundled JS
+
+| Pattern | Why it's silent |
+|---|---|
+| Bundle includes unreachable dead code from tree-shaking failures | You read code that never runs — verify with runtime trace |
+| `process.env.X` resolved at BUILD time, not RUNTIME | Setting the env var at runtime has no effect; the value is baked in |
+| `import.meta.url` in compiled binary returns `bun://...` not a real path | File-relative resolution silently breaks |
+| Worker threads spawn from embedded code, look for sub-bundle inside main bundle | Workers may have their own copy of dependencies |
+| Minified identifiers with case variants used in same module | Easy to confuse `cVR` with `CVR` when reading fast |
+
+---
+
+## Phase 9 cleanup specifics for bundled-JS work
+
+```bash
+# Remove extracted bundles — they may contain proprietary source
+rm -f /tmp/extracted-bundle.js /tmp/extracted-*.js
+rm -rf /tmp/asar-extracted/
+rm -rf /tmp/_MEI*
+
+# Remove strings dumps
+rm -f /tmp/*-strings.txt /tmp/*-strings-v*.txt
+
+# Remove Python helper scripts created for parsing
+rm -f /tmp/extract_bundled_js.py /tmp/parse_template.py
+
+# Verify the extraction directory is gone (if you used a workspace dir)
+ls /Users/$USER/local-workspaces/*-extracted/ 2>/dev/null
+# rm -rf only after journal review confirms nothing important is there
+```
+
+---
+
+## When to escalate back to `native-binary.md`
+
+If extraction reveals the "bundle" is actually compiled to v8 cached data (pkg with `--public-packages` or PyInstaller with bytecode-only mode), and decompilation is non-trivial, **switch back to `native-binary.md` workflow** (Ghidra against the runtime + careful tracing). Bundled-JS workflow only helps when the high-level source is recoverable as readable text.
diff --git a/plugins/omo/skills/debugging/references/runtimes/go.md b/plugins/omo/skills/debugging/references/runtimes/go.md
new file mode 100644
index 00000000..afed82ed
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/runtimes/go.md
@@ -0,0 +1,252 @@
+# Go Debugging
+
+Covers goroutines, `dlv` (Delve), `pprof`, the race detector, and the fact that Go's concurrency model means most bugs are about goroutines doing something quiet and wrong.
+
+---
+
+## Environment detection (Phase 0)
+
+```bash
+go version
+cat go.mod | head -5
+
+# Delve installed?
+which dlv
+dlv version
+
+# Build constraints
+grep -r '// +build\|//go:build' cmd/ internal/ pkg/ 2>/dev/null | head
+
+# pprof wired up?
+grep -r 'net/http/pprof\|runtime/pprof' --include='*.go' | head -3
+```
+
+---
+
+## Delve (`dlv`) — the Go debugger
+
+Go's gc compiler emits DWARF, but plain gdb barely understands goroutines. **Use dlv, not gdb.** Plain gdb on a Go binary will miss goroutine state and print garbage for interface values.
+
+### The five `dlv` launch modes
+
+```bash
+# Build and launch under debugger (equivalent to `go run` + debug)
+dlv debug ./cmd/server -- --port=8080
+
+# Debug a test binary
+dlv test ./internal/handler/ # enters the test package under debug
+
+# Debug an existing binary (must be built with -gcflags="all=-N -l" for best results)
+dlv exec ./bin/myserver
+
+# Attach to a running process
+dlv attach $(pgrep myserver)
+
+# Headless mode (IDE / remote attach) — default port 2345
+dlv debug --headless --listen=:2345 --api-version=2 ./cmd/server
+```
+
+### Building a debuggable binary
+
+The compiler inlines and optimizes aggressively in normal builds, which makes stepping confusing. For serious debugging:
+
+```bash
+go build -gcflags="all=-N -l" -o ./bin/server ./cmd/server
+# -N disables optimization
+# -l disables inlining
+```
+
+Then `dlv exec ./bin/server`.
+
+### Essential dlv commands
+
+```
+(dlv) b main.main # breakpoint at function
+(dlv) b handler.go:42 # breakpoint at file:line
+(dlv) b pkg/foo.Bar # breakpoint at type method (Go path syntax)
+(dlv) c / continue # continue until next break
+(dlv) n / next # step over
+(dlv) s / step # step into
+(dlv) so / stepout # step out
+(dlv) bt / stack # stack trace of current goroutine
+(dlv) goroutines # list all goroutines
+(dlv) goroutine <id> # switch to goroutine N
+(dlv) goroutine <id> bt # stack of a specific goroutine
+(dlv) locals # all locals in frame
+(dlv) args # function args
+(dlv) p <expr> # print value (understands interfaces, maps, slices)
+(dlv) vars <regex> # package vars matching regex
+(dlv) regs # registers (rare in Go debugging)
+(dlv) on <bpid> print <expr> # auto-print on breakpoint hit (powerful!)
+(dlv) trace <location> # like breakpoint but just logs, doesn't stop
+```
+
+The `trace` command is underused — it's like a logpoint, no stepping required.
+
+---
+
+## Goroutine-centric debugging
+
+Goroutine leaks and deadlocks are the most common Go bugs. `dlv`'s `goroutines` command is the starting point.
+
+```
+(dlv) goroutines -t # with truncated stack
+(dlv) goroutines -s # sorted by stack
+(dlv) goroutines -with user # filter user-spawned goroutines
+```
+
+Common patterns:
+
+| You see in `goroutines` | Usually means |
+|---|---|
+| 100s of goroutines stuck at `chan receive` | Producer died; consumers leak |
+| 100s stuck at `semacquire` | Lock contention; a holder probably deadlocked |
+| One stuck at `select` with no default | Missing case or closed channel scenario |
+| Stuck at `netpoll` | External I/O not responding — not a Go bug, check downstream |
+| Growing count over time | Goroutine leak — need to find who's spawning without cleanup |
+
+### Panic signals in Go
+
+```go
+// Without recovery, panics crash the program with a stack trace of ALL goroutines
+// With recovery, they're silent unless explicitly logged:
+defer func() {
+ if r := recover(); r != nil {
+ log.Printf("recovered panic: %v\n%s", r, debug.Stack()) // GOOD
+ // log.Printf("recovered") // BAD — silent
+ }
+}()
+```
+
+**Always check for silent recovers** in Phase 8. Grep:
+```bash
+rg 'recover\(\)' --type go
+```
+
+And inspect each site for whether the panic is actually surfaced.
+
+---
+
+## Race detector — ALWAYS run when the bug is intermittent
+
+```bash
+go test -race ./...
+go run -race ./cmd/server
+go build -race ./cmd/server
+```
+
+The race detector wraps memory accesses and catches concurrent read/write without synchronization. **Run this before attaching dlv** if intermittency is involved — it often finds the bug directly.
+
+Output shape:
+```
+WARNING: DATA RACE
+Read at 0x00c0001a0080 by goroutine 7:
+ main.(*Counter).Value()
+ /path/to/counter.go:14 +0x3c
+Previous write at 0x00c0001a0080 by goroutine 6:
+ main.(*Counter).Inc()
+ /path/to/counter.go:10 +0x5f
+```
+
+Both stacks. Both goroutines. The race is obvious from the line pair.
+
+---
+
+## pprof — for perf, memory, goroutine leaks
+
+### Wire it up (idempotent; usually already present)
+
+```go
+import _ "net/http/pprof"
+
+func main() {
+ go func() {
+ log.Println(http.ListenAndServe("localhost:6060", nil))
+ }()
+ // ... rest of your server
+}
+```
+
+### Queries
+
+```bash
+# CPU profile (30s)
+go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
+
+# Heap snapshot
+go tool pprof http://localhost:6060/debug/pprof/heap
+
+# Goroutine snapshot — find leaks
+go tool pprof http://localhost:6060/debug/pprof/goroutine
+
+# Block profile — find blocking ops (needs runtime.SetBlockProfileRate)
+go tool pprof http://localhost:6060/debug/pprof/block
+
+# Mutex profile — find lock contention (needs runtime.SetMutexProfileFraction)
+go tool pprof http://localhost:6060/debug/pprof/mutex
+```
+
+Inside pprof:
+```
+(pprof) top # top functions by self time
+(pprof) list main.handler # annotated source of a function
+(pprof) web # SVG callgraph in browser (requires graphviz)
+(pprof) traces # sample traces
+```
+
+For goroutine leaks, **take two snapshots 30s apart** and diff:
+```bash
+go tool pprof -base prof1.pb.gz prof2.pb.gz
+```
+
+Goroutines that appear in prof2 but not prof1 are new; if they stick around, they're leaking.
+
+---
+
+## `GODEBUG` — runtime-level observability
+
+```bash
+GODEBUG=gctrace=1 ./myserver # print GC stats
+GODEBUG=schedtrace=1000 ./myserver # scheduler trace every 1000ms
+GODEBUG=scheddetail=1,schedtrace=1000 # detailed scheduler state
+GODEBUG=allocfreetrace=1 ./myserver # every alloc/free (noisy!)
+GODEBUG=memprofilerate=1 ./myserver # profile every allocation
+```
+
+Useful for diagnosing GC pressure, goroutine starvation, or memory pattern issues.
+
+---
+
+## Silent-failure patterns in Go
+
+| Pattern | Why it's silent |
+|---|---|
+| `if err != nil { return err }` that returns to a caller that ignores | Error bubbles up, then gets discarded at the top |
+| `defer func() { recover() }()` — bare recover, no log | Panic swallowed, program continues with state corruption |
+| `_, _ = conn.Write(data)` | Intentionally discarded error |
+| Buffered channel send that blocks forever | Sender hangs; hard to see if no deadlock detection |
+| `time.Sleep` in a test | "Works on my machine"; test passes locally, fails in CI |
+| `go func() { ... }()` with no error path | Goroutine dies silently on panic unless recover+log |
+| Context canceled but operation continues | Ignored `ctx.Err()` check |
+| `json.Unmarshal` of zero-value struct field | Input missing the key; silently zero |
+| Closed channel read returning zero value | Consumer doesn't check `ok`; reads forever |
+
+---
+
+## Phase 9 cleanup specifics
+
+```bash
+# Kill dlv sessions
+pkill -f 'dlv' || true
+lsof -iTCP:2345 -sTCP:LISTEN -nP 2>/dev/null # dlv default
+
+# Kill pprof HTTP endpoint if you started it just for this session
+lsof -iTCP:6060 -sTCP:LISTEN -nP 2>/dev/null
+
+# Revert any `fmt.Println("DEBUG: ...")` or `log.Printf("DEBUG: ...")` additions
+git diff | grep -E '(fmt\.Println\("DEBUG|log\.Printf\("DEBUG|println!)'
+git checkout <file>
+
+# Unset env vars
+unset GODEBUG
+```
diff --git a/plugins/omo/skills/debugging/references/runtimes/native-binary.md b/plugins/omo/skills/debugging/references/runtimes/native-binary.md
new file mode 100644
index 00000000..b7c303a9
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/runtimes/native-binary.md
@@ -0,0 +1,484 @@
+# Native Binary Debugging (No Source / Reverse Engineering)
+
+For binaries where you don't have trustworthy source: stripped production builds, third-party closed libs, malware, CTF challenges, firmware, vendored libs whose docs lie. The workflow is specific; doing it out of order wastes days.
+
+This reference **coordinates** the triage and dynamic work. The heavy tools each have their own reference:
+- **Static decompilation** → [tools/ghidra.md](../tools/ghidra.md)
+- **Interactive debugging** → [tools/pwndbg.md](../tools/pwndbg.md)
+- **Scripted interaction / exploitation** → [tools/pwntools.md](../tools/pwntools.md)
+
+Read those before using them — especially Ghidra, which has a surprising amount of workflow that's not obvious.
+
+---
+
+## ⚠️ STOP — is this actually a stripped C/C++ binary?
+
+A growing share of "binaries" are actually **bundled high-level apps** — Bun SEA, Node SEA, Deno compile, pkg, nexe, Electron, Tauri, PyInstaller. Their workflow is completely different: the high-level source is recoverable with the right per-bundler tool (often plaintext, sometimes V8 cache / `.pyc` / eszip needing extra tooling), and Ghidra against the runtime VM wastes hours.
+
+Quick check:
+
+```bash
+file ./target # Mach-O / ELF / PE - inconclusive
+du -h ./target # 50 MB+ for a "simple CLI" → suspect bundled
+strings -n 12 ./target | rg -iE 'bun|node_modules|webpack|esbuild|deno|pkg/lib|electron|pyinstaller|nexe|NODE_SEA_FUSE|tauri' | head -5
+```
+
+**If any hits** → close this file, open [bundled-js-binary.md](bundled-js-binary.md) instead. Following the Ghidra/pwndbg path on a bundled-app binary wastes hours decompiling the runtime VM while the app-level bundle is recoverable with the right per-bundler tool (plaintext for Bun/pkg/nexe/Electron-asar; eszip / V8-cache / `.pyc` for Deno / Node SEA / PyInstaller).
+
+If `file` says "Mach-O" or "ELF", `du` is < 20 MB, and the strings check is empty → continue here.
+
+---
+
+## The workflow (do these in order)
+
+Every step's output is input to the next. Skipping steps means guessing later.
+
+```
+ [1] Triage → what kind of binary is this?
+ [2] Dynamic tracing → what syscalls / libcalls does it make?
+ [3] Static analysis → what does it DO, in readable form? (Ghidra)
+ [4] Dynamic debug → confirm hypotheses at runtime (pwndbg)
+ [5] Scripted repro → lock the bug with a pwntools script
+ [6] TDD + fix / report
+```
+
+Steps 1 and 2 are fast (minutes). Step 3 is slow (tens of minutes to hours depending on size). Don't skip 1-2 and go straight to Ghidra — the triage output tells you what to focus on inside Ghidra.
+
+---
+
+## [1] Triage — 5-minute fingerprint
+
+```bash
+# Basic identity
+file ./target
+# elf, mach-o, pe? 32/64-bit? dynamically linked? stripped?
+
+# Architecture details
+readelf -h ./target # ELF header: entry point, arch, type
+lipo -info ./target 2>/dev/null # macOS: universal binary?
+
+# Interesting strings (often leaks function names, error messages, URLs, API keys)
+strings -n 8 ./target | head -100
+strings -n 8 ./target | grep -iE '(http|/api/|error|debug|version)'
+
+# Imported symbols (what does it link against?)
+nm -D ./target 2>/dev/null # dynamic symbols
+objdump -T ./target 2>/dev/null # same, alternate tool
+readelf -d ./target # dynamic section (NEEDED libs)
+ldd ./target 2>/dev/null # resolved library paths
+
+# Security posture (affects what exploits / bugs are possible)
+checksec --file=./target # requires pwntools or installing checksec
+# NX, PIE, RELRO, stack canary, FORTIFY
+
+# Is it stripped?
+nm ./target 2>/dev/null | head # empty? stripped. full? not stripped.
+file ./target # will say "stripped" or "not stripped"
+```
+
+### ⚠️ `strings -n N` silently drops short content
+
+`strings` prints runs of printable characters of length **≥ N**. With `-n 8`, **anything shorter than 8 chars sandwiched between non-printable bytes is dropped silently**. This includes:
+
+- Short identifier interpolations in templates (`${x}`, `${i}`, `${R}`)
+- Short embedded constants (`v3`, `null`, integer immediates as bytes)
+- Short error codes between binary padding
+
+Real example: a JavaScript template literal `<INSTRUCTIONS>\n${x}\n</INSTRUCTIONS>` came out of `strings -n 8` as `<INSTRUCTIONS>\n</INSTRUCTIONS>` — the `${x}` (4 chars) was dropped. A consumer reading the dump would conclude the template was empty. It is not.
+
+**Use `strings` only for fingerprinting (Phase 1).** For any extraction whose correctness matters, **read bytes directly**:
+
+```bash
+# Count occurrences of a needle
+LC_ALL=C grep -aoc 'NEEDLE' ./target
+
+# Find offsets
+LC_ALL=C grep -aob 'NEEDLE' ./target | head
+
+# Or via Python for byte-precise context
+python3 -c "
+import sys
+data = open('./target','rb').read()
+needle = b'NEEDLE'
+pos = data.find(needle)
+print(repr(data[max(0,pos-100):pos+200]))
+"
+```
+
+If you must keep using `strings`, lower the threshold: `strings -n 1 -t x ./target | rg ...`. The signal-to-noise drops sharply but short content is preserved.
+
+Write the triage summary to the journal:
+
+```markdown
+## Binary triage
+- Type: <ELF 64-bit, dynamically linked, stripped>
+- Arch: <x86_64 | arm64 | ...>
+- Libs: <libc, openssl, libcurl>
+- Security: <NX, PIE, Partial RELRO, no canary>
+- Interesting strings: <short list>
+- First hypothesis surface: <which function / area looks most relevant>
+```
+
+---
+
+## [2] Dynamic tracing — what does it actually call?
+
+These are cheap — run them before Ghidra to orient yourself.
+
+### Linux: strace + ltrace
+
+```bash
+# System calls
+strace -f -o trace.out ./target arg1 arg2
+strace -f -e trace=network ./target # filter to network syscalls
+strace -f -e trace=file ./target # filter to file ops
+
+# Library calls (less useful when stripped but still informative)
+ltrace -f -o ltrace.out ./target
+ltrace -f -e 'str*+mem*' ./target # filter to string/mem functions
+```
+
+### macOS: Mach-O specifics
+
+**SIP block reality check.** With System Integrity Protection enabled (default on every modern macOS), `dtruss` / `dtrace` will **silently fail** to attach to:
+- Anything in `/usr`, `/bin`, `/sbin`, `/System`
+- Apple-signed binaries (Xcode CLT, Homebrew formulae from Apple-distributed taps)
+- Notarized vendor binaries (Bun, Deno, Docker Desktop, etc.)
+
+`dtruss ./target` will appear to run but produce zero events. This is not a bug; it is the SIP design. Disabling SIP requires a Recovery Mode reboot — usually not worth it. Use the alternatives below.
+
+```bash
+# dtruss — works only when SIP allows it (your own unsigned binaries)
+sudo dtruss -f ./target 2>&1 | head -20 # equivalent to strace
+# If output is suspiciously empty → SIP blocked it. Switch to lldb or app-level logging.
+```
+
+**Mach-O metadata inspection (no SIP issues, no debugger needed):**
+
+```bash
+# Architecture and slices
+file ./target # arm64 / x86_64 / universal
+lipo -info ./target # which architectures included
+lipo -thin arm64 ./target -output ./target-arm64 # extract one slice for analysis
+
+# Headers & load commands (segments, dylibs, code-signature pointer)
+otool -h ./target # Mach header (cputype, ncmds, flags)
+otool -l ./target | head -100 # load commands; entitlements live in code-signature blob, see codesign below
+
+# Dynamic library dependencies (macOS equivalent of ldd)
+otool -L ./target # linked dylibs with versions
+dyld_info ./target # macOS 13+, more detailed than otool -L
+
+# Disassembly
+otool -tv ./target | head -200 # quick disassembly without Ghidra
+otool -tV ./target # with symbol-resolved branches
+
+# Imported / exported symbols (Apple `nm`, NOT GNU)
+nm -u ./target # undefined references = imports
+nm -gU ./target # external defined = exports
+# Note: GNU `-D`/dynamic flags are not honored on Apple `nm`; use the above forms.
+symbols -fullSourcePath -onlyWithDebugInfo ./target # if any debug info survives
+
+# Code signature & entitlements (entitlements come from codesign, NOT otool)
+codesign -dv --entitlements :- ./target 2>&1 # signature info + entitlements XML on stdout
+spctl --assess --type execute -vv ./target # Gatekeeper assessment
+
+# Cert chain — extract to a temp dir to avoid creating files named -0/-1 in cwd
+tmp=$(mktemp -d)
+codesign -dvv --extract-certificates="$tmp/cert" ./target 2>&1
+ls -la "$tmp"
+# rm -rf "$tmp" # journal first, clean up later
+
+# Strings inside specific segments only (less noise than full-binary strings)
+otool -s __TEXT __cstring ./target # C string section
+otool -s __TEXT __const ./target # constants section
+```
+
+**Interactive debugging on macOS — use `lldb`, not `gdb`.**
+
+GDB on macOS requires a self-signed code-signing certificate (`codesign --entitlements gdb.entitlements --sign gdb-cert /opt/homebrew/bin/gdb`) and even then is unreliable on arm64. **Use `lldb` directly** — it ships with Xcode CLT and works without configuration.
+
+```bash
+# Start lldb
+lldb ./target
+
+# Set arguments
+(lldb) settings set target.run-args arg1 arg2
+
+# Run with breakpoints
+(lldb) breakpoint set --name function_name # symbol-based
+(lldb) breakpoint set --address 0x1000034c0 # address-based
+(lldb) breakpoint set --regex '.*decode.*' # regex over symbols
+
+# Run / step / inspect
+(lldb) run
+(lldb) bt # backtrace
+(lldb) frame variable # locals
+(lldb) register read # all registers
+(lldb) memory read --size 8 --format x --count 16 $sp # 16 qwords from stack
+(lldb) disassemble --frame # current function
+(lldb) image list # loaded modules
+(lldb) image lookup -a 0x1000034c0 # which module + symbol owns this address
+
+# Process attach to running process
+(lldb) process attach --pid 12345
+(lldb) process attach --name target # attach by name
+
+# Print Mach-O specific
+(lldb) image dump sections ./target
+(lldb) image dump symtab ./target
+```
+
+**Function interception via `DYLD_INSERT_LIBRARIES`** (macOS equivalent of `LD_PRELOAD`):
+
+```bash
+# Build a shim dylib that overrides specific functions
+# Then run target with it preloaded
+DYLD_INSERT_LIBRARIES=./shim.dylib DYLD_FORCE_FLAT_NAMESPACE=1 ./target
+```
+
+DYLD_INSERT works in the unrestricted case but is blocked in three distinct scenarios — distinguish them when diagnosing why your shim didn't load:
+
+1. **SIP / restricted process** (target has the `__RESTRICT,__restrict` section, is setuid/setgid, or is a platform/Apple-signed binary): dyld unconditionally strips all `DYLD_*` env vars before the process starts. Nothing you set will reach the target.
+2. **Hardened runtime + library validation** (`CS_RUNTIME` flag set, `com.apple.security.cs.disable-library-validation` entitlement absent): the process accepts `DYLD_INSERT_LIBRARIES` but **rejects** loading any dylib that isn't signed by the same Team ID or by Apple. Symptom: shim is found but not loaded; check `log show --predicate 'eventMessage CONTAINS "library validation failed"'`.
+3. **Notarization / Gatekeeper translocation**: the binary may be running from a translocated path; relative paths in `DYLD_INSERT_LIBRARIES` won't resolve. Use absolute paths.
+
+Check each:
+
+```bash
+# Restrict segment present? (case 1)
+otool -l ./target | grep -A2 __RESTRICT
+# Hardened runtime flag? (case 2)
+codesign -d --verbose=4 ./target 2>&1 | grep -iE 'flags=|CodeDirectory'
+# Look for "0x10000(runtime)" or similar in the flags line.
+# Disable-library-validation entitlement?
+codesign -d --entitlements :- ./target 2>&1 | grep disable-library-validation
+```
+
+**App-level debug logging (always works, ignores SIP):**
+
+When debugger attach is blocked, fall back to maximizing the app's own logging:
+
+```bash
+# Try common patterns
+APP_DEBUG=1 APP_LOG_LEVEL=debug APP_LOG_FILE=/tmp/trace.log ./target
+NSDebugEnabled=YES ./target # Cocoa apps
+OS_ACTIVITY_MODE=debug ./target # os_log subsystem
+
+# Then read os_log unified logging stream live
+log stream --predicate 'process == "target"' --level debug
+
+# Or extract historical logs
+log show --predicate 'process == "target"' --last 1h --info --debug
+```
+
+This is the **partial-runtime-evidence path** for macOS. See [methodology/partial-runtime-evidence.md](../methodology/partial-runtime-evidence.md) for how to combine app-level logs with static analysis when wire-level capture is blocked.
+
+**Network capture on macOS (TLS-decrypted):**
+
+```bash
+# 1. Find the active network service (don't assume "Wi-Fi"):
+# Map the default-route interface to the matching networksetup service name.
+networksetup -listallnetworkservices # show options
+DEFAULT_IF=$(route -n get default 2>/dev/null | awk '/interface:/ {print $2}')
+echo "Default-route interface: $DEFAULT_IF"
+# Match the interface (en0, en1, ...) back to a service name:
+SERVICE=$(networksetup -listallhardwareports | awk -v iface="$DEFAULT_IF" '
+ /^Hardware Port:/ { hp = substr($0, index($0,$3)) }
+ /^Device:/ { if ($2 == iface) print hp }
+')
+if [ -z "$SERVICE" ]; then
+ echo "Could not auto-detect active service. Pick one from -listallnetworkservices manually." >&2
+ echo "Aborting proxy setup." >&2
+ false # signal failure but stay safe at top level
+else
+ echo "Using service: $SERVICE"
+fi
+
+# 2. JOURNAL the original proxy state before changing it (REQUIRED for safe rollback):
+networksetup -getwebproxy "$SERVICE" # save this output to journal
+networksetup -getsecurewebproxy "$SERVICE" # save this too
+
+# 3. Start mitmproxy with persistent CA at ~/.mitmproxy/
+mitmproxy --listen-host 127.0.0.1 --listen-port 8888 &
+
+# 4. Trust the mitmproxy CA system-wide if the target uses URLSession or any framework
+# that ignores HTTPS_PROXY/SSL_CERT_FILE (most macOS-native apps do):
+sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain ~/.mitmproxy/mitmproxy-ca-cert.pem
+
+# 5. Two routing options. Try env-var first; fall back to system proxy:
+# 5a. Apps that honor env vars (most CLIs):
+HTTPS_PROXY=http://127.0.0.1:8888 SSL_CERT_FILE=~/.mitmproxy/mitmproxy-ca-cert.pem ./target ...
+
+# 5b. Apps that use URLSession / system network config (most GUI apps, Bun, some CLIs):
+networksetup -setwebproxy "$SERVICE" 127.0.0.1 8888
+networksetup -setsecurewebproxy "$SERVICE" 127.0.0.1 8888
+
+# 6. Cleanup — RESTORE original state from journal, untrust CA:
+networksetup -setwebproxystate "$SERVICE" off
+networksetup -setsecurewebproxystate "$SERVICE" off
+sudo security delete-certificate -c "mitmproxy" /Library/Keychains/System.keychain
+```
+
+**Critical**: forgetting step 6 leaves all your subsequent traffic mis-routed and silently MITM-able. Journal every step.
+
+### What to look for
+
+| Observation | Hypothesis |
+|---|---|
+| `open("/etc/secret-config", ...)` | Reads unexpected config; look at what it does with contents |
+| `connect(... 1.2.3.4:443)` | Phones home or depends on an external service |
+| `getenv("FOO")` returning NULL | Env var expected but not set |
+| Repeated `poll`/`epoll_wait` with no progress | Stuck on I/O; check downstream |
+| `SIGSEGV` caught by signal handler | Custom crash recovery — often hides the real bug |
+| `dlopen("libfoo.so.42")` | Dynamic plugin loading; check plugin path |
+
+---
+
+## [3] Static analysis with Ghidra
+
+When triage + tracing have narrowed you to "something in function X" or "the crypto routine is weird", open Ghidra.
+
+**Open [tools/ghidra.md](../tools/ghidra.md) before launching Ghidra** — the import / analyze / decompile workflow is not obvious and first-time users waste an hour figuring it out.
+
+Ghidra's decompiler turns machine code into readable-ish C. That's usually what you want. Stay in the Decompiler view; drop to Listing (disassembly) only when the decompiler punts.
+
+---
+
+## [4] Dynamic debugging with pwndbg
+
+Once static analysis gives you a hypothesis ("this branch at 0x401234 is where the validation fails"), confirm it at runtime with pwndbg.
+
+**Open [tools/pwndbg.md](../tools/pwndbg.md) before launching gdb.** Pwndbg gives you the context view (registers / stack / disasm / code all visible at once) which is essential for binary debugging.
+
+Typical pwndbg flow:
+
+```
+$ gdb ./target # pwndbg loads automatically if installed
+pwndbg> break *0x401234 # break at the address static analysis flagged
+pwndbg> run arg1 arg2
+# At the breakpoint:
+pwndbg> context # registers + stack + disasm
+pwndbg> telescope $rdi # walk pointers at $rdi
+pwndbg> x/20xw $rsp # raw dump of stack
+pwndbg> ni / si # step next / step instruction
+```
+
+---
+
+## [5] Scripted reproduction with pwntools
+
+Once you have a hypothesis with a concrete repro input, lock it down with pwntools. This is the "failing test" equivalent for binaries.
+
+**Open [tools/pwntools.md](../tools/pwntools.md)** — the Process/Remote/ELF/context APIs are the foundation.
+
+```python
+from pwn import *
+
+context.binary = elf = ELF('./target')
+
+p = process('./target')
+p.sendlineafter(b'> ', b'<trigger input that reproduces the bug>')
+result = p.recvall(timeout=3)
+assert b'expected-output-when-fixed' in result, f'bug repro: {result}'
+```
+
+This script is now your "red test". When the fix is applied, the script should pass (or the assertion should be inverted for negative tests — e.g. "the crash string should NOT appear").
+
+---
+
+## [6] Fixing a binary bug you can't recompile
+
+Three options, in preference order:
+
+### Option A: Patch at the source (if you have it)
+
+If the bug is in your own code and source is available, fix it there and rebuild. Standard TDD path.
+
+### Option B: Binary patch
+
+For tiny fixes (one byte, one branch inversion):
+
+```bash
+# Identify the exact byte offset
+# e.g. Ghidra says the bug is at 0x401234 = file offset 0x1234
+printf '\x90\x90' | dd of=./target bs=1 seek=$((0x1234)) conv=notrunc
+```
+
+Journal the exact `dd` command and the original bytes so you can revert.
+
+### Option C: Wrap / shim
+
+If you can't patch the binary, write a shim library (LD_PRELOAD on Linux, DYLD_INSERT_LIBRARIES on macOS) that overrides the buggy function. pwntools has examples.
+
+### Option D: Report upstream
+
+If it's a third-party binary and none of the above are feasible, the "fix" is a high-quality bug report with:
+- Full triage summary
+- Reproducible pwntools script
+- Ghidra decompilation of the buggy function
+- Hypothesis about the root cause
+- Recommended patch sketch (in C or pseudocode)
+
+---
+
+## Silent-failure patterns in native binaries
+
+| Pattern | Why it's silent |
+|---|---|
+| Ignored libc return codes (`read`, `write`, `malloc`) | Bug continues with garbage data; no check |
+| Signal handler swallows SIGSEGV | Crash converted to "something didn't work"; no log |
+| `setjmp`/`longjmp` unwinding over cleanup | Resources leak silently |
+| Thread-local error state never read (`errno`, `GetLastError`) | Error happened, nobody asked |
+| Recovered assertion failure in release build | `assert` compiled out; precondition violations silently corrupt |
+| Dangling pointer reads after free | Often looks like valid data until it doesn't |
+
+---
+
+## Phase 9 cleanup specifics
+
+```bash
+# Kill debugger sessions
+pkill -f 'gdb' || true
+pkill -f 'lldb' || true
+
+# Ghidra scratch projects (if made just for this session)
+# Named something like ~/ghidra-projects/debug-<timestamp>:
+ls -la ~/ghidra-projects/ 2>/dev/null
+# rm -rf ~/ghidra-projects/debug-scratch # only if the journal says to
+
+# Core dumps left from crashes
+rm -f ./core ./core.* ~/core.*
+
+# strace/ltrace output files
+rm -f trace.out ltrace.out
+
+# If you made a binary patch (Option B above), confirm revert
+# The journal should have the original bytes — restore them:
+# printf '<original-bytes>' | dd of=./target bs=1 seek=<offset> conv=notrunc
+
+# Trace-output files
+rm -f /tmp/debug-*.bin /tmp/debug-*.strace /tmp/debug-*.ltrace
+
+# macOS-specific:
+# Restore proxy settings if you set them (CRITICAL — leaves system traffic mis-routed otherwise)
+# Use the SAME $SERVICE you used when enabling the proxy (read it from the journal).
+# Do NOT hardcode "Wi-Fi" — many machines route traffic over Ethernet, USB tether, or a VPN service.
+[ -n "$SERVICE" ] && {
+ networksetup -setwebproxystate "$SERVICE" off 2>/dev/null
+ networksetup -setsecurewebproxystate "$SERVICE" off 2>/dev/null
+}
+# Or restore explicitly from the journaled original state — see the proxy section above.
+
+# Stop mitmproxy
+pkill -f 'mitmproxy' 2>/dev/null
+
+# Remove DYLD shim libraries you built
+rm -f /tmp/*-shim.dylib
+
+# Clear extracted strings dumps (these can be huge and may contain secrets)
+rm -f /tmp/*-strings*.txt
+
+# Verify hostname resolution returns to normal (mitmproxy can leave entries)
+scutil --dns | head -20
+```
diff --git a/plugins/omo/skills/debugging/references/runtimes/node.md b/plugins/omo/skills/debugging/references/runtimes/node.md
new file mode 100644
index 00000000..aac7fb17
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/runtimes/node.md
@@ -0,0 +1,260 @@
+# Node.js / tsx / ts-node / Bun / Deno Debugging
+
+Covers Node 18+, tsx, ts-node, Bun, Deno. Launch recipes, inspector protocol usage, the `node inspect` CLI, and the **tsx source-map silent-failure** that costs people days.
+
+---
+
+## Environment detection (Phase 0)
+
+```bash
+node --version
+cat package.json | head -40
+
+# Which JS runtime launches the app? (order them; the first match wins)
+ls node_modules/.bin/tsx 2>/dev/null && echo 'has tsx'
+ls node_modules/.bin/ts-node 2>/dev/null && echo 'has ts-node'
+ls node_modules/.bin/vitest 2>/dev/null && echo 'has vitest'
+which bun 2>/dev/null && bun --version
+which deno 2>/dev/null && deno --version
+
+# Source-map situation
+grep -E '"sourceMap"|"inlineSources"' tsconfig.json 2>/dev/null
+grep -l '//# sourceMappingURL' dist/*.js 2>/dev/null | head -3
+
+# Debug-relevant ports
+lsof -iTCP:9229 -sTCP:LISTEN -nP 2>/dev/null
+lsof -iTCP:9230 -sTCP:LISTEN -nP 2>/dev/null
+```
+
+---
+
+## 🚨 The tsx + `node inspect` CLI silent-failure (READ THIS)
+
+`tsx` transpiles each `.ts` file on the fly and emits an inline source map. V8 Inspector registers the module with its `.ts` path (so it shows up in the debugger's `scripts` list), **but the `node inspect` CLI REPL does not resolve source-map line numbers reliably**. Setting `sb('session.ts', 285)` will show a "pending" breakpoint that **never fires even after the module loads**.
+
+The breakpoint list will happily display it, so you think it's set. It isn't.
+
+### Three reliable workarounds
+
+| Workaround | When to use | Downside |
+|---|---|---|
+| **`debugger;` statement in source** | You can edit the source, CLI required | Requires source edit + revert |
+| **Chrome DevTools GUI** (`chrome://inspect`) | CLI not required, faster iteration | Not usable if user specifically asked for CLI |
+| **Debug the built `dist/` JS** | Source maps are working end-to-end | Requires `npm run build` on every source change |
+
+The `debugger;` statement is the most reliable. Journal the edit — revert at Phase 9.
+
+---
+
+## Launch recipes by runtime
+
+### Node (plain JS / compiled TS)
+
+```bash
+# Break on first line, wait for debugger to attach
+node --inspect-brk=9229 dist/index.js
+
+# Attach immediately, don't block startup — pair with debugger; statements
+node --inspect=9229 dist/index.js
+
+# Wait for debugger to attach, THEN run (new in Node 20.15+)
+node --inspect-wait=9229 dist/index.js
+
+# Source maps in stack traces (always a good idea in debug builds)
+node --enable-source-maps --inspect dist/index.js
+```
+
+### tsx
+
+```bash
+# The tsx runner is --import-compatible, so these work:
+node --inspect-brk=9229 --import tsx index.ts
+node --inspect=9229 --import tsx index.ts
+
+# If user prefers invoking tsx directly, this also works but is less explicit:
+NODE_OPTIONS='--inspect-brk=9229' npx tsx index.ts
+
+# ⚠️ tsx watch + inspector = inspector reloads per file change
+# Debug without watch:
+node --inspect=9229 --import tsx index.ts # (no `watch`)
+```
+
+### ts-node (legacy but still encountered)
+
+```bash
+node --inspect-brk -r ts-node/register src/index.ts
+# ESM (ts-node's ESM loader is fragile — if possible, migrate to tsx):
+node --inspect --loader ts-node/esm src/index.ts
+```
+
+### Bun (WebKit Inspector Protocol, NOT V8)
+
+```bash
+bun --inspect src/index.ts # opens debug.bun.sh URL
+bun --inspect-brk src/index.ts # break on start
+bun --inspect-wait src/index.ts # wait for attach
+bun test --inspect-brk # debug test runner
+```
+
+**Critical**: Bun uses WebKit Inspector Protocol, not V8. `chrome://inspect` cannot connect directly. Use `debug.bun.sh` or the (currently buggy, per Bun docs) VS Code extension.
+
+### Deno (native V8, Chrome DevTools / VS Code compatible)
+
+```bash
+deno run --inspect-brk --allow-all src/main.ts
+deno test --inspect-brk --filter "auth"
+```
+
+Deno is the smoothest TS debugging experience — native V8 inspector, no source-map workarounds.
+
+### Vitest
+
+```bash
+# Single worker required — inspector can't attach to multiple workers
+vitest --inspect-brk --no-file-parallelism
+vitest --inspect-brk --browser --no-file-parallelism # browser mode
+```
+
+Without `--no-file-parallelism`, breakpoints won't fire because the process Vitest spawns workers in isn't the one listening on the inspector port.
+
+---
+
+## Attaching with `node inspect` CLI
+
+```bash
+node inspect 127.0.0.1:9229 # attach to an existing --inspect process
+```
+
+Core commands at the `debug>` prompt:
+
+```
+cont, c resume until next break / debugger;
+next, n step over
+step, s step into
+out, o step out
+pause pause a running process
+bt backtrace
+scripts list all modules V8 has loaded (incl. tsx-transpiled .ts)
+sb(N) set breakpoint at line N of current file
+sb('file', N) set breakpoint at line N of matching file (⚠️ unreliable with tsx)
+sb(func) set breakpoint at function reference
+cb(N), cb('file', N) clear breakpoint
+breakpoints list breakpoints (shows pending ones, doesn't tell you they'll never fire)
+watch('expr') persistent watch expression
+watchers show watchers
+exec('expr') evaluate expression in paused frame's scope
+repl drop into full REPL with frame's scope
+restart restart the debuggee
+kill kill the debuggee
+```
+
+**`exec('expr')` is the most powerful tool in this CLI** — it evaluates any JS in the paused frame and returns the value. Use it heavily.
+
+---
+
+## `exec()` patterns that resolve hypotheses fast
+
+At a breakpoint, these queries resolve most LLM / agent / async bugs in one line each:
+
+```js
+// Agent / LLM state
+exec('this.agent.state.messages.length')
+exec('this.agent.state.messages.map(m => m.role)')
+exec('JSON.stringify(this.agent.state.messages.at(-1)).substring(0, 500)')
+exec('this.agent.state.messages.at(-1).errorMessage') // silent-error sentinel
+exec('this.agent.state.messages.at(-1).stopReason')
+exec('JSON.stringify(this.agent.state.usage)') // undefined / all-zero = failed call
+exec('this.agent.state.model.baseUrl') // catch hardcoded vs env-var
+
+// Env / config at runtime
+exec('process.env.RELEVANT_VAR')
+exec('Object.keys(process.env).filter(k => k.startsWith("ANTHROPIC"))')
+exec('this.config')
+
+// Async / timing
+exec('Date.now() - this._turnStartedAt')
+exec('this._activePromises?.size')
+
+// HTTP request/response in-flight
+exec('JSON.stringify(req.body).length')
+exec('res.statusCode')
+exec('res.headersSent')
+
+// What's actually running
+exec('process.version')
+exec('process.cwd()')
+exec('process.argv')
+```
+
+---
+
+## Silent-failure patterns in Node
+
+These are the patterns that most commonly look like success but aren't. Always check when a response is "too fast" or "too empty":
+
+| Signal | What it means |
+|---|---|
+| HTTP 200 + `content: ""` | Silent error swallowed |
+| HTTP 200 + response in <1s for an LLM call | Too fast for a real Claude/GPT call; something short-circuited |
+| `usage: { totalTokens: 0 }` | LLM SDK returned a stub without making the call |
+| `stopReason: "error" + content: []` | SDK packaged an error into a "success" message |
+| Unhandled promise rejection with no log | Caller forgot to `await`, or `.catch(() => {})` |
+| `try { await x(); } catch {}` | Error eaten, no log |
+| `void somePromise()` | Explicit opt-out of error propagation; often a bug |
+| Callback-style API where callback never fires | Error happened before callback scheduled |
+| Handler returns `res.json(...)` twice | Second call is silent on some Express versions |
+
+When you find one, add a temporary `console.error('[DEBUG]', ...)` to make it loud — journal it, revert at Phase 9.
+
+---
+
+## tmux session layout (two sessions, one purpose each)
+
+```bash
+# Long-running inspected process
+tmux new-session -d -s debug-server -c "$PWD"
+tmux send-keys -t debug-server 'node --inspect=9229 --import tsx index.ts' Enter
+
+# Interactive debugger client (separate pane for readability)
+tmux new-session -d -s debug-client -c "$PWD"
+tmux send-keys -t debug-client 'node inspect 127.0.0.1:9229' Enter
+
+# Non-blocking pane inspection from the outside
+tmux capture-pane -p -t debug-server -S -50
+```
+
+Journal both session names. Kill both at Phase 9:
+
+```bash
+tmux kill-session -t debug-server
+tmux kill-session -t debug-client
+```
+
+---
+
+## When to abandon the CLI and switch to Chrome DevTools
+
+The user's preference for CLI is valid and should be respected. But you may recommend a switch in one short sentence if ANY of these hold:
+
+- You hit source-map resolution failures (`sb('file', line)` not firing) AND the fix is time-sensitive
+- You need to watch many values simultaneously (GUI watch panel is faster to scan)
+- You're stepping through async-heavy code where CLI step semantics get murky across microtask boundaries
+
+Phrase as a note, not a request: "I can push through with `debugger;` statements in CLI. If we hit three or more of these in a row, switching to `chrome://inspect` GUI would cut cycle time in half — your call."
+
+---
+
+## Phase 9 cleanup specifics
+
+```bash
+# Revert source-level debug statements
+git diff | grep -E '(debugger;|console\.log\(.*DEBUG|\[ARBITER-DEBUG|\[DEBUG)'
+# Revert any matching files:
+git checkout <file>
+
+# Kill inspector-attached processes
+pkill -f 'node --inspect' || true
+pkill -f 'bun --inspect' || true
+pkill -f 'deno.*--inspect' || true
+lsof -iTCP:9229 -sTCP:LISTEN -nP 2>/dev/null
+```
diff --git a/plugins/omo/skills/debugging/references/runtimes/python.md b/plugins/omo/skills/debugging/references/runtimes/python.md
new file mode 100644
index 00000000..e16a9ad0
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/runtimes/python.md
@@ -0,0 +1,248 @@
+# Python Debugging
+
+Covers CPython 3.9+, pytest, asyncio, Django, FastAPI. Setup commands, attach mechanisms, state-query patterns, gotchas, silent-failure signatures.
+
+---
+
+## Environment detection (Phase 0)
+
+```bash
+# Which Python will actually run the code?
+which python; which python3
+python --version
+
+# Is there a project env manager in play?
+ls poetry.lock uv.lock Pipfile.lock requirements*.txt .python-version 2>/dev/null
+
+# Installed debuggers / profilers in this env?
+python -c 'import pdb, sys; print("pdb", "built-in"); print("python", sys.executable)'
+pip list 2>/dev/null | grep -iE '^(ipdb|pudb|debugpy|py-spy|memray|rich)\s'
+
+# asyncio debug mode available?
+python -c 'import asyncio; print(asyncio.__version__)'
+```
+
+**Wrapper gotchas** (these change how flags propagate):
+
+- `poetry run python ...` — args after `python` are fine; args before `poetry run` go to poetry, not python
+- `uv run python ...` — similar; prefer `uv run -- python -X dev` if flags collide
+- `pipenv run` — same story
+- `./manage.py <cmd>` (Django) — shebang resolution; make sure it points to the right venv
+- `pytest` — loads `conftest.py` at collection; breakpoints inside collection need `pytest --pdb-trace` not `--pdb`
+
+---
+
+## The four ways to attach
+
+| Method | When to use | Command |
+|---|---|---|
+| **`breakpoint()` inline** (Python 3.7+) | You can edit the source and restart. Most reliable. | Add `breakpoint()` to source. Run normally. It invokes `pdb` by default. |
+| **`python -m pdb <script>`** | No source edit desired. Breaks on entry. | `python -m pdb script.py arg1` |
+| **post-mortem `pdb.pm()`** | Exception already happened, you want to inspect state | In an exception-caught REPL: `import pdb; pdb.pm()` after the exception propagates |
+| **debugpy (remote / IDE)** | IDE attach, remote host, containerized process | `python -m debugpy --listen 5678 --wait-for-client script.py` then attach from VS Code / PyCharm |
+
+### Prefer `ipdb` or `pudb` over plain `pdb` when available
+
+- **ipdb** — drop-in replacement with tab completion, syntax highlighting. `pip install ipdb`, then `PYTHONBREAKPOINT=ipdb.set_trace` or use `import ipdb; ipdb.set_trace()`.
+- **pudb** — full-screen TUI debugger, much faster to navigate stack/locals. `pip install pudb`, then `PYTHONBREAKPOINT=pudb.set_trace`.
+
+### Control `breakpoint()` globally
+
+```bash
+# Use ipdb instead of pdb
+export PYTHONBREAKPOINT=ipdb.set_trace
+
+# Disable all breakpoint() calls (useful to ship without removing them)
+export PYTHONBREAKPOINT=0
+```
+
+**Journal this env var** — unset at Phase 9.
+
+---
+
+## pdb / ipdb essentials
+
+At a `(Pdb)` or `ipdb>` prompt:
+
+```
+l list source around current line
+ll list whole function
+s step into
+n step over (next)
+r step out (return)
+c continue
+b list breakpoints
+b <line> breakpoint at line
+b <func> breakpoint at function
+cl <n> clear breakpoint n
+w where (backtrace)
+u / d move up/down the stack
+a args of current frame
+p <expr> print expression
+pp <expr> pretty-print
+!<stmt> execute Python statement (e.g. !x = 5)
+interact drop into a full Python REPL with current frame's locals
+q quit (aborts the program)
+```
+
+**`interact` is underused** — it gives you a full IPython-esque REPL with all locals available. Faster than typing `p` for 20 things.
+
+---
+
+## pytest-specific debugging
+
+```bash
+# Enter pdb on first failure
+pytest --pdb
+
+# Enter pdb at the START of each test (not on failure)
+pytest --trace
+
+# Run only the failing test, with -s to show print output
+pytest --pdb -x -s path/to/test.py::test_name
+
+# Collect-time debugging (for problems in conftest.py / fixture setup)
+pytest --pdb-trace
+
+# Disable capture for this test (so breakpoint prompt is visible)
+pytest -s
+```
+
+**Common failure**: `breakpoint()` hangs inside a pytest test — that's because pytest captures stdout/stderr by default. Always add `-s` when debugging with breakpoints inside pytest.
+
+---
+
+## asyncio gotchas
+
+Async is where most Python debug sessions go sideways. Know these before attaching.
+
+### Breakpoints inside coroutines
+
+`breakpoint()` works inside an async function, but stepping into another coroutine from `pdb` is awkward. Two techniques:
+
+```python
+async def handler():
+ result = await some_async_fn() # add breakpoint ABOVE, not inside, when possible
+ breakpoint()
+ return result
+```
+
+Inside the breakpoint, to inspect a coroutine without actually advancing time:
+```
+!import asyncio
+!loop = asyncio.get_event_loop()
+!task = asyncio.ensure_future(some_async_fn())
+# Now inspect task state, don't await it
+p task
+```
+
+### PYTHONASYNCIODEBUG
+
+Enable before running the process:
+
+```bash
+PYTHONASYNCIODEBUG=1 python script.py
+```
+
+Surfaces: coroutines that were never awaited, slow callbacks, unhandled task exceptions. **Always turn this on** if the bug is timing- or async-related.
+
+### `asyncio.gather` swallows the first exception
+
+By default, `asyncio.gather(t1, t2)` raises the first exception and cancels the rest. If you need all exceptions, use `gather(..., return_exceptions=True)`.
+
+### Unhandled task exceptions are silent
+
+```python
+async def main():
+ task = asyncio.create_task(broken_coroutine())
+ # If task raises and we never await it, the exception is eaten at gc time
+ await asyncio.sleep(10)
+```
+
+To catch these, set `loop.set_exception_handler(...)` or upgrade to Python 3.12+ which warns louder by default.
+
+---
+
+## debugpy — remote / IDE / container attach
+
+Listen and wait for attach:
+
+```bash
+python -m debugpy --listen 0.0.0.0:5678 --wait-for-client script.py
+```
+
+Attach from VS Code:
+```json
+// .vscode/launch.json
+{
+ "name": "attach",
+ "type": "python",
+ "request": "attach",
+ "connect": { "host": "localhost", "port": 5678 }
+}
+```
+
+Inside the code, programmatic attach point:
+```python
+import debugpy
+debugpy.listen(5678)
+debugpy.wait_for_client() # blocks until attached
+debugpy.breakpoint() # programmatic breakpoint
+```
+
+**Journal**: the port (5678) and the listener file — unset at Phase 9.
+
+---
+
+## Sampling profilers for "why is it slow / stuck"
+
+When the problem is performance or a hang (not a crash), don't attach pdb — it alters timing. Use a sampling profiler that attaches to the running process:
+
+```bash
+# py-spy — production-safe, zero code change, works on running process
+py-spy top --pid <pid> # live top-like view
+py-spy record -o profile.svg --pid <pid> # flamegraph
+py-spy dump --pid <pid> # stack traces of all threads right now
+
+# memray — memory allocation tracking
+memray run script.py
+memray flamegraph output.bin
+memray stats output.bin
+```
+
+`py-spy dump` on a stuck process is often enough to find the hung call — no breakpoints needed.
+
+---
+
+## Silent-failure patterns in Python
+
+Add these to Phase 8's silent-failure check:
+
+| Pattern | Why it's silent |
+|---|---|
+| `except Exception: pass` or `except: pass` | Catches and discards every error including KeyboardInterrupt |
+| `logging.exception(...)` in a logger with no handlers | "Logs" but actually writes nowhere |
+| `asyncio.create_task(coro)` without storing the task | Task GC'd before completion, exception swallowed |
+| `return x.get("key")` where key is missing | Returns None silently, caller often doesn't check |
+| `subprocess.run(..., check=False)` with ignored returncode | Non-zero exit treated as success |
+| Django `transaction.atomic()` inside a broader `except` | Rolls back silently |
+| `contextlib.suppress(Exception)` | Explicit silencer; easy to leave wider than intended |
+| `queue.get(block=False)` with `except queue.Empty: pass` | Polling that silently drops the work |
+
+---
+
+## Phase 9 cleanup specifics
+
+```bash
+# Remove breakpoint() / ipdb / pudb lines from source
+git diff | grep -E '(breakpoint\(\)|import ipdb|import pudb|import pdb; pdb\.set_trace)'
+# If the above has output, revert those files:
+git checkout <file>
+
+# Unset the global breakpoint override
+unset PYTHONBREAKPOINT
+
+# Kill any leftover debugpy listeners
+pkill -f 'debugpy' || true
+lsof -iTCP:5678 -sTCP:LISTEN -nP 2>/dev/null # confirm free
+```
diff --git a/plugins/omo/skills/debugging/references/runtimes/rust.md b/plugins/omo/skills/debugging/references/runtimes/rust.md
new file mode 100644
index 00000000..94829024
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/runtimes/rust.md
@@ -0,0 +1,234 @@
+# Rust Debugging
+
+Covers `cargo`, `tokio`, panics, and the fact that you usually don't actually need a debugger — Rust's type system, `dbg!`, and logging cover 80% of sessions faster than gdb would.
+
+---
+
+## Environment detection (Phase 0)
+
+```bash
+cargo --version
+rustc --version
+cat rust-toolchain.toml rust-toolchain 2>/dev/null
+cat Cargo.toml | head -30
+
+# Debuggers available
+which rust-gdb
+which rust-lldb
+which lldb
+
+# Async infrastructure
+grep -E '"(tokio|async-std|smol)"' Cargo.toml
+
+# Profile flags
+grep -E '^\[profile' Cargo.toml
+```
+
+**The default `cargo run` builds with `dev` profile** which includes debug symbols. `cargo run --release` strips them. For debugging, stay in dev unless the bug only manifests under optimization.
+
+---
+
+## The Rust debugging hierarchy (use in this order)
+
+Rust's ecosystem has a specific order that's faster than reaching for gdb first:
+
+1. **`dbg!(expr)` macro** — for a single value at a specific spot. Prints file:line + value, returns the value unchanged so you can inline it. Faster than a debugger for 60% of bugs.
+2. **`RUST_LOG=trace` with `tracing` / `env_logger`** — for flow and state across an operation. Zero code change in dev-time.
+3. **`RUST_BACKTRACE=1` / `=full`** — for crashes. Almost always sufficient; you rarely need a live debugger for a panic.
+4. **`rust-gdb` / `rust-lldb`** — when you need to pause execution and inspect memory, especially for unsafe code or FFI.
+5. **`tokio-console`** — for async deadlocks, stuck tasks, hot loops.
+6. **`cargo-expand`** — when a macro is doing something weird.
+
+Reach for the lightest tool that answers the hypothesis.
+
+---
+
+## `dbg!` — the underused macro
+
+```rust
+let x = 5;
+let y = dbg!(x * 2); // prints: [src/main.rs:2] x * 2 = 10
+```
+
+Inside a complex expression:
+```rust
+let total = items.iter().filter(|i| i.active).map(|i| dbg!(i.cost)).sum::<u64>();
+```
+
+Multiple values at once:
+```rust
+dbg!(&user, &request, elapsed.as_millis());
+```
+
+`dbg!` writes to stderr, so it won't corrupt stdout-based pipelines. **Journal each `dbg!` you add**; revert at Phase 9.
+
+---
+
+## `RUST_LOG` for flow-level debugging
+
+If the codebase uses `tracing` or `env_logger`:
+
+```bash
+RUST_LOG=debug cargo run
+RUST_LOG=trace cargo run # very verbose
+RUST_LOG=my_crate=trace,hyper=info cargo run # per-module level
+RUST_LOG=debug,tokio=off cargo run # silence noisy crates
+```
+
+For `tracing`-based apps, instrument with spans:
+```rust
+#[tracing::instrument]
+fn handle_request(req: &Request) -> Response { ... }
+```
+
+This gives you structured per-call entry/exit logs with args and timing, zero additional code in the body.
+
+---
+
+## `RUST_BACKTRACE` for panics
+
+```bash
+RUST_BACKTRACE=1 cargo run # backtrace on panic
+RUST_BACKTRACE=full cargo run # include libstd/tokio frames
+```
+
+The panic itself usually tells you the file:line. The backtrace tells you how it got there. Between the two, most crash bugs are solved without a debugger.
+
+---
+
+## rust-gdb / rust-lldb
+
+### Launch
+
+```bash
+# Build with debug symbols (default dev profile)
+cargo build
+
+# Attach gdb wrapper (applies Rust type pretty-printers)
+rust-gdb ./target/debug/my_binary
+# Or lldb:
+rust-lldb ./target/debug/my_binary
+
+# With args
+rust-gdb --args ./target/debug/my_binary arg1 arg2
+
+# Attach to running process
+rust-gdb -p $(pgrep my_binary)
+```
+
+### Breakpoints
+
+Rust symbols are mangled. Use either:
+
+```
+(gdb) b main # main function
+(gdb) b my_crate::module::function # canonical path
+(gdb) b src/handler.rs:42 # file:line
+(gdb) info functions my_function # find mangled name
+```
+
+### State inspection
+
+```
+(gdb) p x # print value (uses Rust pretty-printer for Vec, Option, HashMap, etc.)
+(gdb) p *ptr # deref
+(gdb) info locals # all locals in current frame
+(gdb) info args # function args
+(gdb) bt # backtrace
+(gdb) frame <n> # switch to stack frame n
+(gdb) watch my_var # stop when my_var changes
+(gdb) rbreak regex # breakpoint all functions matching regex
+```
+
+**Pair with pwndbg** for better layout on native bugs — see [tools/pwndbg.md](../tools/pwndbg.md). Pwndbg works with rust-gdb too.
+
+---
+
+## tokio-console — async task debugging
+
+For tokio-based async apps, this is essential when tasks are stuck or leaking.
+
+```bash
+# Add tokio-console instrumentation to the target binary
+# In Cargo.toml:
+# [dependencies]
+# console-subscriber = "0.2"
+
+# In main.rs:
+# console_subscriber::init();
+
+# Build with tokio_unstable:
+RUSTFLAGS="--cfg tokio_unstable" cargo run
+
+# In another terminal:
+tokio-console # connects to default port 6669
+```
+
+Shows live tasks, their state, wake counts, poll durations, parent tasks. The single fastest way to find "why is my async thing stuck".
+
+---
+
+## cargo-expand — when a macro is suspect
+
+```bash
+cargo install cargo-expand
+cargo expand # expand all macros in the crate
+cargo expand my::module::path # scope to one item
+```
+
+If you suspect a macro (especially `#[derive]`, `#[tokio::main]`, `#[async_trait]`) is generating code that doesn't match your mental model, this shows you exactly what the compiler sees.
+
+---
+
+## Release-build gotcha
+
+```bash
+cargo build --release # no debug symbols by default
+```
+
+If the bug only shows up in `--release`:
+
+```toml
+# Cargo.toml
+[profile.release]
+debug = true # add symbols, keep optimizations
+```
+
+Now `rust-gdb ./target/release/my_binary` works on release builds. This is required when optimization-enabled codegen bugs (inlining, LLVM folding) are suspected.
+
+---
+
+## Silent-failure patterns in Rust
+
+| Pattern | Why it's silent |
+|---|---|
+| `.unwrap_or_default()` | Masks errors as the zero value |
+| `.unwrap_or(fallback)` | Same, with a specific fallback |
+| `let _ = fallible_operation()` | Explicitly discards the Result, no compiler warning |
+| `if let Ok(x) = ... { use(x); } // no else` | Silent on Err |
+| `.ok()` chaining | Converts Result to Option, throwing the error away |
+| Panic inside a tokio task not `.await`ed | Task dies silently; runtime usually logs but it's quiet if logs are off |
+| `eprintln!` that goes to a redirected-null stderr | Looks like nothing happened |
+| `Drop` impl that panics under specific condition | Double-panic aborts process silently if no logging configured |
+
+---
+
+## Phase 9 cleanup specifics
+
+```bash
+# Revert dbg! macro additions
+git diff | grep -E 'dbg!\('
+# For any file with dbg! additions:
+git checkout <file>
+
+# Unset env vars
+unset RUST_LOG RUST_BACKTRACE
+
+# Kill any rust-gdb/lldb sessions
+pkill -f 'rust-gdb' || true
+pkill -f 'rust-lldb' || true
+pkill -f '^lldb ' || true
+
+# tokio-console binds 6669 by default
+lsof -iTCP:6669 -sTCP:LISTEN -nP 2>/dev/null
+```
diff --git a/plugins/omo/skills/debugging/references/tools/ghidra.md b/plugins/omo/skills/debugging/references/tools/ghidra.md
new file mode 100644
index 00000000..045cda03
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/tools/ghidra.md
@@ -0,0 +1,212 @@
+# Ghidra — Decompile Binaries Into Readable C
+
+**https://github.com/NationalSecurityAgency/ghidra**
+
+Ghidra is the NSA's open-source reverse-engineering suite. Its defining feature is a **decompiler** that turns machine code back into readable C. For any binary you don't have source for, this is the correct starting point — not `strings`, not hex-staring, not `objdump -d`.
+
+**Use Ghidra when**: third-party closed-source libs, malware analysis, vendored binaries whose behavior contradicts docs, CTF challenges, firmware, any time you need to read compiled code.
+
+---
+
+## Install
+
+```bash
+# macOS
+brew install --cask ghidra
+# OR download the release ZIP from the repo and ./ghidraRun
+
+# Linux
+# Download from https://github.com/NationalSecurityAgency/ghidra/releases
+# Requires JDK 21+
+./ghidraRun
+
+# Dependency
+java -version # must be 21+
+```
+
+Ghidra is a Java Swing app. Looks dated, works well.
+
+---
+
+## First-time workflow (memorize this — it's not obvious)
+
+1. **Start Ghidra**: `ghidraRun`
+2. **Create a project**: File → New Project → Non-Shared → name it `debug-<binary-name>` (journal this path so you can rm it at Phase 9 if disposable).
+3. **Import the binary**: File → Import File → pick your target. Accept default format detection.
+4. **Double-click the imported binary** in the project listing. Ghidra asks to analyze it — say **yes**, accept defaults for the first pass. This takes anywhere from seconds (small binary) to tens of minutes (large binary).
+5. **Once analysis completes**, you're in the CodeBrowser view.
+
+Two panels you'll use 95% of the time:
+
+- **Listing** (middle) — the disassembly with Ghidra's inferred labels/types.
+- **Decompiler** (right) — the reconstructed C. The real value.
+
+---
+
+## Finding the right function fast
+
+Don't try to read the whole binary. Use these to narrow:
+
+### Symbol Tree (left panel)
+
+- `Functions` — all detected functions. Stripped binaries show `FUN_00401234` (address-named); unstripped show actual names.
+- `Imports` — dynamically-linked functions. Great for "does this binary call `system()`, `strcpy`, `curl_easy_perform`?"
+- `Exports` — if it's a library.
+
+Click to jump. The Decompiler updates instantly.
+
+### String search
+
+```
+Search → For Strings
+```
+
+Produces a list of all strings. Right-click a string → `References` → `Show References to Address`. Jumps to code that references it. **This is how you find which function handles the error message you saw at runtime.**
+
+### Memory search for bytes
+
+```
+Search → Memory
+```
+
+Search hex or text. Useful for known magic bytes, file-format signatures, constants.
+
+### Cross-references (XREF)
+
+Right-click any function / address → `References → Find References to`. Shows every place that calls it. Walk the call graph backward from interesting functions.
+
+---
+
+## Making the decompiler's output readable
+
+Ghidra's decompiler is good but needs hints. These three actions dramatically improve its output:
+
+### 1. Rename variables
+
+Click a variable in the Decompiler view → press `L` → type a better name. Ghidra propagates the rename across all uses.
+
+### 2. Set types
+
+A variable that looks like `undefined4` or `void *` is unhelpful. Click it → press `Ctrl+L` → set type (e.g. `int`, `char *`, `struct my_header *`).
+
+For pointers to structs from headers you have, use:
+```
+File → Parse C Source → paste header file → auto-creates struct types
+```
+
+Then assign the struct type to the pointer. Ghidra resolves field accesses immediately.
+
+### 3. Retype function signatures
+
+Click the function name in the Decompiler → press `F` (Edit Function Signature) → set return type + argument types. This propagates through callers.
+
+Do these three actions on the 3-5 most relevant functions and the decompiler output becomes near-source-readable.
+
+---
+
+## Patterns for specific bug types
+
+### Looking for integer overflow / buffer overflow
+
+```
+Listing: look for
+ - LEA → CMP patterns on sizes
+ - memcpy/strcpy/sprintf with non-constant sizes
+Decompiler: look for
+ - arithmetic on size_t without bounds check
+ - `+ user_input` in a length calculation
+```
+
+### Looking for a missing auth check
+
+Navigate from the handler entry (found via Strings or Imports) and check the control flow:
+
+```
+Decompiler: does the function return early / jump to error handler when some flag is not set?
+ If the check is absent, that's the bug.
+```
+
+### Looking for hardcoded URLs / keys / paths
+
+```
+Search → For Strings → filter `http:` / `https:` / `/etc/` / `bearer ` / `api_key`
+```
+
+### Looking for dispatch / plugin loading
+
+```
+Imports → dlopen, LoadLibrary, dlsym, GetProcAddress
+```
+
+The strings referenced near those calls are often plugin names.
+
+---
+
+## Scripting (headless Ghidra)
+
+When you need to automate analysis across many binaries, or repeat a workflow:
+
+```bash
+# Headless analyzer
+$GHIDRA_INSTALL_DIR/support/analyzeHeadless \
+ <project-dir> <project-name> \
+ -import <binary> \
+ -postScript <script.py or script.java>
+```
+
+Ghidra supports Python 3 scripts (via Jython-compatible API) and Java. Useful scripts:
+
+- Dump all function signatures to JSON
+- Find all calls to `system()` with constant arguments
+- Auto-rename FUN_xxx based on heuristics (string refs, call patterns)
+
+The community has a large collection: https://github.com/NationalSecurityAgency/ghidra/tree/master/Ghidra/Features/Base/ghidra_scripts
+
+---
+
+## Bookmarks + Notes
+
+Ghidra has built-in bookmarks and comments. Use them as your journal inside the project:
+
+- Right-click an address → `Set Bookmark` → tag as `Note`. Attach a description.
+- Right-click → `Comments → Set EOL Comment` (shows up inline in decompiler).
+
+Treat these as part of the journal. If you end up promoting this Ghidra project (keeping it after the debug session), the comments become durable documentation.
+
+---
+
+## Gotchas
+
+- **Large binaries need more Java heap.** Edit `support/launch.properties` and bump `VMARGS=-Xmx8G` (default is often 2G, too small).
+- **Save often.** Ghidra's autosave is not instant; a crash loses uncommitted analysis.
+- **Decompiler has timeouts.** For complex functions it may give up and print `/* WARNING: ... */`. Increase timeout in `Edit → Tool Options → Decompiler`.
+- **Archs beyond x86/ARM/MIPS** sometimes need Sleigh processor module tweaks. Rare but possible.
+- **Signed vs unsigned decompilation** is frequently wrong. Manually retype when integer behavior matters.
+
+---
+
+## When Ghidra is NOT the right tool
+
+- You have the source. Go read it.
+- Bug is in your own recently-compiled binary. Rebuild with `-g` and use gdb/pwndbg (see [pwndbg.md](pwndbg.md)).
+- You just need to know which libs a binary links. `ldd` / `otool -L` / `readelf -d` are faster.
+- You just need strings. `strings -n 8` is faster.
+
+Ghidra is the right tool when you need to **read the logic** of a binary you don't have source for.
+
+---
+
+## Phase 9 cleanup specifics
+
+```bash
+# If you created a scratch project just for this debug session, journal path and remove:
+# (the journal should have the exact path)
+# Example:
+ls ~/ghidra-projects/ 2>/dev/null
+# rm -rf ~/ghidra-projects/debug-<binary-name>
+
+# If you promoted the project (kept it), it's not cleanup — note it in the final summary to the user
+
+# Kill any running Ghidra headless processes
+pkill -f 'analyzeHeadless' || true
+```
diff --git a/plugins/omo/skills/debugging/references/tools/playwright-cli.md b/plugins/omo/skills/debugging/references/tools/playwright-cli.md
new file mode 100644
index 00000000..7d636715
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/tools/playwright-cli.md
@@ -0,0 +1,194 @@
+# Playwright CLI — Browser QA That Actually Drives a Browser
+
+**https://playwright.dev/ · https://github.com/microsoft/playwright**
+
+For any browser-served web UI bug, this is the correct tool. Not curl. Not imagination. Not a headless HTTP library. A real browser with a real rendering engine, real JS execution, real cookies, real service workers, real viewport.
+
+**In Phase 8 Manual QA for browser products, using Playwright is not optional.** Curl cannot catch: CSS that breaks at specific viewport widths, hydration mismatches, client-side router bugs, cookie/session interactions, service-worker caching, JS-triggered navigations. All of those are common bug classes. Drive a browser.
+
+> Note: `microsoft/playwright-cli` is the legacy repo; the current tooling lives in `@playwright/test` (npm) and `playwright` (pip), which include the `playwright` CLI. Use those — the legacy `playwright-cli` package is deprecated.
+
+---
+
+## When to reach for Playwright
+
+| Bug symptom | Use Playwright? |
+|---|---|
+| Form submit produces wrong result | ✅ — Playwright drives the form exactly as a user does |
+| Page blank in prod, fine locally | ✅ — hydration/env differences need a real browser |
+| CSS looks wrong at a specific width | ✅ — use `--viewport-size` |
+| Click doesn't fire / wrong handler | ✅ — Playwright fires real DOM events |
+| Flash of unstyled content / loading glitch | ✅ — use trace viewer to see frames |
+| API returns wrong data | ❌ — use curl, this isn't a browser bug |
+| Backend returns wrong status code | ❌ — use curl |
+| Client hits a URL that returns 500 | ✅ but also ❌ — Playwright shows the call + response + failure effect on UI |
+
+---
+
+## Install (per-project)
+
+Playwright installs browser binaries separately from the npm package.
+
+```bash
+# In the project
+npm init playwright@latest # interactive; picks TS/JS + browsers + config
+# Or if Playwright is already a dep:
+npx playwright install # downloads browsers
+npx playwright install chromium # just chromium
+npx playwright install --with-deps # also installs OS deps (Linux)
+```
+
+Python:
+```bash
+pip install playwright
+playwright install
+```
+
+---
+
+## The four things you'll actually use
+
+### 1. `codegen` — record a session, generate the script
+
+The fastest way to create a repro. Opens a real browser; your clicks / typing become a Playwright script you can paste into a test.
+
+```bash
+npx playwright codegen https://your-app.local
+npx playwright codegen --viewport-size=375,667 https://your-app.local # iPhone SE size
+npx playwright codegen --device="iPhone 14" https://your-app.local
+```
+
+Click / type / navigate in the browser; watch the script build in the side panel. Copy the generated script into your journal as the repro for Phase 8.
+
+### 2. A one-shot Playwright script — reproduce + capture
+
+Usually the Phase 8 QA artifact. Save to `/tmp/debug-repro.spec.ts` (journal it):
+
+```ts
+// /tmp/debug-repro.spec.ts
+import { test, expect } from '@playwright/test';
+
+test('refinement chat shows non-empty response when env var set', async ({ page }) => {
+ await page.goto('http://localhost:3000/chat');
+ await page.fill('textarea[name="message"]', 'Add a logging step');
+ await page.click('button[type=submit]');
+
+ // Wait for the response to appear (not just the spinner to disappear)
+ const response = page.locator('[data-testid="assistant-reply"]');
+ await expect(response).toBeVisible({ timeout: 30_000 });
+ await expect(response).not.toBeEmpty();
+
+ // Capture evidence
+ await page.screenshot({ path: '/tmp/debug-after-fix.png', fullPage: true });
+ console.log(await response.textContent());
+});
+```
+
+Run it with tracing enabled for rich post-mortem:
+
+```bash
+npx playwright test /tmp/debug-repro.spec.ts --trace on --headed
+```
+
+### 3. `PWDEBUG=1` — step through the script with Playwright Inspector
+
+```bash
+PWDEBUG=1 npx playwright test /tmp/debug-repro.spec.ts
+```
+
+Opens the Playwright Inspector alongside the browser. You can step through Playwright actions, see the DOM state at each step, and edit selectors on the fly.
+
+Use this when the script doesn't reproduce cleanly and you need to watch it run.
+
+### 4. `show-trace` — post-mortem on a failed run
+
+```bash
+npx playwright show-trace trace.zip
+# or from the test-results dir:
+npx playwright show-trace test-results/<test-name>/trace.zip
+```
+
+Scrubs through a recorded session: timeline, DOM snapshot at each action, network, console, source. When a test failed on CI but passed locally, this is the single best artifact.
+
+---
+
+## Headless vs headed during debugging
+
+Always add `--headed` when debugging. Headless browsers sometimes behave subtly differently (font rendering, viewport, media permissions). For QA evidence, run headed and screenshot.
+
+```bash
+npx playwright test --headed
+npx playwright test --headed --project=chromium # pin the browser
+```
+
+---
+
+## Catching the silent-failure patterns Playwright is good at
+
+```ts
+// Toast that flashes and disappears
+page.on('console', msg => console.log('[browser console]', msg.type(), msg.text()));
+
+// Unhandled page errors (uncaught exceptions in the page JS)
+page.on('pageerror', err => console.error('[page error]', err));
+
+// Network failures — e.g., backend returned 500 but UI shows nothing
+page.on('response', async resp => {
+ if (!resp.ok()) {
+ console.warn(`[network ${resp.status()}] ${resp.url()} — ${await resp.text()}`);
+ }
+});
+
+// Request that never came back
+page.on('requestfailed', req => {
+ console.error('[request failed]', req.url(), req.failure()?.errorText);
+});
+```
+
+Add these listeners to the top of the debug script. They surface a lot of the "UI showed nothing" class of bug.
+
+---
+
+## Viewport and device emulation
+
+CSS bugs that only appear at specific sizes, or layout bugs on mobile:
+
+```ts
+// At test level
+test.use({ viewport: { width: 375, height: 667 } });
+
+// Per-page
+await page.setViewportSize({ width: 375, height: 667 });
+
+// Predefined devices
+import { devices } from '@playwright/test';
+test.use({ ...devices['iPhone 14'] });
+```
+
+---
+
+## Gotchas
+
+- **Wait for state, not for time.** `await page.waitForTimeout(2000)` is flaky. Use `await expect(locator).toBeVisible()` or `page.waitForResponse(urlPattern)`.
+- **Stale selectors re-resolve.** Playwright's locators re-find the element on each action, unlike Puppeteer's handles. Don't over-think it.
+- **Service workers persist across test runs in headed mode.** If you see cached behavior from a previous run, add `await context.clearCookies()` + clear storage before the test.
+- **Installing on CI requires `--with-deps`** on Linux images that lack the browser's shared-library deps.
+- **Parallel tests share a browser process by default**; if one test polls a debugger port, others may interfere. Use `workers: 1` for debugging.
+
+---
+
+## Phase 9 cleanup specifics
+
+```bash
+# Remove trace files from debug runs
+rm -rf playwright-report/ test-results/ trace.zip
+
+# Remove debug spec files from /tmp
+rm -f /tmp/debug-*.spec.ts
+
+# Remove screenshot captures
+rm -f /tmp/debug-*.png
+
+# If you installed browsers just for this session (rare):
+# Don't remove them — they're useful for future sessions. They live in ~/Library/Caches/ms-playwright (macOS) or ~/.cache/ms-playwright (Linux).
+```
diff --git a/plugins/omo/skills/debugging/references/tools/pwndbg.md b/plugins/omo/skills/debugging/references/tools/pwndbg.md
new file mode 100644
index 00000000..8a28ae3f
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/tools/pwndbg.md
@@ -0,0 +1,263 @@
+# pwndbg — GDB With the Useful Views Always On
+
+**https://github.com/pwndbg/pwndbg**
+
+pwndbg is a GDB plugin that turns GDB into something humans can actually use for binary debugging. It's strictly a superset of plain GDB — every vanilla GDB command still works, and pwndbg adds views and commands that make you productive.
+
+**If you'd reach for plain `gdb`, reach for pwndbg instead.** The only reason not to is if pwndbg isn't installed on the machine, and that's a 2-minute fix.
+
+---
+
+## Install
+
+```bash
+# macOS
+brew install pwndbg
+# Or from source:
+git clone https://github.com/pwndbg/pwndbg
+cd pwndbg && ./setup.sh
+
+# Linux
+# Most distros: apt/dnf/pacman install pwndbg (check availability)
+# Or the same git + ./setup.sh
+
+# Verify
+gdb --version
+gdb ./any-binary
+# At gdb prompt, you should see pwndbg banner + colorful context view
+```
+
+Once installed, pwndbg auto-loads every time you start `gdb`. You don't source anything manually.
+
+---
+
+## The `context` view — the one feature that changes everything
+
+Plain GDB: you run `info registers`, then `bt`, then `x/10xw $rsp`, then `disas`. Four commands to see what's going on.
+
+pwndbg: `context` (or it auto-shows at every break). One command. Everything on screen:
+
+```
+──── registers ────
+ RAX 0x0
+ RBX 0x7ffffffde158
+ RCX 0x7fffff7abf10
+ ...
+──── disasm ────
+ ► 0x401234 mov rdi, rax
+ 0x401237 call 0x401190
+ ...
+──── stack ────
+ 00:0000│ rsp 0x7ffffffde0a0 → 0x7fffff7c4000
+ 01:0008│ 0x7ffffffde0a8 → 0x0
+ ...
+──── backtrace ────
+ ► f 0 0x401234 parse_input+0x3c
+ f 1 0x401180 main+0x120
+ f 2 0x7fffff7a5083 __libc_start_main+0xf3
+```
+
+You always know where you are, what the CPU state is, what's on the stack, and how you got here. This is why pwndbg is the default.
+
+---
+
+## Launch recipes
+
+```bash
+# Debug an existing binary
+gdb ./target
+
+# With args
+gdb --args ./target arg1 arg2
+
+# Attach to a running process
+gdb -p $(pgrep target)
+
+# With a core dump
+gdb ./target ./core
+
+# Headless / remote (for automation or IDE attach)
+gdbserver :2345 ./target # on the target box
+gdb ./target # on your box
+(gdb) target remote <host>:2345
+```
+
+At the pwndbg prompt:
+
+---
+
+## Essential commands (pwndbg additions)
+
+### Layout / view
+
+```
+context # reprint the context view (usually auto)
+context regs stack # only show registers + stack sections
+tel $rsp 20 # telescope — walk pointers at $rsp for 20 slots (KEY COMMAND)
+tel $rdi 10 # walk pointers at $rdi (e.g. to dump a struct)
+stack 20 # 20 entries of stack
+vmmap # virtual memory map of the process
+```
+
+**`telescope` is pwndbg's killer command.** Given an address, it walks pointers recursively:
+```
+00:0000│ 0x7ffd... → 0x601010 (heap) → 0x2a (unknown, i.e. a number 42)
+01:0008│ 0x7ffd... → 0x7fff... (stack) → 'hello world'
+```
+This single view resolves 80% of "what is at this address" questions.
+
+### Heap debugging
+
+```
+heap # overview of chunks
+bins # tcache / fastbin / unsorted / smallbin / largebin state
+malloc_chunk <addr> # inspect a specific chunk
+find_fake_fast <addr> # (exploit context) find fake-fast overlap candidates
+vis_heap_chunks # visualize heap layout
+```
+
+For use-after-free / double-free / heap overflow hypotheses, `heap` + `bins` is usually sufficient to see the corruption.
+
+### Exploitation-adjacent (useful for bug understanding too)
+
+```
+checksec # NX, PIE, RELRO, canary status
+rop --grep 'pop rdi' # find ROP gadgets
+nx # step over (aliased nicely)
+ni # step over single instruction
+si # step into single instruction
+```
+
+### Search
+
+```
+search -t byte 0x41 # find byte 0x41 anywhere in memory
+search -t string "admin" # find string
+search -p <addr> # find pointers to <addr>
+```
+
+---
+
+## Standard GDB commands still work
+
+pwndbg doesn't replace GDB; it augments it. Everything you know still works:
+
+```
+break main # breakpoint at function
+b *0x401234 # breakpoint at address
+b file.c:42 # breakpoint at file:line
+c # continue
+n # next (source-level step over)
+s # step (source-level step into)
+finish # step out
+info breakpoints # list breakpoints
+delete <n> # delete breakpoint
+watch <var> # break on write to variable
+rwatch <var> # break on read
+awatch <var> # break on access
+p <expr> # print expression
+p/x <expr> # print in hex
+x/20xw <addr> # examine 20 words as hex
+bt # backtrace
+frame <n> # switch frame
+info registers # registers (but `context` is better)
+disassemble <func> # disasm a function
+```
+
+---
+
+## Python scripting inside GDB
+
+pwndbg exposes a full Python API. Useful for automating observations across many breakpoints:
+
+```python
+(gdb) python
+import gdb
+def on_break():
+ frame = gdb.selected_frame()
+ pc = frame.read_register('pc')
+ print(f'hit at {hex(int(pc))}')
+ # Dump args, locals, anything
+end
+```
+
+Or scripted runs from outside:
+```bash
+gdb -batch -ex 'source script.gdb' -ex 'run' ./target
+```
+
+---
+
+## Common workflows by bug type
+
+### Segfault / crash
+
+```bash
+gdb ./target
+(gdb) run <args>
+# ... crash ...
+(gdb) context # see the crash site
+(gdb) bt # how did we get here?
+(gdb) info registers # what state
+(gdb) tel $rsp 20 # what's on the stack
+```
+
+### "Function returns wrong value"
+
+```bash
+gdb ./target
+(gdb) break <function>
+(gdb) run <args>
+# At breakpoint:
+(gdb) finish # let it run to the return
+# pwndbg shows RAX (return value) in context
+```
+
+### "Variable has unexpected value at point X"
+
+```bash
+gdb ./target
+(gdb) break <point-X>
+(gdb) run
+# At breakpoint:
+(gdb) p <var> # its value
+(gdb) watch <var> # set a watchpoint — break when it changes
+(gdb) c # continue; next stop is where it was modified
+```
+
+### "Memory corruption / heap bug"
+
+```bash
+gdb ./target
+(gdb) run
+# Crash at free():
+(gdb) heap # heap state
+(gdb) bins # bin state — often shows corruption here
+(gdb) vis_heap_chunks # visualize
+(gdb) malloc_chunk <suspicious-addr>
+```
+
+---
+
+## Gotchas
+
+- **`bt` looks weird on stripped binaries** — function names become offsets. Use Ghidra's function labels to map back (see [ghidra.md](ghidra.md)).
+- **PIE binaries have randomized base addresses.** Addresses you see in Ghidra are unslid; addresses in pwndbg are slid. The `vmmap` command shows the base, and pwndbg's `piebase` command gives you the offset.
+- **Optimized builds inline functions.** You'll set a breakpoint on `my_function` and it won't hit because the function was inlined. Either disable optimizations or break on callers.
+- **Stack canaries trigger `__stack_chk_fail`.** If you see that in a backtrace, the bug caused a stack-smash; look one frame up.
+
+---
+
+## Phase 9 cleanup specifics
+
+```bash
+# Kill gdb / pwndbg sessions
+pkill -f 'gdb' || true
+pkill -f 'gdbserver' || true
+
+# Remove core dumps generated during session
+rm -f ./core ./core.* ~/core.*
+
+# Remove any scripted GDB files
+rm -f /tmp/debug-*.gdb
+```
diff --git a/plugins/omo/skills/debugging/references/tools/pwntools.md b/plugins/omo/skills/debugging/references/tools/pwntools.md
new file mode 100644
index 00000000..e4b1e2dc
--- /dev/null
+++ b/plugins/omo/skills/debugging/references/tools/pwntools.md
@@ -0,0 +1,265 @@
+# pwntools — Scripted Binary / Network Interaction
+
+**https://docs.pwntools.com/en/stable/ · https://github.com/Gallopsled/pwntools**
+
+pwntools is a Python framework for building reproducible interactions with binaries and network services. Originally built for CTF exploitation, it's the correct tool for any situation where you need:
+
+- A crafted input sent to a binary or network service, repeatably
+- A "failing test" equivalent for a bug that only manifests with specific byte-level input
+- A fuzz harness
+- An exploit PoC
+- Anything where you're tempted to use `echo ... | ./binary` but need more control than shell allows
+
+**Use pwntools for Phase 5 reproduction of binary bugs and Phase 7 tests against binaries.**
+
+---
+
+## Install
+
+```bash
+pip install pwntools
+# Or in a venv:
+python -m venv .venv && source .venv/bin/activate
+pip install pwntools
+
+# Verify
+python -c 'from pwn import *; print("ok")'
+```
+
+On some Linux distros you may need build deps: `apt install python3-dev libssl-dev`.
+
+---
+
+## The core API in five idioms
+
+### 1. Process / Remote — the same interface
+
+```python
+from pwn import *
+
+# Local process
+p = process('./target')
+
+# Remote service
+p = remote('example.com', 1337)
+
+# SSH (tunnel to a remote process)
+shell = ssh('user', 'host', password='...')
+p = shell.process('./target', cwd='/tmp')
+
+# Same methods on all of the above — this is the value proposition
+```
+
+### 2. I/O — the only five methods you need
+
+```python
+p.send(b'data') # send bytes
+p.sendline(b'data') # send bytes + \n
+p.recv(n) # receive up to n bytes
+p.recvuntil(b'> ') # receive until pattern (blocks)
+p.recvline() # receive until \n
+p.interactive() # hand control to your terminal (for manual exploration)
+
+# Combined
+p.sendlineafter(b'prompt> ', b'payload')
+p.sendafter(b'key:', key)
+```
+
+Timeouts:
+```python
+try:
+ data = p.recvuntil(b'done', timeout=5)
+except pwnlib.exception.EOFError:
+ print('process died')
+except TimeoutError:
+ print('no response in 5s')
+```
+
+### 3. context — set arch/OS once, tools align
+
+```python
+context.binary = elf = ELF('./target') # auto-sets arch/os/endianness
+# or explicitly:
+context.update(arch='amd64', os='linux', endian='little', bits=64)
+```
+
+After setting context, helpers like `asm()`, `disasm()`, `cyclic()`, and `ROP()` produce correct output for that target automatically.
+
+### 4. ELF — parse without reverse-engineering by hand
+
+```python
+elf = ELF('./target')
+
+elf.symbols['main'] # address of main
+elf.plt['printf'] # address in PLT (dynamic linkage)
+elf.got['printf'] # GOT entry
+elf.address = 0x555555554000 # set base for PIE binaries
+elf.search(b'/bin/sh') # find string or bytes in the binary
+elf.functions['main'].address # same as elf.symbols['main']
+list(elf.functions)[:10] # first 10 function names
+```
+
+For the libc that's linked:
+```python
+libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
+libc.symbols['system']
+```
+
+### 5. cyclic — find offsets without counting
+
+For "where exactly does user input reach this variable" bugs:
+
+```python
+p = process('./target')
+p.sendline(cyclic(256)) # send a De Bruijn pattern
+# Crash occurs; note the crash value (e.g. RIP = 0x6161616c)
+offset = cyclic_find(0x6161616c) # returns 12 (or wherever in the pattern)
+# Now you know: byte 12 of your input lands at RIP
+```
+
+Saves an hour of "pad by N bytes then check" iteration.
+
+---
+
+## Logging during debug
+
+pwntools logs output by default. Configure level in the script:
+
+```python
+context.log_level = 'debug' # very verbose — shows sent/received bytes
+context.log_level = 'info' # default
+context.log_level = 'warning' # quiet
+```
+
+For long scripts, log milestones:
+
+```python
+log.info('Connected to target')
+log.success('Bypassed the check')
+log.failure('Canary corrupted')
+log.progress('brute-forcing').status('attempt %d' % i)
+```
+
+---
+
+## Typical debug-session patterns
+
+### Reproduce a crash with a specific input
+
+```python
+# /tmp/debug-repro.py
+from pwn import *
+context.binary = './target'
+
+p = process('./target')
+p.sendlineafter(b'> ', b'<bad input that crashes>')
+p.wait()
+# If it crashed, p.poll() returns non-zero
+assert p.poll() is not None and p.poll() != 0, 'expected crash, got clean exit'
+log.success(f'confirmed crash (exit {p.poll()})')
+```
+
+Journal this script path. Run it as your "red test":
+
+```bash
+python /tmp/debug-repro.py
+```
+
+### Fuzz harness for a suspected input class
+
+```python
+# /tmp/debug-fuzz.py
+from pwn import *
+import random
+
+context.binary = './target'
+context.log_level = 'warning' # keep quiet in the loop
+
+crashes = []
+for i in range(1000):
+ payload = bytes(random.randint(0, 255) for _ in range(random.randint(1, 100)))
+ p = process('./target')
+ p.sendline(payload)
+ p.wait()
+ if p.poll() is not None and p.poll() < 0: # crashed by signal
+ crashes.append((payload, p.poll()))
+ log.success(f'iter {i}: crash sig={-p.poll()}')
+
+open('/tmp/debug-crashes.txt', 'w').write(repr(crashes))
+log.info(f'found {len(crashes)} crashes')
+```
+
+### Automated exploit harness (CTF or self-testing a known CVE)
+
+```python
+from pwn import *
+context.binary = elf = ELF('./target')
+libc = elf.libc or ELF('/lib/x86_64-linux-gnu/libc.so.6')
+
+p = process('./target')
+
+# Leak
+p.sendline(b'A' * 64 + p64(elf.plt['puts']) + p64(elf.symbols['main']) + p64(elf.got['puts']))
+leak = u64(p.recv(6).ljust(8, b'\x00'))
+libc.address = leak - libc.symbols['puts']
+log.success(f'libc base: {hex(libc.address)}')
+
+# Exploit
+rop = ROP(libc)
+rop.system(next(libc.search(b'/bin/sh')))
+p.sendline(b'A' * 64 + rop.chain())
+
+p.interactive()
+```
+
+---
+
+## Integration with gdb / pwndbg
+
+pwntools can launch your process under gdb:
+
+```python
+p = gdb.debug('./target', gdbscript='''
+ break main
+ continue
+''')
+```
+
+Or attach to a running pwntools-launched process:
+
+```python
+p = process('./target')
+gdb.attach(p, gdbscript='break *0x401234')
+# continues in a new terminal window with gdb attached
+p.sendline(b'trigger input')
+```
+
+This is the best way to debug a specific crash repeatably — pwntools drives input, gdb/pwndbg observes runtime state.
+
+---
+
+## Gotchas
+
+- **Python version**: pwntools supports Python 3.8+. Very old distros may not have it.
+- **`p.interactive()` blocks.** It's for manual exploration; remove it from automated scripts.
+- **ASLR on local runs**: turn off for reproducibility during debugging: `echo 0 | sudo tee /proc/sys/kernel/randomize_va_space` (remember to revert — journal this!).
+- **`gdb.debug()` requires `gdb-multiarch`** for cross-arch binaries.
+- **Subprocess cleanup**: if your script crashes, orphan `./target` processes may linger. Kill them at Phase 9 or add `atexit` cleanup.
+
+---
+
+## Phase 9 cleanup specifics
+
+```bash
+# Remove pwntools debug scripts
+rm -f /tmp/debug-*.py
+rm -f /tmp/debug-crashes.txt
+
+# Kill orphan target processes from failed runs
+pkill -f './target' || true # adjust to actual binary name
+
+# Restore ASLR if disabled
+# echo 2 | sudo tee /proc/sys/kernel/randomize_va_space # Linux default
+
+# Revert any binary patches applied for testing (see native-binary.md for details)
+```
diff --git a/plugins/omo/skills/frontend-ui-ux/SKILL.md b/plugins/omo/skills/frontend-ui-ux/SKILL.md
new file mode 100644
index 00000000..9eea542e
--- /dev/null
+++ b/plugins/omo/skills/frontend-ui-ux/SKILL.md
@@ -0,0 +1,77 @@
+---
+name: frontend-ui-ux
+description: "Designer-turned-developer who crafts stunning UI/UX even without design mockups"
+---
+# Role: Designer-Turned-Developer
+
+You are a designer who learned to code. You see what pure developers miss-spacing, color harmony, micro-interactions, that indefinable "feel" that makes interfaces memorable. Even without mockups, you envision and create beautiful, cohesive interfaces.
+
+**Mission**: Create visually stunning, emotionally engaging interfaces users fall in love with. Obsess over pixel-perfect details, smooth animations, and intuitive interactions while maintaining code quality.
+
+---
+
+# Work Principles
+
+1. **Complete what's asked** - Execute the exact task. No scope creep. Work until it works. Never mark work complete without proper verification.
+2. **Leave it better** - Ensure that the project is in a working state after your changes.
+3. **Study before acting** - Examine existing patterns, conventions, and commit history (git log) before implementing. Understand why code is structured the way it is.
+4. **Blend seamlessly** - Match existing code patterns. Your code should look like the team wrote it.
+5. **Be transparent** - Announce each step. Explain reasoning. Report both successes and failures.
+
+---
+
+# Design Process
+
+Before coding, commit to a **BOLD aesthetic direction**:
+
+1. **Purpose**: What problem does this solve? Who uses it?
+2. **Tone**: Pick an extreme-brutally minimal, maximalist chaos, retro-futuristic, organic/natural, luxury/refined, playful/toy-like, editorial/magazine, brutalist/raw, art deco/geometric, soft/pastel, industrial/utilitarian
+3. **Constraints**: Technical requirements (framework, performance, accessibility)
+4. **Differentiation**: What's the ONE thing someone will remember?
+
+**Key**: Choose a clear direction and execute with precision. Intentionality > intensity.
+
+Then implement working code (HTML/CSS/JS, React, Vue, Angular, etc.) that is:
+- Production-grade and functional
+- Visually striking and memorable
+- Cohesive with a clear aesthetic point-of-view
+- Meticulously refined in every detail
+
+---
+
+# Aesthetic Guidelines
+
+## Typography
+Choose distinctive fonts. **Avoid**: Arial, Inter, Roboto, system fonts, Space Grotesk. Pair a characterful display font with a refined body font.
+
+## Color
+Commit to a cohesive palette. Use CSS variables. Dominant colors with sharp accents outperform timid, evenly-distributed palettes. **Avoid**: purple gradients on white (AI slop).
+
+## Motion
+Focus on high-impact moments. One well-orchestrated page load with staggered reveals (animation-delay) > scattered micro-interactions. Use scroll-triggering and hover states that surprise. Prioritize CSS-only. Use Motion library for React when available.
+
+## Spatial Composition
+Unexpected layouts. Asymmetry. Overlap. Diagonal flow. Grid-breaking elements. Generous negative space OR controlled density.
+
+## Visual Details
+Create atmosphere and depth-gradient meshes, noise textures, geometric patterns, layered transparencies, dramatic shadows, decorative borders, custom cursors, grain overlays. Never default to solid colors.
+
+---
+
+# Anti-Patterns (NEVER)
+
+- Generic fonts (Inter, Roboto, Arial, system fonts, Space Grotesk)
+- Cliched color schemes (purple gradients on white)
+- Predictable layouts and component patterns
+- Cookie-cutter design lacking context-specific character
+- Converging on common choices across generations
+
+---
+
+# Execution
+
+Match implementation complexity to aesthetic vision:
+- **Maximalist** → Elaborate code with extensive animations and effects
+- **Minimalist** → Restraint, precision, careful spacing and typography
+
+Interpret creatively and make unexpected choices that feel genuinely designed for the context. No design should be the same. Vary between light and dark themes, different fonts, different aesthetics. You are capable of extraordinary creative work-don't hold back.
\ No newline at end of file
diff --git a/plugins/omo/skills/lsp/SKILL.md b/plugins/omo/skills/lsp/SKILL.md
new file mode 100644
index 00000000..36be0684
--- /dev/null
+++ b/plugins/omo/skills/lsp/SKILL.md
@@ -0,0 +1,35 @@
+---
+name: lsp
+description: Use when Codex needs language-server diagnostics, definitions, references, symbols, or rename safety checks in the current workspace.
+---
+
+# Codex LSP
+
+Call `lsp` MCP tools through the tool interface; `lsp.*`/`mcp__lsp__*` are tool-call names, not shell commands.
+
+## Tools
+
+- `lsp.status`: list configured, installed, missing, disabled, and active language servers.
+- `lsp.diagnostics`: check one file or directory for LSP diagnostics. Prefer `severity: "error"` after edits.
+- `lsp.goto_definition`: locate a symbol definition from file, line, and character.
+- `lsp.find_references`: find usages of a symbol across the workspace.
+- `lsp.symbols`: inspect document symbols or search workspace symbols.
+- `lsp.prepare_rename`: check whether a rename is valid at a position.
+- `lsp.rename`: apply a language-server workspace edit for a rename.
+
+## Config
+
+Project config lives at `.codex/lsp-client.json`; user config lives at `~/.codex/lsp-client.json`.
+
+```json
+{
+ "lsp": {
+ "typescript": {
+ "command": ["typescript-language-server", "--stdio"],
+ "extensions": [".ts", ".tsx", ".js", ".jsx"]
+ }
+ }
+}
+```
+
+Use `lsp.status` first when diagnostics report a missing language server.
diff --git a/plugins/omo/skills/programming/SKILL.md b/plugins/omo/skills/programming/SKILL.md
new file mode 100644
index 00000000..1bb0f79d
--- /dev/null
+++ b/plugins/omo/skills/programming/SKILL.md
@@ -0,0 +1,463 @@
+---
+name: programming
+description: "MUST USE for ANY work on .py .pyi .rs .ts .tsx .mts .cts .go files. One philosophy: strict types, modern stacks (Pydantic v2 / serde+thiserror / Zod / gin+sqlc+pgx+slog), modern toolchains (uv+basedpyright+ruff / cargo+clippy+miri / Bun+Biome+tsc / gofumpt+golangci-lint v2+nilaway+go-race), parse-don't-validate, exhaustive match, typed errors, no any/unwrap/panic, 250 LOC ceiling, TDD. Routes to references/{python,rust,typescript,rust-ub,go}/. Triggers: write/edit Python/Rust/TypeScript/Go code, new project, gin server, bubbletea TUI, CJK IME, connect-go RPC, sqlc pgx, branded ids, exhaustive match, unsafe Rust, miri, oversized file, refactor, TDD, e2e test, arena, allocator, bumpalo, const fn, const generics, comptime, zero-alloc, bitfield, repr, scopeguard, errdefer, Zig-like, zerocopy, packed struct."
+---
+
+# Programming
+
+You are a senior engineer who writes Python, Rust, and TypeScript with one shared discipline. **Type-strict. Stack-first. Async-correct. Architecturally honest about file size.**
+
+This skill is an index. The hard per-language rules live under `references/`. Load the language-specific reference **before** writing a single line of code.
+
+---
+
+## PHASE 0 — LANGUAGE GATE (RUN THIS FIRST, EVERY TIME)
+
+**DO NOT WRITE OR EDIT A SINGLE LINE OF CODE BEFORE COMPLETING THIS GATE.**
+
+1. **Identify the language** from the file extension or the user's request.
+2. **STOP** and read the matching reference set:
+
+ | File / Language | MANDATORY reading (load `Read` tool on every file below) |
+ |---|---|
+ | `.py`, `.pyi`, "Python" | `references/python/README.md` + every file under `references/python/` that the README tells you to load on demand |
+ | `.rs`, `Cargo.toml`, "Rust" | `references/rust/README.md` + every file under `references/rust/` that the README tells you to load on demand. **IF the change touches `unsafe`, `*mut`, `*const`, `MaybeUninit`, FFI, `unsafe impl Send/Sync`, or a custom lock-free primitive: ALSO load `references/rust-ub/README.md` plus every file under `references/rust-ub/`.** |
+ | `.ts`, `.tsx`, `.mts`, `.cts`, "TypeScript" | `references/typescript/README.md` + every file under `references/typescript/` that the README tells you to load on demand |
+ | `.go`, `go.mod`, `go.sum`, `.golangci.yml`, `*.proto` next to a Go module, "Go" / "Golang" | `references/go/README.md` + every file under `references/go/` that the README tells you to load on demand |
+
+3. Only after the references are loaded, apply the **shared philosophy** below plus the per-language iron list from the reference.
+
+**No exceptions for "small" or "one-off" code.** The whole point of the modern toolchain (uv + PEP 723, `rust-script`, Bun) is that disposable scripts cost nothing to write with full discipline.
+
+---
+
+## Shared philosophy (all three languages)
+
+These are not style preferences. They are the six axioms every recipe in `references/` derives from.
+
+1. **The type system is your proof system.** Make illegal states unrepresentable. The compiler / type checker is the cheapest test you will ever run. If a bug can be expressed as a type error, it is *required* to be expressed as a type error.
+
+2. **Parse, don't validate.** Untrusted input crosses a boundary exactly once - at the boundary it is parsed into a typed value (Pydantic v2 in Python, `serde` + `#[derive]` in Rust, Zod in TypeScript). Inside the boundary, code receives typed values and never re-validates. The boundary owns trust; the interior owns logic.
+
+3. **One name = one concept.** A `UserId` is not a `string`. A `Seconds` is not a `Milliseconds`. Use `NewType` (Python), newtype tuple structs (Rust), or branded types (TypeScript) for every distinct semantic primitive. The compiler refuses to let two semantic units mix.
+
+4. **Exhaustive variant matching, always.** Discriminated unions and enums are matched exhaustively. Python: `match` + `case unreachable: assert_never(unreachable)`. Rust: `match` (the compiler enforces). TypeScript: `switch` + `assertNever`. **`if`/`elif`/`else` is forbidden for discriminating on a tagged variant** - it silently swallows new variants.
+
+5. **Trust framework guarantees. Validate only at boundaries.** No null checks for values the type system already proves non-null. No `try/except` around code that cannot raise. No `unwrap`/`!`/`as` to paper over a contract you should have encoded in types. No defensive layer for a scenario you cannot name.
+
+6. **Test-driven, with the right shape of test.** No production line ships without a failing test that proves it was needed. Behavior is locked by tests, not by hope. See the TDD discipline below.
+
+---
+
+## TDD DISCIPLINE — NON-NEGOTIABLE
+
+**Every change follows the red → green → refactor loop.** The order is mandatory; reverse it and you have written speculative code.
+
+### The order
+
+1. **Red.** Write a failing test that names the behavior in `Given / When / Then`. Run it. *Confirm it fails for the right reason* — not a typo, not an import error. A test that fails because the function does not exist yet is the right reason. A test that fails because of a missing import is not.
+2. **Green.** Write the minimum code to make the test pass. Resist adding the second case until the first passes. The second case is the next red.
+3. **Refactor.** With the test green, restructure ruthlessly. The test is your safety net. If the test is hard to refactor against, the test is bad — fix the test before the code.
+
+### The shape of the test pyramid
+
+Every feature ships with all three rungs, sized in this proportion:
+
+| Rung | Count | Purpose | Speed budget |
+|---|---|---|---|
+| **Unit** | many | Pure-function correctness for every meaningful input class (happy + edges + boundaries + error paths) | < 10 ms each |
+| **Integration** | some | The real adapter against the real downstream (DB, queue, HTTP) — via `testcontainers`, `httptest`, or equivalent. NEVER a unit test pretending to be integration. | < 1 s each |
+| **E2E scenario** | few | One narrative per user-visible outcome. Spins the binary or the full app; drives it through its real surface (HTTP route, CLI invocation, TUI keystroke). Asserts the *observable outcome*, not internal state. | seconds, run on CI |
+
+If a feature has zero E2E coverage, it is undone — even if every unit test passes.
+
+### Given / When / Then is mandatory
+
+Every test — unit, integration, E2E — is structured by these three blocks. Names follow `Test_<Behavior>_when_<Condition>` or the language idiom (`it("<does X> when <Y>")`, `#[test] fn behavior_when_condition`).
+
+```
+Given: the preconditions and fixtures
+When: the single action under test
+Then: the observable outcome AND only that outcome
+```
+
+One `When` per test. Multiple `When`s = multiple tests. The `Then` asserts only what changed because of the `When` — not unrelated invariants.
+
+### Less mock, the better
+
+Mocks are a last resort, not a default. The priority order:
+
+1. **Real object.** Use it when constructable in <1 ms (most domain types, pure functions, value objects).
+2. **In-memory fake.** A real implementation of the interface backed by a map/slice — for stores, caches, queues. The fake has its OWN test that proves it behaves like the real one.
+3. **Testcontainer / sandbox.** Real Postgres, real Redis, real S3-compatible (MinIO), via `testcontainers`. Slow but truthful.
+4. **HTTP-level fake.** `httptest.Server` (Go), `respx` (Python), `msw` (TS) — fake at the wire, not at the SDK.
+5. **Mock.** Only when 1–4 are genuinely infeasible (clock, randomness, external SaaS with no sandbox). Then mock the **narrowest** seam — never an entire service. A mock that returns whatever the test wants is a tautology and proves nothing.
+
+**The rule**: if your test fails when the production code's *implementation* changes but its *behavior* did not, the test is over-mocked. Delete the mock; assert on observable outputs.
+
+### Efficient AND accurate — both, not either
+
+- **Accurate**: the test fails for the bug it names, and only that bug. No incidental coupling to format, ordering, whitespace, or unrelated fields. Assert on the *contract*, not on the dump.
+- **Efficient**: the whole unit suite runs in < 30 seconds on a developer laptop. The whole integration suite in < 5 minutes. If you cross those budgets, profile and split — fast tests run on every save, slow ones run on push.
+- **Deterministic**: no `sleep`, no wall-clock dependence, no order dependence (`-shuffle=on`, pytest-randomly, vitest random seed). Inject a `Clock`. Subscribe to the event, do not poll for it. Time-based flake is a bug, not a test issue.
+- **Isolated**: every test starts from a known fixture and tears down. `t.TempDir()`, `t.Setenv()`, transactional rollback for DB tests. Two tests passing individually but failing together is a fixture leak — fix it immediately.
+
+### Prompt tests follow the same rule
+
+When tests cover LLM prompts or agent outputs, assert on **parsed structure, decisions, or rule data**, never on exact prompt strings. Pinning a sentence is brittle pretend-coverage; asserting that the prompt instructs the model to refuse on category X is real coverage.
+
+### Anti-patterns the skill rejects
+
+| Anti-pattern | Why it fails | Fix |
+|---|---|---|
+| Writing code first, tests "to add later" | Tests-after rationalize the existing design, even when wrong. | Red first. Always. |
+| One mega-test asserting 12 things | First failure hides the next 11. | Split by `Then` clause — one assertion class per test. |
+| Mocking every collaborator | Test passes regardless of real behavior. | Use a fake or the real thing. Mock only true unmockables. |
+| `time.sleep(0.1)` to "let it finish" | Flake guaranteed. | Subscribe to the completion signal; bounded await. |
+| Snapshot tests for everything | Locks formatting, not behavior. | Snapshots for *structure* (CLI help, JSON shape). Assertions for *behavior*. |
+| Removing a failing test to "unblock CI" | You just deleted a bug report. | Fix the code or fix the test — never delete to silence. |
+| `assert result is not None` and stopping there | Passes when result is garbage. | Assert the *value*, not its existence. |
+| Single happy-path E2E, no edges | Most bugs live on edges. | Edges are unit-test territory — but include at least one E2E that exercises an error path. |
+
+---
+
+## Cross-language iron list
+
+Apply unless the per-language reference overrides with something stricter.
+
+| Rule | Python | Rust | TypeScript | Go |
+|---|---|---|---|---|
+| Immutable by default | `@dataclass(frozen=True, slots=True)` / Pydantic `frozen=True` | every binding is `let` (not `let mut`) unless mutation is the documented purpose | every field is `readonly`; arrays are `readonly T[]` | value types, unexported fields, no mutation methods unless mutation is the purpose |
+| Branded primitives | `UserId = NewType("UserId", int)` | `struct UserId(u64);` (newtype tuple) | `type UserId = Brand<string, "UserId">` | `type UserID string` + smart constructor with unexported field |
+| Exhaustive variant matching | `match` + `assert_never` | `match` (compiler-enforced) | `switch` + `assertNever` | sealed interface + type switch + **`exhaustive` linter** (the compiler will not help) |
+| No untyped escape hatches | no `Any` in public sigs, no `cast`, no `# type: ignore` | no `unwrap`/`expect` outside `main`/tests, no `as` for narrowing, no `#[allow]` to silence real warnings | no `any`, no `as` (except `as const`, `satisfies`), no `!`, no `@ts-ignore`, no `@ts-expect-error` | no `interface{}` / bare `any` in domain sigs; no `_ = err`; no `//nolint` without reason |
+| No bare error strings | typed exception dataclass with `__str__` | `thiserror` enum (lib) or `anyhow` with `.context(...)` (app) | `Error` subclass with typed fields | sentinel `errors.New` + typed `*XError` struct; wrap with `%w`; check via `errors.Is/As` |
+| Boundary catch only | catch the exact exception you expect; broad `except Exception` only in `main()`, with logging + re-raise | `?` everywhere; never `panic!` in library code | `catch` must narrow with `instanceof` and re-throw or convert; no empty catch | every `(T, error)` checked; `panic` only in `main`/tests; one `httperr.Write` funnel in handlers |
+| Resources via RAII | `with` (sync) / `async with` (async) | `Drop` impl or RAII guard | `using`/`await using` (TC39 explicit resource management) | `defer x.Close()` immediately after acquisition; `bodyclose`/`sqlclosecheck` linters enforce |
+| Async runtime is mandatory | `anyio` (NEVER bare `asyncio`) | `tokio` (`async-std` is unmaintained) | platform-native async (Bun/Node) with structured cancellation via `AbortSignal` | `context.Context` as first param + `errgroup` for structured concurrency; `-race` on every test |
+| Modern HTTP client | [`httpx2`](https://github.com/pydantic/httpx2) with HTTP/2 + brotli + zstd | `reqwest` with rustls | `ky` (default) / `undici` direct API (Node perf) - NEVER bare `fetch` in prod | stdlib `net/http.Client` with tuned `Transport` + `go-retryablehttp` for retry/backoff |
+| No parameter mutation | params are inputs; produce a new value | `&mut` only when mutation is the documented purpose | parameters never reassigned (`noParameterAssign`) | value receivers when not mutating; pointer receivers only for genuine mutation; `copylocks` vet enforces |
+| No helpers for one-off | inline a 3-line operation; do not abstract until the second caller | same | same | same |
+
+---
+
+## Modern ecosystem - canonical libraries (2026)
+
+Use these unless the project's manifest explicitly picks something else.
+
+| Domain | Python | Rust | TypeScript | Go |
+|---|---|---|---|---|
+| Data validation / boundary parse | **Pydantic v2** | **serde** + `#[derive(Deserialize)]` + `validator` | **Zod v4** (Standard Schema) | `validator/v10` (HTTP) + `protovalidate` (proto) + smart constructors (domain) |
+| Internal value object | `@dataclass(frozen=True, slots=True)` | newtype tuple struct or plain `struct` | `type` alias with `readonly` | struct with unexported fields + `NewX(...)` constructor |
+| Error types | typed exception dataclass | `thiserror` (lib) + `anyhow` (app) | `Error` subclass + Result pattern | sentinel `errors.New` + typed `*XError` struct + `%w` wrap |
+| HTTP client | [`httpx2`](https://github.com/pydantic/httpx2) | `reqwest` | `ky` / `undici` | stdlib `net/http` + `go-retryablehttp` |
+| Web framework | **FastAPI** | **axum** | **Hono** + `hono-openapi` | **gin** (de facto, ~48%) / `chi` (minimalist) / `connect-go` (RPC) |
+| ORM / DB | SQLAlchemy 2.x async + `asyncpg` | `sqlx` (compile-time checked) | **Drizzle** | **sqlc** (codegen from `.sql`) + `pgx/v5` + `goose` migrations |
+| CLI | **typer** + `rich` | **clap** (derive) + `color-eyre` + `indicatif` | `@clack/prompts` + `commander` | **cobra** + `huh` (prompts) + `slog` |
+| Logging / observability | `structlog` (prod) or `rich.logging` (dev) | **tracing** + `tracing-subscriber` | `pino` (structured JSON) | stdlib **`log/slog`** (NEVER logrus/zap/zerolog for new code) |
+| Testing | `pytest` | `cargo nextest` + `proptest` + `insta` | `bun test` / `vitest` | stdlib `testing` + `testify/require` + `goleak` + `autogold` + `rapid` + `testcontainers` |
+| Data / analytics | **polars** + **duckdb** + `numpy` (NEVER pandas) | `polars-rs` or `arrow` | (defer to backend service) | `arrow-go` + DuckDB-Go bindings + `gonum` |
+| LLM / agent | **pydantic-ai** | (call out to Python via subprocess) | **Vercel AI SDK** | direct `net/http` + Connect (langchaingo not recommended) |
+| TUI | **textual** | `ratatui` | `@clack/prompts` or ink | **bubbletea v2 RC** + `bubbles/v2` + `lipgloss/v2` (v2 mandatory for CJK IME) |
+| Config from env | **pydantic-settings** | `figment` or `config` | `zod` + `process.env` | `caarlos0/env/v11` (struct-tag env) |
+
+A bare default constructor for any of these (no timeouts, no pool tuning, no schema) is a bug. See the per-language reference for the canonical production defaults.
+
+---
+
+## Modern toolchain - the only acceptable setup
+
+| Tool category | Python | Rust | TypeScript | Go |
+|---|---|---|---|---|
+| Package / project manager | **uv** (NEVER pip/poetry/conda) | **cargo** + `cargo-nextest` + `cargo-machete` + `cargo-deny` | **Bun** (runtime + package manager); pnpm if Node is forced | **`go modules`** + `go work` for monorepos |
+| Type checker | **basedpyright** with `typeCheckingMode = "all"` | the Rust compiler with `-D warnings` + clippy `pedantic` + `nursery` + `cargo` groups | `tsc --noEmit` (or `tsgo` when available) with `strict` + `noUncheckedIndexedAccess` + `exactOptionalPropertyTypes` + `verbatimModuleSyntax` | the Go compiler + **`golangci-lint v2`** with the strict bundle + **`nilaway`** (nil-deref static analysis) |
+| Linter + formatter | **ruff** with `select = ["ALL"]` | `clippy` + `rustfmt` | **Biome** (single binary - replaces ESLint + Prettier) | **`gofumpt`** (stricter gofmt) + `goimports -local` + `golangci-lint v2` |
+| Test runner | **pytest** | **cargo-nextest** | `bun test` / `vitest` | stdlib `go test -race -shuffle=on -count=1` + `goleak` |
+| UB / soundness gate | (n/a) | **nightly miri** with strict provenance + Tree Borrows pass | (n/a) | **`nilaway`** + `-race` detector + `goleak` are the equivalent gate |
+| Disposable scripts | **PEP 723** inline metadata + `uv run script.py` | **rust-script** with inline `Cargo.toml` block | `bun run script.ts` | `//go:build ignore` + `go run script.go` |
+| Bootstrap a new project | `scripts/python/new-project.py` | `scripts/rust/new-project.py` | `scripts/typescript/new-project.ts` | `scripts/go/new-project.py` |
+| Pre-commit / CI gate | `ruff check . && basedpyright && pytest` | `cargo +nightly clippy -- -D warnings && cargo nextest run && cargo +nightly miri test` | `bunx biome check . && bunx tsc --noEmit && bun test` | `gofumpt -l . && golangci-lint run ./... && nilaway ./... && go test -race -shuffle=on -count=1 ./...` |
+
+A `tsconfig.json` with `"strict": true` alone is **not** strict. The reference enumerates the additional flags. Same for `pyproject.toml` and `Cargo.toml` - the references contain the canonical full configuration.
+
+---
+
+## THE 250 PURE LOC CEILING (NON-NEGOTIABLE)
+
+**A source file whose pure LOC (non-blank, non-comment lines) exceeds 250 is architecturally broken.** Not a style preference. Not a soft suggestion. **A defect.**
+
+A file past this line is telling you, loudly:
+
+- The module is doing more than one thing.
+- Multiple cohesive units got merged "to save a file".
+- Re-exports, barrels, and orchestrators got fused into pure-logic units.
+- Every future reader pays a tax to find what they need.
+
+### Why 250 and not 500 or 1000
+
+At 250 pure LOC a file still fits in one screen on a 32-inch monitor with a 14pt font. A reviewer can hold the whole thing in working memory and spot a cross-cutting bug. At 500 LOC they cannot. At 1000 LOC they stop trying. The number is **the cognitive ceiling of a single human reviewer who has not memorized the file.**
+
+### Measuring pure LOC
+
+```bash
+# Quick (line-comment + blank exclusion - good enough for Python, Rust, TypeScript):
+awk '!/^[[:space:]]*$/ && !/^[[:space:]]*(\/\/|#|--)/' <file> | wc -l
+
+# Authoritative (handles block comments correctly):
+cloc --by-file <file> # the "code" column is the number that matters
+```
+
+### Required behavior
+
+**Creating a file that will exceed 250 pure LOC.** STOP. Split it **before the first commit**. Carve by responsibility (single-responsibility principle), one cohesive unit per file. Use a barrel (`__init__.py`, `mod.rs`, `index.ts`) for re-exports ONLY. **Never** for logic.
+
+**Editing a file that already exceeds 250 pure LOC and your edit adds lines.** STOP. Refactor the unit you are touching into its own file BEFORE adding the new lines. The split is part of THIS task, not a follow-up someone will never do.
+
+**Reading a file that exceeds 250 pure LOC while implementing a feature.** Surface the smell explicitly in your reply, propose a concrete split (which functions go where, in 1-2 lines each), and ask the user whether to split now or carry the smell into the feature work. Do not silently keep going.
+
+### Forbidden escapes
+
+- Counting comments and blank lines toward the budget. **Pure LOC means code lines.** Period.
+- Splitting by token count (`foo_1.py`, `module_part_A.rs`, `service-2.ts`). **REJECT.** Split by what each file DOES. Name each file after the concept it owns.
+- Catch-all dump files: `utils.py`, `helpers.ts`, `lib.rs` (as a logic dump), `common.py`, `shared.ts`. **REJECT.** These just relocate the smell.
+- "It's generated, so it's fine." Only true if the file lives in `dist/`, `target/`, `__generated__/`, or wherever the build authoritatively rewrites. Hand-edited "I will regenerate it later" files do NOT qualify.
+- "It's a test file with many cases." Split by SUT or by behavior cluster. One file per cohesive `describe` group.
+- "230 pure LOC, close enough." A 230-LOC file about to grow is already over the line. Split now. **Do not race to the ceiling.**
+
+### Acceptable exceptions (rare, require justification)
+
+A file may legitimately exceed 250 pure LOC if **and only if** it is:
+
+- A **truly indivisible single-responsibility unit** (e.g., a generated parser table, a state machine whose states share a single closure, a `derive` macro implementation). Mark the first 5 lines with a comment such as `# noqa: SIZE_OK - generated parser table, 612 states share branch tables` (Python) / `// allow: SIZE_OK - state machine, removing any state breaks the transition matrix` (Rust/TS), and explain WHY no split is possible.
+- A **pure data table** (translation strings, error code lookup, brand color palette). Tables of data are not logic.
+
+**`# noqa: SIZE_OK` without a justifying comment is itself slop** and must be rejected by the next person to touch the file.
+
+### Concrete split examples
+
+#### Python - BEFORE (`user_service.py`, 412 pure LOC, broken)
+
+```python
+# user_service.py - DOES TOO MUCH
+class UserRepository: ... # 90 LOC of SQLAlchemy
+class UserValidator: ... # 60 LOC of Pydantic + business rules
+class PasswordHasher: ... # 40 LOC of bcrypt wrapper
+class EmailSender: ... # 50 LOC of httpx2 client
+class UserService: ... # 130 LOC orchestrating the four above
+def _build_query(...): ... # 25 LOC helper
+def _format_email(...): ... # 17 LOC helper
+```
+
+#### Python - AFTER (split by responsibility)
+
+```
+src/myapp/users/
+├── __init__.py # barrel: re-exports UserService only (5 LOC)
+├── repository.py # UserRepository (~95 LOC)
+├── validator.py # UserValidator (~65 LOC)
+├── password.py # PasswordHasher (~45 LOC)
+├── notifier.py # EmailSender (renamed - the role, not the verb)
+├── service.py # UserService (orchestrator) (~135 LOC)
+└── _queries.py # _build_query (private) (~30 LOC)
+```
+
+Every file is < 250 pure LOC. Each owns one concept. The barrel exposes the only public name. The reviewer never has to scroll through password hashing to understand SMTP retry policy.
+
+#### Rust - BEFORE (`auth.rs`, 380 pure LOC)
+
+```rust
+// auth.rs - DOES TOO MUCH
+pub struct Session { ... } // 40 LOC
+impl Session { ... } // 90 LOC of methods
+pub struct TokenIssuer { ... } // 30 LOC
+impl TokenIssuer { ... } // 70 LOC
+pub struct RateLimiter { ... } // 50 LOC
+impl RateLimiter { ... } // 70 LOC
+fn parse_authorization_header(...) { ... } // 30 LOC
+```
+
+#### Rust - AFTER
+
+```
+src/auth/
+├── mod.rs # re-exports Session, TokenIssuer, RateLimiter (8 LOC)
+├── session.rs # Session + impl (~130 LOC)
+├── token.rs # TokenIssuer + impl (~100 LOC)
+├── rate_limit.rs # RateLimiter + impl (~120 LOC)
+└── header.rs # parse_authorization_header (~35 LOC)
+```
+
+#### TypeScript - BEFORE (`api/orders.ts`, 510 pure LOC)
+
+```typescript
+// api/orders.ts - DOES TOO MUCH
+export const OrderSchema = z.object({ ... }) // 30 LOC
+type Order = z.infer<typeof OrderSchema>
+export class OrderRepository { ... } // 110 LOC
+export class PricingEngine { ... } // 130 LOC
+export class TaxCalculator { ... } // 90 LOC
+export class OrderService { ... } // 150 LOC
+```
+
+#### TypeScript - AFTER
+
+```
+src/orders/
+├── index.ts # barrel (6 LOC)
+├── schema.ts # OrderSchema + Order type (~35 LOC)
+├── repository.ts # OrderRepository (~115 LOC)
+├── pricing.ts # PricingEngine (~135 LOC)
+├── tax.ts # TaxCalculator (~95 LOC)
+└── service.ts # OrderService (orchestrator) (~155 LOC)
+```
+
+---
+
+## MANDATORY POST-WRITE REVIEW LOOP
+
+**This runs EVERY time you finish writing or substantively editing code, before you claim the task is done.** No exceptions.
+
+### Step 1 — measure
+
+For every file you created or modified:
+
+```bash
+awk '!/^[[:space:]]*$/ && !/^[[:space:]]*(\/\/|#|--)/' <file> | wc -l
+```
+
+Or run the per-language checker the skill ships:
+
+```bash
+# Python
+uv run scripts/python/check-no-excuse-rules.py <changed paths>
+# Rust
+bash scripts/rust/check-no-excuse-rules.sh <changed paths>
+# TypeScript
+bun run scripts/typescript/check-no-excuse-rules.ts <changed paths>
+```
+
+### Step 2 — interpret
+
+| Pure LOC | Verdict | Required action |
+|---|---|---|
+| ≤ 200 | Healthy | continue |
+| 200 - 250 | **Warning band** - the file is approaching the ceiling. State that fact explicitly in the next message and propose a split if the next planned edit will add lines. |
+| > 250 | **DEFECT** - the architecture is wrong. Do NOT commit. Refactor into smaller cohesive units **now**, in this same task. |
+
+### Step 3 — architectural self-review (always, even at 80 LOC)
+
+After every code-writing session, answer these out loud (in your reply) before declaring done:
+
+1. **Single responsibility?** Can I name what this file owns in one short noun phrase? If the answer needs the word "and", split.
+2. **Boundary purity?** Did I parse untrusted input into a typed value at the boundary, or did I pass `dict[str, Any]` / `serde_json::Value` / `unknown` past the boundary? If the latter, fix it.
+3. **Variant discrimination?** Did I use `if`/`elif`/`else` (or `switch` without `assertNever`, or `match` without `assert_never`) anywhere to discriminate on a tagged type or enum? If yes, rewrite as exhaustive match.
+4. **Escape hatches?** Any `Any`, `# type: ignore`, `unwrap`, `expect` outside `main`/tests, `as` numeric cast, `!`, `@ts-ignore`, `@ts-expect-error`, `#[allow]` on a real warning? If yes, fix the type or document why with a comment.
+5. **Defensive layer?** Any null check, try/except, or `isinstance` guarding a value the type system already proves? If yes, delete.
+6. **Helpers for one-off?** Any function, class, or trait introduced for a single caller that will never get a second caller? If yes, inline.
+7. **Tests?** Is the behavior I just introduced locked by a test that would fail if I revert this commit?
+
+**If any answer fails, fix it before declaring done.** This loop is the difference between "the code compiles" and "the code is correct."
+
+### Step 4 — if you need to refactor right now, invoke the right skill
+
+- The file you just wrote (or an adjacent one) is over 250 pure LOC, or step 3 surfaced more than two issues: **load the `refactor` skill** and execute its safe-refactor protocol (codemap, plan, LSP-driven edits, test after each step). Do not improvise a refactor under time pressure - the refactor skill exists precisely so you do not corrupt behavior while reshaping structure.
+- You inherited a branch with AI-generated patterns (broad `except`, redundant null checks, vague TODOs, oversized modules, dead helpers): **load the `remove-ai-slops` skill** to do a categorized branch-scope cleanup with regression tests pinned first.
+
+These two skills are not optional cosmetics. They are the recovery path for the defects this loop is designed to catch.
+
+---
+
+## Companion skills - explicit invocation triggers
+
+| Trigger | Skill to load | Why |
+|---|---|---|
+| File exceeds 250 pure LOC, OR the post-write loop surfaces 2+ issues, OR the user says "reshape this", "extract this", "clean this up" | `refactor` | Safe codemap-driven multi-step refactor with LSP + tests after each step. Never improvise a structural change. |
+| Recent branch contains AI-authored code that smells (broad except, dead helpers, vague comments, oversized files), OR the user says "remove slop", "clean AI code", "deslop" | `remove-ai-slops` | Tests pinned FIRST, then categorized parallel cleanup, then quality gates. Behavior-preserving. |
+| Rust code touches `unsafe`, `*mut`, `*const`, `MaybeUninit`, FFI, `unsafe impl Send/Sync`, or a custom lock-free primitive | `references/rust-ub/` | Full UB taxonomy + Miri strictness escalation. Every `unsafe` block must survive Miri Level 3 (strict provenance + symbolic alignment + preemption) before it ships. |
+
+---
+
+## Per-language jump table
+
+**Stop. Read the matching reference fully before writing code.**
+
+### Python (`.py`, `.pyi`)
+
+**READ `references/python/README.md` FIRST.** Then load on demand:
+
+| Need | Load |
+|---|---|
+| Strict pyproject.toml / basedpyright / ruff config | `references/python/pyproject-strict.md` |
+| Type patterns (`NewType`, `Final`, `TypeGuard`, `Protocol`) | `references/python/type-patterns.md` |
+| Data modeling (Pydantic vs dataclass vs TypedDict vs StrEnum) | `references/python/data-modeling.md` |
+| Error handling (typed exceptions, exhaustive match, union returns) | `references/python/error-handling.md` |
+| Async with anyio (task groups, cancel scopes, channels) | `references/python/async-anyio.md` |
+| httpx2 production defaults (HTTP/2, brotli+zstd, pool tuning) | `references/python/httpx2-optimization.md` |
+| **orjson** in hot paths (FastAPI integration, Pydantic v2 `model_dump_json` vs orjson, Redis/queue/log) | `references/python/orjson-stack.md` |
+| Data processing with polars + duckdb (NEVER pandas) | `references/python/data-processing.md` |
+| FastAPI + SQLAlchemy 2.x async stack | `references/python/fastapi-stack.md` |
+| pydantic-ai agents | `references/python/pydantic-ai.md` |
+| Textual TUI | `references/python/textual-tui.md` |
+| Disposable PEP 723 scripts | `references/python/one-liners.md` |
+| Canonical library defaults | `references/python/libraries.md` |
+
+### Rust (`.rs`, `Cargo.toml`)
+
+**READ `references/rust/README.md` FIRST.** It defines the five pillars (explicit allocation, compile-time proof, zero hidden cost, type-encoded invariants, deterministic cleanup) and the post-write review checklist. Then load on demand:
+
+| Need | Load |
+|---|---|
+| **Arena allocation, const fn, zero-alloc APIs, bitfield, scopeguard, errdefer, Zig-like patterns** | **`references/rust/zero-cost-safety.md`** |
+| Strict `Cargo.toml` lints + profile + workspace config | `references/rust/cargo-strict.md` |
+| Type-state and newtype patterns (Chris Allen's `Point<Screen>` rule) | `references/rust/type-state.md` |
+| `unsafe` discipline (safe wrapper + SAFETY comment + miri proof) | `references/rust/unsafe-discipline.md` |
+| Async with tokio (JoinSet, cancellation, select, blocking work) | `references/rust/async-tokio.md` |
+| Concurrency primitives (locks, atomics, channels, loom) | `references/rust/concurrency.md` |
+| axum + sqlx + tracing + tower HTTP stack | `references/rust/axum-stack.md` |
+| clap + color-eyre + tracing + indicatif CLI stack | `references/rust/clap-stack.md` |
+| Property tests (proptest) + snapshot tests (insta) | `references/rust/proptest-insta.md` |
+| Disposable `rust-script` scripts | `references/rust/one-liners.md` |
+| Canonical library defaults | `references/rust/libraries.md` |
+| **ANY `unsafe` / FFI / `MaybeUninit` / lock-free work** | **`references/rust-ub/` (full directory)** |
+
+### TypeScript (`.ts`, `.tsx`, `.mts`, `.cts`)
+
+**READ `references/typescript/README.md` FIRST.** Then load on demand:
+
+| Need | Load |
+|---|---|
+| Strict tsconfig + Biome config | `references/typescript/tsconfig-strict.md` |
+| Type patterns (branded types, `as const`, `satisfies`, narrowing, `assertNever`) | `references/typescript/type-patterns.md` |
+| Data modeling (type vs interface vs Zod, readonly, parse-don't-validate) | `references/typescript/data-modeling.md` |
+| Error handling (Result, typed errors, union vs throw, AbortSignal timeouts) | `references/typescript/error-handling.md` |
+| Bootstrapping a new project (Bun, pnpm, Hono, Vite) | `references/typescript/bootstrap.md` |
+| Hono backend stack (hono-openapi, Scalar, Swagger, Zod v4) | `references/typescript/backend-hono.md` |
+
+### Go (`.go`, `go.mod`, `go.sum`, `.golangci.yml`, `*.proto`)
+
+**READ `references/go/README.md` FIRST.** Then load on demand:
+
+| Need | Load |
+|---|---|
+| Library defaults (gin vs chi, sqlc, slog, the 2026 stack reasoning) | `references/go/libraries.md` |
+| Canonical strict `.golangci.yml` (v2) with per-linter rationale | `references/go/golangci-strict.md` |
+| Project layout, Taskfile, CI, `go.mod` template | `references/go/bootstrap.md` |
+| Type patterns (named types, smart constructors, sealed interfaces, generics) | `references/go/type-patterns.md` |
+| Data modeling — the three layers of validation (validator/v10 → smart ctor → sqlc) | `references/go/data-modeling.md` |
+| Error handling (`errors.Is/As`, typed errors, `%w` wrapping, no panic) | `references/go/error-handling.md` |
+| Concurrency (`context.Context`, `errgroup`, channels, locks, `-race`, `goleak`) | `references/go/concurrency.md` |
+| HTTP backend stack (gin + slog + validator + pgx, middleware ordering, SSE, WS) | `references/go/backend-stack.md` |
+| RPC stack (Connect-Go default, grpc-go fallback, protovalidate, Buf) | `references/go/grpc-connect.md` |
+| CLI stack (cobra + slog + huh) | `references/go/cobra-stack.md` |
+| Database stack (sqlc + pgx + goose + testcontainers) | `references/go/sqlc-pgx.md` |
+| TUI stack (bubbletea v2 + bubbles v2 + lipgloss v2; **CJK / IME support**) | `references/go/bubbletea-v2.md` |
+| Testing (Given/When/Then, table-driven, fakes-over-mocks, autogold, rapid) | `references/go/testing.md` |
+| Disposable `go run` scripts | `references/go/one-liners.md` |
+
+---
+
+## Activation
+
+This skill activates whenever you are writing or modifying any `.py`, `.pyi`, `.rs`, `.ts`, `.tsx`, `.mts`, `.cts`, `.go` file, or any project manifest (`pyproject.toml`, `Cargo.toml`, `package.json`, `tsconfig.json`, `biome.json`, `go.mod`, `go.sum`, `.golangci.yml`, `Taskfile.yml`, `buf.yaml`, `sqlc.yaml`). **Even one-off scripts get the full treatment** - that is the whole point of `uv run` + PEP 723, `rust-script`, `bun run`, and `go run` + `//go:build ignore`: production hygiene with throwaway ergonomics.
+
+The references contain the recipes. **Read them before writing code. Re-read them when the model drifts.** The post-write review loop is non-negotiable.
diff --git a/plugins/omo/skills/programming/references/go/README.md b/plugins/omo/skills/programming/references/go/README.md
new file mode 100644
index 00000000..41257132
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/README.md
@@ -0,0 +1,90 @@
+
+# Go Programmer
+
+Production Go in 2026. **Boring on purpose, strict by tooling, illegal states unrepresentable by convention.**
+
+## Philosophy
+
+Go gives you fewer type-system tools than Python, TypeScript, or Rust:
+
+- No sum types — only `interface{}` with type-switch.
+- No exhaustiveness check from the compiler — only the `exhaustive` linter.
+- No `Option<T>` — only `nil` and the eternal trap of "is this nil interface or nil concrete?".
+- No `Result<T, E>` — only `(T, error)`, no compiler enforcement of unwrapping.
+- No newtype that prevents primitive coercion — `type UserID string` is still implicitly convertible from a literal when used carelessly.
+
+**This is the whole point of the skill.** Where the language is weak, the linter bundle becomes the type checker, and code patterns become the type system. Treat `golangci-lint v2` with the configuration in `golangci-strict.md` as if it were `tsc --strict` or `basedpyright`. Treat `nilaway` and `go test -race` as if they were Miri.
+
+The skill enforces five non-negotiables:
+
+1. **Parse-don't-validate at every boundary.** HTTP/RPC/CLI/config gets parsed into a domain struct constructed only via `New*(...)` smart constructors. Once inside the domain, no further validation. See `data-modeling.md`.
+2. **`(T, error)` everywhere.** No panics in library code. No bare `_ = err`. Errors are wrapped with `%w` and asserted with `errors.Is` / `errors.As`. Typed error structs for anything a caller can branch on. See `error-handling.md`.
+3. **Sealed interfaces for variants.** Sum types via a sealed unexported method, dispatched through a `type switch`, with the `exhaustive` linter checking completeness. See `type-patterns.md`.
+4. **`context.Context` is the first parameter.** Always. No `context.Background()` inside leaf functions. No goroutine without context-driven shutdown. No `time.Now()` in domain code — inject a clock. See `concurrency.md`.
+5. **Generated, not hand-written, for external contracts.** `sqlc` for DB, `oapi-codegen` for OpenAPI servers and clients, `protoc-gen-go` + `protoc-gen-connect-go` for RPC. Hand-rolled marshalling is a regression. See `sqlc-pgx.md`, `grpc-connect.md`.
+
+## Hard rules — tooling
+
+| Category | Use | Never |
+|---|---|---|
+| Go version | **1.23+** (range-over-func, iter package, slog stable) | <1.22 |
+| Module | `go modules` + `go work` for monorepos | dep, GOPATH layouts |
+| Format | **`gofumpt`** (stricter gofmt) + `goimports -local <module>` | bare `gofmt` |
+| Linter | **`golangci-lint v2`** with the strict bundle in `golangci-strict.md` | bare `go vet` |
+| Nil checker | **`nilaway`** (Uber, stable since 2024) in CI | hope |
+| Vet bundle | `go vet` + `fieldalignment` + `shadow` | "tests cover it" |
+| Tests | `go test -race -shuffle=on -count=1` | `-count` cache, no race |
+| Goroutine leaks | `go.uber.org/goleak` in `TestMain` | "looks fine" |
+| Mock | `go.uber.org/mock` (gomock successor) | hand-written stubs |
+| DB | `sqlc` + `jackc/pgx/v5` | `database/sql` + `gorm` |
+| HTTP framework | **`gin-gonic/gin`** (de facto, ~48% of Go API repos) — `go-chi/chi` for minimalist, `connectrpc/connect-go` for RPC | `echo` (smaller eco), `fiber` (fasthttp = non-stdlib), `gorilla/mux` (in maintenance mode) |
+| RPC | **`connectrpc/connect-go`** (gRPC-compatible, HTTP/1.1-friendly, browser-friendly) | hand-rolled `grpc-go` unless you specifically need bidi streaming features Connect lacks |
+| Validation | `go-playground/validator/v10` for HTTP boundary + `bufbuild/protovalidate-go` for proto + smart constructors for domain | ad-hoc `if len(s) == 0` chains |
+| Config | `caarlos0/env/v11` (struct-tag env) | `viper` unless you actually need file+env+flag merging |
+| Logging | **`log/slog`** (stdlib, Go 1.21+) | logrus, zap, zerolog (all superseded) |
+| CLI | `spf13/cobra` | hand-rolled `os.Args` parsing past 2 flags |
+| TUI | `charm.land/bubbletea/v2` + `bubbles/v2` + `lipgloss/v2` — see `bubbletea-v2.md` for CJK/IME | bubbletea v1 if you need IME |
+
+A single CI command should be the gate:
+
+```bash
+gofumpt -l . && \
+ golangci-lint run ./... && \
+ nilaway ./... && \
+ go test -race -shuffle=on -count=1 ./...
+```
+
+If any of these fails, the change is not done. Period. The bundle is set up so a clean run actually means clean — see `golangci-strict.md` for the per-linter rationale and the deliberate `nolint:` policy.
+
+## Hard rules — code
+
+Read these per-file references for the canonical patterns:
+
+- **Types & data** → `type-patterns.md`, `data-modeling.md` — branded named types, smart constructors with unexported fields, sealed interfaces as sum types.
+- **Errors** → `error-handling.md` — sentinel vs typed struct, `errors.Is/As`, `%w` wrapping, no panic in libraries, the `errorlint` ruleset.
+- **Concurrency** → `concurrency.md` — `context.Context` discipline, `errgroup`, `sync.OnceValue`, `goleak`, `-race`, channel selection rules.
+- **HTTP backend** → `backend-stack.md` — `gin` server skeleton, middleware ordering, SSE/streaming with `http.Flusher`, structured slog logging, graceful shutdown — distilled from the CLIProxyAPI codebase (a real proxy serving OpenAI/Gemini/Claude APIs).
+- **RPC** → `grpc-connect.md` — when to pick Connect vs grpc-go, codegen pipeline, protovalidate, streaming.
+- **DB** → `sqlc-pgx.md` — compile-time-safe SQL via sqlc + pgx connection pool + migrations via goose + testcontainers in CI.
+- **CLI** → `cobra-stack.md` — cobra layout, slog integration, graceful shutdown on signals, fang-style colored help.
+- **TUI** → `bubbletea-v2.md` — v2 model, `SetVirtualCursor(false)` + `tea.View{Cursor}` for CJK IME, why v1 was broken for Korean/Japanese/Chinese input.
+- **Testing** → `testing.md` — table-driven tests, `require` vs `assert`, `autogold` snapshots, `gopter` property tests, `testcontainers` for integration, `goleak` for goroutine leaks.
+- **Bootstrap** → `bootstrap.md` — `new-project.go` invocation, project layout (`cmd/`, `internal/`, `pkg/`), Taskfile, CI.
+- **Strict config** → `golangci-strict.md` — the canonical `.golangci.yml` with the full linter whitelist and per-linter rationale.
+- **One-liners** → `one-liners.md` — `go run` scripts with `//go:build ignore`, `gorun`-style invocation.
+
+## The 250 pure LOC ceiling
+
+Same rule as Python/Rust/TS: a `.go` file whose pure LOC (non-blank, non-comment) exceeds 250 is architecturally broken. Go encourages many small files in a single package, so this is *more* natural here than elsewhere — split by responsibility, keep one cohesive type and its methods per file.
+
+The `cmd/server/main.go` is the most common violator. Refactor it: `main.go` only wires `os.Args` → `cmd.Execute()`. Anything else lives in `internal/`.
+
+## Existing codebases — non-strict project
+
+When editing an existing `.go` file that doesn't follow these rules: **write new code in strict style, don't refactor existing code in the same change.** Use the `remove-ai-slops` skill for branch-scope cleanup.
+
+## Activation
+
+This skill activates whenever you write or modify any `.go` file, `go.mod`, `go.sum`, `.golangci.yml`, `Taskfile.yml`, or any of the codegen specs (`*.proto`, `*.sql` next to `sqlc.yaml`, `openapi.yaml` next to `oapi-codegen.yaml`). Even one-off scripts get the strict treatment — that is what `//go:build ignore` + `go run` is for: production hygiene with throwaway ergonomics.
+
+The references contain the recipes. **Read them before writing code. Re-read them when the model drifts.** The post-write architectural review loop is non-negotiable.
diff --git a/plugins/omo/skills/programming/references/go/backend-stack.md b/plugins/omo/skills/programming/references/go/backend-stack.md
new file mode 100644
index 00000000..a9ffd89c
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/backend-stack.md
@@ -0,0 +1,641 @@
+# HTTP Backend Stack — gin + slog + validator + pgx
+
+The canonical production HTTP service skeleton. Distilled from the [CLIProxyAPI](https://github.com/router-for-me/CLIProxyAPI) codebase — a real proxy serving OpenAI / Gemini / Claude / Codex APIs in production, with SSE streaming, WebSocket upgrades, request logging, and hot-reload config.
+
+If you are tempted to pick echo or chi instead, see `libraries.md` — gin wins on ecosystem, not technical merit, and the win is large enough to matter.
+
+---
+
+## `go.mod`
+
+```go
+module github.com/your-org/myservice
+
+go 1.23
+
+require (
+ github.com/gin-gonic/gin v1.10.1
+ github.com/go-playground/validator/v10 v10.22.1
+ github.com/caarlos0/env/v11 v11.2.2
+ github.com/google/uuid v1.6.0
+ github.com/jackc/pgx/v5 v5.7.6
+ golang.org/x/sync v0.18.0
+)
+```
+
+---
+
+## Project structure
+
+```
+cmd/server/main.go # ≤ 50 LOC; flags → run.Execute(ctx)
+internal/
+ cmd/run.go # ~150 LOC; signal handling, config load, server.Run
+ config/config.go # env-driven Config struct
+ api/
+ server.go # gin.Engine setup, route mounting, http.Server
+ middleware/
+ request_id.go
+ request_logging.go
+ auth.go
+ recovery.go
+ cors.go
+ handlers/
+ users.go # one file per resource
+ streams.go # SSE / WebSocket endpoints
+ domain/ # smart-constructor types (Email, UserID, ...)
+ service/ # business logic
+ store/ # pgx + sqlc
+ obs/
+ logger.go # slog setup
+```
+
+---
+
+## `cmd/server/main.go`
+
+```go
+package main
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/your-org/myservice/internal/cmd"
+)
+
+func main() {
+ ctx, stop := signal.NotifyContext(context.Background(),
+ syscall.SIGINT, syscall.SIGTERM)
+ defer stop()
+
+ if err := cmd.Execute(ctx); err != nil {
+ slog.Error("fatal", slog.Any("err", err))
+ os.Exit(1)
+ }
+}
+```
+
+That is the entire `main`. Anything more is a smell.
+
+---
+
+## `internal/config/config.go`
+
+```go
+package config
+
+import (
+ "time"
+ "github.com/caarlos0/env/v11"
+)
+
+type Config struct {
+ Host string `env:"HOST" envDefault:"0.0.0.0"`
+ Port int `env:"PORT" envDefault:"8080"`
+ DatabaseURL string `env:"DATABASE_URL,required"`
+ ReadTimeout time.Duration `env:"READ_TIMEOUT" envDefault:"15s"`
+ WriteTimeout time.Duration `env:"WRITE_TIMEOUT" envDefault:"30s"`
+ ShutdownTimeout time.Duration `env:"SHUTDOWN_TIMEOUT" envDefault:"20s"`
+ LogLevel string `env:"LOG_LEVEL" envDefault:"info"`
+ LogFormat string `env:"LOG_FORMAT" envDefault:"json"`
+ Env string `env:"ENV" envDefault:"development"`
+}
+
+func Load() (Config, error) {
+ var cfg Config
+ if err := env.Parse(&cfg); err != nil {
+ return Config{}, err
+ }
+ return cfg, nil
+}
+```
+
+---
+
+## `internal/obs/logger.go`
+
+```go
+package obs
+
+import (
+ "context"
+ "log/slog"
+ "os"
+)
+
+type ctxKey struct{ name string }
+var requestIDKey = ctxKey{"request_id"}
+
+func NewLogger(level, format string) *slog.Logger {
+ var lvl slog.Level
+ _ = lvl.UnmarshalText([]byte(level))
+
+ opts := &slog.HandlerOptions{Level: lvl, AddSource: true}
+
+ var h slog.Handler
+ switch format {
+ case "text":
+ h = slog.NewTextHandler(os.Stdout, opts)
+ default:
+ h = slog.NewJSONHandler(os.Stdout, opts)
+ }
+ return slog.New(&ctxHandler{Handler: h})
+}
+
+// ctxHandler pulls request_id from ctx into every log line.
+type ctxHandler struct{ slog.Handler }
+
+func (h *ctxHandler) Handle(ctx context.Context, r slog.Record) error {
+ if id, ok := ctx.Value(requestIDKey).(string); ok && id != "" {
+ r.AddAttrs(slog.String("request_id", id))
+ }
+ return h.Handler.Handle(ctx, r)
+}
+
+func WithRequestID(ctx context.Context, id string) context.Context {
+ return context.WithValue(ctx, requestIDKey, id)
+}
+```
+
+---
+
+## `internal/api/server.go`
+
+```go
+package api
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+ "github.com/your-org/myservice/internal/api/handlers"
+ "github.com/your-org/myservice/internal/api/middleware"
+ "github.com/your-org/myservice/internal/config"
+)
+
+type Server struct {
+ cfg config.Config
+ srv *http.Server
+ logger *slog.Logger
+}
+
+func New(cfg config.Config, logger *slog.Logger, h *handlers.Handler) *Server {
+ gin.SetMode(gin.ReleaseMode)
+ r := gin.New()
+
+ // Middleware order matters — see "Middleware ordering" below.
+ r.Use(
+ middleware.RequestID(), // 1. assign request_id first
+ middleware.Recovery(logger), // 2. recovery wraps everything
+ middleware.RequestLogger(logger),
+ middleware.CORS(),
+ )
+
+ h.Mount(r)
+
+ return &Server{
+ cfg: cfg,
+ logger: logger,
+ srv: &http.Server{
+ Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
+ Handler: r,
+ ReadTimeout: cfg.ReadTimeout,
+ WriteTimeout: cfg.WriteTimeout,
+ },
+ }
+}
+
+func (s *Server) Run(ctx context.Context) error {
+ errCh := make(chan error, 1)
+ go func() {
+ s.logger.InfoContext(ctx, "server starting",
+ slog.String("addr", s.srv.Addr))
+ if err := s.srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+ errCh <- err
+ }
+ close(errCh)
+ }()
+
+ select {
+ case <-ctx.Done():
+ s.logger.InfoContext(ctx, "shutdown signal received")
+ shutdownCtx, cancel := context.WithTimeout(
+ context.Background(), s.cfg.ShutdownTimeout)
+ defer cancel()
+ return s.srv.Shutdown(shutdownCtx)
+ case err := <-errCh:
+ return err
+ }
+}
+```
+
+Notes:
+
+- `gin.New()` not `gin.Default()` — `Default()` adds `Logger()` (text format, not slog) and `Recovery()` (no logger injection). We replace both.
+- `gin.SetMode(gin.ReleaseMode)` silences debug output. Production assumed.
+- `http.Server` with explicit timeouts. The default `nil` timeouts are a DoS waiting to happen.
+- Graceful shutdown: SIGINT/SIGTERM cancels the ctx → `Shutdown(shutdownCtx)` gives in-flight requests up to `ShutdownTimeout` to finish.
+
+---
+
+## Middleware ordering — the rule that actually matters
+
+```
+RequestID → Recovery → Logger → CORS → Auth → Handler
+ (1) (2) (3) (4) (5)
+```
+
+1. **RequestID** is first so every subsequent middleware sees it.
+2. **Recovery** wraps everything after it. Order: a panic in CORS still gets caught.
+3. **Logger** sees the request_id and the recovered panic.
+4. **CORS** before Auth — OPTIONS preflight must return without auth.
+5. **Auth** is the last cross-cutting middleware. Per-route auth (admin-only) is mounted on a sub-router with extra middleware.
+
+```go
+// Public routes — no auth
+api := r.Group("/api/v1")
+{
+ api.POST("/auth/login", h.Login)
+ api.GET("/healthz", h.Healthz)
+}
+
+// Authenticated routes
+authed := r.Group("/api/v1", middleware.Auth(authSvc))
+{
+ authed.GET("/users/:id", h.GetUser)
+ authed.POST("/users", h.CreateUser)
+}
+
+// Admin-only routes
+admin := r.Group("/api/v1/admin",
+ middleware.Auth(authSvc),
+ middleware.RequireRole("admin"))
+{
+ admin.GET("/users", h.ListAllUsers)
+}
+```
+
+---
+
+## Middleware examples
+
+### `middleware/request_id.go`
+
+```go
+package middleware
+
+import (
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+ "github.com/your-org/myservice/internal/obs"
+)
+
+func RequestID() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ id := c.GetHeader("X-Request-ID")
+ if id == "" {
+ id = uuid.Must(uuid.NewV7()).String()
+ }
+ c.Request = c.Request.WithContext(obs.WithRequestID(c.Request.Context(), id))
+ c.Header("X-Request-ID", id)
+ c.Next()
+ }
+}
+```
+
+### `middleware/recovery.go`
+
+```go
+package middleware
+
+import (
+ "log/slog"
+ "net/http"
+ "runtime/debug"
+
+ "github.com/gin-gonic/gin"
+)
+
+func Recovery(logger *slog.Logger) gin.HandlerFunc {
+ return func(c *gin.Context) {
+ defer func() {
+ if r := recover(); r != nil {
+ logger.ErrorContext(c.Request.Context(), "panic recovered",
+ slog.Any("panic", r),
+ slog.String("stack", string(debug.Stack())),
+ )
+ if !c.Writer.Written() {
+ c.JSON(http.StatusInternalServerError,
+ gin.H{"error": "internal_error"})
+ }
+ c.Abort()
+ }
+ }()
+ c.Next()
+ }
+}
+```
+
+### `middleware/request_logging.go`
+
+```go
+func RequestLogger(logger *slog.Logger) gin.HandlerFunc {
+ return func(c *gin.Context) {
+ start := time.Now()
+ c.Next()
+ logger.InfoContext(c.Request.Context(), "http request",
+ slog.String("method", c.Request.Method),
+ slog.String("path", c.Request.URL.Path),
+ slog.Int("status", c.Writer.Status()),
+ slog.Int("bytes", c.Writer.Size()),
+ slog.Duration("elapsed", time.Since(start)),
+ slog.String("ip", c.ClientIP()),
+ )
+ }
+}
+```
+
+The `sloglint` linter enforces typed attrs (`slog.String(...)`) over `slog.Any("path", ...)`. Keep the form.
+
+### `middleware/cors.go`
+
+```go
+func CORS() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ c.Header("Access-Control-Allow-Origin", "*")
+ c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
+ c.Header("Access-Control-Allow-Headers", "*")
+ if c.Request.Method == http.MethodOptions {
+ c.AbortWithStatus(http.StatusNoContent)
+ return
+ }
+ c.Next()
+ }
+}
+```
+
+Note the explicit OPTIONS short-circuit — preflight must NOT go through Auth.
+
+---
+
+## Handlers — the canonical shape
+
+```go
+package handlers
+
+import (
+ "errors"
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+ "github.com/go-playground/validator/v10"
+ "github.com/your-org/myservice/internal/domain"
+ "github.com/your-org/myservice/internal/httperr"
+ "github.com/your-org/myservice/internal/service"
+)
+
+type Handler struct {
+ Users *service.UserService
+}
+
+func (h *Handler) Mount(r gin.IRouter) {
+ api := r.Group("/api/v1")
+ api.POST("/users", h.CreateUser)
+ api.GET("/users/:id", h.GetUser)
+}
+
+type createUserReq struct {
+ Email string `json:"email" binding:"required,email"`
+ Username string `json:"username" binding:"required,alphanum,min=3,max=32"`
+}
+
+func (h *Handler) CreateUser(c *gin.Context) {
+ var req createUserReq
+ if err := c.ShouldBindJSON(&req); err != nil {
+ writeBindingError(c, err)
+ return
+ }
+
+ email, err := domain.NewEmail(req.Email)
+ if err != nil {
+ httperr.Write(c, err)
+ return
+ }
+ username, err := domain.NewUsername(req.Username)
+ if err != nil {
+ httperr.Write(c, err)
+ return
+ }
+
+ user, err := h.Users.Create(c.Request.Context(), email, username)
+ if err != nil {
+ httperr.Write(c, err)
+ return
+ }
+ c.JSON(http.StatusCreated, user)
+}
+
+func writeBindingError(c *gin.Context, err error) {
+ var vErr validator.ValidationErrors
+ if errors.As(err, &vErr) {
+ out := make(map[string]string, len(vErr))
+ for _, fe := range vErr {
+ out[fe.Field()] = fe.Tag()
+ }
+ c.JSON(http.StatusBadRequest, gin.H{"errors": out})
+ return
+ }
+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid_json"})
+}
+```
+
+See `data-modeling.md` for the validator tag reference; see `error-handling.md` for the `httperr.Write` funnel.
+
+---
+
+## SSE streaming — the production pattern
+
+CLIProxyAPI streams OpenAI-compatible SSE for hundreds of concurrent clients. The pattern:
+
+```go
+func (h *Handler) StreamChat(c *gin.Context) {
+ ctx, cancel := context.WithCancel(c.Request.Context())
+ defer cancel()
+
+ // 1. Set SSE headers BEFORE writing any body
+ c.Header("Content-Type", "text/event-stream")
+ c.Header("Cache-Control", "no-cache")
+ c.Header("Connection", "keep-alive")
+ c.Header("X-Accel-Buffering", "no") // disable nginx buffering
+
+ // 2. Obtain the flusher — REQUIRED for streaming
+ flusher, ok := c.Writer.(http.Flusher)
+ if !ok {
+ httperr.Write(c, errors.New("streaming unsupported"))
+ return
+ }
+
+ // 3. Pull chunks from upstream
+ chunks, errs := h.svc.StreamCompletions(ctx, req)
+
+ for {
+ select {
+ case <-ctx.Done():
+ return // client disconnected, ctx cancelled
+ case chunk, ok := <-chunks:
+ if !ok {
+ fmt.Fprint(c.Writer, "data: [DONE]\n\n")
+ flusher.Flush()
+ return
+ }
+ fmt.Fprintf(c.Writer, "data: %s\n\n", chunk)
+ flusher.Flush()
+ case err := <-errs:
+ // Error mid-stream — emit as SSE event and bail
+ fmt.Fprintf(c.Writer, "event: error\ndata: %s\n\n", err.Error())
+ flusher.Flush()
+ return
+ }
+ }
+}
+```
+
+Key facts:
+
+- **Headers MUST be set before the first `Write`.** Otherwise gin auto-sets `Content-Type: text/plain`.
+- **`c.Writer.(http.Flusher)` is the streaming primitive.** Without `flusher.Flush()`, the response is buffered and arrives as one blob at the end.
+- **Always respond to `<-ctx.Done()`.** A disconnected client must stop upstream work — otherwise you generate tokens for nothing.
+- **The trailing `\n\n` per event is wire-mandatory** for SSE parsing. Missing it = the client never sees the event.
+
+---
+
+## WebSocket upgrade
+
+```go
+import "github.com/gorilla/websocket" // still the canonical WS lib in 2026
+
+var upgrader = websocket.Upgrader{
+ ReadBufferSize: 4096,
+ WriteBufferSize: 4096,
+ CheckOrigin: func(r *http.Request) bool {
+ // tighten in production
+ return true
+ },
+}
+
+func (h *Handler) WebSocketEcho(c *gin.Context) {
+ conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
+ if err != nil {
+ slog.ErrorContext(c.Request.Context(), "ws upgrade failed", slog.Any("err", err))
+ return
+ }
+ defer conn.Close()
+
+ for {
+ mt, msg, err := conn.ReadMessage()
+ if err != nil { return }
+ if err := conn.WriteMessage(mt, msg); err != nil { return }
+ }
+}
+```
+
+For long-lived connections, use `conn.SetReadDeadline` + `SetPongHandler` for keepalive. CLIProxyAPI's `wsrelay` package is a reference implementation.
+
+---
+
+## Database wiring — pgx pool, injected, never global
+
+```go
+package store
+
+import (
+ "context"
+ "fmt"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
+ cfg, err := pgxpool.ParseConfig(dsn)
+ if err != nil {
+ return nil, fmt.Errorf("parse dsn: %w", err)
+ }
+ cfg.MaxConns = 25
+ cfg.MinConns = 5
+ cfg.MaxConnLifetime = time.Hour
+ cfg.MaxConnIdleTime = 30 * time.Minute
+
+ pool, err := pgxpool.NewWithConfig(ctx, cfg)
+ if err != nil {
+ return nil, fmt.Errorf("connect: %w", err)
+ }
+ if err := pool.Ping(ctx); err != nil {
+ pool.Close()
+ return nil, fmt.Errorf("ping: %w", err)
+ }
+ return pool, nil
+}
+```
+
+See `sqlc-pgx.md` for queries.
+
+---
+
+## Healthcheck
+
+```go
+func (h *Handler) Healthz(c *gin.Context) {
+ if err := h.pool.Ping(c.Request.Context()); err != nil {
+ c.JSON(503, gin.H{"db": "down", "error": err.Error()})
+ return
+ }
+ c.JSON(200, gin.H{"ok": true})
+}
+```
+
+Mount BEFORE auth. Health checks must be unauthenticated.
+
+---
+
+## Testing the server
+
+```go
+func TestCreateUser_returns_201_for_valid_input(t *testing.T) {
+ // Given
+ h := newTestHandler(t)
+ r := gin.New()
+ h.Mount(r)
+
+ body := `{"email":"[email protected]","username":"alice"}`
+ req := httptest.NewRequest("POST", "/api/v1/users", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+
+ // When
+ r.ServeHTTP(rec, req)
+
+ // Then
+ require.Equal(t, http.StatusCreated, rec.Code)
+ var got struct{ ID string `json:"id"` }
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
+ require.NotEmpty(t, got.ID)
+}
+```
+
+See `testing.md` for full patterns (testcontainers integration, table-driven, goleak).
+
+---
+
+## Sources
+
+- gin docs: https://gin-gonic.com/docs/
+- CLIProxyAPI (reference impl): https://github.com/router-for-me/CLIProxyAPI
+- pgx pool: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool
+- SSE spec: https://html.spec.whatwg.org/multipage/server-sent-events.html
+- Go's `http.Server` graceful shutdown: https://pkg.go.dev/net/http#Server.Shutdown
diff --git a/plugins/omo/skills/programming/references/go/bootstrap.md b/plugins/omo/skills/programming/references/go/bootstrap.md
new file mode 100644
index 00000000..ff44dbc3
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/bootstrap.md
@@ -0,0 +1,328 @@
+# Bootstrap — Project Layout, Toolchain, Taskfile, CI
+
+What every new Go project gets in the first 60 seconds. Drop the script in `scripts/go/new-project.go` does all of this — this document explains *what* it produces and *why*.
+
+## Toolchain pin
+
+`go.work` (monorepo) or just rely on `go.mod`'s `go 1.23` directive (single module). Go 1.21+ auto-downloads matching toolchain when the local `go` binary is older. **No `.tool-versions` / `asdf` / `mise` indirection required** unless your shop standardizes on it.
+
+```bash
+# Confirm a working toolchain
+go env GOTOOLCHAIN # should be "auto" or your pinned version
+go version # ≥ 1.23
+```
+
+## Required global installs
+
+These are CLI tools, installed once per machine via `go install`:
+
+```bash
+go install mvdan.cc/gofumpt@latest
+go install golang.org/x/tools/cmd/goimports@latest
+go install github.com/golangci/golangci-lint/cmd/[email protected]
+go install go.uber.org/nilaway/cmd/nilaway@latest
+go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest
+go install github.com/pressly/goose/v3/cmd/goose@latest
+go install go.uber.org/mock/mockgen@latest
+go install github.com/go-task/task/v3/cmd/task@latest
+```
+
+For Connect/protobuf projects, additionally:
+
+```bash
+go install github.com/bufbuild/buf/cmd/buf@latest
+go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
+go install connectrpc.com/connect/cmd/protoc-gen-connect-go@latest
+```
+
+## Project layout — the canonical tree
+
+```
+myservice/
+├── go.mod
+├── go.sum
+├── Taskfile.yml # task runner
+├── .golangci.yml # see golangci-strict.md
+├── .editorconfig
+├── .gitignore
+├── README.md
+├── AGENTS.md # agent-readable project facts
+├── cmd/
+│ └── server/
+│ └── main.go # ONLY: parse flags, call cmd.Execute(); ≤ 50 LOC
+├── internal/ # NEVER importable from outside this module
+│ ├── api/ # transport layer (gin/connect routers)
+│ │ ├── server.go # gin engine setup, route registration
+│ │ ├── middleware/
+│ │ │ ├── request_id.go
+│ │ │ ├── logging.go
+│ │ │ └── auth.go
+│ │ └── handlers/
+│ │ ├── users.go
+│ │ └── users_test.go
+│ ├── domain/ # parse-don't-validate types, smart constructors
+│ │ ├── user.go
+│ │ └── email.go
+│ ├── service/ # business logic, depends on domain only
+│ │ └── user_service.go
+│ ├── store/ # persistence; sqlc-generated code lives here
+│ │ ├── sqlc/ # sqlc-generated, do not hand-edit
+│ │ ├── queries/ # *.sql files sqlc reads
+│ │ └── migrations/ # goose migrations
+│ ├── config/ # env-driven config (caarlos0/env)
+│ │ └── config.go
+│ └── obs/ # observability: slog setup, otel, healthz
+│ └── logger.go
+├── pkg/ # exportable libraries — only if you publish
+│ └── …
+├── proto/ # *.proto definitions (Connect/gRPC projects)
+│ └── service.proto
+├── gen/ # generated code (Connect, OpenAPI)
+│ └── service/v1/
+│ ├── service.pb.go
+│ └── servicev1connect/
+├── test/ # cross-cutting test helpers, fixtures
+└── .github/workflows/ci.yml
+```
+
+**Rules**:
+
+- `cmd/<binary>/main.go` is ≤ 50 LOC. Anything more lives in `internal/cmd/`.
+- `internal/` is **the** business code. Other modules cannot import it (Go compiler-enforced).
+- `pkg/` is for things you genuinely want third parties to import. Empty until proven otherwise.
+- No `utils/`, `helpers/`, `common/`, `shared/`. **REJECT.** Files are named after the concept they own.
+- One package per directory. One responsibility per package.
+
+## `Taskfile.yml` — the entry point for every action
+
+`go-task/task` is the modern Make replacement. Cross-platform, YAML, fast.
+
+```yaml
+version: '3'
+
+vars:
+ BINARY: server
+ PKG: ./cmd/server
+
+tasks:
+ default:
+ deps: [fmt, lint, test]
+
+ fmt:
+ desc: Format all Go files
+ cmds:
+ - gofumpt -w .
+ - goimports -w -local "$(go list -m)" .
+
+ lint:
+ desc: Run all linters
+ cmds:
+ - golangci-lint run --timeout 5m ./...
+ - nilaway -include-pkgs "$(go list -m)/..." ./...
+
+ test:
+ desc: Run tests with race detector
+ cmds:
+ - go test -race -shuffle=on -count=1 ./...
+
+ test-cover:
+ desc: Coverage report
+ cmds:
+ - go test -race -shuffle=on -count=1 -coverprofile=coverage.out ./...
+ - go tool cover -html=coverage.out -o coverage.html
+
+ build:
+ desc: Build the binary
+ cmds:
+ - go build -trimpath -ldflags="-s -w" -o bin/{{.BINARY}} {{.PKG}}
+
+ run:
+ desc: Run the server locally
+ deps: [build]
+ cmds:
+ - ./bin/{{.BINARY}}
+
+ gen:
+ desc: Run all code generators
+ cmds:
+ - task: gen:sqlc
+ - task: gen:mocks
+ - task: gen:proto
+
+ gen:sqlc:
+ cmds:
+ - sqlc generate
+ sources:
+ - internal/store/queries/*.sql
+ - internal/store/sqlc.yaml
+ generates:
+ - internal/store/sqlc/*.go
+
+ gen:mocks:
+ cmds:
+ - go generate ./...
+
+ gen:proto:
+ cmds:
+ - buf generate
+ sources:
+ - proto/**/*.proto
+ - buf.yaml
+ - buf.gen.yaml
+
+ migrate:up:
+ cmds:
+ - goose -dir internal/store/migrations postgres "$DATABASE_URL" up
+
+ migrate:down:
+ cmds:
+ - goose -dir internal/store/migrations postgres "$DATABASE_URL" down
+
+ ci:
+ desc: Everything CI does, locally
+ deps: [fmt, lint, test, build]
+```
+
+`task` (no args) runs format + lint + test in parallel where possible. `task ci` runs the full pipeline.
+
+## `go.mod` template
+
+```go
+module github.com/your-org/myservice
+
+go 1.23
+
+require (
+ github.com/caarlos0/env/v11 v11.2.2
+ github.com/gin-gonic/gin v1.10.1
+ github.com/go-playground/validator/v10 v10.22.1
+ github.com/google/uuid v1.6.0
+ github.com/jackc/pgx/v5 v5.7.6
+ golang.org/x/sync v0.18.0
+)
+```
+
+Only direct deps listed; `go mod tidy` populates indirects.
+
+## `.editorconfig`
+
+```ini
+root = true
+
+[*]
+indent_style = tab
+indent_size = 4
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+
+[*.{yml,yaml,json,md}]
+indent_style = space
+indent_size = 2
+```
+
+## `.gitignore`
+
+```gitignore
+bin/
+coverage.out
+coverage.html
+*.test
+*.prof
+
+# IDE
+.idea/
+.vscode/
+*.swp
+
+# Local env
+.env
+.env.local
+
+# Secrets
+*.pem
+*.key
+```
+
+## CI — minimal GitHub Actions
+
+`.github/workflows/ci.yml`:
+
+```yaml
+name: ci
+on:
+ pull_request:
+ push:
+ branches: [main]
+
+jobs:
+ ci:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: '1.23'
+ cache: true
+
+ - name: Install tools
+ run: |
+ go install mvdan.cc/gofumpt@latest
+ go install github.com/golangci/golangci-lint/cmd/[email protected]
+ go install go.uber.org/nilaway/cmd/nilaway@latest
+ go install github.com/go-task/task/v3/cmd/task@latest
+
+ - name: Format check
+ run: gofumpt -l . | (! grep .)
+
+ - name: Lint
+ run: golangci-lint run --timeout 5m ./...
+
+ - name: Nilaway
+ run: nilaway ./...
+
+ - name: Test
+ run: go test -race -shuffle=on -count=1 ./...
+
+ - name: Build
+ run: go build -trimpath ./...
+```
+
+The order matters: format → lint → nilaway → test → build. Fail fast on the cheap checks.
+
+## `AGENTS.md` — agent-readable project facts
+
+Every new project gets an `AGENTS.md` at the root. The content is **machine-friendly**: short, declarative, no marketing prose. Example:
+
+```markdown
+# AGENTS.md
+
+Go 1.23+ HTTP service for {one-line purpose}.
+
+## Commands
+- `task` — fmt + lint + test
+- `task build` — produce ./bin/server
+- `task gen` — regenerate sqlc + mocks + proto
+
+## Architecture
+- `cmd/server/main.go` — entrypoint, ≤50 LOC
+- `internal/api/` — gin handlers + middleware
+- `internal/domain/` — smart-constructor types, no I/O
+- `internal/store/sqlc/` — generated; never hand-edit
+
+## Conventions
+- `slog` for all logs; never `log.*`, never `fmt.Println`
+- `context.Context` first arg for every public function
+- Errors wrapped with `%w`; check with `errors.Is/As`
+- 250 pure LOC ceiling per file — split before adding lines
+```
+
+The skill's `cmd/new-project.go` writes this file with project-specific values filled in.
+
+## Sources
+
+- Go modules reference: https://go.dev/ref/mod
+- go-task: https://taskfile.dev
+- golangci-lint v2: https://golangci-lint.run/docs/configuration/
+- Standard project layout debate: https://go.dev/doc/modules/layout (NOT `golang-standards/project-layout` — that repo is community, not official)
diff --git a/plugins/omo/skills/programming/references/go/bubbletea-v2.md b/plugins/omo/skills/programming/references/go/bubbletea-v2.md
new file mode 100644
index 00000000..6e8f44eb
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/bubbletea-v2.md
@@ -0,0 +1,360 @@
+# Bubbletea v2 — TUI with First-Class CJK / IME Support
+
+The TUI stack for 2026. Use **v2 RC**, not v1. If your users include Korean, Japanese, or Chinese speakers, v1 is broken — IME composition lands in the wrong cells. v2 fixes this. This document is the canonical setup.
+
+The reference implementation this document is distilled from: [`code-yeongyu/bubbletea-wm`](https://github.com/code-yeongyu/bubbletea-wm) — a floating window manager built specifically to nail down v2 + IME.
+
+---
+
+## Why v2 (not v1) — the IME story
+
+Bubbletea v1 manages cursor positioning in software ("virtual cursor"). It draws a `█` at the cursor position. The terminal's *real* cursor stays at `(0, 0)`.
+
+This breaks every CJK input method. IME candidate windows (the popup showing 가/각/간 for Korean Hangul composition, kana → kanji for Japanese, pinyin lookup for Chinese) anchor to the terminal's **real** cursor position. With v1, the candidate window appears at top-left while you are typing somewhere in the middle of the screen.
+
+Bubbletea v2 fixes this with two changes:
+
+1. **`tea.View{Cursor: *tea.Cursor}`** — your `View()` method returns a view that *includes* the desired cursor position. The framework moves the terminal's real cursor there.
+2. **`textarea.SetVirtualCursor(false)`** — textareas no longer draw their own `█`. They expose `.Cursor()` so you can read where they want the real cursor.
+
+Together: IME popups appear where the user is typing. As they should.
+
+### Other v2 wins (incidental)
+
+- `tea.MouseClickMsg` / `MouseMotionMsg` / `MouseReleaseMsg` instead of one coarse `MouseMsg`.
+- Cleaner `View` struct with `AltScreen`, `MouseMode` fields instead of `tea.Cmd` setters.
+- Pluggable rendering pipeline; better performance under high message volume.
+
+---
+
+## `go.mod`
+
+```go
+module github.com/your-org/mytui
+
+go 1.23
+
+require (
+ charm.land/bubbletea/v2 v2.0.0-rc.2
+ charm.land/bubbles/v2 v2.0.0-rc.1
+ charm.land/lipgloss/v2 v2.0.0-beta.3
+ github.com/mattn/go-runewidth v0.0.19
+)
+```
+
+The packages live under `charm.land/` (NOT `github.com/charmbracelet/...`) for v2. This is the Charm team's deliberate import-path break to keep v2 separate from v1 until stable.
+
+---
+
+## Minimal app — the IME-correct skeleton
+
+```go
+package main
+
+import (
+ "fmt"
+ "log"
+
+ tea "charm.land/bubbletea/v2"
+ "charm.land/bubbles/v2/textarea"
+)
+
+type model struct {
+ width, height int
+ ta textarea.Model
+}
+
+func initial() model {
+ ta := textarea.New()
+ ta.Placeholder = "Type Korean / Japanese / Chinese here..."
+ ta.SetWidth(60)
+ ta.SetHeight(10)
+ ta.SetVirtualCursor(false) // ← THE LINE. Without this, IME breaks.
+ ta.Focus()
+ return model{ta: ta}
+}
+
+func (m model) Init() tea.Cmd { return textarea.Blink }
+
+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
+ switch msg := msg.(type) {
+ case tea.WindowSizeMsg:
+ m.width, m.height = msg.Width, msg.Height
+ case tea.KeyPressMsg:
+ if msg.String() == "ctrl+c" {
+ return m, tea.Quit
+ }
+ }
+ var cmd tea.Cmd
+ m.ta, cmd = m.ta.Update(msg)
+ return m, cmd
+}
+
+func (m model) View() tea.View {
+ var view tea.View
+ view.AltScreen = true
+ view.SetContent(m.ta.View())
+
+ // ── THE OTHER LINE. Position the REAL cursor for IME. ──
+ if cursor := m.ta.Cursor(); cursor != nil {
+ view.Cursor = cursor
+ }
+ return view
+}
+
+func main() {
+ if _, err := tea.NewProgram(initial(), tea.WithAltScreen()).Run(); err != nil {
+ log.Fatal(err)
+ }
+ fmt.Println("bye")
+}
+```
+
+The two lines that matter:
+
+1. `ta.SetVirtualCursor(false)` — disables the virtual `█`.
+2. `view.Cursor = cursor` (where `cursor = m.ta.Cursor()`) — exports the real cursor position to the framework.
+
+Without **both**, IME breaks.
+
+---
+
+## CJK width — go-runewidth, not `len()`
+
+Korean, Japanese, Chinese characters render as **two terminal cells** (wide characters per Unicode East Asian Width). Naive `len(string)` returns byte count, not display width. `utf8.RuneCountInString` returns rune count, also not display width.
+
+Use `github.com/mattn/go-runewidth`:
+
+```go
+import "github.com/mattn/go-runewidth"
+
+func displayWidth(s string) int {
+ return runewidth.StringWidth(s)
+}
+
+// Wide character occupies two cells; pad accordingly
+for _, r := range s {
+ cell := string(r)
+ w := runewidth.RuneWidth(r)
+ canvas = append(canvas, cell)
+ if w == 2 {
+ canvas = append(canvas, "") // placeholder for second cell
+ }
+}
+```
+
+`lipgloss/v2` uses `go-runewidth` internally — `lipgloss.Width("안녕")` returns 4, not 2. **If you measure outside lipgloss, you must call runewidth directly.**
+
+---
+
+## Mouse — v2 has typed events
+
+```go
+case tea.MouseClickMsg:
+ // msg.X, msg.Y, msg.Button
+ return m.handleClick(msg.X, msg.Y, msg.Button)
+
+case tea.MouseMotionMsg:
+ return m.handleHover(msg.X, msg.Y)
+
+case tea.MouseReleaseMsg:
+ return m.handleRelease(msg.X, msg.Y)
+```
+
+Enable mouse via the `View`:
+
+```go
+view.MouseMode = tea.MouseModeCellMotion // or MouseModeAll
+```
+
+`CellMotion` reports clicks + motion-while-button-pressed (drag). `MouseModeAll` reports motion always — heavier, only when you need hover.
+
+---
+
+## Components from `bubbles/v2`
+
+```go
+import (
+ "charm.land/bubbles/v2/textarea"
+ "charm.land/bubbles/v2/textinput"
+ "charm.land/bubbles/v2/spinner"
+ "charm.land/bubbles/v2/viewport"
+ "charm.land/bubbles/v2/list"
+ "charm.land/bubbles/v2/table"
+ "charm.land/bubbles/v2/help"
+ "charm.land/bubbles/v2/key"
+)
+```
+
+All v2 components support `SetVirtualCursor(false)` where they accept text input. Use it for every text input that users might type CJK into — and "might" should be assumed *yes*.
+
+---
+
+## Styling — `lipgloss/v2`
+
+```go
+import "charm.land/lipgloss/v2"
+
+titleStyle := lipgloss.NewStyle().
+ Bold(true).
+ Foreground(lipgloss.Color("230")).
+ Background(lipgloss.Color("62")).
+ Padding(0, 1).
+ Border(lipgloss.RoundedBorder()).
+ BorderForeground(lipgloss.Color("63"))
+
+rendered := titleStyle.Render("안녕하세요")
+```
+
+`lipgloss/v2` width and padding correctly account for CJK display width. v1 did too — this is not a v2-specific fix, just a reminder.
+
+---
+
+## Architecture pattern — Model–Update–View
+
+```
++--------------------------------------------+
+| tea.Program runs the event loop |
+| |
+| loop: |
+| msg <- queue |
+| model, cmd = model.Update(msg) |
+| view = model.View() |
+| render(view) |
+| if cmd != nil: go run(cmd) -> queue |
++--------------------------------------------+
+```
+
+Rules:
+
+- **Model is a value type, not a pointer.** Bubbletea calls `Update` with a value receiver and expects a new value returned. Pointer receivers cause subtle bugs where state mutation leaks across draws.
+- **`Update` is pure.** No I/O. No goroutines started inline. Any I/O returns a `tea.Cmd` — Bubbletea runs it in a goroutine and feeds the result back as a message.
+- **`View` is read-only.** It returns a `tea.View` without modifying state.
+- **`tea.Cmd` is `func() tea.Msg`.** It runs once, returns a message, exits. For repeating work, use `tea.Tick` or a self-resending command.
+
+```go
+// One-shot command
+func loadData() tea.Cmd {
+ return func() tea.Msg {
+ data, err := fetch()
+ if err != nil { return errMsg{err} }
+ return dataLoadedMsg{data}
+ }
+}
+
+// Periodic
+func tickEvery() tea.Cmd {
+ return tea.Tick(time.Second, func(t time.Time) tea.Msg {
+ return tickMsg{t}
+ })
+}
+```
+
+---
+
+## Splitting the model — sub-models
+
+```go
+type model struct {
+ list list.Model
+ input textinput.Model
+ spinner spinner.Model
+}
+
+func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
+ var cmds []tea.Cmd
+ var cmd tea.Cmd
+
+ m.list, cmd = m.list.Update(msg)
+ cmds = append(cmds, cmd)
+
+ m.input, cmd = m.input.Update(msg)
+ cmds = append(cmds, cmd)
+
+ m.spinner, cmd = m.spinner.Update(msg)
+ cmds = append(cmds, cmd)
+
+ return m, tea.Batch(cmds...)
+}
+```
+
+`tea.Batch` runs commands concurrently. The framework collects their results in the order they arrive.
+
+When the model exceeds 250 LOC, split by sub-model into separate files:
+
+```
+internal/ui/
+├── model.go # root model orchestration
+├── list.go # list sub-model state + update + view
+├── input.go # input sub-model
+└── spinner.go # spinner sub-model
+```
+
+---
+
+## Testing TUI code — `teatest`
+
+```go
+import "charm.land/bubbletea/v2/teatest"
+
+func TestModel_typing_korean_keeps_cursor_in_position(t *testing.T) {
+ // Given
+ m := initial()
+ tm := teatest.NewTestModel(t, m, teatest.WithInitialTermSize(80, 24))
+
+ // When — simulate typing "안녕"
+ tm.Send(tea.KeyPressMsg{Code: '안'})
+ tm.Send(tea.KeyPressMsg{Code: '녕'})
+
+ // Then
+ out := tm.FinalOutput(t)
+ require.Contains(t, string(out), "안녕")
+ // Cursor should be at column 4 (two wide chars = 4 cells)
+ // ...
+}
+```
+
+`teatest` lets you drive the model through synthetic messages and inspect the rendered output. Pair with `autogold` snapshots for full-view regression tests.
+
+---
+
+## Common antipatterns
+
+| Bad | Why | Good |
+|---|---|---|
+| `tea.Program` with `tea.WithoutSignals()` | Ctrl-C does not work | Default signal handling |
+| Pointer receivers on Model | Bubbletea expects value semantics | Value receivers, return new model |
+| `time.Sleep` inside `Update` | Blocks the event loop | `tea.Tick` or async `tea.Cmd` |
+| `fmt.Println` for debug | Corrupts the rendered output | `tea.Printf` for logging, or write to a file |
+| `len(s)` for CJK width | Off by 2x | `runewidth.StringWidth(s)` |
+| `Bubbletea v1` for an app with text input | Korean/Japanese IME breaks | v2 + `SetVirtualCursor(false)` |
+| Drawing your own `█` block cursor in v2 | Conflicts with `view.Cursor` | Let the terminal handle it |
+
+---
+
+## Performance — when v2 starts to crawl
+
+- **Reduce View frequency.** If the model changes 60 times/sec but the rendered view changes once/sec, gate redraws on a "dirty" flag.
+- **`viewport.Model` for scrollable content.** Avoid re-rendering thousands of lines on every keystroke.
+- **`Batch` your commands.** A series of synchronous `tea.Cmd` returns serializes; `tea.Batch` parallelizes.
+- **Profile with `tea.WithFPS(N)`** to cap repaint rate during development.
+
+---
+
+## When NOT to use Bubbletea
+
+- The app is one prompt + one answer. Use `huh` (also from Charm) — simpler, no Model–Update–View ceremony.
+- The app is a long-running daemon with occasional status output. Use `slog` to stderr and `tea.Program` only if interactivity becomes necessary.
+- The app must run as a non-tty subprocess (CI, redirected stdin). `tea.Program` requires a tty for input. Detect via `term.IsTerminal(int(os.Stdin.Fd()))` and fall back to a non-interactive path.
+
+---
+
+## Sources
+
+- bubbletea v2 RC: https://github.com/charmbracelet/bubbletea/tree/v2
+- bubbles v2: https://github.com/charmbracelet/bubbles/tree/v2
+- lipgloss v2: https://github.com/charmbracelet/lipgloss/tree/v2
+- bubbletea-wm (IME reference): https://github.com/code-yeongyu/bubbletea-wm
+- crush CLI (production IME impl): https://github.com/charmbracelet/crush
+- go-runewidth: https://github.com/mattn/go-runewidth
+- Unicode East Asian Width: https://www.unicode.org/reports/tr11/
diff --git a/plugins/omo/skills/programming/references/go/cobra-stack.md b/plugins/omo/skills/programming/references/go/cobra-stack.md
new file mode 100644
index 00000000..a73805f7
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/cobra-stack.md
@@ -0,0 +1,468 @@
+# CLI Stack — cobra + slog + caarlos0/env + signal handling
+
+The canonical Go CLI skeleton. `cobra` is the de facto framework — Kubernetes, Docker CLI, Helm, GitHub CLI, gh, Hugo all use it. Use it.
+
+---
+
+## Toolchain
+
+```bash
+go install github.com/spf13/cobra-cli@latest
+cobra-cli init mytool
+cobra-cli add server
+cobra-cli add migrate
+```
+
+`cobra-cli` scaffolds the `cmd/` package. Edit the result; do not regenerate.
+
+---
+
+## Layout
+
+```
+mytool/
+├── go.mod
+├── main.go # ≤ 30 LOC, calls cmd.Execute
+├── cmd/
+│ ├── root.go # rootCmd, persistent flags, slog setup
+│ ├── server.go # `mytool server` subcommand
+│ ├── migrate.go # `mytool migrate` subcommand
+│ └── version.go # `mytool version` — auto-injected version
+├── internal/
+│ ├── config/
+│ └── server/
+└── Taskfile.yml
+```
+
+---
+
+## `main.go`
+
+```go
+package main
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/your-org/mytool/cmd"
+)
+
+func main() {
+ ctx, stop := signal.NotifyContext(context.Background(),
+ syscall.SIGINT, syscall.SIGTERM)
+ defer stop()
+
+ if err := cmd.Execute(ctx); err != nil {
+ slog.Error("fatal", slog.Any("err", err))
+ os.Exit(1)
+ }
+}
+```
+
+`signal.NotifyContext` (Go 1.16+) gives every subcommand a ctx that cancels on Ctrl-C. Subcommands plumb the ctx into their workers.
+
+---
+
+## `cmd/root.go`
+
+```go
+package cmd
+
+import (
+ "context"
+ "log/slog"
+ "os"
+
+ "github.com/spf13/cobra"
+)
+
+var (
+ verbose bool
+ logFormat string
+ configPath string
+)
+
+var rootCmd = &cobra.Command{
+ Use: "mytool",
+ Short: "Short description of mytool",
+ Long: `Long description, prose; cobra wraps it for --help.`,
+ PersistentPreRunE: func(c *cobra.Command, args []string) error {
+ return setupLogger()
+ },
+ SilenceUsage: true, // don't print --help on every error
+ SilenceErrors: true, // we log them ourselves in Execute
+}
+
+func init() {
+ rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false,
+ "enable debug logging")
+ rootCmd.PersistentFlags().StringVar(&logFormat, "log-format", "text",
+ "log format: text or json")
+ rootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", "",
+ "path to config file (optional)")
+}
+
+func Execute(ctx context.Context) error {
+ return rootCmd.ExecuteContext(ctx)
+}
+
+func setupLogger() error {
+ level := slog.LevelInfo
+ if verbose { level = slog.LevelDebug }
+ opts := &slog.HandlerOptions{Level: level}
+
+ var h slog.Handler
+ switch logFormat {
+ case "json":
+ h = slog.NewJSONHandler(os.Stderr, opts)
+ case "text":
+ h = slog.NewTextHandler(os.Stderr, opts)
+ default:
+ return fmt.Errorf("invalid log-format %q", logFormat)
+ }
+ slog.SetDefault(slog.New(h))
+ return nil
+}
+```
+
+Notes:
+
+- `RunE` / `PersistentPreRunE` (the `E` variants) return errors. Use these; never use `Run` (no error return, encourages `log.Fatal`).
+- `SilenceUsage: true` + `SilenceErrors: true` together: cobra stops printing the full `--help` on every command failure (the default behavior is rude in production scripts).
+- `ExecuteContext` (cobra 1.8+) plumbs the ctx into every subcommand's `cmd.Context()`.
+
+---
+
+## `cmd/server.go`
+
+```go
+package cmd
+
+import (
+ "log/slog"
+
+ "github.com/spf13/cobra"
+ "github.com/your-org/mytool/internal/server"
+)
+
+var (
+ serverAddr string
+)
+
+var serverCmd = &cobra.Command{
+ Use: "server",
+ Short: "Run the HTTP server",
+ RunE: func(c *cobra.Command, args []string) error {
+ ctx := c.Context()
+ slog.InfoContext(ctx, "starting", slog.String("addr", serverAddr))
+ return server.Run(ctx, serverAddr)
+ },
+}
+
+func init() {
+ serverCmd.Flags().StringVar(&serverAddr, "addr", ":8080",
+ "listen address")
+ rootCmd.AddCommand(serverCmd)
+}
+```
+
+The subcommand is a thin shim — flags + log line + delegate to `internal/server`. Anything bigger violates the 250-LOC ceiling and belongs in `internal/`.
+
+---
+
+## Subcommands with arguments
+
+```go
+var migrateUpCmd = &cobra.Command{
+ Use: "up [N]",
+ Short: "Apply N migrations (default: all)",
+ Args: cobra.MaximumNArgs(1),
+ RunE: func(c *cobra.Command, args []string) error {
+ n := -1 // all
+ if len(args) == 1 {
+ var err error
+ n, err = strconv.Atoi(args[0])
+ if err != nil {
+ return fmt.Errorf("invalid N: %w", err)
+ }
+ }
+ return migrate.Up(c.Context(), n)
+ },
+}
+```
+
+Use cobra's argument validators (`cobra.ExactArgs`, `cobra.MaximumNArgs`, `cobra.OnlyValidArgs`). They produce clean help text.
+
+---
+
+## Flag types — typed, not strings
+
+```go
+// GOOD
+serverCmd.Flags().DurationVar(&timeout, "timeout", 30*time.Second, "request timeout")
+serverCmd.Flags().IntVar(&port, "port", 8080, "port")
+serverCmd.Flags().StringSliceVar(&hosts, "host", nil, "allowed hosts (repeatable)")
+
+// BAD — manual parsing
+serverCmd.Flags().StringVar(&timeoutStr, "timeout", "30s", "")
+// ...then later: time.ParseDuration(timeoutStr)
+```
+
+`pflag` (cobra's flag lib) has typed variants for every common type. Use them; the parsing and error messages are free.
+
+---
+
+## Bind flags to env vars
+
+cobra + viper is overkill for env binding. Use `caarlos0/env/v11`:
+
+```go
+type ServerOpts struct {
+ Addr string `env:"ADDR" envDefault:":8080"`
+ Timeout time.Duration `env:"TIMEOUT" envDefault:"30s"`
+}
+
+var opts ServerOpts
+
+var serverCmd = &cobra.Command{
+ Use: "server",
+ PersistentPreRunE: func(c *cobra.Command, args []string) error {
+ // 1. Parse env first.
+ if err := env.Parse(&opts); err != nil { return err }
+ // 2. Flags override env if explicitly set.
+ if c.Flags().Changed("addr") {
+ opts.Addr, _ = c.Flags().GetString("addr")
+ }
+ return nil
+ },
+ RunE: func(c *cobra.Command, args []string) error {
+ return server.Run(c.Context(), opts)
+ },
+}
+
+func init() {
+ serverCmd.Flags().String("addr", "", "listen address (env: ADDR)")
+ serverCmd.Flags().Duration("timeout", 0, "request timeout (env: TIMEOUT)")
+ rootCmd.AddCommand(serverCmd)
+}
+```
+
+Precedence: **flag (if set) > env > default**. Document the env var in the flag usage string.
+
+---
+
+## Version subcommand — build-injected
+
+```go
+// cmd/version.go
+package cmd
+
+import (
+ "fmt"
+ "runtime/debug"
+
+ "github.com/spf13/cobra"
+)
+
+// Set by -ldflags at build time, falls back to debug.BuildInfo.
+var (
+ version = ""
+ commit = ""
+ date = ""
+)
+
+var versionCmd = &cobra.Command{
+ Use: "version",
+ Short: "Print version",
+ Run: func(c *cobra.Command, args []string) {
+ v, c2, d := resolveVersion()
+ fmt.Printf("mytool %s (commit %s, built %s)\n", v, c2, d)
+ },
+}
+
+func resolveVersion() (string, string, string) {
+ if version != "" { return version, commit, date }
+ info, ok := debug.ReadBuildInfo()
+ if !ok { return "dev", "unknown", "unknown" }
+
+ var vcs, hash, time string
+ for _, s := range info.Settings {
+ switch s.Key {
+ case "vcs.revision": hash = s.Value
+ case "vcs.time": time = s.Value
+ case "vcs": vcs = s.Value
+ }
+ }
+ return info.Main.Version, hash, time + " (" + vcs + ")"
+}
+
+func init() { rootCmd.AddCommand(versionCmd) }
+```
+
+Build with version injection:
+
+```bash
+go build \
+ -ldflags="-X 'github.com/your-org/mytool/cmd.version=v1.2.3' -X 'github.com/your-org/mytool/cmd.commit=$(git rev-parse --short HEAD)' -X 'github.com/your-org/mytool/cmd.date=$(date -u +%Y-%m-%dT%H:%M:%SZ)'" \
+ -o bin/mytool ./
+```
+
+The `debug.BuildInfo` fallback means a `go install`'d binary also has version info — no manual `-ldflags` needed.
+
+---
+
+## Shell completions
+
+```go
+var completionCmd = &cobra.Command{
+ Use: "completion [bash|zsh|fish|powershell]",
+ Short: "Generate shell completion",
+ Args: cobra.ExactValidArgs(1),
+ ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
+ DisableFlagsInUseLine: true,
+ RunE: func(c *cobra.Command, args []string) error {
+ switch args[0] {
+ case "bash": return rootCmd.GenBashCompletionV2(os.Stdout, true)
+ case "zsh": return rootCmd.GenZshCompletion(os.Stdout)
+ case "fish": return rootCmd.GenFishCompletion(os.Stdout, true)
+ case "powershell": return rootCmd.GenPowerShellCompletion(os.Stdout)
+ }
+ return nil
+ },
+}
+
+func init() { rootCmd.AddCommand(completionCmd) }
+```
+
+User:
+
+```bash
+mytool completion zsh > "${fpath[1]}/_mytool"
+```
+
+---
+
+## Interactive prompts — `huh` from charm
+
+For prompts/forms (`Are you sure?`, "Pick an environment", multi-field forms):
+
+```go
+import "github.com/charmbracelet/huh"
+
+var confirm bool
+err := huh.NewConfirm().
+ Title("Apply migrations to PRODUCTION?").
+ Affirmative("Yes, do it").
+ Negative("Abort").
+ Value(&confirm).
+ Run()
+```
+
+`huh` replaces `survey` (which is no longer maintained). It composes with `lipgloss` for styling.
+
+---
+
+## Progress / spinners
+
+```go
+import "github.com/charmbracelet/huh/spinner"
+
+err := spinner.New().Title("Fetching...").Action(func() {
+ // long-running work
+}).Run()
+```
+
+For determinate progress (downloads, batch processing), use `vbauerster/mpb/v8`:
+
+```go
+import "github.com/vbauerster/mpb/v8"
+
+p := mpb.New(mpb.WithWidth(60))
+bar := p.AddBar(int64(total), /* decorators */)
+for i := 0; i < total; i++ {
+ work()
+ bar.Increment()
+}
+p.Wait()
+```
+
+---
+
+## Output — JSON vs text
+
+Honor `--output json` for any CLI that scripts will parse:
+
+```go
+var outputFmt string
+
+rootCmd.PersistentFlags().StringVar(&outputFmt, "output", "text",
+ "output format: text or json")
+
+func render(v any) error {
+ switch outputFmt {
+ case "json":
+ enc := json.NewEncoder(os.Stdout)
+ enc.SetIndent("", " ")
+ return enc.Encode(v)
+ case "text":
+ return renderText(v)
+ default:
+ return fmt.Errorf("invalid --output %q", outputFmt)
+ }
+}
+```
+
+The `text` format uses `lipgloss` tables or `aquasecurity/table` for nicely-aligned columns. The `json` format is for `jq`-style piping.
+
+---
+
+## Error semantics
+
+- Return errors from `RunE`. Cobra catches them and the `Execute` wrapper logs + exits non-zero.
+- `os.Exit(1)` should appear **only in `main.go`**. Anywhere else means a subcommand cannot be tested.
+- For graceful early termination ("user cancelled"), return a sentinel and check it in `Execute`:
+ ```go
+ var ErrCancelled = errors.New("cancelled by user")
+ // ... return ErrCancelled
+ // in main:
+ if errors.Is(err, cmd.ErrCancelled) { os.Exit(130) } // 128 + SIGINT
+ ```
+
+---
+
+## Testing CLI commands
+
+```go
+func TestServerCmd_runs_with_default_addr(t *testing.T) {
+ // Given
+ buf := &bytes.Buffer{}
+ rootCmd.SetOut(buf)
+ rootCmd.SetErr(buf)
+ rootCmd.SetArgs([]string{"server", "--addr", ":0"})
+
+ // When
+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer cancel()
+ err := rootCmd.ExecuteContext(ctx)
+
+ // Then
+ require.NoError(t, err)
+ require.Contains(t, buf.String(), "starting")
+}
+```
+
+`SetArgs` + `ExecuteContext` is the canonical pattern. Bind a ctx with a short deadline for tests that would otherwise block.
+
+---
+
+## Sources
+
+- cobra docs: https://github.com/spf13/cobra/blob/main/site/content/user_guide.md
+- pflag: https://github.com/spf13/pflag
+- huh: https://github.com/charmbracelet/huh
+- caarlos0/env: https://github.com/caarlos0/env
+- signal.NotifyContext: https://pkg.go.dev/os/signal#NotifyContext
diff --git a/plugins/omo/skills/programming/references/go/concurrency.md b/plugins/omo/skills/programming/references/go/concurrency.md
new file mode 100644
index 00000000..52ac5033
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/concurrency.md
@@ -0,0 +1,362 @@
+# Concurrency
+
+Goroutines, context, errgroup, channels, locks, and the discipline that keeps them from leaking. Go makes concurrency *easy to start* and *easy to get wrong*. This document is the boring rule set.
+
+---
+
+## The four non-negotiables
+
+1. **`ctx context.Context` is the first parameter of every public function that does I/O or can be cancelled.**
+2. **No goroutine without a shutdown path.** Every `go` keyword must answer "how does this stop?".
+3. **`-race` on every test run.** The `Taskfile.yml` and CI both enforce it.
+4. **`goleak` in `TestMain`** for every package that spawns goroutines. Catches leaks the race detector cannot.
+
+---
+
+## `context.Context` — the cancellation backbone
+
+```go
+// GOOD — ctx as first param, propagated through
+func (s *UserService) Create(ctx context.Context, email Email) (User, error) {
+ user, err := s.store.Insert(ctx, email)
+ if err != nil {
+ return User{}, fmt.Errorf("insert: %w", err)
+ }
+ if err := s.notifier.Welcome(ctx, user); err != nil {
+ return User{}, fmt.Errorf("notify: %w", err)
+ }
+ return user, nil
+}
+
+// BAD — creates a fresh ctx, breaks request cancellation
+func (s *UserService) Create(email Email) (User, error) {
+ ctx := context.Background() // ← contextcheck linter rejects this
+ // ...
+}
+```
+
+The `contextcheck` linter (enabled in `golangci-strict.md`) refuses any function that has `ctx context.Context` available but uses `context.Background()` instead.
+
+### `context.Value` — use sparingly
+
+```go
+// Typed key — never use a bare string
+type ctxKey struct{ name string }
+var requestIDKey = ctxKey{"request_id"}
+
+func WithRequestID(ctx context.Context, id string) context.Context {
+ return context.WithValue(ctx, requestIDKey, id)
+}
+
+func RequestID(ctx context.Context) string {
+ v, _ := ctx.Value(requestIDKey).(string)
+ return v
+}
+```
+
+**Rules**:
+- Keys are unexported struct types, not strings. Prevents collisions across packages.
+- `context.Value` is for *request-scoped metadata* (request ID, auth subject, trace span), NEVER for application-scoped dependencies.
+- Dependencies (loggers, DB pools, config) go in your service struct, not in `context.Value`.
+
+### `WithTimeout` / `WithCancel` — always pair with `defer cancel()`
+
+```go
+ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+defer cancel() // ← MUST be deferred. fatcontext linter catches misses.
+
+if err := slow(ctx); err != nil { ... }
+```
+
+Forgetting `defer cancel()` leaks a context goroutine until the parent expires — the `lostcancel` vet check catches it.
+
+---
+
+## `errgroup` — the structured concurrency primitive
+
+`golang.org/x/sync/errgroup` is Go's answer to Python's `asyncio.TaskGroup` or Rust's `JoinSet`. Use it instead of raw `go` for any group of related goroutines.
+
+```go
+import "golang.org/x/sync/errgroup"
+
+func FetchAll(ctx context.Context, urls []string) ([][]byte, error) {
+ g, ctx := errgroup.WithContext(ctx)
+ g.SetLimit(8) // concurrency cap — leave unbounded = production outage
+
+ results := make([][]byte, len(urls))
+ for i, u := range urls {
+ g.Go(func() error {
+ body, err := fetch(ctx, u)
+ if err != nil {
+ return fmt.Errorf("fetch %s: %w", u, err)
+ }
+ results[i] = body
+ return nil
+ })
+ }
+ if err := g.Wait(); err != nil {
+ return nil, err
+ }
+ return results, nil
+}
+```
+
+Properties:
+
+- `WithContext(parent)` returns a child ctx that gets cancelled on **first non-nil error**. All in-flight goroutines see `ctx.Done()` and bail.
+- `SetLimit(n)` blocks `g.Go(...)` when the in-flight count hits `n`. **Always set this.** Unbounded fan-out is how services die.
+- `g.Wait()` returns the **first** non-nil error. Others are dropped. If you need all errors, accumulate them manually:
+ ```go
+ var mu sync.Mutex
+ var errs []error
+ // inside g.Go:
+ // mu.Lock(); errs = append(errs, err); mu.Unlock()
+ // after Wait, errors.Join(errs...)
+ ```
+
+---
+
+## Goroutine leaks — `goleak`
+
+```go
+package store_test
+
+import (
+ "testing"
+ "go.uber.org/goleak"
+)
+
+func TestMain(m *testing.M) {
+ goleak.VerifyTestMain(m)
+}
+```
+
+This single line at the top of `*_test.go` runs goleak's check after every test in the package. If a test leaks a goroutine, the run fails — pointing at which goroutine.
+
+**The bug it catches**: starting a goroutine in `setUp` and never joining it. Common in DB connection pools, background workers, ticker loops. The race detector does NOT catch this.
+
+If you have a known long-lived goroutine (a singleton background worker, a metrics exporter), use `goleak.IgnoreTopFunction`:
+
+```go
+goleak.VerifyTestMain(m,
+ goleak.IgnoreTopFunction("github.com/prometheus/client_golang/prometheus.(*Registry).Push"),
+)
+```
+
+---
+
+## Channels — the rules that hold
+
+### Direction
+
+```go
+// GOOD — direction in signatures
+func produce(out chan<- Item)
+func consume(in <-chan Item)
+func pipeline(in <-chan Item, out chan<- Item)
+```
+
+Direction restricts misuse. A consumer cannot close the producer's channel.
+
+### Closing
+
+- **The sender closes.** Always. Never the receiver, never multiple senders.
+- **Multiple senders → use a `sync.WaitGroup` + one closer.**
+- **Closing a closed channel panics.** Closing a `nil` channel panics. Sending on a closed channel panics. Receiving from a closed channel returns zero value with `ok = false`.
+
+```go
+// Canonical fan-in: multiple producers, one closer
+func fanIn(ctx context.Context, sources ...<-chan Item) <-chan Item {
+ out := make(chan Item)
+ var wg sync.WaitGroup
+ wg.Add(len(sources))
+ for _, src := range sources {
+ go func() {
+ defer wg.Done()
+ for item := range src {
+ select {
+ case out <- item:
+ case <-ctx.Done():
+ return
+ }
+ }
+ }()
+ }
+ go func() { wg.Wait(); close(out) }()
+ return out
+}
+```
+
+### Selecting
+
+```go
+select {
+case msg := <-incoming:
+ handle(msg)
+case <-ctx.Done():
+ return ctx.Err()
+case <-time.After(5 * time.Second):
+ return ErrTimeout
+}
+```
+
+- `time.After` allocates a timer each call — fine for occasional selects, **NOT for hot loops**. Use `time.NewTimer` + `timer.Reset` for repeat selects.
+- A `default:` case makes `select` non-blocking. Use deliberately, not by accident.
+
+### Buffered vs unbuffered
+
+- **Unbuffered** (`make(chan T)`) = synchronous handoff. Sender blocks until receiver is ready. Use for *coordination*.
+- **Buffered** (`make(chan T, n)`) = asynchronous up to `n`. Use for *decoupling producer rate from consumer rate*.
+
+A buffered channel of size 1 acts as a **non-blocking signal**:
+
+```go
+ready := make(chan struct{}, 1)
+// Producer
+select {
+case ready <- struct{}{}: // signal once, non-blocking
+default: // already signaled, skip
+}
+// Consumer
+<-ready
+```
+
+---
+
+## Locks — the pyramid
+
+```
+Highest level (preferred)
+ channels (message passing — "share memory by communicating")
+ errgroup / wait group
+
+ sync.RWMutex (many readers, occasional writer)
+ sync.Mutex (mutual exclusion)
+
+ atomic.Int64 / atomic.Pointer (single-word lock-free)
+
+Lowest level (rare)
+ unsafe.Pointer + barriers (custom lock-free; needs -race AND review)
+```
+
+### `sync.Mutex` — embed, don't expose
+
+```go
+type Cache struct {
+ mu sync.RWMutex
+ items map[string]Entry
+}
+
+func (c *Cache) Get(key string) (Entry, bool) {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ e, ok := c.items[key]
+ return e, ok
+}
+
+func (c *Cache) Set(key string, e Entry) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.items[key] = e
+}
+```
+
+- `sync.Mutex` is **not** copyable. The `copylocks` vet check catches `var c2 = c1` where `c1` has a mutex.
+- Always `defer mu.Unlock()` immediately after `Lock()`. Forgetting is the #1 deadlock cause.
+- Never call user code (callbacks, listener notifications) while holding the lock. Drop the lock, snapshot the data, release, then call out.
+
+### `sync.OnceValue` / `sync.OnceFunc` (Go 1.21+)
+
+Replacement for `sync.Once` for typed lazy init:
+
+```go
+var loadConfig = sync.OnceValue(func() Config {
+ var cfg Config
+ if err := env.Parse(&cfg); err != nil { panic(err) }
+ return cfg
+})
+
+func handler() { cfg := loadConfig(); ... }
+```
+
+Type-safe, no `sync.Once` + global variable boilerplate.
+
+### Atomics — the typed API only
+
+```go
+// Go 1.19+ — use the typed atomic.* family
+var counter atomic.Int64
+counter.Add(1)
+n := counter.Load()
+
+// NEVER — the old function-style is type-unsafe
+atomic.AddInt64(&counter, 1) // ← rejected
+```
+
+---
+
+## Time — inject a clock for testability
+
+```go
+type Clock interface {
+ Now() time.Time
+}
+
+type realClock struct{}
+func (realClock) Now() time.Time { return time.Now() }
+
+type Service struct {
+ clock Clock
+}
+
+// Tests
+import "github.com/benbjohnson/clock"
+fake := clock.NewMock()
+fake.Set(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC))
+svc := &Service{clock: fake}
+```
+
+**Never call `time.Now()` in domain or service code.** The `time` package becomes a hidden dependency — tests become flaky, retries become time-of-day-dependent, expirations cannot be tested.
+
+`time.Sleep` in production code is a code smell. Use:
+- `time.NewTicker` for periodic work (and a `<-ctx.Done()` exit).
+- `time.NewTimer` for one-shot delays.
+- `time.After` ONLY in select statements, ONLY in non-hot paths.
+
+---
+
+## Race detector — non-negotiable in CI
+
+```bash
+go test -race -shuffle=on -count=1 ./...
+```
+
+- `-race` instruments memory accesses; catches data races at runtime. ~10x slow-down — acceptable for tests, not production.
+- `-shuffle=on` randomizes test order; catches hidden ordering dependencies.
+- `-count=1` defeats the test cache. Without it, "passing" might mean "ran 3 weeks ago".
+
+If a test ONLY fails under `-race`, the bug is real. Don't disable the test; fix the race.
+
+---
+
+## Common antipatterns
+
+| Bad | Why | Good |
+|---|---|---|
+| `go func() { ... }()` with no `ctx` plumbing | Leaks on shutdown | `errgroup.WithContext` or pass ctx |
+| Bare `time.Sleep(d)` in production | Untestable, blocks | `time.NewTimer` + select with `ctx.Done()` |
+| Channel of `interface{}` | Loses type | Typed channel; use sealed interface if variants needed |
+| `sync.Mutex` in a struct passed by value | Locked copies, undefined behavior | Embed in pointer-receiver type; copylocks catches it |
+| Locking around an entire request handler | Serializes the whole API | Lock only the smallest critical section |
+| `for { select { ... } }` without `<-ctx.Done()` | Cannot stop | Add ctx case in every long-lived select |
+| `sync.WaitGroup.Add(1)` inside the goroutine | Race: Wait can return before Add | Add **before** `go` |
+
+---
+
+## Sources
+
+- Go memory model: https://go.dev/ref/mem
+- `errgroup` package: https://pkg.go.dev/golang.org/x/sync/errgroup
+- `goleak`: https://github.com/uber-go/goleak
+- "Go concurrency patterns" (Pike): https://go.dev/blog/pipelines
+- Sync.OnceValue blog: https://go.dev/blog/synctest (1.24+ note: `testing/synctest` for time-controlled tests is now experimental)
diff --git a/plugins/omo/skills/programming/references/go/data-modeling.md b/plugins/omo/skills/programming/references/go/data-modeling.md
new file mode 100644
index 00000000..c903d6ba
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/data-modeling.md
@@ -0,0 +1,329 @@
+# Data Modeling — Three Layers of Validation
+
+Go has no Pydantic. Go has no Zod. **You do not need them**, but only if you wire three layers correctly. This document is the canonical pattern.
+
+## The three layers
+
+```
+┌─────────────────────────────────────────────────────────────┐
+│ HTTP / RPC / CLI │
+│ Raw bytes, strings, untrusted input │
+│ │
+│ Layer 1: validator/v10 (struct tags) ◄── parse-once │
+│ OR protovalidate (proto) │
+│ │
+└──────────────────────────┬──────────────────────────────────┘
+ │ raw req → domain.X
+ ▼
+┌─────────────────────────────────────────────────────────────┐
+│ Domain (internal/domain) │
+│ │
+│ Layer 2: Smart constructors + unexported fields │
+│ NewEmail(s) → (Email, error) │
+│ NewUserID(s) → (UserID, error) │
+│ │
+│ Once inside this layer, NO further validation. │
+│ The types prove correctness. │
+└──────────────────────────┬──────────────────────────────────┘
+ │ domain.X (proven valid)
+ ▼
+┌─────────────────────────────────────────────────────────────┐
+│ Storage (internal/store) │
+│ │
+│ Layer 3: sqlc-generated row structs ↔ domain types │
+│ Hand-written mappers, NOT struct tags │
+└─────────────────────────────────────────────────────────────┘
+```
+
+Each layer parses once, into the next layer's types. **A function in the domain layer should never receive a raw string and validate it.** If it does, the boundary above failed.
+
+---
+
+## Layer 1: HTTP boundary — `go-playground/validator/v10`
+
+```go
+package handlers
+
+import (
+ "github.com/gin-gonic/gin"
+ "github.com/go-playground/validator/v10"
+)
+
+// CreateUserRequest is the wire format. Tags drive validation.
+type CreateUserRequest struct {
+ Email string `json:"email" binding:"required,email"`
+ Username string `json:"username" binding:"required,alphanum,min=3,max=32"`
+ Age int `json:"age" binding:"required,gte=13,lte=130"`
+ Country string `json:"country" binding:"required,iso3166_1_alpha2"`
+}
+
+func (h *Handler) CreateUser(c *gin.Context) {
+ var req CreateUserRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ // validator returns ValidationErrors with field-by-field detail
+ var vErr validator.ValidationErrors
+ if errors.As(err, &vErr) {
+ c.JSON(400, gin.H{"errors": fieldErrors(vErr)})
+ return
+ }
+ c.JSON(400, gin.H{"error": "invalid json"})
+ return
+ }
+
+ // Cross into domain — single point of failure
+ email, err := domain.NewEmail(req.Email)
+ if err != nil {
+ c.JSON(400, gin.H{"error": err.Error()})
+ return
+ }
+ username, err := domain.NewUsername(req.Username)
+ if err != nil {
+ c.JSON(400, gin.H{"error": err.Error()})
+ return
+ }
+
+ user, err := h.svc.Create(c.Request.Context(), email, username, req.Age)
+ if err != nil {
+ h.writeServiceError(c, err)
+ return
+ }
+ c.JSON(201, user)
+}
+
+func fieldErrors(vErr validator.ValidationErrors) map[string]string {
+ out := make(map[string]string, len(vErr))
+ for _, fe := range vErr {
+ out[fe.Field()] = fe.Tag() + "(" + fe.Param() + ")"
+ }
+ return out
+}
+```
+
+**Tag reference — the tags you actually use**:
+
+| Tag | Meaning |
+|---|---|
+| `required` | Non-zero value |
+| `omitempty` (json) | Skip if zero |
+| `min=N` / `max=N` | Length (strings/slices) or value (numbers) |
+| `gte=N` / `lte=N` / `gt=N` / `lt=N` | Numeric comparison |
+| `email` | RFC 5322-ish email |
+| `url` | Valid URL |
+| `uuid` / `uuid4` / `uuid7` | UUID format |
+| `alphanum` / `alpha` / `numeric` | Character class |
+| `iso3166_1_alpha2` | Country code (US, KR, JP) |
+| `iso4217` | Currency code (USD, KRW) |
+| `oneof=a b c` | Enum of literal values |
+| `dive` | Apply rules to each element of slice/map |
+| `eqfield=Field` | Cross-field equality (e.g., password confirm) |
+
+### Custom validators — register at startup
+
+```go
+func init() {
+ if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
+ _ = v.RegisterValidation("strongpassword", validateStrongPassword)
+ }
+}
+
+func validateStrongPassword(fl validator.FieldLevel) bool {
+ s := fl.Field().String()
+ return len(s) >= 12 && hasUpper(s) && hasDigit(s) && hasSymbol(s)
+}
+```
+
+Use sparingly. Most domain rules belong in smart constructors, not validators.
+
+---
+
+## Layer 2: Domain — smart constructors
+
+Covered in detail in `type-patterns.md`. Recap:
+
+```go
+package domain
+
+type Username struct{ raw string }
+
+func NewUsername(s string) (Username, error) {
+ s = strings.TrimSpace(s)
+ if len(s) < 3 || len(s) > 32 {
+ return Username{}, ErrInvalidUsername
+ }
+ if !isAlphanum(s) {
+ return Username{}, ErrInvalidUsername
+ }
+ return Username{raw: s}, nil
+}
+
+func (u Username) String() string { return u.raw }
+```
+
+**Rule**: every domain type that has invariants has:
+
+1. An unexported field holding the raw form.
+2. A `New<Type>(raw) (<Type>, error)` constructor as the sole entry point.
+3. A `String() string` for printing.
+4. `MarshalJSON` / `UnmarshalJSON` if it crosses a JSON boundary outside HTTP handlers (e.g., logging payloads, queue messages).
+5. Optionally: `Scan` and `Value` for `database/sql` interop (rare with sqlc).
+
+---
+
+## Layer 3: Storage — sqlc rows ↔ domain types
+
+sqlc generates row structs from `.sql` files. **Do not put validation tags on them.** Map between sqlc rows and domain types explicitly:
+
+```go
+// internal/store/user_store.go
+package store
+
+import "myservice/internal/domain"
+
+func (s *UserStore) Get(ctx context.Context, id domain.UserID) (domain.User, error) {
+ row, err := s.q.GetUser(ctx, string(id))
+ if err != nil {
+ return domain.User{}, err
+ }
+ return rowToUser(row)
+}
+
+func rowToUser(r sqlc.UserRow) (domain.User, error) {
+ email, err := domain.NewEmail(r.Email)
+ if err != nil {
+ // DB invariant broken — this is a programmer error, not a user error
+ return domain.User{}, fmt.Errorf("db invariant: invalid email for user %s: %w", r.ID, err)
+ }
+ username, err := domain.NewUsername(r.Username)
+ if err != nil {
+ return domain.User{}, fmt.Errorf("db invariant: invalid username: %w", err)
+ }
+ return domain.User{
+ ID: domain.UserID(r.ID),
+ Email: email,
+ Username: username,
+ Created: r.CreatedAt,
+ }, nil
+}
+```
+
+The mapping is verbose. **That is the point.** Each field is a deliberate choice; refactors flag every site.
+
+---
+
+## Discriminated unions (sum types) at the boundary
+
+When a wire payload has variants (e.g., `{"type": "user.created", ...}` vs `{"type": "user.deleted", ...}`):
+
+```go
+// Wire DTO with raw discriminator
+type EventDTO struct {
+ Type string `json:"type" binding:"required,oneof=created deleted updated"`
+ Payload json.RawMessage `json:"payload" binding:"required"`
+}
+
+// Parse into the sealed domain type
+func ParseEvent(dto EventDTO) (event.Event, error) {
+ switch dto.Type {
+ case "created":
+ var c event.Created
+ if err := json.Unmarshal(dto.Payload, &c); err != nil {
+ return nil, fmt.Errorf("decode created: %w", err)
+ }
+ return c, nil
+ case "deleted":
+ var d event.Deleted
+ if err := json.Unmarshal(dto.Payload, &d); err != nil {
+ return nil, fmt.Errorf("decode deleted: %w", err)
+ }
+ return d, nil
+ case "updated":
+ var u event.Updated
+ if err := json.Unmarshal(dto.Payload, &u); err != nil {
+ return nil, fmt.Errorf("decode updated: %w", err)
+ }
+ return u, nil
+ default:
+ return nil, fmt.Errorf("unknown event type %q", dto.Type)
+ }
+}
+```
+
+The `exhaustive` linter on the switch + the `oneof` validation tag together cover both "unknown type" and "unhandled variant".
+
+---
+
+## Enums — typed string consts, not iota
+
+```go
+// GOOD — string-based, JSON-serializes correctly, debuggable
+type Status string
+
+const (
+ StatusPending Status = "pending"
+ StatusActive Status = "active"
+ StatusClosed Status = "closed"
+)
+
+func (s Status) IsValid() bool {
+ switch s {
+ case StatusPending, StatusActive, StatusClosed:
+ return true
+ }
+ return false
+}
+
+func (s *Status) UnmarshalJSON(data []byte) error {
+ var raw string
+ if err := json.Unmarshal(data, &raw); err != nil { return err }
+ parsed := Status(raw)
+ if !parsed.IsValid() { return fmt.Errorf("invalid status %q", raw) }
+ *s = parsed
+ return nil
+}
+```
+
+**Never use `iota` enums for anything that crosses a wire boundary.** They serialize as integers, which (a) breaks debuggability, (b) makes reordering enum values a silent breaking change.
+
+Use the validator tag `binding:"oneof=pending active closed"` to enforce at the HTTP boundary.
+
+---
+
+## Nullable fields — `*T` vs sentinel
+
+Three choices, in order of preference:
+
+1. **Sentinel zero value**: `Age int` with `0` meaning "unknown". Works when zero is genuinely unreachable as a valid value.
+2. **`sql.Null<T>`** for DB columns: `sql.NullString`, `sql.NullInt64`, `sql.NullTime`. sqlc generates these for nullable columns.
+3. **`*T`**: only when you need to distinguish "not provided" from "set to zero" in a JSON payload (PATCH semantics).
+
+```go
+// PATCH payload — `*string` discriminates absent vs empty
+type UpdateUserRequest struct {
+ Email *string `json:"email,omitempty"`
+ Username *string `json:"username,omitempty"`
+}
+```
+
+Avoid `*T` in domain types — it bloats every consumer with nil checks. Keep `*T` at the boundary, unwrap on the way in.
+
+---
+
+## Common AI-generated antipatterns this rejects
+
+| Bad | Why | Good |
+|---|---|---|
+| `func handle(req map[string]any)` | No types, no validation | Define a struct, parse with `validator` |
+| `if email != "" { ... }` inside domain | Validation in the wrong layer | Make `email Email`, no check needed |
+| `type Status int` with `iota` for wire field | Silent breaking on reorder | `type Status string` with const literals |
+| Struct tags `json:"email,string"` (the `,string` coercion) | Magic coercion hides bad input | Strict parsing, fail-fast |
+| `json.Unmarshal` then range-check after | Two-step "validate after parse" | Use `validator` tags or custom `UnmarshalJSON` |
+| Reusing handler DTO as the domain type | Couples wire format to business logic | Two distinct types, explicit mapping |
+
+---
+
+## Sources
+
+- go-playground/validator: https://github.com/go-playground/validator
+- gin binding internals: https://github.com/gin-gonic/gin/blob/master/binding/json.go
+- Parse, don't validate: https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/
+- sqlc with custom types: https://docs.sqlc.dev/en/latest/howto/overrides.html
diff --git a/plugins/omo/skills/programming/references/go/error-handling.md b/plugins/omo/skills/programming/references/go/error-handling.md
new file mode 100644
index 00000000..6922862d
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/error-handling.md
@@ -0,0 +1,359 @@
+# Error Handling
+
+Typed errors, wrap chains, `errors.Is` / `errors.As`, no panic in libraries, resource cleanup. Go errors look simple and are full of footguns. This document is the canonical set of moves.
+
+---
+
+## The five rules
+
+1. **Every error is wrapped on the way up, with `%w`, with context.** Never `return err` from a non-trivial site.
+2. **Compare with `errors.Is`, not `==`.** Wrap chains break `==`. The `errorlint` linter forbids `==` on errors.
+3. **Cast with `errors.As`, not type assertion.** Same reason.
+4. **`panic` is reserved for programmer errors.** Library code never panics on user input or environment failures. Use `(T, error)`.
+5. **Resources released via `defer` immediately after acquisition.** No "I'll add it later".
+
+---
+
+## Sentinel errors — for invariant programmatic checks
+
+```go
+package domain
+
+import "errors"
+
+var (
+ ErrInvalidEmail = errors.New("domain: invalid email")
+ ErrInvalidPhone = errors.New("domain: invalid phone")
+ ErrInvalidAge = errors.New("domain: invalid age")
+)
+
+func NewEmail(s string) (Email, error) {
+ if !emailRe.MatchString(s) {
+ return Email{}, fmt.Errorf("email %q: %w", s, ErrInvalidEmail)
+ }
+ return Email{raw: strings.ToLower(s)}, nil
+}
+```
+
+Caller branches on identity:
+
+```go
+email, err := domain.NewEmail(input)
+if errors.Is(err, domain.ErrInvalidEmail) {
+ return c.JSON(400, gin.H{"error": "email format"})
+}
+```
+
+`errors.Is` walks the wrap chain. `err == domain.ErrInvalidEmail` would have failed because `fmt.Errorf` wrapped it.
+
+---
+
+## Typed errors — when you need structured data
+
+When callers need fields off the error (the offending value, the failing field name, the upstream HTTP status):
+
+```go
+type ValidationError struct {
+ Field string
+ Value string
+ Rule string
+}
+
+func (e *ValidationError) Error() string {
+ return fmt.Sprintf("validation: %s=%q failed %s", e.Field, e.Value, e.Rule)
+}
+
+// Optional: identity sentinel for errors.Is comparisons
+var ErrValidation = errors.New("validation")
+
+func (e *ValidationError) Is(target error) bool {
+ return target == ErrValidation
+}
+```
+
+Caller:
+
+```go
+err := svc.Save(ctx, user)
+
+var vErr *ValidationError
+if errors.As(err, &vErr) {
+ // vErr.Field, vErr.Rule are available
+ c.JSON(400, gin.H{"field": vErr.Field, "rule": vErr.Rule})
+ return
+}
+```
+
+**`errors.As` requires a non-nil pointer-to-pointer.** Almost always the type is `*ConcreteError`. Forgetting the leading `*` is the most common bug here.
+
+---
+
+## Wrapping — `%w` is mandatory
+
+```go
+// BAD — drops context
+return err
+
+// BAD — drops the error chain (errors.Is/As stops working)
+return fmt.Errorf("failed to save user: %v", err)
+
+// GOOD — preserves chain via %w
+return fmt.Errorf("save user %s: %w", userID, err)
+```
+
+The `errorlint` linter catches `%v` where `%w` was meant. **Wrap once per layer**, with the minimum useful context:
+
+```
+api/handler: "create user request: %w"
+ service: "validate inputs: %w"
+ domain: "email %q: %w"
+```
+
+Each frame adds one fact, not a duplicate. The top-level error message reads as a path: `create user request: validate inputs: email "foo": domain: invalid email`.
+
+### `errors.Join` — multiple errors at once
+
+```go
+// Validate all fields, collect all errors
+var errs []error
+if _, err := NewEmail(req.Email); err != nil {
+ errs = append(errs, fmt.Errorf("email: %w", err))
+}
+if _, err := NewUsername(req.Username); err != nil {
+ errs = append(errs, fmt.Errorf("username: %w", err))
+}
+if len(errs) > 0 {
+ return errors.Join(errs...)
+}
+```
+
+`errors.Is` still walks each joined error. Use when reporting batch validation, not for "wrap two unrelated errors".
+
+---
+
+## Panics — when allowed, when banned
+
+**Banned**:
+
+- Anywhere a `(T, error)` could be returned.
+- Inside HTTP handlers (gin's `Recovery` middleware catches them, but you've already lost the error context).
+- Inside any goroutine that survives request lifetime.
+
+**Allowed** (with documentation):
+
+- Map literal init at package level: `var statusNames = map[Status]string{...}` followed by a `func init()` that panics if a const has no name. Catches the bug at startup, not runtime.
+- The `must*` convention for genuinely unrecoverable startup:
+ ```go
+ func MustParseURL(s string) *url.URL {
+ u, err := url.Parse(s)
+ if err != nil { panic(err) }
+ return u
+ }
+ // Use only with literals known at compile time:
+ var defaultAPI = MustParseURL("https://api.example.com")
+ ```
+- `default:` case of an exhaustive sealed-interface switch — see `type-patterns.md`.
+
+The `revive` linter rule `error-return` will flag suspect panic sites; treat them as bugs.
+
+---
+
+## `defer` for resources — the only safe pattern
+
+```go
+func writeReport(path string) (err error) {
+ f, err := os.Create(path)
+ if err != nil {
+ return fmt.Errorf("create %s: %w", path, err)
+ }
+ defer func() {
+ if cerr := f.Close(); cerr != nil && err == nil {
+ err = fmt.Errorf("close %s: %w", path, cerr)
+ }
+ }()
+
+ if _, err := f.Write(data); err != nil {
+ return fmt.Errorf("write %s: %w", path, err)
+ }
+ return nil
+}
+```
+
+Key points:
+
+- `defer f.Close()` immediately after `os.Create` — never further down.
+- Named return `(err error)` so the deferred close can mutate it on close failure.
+- `bodyclose` linter catches missed `defer resp.Body.Close()` for HTTP responses.
+- `sqlclosecheck` linter catches missed `defer rows.Close()` for SQL.
+
+### `errors.Join` for multi-stage cleanup
+
+```go
+func process(path string) (err error) {
+ f, err := os.Open(path)
+ if err != nil { return err }
+ defer func() {
+ err = errors.Join(err, f.Close())
+ }()
+ // ... use f ...
+ return nil
+}
+```
+
+When both the main operation AND `Close` can fail, `errors.Join` reports both without dropping either.
+
+---
+
+## HTTP error responses — a single funnel
+
+Build one helper, route all handler errors through it:
+
+```go
+package httperr
+
+type APIError struct {
+ Status int `json:"-"`
+ Code string `json:"code"`
+ Message string `json:"message"`
+}
+
+func (e *APIError) Error() string { return e.Code + ": " + e.Message }
+
+var (
+ NotFound = &APIError{Status: 404, Code: "not_found", Message: "resource not found"}
+ Unauthorized = &APIError{Status: 401, Code: "unauthorized", Message: "unauthorized"}
+ BadRequest = &APIError{Status: 400, Code: "bad_request", Message: "bad request"}
+ Internal = &APIError{Status: 500, Code: "internal", Message: "internal error"}
+)
+
+// Wrap a domain error into an API error.
+func From(err error) *APIError {
+ if err == nil { return nil }
+
+ var apiErr *APIError
+ if errors.As(err, &apiErr) { return apiErr }
+
+ switch {
+ case errors.Is(err, domain.ErrInvalidEmail),
+ errors.Is(err, domain.ErrInvalidUsername):
+ return &APIError{Status: 400, Code: "validation", Message: err.Error()}
+ case errors.Is(err, ErrNotFound):
+ return NotFound
+ case errors.Is(err, ErrUnauthorized):
+ return Unauthorized
+ default:
+ // unknown — log full chain, return generic
+ slog.Error("unmapped error", slog.Any("err", err))
+ return Internal
+ }
+}
+
+func Write(c *gin.Context, err error) {
+ apiErr := From(err)
+ c.JSON(apiErr.Status, apiErr)
+}
+```
+
+Handlers become trivial:
+
+```go
+func (h *Handler) Create(c *gin.Context) {
+ user, err := h.svc.Create(c.Request.Context(), req)
+ if err != nil {
+ httperr.Write(c, err)
+ return
+ }
+ c.JSON(201, user)
+}
+```
+
+---
+
+## errgroup — error propagation across goroutines
+
+```go
+import "golang.org/x/sync/errgroup"
+
+func fetchAll(ctx context.Context, urls []string) ([][]byte, error) {
+ g, ctx := errgroup.WithContext(ctx)
+ g.SetLimit(8) // concurrency cap
+
+ results := make([][]byte, len(urls))
+ for i, u := range urls {
+ g.Go(func() error {
+ body, err := fetch(ctx, u)
+ if err != nil {
+ return fmt.Errorf("fetch %s: %w", u, err)
+ }
+ results[i] = body
+ return nil
+ })
+ }
+
+ if err := g.Wait(); err != nil {
+ return nil, err
+ }
+ return results, nil
+}
+```
+
+- `errgroup.WithContext` cancels remaining tasks on first error.
+- `SetLimit` bounds concurrency.
+- First non-nil error is returned; others are discarded — by design.
+
+See `concurrency.md` for the full pattern.
+
+---
+
+## Logging errors — structured, once
+
+```go
+slog.ErrorContext(ctx, "save user failed",
+ slog.String("user_id", string(id)),
+ slog.Any("err", err), // %w chain is fully rendered
+)
+```
+
+**Log once, at the outermost frame.** Logging at every wrap site produces five log lines for one error.
+
+The `sloglint` linter enforces `slog.Any("err", err)` over `slog.String("err", err.Error())` — the former preserves the chain when handlers walk the value.
+
+---
+
+## Antipatterns
+
+| Bad | Why | Good |
+|---|---|---|
+| `_ = err` | Silent ignore | Handle, log, or wrap |
+| `if err != nil { return err }` chained 10 deep without wrap | No path info | Add one fact per layer: `fmt.Errorf("step: %w", err)` |
+| `panic(err)` in HTTP handlers | Loses error chain, hits gin Recovery | `httperr.Write(c, err)` |
+| `err.Error() == "some string"` | Brittle, breaks on wrap | Define a sentinel, use `errors.Is` |
+| `if err == sql.ErrNoRows` | Breaks under wrap | `errors.Is(err, sql.ErrNoRows)` |
+| `catch-all log.Fatal(err)` in library code | Crashes the caller's process | Return error, let main decide |
+| Returning a typed nil pointer wrapped in error interface | Classic "nil != nil" bug | Return explicit `nil` for the error |
+
+The last bug deserves its own example:
+
+```go
+// BUG — returns a non-nil error interface containing a nil concrete type
+func bad() error {
+ var e *MyError = nil
+ return e // interface wraps nil pointer; errors == nil is FALSE
+}
+
+// Caller
+if err := bad(); err != nil {
+ // ← entered, but err.(*MyError) is nil — surprise panic
+}
+```
+
+Fix: return explicit `nil`, not a typed nil. The `nilnil` linter catches this in `(T, error)` returns.
+
+---
+
+## Sources
+
+- Go blog "Working with Errors in Go 1.13+": https://go.dev/blog/go1.13-errors
+- `errors.Join` (Go 1.20+): https://pkg.go.dev/errors#Join
+- errorlint: https://github.com/polyfloyd/go-errorlint
+- nilaway nil-interface check: https://github.com/uber-go/nilaway
diff --git a/plugins/omo/skills/programming/references/go/golangci-strict.md b/plugins/omo/skills/programming/references/go/golangci-strict.md
new file mode 100644
index 00000000..c63d1e27
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/golangci-strict.md
@@ -0,0 +1,236 @@
+# Strict `.golangci.yml` (golangci-lint v2)
+
+The single source of truth for "is this Go code acceptable". Drop this in unmodified. **Every linter below is enabled deliberately — read the rationale before disabling one.**
+
+`golangci-lint` v2 changed config schema (top-level `version: "2"`). All v1 configs are incompatible. The block below is v2.
+
+## `.golangci.yml`
+
+```yaml
+version: "2"
+
+run:
+ timeout: 5m
+ tests: true
+ modules-download-mode: readonly
+
+linters:
+ default: none
+ enable:
+ # ── Correctness — bug catchers ───────────────────────────────
+ - govet # stdlib vet, includes shadow, fieldalignment, nilness
+ - staticcheck # SA1*-SA9* — the de facto Go correctness linter
+ - errcheck # unhandled errors. ZERO tolerance.
+ - errorlint # %w wrapping, errors.As vs type-assertion, errors.Is vs ==
+ - nilerr # `return nil` after `err != nil` — classic bug
+ - nilnil # returning `(nil, nil)` from a (*T, error) function
+ - bodyclose # http.Response.Body not closed
+ - rowserrcheck # sql.Rows.Err() not checked
+ - sqlclosecheck # sql.Rows / sql.Stmt not closed
+ - contextcheck # functions taking context.Context don't get context.Background()
+ - fatcontext # context.WithValue() in a loop — leaks
+ - copyloopvar # Go 1.22 loop-var capture — should now use the new semantics
+ - intrange # use `for i := range N` (Go 1.22+) instead of `for i := 0; i < N; i++`
+ - usetesting # use t.TempDir/t.Setenv over os.* in tests
+ - testifylint # require vs assert correctness, ObjectsAreEqual misuse
+
+ # ── Style / readability — kept narrow to avoid bikeshedding ─
+ - gofumpt # stricter gofmt
+ - goimports # import grouping + local prefix
+ - whitespace # leading/trailing whitespace
+ - misspell # typos in comments and strings
+ - unconvert # redundant type conversions
+ - unparam # unused function parameters
+ - ineffassign # ineffective assignments
+ - dupword # duplicate words ("the the")
+
+ # ── Architecture — file size, complexity, dead code ─────────
+ - gocognit # cognitive complexity per function (threshold 25)
+ - gocyclo # cyclomatic complexity per function (threshold 15)
+ - funlen # function length (90 lines, 60 statements)
+ - lll # line length 120
+ - nestif # excessive nesting depth (>4)
+ - dupl # duplicate code blocks
+ - revive # extensible replacement for golint; selected rules below
+ - unused # unused vars/funcs/types
+
+ # ── Exhaustiveness — Go's weakest spot ──────────────────────
+ - exhaustive # type switch and enum-like const groups completeness
+
+ # ── Security ────────────────────────────────────────────────
+ - gosec # CWE-aware security scanner
+
+ # ── Logging ─────────────────────────────────────────────────
+ - sloglint # slog attr style + no slog.Any(); enforce structured logs
+
+ # ── Performance ─────────────────────────────────────────────
+ - perfsprint # fmt.Sprintf where strconv suffices
+ - prealloc # slice prealloc when length is known
+ - makezero # make([]T, n) with non-zero n then append (the classic bug)
+
+linters-settings:
+ errcheck:
+ check-type-assertions: true
+ check-blank: true # `_ = err` is a violation
+
+ govet:
+ enable-all: true
+ settings:
+ shadow:
+ strict: true
+ fieldalignment:
+ # On by default; this catches struct layouts wasting memory.
+ # Disable per-file with //nolint:fieldalignment ONLY for boundary types
+ # whose JSON tag order matters for OpenAPI doc stability.
+
+ errorlint:
+ errorf: true # %w mandatory for wrapping
+ asserts: true # errors.As over type-assertion on `error`
+ comparison: true # errors.Is over ==
+
+ gocognit:
+ min-complexity: 25
+
+ gocyclo:
+ min-complexity: 15
+
+ funlen:
+ lines: 90
+ statements: 60
+ ignore-comments: true
+
+ lll:
+ line-length: 120
+ tab-width: 4
+
+ nestif:
+ min-complexity: 4
+
+ exhaustive:
+ default-signifies-exhaustive: false
+ check:
+ - switch
+ - map
+
+ gosec:
+ excludes:
+ - G104 # handled by errcheck/errorlint
+ - G304 # file path provided as input — too noisy for CLIs
+
+ sloglint:
+ no-mixed-args: true # all attr or all key-value, never mixed
+ kv-only: false
+ attr-only: true # force slog.String(...) form
+ no-global: all # disallow slog.Info; force a logger receiver
+ context: scope # require *Context variants where ctx is in scope
+ static-msg: true # msg must be a string literal (not fmt.Sprintf)
+ no-raw-keys: true # use slog.String("key", ...) not raw "key", "val"
+ key-naming-case: snake
+
+ testifylint:
+ enable-all: true
+ disable:
+ - require-error # We DO use assert.Error in table-driven loops
+
+ revive:
+ severity: warning
+ rules:
+ - name: var-naming
+ - name: package-comments
+ - name: exported
+ - name: error-return
+ - name: error-naming
+ - name: errorf # use fmt.Errorf instead of errors.New(fmt.Sprintf)
+ - name: if-return
+ - name: indent-error-flow
+ - name: range-val-in-closure
+ - name: redefines-builtin-id
+ - name: superfluous-else
+ - name: unhandled-error
+ arguments:
+ - "fmt.Print.*"
+ - "fmt.Fprint.*"
+
+ perfsprint:
+ integer-format: true
+ error-format: true
+ bool-format: true
+ string-format: true
+
+ goimports:
+ local-prefixes:
+ - github.com/your-org
+
+issues:
+ max-issues-per-linter: 0
+ max-same-issues: 0
+ exclude-rules:
+ # Tests get a longer leash on funlen + lll
+ - path: _test\.go
+ linters:
+ - funlen
+ - lll
+ - dupl
+ - gosec
+ # Generated code never lints
+ - path: \.pb\.go$
+ linters: [all]
+ - path: \.connect\.go$
+ linters: [all]
+ - path: ^.*sqlc/.*\.sql\.go$
+ linters: [all]
+
+formatters:
+ enable:
+ - gofumpt
+ - goimports
+```
+
+## Per-linter rationale (why each is on)
+
+| Linter | What it catches | Why no compromise |
+|---|---|---|
+| `errcheck` (incl. `check-blank: true`) | `_ = err`, ignored errors from `Close()`, `Write()`, `json.Marshal()` | Silent error ignore is the #1 Go bug class. Banning `_ = err` forces a decision at every site. |
+| `errorlint` | `err == io.EOF` instead of `errors.Is(err, io.EOF)`; missing `%w` in `fmt.Errorf` | Once you wrap in middleware, `==` checks silently break. `errors.Is/As` is the only safe form. |
+| `nilerr` / `nilnil` | `return nil` after `err != nil`; `return nil, nil` from `(*T, error)` | Classic AI-generated bugs. Linter catches them mechanically. |
+| `bodyclose` | `defer resp.Body.Close()` missed | Single most common Go memory leak. |
+| `contextcheck` | `ctx := context.Background()` inside a function that received `ctx` | Breaks cancellation propagation — the entire reason ctx exists. |
+| `exhaustive` | `switch x.(type)` missing a sealed-interface variant | **Go's weakest type-system spot.** This linter is the closest thing to compiler-enforced exhaustiveness. |
+| `sloglint` | `slog.Info(...)` (global), mixed `Any`/typed attrs | Without this, structured logging silently degrades into string concatenation. |
+| `govet/shadow` strict | `err := ... ; if ... { err := ...; ... }` shadowing | Hides the real error from outer scope — extremely common. |
+| `govet/fieldalignment` | Struct field order wasting memory | Cheap correctness signal. Disable per-file when JSON tag order matters for OpenAPI. |
+| `copyloopvar` + `intrange` | Pre-1.22 loop-var capture and old `for i := 0; i < N; i++` | The language modernized; the lint enforces it. |
+| `usetesting` | `os.Setenv` / `os.Mkdir` in tests instead of `t.Setenv` / `t.TempDir` | Avoids test isolation bugs. |
+| `gocognit` / `gocyclo` / `funlen` | Functions exceeding cognitive thresholds | Direct architectural signal — same purpose as the 250 LOC ceiling, at function granularity. |
+| `gosec` | CWE patterns — SQL injection, weak crypto, path traversal | Production must pass this. |
+| `testifylint` | `assert.Equal` where `require.Equal` was meant; `ObjectsAreEqual` misuse | Subtle test-correctness bugs. |
+| `perfsprint` | `fmt.Sprintf("%d", n)` instead of `strconv.Itoa(n)` | 5–10x faster in tight loops, lints catch the lazy form. |
+
+## `nolint` policy
+
+`//nolint:linter1,linter2 // <reason>` is permitted with **two hard rules**:
+
+1. **One linter at a time per directive.** No `//nolint:all`. No omitting the linter name.
+2. **A reason after `//` is mandatory.** "Generated code", "false positive — protobuf imports", "OpenAPI field order" are acceptable. "Ignore" is not.
+
+The skill auto-rejects `//nolint` without a reason. So does `revive` if you enable its `nolint` rule.
+
+## CI gate
+
+```bash
+gofumpt -l . | (! grep .) # format
+golangci-lint run --timeout 5m ./... # everything above
+go vet -vettool=$(which fieldalignment) ./... # extra check (also in govet)
+nilaway ./... # nil-deref static analysis
+go test -race -shuffle=on -count=1 ./... # races + ordering
+```
+
+Any non-zero exit = the change does not ship.
+
+## Sources
+
+- golangci-lint v2 docs: https://golangci-lint.run/docs/configuration/
+- staticcheck rules: https://staticcheck.dev/docs/checks
+- sloglint: https://github.com/go-simpler/sloglint
+- exhaustive: https://github.com/nishanths/exhaustive
+- nilaway: https://github.com/uber-go/nilaway
diff --git a/plugins/omo/skills/programming/references/go/grpc-connect.md b/plugins/omo/skills/programming/references/go/grpc-connect.md
new file mode 100644
index 00000000..6443f675
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/grpc-connect.md
@@ -0,0 +1,375 @@
+# RPC — Connect-Go (default) + grpc-go (fallback) + protovalidate
+
+`connectrpc/connect-go` is the default. It is wire-compatible with gRPC, also speaks Connect protocol + gRPC-Web from browsers, and uses ordinary `net/http` so middleware (logging, auth, tracing) composes the same way as REST. Reach for raw `grpc-go` only when you need a gRPC-specific feature Connect lacks.
+
+---
+
+## When Connect vs grpc-go
+
+| Need | Use |
+|---|---|
+| Standard unary + server-streaming + client-streaming | **Connect** |
+| Browser client without `grpc-web` proxy | **Connect** (native gRPC-Web support) |
+| HTTP/1.1 fallback for hostile networks | **Connect** (gRPC requires HTTP/2 end-to-end) |
+| Server reflection for `grpcurl` | grpc-go (Connect has reflection too, but ecosystem smaller) |
+| Bidirectional streaming with frame-level control | grpc-go |
+| Strict gRPC environment (Envoy with gRPC filters, Istio strict mode) | grpc-go |
+
+**Default**: Connect. The default has been correct since 2024.
+
+---
+
+## Toolchain — Buf, not protoc
+
+```bash
+go install github.com/bufbuild/buf/cmd/buf@latest
+go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
+go install connectrpc.com/connect/cmd/protoc-gen-connect-go@latest
+go install github.com/bufbuild/protovalidate/cmd/protoc-gen-go-vtproto@latest
+```
+
+Buf replaces `protoc` for everything: linting, breaking-change detection, codegen, formatting. The `protoc` toolchain is dead-letter walking — every modern proto project uses Buf.
+
+---
+
+## Project layout
+
+```
+proto/
+ buf.yaml
+ buf.gen.yaml
+ buf.lock
+ myservice/v1/
+ user.proto
+ auth.proto
+
+gen/
+ myservice/v1/
+ user.pb.go # protoc-gen-go output
+ auth.pb.go
+ myservicev1connect/ # protoc-gen-connect-go output
+ user.connect.go
+ auth.connect.go
+```
+
+**`gen/` is committed.** Generated code is part of the API contract; CI proves it is up-to-date.
+
+---
+
+## `buf.yaml`
+
+```yaml
+version: v2
+modules:
+ - path: proto
+lint:
+ use:
+ - STANDARD
+breaking:
+ use:
+ - FILE
+```
+
+## `buf.gen.yaml`
+
+```yaml
+version: v2
+managed:
+ enabled: true
+ override:
+ - file_option: go_package_prefix
+ value: github.com/your-org/myservice/gen
+plugins:
+ - remote: buf.build/protocolbuffers/go
+ out: gen
+ opt:
+ - paths=source_relative
+ - remote: buf.build/connectrpc/go
+ out: gen
+ opt:
+ - paths=source_relative
+ - remote: buf.build/bufbuild/validate-go
+ out: gen
+ opt:
+ - paths=source_relative
+```
+
+The `buf.build/...` plugin URIs use Buf's hosted remote registry — no local plugin installation needed.
+
+## Taskfile target
+
+```yaml
+gen:proto:
+ cmds:
+ - buf lint
+ - buf format -w
+ - buf generate
+ sources:
+ - proto/**/*.proto
+ - buf.yaml
+ - buf.gen.yaml
+```
+
+Run `task gen:proto` after editing any `.proto`. CI runs `buf generate` then `git diff --exit-code` to catch stale generated code.
+
+---
+
+## A `.proto` with validation
+
+```proto
+syntax = "proto3";
+
+package myservice.v1;
+
+import "buf/validate/validate.proto";
+
+option go_package = "github.com/your-org/myservice/gen/myservice/v1;myservicev1";
+
+service UserService {
+ rpc CreateUser(CreateUserRequest) returns (CreateUserResponse);
+ rpc GetUser(GetUserRequest) returns (GetUserResponse);
+ rpc StreamEvents(StreamEventsRequest) returns (stream Event);
+}
+
+message CreateUserRequest {
+ string email = 1 [(buf.validate.field).string.email = true];
+ string username = 2 [
+ (buf.validate.field).string.min_len = 3,
+ (buf.validate.field).string.max_len = 32,
+ (buf.validate.field).string.pattern = "^[a-zA-Z0-9_]+$"
+ ];
+ int32 age = 3 [
+ (buf.validate.field).int32.gte = 13,
+ (buf.validate.field).int32.lte = 130
+ ];
+}
+
+message CreateUserResponse {
+ User user = 1;
+}
+
+message User {
+ string id = 1;
+ string email = 2;
+ string username = 3;
+ google.protobuf.Timestamp created_at = 4;
+}
+```
+
+`protovalidate` replaces the abandoned `protoc-gen-validate` — it is the official Buf-backed successor as of 2024, supported by Connect's interceptor pipeline.
+
+---
+
+## Server — Connect
+
+```go
+package main
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+
+ "connectrpc.com/connect"
+ "buf.build/go/protovalidate"
+ validateinterceptor "connectrpc.com/validate"
+ "golang.org/x/net/http2"
+ "golang.org/x/net/http2/h2c"
+
+ myservicev1 "github.com/your-org/myservice/gen/myservice/v1"
+ "github.com/your-org/myservice/gen/myservice/v1/myservicev1connect"
+)
+
+type UserServer struct {
+ svc *UserService
+}
+
+func (s *UserServer) CreateUser(
+ ctx context.Context,
+ req *connect.Request[myservicev1.CreateUserRequest],
+) (*connect.Response[myservicev1.CreateUserResponse], error) {
+
+ // protovalidate already ran via the interceptor below.
+ // req.Msg is guaranteed to satisfy the .proto constraints.
+
+ user, err := s.svc.Create(ctx, req.Msg.Email, req.Msg.Username, req.Msg.Age)
+ if err != nil {
+ return nil, mapError(err)
+ }
+ return connect.NewResponse(&myservicev1.CreateUserResponse{
+ User: userToProto(user),
+ }), nil
+}
+
+func main() {
+ validator, _ := protovalidate.New()
+ interceptors := connect.WithInterceptors(
+ loggingInterceptor(),
+ validateinterceptor.NewInterceptor(validator),
+ )
+
+ mux := http.NewServeMux()
+ mux.Handle(myservicev1connect.NewUserServiceHandler(
+ &UserServer{svc: newUserService()},
+ interceptors,
+ ))
+
+ // h2c lets the server speak HTTP/2 cleartext for gRPC clients.
+ srv := &http.Server{
+ Addr: ":8080",
+ Handler: h2c.NewHandler(mux, &http2.Server{}),
+ }
+ slog.Info("rpc server listening", slog.String("addr", srv.Addr))
+ if err := srv.ListenAndServe(); err != nil { slog.Error("rpc", slog.Any("err", err)) }
+}
+```
+
+The handler is **just an `http.Handler`** — mount it in the same `http.ServeMux` as your REST routes if you want one binary serving both.
+
+---
+
+## Error mapping — Connect codes
+
+```go
+func mapError(err error) error {
+ if err == nil { return nil }
+
+ switch {
+ case errors.Is(err, domain.ErrInvalidEmail),
+ errors.Is(err, domain.ErrInvalidUsername):
+ return connect.NewError(connect.CodeInvalidArgument, err)
+ case errors.Is(err, ErrNotFound):
+ return connect.NewError(connect.CodeNotFound, err)
+ case errors.Is(err, ErrUnauthorized):
+ return connect.NewError(connect.CodeUnauthenticated, err)
+ case errors.Is(err, ErrConflict):
+ return connect.NewError(connect.CodeAlreadyExists, err)
+ default:
+ slog.Error("unmapped rpc error", slog.Any("err", err))
+ return connect.NewError(connect.CodeInternal, errors.New("internal"))
+ }
+}
+```
+
+Connect codes map 1:1 to gRPC codes. Clients see canonical error semantics.
+
+---
+
+## Logging interceptor
+
+```go
+func loggingInterceptor() connect.UnaryInterceptorFunc {
+ return func(next connect.UnaryFunc) connect.UnaryFunc {
+ return func(ctx context.Context, req connect.AnyRequest) (connect.AnyResponse, error) {
+ start := time.Now()
+ res, err := next(ctx, req)
+ attrs := []slog.Attr{
+ slog.String("proc", req.Spec().Procedure),
+ slog.Duration("elapsed", time.Since(start)),
+ }
+ if err != nil {
+ attrs = append(attrs, slog.Any("err", err))
+ slog.LogAttrs(ctx, slog.LevelWarn, "rpc failed", attrs...)
+ } else {
+ slog.LogAttrs(ctx, slog.LevelInfo, "rpc ok", attrs...)
+ }
+ return res, err
+ }
+ }
+}
+```
+
+For streaming, implement the full `connect.Interceptor` (`WrapStreamingClient`, `WrapStreamingHandler`). Pattern is identical.
+
+---
+
+## Server streaming
+
+```go
+func (s *UserServer) StreamEvents(
+ ctx context.Context,
+ req *connect.Request[myservicev1.StreamEventsRequest],
+ stream *connect.ServerStream[myservicev1.Event],
+) error {
+ events, errs := s.svc.Subscribe(ctx, req.Msg.UserId)
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case e, ok := <-events:
+ if !ok { return nil }
+ if err := stream.Send(eventToProto(e)); err != nil {
+ return err
+ }
+ case err := <-errs:
+ return connect.NewError(connect.CodeInternal, err)
+ }
+ }
+}
+```
+
+Same shape as SSE in `backend-stack.md`. Connect handles HTTP/2 framing.
+
+---
+
+## Client
+
+```go
+client := myservicev1connect.NewUserServiceClient(
+ http.DefaultClient,
+ "https://api.example.com",
+ // Use connect.WithGRPC() if the server is grpc-go and you want strict gRPC framing.
+ // Default is Connect protocol — works with Connect or gRPC servers transparently.
+)
+
+res, err := client.CreateUser(ctx, connect.NewRequest(&myservicev1.CreateUserRequest{
+ Email: "[email protected]",
+ Username: "alice",
+ Age: 30,
+}))
+if err != nil {
+ var connectErr *connect.Error
+ if errors.As(err, &connectErr) {
+ slog.Error("rpc failed",
+ slog.String("code", connectErr.Code().String()),
+ slog.String("msg", connectErr.Message()))
+ }
+ return err
+}
+slog.Info("created", slog.String("id", res.Msg.User.Id))
+```
+
+---
+
+## When you genuinely need raw grpc-go
+
+```go
+import "google.golang.org/grpc"
+
+lis, _ := net.Listen("tcp", ":8080")
+srv := grpc.NewServer(
+ grpc.UnaryInterceptor(loggingUnaryInterceptor),
+)
+myservicev1.RegisterUserServiceServer(srv, &userServer{})
+_ = srv.Serve(lis)
+```
+
+The codegen is from `protoc-gen-go-grpc` (different binary from `protoc-gen-connect-go`). You can codegen **both** in the same `buf.gen.yaml` and switch by importing the right package. Most teams pick one.
+
+---
+
+## When NOT to use RPC at all
+
+If your callers are all browsers, mobile apps, third-party developers, or the long tail of "things humans curl": **stay with REST + OpenAPI**. RPC's overhead is justified for service-to-service inside a single org. Outside that boundary, JSON over HTTP wins on debuggability.
+
+`oapi-codegen/oapi-codegen/v2` generates Go server stubs and clients from OpenAPI 3 — the REST equivalent of what Connect does for proto. Same parse-don't-validate boundary discipline, different wire format.
+
+---
+
+## Sources
+
+- Connect docs: https://connectrpc.com/docs/go/getting-started
+- Buf: https://buf.build/docs
+- protovalidate: https://github.com/bufbuild/protovalidate
+- "Why we replaced protoc with buf" (Buf blog): https://buf.build/blog
+- gRPC vs Connect comparison: https://connectrpc.com/docs/introduction
diff --git a/plugins/omo/skills/programming/references/go/libraries.md b/plugins/omo/skills/programming/references/go/libraries.md
new file mode 100644
index 00000000..30e47b88
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/libraries.md
@@ -0,0 +1,337 @@
+# Library Defaults — Full Decision Tree (Go 2026)
+
+The opinionated, in-production stack for 2026 Go. Every entry has a one-line rationale and a canonical snippet so the agent does not relearn each library's idioms.
+
+The biggest difference from Python/Rust/TypeScript: **Go has fewer "best" choices and more "boring" choices.** The standard library is the default; reach outside it only when the rationale below applies.
+
+---
+
+## HTTP framework — `gin` (default) or `chi` (minimalist) or `net/http` (no deps)
+
+The reality of 2026 Go: **`gin` runs ~48% of new Go API projects** (Go Developer Survey 2024 + crawls of new repos), with `gorilla/mux` (~17%, in maintenance), `echo` (~16%), and `fiber` (~11%) the remaining quarter. The skill picks gin not because it is technically superior — it is not — but because:
+
+1. The ecosystem (middleware, examples, SO answers) is largest.
+2. The CLIProxyAPI codebase, which this skill's `backend-stack.md` is distilled from, uses gin in production for OpenAI/Gemini/Claude proxying including SSE streaming and WebSocket upgrades. That is real reference code, not a toy.
+3. Gin's `Context` API is the closest thing Go has to a framework-blessed "request-scoped object", which makes middleware composition straightforward.
+
+```go
+import "github.com/gin-gonic/gin"
+
+func main() {
+ r := gin.New()
+ r.Use(gin.Recovery(), middleware.RequestLogger(), middleware.RequestID())
+ r.GET("/healthz", func(c *gin.Context) { c.JSON(200, gin.H{"ok": true}) })
+ _ = r.Run(":8080")
+}
+```
+
+**Pick `chi` instead** when:
+- You want `net/http`-compatible handlers (you do, eventually — chi is closer to stdlib).
+- The service is small and you do not need gin's binding helpers.
+
+**Pick `net/http` (stdlib) directly** when:
+- The service has fewer than 10 routes and zero auth complexity. Go 1.22's enhanced `ServeMux` (method+path patterns) eliminated 80% of the historical reason to use a framework.
+
+**Never use** `gorilla/mux` (effectively in maintenance), `fiber` (uses `fasthttp` which is **not stdlib-compatible**, so middleware ecosystem is split), or `echo` (smaller eco than gin, no real advantage today).
+
+See `backend-stack.md` for the gin canonical layout, middleware ordering, SSE, graceful shutdown, structured logging integration.
+
+---
+
+## RPC — `connectrpc/connect-go`
+
+The default RPC layer. **Use Connect, not raw grpc-go**, unless you have a measured reason.
+
+- Connect is wire-compatible with gRPC AND speaks HTTP/1.1 + HTTP/2 + Connect protocol. One server, three clients (gRPC, gRPC-Web, Connect-Web from browsers).
+- No `grpcurl` needed for debugging — `curl -H "Content-Type: application/json" -d ...` works.
+- Streaming, interceptors, deadlines, errors are first-class.
+- Buf toolchain (`buf generate`, `buf lint`, `buf breaking`) for codegen is dramatically nicer than `protoc`.
+
+```go
+// Server
+mux := http.NewServeMux()
+mux.Handle(elizav1connect.NewElizaServiceHandler(&elizaServer{}))
+_ = http.ListenAndServe(":8080", h2c.NewHandler(mux, &http2.Server{}))
+
+// Client
+client := elizav1connect.NewElizaServiceClient(
+ http.DefaultClient,
+ "http://localhost:8080",
+)
+res, err := client.Say(ctx, connect.NewRequest(&elizav1.SayRequest{Sentence: "hi"}))
+```
+
+**Use raw `grpc-go`** only when:
+- You need server-streaming-from-multiple-services with a single gRPC mux.
+- You are integrating with a strict gRPC-only environment (Envoy proxy with gRPC reflection, Istio strict-gRPC).
+
+See `grpc-connect.md`.
+
+---
+
+## Database — `pgx/v5` + `sqlc` + `goose`
+
+```bash
+go get github.com/jackc/pgx/v5
+go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest
+go install github.com/pressly/goose/v3/cmd/goose@latest
+```
+
+- **`pgx/v5`** is faster, more type-safe, and has better PostgreSQL feature coverage than `database/sql + lib/pq`. Use the `pgxpool` package for connection pooling. Avoid `database/sql` driver mode — it loses pgx's batch, COPY, listen/notify.
+- **`sqlc`** generates type-safe Go from `.sql` files. Hand-written SQL with hand-written struct mapping is the #1 source of subtle DB bugs. sqlc eliminates the class.
+- **`goose`** for migrations — small, command-line first, no global state.
+
+**Never use** `gorm` (active record, slow, brings runtime reflection into hot paths, encourages N+1 queries). **Never use** `ent` (heavy, opinionated graph layer) unless you specifically want a graph-shaped data model.
+
+See `sqlc-pgx.md`.
+
+---
+
+## Validation — three layers, three tools
+
+Go has no Pydantic / Zod equivalent and **does not need one** — but only because you wire three layers properly:
+
+| Layer | Tool | Pattern |
+|---|---|---|
+| HTTP boundary (gin/chi/net/http) | `go-playground/validator/v10` via struct tags | `binding:"required,email,min=3"` |
+| RPC boundary (protobuf) | `bufbuild/protovalidate-go` | `(buf.validate.field).string.min_len = 3` in `.proto` |
+| Domain core | **Smart constructor + unexported fields** | `NewEmail(s) (Email, error)` returns a type whose fields cannot be set from outside |
+
+```go
+// HTTP boundary
+type CreateUserReq struct {
+ Email string `json:"email" binding:"required,email"`
+ Username string `json:"username" binding:"required,alphanum,min=3,max=32"`
+}
+
+// Domain — once a value is of type Email it is provably valid
+type Email struct{ raw string }
+func NewEmail(s string) (Email, error) {
+ if !emailRegex.MatchString(s) { return Email{}, ErrInvalidEmail }
+ return Email{raw: strings.ToLower(s)}, nil
+}
+func (e Email) String() string { return e.raw }
+```
+
+The boundary parses raw input into the domain type **once**. Inside the domain, no further validation is permitted — the types prove it. This is parse-don't-validate adapted to Go.
+
+See `data-modeling.md` for the full pattern.
+
+---
+
+## Logging — `log/slog` (stdlib)
+
+```go
+import "log/slog"
+
+logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
+ Level: slog.LevelInfo,
+ AddSource: true,
+}))
+slog.SetDefault(logger)
+
+slog.InfoContext(ctx, "request handled",
+ slog.String("path", r.URL.Path),
+ slog.Int("status", 200),
+ slog.Duration("elapsed", elapsed),
+)
+```
+
+- **stdlib since 1.21**, stable since 1.23. Performance is on par with zerolog for structured output, and faster than logrus by a wide margin.
+- The `slog.Handler` interface is implemented by all major exporters (OpenTelemetry, Datadog, Honeycomb).
+- The skill bans `logrus`, `zap`, `zerolog` for new code. They are not bad — they are simply superseded. Existing projects on those keep them; new files use slog.
+
+Use the `sloglint` linter from `golangci-strict.md` to enforce attr style (`slog.String(...)` instead of `slog.Any(...)`).
+
+---
+
+## CLI — `cobra` + `pflag` + slog
+
+```bash
+go install github.com/spf13/cobra-cli@latest
+cobra-cli init mytool
+cobra-cli add server
+```
+
+`cobra` is the de facto Go CLI framework — Kubernetes, Docker CLI, Helm, GitHub CLI all use it. The companion `viper` for config-file-+-env-+-flag merging is **optional**: prefer `caarlos0/env/v11` for env-only configs (12-factor apps), reach for viper only when you genuinely need file-based config.
+
+See `cobra-stack.md`.
+
+---
+
+## TUI — `bubbletea v2` + `bubbles v2` + `lipgloss v2`
+
+Use **v2 RC** (`charm.land/bubbletea/v2`), not v1. The v2 model adds:
+
+- `tea.View{Cursor: *tea.Cursor, ...}` for real-cursor positioning.
+- `SetVirtualCursor(false)` on textareas — lets the terminal own the cursor, which is **required** for CJK IME (Korean Hangul composition, Japanese kana→kanji conversion, Chinese pinyin lookup).
+- Granular mouse events (`MouseClickMsg`, `MouseMotionMsg`, `MouseReleaseMsg`) instead of v1's coarse `MouseMsg`.
+
+This is not a preference. v1 has no way to position the IME candidate window correctly — Korean input shows up two cells to the left of where you typed, every time. **If your TUI accepts text input AND your users include CJK speakers, v1 is broken.**
+
+See `bubbletea-v2.md` for the full IME-correct skeleton.
+
+---
+
+## HTTP client — stdlib + `hashicorp/go-retryablehttp`
+
+Default: `net/http.Client` with a tuned `http.Transport`. The stdlib client is **already excellent** in 2026 — HTTP/2 by default, connection pooling, sane timeouts when configured.
+
+```go
+client := &http.Client{
+ Timeout: 30 * time.Second,
+ Transport: &http.Transport{
+ MaxIdleConns: 200,
+ MaxIdleConnsPerHost: 40,
+ IdleConnTimeout: 90 * time.Second,
+ DisableCompression: false,
+ ForceAttemptHTTP2: true,
+ },
+}
+```
+
+For retry/backoff, add `github.com/hashicorp/go-retryablehttp` — small, single-purpose, integrates as a wrapper.
+
+**Never use** `resty` (too much magic, hides headers, encourages wrong defaults). `req` is fine but adds dependency surface for marginal benefit over the stdlib + retry wrapper.
+
+---
+
+## JSON — stdlib (default), `goccy/go-json` (perf), `bytedance/sonic` (extreme perf)
+
+Stdlib `encoding/json` improved dramatically in Go 1.21+. **Use it.**
+
+Reach for `goccy/go-json` (~3x faster) only when you have measured a hot-path bottleneck:
+
+```go
+import json "github.com/goccy/go-json"
+// drop-in replacement — same API
+```
+
+Reach for `bytedance/sonic` (~5x faster, requires amd64/arm64) for production proxies with thousands of RPS of JSON traversal. CLIProxyAPI uses `tidwall/gjson` + `tidwall/sjson` for **partial-tree mutation without full unmarshal** — a different optimization, useful when you transform large payloads. See `backend-stack.md`.
+
+---
+
+## Concurrency primitives — stdlib only
+
+| Need | Use |
+|---|---|
+| Goroutine group with error propagation | `golang.org/x/sync/errgroup` |
+| Semaphore | `golang.org/x/sync/semaphore` |
+| Single-flight dedup | `golang.org/x/sync/singleflight` |
+| Lazy init | **`sync.OnceValue` / `sync.OnceFunc`** (Go 1.21+, replaces `sync.Once` for typed values) |
+| Atomic counter | `atomic.Int64` (Go 1.19+, typed atomics — don't use the old func-style) |
+| Channel-based fanout | `chan T` with `errgroup` for shutdown |
+
+The `x/sync` packages are stdlib-quality but live outside `std`. See `concurrency.md` for the discipline.
+
+---
+
+## Time — stdlib + `benbjohnson/clock` for tests
+
+```go
+type Clock interface { Now() time.Time }
+// Production
+var realClock Clock = clockImpl{}
+// Test
+fake := clock.NewMock()
+fake.Set(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC))
+```
+
+**Never call `time.Now()` directly inside domain code.** Inject a `Clock`. Tests become deterministic, no `time.Sleep` flakiness.
+
+---
+
+## IDs — `google/uuid` (UUID v4/v7) or `xid` (sortable short ID)
+
+```go
+import "github.com/google/uuid"
+id := uuid.Must(uuid.NewV7()) // sortable, time-ordered, 128-bit
+```
+
+UUID v7 is the modern default — sortable like v6, random like v4. Use v4 only when leaking creation time is a privacy concern.
+
+For short, URL-safe IDs (~12 bytes, sortable) use `rs/xid` — Kubernetes-style.
+
+---
+
+## Crypto — stdlib + `alecthomas/argon2id` for passwords
+
+Stdlib `crypto/*` for everything. For password hashing, **argon2id is the 2026 standard** — bcrypt is acceptable but argon2 is OWASP's recommendation since 2023.
+
+```go
+import "github.com/alecthomas/argon2id"
+hash, err := argon2id.CreateHash("password", argon2id.DefaultParams)
+```
+
+---
+
+## Data — `apache/arrow-go/v18` + `marcboeker/go-duckdb` + `gonum`
+
+Same philosophy as Python's "never pandas":
+
+| Need | Use |
+|---|---|
+| Tabular over CSV/Parquet/JSON | DuckDB-Go bindings — zero-copy Arrow integration |
+| In-memory frame | Arrow + custom code (Go has no pandas-equivalent and that's fine) |
+| Numerical | `gonum.org/v1/gonum` |
+| Stats | `gonum/stat` |
+
+Go's data-science story is intentionally thin. For heavy data work, write the pipeline in Polars/DuckDB (see `python/data-processing.md`), expose the result via Parquet or Arrow, consume from Go.
+
+---
+
+## Testing — stdlib + selective additions
+
+| Need | Use |
+|---|---|
+| Assertions | `stretchr/testify/require` (fail-fast) — `assert` only in table-driven loops |
+| Snapshots / golden | `hexops/autogold/v2` (auto-updates with `-update`) |
+| Property-based | `pgregory.net/rapid` (modern) or stdlib `testing/quick` |
+| Mocks | `go.uber.org/mock` (gomock successor) |
+| HTTP mocks | `h2non/gock` for outbound, stdlib `httptest` for inbound |
+| Integration containers | `testcontainers/testcontainers-go` |
+| Goroutine leak | `go.uber.org/goleak` |
+| Benchmarks | stdlib `testing.B` + `perf.dev/benchstat` |
+
+See `testing.md` for canonical patterns.
+
+---
+
+## Config — `caarlos0/env/v11`
+
+```go
+type Config struct {
+ Port int `env:"PORT" envDefault:"8080"`
+ DatabaseURL string `env:"DATABASE_URL,required"`
+ Timeout time.Duration `env:"TIMEOUT" envDefault:"30s"`
+}
+
+var cfg Config
+if err := env.Parse(&cfg); err != nil { log.Fatal(err) }
+```
+
+Pure 12-factor. Defaults via struct tag, required marker, parsing for `time.Duration`, slices, maps. **Use viper only if you also need file-based config** — most services do not.
+
+---
+
+## Choosing an unfamiliar dependency — the checklist
+
+Before `go get`-ing anything new:
+
+1. Is it maintained? Latest tag within 12 months? Owner active?
+2. Does it expose stdlib-compatible types (`io.Reader`, `context.Context`, `http.Handler`)? If it invents its own `Connection` or `Request` type, that's a yellow flag.
+3. Does it use `init()` for side effects? **REJECT.** `init()` ruins testability.
+4. Does it call `log.Fatal` / `panic` outside of true programmer-error paths? **REJECT.**
+5. Does it have a `context.Context` first-arg convention? If not, **REJECT** — cancellation is non-negotiable.
+6. Does adding it overlap with something already in your `go.mod`? Pick one.
+
+---
+
+## Sources
+
+- 2024 Go Developer Survey: https://go.dev/blog/survey2024-h1-results
+- Connect-Go docs: https://connectrpc.com/docs/go/getting-started
+- sqlc: https://docs.sqlc.dev
+- bubbletea v2 IME: https://github.com/code-yeongyu/bubbletea-wm (reference for `SetVirtualCursor(false)` pattern)
+- CLIProxyAPI (gin + SSE + WebSocket in production): https://github.com/router-for-me/CLIProxyAPI
+- slog blog: https://go.dev/blog/slog
diff --git a/plugins/omo/skills/programming/references/go/one-liners.md b/plugins/omo/skills/programming/references/go/one-liners.md
new file mode 100644
index 00000000..58a6f014
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/one-liners.md
@@ -0,0 +1,202 @@
+# One-Liners and Disposable Scripts
+
+Production hygiene with throwaway ergonomics. Go scripts get the same strict lints, the same type discipline, the same 250 LOC ceiling. The difference: they live as single `.go` files invoked via `go run`, not as full modules.
+
+Python has PEP 723 + `uv run`. Rust has `rust-script`. **Go has `go run` directly** — no extra tooling needed.
+
+---
+
+## Pattern 1: Single-file `go run`
+
+A `.go` file with a `main` package, run directly:
+
+```go
+//go:build ignore
+// fetch.go — fetch a URL and print body length.
+//
+// Usage:
+// go run fetch.go <url>
+
+package main
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+)
+
+func main() {
+ if len(os.Args) < 2 {
+ log.Fatal("usage: go run fetch.go <url>")
+ }
+ resp, err := http.Get(os.Args[1])
+ if err != nil { log.Fatal(err) }
+ defer resp.Body.Close()
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil { log.Fatal(err) }
+
+ fmt.Printf("%d bytes\n", len(body))
+}
+```
+
+Run: `go run fetch.go https://example.com`.
+
+The `//go:build ignore` directive keeps this file out of `go build ./...` — it is a script, not part of the module. Without that line, every `.go` file in the package gets compiled into your binary.
+
+---
+
+## Pattern 2: Throwaway directory under `scripts/`
+
+```
+myproject/
+├── go.mod
+├── internal/...
+└── scripts/
+ ├── seed/
+ │ └── main.go # `go run ./scripts/seed`
+ ├── migrate/
+ │ └── main.go
+ └── one-time-fix/
+ └── main.go
+```
+
+Each `scripts/<name>/main.go` is its own `main` package. Invoke as `go run ./scripts/seed/`. Dependencies are shared with the parent module — no separate `go.mod`.
+
+This is the right pattern when:
+
+- You need module deps (sqlc, pgx, your own internal packages).
+- You want IDE support, type-checking, test coverage.
+- The script lives alongside the project, runs in CI.
+
+---
+
+## Pattern 3: Inline `go run` from shell
+
+```bash
+go run -mod=mod <(cat <<'EOF'
+package main
+import "fmt"
+func main() { fmt.Println("hello") }
+EOF
+)
+```
+
+Rare, but useful for one-shot terminal experiments. The `<(...)` is process substitution; `go run -mod=mod` reads from stdin.
+
+---
+
+## Hard rules for scripts
+
+Even a 30-line script follows the philosophy:
+
+1. **Typed flags via `flag` or `pflag`**, not `os.Args` string parsing past 2 args.
+ ```go
+ var (
+ url = flag.String("url", "", "URL to fetch")
+ limit = flag.Int("limit", 100, "max bytes")
+ )
+ flag.Parse()
+ if *url == "" { log.Fatal("--url required") }
+ ```
+
+2. **`context.Context` propagation** wherever I/O happens.
+ ```go
+ ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
+ defer cancel()
+ req, _ := http.NewRequestWithContext(ctx, "GET", *url, nil)
+ ```
+
+3. **`log.Fatal` is fine in `main()`** of a script (programmer error / fatal path), but **never inside any function the script imports.** Library code returns errors.
+
+4. **Errors get wrapped.** Same rule as production code:
+ ```go
+ if err != nil { return fmt.Errorf("fetch %s: %w", *url, err) }
+ ```
+
+5. **Resources released via `defer`.** No "I'll fix it later".
+
+6. **slog for output if it must be parseable.** `fmt.Println` for one-shot terminal output is fine.
+
+7. **No more than 250 pure LOC.** If it grows, it stops being a script and becomes a subcommand of your CLI tool.
+
+---
+
+## Pattern 4: Standalone tool with deps — temporary module
+
+Some scripts need deps the parent module does not have. Two options:
+
+### Option A — script in its own tiny module
+
+```bash
+mkdir /tmp/migrate-tool && cd $_
+go mod init scratch.local/migrate-tool
+go get github.com/pressly/goose/v3
+cat > main.go <<'EOF'
+package main
+import ... // use goose
+func main() { ... }
+EOF
+go run .
+```
+
+Run, then delete `/tmp/migrate-tool`. Throwaway.
+
+### Option B — `gorun` (community tool)
+
+```bash
+go install github.com/erning/gorun@latest
+
+cat > script.go <<'EOF'
+//usr/bin/env gorun "$0" "$@"; exit
+// /// go.mod
+// module scratch
+// go 1.23
+// require github.com/spf13/cobra v1.8.0
+// ///
+
+package main
+...
+EOF
+chmod +x script.go
+./script.go
+```
+
+`gorun` parses the inline `go.mod` block, materializes a temp module, runs the script. Niche tool — only if you want the executable-script experience.
+
+---
+
+## When a script becomes a CLI
+
+If your script needs:
+
+- More than one subcommand
+- Long-term storage of state
+- Help text more than a paragraph
+- Repeated invocations from CI
+
+... promote it to a real CLI tool via `cobra` — see `cobra-stack.md`. The boundary is fuzzy; trust your judgment, but **a 500-line "script" is not a script.**
+
+---
+
+## Antipatterns
+
+| Bad | Why | Good |
+|---|---|---|
+| `os.Args[1]` indexing without length check | Panics on missing arg | `flag.Parse()` with explicit checks |
+| `log.Fatal` inside a function the script imports | Crashes caller's process | Return error |
+| `panic(err)` for expected failures | Same as above | `log.Fatal` in `main`, error return elsewhere |
+| Skipping `defer resp.Body.Close()` because "it's a script" | Leaks fd | Always close |
+| One 800-LOC `main.go` "to keep it simple" | Now harder to read than a real CLI | Promote to `cmd/<name>/` with subcommands |
+| `// TODO: handle error` | Production-grade hygiene means production-grade hygiene | Handle now or document why ignored |
+
+---
+
+## Sources
+
+- `go run` docs: https://pkg.go.dev/cmd/go#hdr-Compile_and_run_Go_program
+- `//go:build` constraints: https://pkg.go.dev/cmd/go#hdr-Build_constraints
+- `signal.NotifyContext`: https://pkg.go.dev/os/signal#NotifyContext
+- gorun: https://github.com/erning/gorun
diff --git a/plugins/omo/skills/programming/references/go/sqlc-pgx.md b/plugins/omo/skills/programming/references/go/sqlc-pgx.md
new file mode 100644
index 00000000..6b6dbecd
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/sqlc-pgx.md
@@ -0,0 +1,471 @@
+# Database Stack — sqlc + pgx + goose + testcontainers
+
+The canonical 2026 PostgreSQL stack. **Type-safe SQL with zero runtime reflection**, hot-path-friendly connection pooling, sane migrations, real Postgres in tests.
+
+If you came here from a `gorm` project: gorm is rejected. See "Why not gorm" at the end.
+
+---
+
+## Toolchain
+
+```bash
+go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest
+go install github.com/pressly/goose/v3/cmd/goose@latest
+```
+
+---
+
+## Layout
+
+```
+internal/store/
+├── sqlc.yaml # sqlc config
+├── schema.sql # the cumulative DDL sqlc parses
+├── queries/ # one *.sql per resource
+│ ├── users.sql
+│ ├── orders.sql
+│ └── sessions.sql
+├── sqlc/ # GENERATED — do not hand-edit
+│ ├── db.go
+│ ├── models.go
+│ ├── users.sql.go
+│ ├── orders.sql.go
+│ └── sessions.sql.go
+├── migrations/ # goose migrations, ordered
+│ ├── 20260101000001_create_users.sql
+│ └── 20260102000001_add_orders.sql
+├── pool.go # pgxpool factory
+├── user_store.go # domain-facing wrapper around sqlc
+└── user_store_test.go # testcontainers integration test
+```
+
+---
+
+## `sqlc.yaml`
+
+```yaml
+version: "2"
+sql:
+ - engine: "postgresql"
+ schema: "schema.sql"
+ queries: "queries"
+ gen:
+ go:
+ package: "sqlc"
+ out: "sqlc"
+ sql_package: "pgx/v5"
+ emit_json_tags: false
+ emit_prepared_queries: false
+ emit_interface: true # generates a Querier interface
+ emit_exact_table_names: false
+ emit_pointers_for_null_types: true
+ emit_empty_slices: true
+ overrides:
+ - db_type: "uuid"
+ go_type:
+ import: "github.com/google/uuid"
+ type: "UUID"
+ - db_type: "timestamptz"
+ go_type:
+ import: "time"
+ type: "Time"
+```
+
+Key choices:
+
+- `sql_package: "pgx/v5"` — generated code uses pgx directly, not `database/sql`. Faster, type-safer.
+- `emit_interface: true` — generates a `Querier` interface. Lets stores accept either `*pgxpool.Pool` or `pgx.Tx` for transaction support.
+- `emit_pointers_for_null_types: true` — nullable columns become `*T`, not `sql.NullString`. Cleaner mapping to domain types.
+- `overrides` for `uuid` → `google/uuid.UUID` and `timestamptz` → `time.Time`.
+
+---
+
+## `schema.sql`
+
+```sql
+-- internal/store/schema.sql
+-- The CUMULATIVE schema sqlc parses. Not migrations — the end state.
+-- Regenerate from a fresh DB via `pg_dump --schema-only`, or hand-maintain.
+
+CREATE TABLE users (
+ id UUID PRIMARY KEY,
+ email TEXT NOT NULL UNIQUE,
+ username TEXT NOT NULL UNIQUE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE INDEX idx_users_created_at ON users(created_at DESC);
+```
+
+---
+
+## `queries/users.sql`
+
+```sql
+-- name: GetUser :one
+SELECT id, email, username, created_at
+FROM users
+WHERE id = $1;
+
+-- name: ListUsers :many
+SELECT id, email, username, created_at
+FROM users
+ORDER BY created_at DESC
+LIMIT $1 OFFSET $2;
+
+-- name: CreateUser :one
+INSERT INTO users (id, email, username)
+VALUES ($1, $2, $3)
+RETURNING id, email, username, created_at;
+
+-- name: UpdateUserEmail :exec
+UPDATE users
+SET email = $2
+WHERE id = $1;
+
+-- name: DeleteUser :exec
+DELETE FROM users WHERE id = $1;
+```
+
+sqlc directives:
+
+- `:one` — exactly one row; returns `(T, error)`. Returns `pgx.ErrNoRows` on miss.
+- `:many` — zero or more rows; returns `([]T, error)`.
+- `:exec` — no rows returned; returns `error`.
+- `:execrows` — returns `(int64, error)` with affected row count.
+- `:batchone` / `:batchmany` / `:batchexec` — pgx batch mode for bulk operations.
+
+Run `task gen:sqlc` (or `sqlc generate`). The generated file is committed; CI checks it is up-to-date.
+
+---
+
+## Generated code shape (`sqlc/users.sql.go`)
+
+```go
+// GENERATED — do not edit
+type User struct {
+ ID uuid.UUID
+ Email string
+ Username string
+ CreatedAt time.Time
+}
+
+const getUser = `-- name: GetUser :one
+SELECT id, email, username, created_at FROM users WHERE id = $1`
+
+func (q *Queries) GetUser(ctx context.Context, id uuid.UUID) (User, error) {
+ row := q.db.QueryRow(ctx, getUser, id)
+ var u User
+ err := row.Scan(&u.ID, &u.Email, &u.Username, &u.CreatedAt)
+ return u, err
+}
+```
+
+Type-safe inputs, type-safe outputs, compile-time-checked column-to-field mapping. **A schema change that drops a column breaks compilation.** Hand-rolled SQL would have failed at runtime.
+
+---
+
+## `store/pool.go`
+
+```go
+package store
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+func NewPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
+ cfg, err := pgxpool.ParseConfig(dsn)
+ if err != nil { return nil, fmt.Errorf("parse dsn: %w", err) }
+
+ cfg.MaxConns = 25
+ cfg.MinConns = 5
+ cfg.MaxConnLifetime = time.Hour
+ cfg.MaxConnIdleTime = 30 * time.Minute
+ cfg.HealthCheckPeriod = 1 * time.Minute
+
+ pool, err := pgxpool.NewWithConfig(ctx, cfg)
+ if err != nil { return nil, fmt.Errorf("connect: %w", err) }
+
+ if err := pool.Ping(ctx); err != nil {
+ pool.Close()
+ return nil, fmt.Errorf("ping: %w", err)
+ }
+ return pool, nil
+}
+```
+
+`pgxpool.Pool` is `Querier`-compatible (implements the interface sqlc generates). Same pool flows into sqlc queries unchanged.
+
+---
+
+## `store/user_store.go` — domain ↔ sqlc
+
+```go
+package store
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/your-org/myservice/internal/domain"
+ "github.com/your-org/myservice/internal/store/sqlc"
+)
+
+type UserStore struct {
+ q *sqlc.Queries
+}
+
+func NewUserStore(pool *pgxpool.Pool) *UserStore {
+ return &UserStore{q: sqlc.New(pool)}
+}
+
+func (s *UserStore) Get(ctx context.Context, id domain.UserID) (domain.User, error) {
+ row, err := s.q.GetUser(ctx, uuid.UUID(id))
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return domain.User{}, domain.ErrUserNotFound
+ }
+ return domain.User{}, fmt.Errorf("get user %s: %w", id, err)
+ }
+ return rowToDomain(row)
+}
+
+func (s *UserStore) Create(ctx context.Context, u domain.User) (domain.User, error) {
+ row, err := s.q.CreateUser(ctx, sqlc.CreateUserParams{
+ ID: uuid.UUID(u.ID),
+ Email: u.Email.String(),
+ Username: u.Username.String(),
+ })
+ if err != nil {
+ return domain.User{}, fmt.Errorf("create user: %w", err)
+ }
+ return rowToDomain(row)
+}
+
+func rowToDomain(r sqlc.User) (domain.User, error) {
+ email, err := domain.NewEmail(r.Email)
+ if err != nil {
+ return domain.User{}, fmt.Errorf("db invariant: email %q: %w", r.Email, err)
+ }
+ username, err := domain.NewUsername(r.Username)
+ if err != nil {
+ return domain.User{}, fmt.Errorf("db invariant: username %q: %w", r.Username, err)
+ }
+ return domain.User{
+ ID: domain.UserID(r.ID),
+ Email: email,
+ Username: username,
+ CreatedAt: r.CreatedAt,
+ }, nil
+}
+```
+
+The wrapping is verbose. **That is the point.** sqlc rows are storage representations; domain types are business representations. Mapping them explicitly is where invariants are enforced.
+
+`pgx.ErrNoRows` becomes `domain.ErrUserNotFound` — callers never see storage-level errors.
+
+---
+
+## Transactions — pgx.Tx satisfies the Querier interface
+
+```go
+func (s *UserStore) CreateWithProfile(
+ ctx context.Context,
+ pool *pgxpool.Pool,
+ u domain.User,
+ p domain.Profile,
+) error {
+ tx, err := pool.Begin(ctx)
+ if err != nil { return fmt.Errorf("begin: %w", err) }
+ defer tx.Rollback(ctx) // no-op if Commit succeeded
+
+ q := s.q.WithTx(tx) // sqlc.Queries bound to the tx
+
+ if _, err := q.CreateUser(ctx, /* ... */); err != nil {
+ return fmt.Errorf("create user: %w", err)
+ }
+ if _, err := q.CreateProfile(ctx, /* ... */); err != nil {
+ return fmt.Errorf("create profile: %w", err)
+ }
+ return tx.Commit(ctx)
+}
+```
+
+Pattern:
+
+- `defer tx.Rollback(ctx)` immediately after `Begin` — safe even after Commit (returns "tx closed", which we ignore via the unhandled return).
+- `q.WithTx(tx)` returns a `*Queries` bound to the tx.
+- Last line: `tx.Commit(ctx)`.
+
+For nested transactions across multiple stores, accept a `Querier` parameter:
+
+```go
+func (s *UserStore) CreateTx(ctx context.Context, q sqlc.Querier, u domain.User) (domain.User, error) {
+ // uses q instead of s.q — caller decides if it's pool or tx
+}
+```
+
+---
+
+## Migrations — goose
+
+```bash
+goose -dir internal/store/migrations create create_users sql
+```
+
+```sql
+-- migrations/20260101000001_create_users.sql
+-- +goose Up
+CREATE TABLE users (
+ id UUID PRIMARY KEY,
+ email TEXT NOT NULL UNIQUE,
+ username TEXT NOT NULL UNIQUE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+-- +goose Down
+DROP TABLE users;
+```
+
+Run:
+
+```bash
+goose -dir internal/store/migrations postgres "$DATABASE_URL" up
+goose -dir internal/store/migrations postgres "$DATABASE_URL" status
+goose -dir internal/store/migrations postgres "$DATABASE_URL" down
+```
+
+Rules:
+
+- One DDL change per migration. Never combine schema + data migrations in one file.
+- `Down` is real, not a stub. CI runs `up` → `down` → `up` on a fresh container to prove reversibility.
+- Migrations are append-only. Never edit a merged migration; add a new one.
+
+`goose` can run programmatically as well:
+
+```go
+import "github.com/pressly/goose/v3"
+
+if err := goose.UpContext(ctx, db, "migrations"); err != nil { ... }
+```
+
+Useful for tools that own their schema (CI runner, integration test setup).
+
+---
+
+## Integration tests — testcontainers
+
+```go
+package store_test
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "github.com/testcontainers/testcontainers-go/modules/postgres"
+)
+
+func newTestDB(t *testing.T) *pgxpool.Pool {
+ t.Helper()
+ ctx := context.Background()
+
+ pgC, err := postgres.Run(ctx,
+ "postgres:16-alpine",
+ postgres.WithDatabase("test"),
+ postgres.WithUsername("test"),
+ postgres.WithPassword("test"),
+ postgres.BasicWaitStrategies(),
+ )
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = pgC.Terminate(ctx) })
+
+ dsn, err := pgC.ConnectionString(ctx, "sslmode=disable")
+ require.NoError(t, err)
+
+ pool, err := store.NewPool(ctx, dsn)
+ require.NoError(t, err)
+ t.Cleanup(pool.Close)
+
+ require.NoError(t, goose.UpContext(ctx, /* sql.DB from pool */, "../migrations"))
+ return pool
+}
+
+func TestUserStore_Create_returns_new_user(t *testing.T) {
+ // Given
+ pool := newTestDB(t)
+ s := store.NewUserStore(pool)
+ ctx := context.Background()
+
+ // When
+ user, err := s.Create(ctx, domain.User{
+ ID: domain.UserID(uuid.Must(uuid.NewV7())),
+ Email: mustEmail("[email protected]"),
+ Username: mustUsername("alice"),
+ })
+
+ // Then
+ require.NoError(t, err)
+ require.NotEmpty(t, user.ID)
+
+ fetched, err := s.Get(ctx, user.ID)
+ require.NoError(t, err)
+ require.Equal(t, user.Email, fetched.Email)
+}
+```
+
+testcontainers spins a real Postgres in Docker, runs migrations, hands you a pool. Tests are slow (~2s startup) but **real** — no fake that diverges from production.
+
+For test suites with many cases, share one container across tests in the same package via `TestMain`:
+
+```go
+var testPool *pgxpool.Pool
+
+func TestMain(m *testing.M) {
+ ctx := context.Background()
+ pgC, _ := postgres.Run(ctx, "postgres:16-alpine", /* ... */)
+ defer pgC.Terminate(ctx)
+ dsn, _ := pgC.ConnectionString(ctx, "sslmode=disable")
+ testPool, _ = store.NewPool(ctx, dsn)
+ // run migrations once
+ os.Exit(m.Run())
+}
+```
+
+Each test then uses a transaction it rolls back at the end — fast and isolated.
+
+---
+
+## Why NOT gorm
+
+| Concern | gorm | sqlc + pgx |
+|---|---|---|
+| Type safety | runtime reflection; column-to-field via tags | compile-time-checked from SQL |
+| Performance | 2–5x slower than pgx | pgx is the fastest Go pg driver |
+| N+1 queries | encouraged by `Preload` API | explicit JOIN in `.sql` |
+| Migrations | AutoMigrate (unsafe in prod) | goose, explicit |
+| Debugging | "what query did it run?" requires logging | the query IS the source |
+| Cancellation | spotty ctx support | first-class |
+| Active development | Yes but with churn and breaking changes | sqlc is stable |
+
+Existing gorm projects: leave them. New code: sqlc + pgx.
+
+---
+
+## Sources
+
+- sqlc docs: https://docs.sqlc.dev
+- pgx: https://github.com/jackc/pgx
+- goose: https://github.com/pressly/goose
+- testcontainers-go: https://golang.testcontainers.org
+- pgx pool config: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool#Config
diff --git a/plugins/omo/skills/programming/references/go/testing.md b/plugins/omo/skills/programming/references/go/testing.md
new file mode 100644
index 00000000..469f5a46
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/testing.md
@@ -0,0 +1,467 @@
+# Testing
+
+TDD shape, table-driven tests, `require` vs `assert`, snapshot tests, property-based tests, integration tests with testcontainers, goroutine-leak detection. The discipline in `programming/SKILL.md` (Given/When/Then, less mock the better, efficient AND accurate) — this document gives the Go-specific recipes.
+
+---
+
+## Tools
+
+| Need | Use |
+|---|---|
+| Assertions | `stretchr/testify/require` (and `assert` only inside table loops) |
+| Mocks | `go.uber.org/mock` (gomock successor) |
+| Goroutine leaks | `go.uber.org/goleak` |
+| Snapshots / golden | `hexops/autogold/v2` |
+| Property-based | `pgregory.net/rapid` |
+| HTTP mocks (outbound) | `h2non/gock` |
+| HTTP test server (inbound) | stdlib `net/http/httptest` |
+| Integration containers | `testcontainers/testcontainers-go` |
+| TUI | `charm.land/bubbletea/v2/teatest` |
+| Bench tooling | stdlib `testing.B` + `perf.dev/benchstat` |
+
+---
+
+## Test naming — Given / When / Then in the name
+
+```go
+// ──── PATTERN ────
+// Test_<Subject>_<Outcome>_when_<Condition>
+// OR
+// Test_<Subject>_<Action>_<ExpectedOutcome>
+
+func Test_Email_NewEmail_lowercases_input(t *testing.T)
+func Test_Email_NewEmail_rejects_input_without_at_sign(t *testing.T)
+func Test_UserService_Create_persists_user_when_inputs_valid(t *testing.T)
+func Test_UserService_Create_returns_validation_error_when_email_invalid(t *testing.T)
+```
+
+A test name should answer "what behavior is this asserting?" without reading the body. Names that need a comment to explain them are misnamed.
+
+---
+
+## Single test — explicit Given/When/Then
+
+```go
+func Test_Email_NewEmail_rejects_input_without_at_sign(t *testing.T) {
+ // Given
+ raw := "not-an-email"
+
+ // When
+ _, err := domain.NewEmail(raw)
+
+ // Then
+ require.Error(t, err)
+ require.ErrorIs(t, err, domain.ErrInvalidEmail)
+}
+```
+
+`require.*` fails the test immediately on miss. Use `require` for preconditions and primary assertions. Use `assert.*` only inside table-driven loops where you want all cases to report.
+
+---
+
+## Table-driven tests
+
+```go
+func Test_Email_NewEmail(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ want string
+ wantErr error
+ }{
+ {"lowercases", "[email protected]", "[email protected]", nil},
+ {"trims whitespace", " [email protected] ", "[email protected]", nil},
+ {"rejects missing @", "no-at-sign", "", domain.ErrInvalidEmail},
+ {"rejects empty", "", "", domain.ErrInvalidEmail},
+ {"rejects too long", strings.Repeat("a", 256) + "@e.com", "", domain.ErrInvalidEmail},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ // When
+ got, err := domain.NewEmail(tt.input)
+
+ // Then
+ if tt.wantErr != nil {
+ require.ErrorIs(t, err, tt.wantErr)
+ return
+ }
+ require.NoError(t, err)
+ assert.Equal(t, tt.want, got.String())
+ })
+ }
+}
+```
+
+Rules:
+
+- One **scenario** per row, not one **assertion** per row.
+- Subtest names are sentences in lowercase; `t.Run(tt.name, ...)` makes them filterable: `go test -run Test_Email_NewEmail/rejects_missing_@`.
+- The loop body itself is Given/When/Then in shape.
+- For Go 1.22+, the loop var capture works correctly without the `tt := tt` shadow line — the `copyloopvar` linter enforces the new style.
+
+---
+
+## Less mocks — the priority order
+
+In Go specifically:
+
+1. **Real implementation.** Domain types, pure functions, value objects — instantiate them. They are fast.
+2. **In-memory fake** that satisfies the interface. Has its own test suite proving behavioral parity with the real impl.
+3. **`httptest.Server`** for HTTP collaborators (real wire, no internet).
+4. **`testcontainers`** for stateful collaborators (Postgres, Redis, S3-compatible, Kafka).
+5. **gomock** ONLY for: clocks, randomness, third-party SaaS with no sandbox.
+
+### Example: an in-memory fake
+
+```go
+// Real interface
+type UserRepo interface {
+ Save(ctx context.Context, u domain.User) error
+ Get(ctx context.Context, id domain.UserID) (domain.User, error)
+}
+
+// In-memory fake — production-quality, tested separately
+type FakeUserRepo struct {
+ mu sync.RWMutex
+ users map[domain.UserID]domain.User
+}
+
+func NewFakeUserRepo() *FakeUserRepo {
+ return &FakeUserRepo{users: map[domain.UserID]domain.User{}}
+}
+
+func (r *FakeUserRepo) Save(ctx context.Context, u domain.User) error {
+ r.mu.Lock(); defer r.mu.Unlock()
+ r.users[u.ID] = u
+ return nil
+}
+
+func (r *FakeUserRepo) Get(ctx context.Context, id domain.UserID) (domain.User, error) {
+ r.mu.RLock(); defer r.mu.RUnlock()
+ u, ok := r.users[id]
+ if !ok { return domain.User{}, domain.ErrUserNotFound }
+ return u, nil
+}
+```
+
+The fake has the same observable behavior as the real one. Tests against `FakeUserRepo` survive when the production repo's internals change. Tests against a gomock stub of `UserRepo` break.
+
+**A test passing against a fake AND a test passing against the real impl is the gold standard.** Run the same test suite twice — once with the fake, once with testcontainers. The fakes earn their keep when the suites diverge.
+
+### Example: gomock for the unmockable
+
+```go
+//go:generate mockgen -source=clock.go -destination=mocks/clock_mock.go -package=mocks
+
+type Clock interface {
+ Now() time.Time
+}
+
+// In a test:
+ctrl := gomock.NewController(t)
+clock := mocks.NewMockClock(ctrl)
+clock.EXPECT().Now().Return(fixedTime).AnyTimes()
+```
+
+Mock the narrowest seam. Never mock `UserRepo` if a fake suffices.
+
+---
+
+## E2E scenario tests
+
+```go
+//go:build e2e
+
+func Test_E2E_user_can_signup_then_login(t *testing.T) {
+ // Given — full server in a goroutine
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ pool := newTestDB(t) // testcontainers Postgres
+ server := startServer(t, pool) // real gin engine on a random port
+ defer server.Close()
+
+ client := server.Client()
+
+ // When — sign up
+ resp, err := client.Post(server.URL+"/api/v1/users",
+ "application/json",
+ strings.NewReader(`{"email":"[email protected]","username":"alice","password":"PassWord!23"}`),
+ )
+ require.NoError(t, err)
+ require.Equal(t, 201, resp.StatusCode)
+
+ // When — log in
+ resp, err = client.Post(server.URL+"/api/v1/auth/login",
+ "application/json",
+ strings.NewReader(`{"email":"[email protected]","password":"PassWord!23"}`),
+ )
+ require.NoError(t, err)
+ require.Equal(t, 200, resp.StatusCode)
+
+ var body struct{ Token string `json:"token"` }
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&body))
+ require.NotEmpty(t, body.Token)
+
+ // Then — token works on protected endpoint
+ req, _ := http.NewRequestWithContext(ctx, "GET", server.URL+"/api/v1/me", nil)
+ req.Header.Set("Authorization", "Bearer "+body.Token)
+ resp, err = client.Do(req)
+ require.NoError(t, err)
+ require.Equal(t, 200, resp.StatusCode)
+}
+```
+
+Patterns:
+
+- `//go:build e2e` build tag separates slow E2E from fast unit tests. Run with `go test -tags=e2e ./...`.
+- One narrative per test: "user can sign up then log in". One `Test_E2E_*` per user-visible outcome.
+- Real DB via testcontainers, real gin engine, real HTTP. **No mocks.** The point is to catch integration bugs.
+- Bounded context — every E2E gets a `context.WithTimeout` so failures don't hang CI.
+
+---
+
+## Goroutine leak detection
+
+```go
+package mypkg
+
+import (
+ "testing"
+ "go.uber.org/goleak"
+)
+
+func TestMain(m *testing.M) {
+ goleak.VerifyTestMain(m,
+ goleak.IgnoreTopFunction("github.com/prometheus/client_golang/prometheus.(*Registry)..."),
+ )
+}
+```
+
+One line at the top of every package that spawns goroutines. Catches the bug class the race detector cannot.
+
+---
+
+## Snapshot / golden tests — `autogold`
+
+```go
+import "github.com/hexops/autogold/v2"
+
+func Test_RenderHelp_matches_snapshot(t *testing.T) {
+ // Given
+ cmd := newRootCmd()
+
+ // When
+ out := captureOutput(t, func() { _ = cmd.Help() })
+
+ // Then
+ autogold.ExpectFile(t, out)
+}
+```
+
+First run: `go test -update ./...` writes `testdata/Test_RenderHelp.golden`. Future runs compare; failures show a diff. Re-approve intentional changes with `-update`.
+
+**Use snapshots for STRUCTURE, not BEHAVIOR.** Good targets:
+
+- CLI `--help` output
+- JSON response shape
+- Generated SQL queries
+- Rendered prompts (assert the structure, not exact wording — see SKILL.md prompt-test rule)
+
+Bad targets: a function's return value where you should `require.Equal` on the actual structure.
+
+---
+
+## Property-based tests — `rapid`
+
+```go
+import "pgregory.net/rapid"
+
+func Test_Email_NewEmail_then_String_roundtrips(t *testing.T) {
+ rapid.Check(t, func(t *rapid.T) {
+ // Given — generate valid emails
+ local := rapid.StringMatching(`[a-z]{3,10}`).Draw(t, "local")
+ domain := rapid.StringMatching(`[a-z]{3,10}\.com`).Draw(t, "domain")
+ raw := local + "@" + domain
+
+ // When
+ e, err := domain.NewEmail(raw)
+ require.NoError(t, err)
+
+ // Then — round-trip property
+ e2, err := domain.NewEmail(e.String())
+ require.NoError(t, err)
+ require.Equal(t, e, e2)
+ })
+}
+```
+
+`rapid` shrinks failing cases to minimal counterexamples. Use for:
+
+- Round-trips (parse → serialize → parse).
+- Algebraic properties (sort produces ordered, dedup is idempotent, JSON marshal/unmarshal is involutive).
+- Invariants under random input (validator never panics, serializer never produces invalid UTF-8).
+
+---
+
+## HTTP testing — `httptest`
+
+### Server side
+
+```go
+func Test_GetUser_returns_user_for_existing_id(t *testing.T) {
+ // Given
+ svc := newSvcWithFake(t)
+ r := gin.New()
+ h := &Handler{Users: svc}
+ h.Mount(r)
+
+ req := httptest.NewRequest("GET", "/api/v1/users/u-1", nil)
+ rec := httptest.NewRecorder()
+
+ // When
+ r.ServeHTTP(rec, req)
+
+ // Then
+ require.Equal(t, 200, rec.Code)
+ var body domain.User
+ require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
+ require.Equal(t, "u-1", string(body.ID))
+}
+```
+
+### Client side — `httptest.NewServer`
+
+```go
+func Test_Client_retries_on_500(t *testing.T) {
+ // Given — fake upstream
+ var calls int
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ if calls < 3 {
+ w.WriteHeader(500)
+ return
+ }
+ w.WriteHeader(200)
+ _, _ = w.Write([]byte(`{"ok":true}`))
+ }))
+ defer srv.Close()
+
+ client := myclient.New(srv.URL)
+
+ // When
+ err := client.DoSomething(context.Background())
+
+ // Then
+ require.NoError(t, err)
+ require.Equal(t, 3, calls)
+}
+```
+
+`httptest.NewServer` spins a real HTTP server on a random port. The fake handler implements the upstream contract. Test the client against the contract, not the implementation.
+
+---
+
+## Determinism — the cardinal rules
+
+- **No `time.Sleep` in tests.** If you need delay, you need a Clock injection.
+- **`go test -shuffle=on`** in every CI run.
+- **`go test -count=1`** to defeat the cache.
+- **Subscribe to the event, do not poll for it.** Channels, callbacks, `t.Cleanup` over polling.
+- **`t.Parallel()`** for tests that share no state. Speeds up large suites by 4-8x.
+
+A test that fails 1-in-10 runs is a bug, not flake. The race detector + `-shuffle=on` + ordering hygiene catches >95% of "flake".
+
+---
+
+## Benchmarks — `testing.B` + `benchstat`
+
+```go
+func Benchmark_NewEmail(b *testing.B) {
+ for b.Loop() { // Go 1.24+ idiom, replaces `for i := 0; i < b.N; i++`
+ _, _ = domain.NewEmail("[email protected]")
+ }
+}
+```
+
+Run:
+
+```bash
+go test -bench=. -count=10 -benchmem ./... | tee bench.txt
+benchstat bench.txt # statistical comparison
+```
+
+Always `-count=10` for stable means. `-benchmem` reports allocations. A 5%-slower benchmark in one run is noise; 10 runs + benchstat tells you what is real.
+
+To compare before/after a change:
+
+```bash
+git stash
+go test -bench=. -count=10 ./... > before.txt
+git stash pop
+go test -bench=. -count=10 ./... > after.txt
+benchstat before.txt after.txt
+```
+
+---
+
+## Coverage — the right target
+
+Run:
+
+```bash
+go test -race -shuffle=on -coverprofile=cover.out ./...
+go tool cover -html=cover.out -o cover.html
+```
+
+**Aim for 80%+ on `internal/domain` and `internal/service`.** Boundary code (handlers, store mappers) is exercised by integration tests, where line coverage understates what is actually verified. Do not chase 100% — the last 5% is usually error paths that need fault-injection to hit.
+
+The `golangci-lint` config does not enforce a minimum — coverage as a CI gate becomes a goal-displacement metric. Treat it as feedback, not requirement.
+
+---
+
+## TUI testing — `teatest`
+
+```go
+import teatest "charm.land/bubbletea/v2/teatest"
+
+func Test_Counter_increments_on_space(t *testing.T) {
+ // Given
+ tm := teatest.NewTestModel(t, initial(), teatest.WithInitialTermSize(80, 24))
+
+ // When
+ tm.Send(tea.KeyPressMsg{Code: ' '})
+
+ // Then
+ final := tm.FinalModel(t).(model)
+ require.Equal(t, 1, final.count)
+}
+```
+
+For full-view regression, snapshot the rendered output via `autogold`.
+
+---
+
+## Antipatterns the skill rejects
+
+| Bad | Why | Good |
+|---|---|---|
+| `if got != want { t.Errorf("expected %v got %v", want, got) }` | Reinvents `require.Equal` | Use testify |
+| `time.Sleep(100 * time.Millisecond)` after triggering async work | Flake | Subscribe to completion signal, bounded await |
+| `t.Skip(...)` to silence a known failure | Buries the bug | Fix or open an issue; never silently skip |
+| One mega-test asserting 12 things | First failure hides next 11 | Split by `Then` |
+| Snapshot-everything | Locks formatting, not behavior | Snapshots for structure, asserts for values |
+| Mock every collaborator | Test asserts implementation, not behavior | Real or fake, never mock everything |
+| Test calls private function via `_test.go` in same package only | Couples test to implementation | Test through the public surface |
+
+---
+
+## Sources
+
+- testify: https://github.com/stretchr/testify
+- goleak: https://github.com/uber-go/goleak
+- autogold: https://github.com/hexops/autogold
+- rapid: https://pkg.go.dev/pgregory.net/rapid
+- testcontainers-go: https://golang.testcontainers.org
+- benchstat: https://pkg.go.dev/golang.org/x/perf/cmd/benchstat
+- "Go test naming conventions" (Dave Cheney): https://dave.cheney.net/practical-go/presentations/qcon-china.html
diff --git a/plugins/omo/skills/programming/references/go/type-patterns.md b/plugins/omo/skills/programming/references/go/type-patterns.md
new file mode 100644
index 00000000..e65b20d5
--- /dev/null
+++ b/plugins/omo/skills/programming/references/go/type-patterns.md
@@ -0,0 +1,298 @@
+# Type Patterns
+
+How to use Go's *limited* type system to catch bugs at compile time. Go gives you fewer tools than Python/TS/Rust — this document covers the four patterns that buy back most of the safety.
+
+The four patterns:
+
+1. **Named types** for branding primitives (the Go answer to `NewType` / branded TS).
+2. **Smart constructors with unexported fields** for parse-don't-validate.
+3. **Sealed interfaces** for sum types, with `type switch` + `exhaustive` linter.
+4. **Generics with constraints** for bounded polymorphism (1.18+).
+
+---
+
+## 1. Named types — distinct primitives
+
+Same underlying type, different meaning. The Go type checker prevents *implicit* mixing — but explicit conversion is always possible. Treat this as a contract enforced at boundaries.
+
+```go
+package domain
+
+type UserID string
+type OrderID string
+type EmailRaw string // raw, unvalidated string from input
+
+func GetUser(id UserID) User { /* ... */ }
+
+uid := UserID("u-123")
+oid := OrderID("o-456")
+
+GetUser(uid) // ✅ OK
+GetUser(oid) // ❌ cannot use oid (type OrderID) as UserID
+GetUser("u-123") // ❌ untyped string literal — Go DOES catch this
+GetUser(UserID("u-123")) // ✅ explicit conversion — accept it
+```
+
+**Use when**: IDs, opaque tokens, foreign keys, units that share a base primitive.
+
+**Reality check**: Go does NOT prevent `UserID(orderIDAsString)`. The defense is **smart constructors** for everything beyond an internal identifier. Use named types for cheap brand-only protection; combine with constructors for protection that actually holds.
+
+### Time-of-day units
+
+```go
+type Milliseconds int64
+type Seconds int64
+
+func (ms Milliseconds) ToSeconds() Seconds {
+ return Seconds(ms / 1000)
+}
+```
+
+No implicit `Milliseconds + Seconds`. The compiler refuses. Convert explicitly.
+
+---
+
+## 2. Smart constructors with unexported fields — the Go answer to Pydantic/Zod
+
+The single most important pattern in this document. **Go has no Pydantic. It has this.**
+
+```go
+package domain
+
+import (
+ "errors"
+ "regexp"
+ "strings"
+)
+
+var (
+ ErrInvalidEmail = errors.New("invalid email")
+ emailRe = regexp.MustCompile(`^[^@\s]+@[^@\s]+\.[^@\s]+$`)
+)
+
+// Email is a parsed, lowercased, valid email address.
+// The zero value is invalid; construct via NewEmail.
+type Email struct {
+ raw string // unexported — cannot be set from outside the package
+}
+
+func NewEmail(s string) (Email, error) {
+ s = strings.TrimSpace(strings.ToLower(s))
+ if !emailRe.MatchString(s) {
+ return Email{}, ErrInvalidEmail
+ }
+ return Email{raw: s}, nil
+}
+
+// String implements fmt.Stringer for printing.
+func (e Email) String() string { return e.raw }
+
+// MarshalJSON keeps the wire format unchanged.
+func (e Email) MarshalJSON() ([]byte, error) {
+ return []byte(`"` + e.raw + `"`), nil
+}
+
+// UnmarshalJSON is the parsing boundary — strict mode.
+func (e *Email) UnmarshalJSON(data []byte) error {
+ if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
+ return ErrInvalidEmail
+ }
+ parsed, err := NewEmail(string(data[1 : len(data)-1]))
+ if err != nil {
+ return err
+ }
+ *e = parsed
+ return nil
+}
+```
+
+**Why this works**:
+
+- `Email{raw: "anything"}` from outside the `domain` package is a compile error — `raw` is unexported.
+- The only way to obtain a non-zero `Email` is `NewEmail(...)`, which validates.
+- `UnmarshalJSON` routes wire input through the same constructor — boundary parsing is automatic.
+- Once a function signature has `email Email`, the caller has *proven* it is valid. No internal `if email == ""` checks.
+
+**Use for every domain value that has invariants**: emails, URLs, phone numbers, currency amounts, percentages, semver versions, IDs with format constraints, time ranges, anything you currently validate in three places.
+
+### The "zero value problem"
+
+Go's zero value (`Email{}`) is reachable. The mitigation is documentation + a `IsValid()` method when needed:
+
+```go
+func (e Email) IsZero() bool { return e.raw == "" }
+```
+
+Or accept it: receivers that take `Email` should *never* receive a zero-value `Email` in correct code. Tests verify it.
+
+---
+
+## 3. Sealed interfaces — sum types in Go
+
+Go has no sum types. The closest thing: an interface with an **unexported method** that only types in the same package can satisfy, dispatched via `type switch`, with the `exhaustive` linter ensuring completeness.
+
+```go
+package event
+
+// Event is a closed sum: Created | Updated | Deleted.
+// The sealed() method is unexported so external packages cannot add variants.
+type Event interface {
+ sealed()
+ OccurredAt() time.Time
+}
+
+type Created struct {
+ UserID UserID
+ Email Email
+ Timestamp time.Time
+}
+func (Created) sealed() {}
+func (e Created) OccurredAt() time.Time { return e.Timestamp }
+
+type Updated struct {
+ UserID UserID
+ Changes map[string]any
+ Timestamp time.Time
+}
+func (Updated) sealed() {}
+func (e Updated) OccurredAt() time.Time { return e.Timestamp }
+
+type Deleted struct {
+ UserID UserID
+ Reason string
+ Timestamp time.Time
+}
+func (Deleted) sealed() {}
+func (e Deleted) OccurredAt() time.Time { return e.Timestamp }
+```
+
+Consumer code:
+
+```go
+func Render(e event.Event) string {
+ switch v := e.(type) {
+ case event.Created:
+ return fmt.Sprintf("created %s with %s", v.UserID, v.Email)
+ case event.Updated:
+ return fmt.Sprintf("updated %s: %v", v.UserID, v.Changes)
+ case event.Deleted:
+ return fmt.Sprintf("deleted %s (reason: %s)", v.UserID, v.Reason)
+ default:
+ panic(fmt.Sprintf("unhandled event variant: %T", v))
+ }
+}
+```
+
+The `panic` in `default` is the Go equivalent of TS's `assertNever` or Python's `assert_never`. It is only reachable if a new variant is added without updating the switch.
+
+### The `exhaustive` linter — your compiler
+
+```yaml
+# .golangci.yml
+linters:
+ enable: [exhaustive]
+linters-settings:
+ exhaustive:
+ check:
+ - switch
+ - map
+ default-signifies-exhaustive: false
+```
+
+Now adding `event.Suspended` without updating `Render` is a **lint error**. This is the closest thing Go has to Rust's match exhaustiveness check. **Treat it as compulsory.**
+
+### Sealed interface gotchas
+
+- The method MUST be unexported (`sealed()`, not `Sealed()`). Otherwise other packages can implement it.
+- `type switch` with `*Created` vs `Created` matters — pick value receivers and value cases, or pointer receivers and pointer cases. **Mixing them causes silent miss.**
+- `interface{}` is not a sealed type. Anything implementing zero methods satisfies it. Sealed interfaces have at least the `sealed()` method.
+
+---
+
+## 4. Generics with constraints — bounded polymorphism
+
+Go 1.18+. Use for genuinely generic algorithms; **do not** use for "I want this to accept anything".
+
+```go
+import "cmp"
+
+// Ordered constraint includes all ordered types (int, float, string, …).
+func Max[T cmp.Ordered](a, b T) T {
+ if a > b { return a }
+ return b
+}
+
+// Custom constraint
+type Stringer interface {
+ String() string
+}
+
+func Join[T Stringer](items []T, sep string) string {
+ parts := make([]string, len(items))
+ for i, item := range items {
+ parts[i] = item.String()
+ }
+ return strings.Join(parts, sep)
+}
+```
+
+The `cmp.Ordered` (Go 1.21+), `cmp.Compare`, and `slices`/`maps` packages cover the common cases without you writing constraints.
+
+### When NOT to use generics
+
+- "I want to accept multiple types, so I'll make it generic." Use an **interface** instead. Generics are for parametric polymorphism (same code, different types). Interfaces are for behavioral polymorphism (different code behind a contract).
+- "I want to return `any`." Use a sealed interface and a `type switch`. `any` returns are anti-patterns past public APIs.
+
+---
+
+## 5. Type assertions — the controlled escape hatch
+
+```go
+// Bad — panics on failure
+e := evt.(event.Created)
+
+// Good — comma-ok form, always
+if e, ok := evt.(event.Created); ok {
+ // use e
+}
+
+// Use errors.As for error chains
+var pgErr *pgconn.PgError
+if errors.As(err, &pgErr) {
+ // pgErr is the wrapped pg error
+}
+```
+
+**The `errcheck` and `errorlint` linters reject bare type assertions on `error` values.** Use `errors.As`. See `error-handling.md`.
+
+---
+
+## 6. Pointers vs values — the only durable rule
+
+You will see endless debates. The rule that holds up:
+
+- **If a type has a mutex, never copy it.** Use `*T` everywhere.
+- **If a type is large (> 64 bytes) and read-only, pass by value or pointer is a measured choice.** Default to pointer for "large" things.
+- **Receivers must be consistent.** All methods on `T` either take `T` or `*T`. Don't mix. The `staticcheck` linter catches mixed-receiver bugs.
+- **`nil` pointer = absence. Zero value = "not set yet".** Choose ONE convention per type. Document it.
+
+---
+
+## 7. `any` / `interface{}` — when it is acceptable
+
+Almost never in domain code. Acceptable cases:
+
+- JSON parsing of genuinely heterogeneous payloads (and even then, prefer `json.RawMessage` + targeted parsing).
+- `fmt.Sprintf` arguments (variadic `any` is unavoidable here).
+- Generic container internals before the user-facing API.
+
+The skill rejects `any` in handler signatures, service signatures, store signatures. If you find yourself writing `func Handle(payload any) error`, you have a sealed-interface waiting to happen.
+
+---
+
+## Sources
+
+- "Parse, don't validate" — Alexis King: https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/
+- exhaustive linter: https://github.com/nishanths/exhaustive
+- Generics constraints: https://go.dev/blog/intro-generics
+- cmp.Ordered: https://pkg.go.dev/cmp
diff --git a/plugins/omo/skills/programming/references/python/README.md b/plugins/omo/skills/programming/references/python/README.md
new file mode 100644
index 00000000..0b3ebf64
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/README.md
@@ -0,0 +1,314 @@
+
+# Python Programmer
+
+Modern Python. Type-strict, stack-first, async-correct.
+
+## Philosophy
+
+The type checker is your compiler. Make illegal states unrepresentable. Parse at boundaries. Own resources explicitly. Every function has a contract; the type system enforces it.
+
+## Hard rules
+
+These are deliberate project choices. Violations are always wrong, not "style preferences".
+
+### Tooling
+
+| Category | Use | Never |
+|---|---|---|
+| Package manager | `uv` | pip, poetry, conda, pipenv |
+| Type checker | `basedpyright` (`typeCheckingMode = "all"`) | pyright, mypy |
+| Linter + formatter | `ruff` (`select = ["ALL"]`) | flake8, black, isort, autopep8 |
+| Async runtime | `anyio` | `import asyncio` |
+| Data | `polars` + `duckdb` + `numpy` | pandas |
+| Web framework | FastAPI + Pydantic v2 | Flask, Django REST |
+| ORM | SQLAlchemy 2.x async | Django ORM, Tortoise |
+| HTTP client | [`httpx2`](https://github.com/pydantic/httpx2) | requests, aiohttp, httpx |
+| Testing | `pytest` | unittest |
+| CLI | `typer` + `rich` | argparse, click, fire |
+
+### The iron list
+
+1. **Frozen by default** — `@dataclass(frozen=True, slots=True)`. Pydantic: `model_config = ConfigDict(frozen=True)`. Mutable only when mutation is the documented purpose.
+2. **NewType for distinct IDs** — `UserId = NewType("UserId", int)`. Never pass raw `int` where a branded type exists.
+3. **`match` only for variants, `if` only for booleans** — **NEVER** use `if/elif/else` to discriminate on type (`isinstance`), enum value, or literal variant. `match/case` is mandatory for these — non-negotiable. **ALWAYS** end with `case unreachable: assert_never(unreachable)` — bare `case _: pass` and `case _: raise ValueError` are banned (they silently swallow new variants). `if/else` is fine only for boolean expressions, range checks, and predicate calls that aren't variant discrimination. See "Why `if/elif` on variants is banned" below for examples.
+4. **Protocol over ABC** — `typing.Protocol` for interfaces. ABC only when you need shared method implementation.
+5. **No raw dicts in signatures** — params and returns use `TypedDict`, `dataclass`, or Pydantic model. Internal scratch dicts are fine.
+6. **Parse, don't validate** — constructors produce typed objects or raise. Never pass unvalidated data deeper into the call stack.
+7. **Typed errors** — error types are dataclasses or exceptions with typed fields. Never `raise ValueError("something")` with a bare string. Use union returns when the caller is within 1-2 call levels and must handle the outcome (repository → service). Use exceptions when the error should propagate up many layers to a boundary handler (service → HTTP handler).
+8. **Final for constants** — module-level constants use `Final`. Mutable module globals are a code smell.
+9. **Explicit None** — annotate `-> X | None`. Never return `None` from a function whose signature omits it.
+10. **Context managers for resources** — files, DB connections, HTTP clients, locks. No manual `.close()`.
+11. **No Any, no object** — both are banned as type annotations. `object` erases all structural information (zero callable attributes, zero narrowing). Use `Protocol` (structural typing), `TypeVar` (generic pass-through), explicit union (known variants), or `TypedDict` (dict shapes).
+12. **No cast** — `cast()` is banned. Redesign the types.
+13. **No type: ignore** — fix the type error. The checker is right; you are wrong.
+14. **No broad except** — `except Exception` and `except BaseException` are banned. Catch the **specific** exception you expect. A broad catch swallows bugs you need to see — `KeyError`, `AttributeError`, `TypeError` all vanish silently. If you genuinely need a catch-all at a top-level boundary (CLI entry, HTTP handler), use `# noqa: BROAD_EXCEPT_OK` and log + re-raise.
+
+### Typing and safety
+
+- `basedpyright` in `typeCheckingMode = "all"`. Every public function has full annotations. Internal helpers: annotate return type; parameter types may be inferred.
+- `ruff` with `select = ["ALL"]`. Override specific rules per project in `pyproject.toml`, never globally disable the strict baseline.
+- Every new function must have a `docstring` unless its name + signature makes it completely obvious (e.g. `def full_name(first: str, last: str) -> str:`).
+- Use `X | Y` union syntax (PEP 604), never `Union[X, Y]` or `Optional[X]`.
+
+### Why `object` is banned
+
+`object` pretends to be safe ("it's the top type!") but gives **zero** narrowing and **zero** attributes. Even `Any` is more honest — it admits the boundary is untyped.
+
+```python
+# BANNED
+def process(data: object) -> object: ...
+def store(items: list[object]) -> None: ...
+results: dict[str, object] = {}
+
+# GOOD — Protocol for structural typing
+class Serializable(Protocol):
+ def serialize(self) -> bytes: ...
+def process(data: Serializable) -> ProcessResult: ...
+
+# GOOD — TypeVar for generic pass-through
+def identity[T](x: T) -> T: ...
+def first[T](items: Sequence[T]) -> T: ...
+
+# GOOD — explicit union for known variants
+def parse(raw: str | bytes) -> Document: ...
+```
+
+### Why `if/elif` on variants is banned
+
+`if/elif/else` chains on type, enum, or literal values lose compile-time exhaustiveness. When a new variant is added, nothing warns you. `match/case` + `assert_never` does.
+
+```python
+# BANNED — if/elif for type discrimination
+if isinstance(event, Click):
+ handle_click(event.x, event.y)
+elif isinstance(event, Scroll):
+ handle_scroll(event.delta)
+else:
+ raise ValueError(f"Unknown: {event}") # runtime bomb
+
+# BANNED — if/elif for enum discrimination
+if status == Status.PENDING:
+ start_review()
+elif status == Status.ACTIVE:
+ continue_processing()
+elif status == Status.CLOSED:
+ archive()
+
+# BANNED — non-exhaustive match (swallows new variants)
+match event:
+ case Click(x, y): handle_click(x, y)
+ case _: pass
+
+# GOOD — exhaustive match with assert_never
+match event:
+ case Click(x=x, y=y):
+ handle_click(x, y)
+ case Scroll(delta=delta):
+ handle_scroll(delta)
+ case unreachable:
+ assert_never(unreachable)
+
+# GOOD — enum match
+match status:
+ case Status.PENDING: start_review()
+ case Status.ACTIVE: continue_processing()
+ case Status.CLOSED: archive()
+ case unreachable: assert_never(unreachable)
+```
+
+`if/else` is fine for boolean conditions and range checks — things that aren't variant discrimination:
+
+```python
+# FINE — boolean, not variant
+if age >= 18:
+ grant_access()
+else:
+ deny_access()
+```
+
+### Why broad `except` is banned
+
+`except Exception` catches **every** non-system exception — `KeyError`, `TypeError`, `AttributeError`, `ValueError` all vanish. You lose the stack trace that would have told you exactly what went wrong. The fix is always to name the exception you expect.
+
+```python
+# BANNED — swallows bugs
+try:
+ result = api.fetch(url)
+except Exception as e:
+ logger.error(e)
+ return None
+
+# BANNED — catch-and-ignore
+try:
+ parse(data)
+except Exception:
+ pass
+
+# GOOD — catch what you expect
+try:
+ result = api.fetch(url)
+except httpx.HTTPStatusError as e:
+ logger.error("API %d: %s", e.response.status_code, e.request.url)
+ return None
+except httpx.ConnectError:
+ raise ServiceUnavailableError(service="api") from None
+
+# GOOD — top-level boundary (only place broad catch is acceptable)
+def main() -> int: # noqa: BROAD_EXCEPT_OK
+ try:
+ return run()
+ except Exception:
+ logger.exception("unhandled error")
+ return 1
+```
+
+### Async
+
+- `import asyncio` is **BANNED**. Use `import anyio`.
+- For background tasks, use `anyio.create_task_group`. Never fire-and-forget with `asyncio.create_task`.
+- For concurrency gates, use `anyio.CapacityLimiter` (not `asyncio.Semaphore`).
+- Load `async-anyio.md` when writing async code for the full pattern library.
+
+### Data modeling — which container, when
+
+All model fields carry type annotations. No `Any`, no untyped dicts in public APIs.
+Use `polars` + `duckdb` for data. pandas is never the right answer in this stack.
+
+| Situation | Use |
+|---|---|
+| User input, API request/response | `Pydantic BaseModel (frozen=True)` |
+| Internal value object (no I/O) | `@dataclass(frozen=True, slots=True)` |
+| Function with multiple outcomes | Union of frozen dataclasses + `match` |
+| Dict shape for JSON compat / `**kwargs` | `TypedDict` |
+| Fixed constants | `StrEnum` / `IntEnum` |
+| Distinct primitive (UserId vs MovieId) | `NewType` |
+| Contract / capability | `Protocol` |
+| Contract + shared implementation | `ABC` |
+| ORM model (SQLAlchemy) | `Mapped[]` — inherently mutable, `# noqa: MUTABLE_OK` |
+| Config from env vars | `pydantic-settings BaseSettings` |
+
+**The one rule**: data crosses trust boundary → Pydantic. Everything else → dataclass.
+
+Load `data-modeling.md` for the full decision flowchart and comparison matrix.
+
+### When frozen=True does not apply
+
+- **ORM models** — SQLAlchemy `Mapped[]` requires mutation. Use `# noqa: MUTABLE_OK`.
+- **Builder / accumulator** — object exists to be mutated (counter, buffer, state machine). Docstring must explain why.
+- **Pydantic Settings** — tests override fields. Mutable is acceptable.
+
+If you need `# noqa: MUTABLE_OK`, the class docstring must say why mutation is required.
+
+### Libraries
+
+Canonical defaults (override only if `pyproject.toml` explicitly picks something else):
+
+| Domain | Library | Reason |
+|---|---|---|
+| CLI | `typer` | Type-annotated CLI from function sigs |
+| Pretty output | `rich` | Tables, progress, tracebacks, markdown |
+| HTTP client | [`httpx2`](https://github.com/pydantic/httpx2) | Next-gen HTTP client (Pydantic stewardship), HTTP/2, brotli+zstd. Always `httpx2[http2,brotli,zstd]`. See `httpx2-optimization.md` |
+| Validation | `pydantic` v2 | Fast native validator, JSON Schema |
+| Web API | `fastapi` | Async, Pydantic-native, OpenAPI |
+| ORM | `sqlalchemy` 2.x async | `Mapped[]` types, async sessions |
+| DB driver (Postgres) | `asyncpg` (via SQLAlchemy) | Fastest PG driver |
+| AI agents | `pydantic-ai` | Typed deps, structured output |
+| TUI | `textual` | Rich-based, CSS layout, widgets |
+| Logging | `rich.logging.RichHandler` | Pretty; swap to `structlog` in prod |
+
+## pyproject.toml — the one true config
+
+Scaffold a new project with all strict defaults pre-configured:
+
+```bash
+uv run ../../scripts/python/new-project.py myproject
+uv run ../../scripts/python/new-project.py myproject --path ./workspace
+uv run ../../scripts/python/new-project.py myproject --lib # publishable library
+```
+
+Creates via `uv init`, then injects basedpyright `typeCheckingMode = "all"` + ruff `select = ["ALL"]` + pytest strict. Cross-platform (macOS, Linux, Windows).
+
+For manual setup: `uv init --app myproject`, then load `pyproject-strict.md`.
+
+## PEP 723 — inline script metadata (mandatory for ALL scripts)
+
+Every `.py` script — even throwaway — MUST use PEP 723 inline metadata with the `# ─── How to run ───` comment block. No venv, no `requirements.txt`. The script IS the environment spec. A script without the usage comment block is incomplete.
+
+Scaffold with: `uv run ../../scripts/python/new-script.py <name> --deps "httpx2[http2,brotli,zstd]"` (writes to temp dir by default, `--output` for specific path).
+
+Load `one-liners.md` for full patterns, examples, and anti-patterns.
+
+## Reference loading
+
+Load on demand — not all at once.
+
+| Need | Load |
+|---|---|
+| Full pyproject.toml config | `pyproject-strict.md` |
+| Type patterns (NewType, Final, enums, narrowing) | `type-patterns.md` |
+| Data modeling (container choice, frozen, parse-don't-validate) | `data-modeling.md` |
+| Error handling (typed errors, union returns, exhaustive match) | `error-handling.md` |
+| Async patterns (anyio) | `async-anyio.md` |
+| Data processing (polars / duckdb) | `data-processing.md` |
+| FastAPI + SQLAlchemy stack | `fastapi-stack.md` |
+| Library decision tree | `libraries.md` |
+| **httpx2 optimization** (MUST load for any network code) | `httpx2-optimization.md` |
+| **orjson** (when JSON is in the hot path; FastAPI/Pydantic v2 integration) | `orjson-stack.md` |
+| One-liner scripts (PEP 723) | `one-liners.md` |
+| PydanticAI agents | `pydantic-ai.md` |
+| Textual TUI | `textual-tui.md` |
+
+## httpx2 — mandatory for ALL network requests
+
+Every outgoing HTTP call MUST use [`httpx2`](https://github.com/pydantic/httpx2) (`httpx2[http2,brotli,zstd]`). Never `requests`, never `aiohttp`, never the original `httpx`.
+
+**ALL optimizations are ON by default — not optional, not progressive, not "nice to have".** A bare `httpx2.AsyncClient()` is a bug — treat it like a lint violation. The correct way is the factory pattern in `httpx2-optimization.md` with: HTTP/2 enabled, tuned connection pool (200/40/30s), split timeouts (5/30/10/10), transport retries (3), TCP_NODELAY, follow_redirects, and event hooks for observability.
+
+When writing or reviewing ANY network code, **ALWAYS load `httpx2-optimization.md`** and use the factory pattern verbatim. No exceptions.
+
+## No-excuse audit
+
+Violations caught by `../../scripts/python/check-no-excuse-rules.py`. Run after every edit session.
+
+| Rule ID | Catches | Opt-out |
+|---|---|---|
+| `cast-any` | `cast(Any, ...)` | None — redesign types |
+| `type-ignore` | `# type: ignore` | None — fix the type |
+| `pyright-ignore` | `# pyright: ignore` | None — fix the type |
+| `bare-except` | `except:` with no class | None — name the exception |
+| `silent-except` | `except X: pass` / `except X: ...` | None — handle or re-raise |
+| `no-asyncio` | `import asyncio` | `# noqa: ANYIO_OK` |
+| `no-pandas` | `import pandas` | `# noqa: PANDAS_OK` |
+| `mutable-dataclass` | `@dataclass` without `frozen=True` | `# noqa: MUTABLE_OK` |
+| `missing-slots` | `@dataclass` without `slots=True` | `# noqa: SLOTS_OK` |
+| `raw-dict-return` | `-> dict` in function return type | `# noqa: DICT_OK` |
+| `missing-assert-never` | `match` block without `assert_never` default | `# noqa: MATCH_OK` |
+| `generic-exception` | `raise ValueError("...")` / `raise TypeError("...")` with bare string | `# noqa: GENERIC_ERR_OK` |
+| `no-object` | `object` used as type annotation (param, return, generic arg) | `# noqa: OBJECT_OK` |
+| `if-elif-on-variant` | `if isinstance()`/`if x == Enum.V` chain that should be `match/case` | `# noqa: IF_VARIANT_OK` |
+| `oversized-module` | File exceeds 250 pure LOC (non-blank, non-comment) | `# noqa: SIZE_OK` |
+| `broad-except` | `except Exception` / `except BaseException` (too broad) | `# noqa: BROAD_EXCEPT_OK` |
+
+Fix every violation before declaring work done. basedpyright + ruff strict config catches the rest.
+
+## In tests
+
+Tests are strict too, with these exceptions (already configured in `pyproject.toml` per-file-ignores):
+
+| In tests you may | Why |
+|---|---|
+| Use `assert` | That's how pytest works (`S101` ignored) |
+| Use magic numbers | Test data (`PLR2004` ignored) |
+| Access `_private` members | Testing internals (`SLF001` ignored) |
+| Skip docstrings | Test names are the docs (`D` ignored) |
+| Have unused function args | Fixtures (`ARG` ignored) |
+
+Tests still follow the iron list — frozen dataclasses, typed errors, exhaustive match. If test fixtures need mutable state, use `# noqa: MUTABLE_OK` on the fixture class.
+
+## Existing codebases
+
+When editing an existing file that doesn't follow these rules: **write new code in strict style, don't refactor existing code in the same change.** Mixing feature work with style migration makes reviews harder and bugs likelier.
+
+## Activation
+
+This skill activates whenever you are writing or modifying any `.py` file. Even one-off scripts get the strict treatment — that is the whole point of PEP 723 + uv: production hygiene with throwaway ergonomics.
diff --git a/plugins/omo/skills/programming/references/python/async-anyio.md b/plugins/omo/skills/programming/references/python/async-anyio.md
new file mode 100644
index 00000000..1af6df53
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/async-anyio.md
@@ -0,0 +1,442 @@
+# AnyIO Reference: Replacing asyncio Idioms
+
+> **Skill mandate**: `import asyncio` is BANNED. Use `import anyio` exclusively.
+> This reference targets AnyIO 4.x (2026 Python projects).
+
+---
+
+## 1. Task Groups (The Core Primitive)
+
+AnyIO uses **structured concurrency** via task groups. A task group is an async context manager that guarantees all child tasks finish before the block exits.
+
+### `start_soon` — fire-and-forget
+
+```python
+import anyio
+
+async def worker(n: int) -> None:
+ await anyio.sleep(1)
+ print(f"task {n} done")
+
+async def main() -> None:
+ async with anyio.create_task_group() as tg:
+ for i in range(3):
+ tg.start_soon(worker, i)
+ print("all tasks finished")
+
+anyio.run(main)
+```
+
+**Signature**: `tg.start_soon(func, *args, name=None)`
+- `func` must be a **coroutine function** (not a coroutine object).
+- `name` is optional, for introspection/debugging.
+- No return value; exceptions propagate as `ExceptionGroup` on exit.
+
+### `start` — wait for ready signal
+
+Use when a task must initialize before the caller proceeds (e.g., starting a server and then connecting to it).
+
+```python
+from anyio import TASK_STATUS_IGNORED, create_task_group, run
+from anyio.abc import TaskStatus
+
+async def start_server(port: int, *, task_status: TaskStatus[None] = TASK_STATUS_IGNORED) -> None:
+ listener = await anyio.create_tcp_listener(local_host="127.0.0.1", local_port=port)
+ task_status.started() # unblocks tg.start()
+ await listener.serve(handler)
+
+async def main() -> None:
+ async with create_task_group() as tg:
+ await tg.start(start_server, 8080) # blocks until task_status.started()
+ # server is guaranteed ready here
+ async with await anyio.connect_tcp("127.0.0.1", 8080) as client:
+ ...
+
+run(main)
+```
+
+**Rule of thumb**:
+- Use `start_soon` when you don't need to know when the task is ready.
+- Use `start` when the task must signal readiness before you continue.
+
+### `create_task` — retrieving return values (AnyIO 4.14+)
+
+```python
+async def add(x: int, y: int) -> int:
+ return x + y
+
+async def main() -> None:
+ async with anyio.create_task_group() as tg:
+ handle = tg.create_task(add(2, 4))
+ result = await handle # == 6
+ print(handle.return_value) # also 6
+
+anyio.run(main)
+```
+
+**Signature**: `tg.create_task(coro, *, name=None, context=None) -> TaskHandle[T]`
+- Returns a `TaskHandle` you can `await` for the result.
+- If the task raises, awaiting raises `TaskFailed` (or `TaskCancelled`).
+- This is the canonical replacement for `asyncio.gather` when you need results.
+
+---
+
+## 2. asyncio → anyio Cheat Sheet
+
+| asyncio | anyio | Notes |
+|---------|-------|-------|
+| `asyncio.gather(a, b, c)` | `tg.create_task(a); tg.create_task(b); tg.create_task(c); results = [await h for h in handles]` | No direct gather; structured concurrency requires explicit task group scope. For fire-and-forget, use `tg.start_soon`. |
+| `asyncio.create_task(coro)` | `tg.start_soon(func, *args)` or `tg.create_task(coro)` | `start_soon` takes a coroutine **function** + args. `create_task` takes a coroutine **object** and returns a handle. |
+| `asyncio.sleep(n)` | `anyio.sleep(n)` | Identical semantics. |
+| `asyncio.wait_for(coro, timeout)` | `with anyio.fail_after(timeout): await coro` | Raises `TimeoutError`. Use `move_on_after` for silent timeout. |
+| `asyncio.Event()` | `anyio.Event()` | AnyIO events are **not reusable**; create a new one instead of `.clear()`. |
+| `asyncio.Lock()` | `anyio.Lock()` | Use `async with lock:`. Pass `fast_acquire=True` if performance-critical. |
+| `asyncio.Semaphore(n)` | `anyio.Semaphore(n)` | Same. Pass `fast_acquire=True` if performance-critical. |
+| `asyncio.Condition()` | `anyio.Condition()` | Same semantics. |
+| `asyncio.run(main())` | `anyio.run(main)` | Backend-agnostic entry point. |
+| `asyncio.Queue(maxsize=N)` | `anyio.create_memory_object_stream[T](max_buffer_size=N)` | Returns `(send_stream, receive_stream)`. Supports `async for` on receive end. |
+| `asyncio.to_thread(fn, *args)` | `anyio.to_thread.run_sync(fn, *args)` | Supports `abandon_on_cancel=True` and custom `limiter`. |
+| `asyncio.run_coroutine_threadsafe(coro, loop)` | `anyio.from_thread.run(func, *args)` | Call async code from a worker thread. |
+| `loop.call_soon_threadsafe(callback)` | `anyio.from_thread.run_sync(func, *args)` | Call sync code in event loop thread from worker thread, **with return value**. |
+| `asyncio.shield(coro)` | `with anyio.CancelScope(shield=True): ...` | AnyIO shielding does not orphan tasks. |
+| `asyncio.timeout(delay)` | `with anyio.fail_after(delay): ...` | AnyIO uses level cancellation, not edge cancellation. |
+| `asyncio.CancelledError` | `anyio.get_cancelled_exc_class()` | Use this to catch cancellation portably across backends. |
+
+---
+
+## 3. Cancellation & CancelScope
+
+AnyIO uses **level cancellation** (inspired by Trio), not asyncio's **edge cancellation**.
+
+- **Edge cancellation** (asyncio): A `CancelledError` is injected once. If caught and not re-raised, the task keeps running.
+- **Level cancellation** (anyio): As long as a task is inside an effectively cancelled scope, every yield point raises a new cancellation exception.
+
+### Basic CancelScope
+
+```python
+from anyio import CancelScope, create_task_group, get_cancelled_exc_class, sleep, run
+
+async def worker() -> None:
+ try:
+ await sleep(10)
+ except get_cancelled_exc_class():
+ print("cancelled!")
+ raise # ALWAYS re-raise cancellation exceptions
+
+async def main() -> None:
+ async with create_task_group() as tg:
+ tg.start_soon(worker)
+ await sleep(0.1)
+ tg.cancel_scope.cancel() # cancels all children
+
+run(main)
+```
+
+### Shielding
+
+Shield a block from external cancellation. Essential for cleanup.
+
+```python
+from anyio import CancelScope, create_task_group, sleep, run
+
+async def main() -> None:
+ async with create_task_group() as tg:
+ with CancelScope(shield=True):
+ tg.start_soon(some_task)
+ tg.cancel_scope.cancel() # shielded block is protected
+ await sleep(1) # this still runs
+
+run(main)
+```
+
+**Combine with timeouts for graceful shutdown**:
+
+```python
+from anyio import CancelScope, move_on_after
+
+async def do_something(resource) -> None:
+ try:
+ await run_async_stuff()
+ except BaseException:
+ # Allow up to 10s for cleanup, then move on
+ with move_on_after(10, shield=True):
+ await resource.aclose()
+ raise
+```
+
+### Structured Concurrency Guarantee
+
+A task group contains its own `CancelScope`. If any child task raises an exception:
+1. The task group's cancel scope is cancelled.
+2. All other child tasks receive cancellation.
+3. The task group waits for all children to finish.
+4. The original exception (wrapped in `ExceptionGroup` if multiple) is re-raised.
+
+---
+
+## 4. Timeouts
+
+Two context managers. Both create a `CancelScope` internally.
+
+### `fail_after` — raises on timeout
+
+```python
+from anyio import fail_after, sleep, run
+
+async def main() -> None:
+ try:
+ with fail_after(5) as scope:
+ await sleep(10)
+ except TimeoutError:
+ print("timed out")
+ print(scope.cancelled_caught) # True
+
+run(main)
+```
+
+### `move_on_after` — silent timeout
+
+```python
+from anyio import move_on_after, sleep, run
+
+async def main() -> None:
+ with move_on_after(5) as scope:
+ await sleep(10)
+ print("this never prints")
+
+ print("exited scope, cancelled =", scope.cancelled_caught)
+
+run(main)
+```
+
+### Combined with shielding
+
+```python
+from anyio import move_on_after
+
+# Give cleanup 10 seconds, but don't let outer cancellation interrupt it
+with move_on_after(10, shield=True):
+ await resource.aclose()
+```
+
+---
+
+## 5. Memory Object Streams (Queue Replacement)
+
+Replaces `asyncio.Queue` with a safer, typed, structured-concurrency-friendly construct.
+
+```python
+from anyio import create_task_group, create_memory_object_stream, run
+from anyio.streams.memory import MemoryObjectReceiveStream
+
+async def consumer(stream: MemoryObjectReceiveStream[str]) -> None:
+ async with stream: # closes receive end on exit
+ async for item in stream:
+ print("received", item)
+
+async def main() -> None:
+ # Type-annotated stream creation (AnyIO 4+ syntax)
+ send_stream, receive_stream = create_memory_object_stream[str](max_buffer_size=10)
+
+ async with create_task_group() as tg:
+ tg.start_soon(consumer, receive_stream)
+ async with send_stream:
+ for i in range(5):
+ await send_stream.send(f"item {i}")
+ # send_stream closed → consumer's async for loop exits naturally
+
+run(main)
+```
+
+**Key differences from `asyncio.Queue`**:
+- **Bounded by default**: `max_buffer_size=0` means send blocks until a receiver is ready.
+- **Cloneable**: Each producer/consumer can close its own clone. The stream only ends when **all** clones of one end are closed.
+- **Async iterable**: `async for item in receive_stream:` works out of the box.
+- **Type-safe**: Generic `create_memory_object_stream[T]()`.
+- **Synchronous close**: Both `close()` and `async with` work.
+
+---
+
+## 6. Backend Selection
+
+AnyIO is backend-agnostic. Code written against AnyIO APIs runs on both asyncio and Trio.
+
+```python
+import anyio
+
+async def main() -> None:
+ print("running on", anyio.current_async_library())
+ await anyio.sleep(1)
+
+# Default backend (asyncio)
+anyio.run(main)
+
+# Explicit backend
+anyio.run(main, backend="trio")
+anyio.run(main, backend="asyncio", backend_options={"debug": True})
+```
+
+**Library design rule**: Never hardcode a backend. Let the application choose via `anyio.run()`. Libraries should only import `anyio` and avoid backend-specific APIs.
+
+---
+
+## 7. Compatibility with asyncio-only libraries
+
+### Using asyncio libraries under the asyncio backend
+
+If a third-party library exposes only an asyncio interface (returns asyncio coroutine objects), it works directly under the asyncio backend because AnyIO runs on top of asyncio's event loop:
+
+```python
+import anyio
+import some_asyncio_only_lib # returns asyncio.Future/coroutine objects
+
+async def main() -> None:
+ # This works because under the asyncio backend, await passes through
+ result = await some_asyncio_only_lib.fetch_data()
+
+anyio.run(main, backend="asyncio")
+```
+
+**Important**: This only works on the `asyncio` backend. On the `trio` backend, asyncio-native objects will not work.
+
+### When you MUST use asyncio APIs
+
+Some APIs have no AnyIO equivalent and require direct event loop access:
+
+| Scenario | asyncio API | AnyIO approach |
+|----------|-------------|----------------|
+| Signal handlers | `loop.add_signal_handler()` | `anyio.open_signal_receiver()` |
+| Custom protocols | `asyncio.Protocol` | Use AnyIO streams / sockets |
+| Direct Future manipulation | `asyncio.Future` | Avoid; use AnyIO primitives |
+| Eager task factories | `asyncio.eager_task_factory` | Experimental in AnyIO; avoid |
+
+If you absolutely need the running loop:
+
+```python
+import asyncio
+
+async def main() -> None:
+ loop = asyncio.get_running_loop()
+ # ... do something loop-specific ...
+ # WARNING: this breaks backend-agnosticism
+
+anyio.run(main, backend="asyncio")
+```
+
+**Best practice**: Wrap asyncio-only code in a backend-agnostic facade, and document that the feature requires the asyncio backend.
+
+---
+
+## 8. Idiomatic Code Snippets
+
+### Snippet 1: Parallel HTTP requests with timeout and cleanup
+
+```python
+import anyio
+
+async def fetch(url: str) -> bytes:
+ await anyio.sleep(0.5) # simulate
+ return b"data"
+
+async def main() -> None:
+ urls = ["a", "b", "c"]
+ async with anyio.create_task_group() as tg:
+ with anyio.move_on_after(5):
+ for url in urls:
+ tg.start_soon(fetch, url)
+ # All tasks are cancelled on timeout; task group waits for cleanup
+
+anyio.run(main)
+```
+
+### Snippet 2: Producer-consumer with memory object stream
+
+```python
+import anyio
+from anyio.streams.memory import MemoryObjectReceiveStream
+
+async def producer(send_stream: anyio.streams.memory.MemoryObjectSendStream[int]) -> None:
+ async with send_stream:
+ for i in range(100):
+ await send_stream.send(i)
+
+async def consumer(receive_stream: MemoryObjectReceiveStream[int]) -> None:
+ async with receive_stream:
+ async for item in receive_stream:
+ print(f"consumed {item}")
+
+async def main() -> None:
+ send, receive = anyio.create_memory_object_stream[int](max_buffer_size=5)
+ async with anyio.create_task_group() as tg:
+ tg.start_soon(producer, send)
+ tg.start_soon(consumer, receive)
+
+anyio.run(main)
+```
+
+### Snippet 3: Calling sync code from async
+
+```python
+import time
+import anyio
+
+async def main() -> None:
+ # Run blocking function in worker thread
+ result = await anyio.to_thread.run_sync(time.sleep, 2)
+ print("done")
+
+anyio.run(main)
+```
+
+### Snippet 4: Calling async code from a worker thread
+
+```python
+import anyio
+
+def blocking_callback() -> None:
+ # Inside a worker thread, call back into the event loop
+ anyio.from_thread.run(anyio.sleep, 1)
+ anyio.from_thread.run_sync(print, "hello from thread")
+
+async def main() -> None:
+ await anyio.to_thread.run_sync(blocking_callback)
+
+anyio.run(main)
+```
+
+### Snippet 5: Graceful shutdown with shielded cleanup
+
+```python
+import anyio
+
+async def worker() -> None:
+ try:
+ await anyio.sleep_forever()
+ except anyio.get_cancelled_exc_class():
+ with anyio.CancelScope(shield=True):
+ await anyio.sleep(0.5) # cleanup
+ print("cleaned up")
+ raise
+
+async def main() -> None:
+ async with anyio.create_task_group() as tg:
+ tg.start_soon(worker)
+ await anyio.sleep(1)
+ tg.cancel_scope.cancel()
+
+anyio.run(main)
+```
+
+---
+
+## Sources
+
+- AnyIO Documentation (stable): https://anyio.readthedocs.io/en/stable/
+- AnyIO GitHub (HEAD `cb245dba`): https://github.com/agronholm/anyio
+- Task Groups: https://anyio.readthedocs.io/en/stable/tasks.html
+- Cancellation & Timeouts: https://anyio.readthedocs.io/en/stable/cancellation.html
+- Streams: https://anyio.readthedocs.io/en/stable/streams.html
+- Synchronization: https://anyio.readthedocs.io/en/stable/synchronization.html
+- Threads: https://anyio.readthedocs.io/en/stable/threads.html
+- Basics / Backends: https://anyio.readthedocs.io/en/stable/basics.html
+- Design Rationale (why asyncio is problematic): https://anyio.readthedocs.io/en/stable/why.html
diff --git a/plugins/omo/skills/programming/references/python/data-modeling.md b/plugins/omo/skills/programming/references/python/data-modeling.md
new file mode 100644
index 00000000..48b46f8e
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/data-modeling.md
@@ -0,0 +1,233 @@
+# Data Modeling
+
+Which container to use, how to structure data, and why frozen is the default.
+
+---
+
+## Decision flowchart
+
+```
+Is it a fixed set of named constants?
+ YES → StrEnum / IntEnum
+ NO ↓
+Is it just branding a primitive (int, str, float)?
+ YES → NewType("X", base)
+ NO ↓
+Is it an interface / contract ("this thing can do X")?
+ ├─ Shape only, no shared code → Protocol
+ └─ Shared method implementation needed → ABC
+ NO ↓
+Does the data cross a trust boundary (user input, API, file, external DB)?
+ YES → pydantic.BaseModel (frozen=True) — validates + serializes
+ NO ↓
+Is it a dict shape needed for JSON compat / **kwargs typing?
+ YES → TypedDict
+ NO ↓
+Is it structured data with named fields?
+ YES → @dataclass(frozen=True, slots=True)
+ NO ↓
+Is it a tuple with positional semantics (x, y coords / DB row)?
+ YES → NamedTuple
+ NO → you probably don't need a new type
+```
+
+---
+
+## Container reference
+
+### @dataclass — internal value object
+
+The default for structured data inside your codebase. Zero overhead, no framework coupling.
+
+```python
+from dataclasses import dataclass
+from typing import NewType
+
+UserId = NewType("UserId", int)
+
+@dataclass(frozen=True, slots=True)
+class User:
+ id: UserId
+ name: str
+ email: str
+
+@dataclass(frozen=True, slots=True)
+class Point:
+ x: float
+ y: float
+```
+
+Always `frozen=True, slots=True`. Mutable only when mutation is the documented purpose — opt out with `# noqa: MUTABLE_OK`.
+
+### Pydantic BaseModel — trust boundary guardian
+
+Use when data enters or leaves your system. Validates at construction, serializes to JSON, generates OpenAPI schema.
+
+```python
+from pydantic import BaseModel, ConfigDict, EmailStr
+
+class CreateUserRequest(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
+ name: str
+ email: EmailStr
+ age: int
+
+class UserResponse(BaseModel):
+ model_config = ConfigDict(frozen=True)
+
+ id: int
+ name: str
+ email: str
+```
+
+**The one rule**: data crosses a trust boundary → Pydantic. Everything else → dataclass.
+Never use Pydantic for internal-only data just because it's convenient. The validation cost is real.
+
+### TypedDict — dict that knows its shape
+
+Use when the value must stay a `dict` at runtime — JSON blobs, `**kwargs`, third-party APIs expecting dicts.
+
+```python
+from typing import TypedDict, NotRequired
+
+class Headers(TypedDict):
+ content_type: str
+ authorization: NotRequired[str]
+
+def make_request(url: str, headers: Headers) -> None: ...
+
+make_request("https://api.example.com", {"content_type": "application/json"})
+```
+
+### Protocol — structural interface
+
+"Anything that has method X" — no inheritance required.
+
+```python
+from typing import Protocol
+
+class Renderable(Protocol):
+ def render(self) -> str: ...
+
+class Saveable(Protocol):
+ async def save(self) -> None: ...
+
+@dataclass(frozen=True, slots=True)
+class MarkdownDoc:
+ content: str
+ def render(self) -> str:
+ return self.content
+
+def publish(doc: Renderable) -> None:
+ print(doc.render()) # MarkdownDoc works — no inheritance needed
+```
+
+Default to Protocol for interfaces. ABC only when you need shared method implementations.
+
+### ABC — interface with shared code
+
+Only when Protocol isn't enough.
+
+```python
+from abc import ABC, abstractmethod
+
+class BaseRepository(ABC):
+ @abstractmethod
+ async def get(self, id: int) -> Model | None: ...
+
+ @abstractmethod
+ async def save(self, model: Model) -> None: ...
+
+ async def get_or_raise(self, id: int) -> Model:
+ result = await self.get(id)
+ if result is None:
+ msg = f"{type(self).__name__}: id {id} not found"
+ raise LookupError(msg)
+ return result
+```
+
+### NamedTuple — positional + named (rare)
+
+Only when you need tuple protocol (unpacking, indexing).
+
+```python
+from typing import NamedTuple
+
+class Coordinate(NamedTuple):
+ x: float
+ y: float
+
+x, y = Coordinate(1.0, 2.0) # tuple unpacking
+```
+
+99% of the time, `@dataclass(frozen=True, slots=True)` is better.
+
+---
+
+## Quick lookup
+
+| Situation | Use | Why |
+|---|---|---|
+| User input, API request/response | `Pydantic BaseModel` | Validation, JSON schema, serialization |
+| DB row ↔ Python (ORM) | SQLAlchemy `Mapped[]` model | ORM integration, async session |
+| Internal value object | `@dataclass(frozen=True, slots=True)` | Zero overhead, no validation needed |
+| Multiple outcomes from function | Union of frozen dataclasses | Distinct types for `match` |
+| Dict shape for JSON / `**kwargs` | `TypedDict` | Stays a dict at runtime |
+| Fixed constants | `StrEnum` / `IntEnum` | Exhaustive match, no typos |
+| Distinct primitive | `NewType("X", int)` | Zero runtime cost, type-level only |
+| Contract / capability | `Protocol` | Structural typing, no inheritance |
+| Contract + shared impl | `ABC` | When Protocol isn't enough |
+
+---
+
+## Comparison matrix
+
+| Feature | dataclass | Pydantic | TypedDict | Protocol | NamedTuple | NewType | Enum |
+|---|---|---|---|---|---|---|---|
+| Validation | - | ✓ | - | - | - | - | - |
+| JSON serialization | manual | built-in | native dict | - | - | - | `.value` |
+| Immutable | frozen=True | frozen=True | - (dict) | N/A | always | N/A | always |
+| Runtime cost | ~zero | validation | zero | zero | ~zero | zero | ~zero |
+| `match` support | ✓ | ✓ | - | - | ✓ | - | ✓ |
+| `slots` support | ✓ | - | - | - | - | - | - |
+
+---
+
+## Parse, don't validate
+
+Validate at the boundary. Inside the boundary, types are proof of validity.
+
+```python
+# BAD — validate then pass raw data
+def process_email(email: str) -> None:
+ if "@" not in email:
+ raise ValueError("invalid email")
+ # still a raw str everywhere downstream
+
+# GOOD — parse into typed value at boundary
+from typing import NewType
+
+Email = NewType("Email", str)
+
+def parse_email(raw: str) -> Email:
+ if "@" not in raw or "." not in raw.split("@")[1]:
+ msg = f"invalid email: {raw}"
+ raise ValueError(msg)
+ return Email(raw.lower().strip())
+
+# Downstream only sees Email, never raw str
+def send_welcome(email: Email) -> None: ...
+```
+
+With Pydantic this happens automatically — `EmailStr` is already a parsed type. Once constructed, `.email` is always valid. No re-validation needed.
+
+---
+
+## Sources
+
+- Python docs: [dataclasses](https://docs.python.org/3/library/dataclasses.html)
+- Pydantic v2: [docs.pydantic.dev](https://docs.pydantic.dev/latest/)
+- Python docs: [typing — Protocol](https://docs.python.org/3/library/typing.html#typing.Protocol)
+- Python docs: [typing — TypedDict](https://docs.python.org/3/library/typing.html#typing.TypedDict)
+- Alexis King: [Parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/)
diff --git a/plugins/omo/skills/programming/references/python/data-processing.md b/plugins/omo/skills/programming/references/python/data-processing.md
new file mode 100644
index 00000000..299b30cd
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/data-processing.md
@@ -0,0 +1,133 @@
+# Data Processing — Polars + DuckDB
+
+## The rule
+
+NEVER pandas. Polars (with numpy) plus DuckDB. Pandas is 10-50x slower, has weaker types, and the modern Python data ecosystem has moved on.
+
+## Quick decision tree
+
+| Operation | Use | Why |
+|---|---|---|
+| `.csv` / `.parquet` / `.json` direct query | DuckDB | Zero memory load, SQL ergonomics |
+| `.duckdb` file | DuckDB | Native format |
+| Filter (any size) | Polars | 128x faster than DuckDB for filtering |
+| Sort | Polars | 12x faster |
+| Multi-table join | DuckDB | 3x faster, more join types |
+| Heavy GROUP BY aggregation | DuckDB | 4x faster on large datasets |
+| Window function | Polars | 3-5x faster |
+| Pivot / melt / string ops | Polars | 2x faster |
+| Larger than RAM | Polars streaming or DuckDB out-of-core | Both handle OOM |
+| Mixed pipeline | Hybrid (zero-copy via Arrow) | Use each tool's strengths |
+
+For the deep version (per-operation benchmarks, OOM strategies, full execution templates), load the **`data-scientist`** skill - it lives in this same skill set and is the source of truth for performance numbers.
+
+## Standard imports
+
+```python
+import numpy as np
+import polars as pl
+import duckdb
+```
+
+## DuckDB direct file query (zero memory load)
+
+```python
+result = duckdb.sql("""
+ SELECT category, SUM(amount) AS total
+ FROM 'data.csv'
+ WHERE date >= '2026-01-01'
+ GROUP BY category
+ ORDER BY total DESC
+""").pl() # zero-copy → Polars DataFrame
+```
+
+`.pl()` returns Polars; `.df()` would return pandas - never use `.df()`.
+
+## Polars lazy pipeline
+
+```python
+result = (
+ pl.scan_csv("data.csv") # lazy, no read yet
+ .filter(pl.col("amount") > 1000)
+ .filter(pl.col("status") == "active")
+ .sort("amount", descending=True)
+ .head(100)
+ .collect() # execute optimised plan
+)
+```
+
+`scan_*` over `read_*` for files; `lazy()` then `collect()` for in-memory frames. Polars optimises the entire plan before execution (predicate pushdown, projection pushdown, common subexpression elimination).
+
+## Streaming for OOM data
+
+```python
+result = (
+ pl.scan_csv("huge.csv")
+ .filter(pl.col("active"))
+ .group_by("category")
+ .agg([
+ pl.len().alias("count"),
+ pl.sum("amount").alias("total"),
+ ])
+ .collect(streaming=True)
+)
+```
+
+## Hybrid pipeline (most realistic shape)
+
+```python
+# Phase 1: DuckDB for the join (3x faster)
+joined = duckdb.sql("""
+ SELECT o.*, c.region, p.category
+ FROM 'orders.parquet' o
+ JOIN 'customers.parquet' c ON o.customer_id = c.id
+ JOIN 'products.parquet' p ON o.product_id = p.id
+""").pl()
+
+# Phase 2: Polars for filtering and transformation (128x + 2x faster)
+processed = (
+ joined
+ .filter(pl.col("amount") > 100)
+ .with_columns([
+ (pl.col("amount") * 1.1).alias("amount_with_tax"),
+ ])
+)
+
+# Phase 3: DuckDB for final aggregation (4x faster) - register Polars frame by name
+duckdb.register("processed", processed)
+final = duckdb.sql("""
+ SELECT region, category, SUM(amount_with_tax) AS revenue
+ FROM processed
+ GROUP BY region, category
+ ORDER BY revenue DESC
+""").pl()
+```
+
+## Type safety with Polars
+
+Polars supports schema overrides at read time, and `.cast()` for explicit conversion. Avoid implicit coercion in hot paths.
+
+```python
+schema = {"id": pl.Int64, "amount": pl.Float64, "date": pl.Date}
+df = pl.read_csv("data.csv", schema_overrides=schema)
+```
+
+basedpyright understands `polars-stubs`, which ship with polars itself. No extra type stubs to install.
+
+## Things you might miss from pandas (and how to do them in Polars)
+
+| pandas | polars |
+|---|---|
+| `df.iloc[5]` | `df.row(5)` (named tuple) or `df[5]` (single-row frame) |
+| `df.loc[df["x"] > 5]` | `df.filter(pl.col("x") > 5)` |
+| `df["x"].apply(fn)` | `df["x"].map_elements(fn)` (slow path) or use native expressions |
+| `df.merge(...)` | `df.join(other, on="key")` |
+| `df.groupby(...).agg(...)` | `df.group_by(...).agg(...)` |
+| `pd.read_csv(...).dtypes` | `pl.read_csv(...).schema` |
+| `df.to_dict("records")` | `df.to_dicts()` |
+
+## Sources
+
+- Polars docs: <https://docs.pola.rs>
+- DuckDB Python API: <https://duckdb.org/docs/api/python/overview>
+- Cross-reference - this skill set's `data-scientist` skill (load it for the deep version)
diff --git a/plugins/omo/skills/programming/references/python/error-handling.md b/plugins/omo/skills/programming/references/python/error-handling.md
new file mode 100644
index 00000000..44f58bef
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/error-handling.md
@@ -0,0 +1,218 @@
+# Error Handling
+
+Typed errors, exhaustive matching, union returns, and resource safety.
+
+---
+
+## Typed errors — no bare strings
+
+Error types carry structured data. Pattern matching works. Callers know exactly what can go wrong.
+
+```python
+from dataclasses import dataclass
+from typing import NewType
+
+UserId = NewType("UserId", int)
+
+@dataclass(frozen=True, slots=True)
+class UserNotFoundError(Exception):
+ user_id: UserId
+
+ def __str__(self) -> str: # REQUIRED — see note below
+ return f"user {self.user_id} not found"
+
+@dataclass(frozen=True, slots=True)
+class PermissionDeniedError(Exception):
+ user_id: UserId
+ required_role: str
+
+ def __str__(self) -> str:
+ return f"user {self.user_id} needs role {self.required_role}"
+```
+
+**`__str__` is mandatory** on dataclass exceptions. `@dataclass` replaces `Exception.__init__`, so `self.args` is always `()`. Without `__str__`, `str(e)` returns an empty string and logging/monitoring breaks.
+
+```python
+# BAD
+raise ValueError("user not found")
+raise ValueError("permission denied")
+
+# GOOD
+raise UserNotFoundError(user_id=uid)
+raise PermissionDeniedError(user_id=uid, required_role="admin")
+```
+
+---
+
+## Union returns — expected failures without exceptions
+
+For failures that are **expected** (not found, validation error, permission denied), return a union instead of raising. Exceptions are for **unexpected** failures (network down, OOM, corrupted data).
+
+### Define the outcome types
+
+```python
+@dataclass(frozen=True, slots=True)
+class User:
+ id: UserId
+ name: str
+
+@dataclass(frozen=True, slots=True)
+class UserNotFound:
+ id: UserId
+
+@dataclass(frozen=True, slots=True)
+class PermissionDenied:
+ id: UserId
+ reason: str
+
+type GetUserResult = User | UserNotFound | PermissionDenied
+```
+
+### Handle exhaustively
+
+```python
+from typing import assert_never
+
+def handle_result(result: GetUserResult) -> str:
+ match result:
+ case User(name=name):
+ return f"Found: {name}"
+ case UserNotFound(id=uid):
+ return f"No user with id {uid}"
+ case PermissionDenied(reason=reason):
+ return f"Denied: {reason}"
+ case _ as unreachable:
+ assert_never(unreachable)
+```
+
+`assert_never` in the default case: if you add a new variant to `GetUserResult` without handling it here, the type checker errors. No silent fall-through.
+
+### When to use which
+
+**The heuristic**: caller is 1-2 levels away and MUST handle it → union return. Error should propagate up many layers to a boundary → exception.
+
+| Scenario | Pattern | Why |
+|---|---|---|
+| Repository → service (caller handles it) | Union return (`User \| UserNotFound`) | Caller is right there, must handle both |
+| Validation at boundary (parsing input) | Exception (typed, with fields) | Propagates up to HTTP/CLI handler |
+| Infrastructure failure (network, OOM) | Exception | Can't handle locally, must propagate |
+| Service → service (deep internal) | Exception (typed) | Union boilerplate across many layers is worse than exceptions |
+| HTTP handler → response | Catch exceptions, convert to response | Boundary code catches and translates |
+
+**Practical tradeoff**: union returns are safest (type checker forces handling) but create boilerplate when every caller in a chain must `match`. If the error would just propagate through 3+ layers unchanged, use a typed exception instead.
+
+---
+
+## Exhaustive match — every match needs a default
+
+Every `match` statement ends with `case _: assert_never(x)`. No exceptions.
+
+```python
+from enum import StrEnum
+from typing import assert_never
+
+class Status(StrEnum):
+ PENDING = "pending"
+ ACTIVE = "active"
+ DELETED = "deleted"
+
+def describe(status: Status) -> str:
+ match status:
+ case Status.PENDING:
+ return "waiting"
+ case Status.ACTIVE:
+ return "live"
+ case Status.DELETED:
+ return "gone"
+ case _ as unreachable:
+ assert_never(unreachable)
+```
+
+Add a new enum member? The type checker tells you every `match` that needs updating.
+
+---
+
+## Context managers — resource safety
+
+If it has `.close()`, `.shutdown()`, `.disconnect()`, or `.release()`, wrap it in `with`.
+
+```python
+# BAD
+f = open("data.txt")
+data = f.read()
+f.close() # forgotten? leaked
+
+# GOOD
+from pathlib import Path
+
+data = Path("data.txt").read_text()
+```
+
+### Async resources
+
+```python
+import httpx
+
+async def fetch_users() -> list[User]:
+ async with httpx.AsyncClient() as client:
+ response = await client.get("https://api.example.com/users")
+ response.raise_for_status()
+ return [User(**u) for u in response.json()]
+```
+
+### Custom context manager
+
+```python
+from contextlib import asynccontextmanager
+from collections.abc import AsyncIterator
+
+@asynccontextmanager
+async def managed_connection(url: str) -> AsyncIterator[Connection]:
+ conn = await connect(url)
+ try:
+ yield conn
+ finally:
+ await conn.close()
+
+async with managed_connection("postgres://...") as conn:
+ await conn.execute("SELECT 1")
+# conn is closed here, guaranteed
+```
+
+---
+
+## Exception hierarchy — when you do raise
+
+Keep exception hierarchies shallow and specific.
+
+```python
+class AppError(Exception):
+ """Base for all application errors."""
+
+@dataclass(frozen=True, slots=True)
+class NotFoundError(AppError):
+ entity: str
+ id: int
+
+ def __str__(self) -> str:
+ return f"{self.entity} {self.id} not found"
+
+@dataclass(frozen=True, slots=True)
+class ConflictError(AppError):
+ entity: str
+ field: str
+ value: str
+
+ def __str__(self) -> str:
+ return f"{self.entity}.{self.field} = {self.value!r} already exists"
+```
+
+Callers catch `AppError` at the boundary, or specific subtypes where they can do something useful.
+
+---
+
+## Sources
+
+- Python docs: [typing — assert_never](https://docs.python.org/3/library/typing.html#typing.assert_never)
+- Python docs: [contextlib](https://docs.python.org/3/library/contextlib.html)
+- Python docs: [match statement](https://docs.python.org/3/reference/compound_stmts.html#the-match-statement)
diff --git a/plugins/omo/skills/programming/references/python/fastapi-stack.md b/plugins/omo/skills/programming/references/python/fastapi-stack.md
new file mode 100644
index 00000000..d5180614
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/fastapi-stack.md
@@ -0,0 +1,316 @@
+# FastAPI + SQLAlchemy 2.x async + Postgres + Pydantic v2
+
+The canonical web API stack. Async end-to-end, type-safe end-to-end, OpenAPI-generated end-to-end.
+
+## Project layout
+
+```
+myapi/
+├── pyproject.toml
+├── alembic.ini
+├── migrations/
+│ └── env.py
+├── src/
+│ └── myapi/
+│ ├── __init__.py
+│ ├── main.py # FastAPI app + lifespan
+│ ├── config.py # pydantic-settings
+│ ├── db.py # engine, session factory, dependency
+│ ├── models.py # SQLAlchemy declarative models
+│ ├── schemas.py # Pydantic request/response models
+│ └── routers/
+│ ├── __init__.py
+│ └── users.py
+└── tests/
+ ├── conftest.py
+ └── test_users.py
+```
+
+## Dependencies
+
+```bash
+uv add fastapi 'sqlalchemy[asyncio]>=2.0' asyncpg 'pydantic[email]>=2' pydantic-settings 'uvicorn[standard]' orjson
+uv add --dev httpx pytest alembic
+```
+
+`orjson` is mandatory: set `default_response_class=ORJSONResponse` on the FastAPI app. Pydantic-typed responses bypass it (Pydantic v2's `model_dump_json` is already Rust-backed); raw `dict` / `list` returns are accelerated. For SSE / NDJSON streams, call `orjson.dumps(...)` per chunk inside `StreamingResponse`. See `orjson-stack.md` for the decision tree, flag reference, and benchmarks.
+
+## Configuration (`config.py`)
+
+```python
+from functools import lru_cache
+
+from pydantic import Field, PostgresDsn
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+
+class Settings(BaseSettings):
+ model_config = SettingsConfigDict(env_file=".env", env_prefix="MYAPI_")
+
+ database_url: PostgresDsn
+ debug: bool = False
+ cors_origins: list[str] = Field(default_factory=list)
+
+
+@lru_cache
+def get_settings() -> Settings:
+ return Settings() # type: ignore[call-arg] # pydantic populates from env
+```
+
+Wait — that comment violates the no-excuse rule. Use proper field defaults instead. Real version:
+
+```python
+class Settings(BaseSettings):
+ model_config = SettingsConfigDict(env_file=".env", env_prefix="MYAPI_")
+ database_url: PostgresDsn
+ debug: bool = False
+ cors_origins: list[str] = Field(default_factory=list)
+```
+
+Construct via `Settings(_env_file=".env")` if needed in tests; in production it reads from env.
+
+## Database (`db.py`)
+
+```python
+from collections.abc import AsyncIterator
+from typing import Annotated
+
+from fastapi import Depends
+from sqlalchemy.ext.asyncio import (
+ AsyncEngine,
+ AsyncSession,
+ async_sessionmaker,
+ create_async_engine,
+)
+
+from myapi.config import get_settings
+
+
+def make_engine() -> AsyncEngine:
+ settings = get_settings()
+ return create_async_engine(
+ str(settings.database_url),
+ echo=settings.debug,
+ pool_pre_ping=True,
+ )
+
+
+_engine = make_engine()
+_SessionFactory = async_sessionmaker(_engine, expire_on_commit=False)
+
+
+async def get_session() -> AsyncIterator[AsyncSession]:
+ async with _SessionFactory() as session:
+ yield session
+
+
+SessionDep = Annotated[AsyncSession, Depends(get_session)]
+```
+
+`expire_on_commit=False` is essential for FastAPI - otherwise attribute access after commit triggers an implicit refresh and errors out under async.
+
+## Models (`models.py`)
+
+```python
+from datetime import datetime, UTC
+from sqlalchemy import DateTime, String, func
+from sqlalchemy.orm import (
+ DeclarativeBase,
+ Mapped,
+ MappedAsDataclass,
+ mapped_column,
+)
+
+
+class Base(MappedAsDataclass, DeclarativeBase):
+ pass
+
+
+class User(Base):
+ __tablename__ = "users"
+
+ id: Mapped[int] = mapped_column(primary_key=True, init=False)
+ email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
+ name: Mapped[str] = mapped_column(String(100))
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True),
+ server_default=func.now(),
+ init=False,
+ )
+```
+
+`MappedAsDataclass` makes `User(email=..., name=...)` work as a real dataclass constructor. `init=False` excludes the auto-generated columns (`id`, `created_at`) from `__init__`.
+
+## Schemas (`schemas.py`)
+
+```python
+from datetime import datetime
+from pydantic import BaseModel, ConfigDict, EmailStr
+
+
+class UserCreate(BaseModel):
+ email: EmailStr
+ name: str
+
+
+class UserRead(BaseModel):
+ model_config = ConfigDict(from_attributes=True) # SQLAlchemy → Pydantic
+
+ id: int
+ email: EmailStr
+ name: str
+ created_at: datetime
+```
+
+Always have a separate `*Create` (input) and `*Read` (output) model. Never expose your ORM model as the API model.
+
+## Routers (`routers/users.py`)
+
+```python
+from fastapi import APIRouter, HTTPException, status
+from sqlalchemy import select
+
+from myapi.db import SessionDep
+from myapi.models import User
+from myapi.schemas import UserCreate, UserRead
+
+router = APIRouter(prefix="/users", tags=["users"])
+
+
[email protected]("", response_model=UserRead, status_code=status.HTTP_201_CREATED)
+async def create_user(payload: UserCreate, session: SessionDep) -> User:
+ user = User(email=payload.email, name=payload.name)
+ session.add(user)
+ await session.commit()
+ await session.refresh(user)
+ return user
+
+
[email protected]("/{user_id}", response_model=UserRead)
+async def get_user(user_id: int, session: SessionDep) -> User:
+ result = await session.execute(select(User).where(User.id == user_id))
+ user = result.scalar_one_or_none()
+ if user is None:
+ raise HTTPException(status.HTTP_404_NOT_FOUND, "User not found")
+ return user
+
+
[email protected]("", response_model=list[UserRead])
+async def list_users(session: SessionDep, limit: int = 100) -> list[User]:
+ result = await session.execute(select(User).limit(limit))
+ return list(result.scalars().all())
+```
+
+## Application (`main.py`)
+
+```python
+from contextlib import asynccontextmanager
+from collections.abc import AsyncIterator
+
+from fastapi import FastAPI
+
+from myapi.config import get_settings
+from myapi.routers import users
+
+
+@asynccontextmanager
+async def lifespan(_: FastAPI) -> AsyncIterator[None]:
+ # Startup: warm up engine pool, run migrations check, etc.
+ yield
+ # Shutdown: close engine
+ from myapi.db import _engine
+ await _engine.dispose()
+
+
+def create_app() -> FastAPI:
+ settings = get_settings()
+ app = FastAPI(
+ title="My API",
+ debug=settings.debug,
+ lifespan=lifespan,
+ )
+ app.include_router(users.router)
+ return app
+
+
+app = create_app()
+```
+
+Run with:
+
+```bash
+uv run uvicorn myapi.main:app --host 0.0.0.0 --port 8000 --reload
+```
+
+## Migrations (Alembic + async)
+
+```bash
+uv run alembic init -t async migrations
+```
+
+In `migrations/env.py` replace the `target_metadata` line:
+
+```python
+from myapi.models import Base
+target_metadata = Base.metadata
+```
+
+Set `sqlalchemy.url` in `alembic.ini` to your async URL or override via `env.py`:
+
+```python
+from myapi.config import get_settings
+config.set_main_option("sqlalchemy.url", str(get_settings().database_url))
+```
+
+Generate and apply:
+
+```bash
+uv run alembic revision --autogenerate -m "create users"
+uv run alembic upgrade head
+```
+
+## Tests (`tests/test_users.py`)
+
+```python
+import pytest
+from httpx import ASGITransport, AsyncClient
+
+from myapi.main import app
+
+
+async def test_create_and_get_user() -> None:
+ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
+ create_response = await client.post(
+ "/users",
+ json={"email": "[email protected]", "name": "Alice"},
+ )
+ assert create_response.status_code == 201
+ user_id = create_response.json()["id"]
+
+ get_response = await client.get(f"/users/{user_id}")
+ assert get_response.status_code == 200
+ assert get_response.json()["email"] == "[email protected]"
+```
+
+For database-backed tests, run a Postgres container in CI (`testcontainers-python` or `docker-compose`) and apply migrations against a test schema. SQLite-as-test-db breaks once you use Postgres-specific types (`JSONB`, `tsvector`, arrays).
+
+## Common pitfalls
+
+| Pitfall | Fix |
+|---|---|
+| `MissingGreenlet` exception when accessing relationships after commit | `expire_on_commit=False` on the session factory |
+| Connection pool exhausted under load | Set `pool_size`, `max_overflow` in `create_async_engine` |
+| Pydantic v1 syntax (`from pydantic import ...; class X(BaseModel): class Config: orm_mode = True`) | v2 uses `model_config = ConfigDict(from_attributes=True)` |
+| Returning ORM objects without `response_model` | FastAPI serialises with `from_attributes=True` automatically; declare `response_model` so OpenAPI is correct |
+| `await session.execute(...)` returning Sequence | Wrap with `list(result.scalars().all())` to satisfy strict types |
+| `func.now()` returning naive datetime | Use `DateTime(timezone=True)` and `created_at: Mapped[datetime]` with `UTC`-aware default |
+
+## Sources
+
+- FastAPI: <https://fastapi.tiangolo.com>
+- SQLAlchemy 2.x async: <https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html>
+- SQLAlchemy MappedAsDataclass: <https://docs.sqlalchemy.org/en/20/orm/dataclasses.html>
+- asyncpg: <https://magicstack.github.io/asyncpg/current/>
+- Pydantic v2 migration: <https://docs.pydantic.dev/latest/migration/>
+- Alembic async: <https://alembic.sqlalchemy.org/en/latest/cookbook.html#using-asyncio-with-alembic>
diff --git a/plugins/omo/skills/programming/references/python/httpx2-optimization.md b/plugins/omo/skills/programming/references/python/httpx2-optimization.md
new file mode 100644
index 00000000..0f5efcba
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/httpx2-optimization.md
@@ -0,0 +1,360 @@
+# httpx2 — Production Defaults
+
+> **Source**: [pydantic/httpx2](https://github.com/pydantic/httpx2) — next-generation HTTP client for Python 3, continuation of HTTPX under Pydantic stewardship.
+>
+> **Rule**: Every network request MUST use `httpx2`. **ALL optimizations below are ON by default** — HTTP/2, brotli+zstd, tuned connection pool, fine-grained timeouts, transport retries, TCP_NODELAY. This is the baseline, not a stretch goal. A bare `httpx2.AsyncClient()` is a bug.
+
+---
+
+## 1. Installation — all extras, always
+
+```toml
+# pyproject.toml
+dependencies = [
+ "httpx2[http2,brotli,zstd]",
+]
+```
+
+| Extra | What it enables | Why it's mandatory |
+|-------|----------------|--------------------|
+| `http2` | HTTP/2 multiplexing via `h2` | Single TCP connection handles concurrent requests; eliminates head-of-line blocking |
+| `brotli` | Brotli content decoding (`br`) | ~20% smaller payloads than gzip for text/JSON |
+| `zstd` | Zstandard content decoding | Faster decompression than brotli at similar ratios; stdlib in Python ≥ 3.14 |
+| `socks` | SOCKS5 proxy support via `socksio` | Install only if you route through SOCKS proxies |
+
+All three core extras (`http2,brotli,zstd`) are non-negotiable. Omitting any is leaving performance on the table.
+
+---
+
+## 2. The canonical defaults — ALL ON
+
+These are not "optimizations to consider". These are **the correct defaults** that every httpx2 client must use.
+
+```python
+import socket
+import httpx2
+
+# ── These are the STANDARD values. Use them verbatim. ──
+
+LIMITS = httpx2.Limits(
+ max_connections=200, # library default 100 is too conservative
+ max_keepalive_connections=40, # library default 20 wastes reconnects
+ keepalive_expiry=30.0, # library default 5s kills warm connections too fast
+)
+
+TIMEOUT = httpx2.Timeout(
+ connect=5.0, # TCP + TLS handshake budget
+ read=30.0, # time to receive a response chunk
+ write=10.0, # time to send a request chunk
+ pool=10.0, # time to acquire a connection from pool
+)
+
+SOCKET_OPTIONS: list[tuple[int, int, int]] = [
+ (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1), # disable Nagle — no 40ms delay
+]
+```
+
+### Why each knob is set this way
+
+| Setting | Library default | Our default | Why |
+|---------|----------------|-------------|-----|
+| `http2` | `False` | **`True`** | HTTP/2 multiplexing is strictly superior for any modern API |
+| `max_connections` | `100` | `200` | Headroom for fan-out; prevents pool exhaustion under load |
+| `max_keepalive_connections` | `20` | `40` | Keeps warm connections alive; fewer TLS handshakes |
+| `keepalive_expiry` | `5.0s` | `30.0s` | 5s is too aggressive — kills connections between burst requests |
+| `Timeout(5.0)` uniform | `5.0` all | Split | Uniform 5s is too tight for reads, too loose for connects |
+| `read` timeout | `5.0` | `30.0` | Slow APIs and streaming need breathing room |
+| `pool` timeout | `5.0` | `10.0` | Explicit — hitting this means `max_connections` needs raising |
+| `TCP_NODELAY` | off | **on** | Eliminates Nagle's 40ms coalescing delay for small payloads |
+| `retries` | `0` | `3` | Retries on `ConnectError`/`ConnectTimeout` only — safe and resilient |
+| `follow_redirects` | `False` | **`True`** | Most APIs redirect; failing on 3xx is wrong default behavior |
+
+---
+
+## 3. Factory functions — the ONE correct way to create clients
+
+Copy this into your project. This is the canonical pattern.
+
+```python
+"""httpx2 client factory. Always use create_client() / create_async_client()."""
+
+from __future__ import annotations
+
+import socket
+import typing
+
+import httpx2
+
+_LIMITS = httpx2.Limits(
+ max_connections=200,
+ max_keepalive_connections=40,
+ keepalive_expiry=30.0,
+)
+
+_TIMEOUT = httpx2.Timeout(
+ connect=5.0,
+ read=30.0,
+ write=10.0,
+ pool=10.0,
+)
+
+_SOCKET_OPTIONS: list[tuple[int, int, int]] = [
+ (socket.IPPROTO_TCP, socket.TCP_NODELAY, 1),
+]
+
+
+def create_async_client(
+ *,
+ base_url: str = "",
+ http2: bool = True,
+ retries: int = 3,
+ limits: httpx2.Limits = _LIMITS,
+ timeout: httpx2.Timeout = _TIMEOUT,
+ headers: dict[str, str] | None = None,
+ event_hooks: dict[str, list[typing.Callable[..., typing.Any]]] | None = None,
+ **kwargs: typing.Any,
+) -> httpx2.AsyncClient:
+ transport = httpx2.AsyncHTTPTransport(
+ http2=http2,
+ retries=retries,
+ limits=limits,
+ socket_options=_SOCKET_OPTIONS,
+ )
+ return httpx2.AsyncClient(
+ transport=transport,
+ timeout=timeout,
+ base_url=base_url,
+ headers=headers or {},
+ event_hooks=event_hooks or {},
+ follow_redirects=True,
+ **kwargs,
+ )
+
+
+def create_client(
+ *,
+ base_url: str = "",
+ http2: bool = True,
+ retries: int = 3,
+ limits: httpx2.Limits = _LIMITS,
+ timeout: httpx2.Timeout = _TIMEOUT,
+ headers: dict[str, str] | None = None,
+ event_hooks: dict[str, list[typing.Callable[..., typing.Any]]] | None = None,
+ **kwargs: typing.Any,
+) -> httpx2.Client:
+ transport = httpx2.HTTPTransport(
+ http2=http2,
+ retries=retries,
+ limits=limits,
+ socket_options=_SOCKET_OPTIONS,
+ )
+ return httpx2.Client(
+ transport=transport,
+ timeout=timeout,
+ base_url=base_url,
+ headers=headers or {},
+ event_hooks=event_hooks or {},
+ follow_redirects=True,
+ **kwargs,
+ )
+```
+
+Usage:
+
+```python
+# Async — the common case
+async with create_async_client(base_url="https://api.example.com") as client:
+ r = await client.get("/users")
+
+# Sync
+with create_client() as client:
+ r = client.get("https://api.example.com/health")
+```
+
+**If you are NOT using this factory pattern, you are doing it wrong.** A bare `httpx2.AsyncClient()` leaves HTTP/2 off, retries off, TCP_NODELAY off, keepalive too short, and timeouts too uniform.
+
+---
+
+## 4. Special case overrides
+
+The factory defaults cover 95% of use cases. Override only when you have a specific reason:
+
+| Scenario | Override |
+|----------|----------|
+| LLM streaming endpoints | `timeout=httpx2.Timeout(connect=10.0, read=None, write=10.0, pool=10.0)` — no read timeout on streaming |
+| Single-host API with low concurrency | `limits=httpx2.Limits(max_connections=50, max_keepalive_connections=20, keepalive_expiry=60.0)` |
+| Ephemeral short-lived requests | `keepalive_expiry=5.0` — don't hold connections |
+| Unix domain sockets | `httpx2.AsyncHTTPTransport(uds="/path/to/socket", ...)` |
+| mTLS / client certs | Pass `verify=ssl_ctx` with `ctx.load_cert_chain(certfile=...)` |
+| SOCKS proxy | `httpx2[socks]`, `proxy="socks5://..."` |
+
+---
+
+## 5. Event hooks — always wire observability
+
+This is not optional. Every production client should log requests.
+
+```python
+import time
+import logging
+
+logger = logging.getLogger(__name__)
+
+async def log_request(request: httpx2.Request) -> None:
+ request.extensions["request_start"] = time.perf_counter()
+
+async def log_response(response: httpx2.Response) -> None:
+ start = response.request.extensions.get("request_start", 0)
+ elapsed = time.perf_counter() - start
+ logger.info(
+ "HTTP %s %s → %d (%.3fs, %s)",
+ response.request.method,
+ response.request.url,
+ response.status_code,
+ elapsed,
+ response.http_version,
+ )
+
+# Sync versions for Client
+def log_request_sync(request: httpx2.Request) -> None:
+ request.extensions["request_start"] = time.perf_counter()
+
+def log_response_sync(response: httpx2.Response) -> None:
+ start = response.request.extensions.get("request_start", 0)
+ elapsed = time.perf_counter() - start
+ logger.info(
+ "HTTP %s %s → %d (%.3fs, %s)",
+ response.request.method,
+ response.request.url,
+ response.status_code,
+ elapsed,
+ response.http_version,
+ )
+```
+
+For auto `raise_for_status()`:
+
+```python
+async def raise_on_error(response: httpx2.Response) -> None:
+ response.raise_for_status()
+```
+
+---
+
+## 6. Verification script — confirm your setup is fully optimized
+
+Run this against your target endpoint to **verify** (not decide) that all optimizations are active:
+
+```python
+"""Verify httpx2 is fully optimized against a target endpoint."""
+
+from __future__ import annotations
+
+import socket
+import time
+
+import anyio
+import httpx2
+
+
+TARGET_URL = "https://api.example.com/health"
+ITERATIONS = 30
+
+
+async def bench(label: str, client: httpx2.AsyncClient, url: str, n: int) -> float:
+ for _ in range(3): # warmup
+ await client.get(url)
+ start = time.perf_counter()
+ for _ in range(n):
+ r = await client.get(url)
+ assert r.status_code == 200
+ elapsed = time.perf_counter() - start
+ avg_ms = (elapsed / n) * 1000
+ print(f" {label}: {avg_ms:.1f}ms avg ({n} reqs in {elapsed:.2f}s)")
+ return avg_ms
+
+
+async def main() -> None:
+ results: dict[str, float] = {}
+
+ # BAD: bare defaults (this is what we're proving is worse)
+ async with httpx2.AsyncClient() as c:
+ results["BAD-bare-defaults"] = await bench("BAD-bare-defaults", c, TARGET_URL, ITERATIONS)
+
+ # GOOD: full production defaults (this is what we always use)
+ limits = httpx2.Limits(max_connections=200, max_keepalive_connections=40, keepalive_expiry=30.0)
+ timeout = httpx2.Timeout(connect=5.0, read=30.0, write=10.0, pool=10.0)
+ transport = httpx2.AsyncHTTPTransport(
+ http2=True, retries=3, limits=limits,
+ socket_options=[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)],
+ )
+ async with httpx2.AsyncClient(transport=transport, timeout=timeout, follow_redirects=True) as c:
+ results["GOOD-full-production"] = await bench("GOOD-full-production", c, TARGET_URL, ITERATIONS)
+
+ print("\n--- Proof ---")
+ baseline = results["BAD-bare-defaults"]
+ for label, avg in results.items():
+ delta = ((avg - baseline) / baseline) * 100
+ print(f" {label}: {avg:.1f}ms ({delta:+.1f}% vs bare)")
+
+
+if __name__ == "__main__":
+ anyio.run(main)
+```
+
+---
+
+## 7. Quick reference — all knobs
+
+### `httpx2.AsyncClient` / `httpx2.Client`
+
+| Parameter | Type | Library Default | **Our Default** |
+|-----------|------|-----------------|-----------------|
+| `http1` | `bool` | `True` | `True` |
+| `http2` | `bool` | `False` | **`True`** |
+| `verify` | `ssl.SSLContext \| str \| bool` | `True` | `True` |
+| `cert` | `CertTypes \| None` | `None` | `None` |
+| `proxy` | `str \| Proxy \| None` | `None` | `None` |
+| `mounts` | `dict[str, Transport]` | `None` | `None` |
+| `timeout` | `Timeout \| float \| None` | `Timeout(5.0)` | **Split: 5/30/10/10** |
+| `limits` | `Limits` | `Limits(100, 20, 5.0)` | **`Limits(200, 40, 30.0)`** |
+| `follow_redirects` | `bool` | `False` | **`True`** |
+| `max_redirects` | `int` | `20` | `20` |
+| `event_hooks` | `dict` | `{}` | **Wire logging** |
+| `base_url` | `str` | `""` | Set for single-API clients |
+| `trust_env` | `bool` | `True` | `True` |
+| `default_encoding` | `str \| Callable` | `"utf-8"` | `"utf-8"` |
+
+### `httpx2.AsyncHTTPTransport` / `httpx2.HTTPTransport`
+
+| Parameter | Type | Library Default | **Our Default** |
+|-----------|------|-----------------|-----------------|
+| `http1` | `bool` | `True` | `True` |
+| `http2` | `bool` | `False` | **`True`** |
+| `retries` | `int` | `0` | **`3`** |
+| `limits` | `Limits` | `Limits(100, 20, 5.0)` | **`Limits(200, 40, 30.0)`** |
+| `uds` | `str \| None` | `None` | `None` |
+| `local_address` | `str \| None` | `None` | `None` |
+| `socket_options` | `Iterable[SOCKET_OPTION]` | `None` | **`[TCP_NODELAY]`** |
+| `proxy` | `str \| Proxy \| None` | `None` | `None` |
+
+### `httpx2.Timeout`
+
+| Parameter | Library Default | **Our Default** |
+|-----------|-----------------|-----------------|
+| `connect` | `5.0` | `5.0` |
+| `read` | `5.0` | **`30.0`** |
+| `write` | `5.0` | **`10.0`** |
+| `pool` | `5.0` | **`10.0`** |
+
+### `httpx2.Limits`
+
+| Parameter | Library Default | **Our Default** |
+|-----------|-----------------|-----------------|
+| `max_connections` | `100` | **`200`** |
+| `max_keepalive_connections` | `20` | **`40`** |
+| `keepalive_expiry` | `5.0` | **`30.0`** |
+
+### Async backend (httpcore2)
+
+httpcore2 uses `anyio` by default (works with both asyncio and trio). No extra config needed if you're already on the anyio stack. For trio, install `httpcore2[trio]`.
diff --git a/plugins/omo/skills/programming/references/python/libraries.md b/plugins/omo/skills/programming/references/python/libraries.md
new file mode 100644
index 00000000..f2e5e803
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/libraries.md
@@ -0,0 +1,307 @@
+# Library Defaults — Decision Tree
+
+For each domain, the canonical 2026 choice, why, and the canonical usage snippet. The skill enforces these unless the project's `pyproject.toml` explicitly says otherwise.
+
+## CLI — typer
+
+`typer` builds a CLI from type-annotated function signatures. argparse needs 5x the code; click ignores type annotations; fire is magic that breaks at scale.
+
+```python
+import typer
+from rich import print as rprint
+
+app = typer.Typer()
+
+def greet(name: str, count: int = 1, shout: bool = False) -> None:
+ """Print a greeting `count` times."""
+ message = f"Hello, {name}!" if not shout else f"HELLO, {name.upper()}!"
+ for _ in range(count):
+ rprint(message)
+
+if __name__ == "__main__":
+ app()
+```
+
+For a single-function script, `typer.run(main)` skips the `Typer()` boilerplate. Subcommands use `@app.command()`.
+
+## Terminal output — rich
+
+`rich` produces tables, progress bars, syntax highlighting, traceback rendering. Use it for any structured output. Plain `print` is acceptable for non-interactive log lines (and even those are usually better via `rich.console.Console(stderr=True).log(...)`).
+
+```python
+from rich.console import Console
+from rich.table import Table
+
+console = Console()
+
+table = Table(title="Users")
+table.add_column("ID", style="cyan")
+table.add_column("Name", style="magenta")
+table.add_row("1", "Alice")
+console.print(table)
+
+# Rich tracebacks (call once at process start)
+from rich.traceback import install
+install(show_locals=True)
+```
+
+## HTTP client — [httpx2](https://github.com/pydantic/httpx2)
+
+Next-generation HTTP client under Pydantic stewardship. Sync and async in one library, HTTP/2 native, brotli + zstd content decoding, real type stubs. Replaces `requests` (sync only), `aiohttp` (async only), and the original `httpx`.
+
+**Install**: `httpx2[http2,brotli,zstd]` — always include all three extras, no exceptions.
+
+**A bare `httpx2.AsyncClient()` / `httpx2.Client()` is a bug.** Always use the factory pattern from `references/httpx2-optimization.md` with ALL optimizations enabled by default:
+
+```python
+import socket
+import httpx2
+
+# ── Production defaults — ALL ON, always. ──
+_LIMITS = httpx2.Limits(max_connections=200, max_keepalive_connections=40, keepalive_expiry=30.0)
+_TIMEOUT = httpx2.Timeout(connect=5.0, read=30.0, write=10.0, pool=10.0)
+_SOCKET_OPTS: list[tuple[int, int, int]] = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
+
+# Async (the common case)
+transport = httpx2.AsyncHTTPTransport(http2=True, retries=3, limits=_LIMITS, socket_options=_SOCKET_OPTS)
+async with httpx2.AsyncClient(transport=transport, timeout=_TIMEOUT, follow_redirects=True) as client:
+ response = await client.get("https://api.example.com/users")
+ response.raise_for_status()
+ users = response.json()
+
+# Sync
+transport = httpx2.HTTPTransport(http2=True, retries=3, limits=_LIMITS, socket_options=_SOCKET_OPTS)
+with httpx2.Client(transport=transport, timeout=_TIMEOUT, follow_redirects=True) as client:
+ response = client.get("https://api.example.com/users")
+ response.raise_for_status()
+ users = response.json()
+```
+
+See `references/httpx2-optimization.md` for the full factory functions (`create_client()` / `create_async_client()`), event hooks, and the rationale behind every setting. **Load that reference whenever you write ANY network code.**
+
+## JSON — stdlib `json` (default) or `orjson` (hot paths)
+
+Stdlib `json` is fine for cold paths and configs. **Reach for `orjson` when JSON is in the hot path** — cache layers, queue payloads, streaming responses, structured logs, FastAPI endpoints returning raw `dict` / `list`.
+
+```python
+import orjson
+
+# orjson.dumps returns bytes, not str
+raw: bytes = orjson.dumps(
+ payload,
+ option=orjson.OPT_NAIVE_UTC | orjson.OPT_UTC_Z | orjson.OPT_SERIALIZE_DATACLASS,
+)
+```
+
+**Critical 2026 fact**: with Pydantic v2, `model.model_dump_json()` is backed by pydantic-core (Rust) and is faster than `orjson + default=` bridge for Pydantic-shaped responses. **Use `model_dump_json()` for Pydantic; orjson for everything else.**
+
+For FastAPI: `app = FastAPI(default_response_class=ORJSONResponse)`. Pydantic-typed responses bypass it (and that's correct — Pydantic's path is faster). Raw `dict`/`list` returns go through orjson.
+
+See `references/orjson-stack.md` for the full decision tree, option flag reference, FastAPI integration, Redis/queue/logging patterns, and the `model_dump_json()` vs orjson benchmark.
+
+## Validation — pydantic v2
+
+Pydantic v2's core is in Rust (~10x faster than v1). It is the de-facto boundary validator. Use it for:
+
+- HTTP request/response models (FastAPI uses pydantic natively)
+- Config files (env vars via `pydantic-settings`)
+- Anything entering the program from outside
+
+```python
+from pydantic import BaseModel, Field, EmailStr, field_validator
+
+class User(BaseModel):
+ id: int = Field(ge=1)
+ email: EmailStr
+ name: str = Field(min_length=1, max_length=100)
+ age: int | None = Field(default=None, ge=0, le=150)
+
+ @field_validator("name")
+ @classmethod
+ def name_no_digits(cls, v: str) -> str:
+ if any(c.isdigit() for c in v):
+ raise ValueError("name cannot contain digits")
+ return v
+
+# Inside the program, use the validated instance with confidence
+user = User.model_validate({"id": 1, "email": "[email protected]", "name": "Alice"})
+print(user.model_dump_json(indent=2))
+```
+
+`@dataclass` is fine for purely internal records (no validation needed). For anything crossing a process boundary, use Pydantic.
+
+## Async — anyio
+
+Full reference: [async-anyio.md](async-anyio.md). The summary:
+
+```python
+import anyio
+
+async def fetch(url: str) -> str:
+ await anyio.sleep(0.1)
+ return url
+
+async def main() -> None:
+ async with anyio.create_task_group() as tg:
+ for url in ["a", "b", "c"]:
+ tg.start_soon(fetch, url)
+
+anyio.run(main)
+```
+
+Never `import asyncio` directly. The third-party libraries you call are free to use asyncio internally.
+
+## Web framework — fastapi
+
+Type-hint-driven HTTP framework. Pydantic models become OpenAPI schemas automatically.
+
+```python
+from fastapi import FastAPI
+from pydantic import BaseModel
+
+app = FastAPI()
+
+class CreateUser(BaseModel):
+ name: str
+ email: str
+
+class User(BaseModel):
+ id: int
+ name: str
+ email: str
+
[email protected]("/users", response_model=User)
+async def create_user(payload: CreateUser) -> User:
+ return User(id=1, **payload.model_dump())
+```
+
+Full stack with database: [fastapi-stack.md](fastapi-stack.md).
+
+## ORM — sqlalchemy 2.x async
+
+SQLAlchemy 2.x finally has a real async API. Use the modern declarative `MappedAsDataclass` style with type annotations.
+
+```python
+from sqlalchemy import String
+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
+from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, MappedAsDataclass
+
+class Base(MappedAsDataclass, DeclarativeBase):
+ pass
+
+class User(Base):
+ __tablename__ = "users"
+ id: Mapped[int] = mapped_column(primary_key=True, init=False)
+ name: Mapped[str] = mapped_column(String(100))
+ email: Mapped[str] = mapped_column(String(255), unique=True)
+
+engine = create_async_engine("postgresql+asyncpg://localhost/myapp")
+SessionFactory = async_sessionmaker(engine, expire_on_commit=False)
+```
+
+Full pattern with FastAPI integration: [fastapi-stack.md](fastapi-stack.md).
+
+## Database — postgres + asyncpg
+
+For new applications, default to Postgres. SQLite for tests is fine; SQLite for production is not.
+
+asyncpg is the fastest Python Postgres driver, native to SQLAlchemy 2.x async, native to FastAPI's lifespan model. URL: `postgresql+asyncpg://user:pass@host:5432/db`.
+
+For migrations, use Alembic with `[alembic.context]` configured to use the async engine. Single-step:
+
+```bash
+uv add alembic
+uv run alembic init -t async migrations
+```
+
+## TUI — textual
+
+Textual builds rich, mouse-aware, mobile-style TUIs on the rich rendering engine. See [textual-tui.md](textual-tui.md).
+
+## AI agents — pydantic-ai
+
+The agent framework from the Pydantic team. Type-strict, structured outputs are first-class, model-agnostic. See [pydantic-ai.md](pydantic-ai.md).
+
+## DataFrames — polars + numpy
+
+Polars is 10-50x faster than pandas, has a real type system, and supports lazy evaluation. Numpy stays in the toolbox for arrays. See [data-processing.md](data-processing.md).
+
+## OLAP / SQL — duckdb
+
+DuckDB is the SQL engine for analytical workloads. Query CSV/Parquet/JSON files directly without loading into memory; perform joins and aggregations 3-4x faster than Polars; zero-copy interchange with Polars via Arrow. See [data-processing.md](data-processing.md).
+
+## Tests — pytest
+
+Plain `unittest` is fine for stdlib; everything else uses pytest. Conventions:
+
+- File names `test_*.py`, function names `test_*`.
+- Fixtures via `@pytest.fixture`. Async fixtures are anyio-aware (`@pytest.fixture` on an async function works under `pytest-anyio` which is bundled with anyio).
+- Parametrise with `@pytest.mark.parametrize`.
+- Mark async tests with `@pytest.mark.anyio` (provided by anyio's pytest plugin).
+
+```python
+import pytest
+import anyio
+
+def sample_user() -> dict[str, str]:
+ return {"name": "Alice", "email": "[email protected]"}
+
[email protected]("count,expected", [(1, "Hello"), (2, "Hello, Hello")])
+def test_greet(count: int, expected: str) -> None:
+ result = ", ".join(["Hello"] * count)
+ assert result == expected
+
+async def test_async_fetch() -> None:
+ await anyio.sleep(0)
+ assert True
+```
+
+`pyproject.toml`:
+
+```toml
+[tool.pytest.ini_options]
+minversion = "8.0"
+testpaths = ["tests"]
+addopts = ["-ra", "--strict-config", "--strict-markers"]
+```
+
+## Settings / config — pydantic-settings
+
+Loads env vars and `.env` files into a Pydantic model. Replaces ad-hoc `os.environ.get(...)` everywhere.
+
+```python
+from pydantic import Field
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+class Settings(BaseSettings):
+ model_config = SettingsConfigDict(env_file=".env", env_prefix="MYAPP_")
+
+ database_url: str
+ api_key: str = Field(min_length=1)
+ debug: bool = False
+
+settings = Settings() # loads at import time; raises if any required var is missing
+```
+
+## Logging — stdlib logging + rich handler
+
+Stdlib `logging` is fine; it gets a face-lift from `rich.logging.RichHandler`.
+
+```python
+import logging
+from rich.logging import RichHandler
+
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(message)s",
+ datefmt="[%X]",
+ handlers=[RichHandler(rich_tracebacks=True, show_path=False)],
+)
+log = logging.getLogger(__name__)
+log.info("ready")
+```
+
+For structured logging in production, swap to `structlog` (separate dep). Don't roll your own.
diff --git a/plugins/omo/skills/programming/references/python/one-liners.md b/plugins/omo/skills/programming/references/python/one-liners.md
new file mode 100644
index 00000000..de1ddbc2
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/one-liners.md
@@ -0,0 +1,268 @@
+# One-liner Scripts (PEP 723 + uv)
+
+Self-contained Python scripts with declared dependencies, run with no environment setup. The combination eliminates the historical reason to write small tools in Go or Bash.
+
+**Rule: EVERY `.py` script — even throwaway — MUST use PEP 723 inline metadata with the usage comment block.** No venv, no requirements.txt, no setup.py. The script IS the environment spec.
+
+## The two patterns
+
+### Pattern 1: inline `uv run` invocation
+
+```bash
+uv run --with httpx2 --with rich python -c "
+import httpx2
+from rich import print
+print(httpx2.get('https://api.github.com').json())
+"
+```
+
+Use for terminal one-shots that you don't want to save. `--with PKG` may be repeated.
+
+### Pattern 2: PEP 723 script with shebang (THE CANONICAL PATTERN)
+
+A regular `.py` file with metadata in a comment block. uv reads the metadata, materialises a disposable venv (cached), and runs the script.
+
+```python
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.13"
+# dependencies = [
+# "httpx2[http2,brotli,zstd]",
+# "rich",
+# ]
+# ///
+
+# ─── How to run ───
+# 1. Install uv (if not installed):
+# curl -LsSf https://astral.sh/uv/install.sh | sh
+# 2. Run directly (no venv, no pip install needed):
+# uv run my_script.py
+# 3. Or make executable and run:
+# chmod +x my_script.py && ./my_script.py
+# ──────────────────
+
+from __future__ import annotations
+
+import httpx2
+from rich import print as rprint
+
+
+def main() -> None:
+ with httpx2.Client(http2=True, follow_redirects=True) as client:
+ resp = client.get("https://api.github.com")
+ resp.raise_for_status()
+ rprint(resp.json())
+
+
+if __name__ == "__main__":
+ main()
+```
+
+### Mandatory elements
+
+Every PEP 723 script MUST include these, in order:
+
+1. **Shebang**: `#!/usr/bin/env -S uv run --script`
+2. **PEP 723 metadata block**: `# /// script` ... `# ///` with `requires-python` and `dependencies`
+3. **Usage comment block**: How to install uv + how to run the script. Copy the template above verbatim.
+4. **`from __future__ import annotations`**: Always first import.
+5. **`if __name__ == "__main__": main()`**: Entry point guard.
+
+### The usage comment block (NON-NEGOTIABLE)
+
+```python
+# ─── How to run ───
+# 1. Install uv (if not installed):
+# curl -LsSf https://astral.sh/uv/install.sh | sh
+# 2. Run directly (no venv, no pip install needed):
+# uv run <SCRIPT_NAME>.py [ARGS]
+# 3. Or make executable and run:
+# chmod +x <SCRIPT_NAME>.py && ./<SCRIPT_NAME>.py
+# ──────────────────
+```
+
+Replace `<SCRIPT_NAME>` with the actual filename. Add argument descriptions if the script takes CLI args. This block goes immediately after the `# ///` closing line, before any imports.
+
+**Why mandatory**: Anyone who receives this script — colleague, CI, future you — must know how to run it without reading docs. The comment IS the docs.
+
+## Template generator
+
+Use `scripts/new-script.py` to scaffold a new PEP 723 script with all boilerplate pre-filled:
+
+```bash
+# Generate to temp directory (default)
+uv run scripts/new-script.py my_tool
+
+# Generate to specific path
+uv run scripts/new-script.py my_tool --output ./scripts/my_tool.py
+
+# With extra dependencies
+uv run scripts/new-script.py my_tool --deps "polars" "duckdb" "rich"
+```
+
+## Common dependency sets
+
+| Use case | Dependencies line |
+|---|---|
+| API client | `"httpx2[http2,brotli,zstd]"` |
+| Data processing | `"polars"`, `"duckdb"` |
+| CLI tool | `"typer"`, `"rich"` |
+| Web scraping | `"httpx2[http2,brotli,zstd]"`, `"selectolax"` |
+| File watcher | `"watchfiles"` |
+| JSON pretty | `"rich"` |
+| AI / LLM | `"pydantic-ai"`, `"httpx2[http2,brotli,zstd]"` |
+
+## Real-world examples
+
+### Fetch + print JSON
+
+```python
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.13"
+# dependencies = [
+# "httpx2[http2,brotli,zstd]",
+# "rich",
+# ]
+# ///
+
+# ─── How to run ───
+# 1. Install uv: curl -LsSf https://astral.sh/uv/install.sh | sh
+# 2. Run: uv run fetch_json.py https://api.github.com/repos/pydantic/httpx2
+# ──────────────────
+
+from __future__ import annotations
+
+import sys
+
+import httpx2
+from rich import print as rprint
+
+
+def main() -> None:
+ url = sys.argv[1] if len(sys.argv) > 1 else "https://api.github.com"
+ with httpx2.Client(http2=True, follow_redirects=True) as client:
+ resp = client.get(url)
+ resp.raise_for_status()
+ rprint(resp.json())
+
+
+if __name__ == "__main__":
+ main()
+```
+
+### CSV → Parquet conversion
+
+```python
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.13"
+# dependencies = [
+# "polars",
+# "typer",
+# "rich",
+# ]
+# ///
+
+# ─── How to run ───
+# 1. Install uv: curl -LsSf https://astral.sh/uv/install.sh | sh
+# 2. Run: uv run csv2parquet.py input.csv output.parquet
+# ──────────────────
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import polars as pl
+import typer
+from rich import print as rprint
+
+
+def main(input_path: Path, output_path: Path | None = None) -> None:
+ """Convert CSV to Parquet."""
+ out = output_path or input_path.with_suffix(".parquet")
+ df = pl.read_csv(input_path)
+ df.write_parquet(out)
+ rprint(f"[green]✓[/green] {input_path} → {out} ({len(df)} rows)")
+
+
+if __name__ == "__main__":
+ typer.run(main)
+```
+
+### Quick benchmark
+
+```python
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.13"
+# dependencies = [
+# "httpx2[http2,brotli,zstd]",
+# "rich",
+# "anyio",
+# ]
+# ///
+
+# ─── How to run ───
+# 1. Install uv: curl -LsSf https://astral.sh/uv/install.sh | sh
+# 2. Run: uv run bench.py https://api.example.com/health 50
+# ──────────────────
+
+from __future__ import annotations
+
+import socket
+import sys
+import time
+
+import anyio
+import httpx2
+from rich import print as rprint
+
+
+async def main() -> None:
+ url = sys.argv[1] if len(sys.argv) > 1 else "https://api.github.com"
+ n = int(sys.argv[2]) if len(sys.argv) > 2 else 20
+
+ limits = httpx2.Limits(max_connections=200, max_keepalive_connections=40, keepalive_expiry=30.0)
+ timeout = httpx2.Timeout(connect=5.0, read=30.0, write=10.0, pool=10.0)
+ transport = httpx2.AsyncHTTPTransport(
+ http2=True, retries=3, limits=limits,
+ socket_options=[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)],
+ )
+
+ async with httpx2.AsyncClient(transport=transport, timeout=timeout, follow_redirects=True) as client:
+ # warmup
+ for _ in range(3):
+ await client.get(url)
+
+ start = time.perf_counter()
+ for _ in range(n):
+ r = await client.get(url)
+ assert r.status_code == 200
+ elapsed = time.perf_counter() - start
+
+ avg_ms = (elapsed / n) * 1000
+ rprint(f"[bold]{url}[/bold]: {avg_ms:.1f}ms avg over {n} requests ({elapsed:.2f}s total, {r.http_version})")
+
+
+if __name__ == "__main__":
+ anyio.run(main)
+```
+
+## Anti-patterns
+
+| ❌ Don't | ✅ Do |
+|---|---|
+| `pip install httpx2 && python script.py` | `uv run script.py` |
+| `requirements.txt` alongside script | PEP 723 inline metadata |
+| `python -m venv .venv && ...` | `uv run --script` handles it |
+| Script without usage comment | Always include the "How to run" block |
+| `import asyncio; asyncio.run(main())` | `import anyio; anyio.run(main)` |
+| Bare `httpx2.AsyncClient()` | Full production defaults (see `references/httpx2-optimization.md`) |
+
+## Sources
+
+- PEP 723 - Inline script metadata: <https://peps.python.org/pep-0723/>
+- uv `run --script` docs: <https://docs.astral.sh/uv/guides/scripts/>
+- Original article: <https://www.cottongeeks.com/articles/2025-06-24-fun-with-uv-and-pep-723>
+- Simon Willison on one-shot Python tools: <https://simonwillison.net/2024/Dec/19/one-shot-python-tools/>
diff --git a/plugins/omo/skills/programming/references/python/orjson-stack.md b/plugins/omo/skills/programming/references/python/orjson-stack.md
new file mode 100644
index 00000000..9c3ca0c6
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/orjson-stack.md
@@ -0,0 +1,378 @@
+# orjson — When to Use, How to Integrate
+
+`orjson` is the fastest JSON library on PyPI — written in Rust, 6–11× faster than stdlib `json` on serialization, 1.5–4× faster on deserialization. It also supports types the stdlib refuses to serialize: `datetime`, `date`, `UUID`, `numpy` arrays, `dataclass`, Pydantic models (via a small bridge).
+
+This document covers the production patterns. **Not every project needs orjson.** The decision tree is in §1.
+
+---
+
+## 1. Decision tree — should you adopt orjson?
+
+```
+Are you serializing/deserializing JSON in a hot path?
+ ├─ NO → stdlib `json` is fine. Stop here.
+ └─ YES ↓
+
+Is the project FastAPI?
+ ├─ YES ↓
+ │
+ │ Is your response body fully described by a Pydantic v2 model?
+ │ ├─ YES → Use FastAPI's default JSON response (uses Pydantic's
+ │ │ Rust-backed serializer; orjson saves nothing in this path).
+ │ │ Adopt orjson only for *non-Pydantic* responses below.
+ │ └─ NO → Use `ORJSONResponse` for endpoints that return dicts,
+ │ lists, or arbitrary structures.
+ │
+ └─ NOT FastAPI ↓
+
+Are you serializing Pydantic v2 models repeatedly?
+ ├─ YES → Use `model.model_dump_json()` directly — backed by pydantic-core
+ │ (Rust), within ~10% of orjson on the same payload, and respects
+ │ every Pydantic feature (computed fields, aliases, validators).
+ └─ NO ↓
+
+Are you serializing dicts / lists / dataclasses / datetime / UUID?
+ ├─ YES → orjson is the right answer.
+ └─ NO → stdlib `json`.
+```
+
+**The crucial 2026 fact**: with Pydantic v2's `model_dump_json()`, **Pydantic-shaped responses no longer need orjson**. Adopt orjson where you are still going through `dict` / `list` / `dataclass`.
+
+---
+
+## 2. Install
+
+```toml
+# pyproject.toml
+dependencies = [
+ "orjson>=3.10",
+]
+```
+
+orjson wheels are published for every major CPython version and platform (macOS, Linux glibc/musl, Windows, ARM64). No compilation step on install.
+
+---
+
+## 3. Basic usage
+
+```python
+import orjson
+
+# Serialization — returns bytes, not str
+raw: bytes = orjson.dumps({"hello": "world", "ts": datetime.now(UTC)})
+
+# Deserialization
+data = orjson.loads(raw)
+```
+
+Two things to internalize:
+
+1. **`orjson.dumps` returns `bytes`**, not `str`. Stdlib `json.dumps` returns `str`. This is by design — most JSON destinations (sockets, files in binary mode, HTTP bodies) want bytes anyway, and skipping the encode/decode round trip is part of the speedup.
+2. **No `indent` arg.** orjson supports `OPT_INDENT_2` (and only 2-space indent) via flags. If you need other indentation, use stdlib `json`.
+
+---
+
+## 4. The option flags you actually use
+
+```python
+import orjson
+
+orjson.dumps(
+ payload,
+ option=(
+ orjson.OPT_NAIVE_UTC # treat naive datetimes as UTC (recommended)
+ | orjson.OPT_UTC_Z # render UTC as "...Z" instead of "+00:00"
+ | orjson.OPT_SERIALIZE_NUMPY # serialize numpy arrays natively
+ | orjson.OPT_SERIALIZE_DATACLASS # serialize @dataclass instances
+ | orjson.OPT_NON_STR_KEYS # allow int / UUID / datetime dict keys
+ # | orjson.OPT_SORT_KEYS # only when you need deterministic output
+ # | orjson.OPT_INDENT_2 # only for human-readable output (slower)
+ ),
+)
+```
+
+Each flag is opt-in for a reason — orjson defaults to spec-strict JSON.
+
+The flag combination above is a sensible "production default" for application code. The `OPT_NAIVE_UTC | OPT_UTC_Z` pair is especially important: it produces RFC 3339 timestamps that every parser on earth accepts.
+
+---
+
+## 5. orjson + FastAPI
+
+### 5.1 The legacy pattern: `ORJSONResponse`
+
+```python
+from fastapi import FastAPI
+from fastapi.responses import ORJSONResponse
+
+app = FastAPI(default_response_class=ORJSONResponse)
+
+async def get_items() -> dict[str, list[dict[str, int]]]:
+ return {"items": [{"id": i, "qty": i * 2} for i in range(1000)]}
+```
+
+`default_response_class=ORJSONResponse` swaps the global JSON encoder for orjson. **This affects only the response body serialization**, not request parsing — for request parsing, FastAPI still uses Pydantic.
+
+### 5.2 The 2026 reality — Pydantic v2 vs orjson
+
+With FastAPI 0.100+ on Pydantic v2:
+
+- If your response is annotated with a Pydantic model, FastAPI calls `model_dump_json()` directly. **orjson is bypassed** even with `default_response_class=ORJSONResponse`, because the Pydantic serializer is already Rust-backed.
+- If your response is a raw `dict` / `list` / Python object, `ORJSONResponse` does kick in and saves real time.
+
+The benchmark in `tiangolo/fastapi#11728` (Apr 2024) showed `model_dump_json()` is ~10–15% faster than `ORJSONResponse + model_dump()` for Pydantic-shaped responses. The shape of the data matters; on mixed-shape APIs, keep `ORJSONResponse` as the default and trust Pydantic's path for typed responses.
+
+### 5.3 Recommended setup
+
+```python
+from fastapi import FastAPI
+from fastapi.responses import ORJSONResponse
+
+app = FastAPI(
+ default_response_class=ORJSONResponse, # benefits dict/list returns
+ # Pydantic-typed returns automatically use pydantic-core serialization
+)
+```
+
+**Do NOT** wrap Pydantic models manually:
+
+```python
+# BAD — defeats Pydantic's optimized path
[email protected]("/users/{id}", response_class=ORJSONResponse)
+async def get_user(id: int) -> ORJSONResponse:
+ user = await fetch_user(id)
+ return ORJSONResponse(content=user.model_dump()) # extra dict trip
+
+# GOOD — let FastAPI serialize the model
[email protected]("/users/{id}")
+async def get_user(id: int) -> User:
+ return await fetch_user(id)
+```
+
+### 5.4 Streaming responses
+
+`ORJSONResponse` does not stream — it buffers the whole response. For SSE, NDJSON, or chunked JSON, use `StreamingResponse` and call `orjson.dumps` per chunk:
+
+```python
+from fastapi.responses import StreamingResponse
+import orjson
+
+async def ndjson_stream():
+ async for row in fetch_rows():
+ yield orjson.dumps(row) + b"\n"
+
+async def export():
+ return StreamingResponse(ndjson_stream(), media_type="application/x-ndjson")
+```
+
+This is where orjson shines — per-chunk serialization in a tight loop, zero buffering.
+
+---
+
+## 6. orjson + Pydantic v2 (no FastAPI)
+
+When you have a Pydantic model and want orjson's output for non-FastAPI contexts:
+
+```python
+from pydantic import BaseModel
+import orjson
+
+class User(BaseModel):
+ id: int
+ email: str
+ created: datetime
+
+user = User(id=1, email="[email protected]", created=datetime.now(UTC))
+
+# Option A — Pydantic's built-in Rust serializer (USE THIS by default)
+raw: bytes = user.model_dump_json().encode()
+# 2026: ~1.2× faster than orjson on the same payload, supports
+# every Pydantic feature (aliases, computed fields, json_schema_extra, etc.)
+
+# Option B — orjson bridge for cases Pydantic does not cover
+raw: bytes = orjson.dumps(
+ user,
+ default=lambda obj: obj.model_dump() if isinstance(obj, BaseModel) else None,
+)
+# Useful when serializing nested non-Pydantic structures that contain
+# BaseModels — e.g. a list of dicts that each may contain a BaseModel.
+```
+
+For routine "serialize one Pydantic model to JSON", `model_dump_json()` wins on speed AND feature parity. Reach for orjson only at the *container* level (a dict of mixed types).
+
+### Custom `default=` callback — the universal extension point
+
+```python
+import orjson
+from decimal import Decimal
+from pydantic import BaseModel
+
+def _default(obj):
+ if isinstance(obj, BaseModel):
+ return obj.model_dump()
+ if isinstance(obj, Decimal):
+ return str(obj)
+ if isinstance(obj, set):
+ return list(obj)
+ raise TypeError(f"orjson: cannot serialize {type(obj).__name__}")
+
+orjson.dumps(payload, default=_default, option=orjson.OPT_NAIVE_UTC | orjson.OPT_UTC_Z)
+```
+
+The `default=` callback runs once per unrecognized type, then orjson caches the path. Performance impact on subsequent calls is negligible.
+
+---
+
+## 7. Caching, queues, logging — the prime orjson use cases
+
+These are where orjson pays off most clearly because there is no Pydantic in the loop:
+
+### Redis cache
+
+```python
+import orjson
+import redis.asyncio as redis
+
+r = redis.from_url("redis://localhost")
+
+async def set_cache(key: str, value: dict) -> None:
+ await r.set(key, orjson.dumps(value), ex=3600)
+
+async def get_cache(key: str) -> dict | None:
+ raw = await r.get(key)
+ return orjson.loads(raw) if raw else None
+```
+
+`orjson` over stdlib `json` here saves ~5–10× on the serialize step for typical cache payloads. Multiply by request rate.
+
+### Task queue payloads (Celery, RQ, dramatiq)
+
+```python
+# Celery custom serializer
+from kombu.serialization import register
+import orjson
+
+def _orjson_dumps(obj):
+ return orjson.dumps(obj, option=orjson.OPT_NAIVE_UTC | orjson.OPT_UTC_Z).decode()
+
+def _orjson_loads(s):
+ return orjson.loads(s)
+
+register("orjson", _orjson_dumps, _orjson_loads,
+ content_type="application/x-orjson",
+ content_encoding="utf-8")
+```
+
+Same speedup, applied to every task payload encode/decode.
+
+### Structured logging (structlog, custom slog)
+
+```python
+import structlog
+import orjson
+
+structlog.configure(
+ processors=[
+ structlog.processors.TimeStamper(fmt="iso"),
+ structlog.processors.add_log_level,
+ structlog.processors.JSONRenderer(serializer=orjson.dumps),
+ ],
+)
+```
+
+structlog's `JSONRenderer` accepts any callable; orjson is the obvious default. Logging hot paths benefit dramatically — every log line at info level becomes ~5× cheaper to render.
+
+---
+
+## 8. Gotchas
+
+### `orjson.dumps` returns bytes, not str
+
+```python
+# BAD — concatenating bytes and str
+log.info("payload: " + orjson.dumps(data)) # TypeError
+
+# GOOD
+log.info("payload: %s", orjson.dumps(data).decode())
+# or
+log.info("payload: %s", orjson.dumps(data)) # let the formatter handle it
+```
+
+### No `cls=` argument for custom encoders
+
+orjson uses `default=` only. If you have a custom `JSONEncoder` subclass from stdlib `json`, port its `default()` method to a `default=` callable.
+
+### Subclasses of `dict` / `list` are NOT serialized as their parent
+
+```python
+class StrictDict(dict): ...
+d = StrictDict({"k": "v"})
+
+import json
+json.dumps(d) # OK — stdlib walks subclasses
+orjson.dumps(d) # TypeError — orjson is strict by design
+orjson.dumps(d, option=orjson.OPT_PASSTHROUGH_SUBCLASS) # then route via default=
+```
+
+Set `OPT_PASSTHROUGH_SUBCLASS` and handle the subclass in `default=`. The design discourages accidental subclass usage that breaks elsewhere.
+
+### `int` overflow
+
+orjson refuses to encode integers larger than 2⁵³ - 1 by default (the IEEE-754 double-precision safe-integer limit — what JavaScript can round-trip). For larger ints, opt in:
+
+```python
+orjson.dumps(huge_int, option=orjson.OPT_STRICT_INTEGER) # error
+orjson.dumps(huge_int) # default — int is encoded as JSON number
+# JavaScript clients lose precision past 2^53; consider sending as string
+```
+
+This is more spec-strict than stdlib `json`, which silently emits ints of any size.
+
+### Timezone-naive datetimes
+
+By default, orjson treats naive `datetime` as the system local timezone — almost never what you want. **Always set `OPT_NAIVE_UTC`** to treat naive datetimes as UTC, or use timezone-aware datetimes (which is the better long-term habit).
+
+---
+
+## 9. Benchmark — should I actually adopt this?
+
+The numbers below are 2024–2026 averages from `tiangolo/fastapi#11728` and orjson's own benchmark suite, on Python 3.13, modern x86_64:
+
+| Payload | stdlib `json` | `orjson` | `model_dump_json()` (Pydantic v2) |
+|---|---|---|---|
+| Small dict (100 fields) | 1.0× | **8×** | n/a |
+| List of 10k dicts | 1.0× | **11×** | n/a |
+| Pydantic model with 20 fields | 1.0× (after `model_dump()`) | 5× (with `default=` bridge) | **6×** |
+| Datetime-heavy payload | 1.0× (after manual ISO conv) | **9×** | 6× |
+| numpy array (1M floats) | impossible without manual conv | **20×** vs json+tolist | n/a |
+
+The takeaways:
+
+- For raw dict/list/datetime, **orjson is dramatically faster**.
+- For Pydantic models, **`model_dump_json()` is already faster than orjson+bridge**.
+- For numpy, orjson is the only sane choice.
+
+In production, the actual measured win on a FastAPI app with mixed payloads is typically 5–15% reduction in p99 latency. Worth the one-line `default_response_class=ORJSONResponse` switch.
+
+---
+
+## 10. When NOT to adopt orjson
+
+- The codebase is small, JSON is not a bottleneck, and you have no measured perf concern.
+- You depend on stdlib `json`'s `cls=` arg or its lax tolerance for non-spec input (NaN, Infinity, comments).
+- You need pretty-printed JSON with custom indent — orjson only supports 2-space indent via the flag.
+- You need pure-Python portability (e.g., MicroPython, no-wheel platforms) — orjson is a compiled Rust extension.
+
+If the choice is "add a dependency that does 5–10× the speed on serialization for free", the answer is almost always yes. The "almost" is in the bullets above.
+
+---
+
+## Sources
+
+- orjson: https://github.com/ijl/orjson
+- Pydantic v2 `model_dump_json`: https://docs.pydantic.dev/latest/concepts/serialization/#modelmodel_dump_json
+- FastAPI `ORJSONResponse`: https://fastapi.tiangolo.com/advanced/custom-response/#use-orjsonresponse
+- "FastAPI + orjson vs Pydantic v2" benchmark: https://github.com/fastapi/fastapi/discussions/11728
+- structlog JSON rendering: https://www.structlog.org/en/stable/api.html#structlog.processors.JSONRenderer
diff --git a/plugins/omo/skills/programming/references/python/pydantic-ai.md b/plugins/omo/skills/programming/references/python/pydantic-ai.md
new file mode 100644
index 00000000..3d8f4110
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/pydantic-ai.md
@@ -0,0 +1,285 @@
+# PydanticAI Reference (v1.x, 2026)
+
+> Canonical patterns for wiring PydanticAI agents. Target: production usage, late-2025 / 2026.
+> Source: [ai.pydantic.dev](https://ai.pydantic.dev) and [pydantic/pydantic-ai@`cad9569`](https://github.com/pydantic/pydantic-ai/blob/cad956910079737ea0886b50cef15777208f92e6).
+
+---
+
+## 1. Agent Constructor
+
+```python
+from pydantic_ai import Agent
+
+agent = Agent(
+ 'openai:gpt-5.2', # model (str | Model | None)
+ output_type=MyOutputModel, # structured output type; default=str
+ instructions='You are a...', # static or callable instructions
+ system_prompt='Be concise.', # static system prompt(s)
+ deps_type=MyDeps, # dependency type for type-checking only
+ name='my-agent', # optional, inferred from var name if omitted
+ retries=1, # default retries for tools + output validation
+ output_retries=None, # override retries for output validation only
+ tools=[my_tool], # list of Tool objects or plain functions
+ defer_model_check=False, # set True to skip env-var check at init time
+ end_strategy='early', # 'early' | 'graceful' | 'exhaustive'
+)
+```
+
+**Breaking change (v1.88.0)**: `result_type` was renamed to `output_type`. Use `output_type`.
+
+---
+
+## 2. Model Strings
+
+Format: `provider:model-name`. The framework infers the provider from the prefix.
+
+| Provider prefix | Example |
+|---|---|
+| `openai:` | `'openai:gpt-5.2'`, `'openai:gpt-4o'` |
+| `anthropic:` | `'anthropic:claude-sonnet-4-6'`, `'anthropic:claude-opus-4-1'` |
+| `google-gla:` | `'google-gla:gemini-3-flash-preview'` |
+| `google-vertex:` | `'google-vertex:gemini-3-pro-preview'` |
+| `bedrock:` | `'bedrock:anthropic.claude-sonnet-4-6'` |
+| `xai:` / `grok:` | `'xai:grok-3'`, `'grok:grok-3-fast'` |
+| `deepseek:` | `'deepseek:deepseek-chat'` |
+| `cohere:` | `'cohere:command-r-08-2024'` |
+| `gateway/...` | `'gateway/openai:gpt-5.2'` (PydanticAI Gateway) |
+
+Model can also be omitted at construction and passed per-run: `agent.run(prompt, model='openai:gpt-5.2')`.
+
+---
+
+## 3. Tools
+
+### Decorator syntax
+
+```python
+from pydantic_ai import Agent, RunContext
+
+agent = Agent('openai:gpt-5.2', deps_type=str)
+
[email protected] # default: receives RunContext as first arg
+async def greet(ctx: RunContext[str], name: str) -> str:
+ return f"Hello {ctx.deps}, {name}!"
+
[email protected]_plain # no context needed
+async def roll_dice(sides: int) -> int:
+ import random
+ return random.randint(1, sides)
+```
+
+### `RunContext[Deps]`
+
+First parameter of `@agent.tool` functions. Carries:
+
+- `ctx.deps` — the dependency instance
+- `ctx.model` — the model being used
+- `ctx.usage` — token usage so far
+- `ctx.messages` — conversation history
+- `ctx.retry` / `ctx.max_retries` — current retry count
+- `ctx.agent` — the running agent instance
+
+Use `@agent.tool_plain` when the tool does **not** need any of the above.
+
+---
+
+## 4. Structured Output
+
+Pass a Pydantic `BaseModel` (or `bool`, `int`, `list[str]`, etc.) as `output_type`. The result is accessed via `.output`.
+
+```python
+from pydantic import BaseModel
+from pydantic_ai import Agent
+
+class City(BaseModel):
+ name: str
+ country: str
+ population_millions: float
+
+agent = Agent('openai:gpt-5.2', output_type=City)
+result = agent.run_sync('Tell me about Tokyo')
+print(result.output) # City(name='Tokyo', country='Japan', ...)
+print(result.output.name) # 'Tokyo'
+```
+
+**Note**: `result.data` was renamed; the canonical accessor is `result.output`.
+
+---
+
+## 5. Async vs Sync
+
+| Method | Mode | Returns |
+|---|---|---|
+| `await agent.run(prompt, ...)` | async | `AgentRunResult[OutputDataT]` |
+| `agent.run_sync(prompt, ...)` | sync | `AgentRunResult[OutputDataT]` |
+| `async with agent.run_stream(prompt, ...) as response:` | async streaming | `StreamedRunResult` |
+
+```python
+# Sync
+result = agent.run_sync('What is the capital of Italy?')
+print(result.output)
+
+# Async
+result = await agent.run('What is the capital of France?')
+print(result.output)
+
+# Streaming
+async with agent.run_stream('What is the capital of the UK?') as response:
+ async for text in response.stream_text():
+ print(text, end='')
+ # After streaming finishes:
+ print(response.output)
+```
+
+`run_sync()` is a convenience wrapper over `loop.run_until_complete(self.run(...))`. Do not use it inside an active async context.
+
+---
+
+## 6. Dependencies
+
+Use a `@dataclass` container, pass the **type** to `deps_type`, and pass an **instance** to `deps` at run time.
+
+```python
+from dataclasses import dataclass
+import httpx
+from pydantic_ai import Agent, RunContext
+
+@dataclass
+class Deps:
+ api_key: str
+ http_client: httpx.AsyncClient
+
+agent = Agent(
+ 'openai:gpt-5.2',
+ deps_type=Deps,
+)
+
+async def fetch_data(ctx: RunContext[Deps], endpoint: str) -> str:
+ r = await ctx.deps.http_client.get(
+ endpoint,
+ headers={'Authorization': f'Bearer {ctx.deps.api_key}'},
+ )
+ r.raise_for_status()
+ return r.text
+
+async def main():
+ async with httpx.AsyncClient() as client:
+ deps = Deps(api_key='sk-...', http_client=client)
+ result = await agent.run('Get /users', deps=deps)
+ print(result.output)
+```
+
+---
+
+## 7. Error Types & Retrying from a Tool
+
+```python
+from pydantic_ai import Agent, ModelRetry, UnexpectedModelBehavior, capture_run_messages
+
+agent = Agent('openai:gpt-5.2', retries=3)
+
+def calc_volume(size: int) -> int:
+ if size == 42:
+ return size ** 3
+ raise ModelRetry('Please try again with size 42.')
+
+with capture_run_messages() as messages:
+ try:
+ result = agent.run_sync('Get the volume of a box with size 6.')
+ except UnexpectedModelBehavior as e:
+ print('Error:', e) # "Tool 'calc_volume' exceeded max retries count of 3"
+ print('Cause:', e.__cause__) # ModelRetry('Please try again...')
+ print('Messages:', messages)
+```
+
+- **`ModelRetry`** — raise from a tool, output validator, or capability hook to ask the model to retry.
+- **`UnexpectedModelBehavior`** — raised when the retry limit is exceeded or the model API returns an unrecoverable error.
+- **`capture_run_messages()`** — context manager that records all messages exchanged during a run for debugging.
+
+---
+
+## 8. Logfire Integration
+
+One-line setup if the `logfire` extra is installed (included in the default `pydantic-ai` package):
+
+```python
+import logfire
+
+logfire.configure() # reads token from .logfire directory
+logfire.instrument_pydantic_ai() # auto-traces all agent runs
+```
+
+Alternatively, set `instrument=True` on the agent:
+
+```python
+agent = Agent('openai:gpt-5.2', instrument=True)
+```
+
+---
+
+## 9. Minimal Complete Snippets
+
+### (a) Basic agent with structured output
+
+```python
+from pydantic import BaseModel
+from pydantic_ai import Agent
+
+class City(BaseModel):
+ name: str
+ country: str
+
+agent = Agent('openai:gpt-5.2', output_type=City)
+result = agent.run_sync('Tell me about Paris')
+print(result.output) # City(name='Paris', country='France')
+```
+
+### (b) Agent with tools and dependencies
+
+```python
+from dataclasses import dataclass
+from pydantic_ai import Agent, RunContext
+
+@dataclass
+class Deps:
+ api_key: str
+
+agent = Agent('openai:gpt-5.2', deps_type=Deps)
+
+async def get_secret(ctx: RunContext[Deps], code: str) -> str:
+ if code == '1234':
+ return f'secret-for-{ctx.deps.api_key}'
+ return 'wrong code'
+
+result = agent.run_sync('My code is 1234', deps=Deps(api_key='sk-abc'))
+print(result.output)
+```
+
+### (c) Async streaming
+
+```python
+import anyio
+from pydantic_ai import Agent
+
+agent = Agent('openai:gpt-5.2')
+
+async def main() -> None:
+ async with agent.run_stream('Write a haiku about Python') as response:
+ async for text in response.stream_text():
+ print(text, end='')
+ print('\n---')
+ print('Final:', response.output)
+
+anyio.run(main)
+```
+
+---
+
+## Version Notes
+
+- **V1** reached API stability in September 2025. Breaking changes are reserved for V2 (earliest April 2026).
+- **v1.88.0** renamed `result_type` → `output_type` and `result_tool_name` / `result_tool_description` were removed. Use `output_type`.
+- The canonical accessor for run results is `result.output` (not `result.data`).
diff --git a/plugins/omo/skills/programming/references/python/pyproject-strict.md b/plugins/omo/skills/programming/references/python/pyproject-strict.md
new file mode 100644
index 00000000..7bbf9660
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/pyproject-strict.md
@@ -0,0 +1,232 @@
+# Strict pyproject.toml (basedpyright + ruff + uv)
+
+The canonical "super strict but sane" config for modern Python projects. Copy-paste, then add your own dependencies.
+
+## Bootstrap
+
+```bash
+# Application
+uv init --app myproject
+cd myproject
+
+# Library (publishable to PyPI)
+uv init --lib mylibrary
+cd mylibrary
+
+# Add dev tools
+uv add --dev basedpyright ruff pytest
+```
+
+`uv init` creates `pyproject.toml`, `.python-version`, and `src/` layout. Replace its `pyproject.toml` `[tool.*]` sections with the block below.
+
+## The full pyproject.toml
+
+```toml
+[project]
+name = "myproject"
+version = "0.1.0"
+description = "..."
+readme = "README.md"
+requires-python = ">=3.13"
+dependencies = []
+
+[dependency-groups]
+dev = [
+ "basedpyright>=1.21",
+ "ruff>=0.8",
+ "pytest>=8",
+ "pytest-cov>=5",
+]
+
+# ─────────────────────────────────────────────────────────────────
+# basedpyright - typeCheckingMode = "all" sets every report flag to error
+# Source: https://docs.basedpyright.com/latest/configuration/config-files/
+# ─────────────────────────────────────────────────────────────────
+[tool.basedpyright]
+typeCheckingMode = "all"
+pythonVersion = "3.13"
+pythonPlatform = "All" # default in basedpyright; explicit for clarity
+include = ["src", "tests"]
+exclude = ["**/__pycache__", "**/.venv", "**/build", "**/dist"]
+
+# Strict enforcement extras (most are already "error" under "all" mode,
+# but listing them explicitly documents the intent)
+reportUnusedCallResult = "warning" # flag ignored return values
+reportUnnecessaryTypeIgnoreComment = "error" # stale type: ignore comments must die
+reportUnusedVariable = "error" # unused variables are errors
+reportMissingParameterType = "error" # every parameter must have a type
+reportMissingReturnType = "error" # every function must declare its return type
+reportPrivateUsage = "error" # respect _private convention
+
+# Optional: gradual adoption baseline
+# baselineFile = "./.basedpyright/baseline.json"
+
+# ─────────────────────────────────────────────────────────────────
+# ruff - select = ["ALL"] enables every rule, then we ignore the
+# small set that conflicts with the formatter or is not useful.
+# Source: https://docs.astral.sh/ruff/linter/#rule-selection
+# ─────────────────────────────────────────────────────────────────
+[tool.ruff]
+target-version = "py313"
+line-length = 88 # ruff/black default; 100 or 120 also fine
+src = ["src", "tests"]
+
+[tool.ruff.lint]
+select = ["ALL"]
+ignore = [
+ # Formatter conflicts (ruff itself tells you to ignore these)
+ "COM812", # missing trailing comma
+ "ISC001", # implicit string concat
+ # Docstyle conflicts (pick D211 over D203, D212 over D213)
+ "D203",
+ "D213",
+ # Project-specific noise
+ "CPY001", # missing copyright notice
+ "FBT001", # boolean positional arg in def
+ "FBT002", # boolean positional default in def
+ "TD002", # missing TODO author
+ "TD003", # missing TODO link
+ "FIX002", # line contains TODO (TODOs are allowed)
+]
+fixable = ["ALL"]
+unfixable = []
+
+[tool.ruff.lint.per-file-ignores]
+"tests/**/*.py" = [
+ "S101", # `assert` is the entire point of pytest
+ "ARG", # unused args (fixtures appear unused)
+ "PLR2004", # magic numbers in test data
+ "SLF001", # tests need access to private members
+ "D", # docstrings not required in tests
+]
+"scripts/**/*.py" = [
+ "T201", # `print` allowed in scripts
+ "INP001", # implicit namespace package
+]
+
+[tool.ruff.lint.pydocstyle]
+convention = "google" # or "numpy" / "pep257"
+
+[tool.ruff.lint.flake8-bugbear]
+# typer / fastapi rely on call-as-default for parameter metadata.
+# Without this, ruff B008 ("function call in default") fires on every typer/fastapi route.
+extend-immutable-calls = [
+ "typer.Argument",
+ "typer.Option",
+ "fastapi.Depends",
+ "fastapi.Query",
+ "fastapi.Path",
+ "fastapi.Body",
+ "fastapi.Header",
+ "fastapi.Cookie",
+ "fastapi.File",
+ "fastapi.Form",
+]
+
+[tool.ruff.format]
+quote-style = "double"
+indent-style = "space"
+docstring-code-format = true
+docstring-code-line-length = "dynamic"
+
+# ─────────────────────────────────────────────────────────────────
+# pytest
+# ─────────────────────────────────────────────────────────────────
+[tool.pytest.ini_options]
+minversion = "8.0"
+testpaths = ["tests"]
+addopts = [
+ "-ra",
+ "--strict-config",
+ "--strict-markers",
+]
+filterwarnings = ["error"]
+
+# ─────────────────────────────────────────────────────────────────
+# coverage
+# ─────────────────────────────────────────────────────────────────
+[tool.coverage.run]
+source = ["src"]
+branch = true
+
+[tool.coverage.report]
+exclude_lines = [
+ "pragma: no cover",
+ "if TYPE_CHECKING:",
+ "if typing.TYPE_CHECKING:",
+ "raise NotImplementedError",
+ "@(abc\\.)?abstractmethod",
+]
+```
+
+## Why these settings
+
+### basedpyright `typeCheckingMode = "all"`
+
+basedpyright's modes, strictest first:
+
+| Mode | Behavior |
+|---|---|
+| `"all"` | Every diagnostic at `error` |
+| `"recommended"` | Same rules; less severe ones at `warning`; `failOnWarnings = true` makes CI still fail |
+| `"strict"` | pyright's strict mode |
+| `"standard"` | Default |
+| `"basic"` / `"off"` | Loose / disabled |
+
+`"all"` enables basedpyright-exclusive rules pyright lacks: `reportImplicitOverride`, `reportImplicitStringConcatenation`, `reportIncompatibleUnannotatedOverride`, `reportUnannotatedClassAttribute`. No need to opt-in to additional flags.
+
+`pythonPlatform = "All"` is basedpyright's default (better than pyright's host-OS default) - it errors on platform-specific imports that fail on other OSes.
+
+### ruff `select = ["ALL"]`
+
+The official docs say *"Use ALL with discretion. Enabling ALL will implicitly enable new rules whenever you upgrade."* For a strict skill that is the intended behavior - every new ruff rule should be considered an error until you justify ignoring it.
+
+The minimal ignore set:
+
+| Rule | Reason |
+|---|---|
+| `COM812`, `ISC001` | Conflict with `ruff format` (ruff itself documents this) |
+| `D203` vs `D211`, `D213` vs `D212` | Mutually-exclusive docstring conventions; pick the modern one |
+| `CPY001` | Most projects don't need a copyright header on every file |
+| `FBT001`, `FBT002` | Boolean flags are ergonomic for CLI/typer; ban makes typer awkward |
+| `TD002`, `TD003`, `FIX002` | TODOs without a JIRA link are fine in solo / internal code |
+
+`ANN101` and `ANN102` were **removed in ruff 0.8.0** (Nov 2024). Do NOT include them in `ignore` - ruff errors on unknown rule codes.
+
+`per-file-ignores` for `tests/**` is the standard pattern from real-world repos like `community-of-python/auto-typing-final` and `Preston-Landers/concurrent-log-handler`.
+
+## CI gate
+
+```bash
+# In CI, fail on any violation:
+uv run basedpyright
+uv run ruff check
+uv run ruff format --check
+uv run pytest
+```
+
+A single `make ci` target combining the four works fine.
+
+## Enforcement summary
+
+The config above, combined with `scripts/check-no-excuse-rules.py`, enforces:
+
+| What | How |
+|---|---|
+| Exhaustive match | basedpyright `all` mode + `assert_never` |
+| No `Any` | basedpyright `all` mode + script `cast-any` rule |
+| Ignored return values | `reportUnusedCallResult = "warning"` |
+| Immutable default | Script `mutable-dataclass` + `missing-slots` rules |
+| No null surprise | basedpyright strict `None` analysis |
+| Constants are const | basedpyright catches `Final` reassignment |
+| Unused variables | `reportUnusedVariable = "error"` |
+
+## Sources
+
+- basedpyright modes: <https://docs.basedpyright.com/latest/configuration/config-files/#type-check-diagnostics-settings>
+- basedpyright `"all"` vs `"recommended"`: <https://docs.basedpyright.com/latest/configuration/config-files/#recommended-and-all>
+- basedpyright better defaults: <https://docs.basedpyright.com/latest/benefits-over-pyright/better-defaults/>
+- ruff rule selection: <https://docs.astral.sh/ruff/linter/#rule-selection>
+- ruff ANN101/ANN102 removed: <https://github.com/astral-sh/ruff/pull/14384>
+- Real-world ALL config: <https://github.com/community-of-python/auto-typing-final/blob/main/pyproject.toml>
+- PEP 735 dependency-groups: <https://peps.python.org/pep-0735/>
diff --git a/plugins/omo/skills/programming/references/python/textual-tui.md b/plugins/omo/skills/programming/references/python/textual-tui.md
new file mode 100644
index 00000000..27f027de
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/textual-tui.md
@@ -0,0 +1,201 @@
+# Textual TUI
+
+Textual builds rich, mouse-aware, scrollable, mobile-style TUIs on top of `rich`. Replaces curses, urwid, blessed.
+
+## Install
+
+```bash
+uv add textual
+uv add --dev textual-dev # textual console + run --dev for hot reload
+```
+
+## Minimal app
+
+```python
+from textual.app import App, ComposeResult
+from textual.widgets import Header, Footer, Button, Label
+from textual.containers import Vertical
+
+
+class CounterApp(App[None]):
+ """A trivial counter app."""
+
+ BINDINGS = [("q", "quit", "Quit")]
+ CSS = """
+ #count {
+ height: 3;
+ content-align: center middle;
+ background: $boost;
+ }
+ """
+
+ count: int = 0
+
+ def compose(self) -> ComposeResult:
+ yield Header()
+ with Vertical():
+ yield Label("0", id="count")
+ yield Button("Increment", id="inc", variant="primary")
+ yield Button("Reset", id="reset", variant="warning")
+ yield Footer()
+
+ def on_button_pressed(self, event: Button.Pressed) -> None:
+ if event.button.id == "inc":
+ self.count += 1
+ elif event.button.id == "reset":
+ self.count = 0
+ self.query_one("#count", Label).update(str(self.count))
+
+
+if __name__ == "__main__":
+ CounterApp().run()
+```
+
+Run:
+
+```bash
+uv run python counter.py
+```
+
+For hot reload during development:
+
+```bash
+uv run textual run --dev counter.py
+```
+
+## Reactive attributes
+
+Textual's `reactive()` descriptor turns a class attribute into something that watches assignments and re-renders automatically. Replaces the manual `query_one` + `update` dance.
+
+```python
+from textual.app import App, ComposeResult
+from textual.reactive import reactive
+from textual.widgets import Label
+
+
+class CountWidget(Label):
+ count: reactive[int] = reactive(0)
+
+ def render(self) -> str:
+ return f"Count: {self.count}"
+
+
+class CounterApp(App[None]):
+ def compose(self) -> ComposeResult:
+ yield CountWidget()
+
+ def on_key(self, event) -> None:
+ if event.key == "space":
+ self.query_one(CountWidget).count += 1
+```
+
+`reactive()` triggers `render()` (or `watch_<attr>` and `validate_<attr>` callbacks if defined). Use `recompose=True` if you need to call `compose()` again on change.
+
+## Async work — workers
+
+NEVER block the event loop. For network/disk/CPU work, use `@work` (creates a worker) or `run_worker`.
+
+```python
+import httpx
+from textual.app import App, ComposeResult
+from textual.widgets import Input, Static
+from textual.work import work
+
+
+class FetchApp(App[None]):
+ def compose(self) -> ComposeResult:
+ yield Input(placeholder="URL", id="url")
+ yield Static(id="result")
+
+ @work(exclusive=True)
+ async def fetch(self, url: str) -> None:
+ async with httpx.AsyncClient(timeout=10.0) as client:
+ response = await client.get(url)
+ self.query_one("#result", Static).update(f"{response.status_code} - {len(response.text)} bytes")
+
+ def on_input_submitted(self, event: Input.Submitted) -> None:
+ self.fetch(event.value)
+```
+
+`exclusive=True` cancels the previous worker if the user submits a new URL before the first finishes. Workers integrate with Textual's lifecycle - they're cancelled when the app exits.
+
+`@work` is asyncio-flavoured under the hood. That is fine - it does not violate the no-asyncio rule because you are calling Textual's API, not importing asyncio yourself. Inside the worker body, use `httpx.AsyncClient` and other anyio-friendly libraries.
+
+## Action handlers
+
+Bind keys to method calls via `BINDINGS` and `action_*` methods.
+
+```python
+class App(App):
+ BINDINGS = [
+ ("ctrl+s", "save", "Save"),
+ ("ctrl+r", "reload", "Reload"),
+ ]
+
+ def action_save(self) -> None:
+ # Called on ctrl+s
+ ...
+
+ def action_reload(self) -> None:
+ ...
+```
+
+Bindings can also include the `priority=True` flag to fire before children get a chance.
+
+## CSS
+
+Textual's CSS supports selectors, variables (`$primary`, `$boost`), animations. Inline via `CSS = "..."` or external via `CSS_PATH = "app.tcss"`.
+
+```css
+Screen {
+ background: $surface;
+ color: $text;
+ layout: vertical;
+}
+
+#sidebar {
+ width: 30;
+ background: $boost;
+}
+
+Button.danger {
+ background: $error;
+}
+```
+
+Reload with `r` in dev mode (`textual run --dev`).
+
+## Testing
+
+```python
+import pytest
+from myapp import CounterApp
+
+
+async def test_counter_increments() -> None:
+ app = CounterApp()
+ async with app.run_test() as pilot:
+ await pilot.click("#inc")
+ await pilot.click("#inc")
+ assert app.count == 2
+```
+
+`pilot.click(selector)`, `pilot.press("q")`, `pilot.pause()` for waiting on the next frame.
+
+## When NOT to use Textual
+
+| Need | Use |
+|---|---|
+| One-off CLI with structured output | typer + rich |
+| Progress bar in a script | rich.progress |
+| Tabular display of query results | rich.table |
+| Full-screen app with state, input, mouse | Textual |
+
+A pretty CLI is not a TUI. Reach for Textual when the user expects to navigate a UI, not when you want colours.
+
+## Sources
+
+- Textual docs: <https://textual.textualize.io>
+- Textual tutorial: <https://textual.textualize.io/tutorial/>
+- API reference: <https://textual.textualize.io/api/>
diff --git a/plugins/omo/skills/programming/references/python/type-patterns.md b/plugins/omo/skills/programming/references/python/type-patterns.md
new file mode 100644
index 00000000..2811813d
--- /dev/null
+++ b/plugins/omo/skills/programming/references/python/type-patterns.md
@@ -0,0 +1,176 @@
+# Type Patterns
+
+How to use Python's type system to catch bugs at check time, not runtime.
+
+---
+
+## NewType — distinct primitives
+
+Same runtime type, different meaning. The type checker prevents mixing.
+
+```python
+from typing import NewType
+
+UserId = NewType("UserId", int)
+MovieId = NewType("MovieId", int)
+Email = NewType("Email", str)
+Seconds = NewType("Seconds", float)
+Milliseconds = NewType("Milliseconds", float)
+
+def get_user(user_id: UserId) -> User: ...
+def get_movie(movie_id: MovieId) -> Movie: ...
+def sleep(duration: Seconds) -> None: ...
+
+uid = UserId(42)
+mid = MovieId(42)
+
+get_user(uid) # OK
+get_user(mid) # type error: MovieId is not UserId
+get_user(42) # type error: int is not UserId
+sleep(Milliseconds(100.0)) # type error
+```
+
+**Use when**: IDs, indices, keys, units of measurement — any pair where swapping is a bug.
+**Skip when**: ephemeral local math where branding adds noise with zero safety gain.
+
+---
+
+## Final — constants are const
+
+Module-level constants declare their intent. Reassignment is a type error.
+
+```python
+from typing import Final
+
+MAX_RETRIES: Final = 3
+API_BASE_URL: Final = "https://api.example.com"
+DEFAULT_TIMEOUT: Final = 30.0
+
+MAX_RETRIES = 5 # type error: cannot assign to Final
+```
+
+If it changes at runtime, it's not a constant — make it a function parameter or config field.
+
+---
+
+## TypeAlias — name complex types
+
+If a union or generic appears more than once, give it a name.
+
+```python
+# Python 3.12+
+type JsonValue = str | int | float | bool | None | list["JsonValue"] | dict[str, "JsonValue"]
+type Headers = dict[str, str]
+type Middleware = Callable[[Request], Awaitable[Response]]
+
+# Pre-3.12
+from typing import TypeAlias
+
+JsonValue: TypeAlias = str | int | float | bool | None | list["JsonValue"] | dict[str, "JsonValue"]
+```
+
+---
+
+## StrEnum / IntEnum — closed sets
+
+Any fixed set of known values. No string literals scattered through code.
+
+```python
+from enum import StrEnum, IntEnum, unique
+
+@unique
+class Role(StrEnum):
+ ADMIN = "admin"
+ USER = "user"
+ GUEST = "guest"
+
+@unique
+class HttpStatus(IntEnum):
+ OK = 200
+ NOT_FOUND = 404
+ INTERNAL_ERROR = 500
+
+# BAD
+def check_role(role: str) -> bool: ...
+
+# GOOD
+def check_role(role: Role) -> bool: ...
+```
+
+`StrEnum` when values serialize as strings (API, DB). `IntEnum` for numeric codes. Plain `Enum` for pure labels.
+
+---
+
+## Type narrowing — let the checker follow your logic
+
+`isinstance`, `is None`, and `match` narrow types automatically. Use them instead of `cast`.
+
+```python
+def process(value: str | int | None) -> str:
+ if value is None:
+ return "nothing"
+ # checker knows: str | int
+
+ if isinstance(value, str):
+ return value.upper()
+ # checker knows: int
+
+ return str(value * 2)
+```
+
+### TypeGuard for custom narrowing
+
+```python
+from typing import TypeGuard
+
+def is_valid_email(value: str) -> TypeGuard[Email]:
+ return "@" in value and "." in value.split("@")[1]
+
+def send(addr: str) -> None:
+ if not is_valid_email(addr):
+ raise ValueError(addr)
+ # checker knows: addr is Email
+ deliver(addr)
+```
+
+### TypeIs (Python 3.13+) — the strict version
+
+`TypeIs` is stricter than `TypeGuard` — it narrows in both `if` and `else` branches.
+
+```python
+from typing import TypeIs
+
+def is_str(value: str | int) -> TypeIs[str]:
+ return isinstance(value, str)
+
+def handle(v: str | int) -> None:
+ if is_str(v):
+ print(v.upper()) # checker knows: str
+ else:
+ print(v + 1) # checker knows: int
+```
+
+---
+
+## Union syntax
+
+Always `X | Y`. Never `Union[X, Y]` or `Optional[X]`.
+
+```python
+# BAD
+from typing import Union, Optional
+def f(x: Optional[int]) -> Union[str, int]: ...
+
+# GOOD
+def f(x: int | None) -> str | int: ...
+```
+
+---
+
+## Sources
+
+- Python docs: [typing — NewType](https://docs.python.org/3/library/typing.html#newtype)
+- Python docs: [typing — Final](https://docs.python.org/3/library/typing.html#typing.Final)
+- Python docs: [typing — TypeGuard](https://docs.python.org/3/library/typing.html#typing.TypeGuard)
+- PEP 604: [Union syntax X | Y](https://peps.python.org/pep-0604/)
+- PEP 742: [TypeIs](https://peps.python.org/pep-0742/)
diff --git a/plugins/omo/skills/programming/references/rust-ub/README.md b/plugins/omo/skills/programming/references/rust-ub/README.md
new file mode 100644
index 00000000..55920b5a
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust-ub/README.md
@@ -0,0 +1,289 @@
+
+# Rust Undefined Behavior Exorcist
+
+You are a UB hunter. Your job is to find, classify, prove, and eliminate every instance of undefined behavior in Rust code. **Miri is your primary weapon** — everything else supplements where Miri cannot reach.
+
+## Core Philosophy
+
+1. **Miri first, always.** Before reading a single line of `unsafe`, run Miri. Before proposing a fix, run Miri. After applying a fix, run Miri. Miri is the oracle.
+2. **Classify before fixing.** Every UB finding gets classified against the 14-category taxonomy (see [ub-taxonomy.md](ub-taxonomy.md)). This prevents misdiagnosis and ensures the fix targets the root cause, not a symptom.
+3. **Prove the fix.** A fix is not done until Miri passes with full paranoia flags. If Miri cannot run the test (FFI, I/O), the fix is not done until the appropriate sanitizer passes.
+4. **Bead handoff.** Each resolved UB instance is a "bead" — a discrete, documented, proven fix. Hand it off with: the UB category, the root cause, the fix, and the Miri proof.
+
+## The UB Taxonomy
+
+14 categories. The full reference is in [ub-taxonomy.md](ub-taxonomy.md). Memorize the categories; classify every finding:
+
+| # | Category | Miri? |
+|---|----------|-------|
+| 1 | Aliasing violations (Stacked/Tree Borrows) | YES |
+| 2 | Data races | YES |
+| 3 | Use-after-free / dangling pointers | YES |
+| 4 | Uninitialized memory | YES |
+| 5 | Invalid values (type invariant violations) | YES |
+| 6 | Misaligned pointer access | YES |
+| 7 | Pin invariant violations | PARTIAL |
+| 8 | FFI boundary UB | LIMITED |
+| 9 | Incorrect Send/Sync implementations | YES (via race) |
+| 10 | Out-of-bounds memory access | YES |
+| 11 | Provenance violations | YES (strict mode) |
+| 12 | Double free / invalid free | YES |
+| 13 | Library / unsafe contract violations | PARTIAL |
+| 14 | Unwinding across extern "C" | PARTIAL |
+
+## The Hunt Workflow
+
+### Phase 1: Reconnaissance
+
+1. **Find all `unsafe` blocks and `unsafe impl`s:**
+ ```bash
+ rg 'unsafe\s*(fn|impl|{|\{)' --type rust -n
+ ```
+
+2. **Find all `unsafe` trait implementations:**
+ ```bash
+ rg 'unsafe\s+impl\s+(Send|Sync)' --type rust -n
+ ```
+
+3. **Find transmute / pointer casts / raw pointer derefs:**
+ ```bash
+ rg '(transmute|transmute_copy|from_raw|into_raw|as_ptr|as_mut_ptr|offset|add|sub|read|write|copy|ptr::null)' --type rust -n
+ ```
+
+4. **Find FFI boundaries:**
+ ```bash
+ rg 'extern\s+"C"' --type rust -n
+ ```
+
+5. **Count and catalog.** Create a hit list: file, line, `unsafe` category, initial risk assessment (high/medium/low based on the UB taxonomy).
+
+### Phase 2: Miri Sweep (THE CRITICAL PHASE)
+
+Run Miri with escalating strictness. **Do not skip any level.**
+
+**Level 1 — Default (Stacked Borrows):**
+```bash
+cargo +nightly miri test 2>&1
+```
+
+**Level 2 — Strict Provenance + Symbolic Alignment:**
+```bash
+MIRIFLAGS="-Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-backtrace=full" \
+ cargo +nightly miri test 2>&1
+```
+
+**Level 3 — Full Paranoia (the audit standard):**
+```bash
+MIRIFLAGS="\
+ -Zmiri-strict-provenance \
+ -Zmiri-symbolic-alignment-check \
+ -Zmiri-preemption-rate=0.1 \
+ -Zmiri-backtrace=full \
+ -Zmiri-disable-isolation" \
+ cargo +nightly miri test 2>&1
+```
+
+**Level 4 — Tree Borrows (second model confirmation):**
+```bash
+MIRIFLAGS="\
+ -Zmiri-tree-borrows \
+ -Zmiri-strict-provenance \
+ -Zmiri-symbolic-alignment-check \
+ -Zmiri-preemption-rate=0.1 \
+ -Zmiri-backtrace=full \
+ -Zmiri-disable-isolation" \
+ cargo +nightly miri test 2>&1
+```
+
+**Interpret results:**
+- Fails at Level 1 → Definite UB. Fix immediately.
+- Passes Level 1, fails Level 2 → Provenance or alignment UB. Fix.
+- Passes Levels 1-3, fails Level 4 → Tree Borrows found something Stacked Borrows missed (unusual). Investigate — may be a Tree Borrows false positive, but usually indicates fragile aliasing.
+- Passes all 4 → Miri-clean. Proceed to supplementary tools.
+
+### Phase 3: Supplementary Scans
+
+For code Miri cannot fully cover:
+
+**Concurrent code with custom atomics:**
+```bash
+RUSTFLAGS="--cfg loom" cargo test --lib --release -- loom_tests 2>&1
+```
+
+**FFI-heavy code:**
+```bash
+RUSTFLAGS="-Zsanitizer=address" cargo +nightly test -Zbuild-std --target $(rustc -vV | rg host | awk '{print $2}') 2>&1
+```
+
+**Untrusted input parsing:**
+```bash
+cargo +nightly fuzz run <target> -- -max_total_time=300 2>&1
+```
+
+### Phase 4: Fix-and-Prove Loop
+
+For each UB finding:
+
+1. **Classify** against the 14-category taxonomy.
+2. **Write the SAFETY comment** explaining what is wrong and what the fix must achieve.
+3. **Apply the minimal fix.** Do not refactor — fix the UB and nothing else.
+4. **Run Miri (Level 3 minimum) on the specific test that triggered the UB.**
+5. **Run Miri (Level 3) on the full test suite** to check for regressions.
+6. **Document the bead:**
+ ```
+ BEAD: [Category #] [Short description]
+ FILE: [path:line]
+ ROOT CAUSE: [one sentence]
+ FIX: [one sentence]
+ PROOF: Miri Level [N] pass — [command used]
+ ```
+
+### Phase 5: Hardening (Post-Fix)
+
+After all beads are resolved:
+
+1. **Add Miri to CI** if not already present (see [miri-sanitizers-loom.md](miri-sanitizers-loom.md) for the GitHub Actions config).
+2. **Add `#[cfg(miri)]` regression tests** for each bead — these are the tests that originally caught the UB, locked in so it never returns.
+3. **Review SAFETY comments** on every remaining `unsafe` block. Each must name the specific invariant from the taxonomy.
+4. **Run the full paranoia sweep one final time** to confirm clean.
+
+## Miri-First Decision Protocol
+
+When the agent encounters `unsafe` code during ANY Rust task (not just audits):
+
+```
+Is there unsafe code in the changeset?
+ YES → Run Miri Level 1 before proceeding.
+ │ Miri fails?
+ │ YES → Stop. Classify. Fix. Prove. Then continue.
+ │ NO → Run Miri Level 2 (strict provenance).
+ │ Miri fails?
+ │ YES → Stop. Classify. Fix. Prove. Then continue.
+ │ NO → Proceed with the original task.
+ NO → Proceed normally.
+```
+
+This is not optional. **Every `unsafe` block gets Miri'd before it ships.**
+
+## SAFETY Comment Standard
+
+Every `unsafe` block requires a SAFETY comment within 5 lines above it. The comment must:
+
+1. **Name the UB category** it could trigger (from the taxonomy).
+2. **State the invariant** that makes this safe.
+3. **Name who/what guarantees** the invariant (caller contract, type system, runtime check).
+
+```rust
+// SAFETY: [Category 4 — Uninitialized Memory]
+// All N elements have been written to via `ptr::write` in the loop above.
+// The loop runs exactly `len` times, and `len` was validated against the
+// allocation size at line 42. MaybeUninit::assume_init is therefore sound.
+unsafe { buf.assume_init() }
+```
+
+Bad SAFETY comments that must be rejected:
+- `// SAFETY: we know this is safe` — Says nothing.
+- `// SAFETY: this is fine because we tested it` — Testing does not prove absence of UB.
+- `// SAFETY: the caller ensures correctness` — Which invariant? What is the contract?
+- No SAFETY comment at all — Immediate failure.
+
+## Audit Report Format
+
+When completing a UB audit, produce a summary:
+
+```markdown
+## UB Audit Report
+
+**Scope:** [crate/module/file]
+**Miri version:** [output of `cargo +nightly miri --version`]
+**Date:** [date]
+
+### Findings
+
+| # | Category | File:Line | Severity | Status |
+|---|----------|-----------|----------|--------|
+| 1 | Aliasing | src/buf.rs:42 | High | Fixed (Bead #1) |
+| 2 | Uninit | src/ffi.rs:98 | High | Fixed (Bead #2) |
+
+### Beads
+
+#### Bead #1: Aliasing violation in buffer resize
+- **Root cause:** `&mut` created while `&` to same slice existed
+- **Fix:** Restructured to drop shared ref before taking mutable
+- **Proof:** `cargo +nightly miri test -- test_buffer_resize` passes Level 3
+
+### Miri CI Status
+- [ ] Miri added to CI (Level 2 minimum)
+- [ ] All SAFETY comments reviewed
+- [ ] Regression tests added for each bead
+```
+
+## Common Fix Patterns
+
+### Aliasing → Use `UnsafeCell` or restructure borrows
+```rust
+// BEFORE (UB: &mut while & exists)
+let ptr = slice.as_ptr();
+let mut_ref = &mut slice[0]; // UB: ptr still usable
+
+// AFTER
+let mut_ref = &mut slice[0];
+// ptr is never created / used across the mutable borrow
+```
+
+### Uninitialized → Use `MaybeUninit::write` + `assume_init`
+```rust
+// BEFORE (UB: mem::uninitialized)
+let x: T = unsafe { std::mem::uninitialized() };
+
+// AFTER
+let x: T = unsafe {
+ let mut uninit = MaybeUninit::<T>::uninit();
+ uninit.write(initial_value);
+ uninit.assume_init()
+};
+```
+
+### Provenance → Use `expose_provenance` / `with_exposed_provenance`
+```rust
+// BEFORE (UB: provenance lost)
+let addr = ptr as usize;
+let recovered = addr as *const T;
+
+// AFTER
+let addr = ptr.expose_provenance();
+let recovered = std::ptr::with_exposed_provenance::<T>(addr);
+```
+
+### Send/Sync → Remove manual impl, use PhantomData
+```rust
+// BEFORE (unsound)
+unsafe impl Send for MyType {}
+
+// AFTER — if MyType truly needs Send, prove it:
+// SAFETY: [Category 9 — Send/Sync]
+// MyType's only non-Send field is `*mut Buffer`. Access to the buffer
+// is guarded by `self.lock: Mutex<()>`, which provides the
+// happens-before guarantee required by Send.
+unsafe impl Send for MyType {}
+```
+
+### FFI → Validate at boundary
+```rust
+// BEFORE (UB: null pointer from C becomes &T)
+let result = unsafe { ffi_call() };
+
+// AFTER
+let raw = unsafe { ffi_call() };
+let result = NonNull::new(raw).ok_or(Error::NullFromFfi)?;
+```
+
+## Activation
+
+This skill activates when:
+- The user requests a "UB audit", "miri sweep", "unsafe audit", "soundness check", "rustonomicon audit", "race hunt"
+- The agent encounters `unsafe` code during a Rust task and needs to verify it
+- Miri reports a failure and the agent needs to classify and fix it
+- The user asks "is this sound?" about Rust code
+
+**Miri is not optional. Miri is the proof. Ship nothing `unsafe` without Miri's blessing.**
diff --git a/plugins/omo/skills/programming/references/rust-ub/miri-sanitizers-loom.md b/plugins/omo/skills/programming/references/rust-ub/miri-sanitizers-loom.md
new file mode 100644
index 00000000..8ba81e74
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust-ub/miri-sanitizers-loom.md
@@ -0,0 +1,411 @@
+# Miri, Sanitizers, Loom, and Fuzzing — The UB Detection Arsenal
+
+Miri is the **primary weapon**. Everything else is supplementary for the gaps Miri cannot reach.
+
+---
+
+## Miri — The First and Last Line of Defense
+
+### What Miri Is
+
+Miri is an interpreter for Rust's MIR (Mid-level IR). It executes your test suite inside a virtual machine that tracks every byte of memory for validity, provenance, alignment, initialization, and aliasing. It is **deterministic** — same inputs, same result — and it can find UB that no amount of testing on real hardware will ever trigger.
+
+### Why Miri Is Non-Negotiable
+
+- Detects 12 of 14 UB categories (see `ub-taxonomy.md`).
+- Catches aliasing violations that compile and run correctly on every platform today but are UB that future compiler optimizations will exploit.
+- Catches data races under a configurable scheduling model.
+- Catches provenance violations that are impossible to observe on real hardware.
+- **Zero false positives** — if Miri says it is UB, it is UB. Period.
+
+### Installation
+
+```bash
+rustup install nightly
+rustup component add miri rust-src --toolchain nightly
+```
+
+Verify:
+```bash
+cargo +nightly miri --version
+```
+
+### Running Miri
+
+**Default run (Stacked Borrows, standard checks):**
+```bash
+cargo +nightly miri test
+```
+
+**With nextest (recommended for projects already using nextest):**
+```bash
+cargo +nightly miri nextest run
+```
+
+**Specific test:**
+```bash
+cargo +nightly miri test -- test_name
+```
+
+**Run a binary:**
+```bash
+cargo +nightly miri run
+```
+
+### MIRIFLAGS — The Dial-Up Knobs
+
+These flags are set via the `MIRIFLAGS` environment variable. The agent should use ALL of the strictness flags during a UB audit.
+
+#### Aliasing Model
+
+```bash
+# Default: Stacked Borrows (strict)
+cargo +nightly miri test
+
+# Tree Borrows (newer, more permissive — use as a second pass)
+MIRIFLAGS="-Zmiri-tree-borrows" cargo +nightly miri test
+```
+
+**Protocol:** Run Stacked Borrows first. If it fails, fix it. Then run Tree Borrows to confirm. Code that passes Stacked Borrows is sound under both models.
+
+#### Strict Provenance
+
+```bash
+MIRIFLAGS="-Zmiri-strict-provenance" cargo +nightly miri test
+```
+
+Catches `ptr as usize as *const T` roundtrips where provenance is lost. **Should be ON for every audit.**
+
+#### Symbolic Alignment Checks
+
+```bash
+MIRIFLAGS="-Zmiri-symbolic-alignment-check" cargo +nightly miri test
+```
+
+Catches alignment UB that happens to be aligned on your machine but is not guaranteed by the type system.
+
+#### Data Race Detection Tuning
+
+```bash
+# Increase preemption rate to stress-test race conditions
+MIRIFLAGS="-Zmiri-preemption-rate=0.5" cargo +nightly miri test
+
+# Disable preemption (sequential scheduling — fewer races found but deterministic)
+MIRIFLAGS="-Zmiri-preemption-rate=0" cargo +nightly miri test
+```
+
+#### The Full Paranoia Sweep (Use This for Audits)
+
+```bash
+MIRIFLAGS="\
+ -Zmiri-strict-provenance \
+ -Zmiri-symbolic-alignment-check \
+ -Zmiri-preemption-rate=0.1 \
+ -Zmiri-backtrace=full \
+ -Zmiri-disable-isolation" \
+cargo +nightly miri test
+```
+
+Then a second pass with Tree Borrows:
+```bash
+MIRIFLAGS="\
+ -Zmiri-tree-borrows \
+ -Zmiri-strict-provenance \
+ -Zmiri-symbolic-alignment-check \
+ -Zmiri-preemption-rate=0.1 \
+ -Zmiri-backtrace=full \
+ -Zmiri-disable-isolation" \
+cargo +nightly miri test
+```
+
+#### Isolation and I/O
+
+Miri runs in isolation by default — no file I/O, no network, no system calls. If your tests need the filesystem:
+```bash
+MIRIFLAGS="-Zmiri-disable-isolation" cargo +nightly miri test
+```
+
+Use sparingly — isolation is a feature, not a limitation. Tests that need I/O should have a separate `#[cfg(not(miri))]` path.
+
+### Miri Limitations
+
+| Cannot do | Workaround |
+|-----------|-----------|
+| Execute FFI / C code | ASAN, MSAN, Valgrind |
+| Run I/O-heavy tests (default) | `-Zmiri-disable-isolation` or `#[cfg(not(miri))]` |
+| Exhaustive interleaving exploration | loom |
+| Find performance bugs | criterion, flamegraph |
+| Run inline assembly | skip with `#[cfg(not(miri))]` |
+| Test OS-specific behavior | real hardware + sanitizers |
+
+### Miri in CI
+
+```yaml
+# GitHub Actions example
+miri:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@nightly
+ with:
+ components: miri, rust-src
+ - name: Miri test (Stacked Borrows + strict provenance)
+ run: |
+ MIRIFLAGS="-Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-backtrace=full" \
+ cargo +nightly miri test
+ - name: Miri test (Tree Borrows)
+ run: |
+ MIRIFLAGS="-Zmiri-tree-borrows -Zmiri-strict-provenance -Zmiri-symbolic-alignment-check -Zmiri-backtrace=full" \
+ cargo +nightly miri test
+```
+
+### Miri-Incompatible Test Gating
+
+```rust
+#[test]
+#[cfg_attr(miri, ignore)] // Miri cannot run this (FFI, I/O, inline asm)
+fn test_requires_real_hardware() {
+ // ...
+}
+
+// Or conditionally compile the test body:
+#[test]
+fn test_with_miri_fallback() {
+ #[cfg(miri)]
+ {
+ // Simplified version that avoids FFI
+ }
+ #[cfg(not(miri))]
+ {
+ // Full version with FFI
+ }
+}
+```
+
+---
+
+## Sanitizers — Where Miri Cannot Reach
+
+Sanitizers are compiler instrumentation passes. They run your actual binary on real hardware with extra checks injected. Use them for FFI, I/O-heavy code, and integration tests.
+
+### AddressSanitizer (ASAN)
+
+Detects: use-after-free, buffer overflow, stack-use-after-return, double-free, memory leaks.
+
+```bash
+RUSTFLAGS="-Zsanitizer=address" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu
+```
+
+On macOS:
+```bash
+RUSTFLAGS="-Zsanitizer=address" cargo +nightly test -Zbuild-std --target aarch64-apple-darwin
+```
+
+### ThreadSanitizer (TSAN)
+
+Detects: data races on non-atomic accesses across threads.
+
+```bash
+RUSTFLAGS="-Zsanitizer=thread" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu
+```
+
+**When to use over Miri:** Integration tests involving real threads + real I/O + FFI. Miri's data-race detector is superior for pure-Rust code.
+
+### MemorySanitizer (MSAN)
+
+Detects: reads of uninitialized memory.
+
+```bash
+RUSTFLAGS="-Zsanitizer=memory -Zsanitizer-memory-track-origins" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu
+```
+
+**When to use over Miri:** FFI code where C/C++ may return uninitialized memory into Rust.
+
+### UndefinedBehaviorSanitizer (UBSAN)
+
+Detects: integer overflow, misaligned access, null dereference, and other C/C++-style UB at the LLVM level.
+
+```bash
+RUSTFLAGS="-Zsanitizer=undefined" cargo +nightly test -Zbuild-std --target x86_64-unknown-linux-gnu
+```
+
+### Sanitizer Limitations
+
+- Require nightly + `-Zbuild-std` (rebuilds the standard library with instrumentation).
+- MSAN requires ALL dependencies (including C libs) to be instrumented — practically hard.
+- Cannot catch aliasing violations (that is Miri's domain).
+- Significant runtime overhead (2-15x slower).
+- Linux has the best support; macOS works for ASAN; Windows support is minimal.
+
+---
+
+## Loom — Exhaustive Concurrency Testing
+
+Loom explores all possible thread interleavings of a bounded concurrent program. It is mandatory for lock-free and wait-free primitives.
+
+### When to Use Loom
+
+- Any `unsafe` code involving atomics with ordering weaker than `SeqCst`.
+- Custom lock implementations.
+- Lock-free queues, stacks, or other concurrent data structures.
+- Any code where you chose `Relaxed`, `Acquire`, or `Release` ordering.
+
+### When NOT to Use Loom
+
+- Code using only `Mutex`/`RwLock` from std or `parking_lot` — the locks are sound, your usage is the question, and Miri + TSAN cover that.
+- Async code (loom does not model async runtimes — use `tokio::test` + Miri instead).
+
+### Setup
+
+```toml
+[dev-dependencies]
+loom = "0.7"
+```
+
+### Loom Test Pattern
+
+```rust
+#[cfg(loom)]
+mod loom_tests {
+ use loom::sync::atomic::{AtomicUsize, Ordering};
+ use loom::sync::Arc;
+ use loom::thread;
+
+ #[test]
+ fn concurrent_increment_is_sound() {
+ loom::model(|| {
+ let counter = Arc::new(AtomicUsize::new(0));
+
+ let threads: Vec<_> = (0..2).map(|_| {
+ let c = counter.clone();
+ thread::spawn(move || {
+ c.fetch_add(1, Ordering::SeqCst);
+ })
+ }).collect();
+
+ for t in threads {
+ t.join().unwrap();
+ }
+
+ assert_eq!(counter.load(Ordering::SeqCst), 2);
+ });
+ }
+}
+```
+
+### Conditional Compilation for Loom
+
+```rust
+#[cfg(loom)]
+use loom::sync::atomic::{AtomicUsize, Ordering};
+#[cfg(not(loom))]
+use std::sync::atomic::{AtomicUsize, Ordering};
+```
+
+### Running Loom Tests
+
+```bash
+# Loom tests only (use cfg flag)
+RUSTFLAGS="--cfg loom" cargo test --lib -- loom_tests
+
+# With release optimizations (loom is slow)
+RUSTFLAGS="--cfg loom" cargo test --lib --release -- loom_tests
+```
+
+### Loom + Miri Interaction
+
+Loom and Miri solve different problems:
+- **Miri** checks a single execution for UB (aliasing, validity, provenance).
+- **Loom** checks all interleavings for correctness (ordering, atomicity).
+
+Run BOTH on lock-free code:
+```bash
+# Step 1: loom for interleaving correctness
+RUSTFLAGS="--cfg loom" cargo test --lib --release -- loom_tests
+
+# Step 2: Miri for UB in each path
+cargo +nightly miri test -- concurrent_tests
+```
+
+---
+
+## Cargo-Fuzz — Property-Based UB Hunting
+
+Fuzzing generates random inputs to maximize code coverage and find crashes, panics, and UB.
+
+### Setup
+
+```bash
+cargo install cargo-fuzz
+cargo fuzz init
+```
+
+### Fuzz Target
+
+```rust
+// fuzz/fuzz_targets/parse_input.rs
+#![no_main]
+use libfuzzer_sys::fuzz_target;
+
+fuzz_target!(|data: &[u8]| {
+ // Your parsing/deserialization/processing code here.
+ // If it panics or triggers UB, the fuzzer catches it.
+ let _ = my_crate::parse(data);
+});
+```
+
+### Running
+
+```bash
+# Run until interrupted
+cargo +nightly fuzz run parse_input
+
+# Run with ASAN (catches memory bugs in unsafe code)
+cargo +nightly fuzz run parse_input -- -rss_limit_mb=4096
+
+# Minimize a crashing input
+cargo +nightly fuzz tmin parse_input artifacts/parse_input/crash-xxxxx
+```
+
+### Fuzz + Miri Pipeline
+
+When the fuzzer finds a crashing input:
+1. Minimize it with `cargo fuzz tmin`.
+2. Add it as a regression test.
+3. Run the regression test under Miri to classify whether it is a panic (safe) or UB (must fix).
+
+```bash
+# After adding the input as a test case:
+cargo +nightly miri test -- test_fuzz_regression_001
+```
+
+---
+
+## Tool Selection Decision Tree
+
+```
+Start
+ │
+ ├── Is it pure Rust (no FFI, no I/O)?
+ │ YES → Miri (full paranoia flags)
+ │ │ └── Also: loom (if atomics/lock-free)
+ │ │ └── Also: proptest (if parsing/serialization)
+ │ │ └── Also: cargo-fuzz (if untrusted input)
+ │ │
+ │ NO → Does it involve FFI?
+ │ YES → ASAN + MSAN on integration tests
+ │ │ └── Miri on the Rust-side handling
+ │ │ └── cbindgen in CI for layout verification
+ │ │
+ │ NO → Is it I/O-heavy?
+ │ YES → TSAN for thread safety
+ │ │ └── Miri with -Zmiri-disable-isolation where possible
+ │ │
+ │ NO → Miri (full paranoia flags)
+ │
+ └── Always: Miri is the default. Other tools supplement.
+```
+
+## The One Rule
+
+> **When in doubt, run Miri.** If Miri cannot run it, write a version it can run, and test that under Miri. Then test the real version under sanitizers. Never ship `unsafe` code that has not passed Miri.
diff --git a/plugins/omo/skills/programming/references/rust-ub/ub-taxonomy.md b/plugins/omo/skills/programming/references/rust-ub/ub-taxonomy.md
new file mode 100644
index 00000000..b5b64283
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust-ub/ub-taxonomy.md
@@ -0,0 +1,269 @@
+# Rust Undefined Behavior Taxonomy
+
+Every category of UB the Rust compiler, Miri, and the language specification recognize. The agent must know the full surface to hunt systematically. Each entry names the UB class, its root cause, canonical trigger, Miri detection status, and the canonical fix.
+
+## 1. Aliasing Violations (Stacked Borrows / Tree Borrows)
+
+**Root cause:** Two pointers access the same memory in ways that violate Rust's borrowing model — even through raw pointers inside `unsafe`.
+
+**Canonical triggers:**
+- Creating a `&mut T` while another `&T` or `&mut T` to the same location exists.
+- Dereferencing a raw pointer derived from a reference after that reference was invalidated (e.g., `&mut` was retaken).
+- Calling `slice::from_raw_parts_mut` on overlapping regions.
+- Interior mutability through `UnsafeCell` without going through the `UnsafeCell` API.
+- Casting `&T` to `*mut T` and writing through it (even via FFI).
+
+**Miri detection:** YES — Stacked Borrows is the default model. Tree Borrows (`-Zmiri-tree-borrows`) is the newer, more permissive model. Run both:
+```bash
+cargo +nightly miri test # Stacked Borrows (stricter)
+MIRIFLAGS="-Zmiri-tree-borrows" cargo +nightly miri test # Tree Borrows (relaxed)
+```
+If code passes Tree Borrows but fails Stacked Borrows, it is *likely* sound but *possibly* relying on unspecified behavior. Fix it anyway — Stacked Borrows is the conservative bet.
+
+**Fix pattern:** Use `UnsafeCell` for all interior mutability. Never cast `&T` to `*mut T`. Derive mutable pointers from `*mut T` obtained via `UnsafeCell::get()` or `addr_of_mut!()`.
+
+---
+
+## 2. Data Races
+
+**Root cause:** Two threads access the same non-atomic memory location, at least one is a write, and there is no happens-before ordering between them.
+
+**Canonical triggers:**
+- `unsafe impl Send for T` on a type containing `*mut U` without synchronization.
+- `unsafe impl Sync for T` on a type containing `Cell<T>` or `UnsafeCell<T>` without a lock.
+- Using `std::ptr::write` from multiple threads to the same allocation.
+- Shared `&T` where `T` has interior mutability but no atomic/lock guard.
+
+**Miri detection:** YES — Miri's data-race detector is on by default. It detects races on non-atomic accesses. For **preemptive scheduling** stress, use:
+```bash
+MIRIFLAGS="-Zmiri-preemption-rate=0.1" cargo +nightly miri test
+```
+
+**Complementary tools:** `loom` for exhaustive interleaving exploration on lock-free algorithms. ThreadSanitizer (TSAN) for integration tests Miri cannot run (I/O, FFI).
+
+**Fix pattern:** Wrap in `Mutex`/`RwLock`/`AtomicXxx`. Never `unsafe impl Sync` unless you can name the synchronization primitive guarding every mutable field.
+
+---
+
+## 3. Use After Free / Dangling Pointers
+
+**Root cause:** A pointer or reference outlives the allocation it points to.
+
+**Canonical triggers:**
+- Returning a reference to a local variable (compiler catches most, but raw pointers escape).
+- `Box::into_raw` → manual `Box::from_raw` with wrong lifetime.
+- `Vec` reallocation invalidating raw pointers obtained from `as_ptr()` / `as_mut_ptr()`.
+- `Pin<Box<T>>` unpinned and moved after self-referential pointers were set up.
+
+**Miri detection:** YES — allocation tracking catches use-after-free on the exact operation.
+
+**Fix pattern:** Borrow checker for references. For raw pointers: tie pointer validity to an explicit lifetime via a `PhantomData<&'a T>` in the wrapper, or use arena allocation (`bumpalo`) so all pointers share one lifetime.
+
+---
+
+## 4. Uninitialized Memory
+
+**Root cause:** Reading a value from memory that was never written to.
+
+**Canonical triggers:**
+- `MaybeUninit::assume_init()` before all bytes are written.
+- `mem::uninitialized()` (deprecated, still compiles).
+- `alloc::alloc(layout)` returns uninitialized memory — reading it before writing is UB.
+- Padding bytes in structs read via `transmute` or raw pointer casts.
+- `read_unaligned` on uninitialized memory.
+
+**Miri detection:** YES — tracks initialization state per byte. Catches partial-init structs, padding reads, and premature `assume_init`.
+
+**Fix pattern:** Use `MaybeUninit::zeroed()` when zero-init is acceptable. Write every field before calling `assume_init()`. Use `MaybeUninit::write()` instead of raw pointer writes. Never `transmute` structs with padding unless you zeroed the padding.
+
+---
+
+## 5. Invalid Values (Type Invariant Violations)
+
+**Root cause:** Producing a value that violates the type's validity invariant.
+
+**Canonical triggers:**
+- `bool` not 0 or 1.
+- `char` outside Unicode scalar range.
+- Enum discriminant not matching any variant.
+- `NonZeroU32` containing 0.
+- `&T` or `&mut T` that is null or dangling.
+- `str` containing non-UTF-8 bytes.
+- `fn` pointer that is null.
+
+**Miri detection:** YES — validity checks are on by default. Extra strictness:
+```bash
+MIRIFLAGS="-Zmiri-strict-provenance" cargo +nightly miri test
+```
+
+**Fix pattern:** Validate before transmuting. Use `TryFrom` at boundaries. Never `transmute` to enum types — use a checked conversion function.
+
+---
+
+## 6. Misaligned Pointer Access
+
+**Root cause:** Dereferencing a pointer that is not aligned to the type's required alignment.
+
+**Canonical triggers:**
+- Casting `*const u8` to `*const u64` and dereferencing (alignment goes from 1 to 8).
+- `#[repr(packed)]` struct field references (the compiler warns, but raw pointers bypass the warning).
+- Network buffer parsing where offsets are arbitrary.
+
+**Miri detection:** YES — immediate trap on misaligned read/write.
+
+**Fix pattern:** Use `read_unaligned` / `write_unaligned` for packed data. Use `bytemuck` or `zerocopy` for safe reinterpretation with alignment checks.
+
+---
+
+## 7. Violating `Pin` Invariants
+
+**Root cause:** Moving a value that was pinned and relied on its address stability (self-referential types, intrusive linked lists).
+
+**Canonical triggers:**
+- `mem::swap` on a `Pin<&mut T>` after `unsafe` deref.
+- Implementing `Unpin` for a type that contains self-referential pointers.
+- Manually calling `Pin::new_unchecked` on a movable allocation.
+
+**Miri detection:** PARTIAL — Miri detects the resulting aliasing/use-after-free if the self-referential pointer is actually used. It does not detect "Pin contract violated but pointer was never dereferenced."
+
+**Fix pattern:** Never `impl Unpin` for self-referential types. Use `pin_project` or `pin_project_lite` for safe pin projections. Review every `Pin::new_unchecked` call.
+
+---
+
+## 8. FFI Boundary UB
+
+**Root cause:** Mismatch between Rust's ABI expectations and the foreign code's actual behavior.
+
+**Canonical triggers:**
+- C function returning uninitialized memory into a Rust `&T`.
+- Wrong `#[repr(C)]` layout (padding differs between platforms).
+- Passing a Rust `enum` to C without `#[repr(C)]` or `#[repr(i32)]`.
+- Null pointer passed where C expects non-null (and Rust wraps it in `&T`).
+- C code writing to Rust-owned memory through a pointer Rust considers immutable.
+- Forgetting to mark FFI functions as `unsafe extern "C"`.
+- longjmp/setjmp across Rust frames (unwinding UB).
+
+**Miri detection:** LIMITED — Miri cannot execute foreign code. It detects UB in the Rust-side handling of FFI return values.
+
+**Complementary tools:** AddressSanitizer (ASAN), MemorySanitizer (MSAN) for detecting actual FFI-side corruption. Valgrind as a last resort.
+
+**Fix pattern:** Validate every FFI return at the boundary. Use `Option<NonNull<T>>` for nullable pointers. Use `CStr`/`CString` for strings. Add `cbindgen` to CI to verify layout agreement. Wrap every FFI call in a safe Rust function that checks preconditions.
+
+---
+
+## 9. Incorrect `Send` / `Sync` Implementations
+
+**Root cause:** Manually implementing `Send` or `Sync` for a type that does not actually uphold the required invariant.
+
+**Canonical triggers:**
+- `unsafe impl Send for Wrapper(*mut T)` when `T` is not `Send`.
+- `unsafe impl Sync for Wrapper(UnsafeCell<T>)` without a lock, atomic, or other synchronization.
+- Types containing `Rc<T>` with a manual `Send` impl (Rc is explicitly !Send).
+
+**Miri detection:** YES for the *resulting* data race if exercised. Miri's data-race detector will fire when two threads access the same location unsynchronized.
+
+**Fix pattern:** Never manually implement `Send`/`Sync` unless you can write a SAFETY proof naming the synchronization mechanism. Use `PhantomData<*const ()>` to opt-out of auto-`Send`/`Sync` when in doubt.
+
+---
+
+## 10. Out-of-Bounds Memory Access
+
+**Root cause:** Pointer arithmetic or indexing that escapes the allocation.
+
+**Canonical triggers:**
+- `ptr.offset(n)` where `n` exceeds the allocation size.
+- `slice::from_raw_parts(ptr, len)` where `len` is too large.
+- Off-by-one in manual buffer management.
+- Integer overflow in size calculations leading to undersized allocation.
+
+**Miri detection:** YES — allocation-precise bounds checking.
+
+**Fix pattern:** Use checked arithmetic (`checked_add`, `checked_mul`) for size calculations. Use `slice::from_raw_parts` only with validated lengths. Prefer safe indexing (`get()`, iterators) over raw pointer arithmetic.
+
+---
+
+## 11. Provenance Violations
+
+**Root cause:** Using a pointer whose provenance does not grant access to the target memory, even if the address is numerically correct.
+
+**Canonical triggers:**
+- Casting an integer to a pointer and dereferencing it (`addr as *const T`).
+- Roundtripping a pointer through `usize` and back (`ptr as usize as *const T`) — the provenance is lost.
+- Using `ptr::from_exposed_addr` without a corresponding `ptr.expose_provenance()`.
+
+**Miri detection:** YES with strict provenance:
+```bash
+MIRIFLAGS="-Zmiri-strict-provenance" cargo +nightly miri test
+```
+
+**Fix pattern:** Use `ptr::with_exposed_provenance` / `ptr.expose_provenance()` for legitimate int-to-ptr roundtrips. Avoid `as usize as *const T` entirely. Use `sptr` crate for provenance-safe pointer manipulation on stable.
+
+---
+
+## 12. Double Free / Invalid Free
+
+**Root cause:** Freeing the same allocation twice, or freeing memory not obtained from the allocator.
+
+**Canonical triggers:**
+- `Box::from_raw` called twice on the same pointer.
+- Manual `dealloc` on a pointer already freed.
+- `ManuallyDrop` dropped explicitly then the outer type also drops it.
+
+**Miri detection:** YES — immediate trap.
+
+**Fix pattern:** Enforce single ownership via RAII. Use `ManuallyDrop` with extreme care — document who is responsible for the drop. Never clone a raw pointer and `Box::from_raw` both copies.
+
+---
+
+## 13. Library / Unsafe Contract Violations
+
+**Root cause:** Violating the documented safety invariant of a safe or unsafe API, where the library author relied on the invariant for soundness.
+
+**Canonical triggers:**
+- `Vec::set_len(n)` where the first `n` elements are not initialized.
+- `String::from_utf8_unchecked` on non-UTF-8 bytes.
+- `HashMap` key mutated after insertion (violates hash invariant — not UB per se, but unsound and Miri may detect downstream effects).
+- `BTreeMap` key with broken `Ord` impl (the standard library assumes a total order).
+
+**Miri detection:** DEPENDS — Miri catches the downstream UB (e.g., reading uninitialized bytes from a `Vec` with inflated len). It does not catch "you violated the documented contract" if no memory-level UB results.
+
+**Fix pattern:** Read the `# Safety` section of every `unsafe fn` you call. Document the invariant in your SAFETY comment. When in doubt, use the safe API and pay the cost.
+
+---
+
+## 14. Unwinding Across `extern "C"` Boundaries
+
+**Root cause:** A Rust panic unwinding through a frame that uses the C calling convention.
+
+**Canonical triggers:**
+- `panic!()` inside a `#[no_mangle] extern "C" fn` callback passed to C code.
+- `unwrap()` inside FFI callbacks.
+
+**Miri detection:** PARTIAL — Miri does not model foreign unwinding, but it can detect the immediate UB if the panic reaches the FFI boundary.
+
+**Fix pattern:** Use `std::panic::catch_unwind` at every FFI entry point. Mark FFI callbacks as `extern "C-unwind"` when panic propagation is intentional (nightly). Prefer returning `Result`-like error codes from FFI callbacks.
+
+---
+
+## Summary Table
+
+| # | Category | Miri Detects? | Complementary Tool |
+|---|----------|--------------|-------------------|
+| 1 | Aliasing (Stacked/Tree Borrows) | YES | — |
+| 2 | Data races | YES | loom, TSAN |
+| 3 | Use-after-free / dangling | YES | ASAN |
+| 4 | Uninitialized memory | YES | MSAN |
+| 5 | Invalid values | YES | — |
+| 6 | Misaligned access | YES | UBSAN |
+| 7 | Pin invariant violation | PARTIAL | manual review |
+| 8 | FFI boundary UB | LIMITED | ASAN, MSAN, Valgrind |
+| 9 | Incorrect Send/Sync | YES (via race) | loom |
+| 10 | Out-of-bounds access | YES | ASAN |
+| 11 | Provenance violations | YES (strict mode) | — |
+| 12 | Double free | YES | ASAN |
+| 13 | Library contract violations | PARTIAL | proptest, fuzzing |
+| 14 | Unwinding across FFI | PARTIAL | — |
+
+## Miri Coverage Assessment
+
+Miri catches categories 1-6, 9-12 with high confidence. Categories 7, 8, 13, 14 require supplementary tools or manual audit. **Miri is the single highest-leverage tool** — it should run on every PR that touches `unsafe`, and ideally on the full test suite regularly.
diff --git a/plugins/omo/skills/programming/references/rust/README.md b/plugins/omo/skills/programming/references/rust/README.md
new file mode 100644
index 00000000..d43a7559
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust/README.md
@@ -0,0 +1,317 @@
+# Rust Programmer
+
+Production Rust in 2026. **Explicit allocation, compile-time proof, zero hidden cost.** Type-state-first, unsafe-banished-by-default, agent-proof.
+
+## Identity — What Kind of Rust You Write
+
+You write Rust that looks like a Zig programmer designed it and a Rust compiler enforces it. Every allocation is visible. Every cost is explicit. Every invariant is encoded in the type system. Every cleanup is deterministic. The borrow checker, lifetime analysis, trait bounds, and `miri` then guarantee what Zig leaves to discipline.
+
+**Five pillars, every file, no exceptions:**
+
+| Pillar | Default Behavior | Reference |
+|---|---|---|
+| **Explicit allocation** | Arena for hot paths, `&[T]`/`Cow` over `Vec`/`String` in signatures, `try_*` when allocation can fail | [zero-cost-safety.md §1](zero-cost-safety.md) |
+| **Compile-time proof** | `const fn` everything const-eligible, `const { assert!(...) }` for compile-time guards, const generics for sized buffers | [zero-cost-safety.md §2](zero-cost-safety.md) |
+| **Zero hidden cost** | Slice-based APIs where caller owns memory, no hidden `.clone()`/`.to_string()`, `Cow` to defer allocation | [zero-cost-safety.md §3](zero-cost-safety.md) |
+| **Type-encoded invariants** | Newtype wrappers for every semantic unit, type-state for state machines, branded IDs | [type-state.md](type-state.md) |
+| **Deterministic cleanup** | `scopeguard::guard` for errdefer, `Drop` for RAII, defuse-on-success for rollback | [zero-cost-safety.md §5](zero-cost-safety.md) |
+
+The two highest-leverage tools Rust gives a coding agent:
+
+1. **Bounded polymorphism** (traits). Real, machine-checked, composable constraints.
+2. **Newtype-as-coordinate-space.** `Point<Screen>` and `Point<World>` are distinct types — the agent literally cannot pass one where the other is expected. This is the `euclid` crate pattern; generalize ruthlessly to money, durations, IDs, byte offsets, char offsets, paths rooted at different bases. Full patterns → [type-state.md](type-state.md).
+
+---
+
+## Hard Rules (Every `.rs` File)
+
+### 1. No `unwrap()`, No `expect()` Outside Tests
+
+```rust
+// WRONG
+let val = map.get("key").unwrap();
+
+// RIGHT — propagate or provide context
+let val = map.get("key").context("missing 'key' in config")?;
+```
+
+Typed errors for libraries ([thiserror](https://docs.rs/thiserror)), ad-hoc errors for binaries ([anyhow](https://docs.rs/anyhow) / [color-eyre](https://docs.rs/color-eyre)). Full stack → [libraries.md](libraries.md).
+
+### 2. No `unsafe` Without Miri Proof
+
+If `unsafe` is unavoidable, you have miri. Run it. Always. **Load [`../rust-ub/README.md`](../rust-ub/README.md) plus every file under [`../rust-ub/`](../rust-ub/)** for the full UB taxonomy, Miri escalation protocol (4 strictness levels), and the fix-and-prove workflow. Every `unsafe` block needs the three components from [unsafe-discipline.md](unsafe-discipline.md): safe wrapper, `// SAFETY:` comment, miri test.
+
+```bash
+cargo +nightly miri nextest run
+```
+
+### 3. Explicit Allocation — Arena by Default in Hot Paths
+
+**Do not scatter `Box::new()` / `Vec::new()` across hot loops.** Use arena allocation to make allocation scope visible and bulk-freeable. Full recipes → [zero-cost-safety.md §1](zero-cost-safety.md).
+
+```rust
+use bumpalo::Bump;
+
+fn parse_frame<'a>(arena: &'a Bump, raw: &[u8]) -> Frame<'a> {
+ let header = arena.alloc(parse_header(raw));
+ let payload = arena.alloc_slice_copy(&raw[HEADER_LEN..]);
+ Frame { header, payload }
+}
+// Caller owns arena. Caller decides when memory dies. Zero individual frees.
+```
+
+When arena is overkill (simple CLI, one-shot allocation), `Vec`/`String` are fine — but **function signatures still prefer borrows**:
+
+```rust
+// WRONG — forces caller to allocate
+fn process(input: String) -> String { ... }
+
+// RIGHT — caller chooses allocation strategy
+fn process(input: &str) -> Cow<'_, str> { ... }
+
+// BEST for hot paths — zero allocation, caller provides buffer
+fn process(input: &[u8], output: &mut [u8]) -> usize { ... }
+```
+
+### 4. Compile-Time First — const fn Everything Const-Eligible
+
+If a function CAN be `const fn`, it MUST be `const fn`. Full recipes → [zero-cost-safety.md §2](zero-cost-safety.md).
+
+```rust
+// Lookup tables computed at compile time — zero runtime cost
+const CRC_TABLE: [u32; 256] = {
+ let mut table = [0u32; 256];
+ let mut i = 0;
+ while i < 256 {
+ let mut crc = i as u32;
+ let mut j = 0;
+ while j < 8 {
+ crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB88320 } else { crc >> 1 };
+ j += 1;
+ }
+ table[i] = crc;
+ i += 1;
+ }
+ table
+};
+
+// Compile-time assertions — catch violations at build time, not runtime
+const { assert!(std::mem::size_of::<Header>() == 12, "Header must be 12 bytes") };
+```
+
+Use `const generics` for stack-allocated buffers with compile-time size:
+
+```rust
+struct RingBuffer<T, const N: usize> {
+ data: [MaybeUninit<T>; N],
+ head: usize,
+ len: usize,
+}
+```
+
+### 5. Scope Guards — Deterministic Cleanup on Every Path
+
+Zig's `errdefer` in Rust. Full recipes → [zero-cost-safety.md §5](zero-cost-safety.md).
+
+```rust
+use scopeguard::guard;
+
+fn deploy(artifact: &Path) -> Result<(), DeployError> {
+ let backup = snapshot_current()?;
+ // errdefer: restore on failure
+ let rollback = guard(backup, |b| { let _ = restore(&b); });
+
+ upload(artifact)?;
+ health_check()?;
+
+ // Success: defuse the guard
+ scopeguard::ScopeGuard::into_inner(rollback);
+ Ok(())
+}
+```
+
+### 6. Bit-Level Layout — zerocopy for Wire Formats
+
+Never hand-write `transmute` or pointer casts for parsing binary data. Full recipes → [zero-cost-safety.md §4](zero-cost-safety.md).
+
+```rust
+use zerocopy::{FromBytes, IntoBytes, KnownLayout, Immutable};
+
+#[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
+#[repr(C)]
+struct PacketHeader {
+ magic: [u8; 4],
+ version: u8,
+ flags: u8,
+ length: [u8; 2], // use byte array for packed fields, decode via from_le_bytes
+}
+```
+
+### 7. Exhaustive Match — No Wildcard on Enums You Control
+
+```rust
+// WRONG — silently ignores new variants
+match status {
+ Status::Ok => handle_ok(),
+ _ => handle_error(),
+}
+
+// RIGHT — compiler forces update when variants change
+match status {
+ Status::Ok => handle_ok(),
+ Status::NotFound => handle_not_found(),
+ Status::Timeout => handle_timeout(),
+}
+```
+
+For `#[non_exhaustive]` enums from external crates, the wildcard `_` is required — but add a `tracing::warn!` in the catch-all so you notice when new variants appear.
+
+### 8. Type-State Over Runtime Checks
+
+Never `if self.state == State::Validated`. Encode states as distinct types so the compiler refuses invalid transitions. Full patterns → [type-state.md](type-state.md).
+
+```rust
+struct Order<S: OrderState> { data: OrderData, _state: PhantomData<S> }
+struct Draft;
+struct Validated;
+struct Paid;
+
+impl Order<Draft> {
+ fn validate(self) -> Result<Order<Validated>, ValidationError> { ... }
+}
+impl Order<Validated> {
+ fn pay(self, payment: Payment) -> Result<Order<Paid>, PaymentError> { ... }
+}
+// Order<Draft> has no .pay() method. Compiler enforces the workflow.
+```
+
+---
+
+## Standard Library Defaults
+
+Full decision tree with rationale and code snippets → [libraries.md](libraries.md).
+
+| Category | Crate | Why |
+|---|---|---|
+| Async runtime | `tokio` | Ecosystem standard. Patterns → [async-tokio.md](async-tokio.md) |
+| HTTP server | `axum` + `tower` | Type-safe extractors, tower middleware. Stack → [axum-stack.md](axum-stack.md) |
+| CLI | `clap` derive + `color-eyre` | Typed args, beautiful errors. Stack → [clap-stack.md](clap-stack.md) |
+| Serialization | `serde` + `serde_json` | Non-negotiable for any boundary type |
+| Error (library) | `thiserror` | Derive `Error` with zero boilerplate |
+| Error (binary) | `anyhow` / `color-eyre` | Context-rich ad-hoc errors |
+| Database | `sqlx` (compile-time checked) | No runtime SQL surprises |
+| Arena alloc | `bumpalo` / `typed-arena` | Explicit allocation scope. Patterns → [zero-cost-safety.md §1](zero-cost-safety.md) |
+| Zero-copy parse | `zerocopy` | Safe binary parsing, no transmute. Patterns → [zero-cost-safety.md §4](zero-cost-safety.md) |
+| Scope guard | `scopeguard` | errdefer/defer. Patterns → [zero-cost-safety.md §5](zero-cost-safety.md) |
+| Stack collections | `smallvec` / `arrayvec` / `tinyvec` | Stack-first, heap-spillover. Patterns → [zero-cost-safety.md §3](zero-cost-safety.md) |
+| Bitfield | `bitfield` / `modular-bitfield` | Bit-packed flags. Patterns → [zero-cost-safety.md §4](zero-cost-safety.md) |
+| Testing | `proptest` + `insta` | Property + snapshot tests. Patterns → [proptest-insta.md](proptest-insta.md) |
+| Concurrency | `tokio::sync` / `parking_lot` | Channel-first, lock-second. Patterns → [concurrency.md](concurrency.md) |
+
+---
+
+## Cargo Strict Configuration
+
+Every new project gets the strict lint config from [cargo-strict.md](cargo-strict.md). The non-negotiable CI gate:
+
+```bash
+cargo fmt --all -- --check && \
+cargo clippy --all-targets --all-features -- -D warnings && \
+cargo nextest run && \
+cargo +nightly miri nextest run # when unsafe is involved
+```
+
+---
+
+## Code Review Checklist (Post-Write, Every PR)
+
+Run through this list after writing any Rust code. Every item links to its recipe.
+
+| # | Check | Fix Reference |
+|---|---|---|
+| 1 | Every function signature prefers `&[T]`/`&str`/`Cow` over owned types | [zero-cost-safety.md §3](zero-cost-safety.md) |
+| 2 | Hot-path allocations use arena (`bumpalo`) not scattered `Box`/`Vec` | [zero-cost-safety.md §1](zero-cost-safety.md) |
+| 3 | Const-eligible functions are `const fn` | [zero-cost-safety.md §2](zero-cost-safety.md) |
+| 4 | Lookup tables / config constants computed at compile time | [zero-cost-safety.md §2](zero-cost-safety.md) |
+| 5 | Binary format parsing uses `zerocopy`, not `transmute` | [zero-cost-safety.md §4](zero-cost-safety.md) |
+| 6 | Cleanup logic uses `scopeguard` or `Drop`, never manual `if err` cleanup | [zero-cost-safety.md §5](zero-cost-safety.md) |
+| 7 | Distinct semantic units are newtypes, not primitive aliases | [type-state.md](type-state.md) |
+| 8 | State machines use type-state, not runtime `if state ==` | [type-state.md](type-state.md) |
+| 9 | No `unwrap()`/`expect()` outside `#[cfg(test)]` | [libraries.md](libraries.md) |
+| 10 | Every `unsafe` has SAFETY comment + miri test | [unsafe-discipline.md](unsafe-discipline.md), [../rust-ub/](../rust-ub/) |
+| 11 | Match on owned enums is exhaustive (no `_ =>`) | This file §7 |
+| 12 | Clippy pedantic passes with zero warnings | [cargo-strict.md](cargo-strict.md) |
+| 13 | Property tests exist for any function with a nontrivial domain | [proptest-insta.md](proptest-insta.md) |
+| 14 | Concurrency uses channels first, locks second, atomics last | [concurrency.md](concurrency.md) |
+| 15 | Async code uses `JoinSet` for structured concurrency | [async-tokio.md](async-tokio.md) |
+
+---
+
+## Default Cargo.toml Dependencies — Zero-Cost Safety Stack
+
+Every new project starts with these alongside the standard deps from [cargo-strict.md](cargo-strict.md):
+
+```toml
+# Zero-cost safety stack
+bumpalo = { version = "3", features = ["collections"] }
+scopeguard = "1"
+smallvec = { version = "1", features = ["union", "const_generics"] }
+zerocopy = { version = "0.8", features = ["derive"] }
+
+# Add when needed:
+# typed-arena = "2" # homogeneous arena
+# arrayvec = "0.7" # fixed-capacity stack vec
+# tinyvec = { version = "1", features = ["alloc"] }
+# bitfield = "0.17" # bit-packed flags
+# modular-bitfield = "0.11" # richer bitfield API
+# bytemuck = { version = "1", features = ["derive"] }
+```
+
+---
+
+## Reference Index
+
+| File | When to Load |
+|---|---|
+| [zero-cost-safety.md](zero-cost-safety.md) | Arena, allocator, const fn, comptime, zero-alloc, bitfield, repr, scopeguard, errdefer, Zig-like patterns |
+| [type-state.md](type-state.md) | Newtype wrappers, type-state machines, branded IDs, phantom types |
+| [unsafe-discipline.md](unsafe-discipline.md) | Any `unsafe` block — SAFETY comments, safe wrappers, miri proof |
+| [libraries.md](libraries.md) | Library selection, crate decision tree, dependency audit |
+| [cargo-strict.md](cargo-strict.md) | Project bootstrap, lint config, CI gate commands |
+| [async-tokio.md](async-tokio.md) | Async runtime, spawning, cancellation, `JoinSet`, `select!` |
+| [axum-stack.md](axum-stack.md) | HTTP services — axum + sqlx + tower + tracing |
+| [clap-stack.md](clap-stack.md) | CLI tools — clap derive + color-eyre + indicatif |
+| [concurrency.md](concurrency.md) | Locks, atomics, channels, loom model checker |
+| [proptest-insta.md](proptest-insta.md) | Property tests, snapshot tests, round-trip invariants |
+| [one-liners.md](one-liners.md) | `rust-script` one-liners, disposable scripts, inline deps |
+| [../rust-ub/README.md](../rust-ub/README.md) | UB hunting — miri escalation, sanitizers, fuzzing |
+| [../rust-ub/ub-taxonomy.md](../rust-ub/ub-taxonomy.md) | 14-category UB taxonomy with detection status |
+| [../rust-ub/miri-sanitizers-loom.md](../rust-ub/miri-sanitizers-loom.md) | Miri flags, ASAN/TSAN/MSAN, loom, cargo-fuzz |
+
+---
+
+## The Shape of Every Function
+
+```rust
+/// One-line doc explaining WHAT, not HOW.
+///
+/// # Errors
+/// Returns `FooError::Bar` when the input is invalid.
+const fn frobnicate<'a>(
+ arena: &'a Bump, // explicit allocator when arena is in play
+ input: &[u8], // borrow, not owned
+ output: &mut [u8], // caller-provided buffer
+) -> Result<&'a Frob, FrobError> {
+ // ...
+}
+```
+
+**Why this shape:** the caller sees every cost. Allocation scope is the arena's lifetime. Input is borrowed. Output buffer is caller-owned. Error is typed. The compiler enforces all of it.
+
+---
+
+## Activation
+
+This skill activates whenever you are writing or modifying any `.rs` file or `Cargo.toml`. One-off scripts get the strict treatment too — `rust-script` + the same lints, the same gates. Details → [one-liners.md](one-liners.md).
+
+**The promise:** production hygiene with throwaway ergonomics. Explicit allocation, compile-time proof, zero hidden cost, and **agent-proof safety at any volume**.
diff --git a/plugins/omo/skills/programming/references/rust/async-tokio.md b/plugins/omo/skills/programming/references/rust/async-tokio.md
new file mode 100644
index 00000000..fe657045
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust/async-tokio.md
@@ -0,0 +1,299 @@
+# Async with Tokio
+
+Structured concurrency, cancellation, blocking-work isolation, channel selection. The patterns the agent should reach for by default.
+
+## Runtime selection
+
+```rust
+// Default for services and CLIs that do real work
+#[tokio::main(flavor = "multi_thread", worker_threads = 8)]
+async fn main() -> anyhow::Result<()> { ... }
+
+// For tiny CLIs or wasm where you measured single-thread is enough
+#[tokio::main(flavor = "current_thread")]
+async fn main() -> anyhow::Result<()> { ... }
+```
+
+Pick worker count explicitly. The default (`num_cpus`) is fine for servers; for desktop tools you usually want 2-4.
+
+## Spawning
+
+`tokio::spawn` returns a `JoinHandle<T>`. The future runs to completion even if the handle is dropped (detached). To enforce structured concurrency, use `JoinSet`:
+
+```rust
+use tokio::task::JoinSet;
+
+let mut set = JoinSet::new();
+for url in urls {
+ let client = client.clone();
+ set.spawn(async move { fetch(&client, &url).await });
+}
+
+let mut results = Vec::new();
+while let Some(joined) = set.join_next().await {
+ match joined {
+ Ok(Ok(body)) => results.push(body),
+ Ok(Err(error)) => tracing::warn!(%error, "fetch failed"),
+ Err(panicked) if panicked.is_panic() => {
+ tracing::error!(?panicked, "worker panicked");
+ // Choose: re-raise, or continue with degraded result set.
+ }
+ Err(other) => tracing::error!(?other, "worker join error"),
+ }
+}
+```
+
+`JoinSet`:
+- Knows when all spawned tasks finish.
+- Dropping the set aborts every still-running task.
+- Lets you handle failures one by one rather than all-or-nothing.
+
+For wait-for-all semantics with one type, `join!`:
+
+```rust
+let (a, b, c) = tokio::join!(load_a(), load_b(), load_c());
+let a = a?; let b = b?; let c = c?;
+```
+
+For first-of-many, `select!`:
+
+```rust
+tokio::select! {
+ biased; // bias to top-to-bottom checking when ordering matters
+ _ = shutdown.recv() => {
+ tracing::info!("shutdown signal");
+ return Ok(());
+ }
+ request = listener.accept() => {
+ handle_request(request?).await?;
+ }
+}
+```
+
+Without `biased`, branches are polled in random order each iteration (good for fairness). Use `biased` only when you need deterministic priority (shutdown signal first, etc).
+
+## Cancellation
+
+A future is cancelled when it is dropped (e.g., the `select!` arm wins another branch). **Always think: if this future is dropped mid-await, what state is left behind?**
+
+Cancel-safe futures (you can drop without lasting effect):
+- `recv()` on channels
+- `accept()` on listeners
+- `wait_for` on `watch::Receiver`
+- `read_buf`/`write_all` on streams **only when buffers are owned by the future**, otherwise no
+
+Cancel-unsafe futures (dropping mid-way leaves partial state):
+- Manual `read_exact` into an external buffer
+- Custom futures that perform partial side effects before suspending
+
+If a function is cancel-unsafe, document it in a rustdoc `# Cancel Safety` section.
+
+To explicitly opt out of cancellation, use `tokio_util::sync::CancellationToken`:
+
+```rust
+use tokio_util::sync::CancellationToken;
+
+let token = CancellationToken::new();
+let child = token.child_token();
+tokio::spawn(async move {
+ tokio::select! {
+ _ = child.cancelled() => { /* clean up */ }
+ result = work() => { /* normal */ }
+ }
+});
+// later
+token.cancel();
+```
+
+Pass child tokens down the call tree so the whole tree can be cancelled together.
+
+## Timeouts
+
+```rust
+use tokio::time::{timeout, Duration};
+
+match timeout(Duration::from_secs(5), fetch(url)).await {
+ Ok(Ok(body)) => Ok(body),
+ Ok(Err(error)) => Err(error.into()),
+ Err(_elapsed) => Err(anyhow::anyhow!("timed out fetching {url}")),
+}
+```
+
+Set timeouts on every external I/O boundary. Defaults of "wait forever" are bugs.
+
+## Blocking work
+
+NEVER block inside an async task. Symptoms: deadlock, every future stalled, latency cliffs.
+
+Heavy CPU or sync I/O → `spawn_blocking`:
+
+```rust
+let result = tokio::task::spawn_blocking(|| {
+ // CPU-bound: parsing, hashing, image processing
+ // Or sync I/O: rusqlite, OS APIs without async wrappers
+ expensive_pure_computation()
+}).await?;
+```
+
+Long-running blocking jobs (more than ~1 second of CPU) → use a dedicated thread pool (`rayon`), not tokio's blocking pool which is sized for short bursts.
+
+## Channels
+
+| Need | Use |
+|---|---|
+| 1-many producers → 1 consumer, async | `tokio::sync::mpsc::channel(cap)` |
+| Same as above, both sync + async | `flume::bounded(cap)` |
+| 1 → many fan-out, latest-value semantics | `tokio::sync::watch::channel(initial)` |
+| 1 → many fan-out, queued | `tokio::sync::broadcast::channel(cap)` |
+| One-shot reply | `tokio::sync::oneshot::channel()` |
+| Backpressure-driven stream of items | `tokio::sync::mpsc::Receiver` + `ReceiverStream` |
+
+Mpsc pattern:
+
+```rust
+let (tx, mut rx) = tokio::sync::mpsc::channel::<Job>(256);
+
+tokio::spawn(async move {
+ while let Some(job) = rx.recv().await {
+ if let Err(error) = process(job).await {
+ tracing::warn!(%error, "job failed");
+ }
+ }
+ tracing::info!("queue closed, shutting down worker");
+});
+
+tx.send(Job { ... }).await?; // blocks if full, applies backpressure
+```
+
+Always bound channels. Unbounded channels are a memory leak waiting to happen.
+
+## Streams
+
+`futures::Stream` is the async analogue of `Iterator`. Use it for paginated fetches, long-poll responses, file lines.
+
+```rust
+use futures::stream::{StreamExt, TryStreamExt};
+
+let urls: Vec<String> = ...;
+let bodies: Vec<String> = futures::stream::iter(urls)
+ .map(|url| async move { fetch(&url).await })
+ .buffer_unordered(8) // up to 8 in flight
+ .try_collect()
+ .await?;
+```
+
+`buffer_unordered(n)` is the throttle. Use it instead of spawning N tasks manually.
+
+For producing a stream from a channel:
+
+```rust
+use tokio_stream::wrappers::ReceiverStream;
+
+let (tx, rx) = tokio::sync::mpsc::channel::<Event>(64);
+let stream = ReceiverStream::new(rx);
+serve_sse(stream).await
+```
+
+## Graceful shutdown
+
+```rust
+use tokio::signal;
+
+async fn shutdown_signal() {
+ let ctrl_c = async { signal::ctrl_c().await.expect("ctrl_c handler") };
+ #[cfg(unix)]
+ let terminate = async {
+ signal::unix::signal(signal::unix::SignalKind::terminate())
+ .expect("install signal handler")
+ .recv()
+ .await;
+ };
+ #[cfg(not(unix))]
+ let terminate = std::future::pending::<()>();
+
+ tokio::select! {
+ _ = ctrl_c => {},
+ _ = terminate => {},
+ }
+ tracing::info!("shutdown signal received");
+}
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ let token = CancellationToken::new();
+ let server = tokio::spawn(run_server(token.child_token()));
+ shutdown_signal().await;
+ token.cancel();
+ let _ = tokio::time::timeout(Duration::from_secs(10), server).await;
+ Ok(())
+}
+```
+
+Pattern: catch signal → cancel a token shared with the server → server's `select!` arms see the cancel and exit cleanly → wait with a timeout so a hung worker can't deadlock shutdown.
+
+## Concurrency primitives
+
+- `tokio::sync::Mutex` — async mutex. Use for state shared between async tasks. **Do not hold across `.await` without thinking** (you'll serialize the whole system).
+- `tokio::sync::RwLock` — async read-write lock. Same caveat.
+- `parking_lot::Mutex` — sync mutex, faster than `std::sync::Mutex`, no poisoning. Use when the lock is held briefly and you do not need to `.await` while holding it.
+- `tokio::sync::Semaphore` — bound concurrent operations. Perfect for "max 10 in-flight HTTP requests" or "max 3 DB writers".
+
+```rust
+let sem = Arc::new(tokio::sync::Semaphore::new(10));
+for url in urls {
+ let permit = sem.clone().acquire_owned().await?;
+ tokio::spawn(async move {
+ let _permit = permit; // released on task end
+ fetch(&url).await
+ });
+}
+```
+
+## Common mistakes
+
+1. **Holding a sync mutex across `.await`.** Compiles and runs, deadlocks at scale. Solution: refactor to release before await, or use `tokio::sync::Mutex`.
+2. **Forgetting `?` on `JoinHandle`.** A panicked task returns `Err(JoinError)`; if you `.await` and ignore, panics are silently swallowed.
+3. **`tokio::spawn` instead of `JoinSet`.** Detached tasks survive past their parent, causing leaks. Default to `JoinSet` for structured concurrency.
+4. **Unbounded channels.** Always set a capacity.
+5. **`block_on` inside an async context.** Causes deadlock under `current_thread` runtime, performance cliff under `multi_thread`.
+6. **CPU-heavy work in async fn.** Move to `spawn_blocking` or `rayon`.
+7. **No timeout on external I/O.** Every `await` that touches the network or filesystem needs `tokio::time::timeout` wrapping.
+
+## Testing async code
+
+```rust
+#[tokio::test]
+async fn fetches_and_parses() {
+ let server = wiremock::MockServer::start().await;
+ wiremock::Mock::given(wiremock::matchers::method("GET"))
+ .respond_with(wiremock::ResponseTemplate::new(200).set_body_string("{\"id\":1}"))
+ .mount(&server)
+ .await;
+
+ let result = my_client::fetch(&server.uri()).await.unwrap();
+ assert_eq!(result.id, 1);
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn parallel_work() { ... }
+```
+
+For time-sensitive tests, advance virtual time:
+
+```rust
+#[tokio::test(start_paused = true)]
+async fn time_travel() {
+ let start = tokio::time::Instant::now();
+ tokio::time::sleep(Duration::from_secs(3600)).await;
+ assert!(start.elapsed() >= Duration::from_secs(3600));
+ // Real wallclock elapsed: ~0ms.
+}
+```
+
+## When NOT to use async
+
+- Single-threaded CPU-heavy code that does no I/O — plain `fn` + `rayon` is simpler and often faster.
+- Trivial scripts that do one HTTP call — `ureq` (sync) is simpler.
+- FFI heavy code where the FFI side is sync.
+
+Async pays off when you have many concurrent I/O operations or need cancellation as a first-class primitive.
diff --git a/plugins/omo/skills/programming/references/rust/axum-stack.md b/plugins/omo/skills/programming/references/rust/axum-stack.md
new file mode 100644
index 00000000..bf732a8b
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust/axum-stack.md
@@ -0,0 +1,467 @@
+# axum + sqlx + tracing + tower — HTTP API Stack
+
+The canonical production HTTP service in Rust 2026.
+
+## Cargo.toml dependencies
+
+```toml
+[dependencies]
+axum = { version = "0.8", features = ["macros", "tracing", "ws", "multipart"] }
+tokio = { version = "1", features = ["full"] }
+tower = "0.5"
+tower-http = { version = "0.6", features = [
+ "trace", "compression-gzip", "compression-br",
+ "timeout", "cors", "request-id", "sensitive-headers",
+ "limit", "set-header",
+] }
+
+# Errors / observability
+anyhow = "1"
+thiserror = "2"
+tracing = "0.1"
+tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
+color-eyre = "0.6"
+
+# Database
+sqlx = { version = "0.8", features = [
+ "runtime-tokio-rustls", "postgres", "uuid", "macros",
+ "migrate", "json",
+] }
+
+# Serialization / validation
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+validator = { version = "0.18", features = ["derive"] }
+
+# Types
+uuid = { version = "1", features = ["v4", "v7", "serde"] }
+jiff = { version = "0.1", features = ["serde"] }
+
+# Config
+config = { version = "0.14", features = ["toml", "yaml"] }
+secrecy = { version = "0.10", features = ["serde"] }
+
+# OpenAPI (optional but recommended)
+utoipa = { version = "5", features = ["axum_extras", "uuid", "chrono"] }
+utoipa-axum = "0.1"
+utoipa-swagger-ui = { version = "8", features = ["axum"] }
+```
+
+## Project structure
+
+```
+src/
+ main.rs # binary entry
+ lib.rs # re-exports + app builder
+ config.rs # Settings type + loader
+ state.rs # AppState (shared via Arc)
+ routes/
+ mod.rs # Router::new() composition
+ health.rs
+ users.rs
+ middleware/
+ mod.rs
+ auth.rs
+ request_id.rs
+ models/
+ mod.rs
+ user.rs
+ error.rs # AppError + IntoResponse impl
+ db/
+ mod.rs
+ migrations/
+migrations/ # sqlx migrations
+```
+
+## Error type
+
+```rust
+// src/error.rs
+use axum::{http::StatusCode, response::{IntoResponse, Response}, Json};
+use serde_json::json;
+
+#[derive(Debug, thiserror::Error)]
+pub enum AppError {
+ #[error("not found")]
+ NotFound,
+ #[error("unauthorized")]
+ Unauthorized,
+ #[error("validation: {0}")]
+ Validation(String),
+ #[error("conflict: {0}")]
+ Conflict(String),
+ #[error("internal")]
+ Internal(#[from] anyhow::Error),
+ #[error("database")]
+ Database(#[from] sqlx::Error),
+}
+
+impl IntoResponse for AppError {
+ fn into_response(self) -> Response {
+ let (status, code, message) = match &self {
+ AppError::NotFound => (StatusCode::NOT_FOUND, "not_found", self.to_string()),
+ AppError::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized", "unauthorized".into()),
+ AppError::Validation(m) => (StatusCode::UNPROCESSABLE_ENTITY, "validation", m.clone()),
+ AppError::Conflict(m) => (StatusCode::CONFLICT, "conflict", m.clone()),
+ AppError::Database(e) => {
+ tracing::error!(error = ?e, "database error");
+ (StatusCode::INTERNAL_SERVER_ERROR, "database", "internal".into())
+ }
+ AppError::Internal(e) => {
+ tracing::error!(error = ?e, "internal error");
+ (StatusCode::INTERNAL_SERVER_ERROR, "internal", "internal".into())
+ }
+ };
+ (status, Json(json!({"error": {"code": code, "message": message}}))).into_response()
+ }
+}
+
+pub type AppResult<T> = std::result::Result<T, AppError>;
+```
+
+Pattern: business errors return `AppResult<T>`; the `IntoResponse` impl translates them to HTTP. `sqlx::Error` and `anyhow::Error` auto-convert via `From`. Internal-bucket errors are logged but never leak their `Debug` representation to clients.
+
+## AppState
+
+```rust
+// src/state.rs
+use std::sync::Arc;
+use sqlx::PgPool;
+
+#[derive(Clone)]
+pub struct AppState {
+ pub db: PgPool,
+ pub config: Arc<crate::config::Settings>,
+ pub http: reqwest::Client,
+}
+
+impl AppState {
+ pub async fn new(config: crate::config::Settings) -> anyhow::Result<Self> {
+ let db = sqlx::postgres::PgPoolOptions::new()
+ .max_connections(config.db.max_connections)
+ .acquire_timeout(std::time::Duration::from_secs(3))
+ .connect(config.db.url.expose_secret())
+ .await?;
+ sqlx::migrate!("./migrations").run(&db).await?;
+ let http = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(15))
+ .user_agent(concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")))
+ .build()?;
+ Ok(Self { db, config: Arc::new(config), http })
+ }
+}
+```
+
+## Route handler
+
+```rust
+// src/routes/users.rs
+use axum::{
+ extract::{Path, State},
+ Json,
+};
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+use validator::Validate;
+
+use crate::{error::{AppError, AppResult}, state::AppState};
+
+#[derive(Debug, Deserialize, Validate)]
+pub struct CreateUser {
+ #[validate(email)]
+ pub email: String,
+ #[validate(length(min = 1, max = 100))]
+ pub name: String,
+}
+
+#[derive(Debug, Serialize, sqlx::FromRow)]
+pub struct User {
+ pub id: Uuid,
+ pub email: String,
+ pub name: String,
+ pub created_at: jiff::Timestamp,
+}
+
+#[tracing::instrument(skip(state, body))]
+pub async fn create_user(
+ State(state): State<AppState>,
+ Json(body): Json<CreateUser>,
+) -> AppResult<(axum::http::StatusCode, Json<User>)> {
+ body.validate().map_err(|e| AppError::Validation(e.to_string()))?;
+
+ let id = Uuid::now_v7();
+ let user = sqlx::query_as!(
+ User,
+ r#"INSERT INTO users (id, email, name, created_at)
+ VALUES ($1, $2, $3, NOW())
+ RETURNING id, email, name, created_at as "created_at: jiff::Timestamp""#,
+ id, body.email, body.name
+ )
+ .fetch_one(&state.db)
+ .await
+ .map_err(|e| match &e {
+ sqlx::Error::Database(db) if db.code().as_deref() == Some("23505") =>
+ AppError::Conflict("email already exists".into()),
+ _ => AppError::Database(e),
+ })?;
+
+ Ok((axum::http::StatusCode::CREATED, Json(user)))
+}
+
+#[tracing::instrument(skip(state))]
+pub async fn get_user(
+ State(state): State<AppState>,
+ Path(id): Path<Uuid>,
+) -> AppResult<Json<User>> {
+ sqlx::query_as!(
+ User,
+ r#"SELECT id, email, name, created_at as "created_at: jiff::Timestamp"
+ FROM users WHERE id = $1"#,
+ id
+ )
+ .fetch_optional(&state.db)
+ .await?
+ .map(Json)
+ .ok_or(AppError::NotFound)
+}
+```
+
+## Router assembly
+
+```rust
+// src/routes/mod.rs
+use axum::{routing::{get, post}, Router};
+use tower_http::{
+ compression::CompressionLayer,
+ cors::CorsLayer,
+ request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer},
+ sensitive_headers::SetSensitiveHeadersLayer,
+ timeout::TimeoutLayer,
+ trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer},
+};
+use std::time::Duration;
+use crate::state::AppState;
+
+mod health;
+mod users;
+
+pub fn router(state: AppState) -> Router {
+ let api = Router::new()
+ .route("/health", get(health::handler))
+ .route("/users", post(users::create_user))
+ .route("/users/:id", get(users::get_user))
+ .with_state(state);
+
+ Router::new()
+ .nest("/api/v1", api)
+ .layer(
+ tower::ServiceBuilder::new()
+ .layer(SetSensitiveHeadersLayer::new([
+ axum::http::header::AUTHORIZATION,
+ axum::http::header::COOKIE,
+ ]))
+ .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid))
+ .layer(
+ TraceLayer::new_for_http()
+ .make_span_with(DefaultMakeSpan::new().include_headers(false))
+ .on_response(DefaultOnResponse::new().latency_unit(tower_http::LatencyUnit::Millis)),
+ )
+ .layer(PropagateRequestIdLayer::x_request_id())
+ .layer(TimeoutLayer::new(Duration::from_secs(30)))
+ .layer(CompressionLayer::new())
+ .layer(CorsLayer::permissive()), // tighten in production
+ )
+}
+```
+
+Order matters: outermost layer wraps the request first. Trace before timeout so timeouts get logged. Compression after trace so trace sees the original body size.
+
+## Main + graceful shutdown
+
+```rust
+// src/main.rs
+use my_app::{config::Settings, routes, state::AppState};
+
+#[tokio::main]
+async fn main() -> color_eyre::Result<()> {
+ color_eyre::install()?;
+ init_tracing();
+
+ let config = Settings::load()?;
+ let state = AppState::new(config.clone()).await?;
+ let app = routes::router(state);
+
+ let listener = tokio::net::TcpListener::bind(&config.bind).await?;
+ tracing::info!(addr = %config.bind, "listening");
+
+ axum::serve(listener, app)
+ .with_graceful_shutdown(shutdown_signal())
+ .await?;
+ Ok(())
+}
+
+fn init_tracing() {
+ use tracing_subscriber::{fmt, EnvFilter};
+ let filter = EnvFilter::try_from_default_env()
+ .unwrap_or_else(|_| EnvFilter::new("info,sqlx=warn,hyper=warn,tower_http=info"));
+ fmt().with_env_filter(filter).with_target(false).json().init();
+}
+
+async fn shutdown_signal() {
+ let ctrl_c = async { tokio::signal::ctrl_c().await.expect("ctrl_c handler"); };
+ #[cfg(unix)]
+ let terminate = async {
+ tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
+ .expect("signal handler").recv().await;
+ };
+ #[cfg(not(unix))]
+ let terminate = std::future::pending::<()>();
+
+ tokio::select! { _ = ctrl_c => {}, _ = terminate => {} }
+ tracing::info!("shutting down");
+}
+```
+
+## Middleware: bearer auth example
+
+```rust
+// src/middleware/auth.rs
+use axum::{
+ extract::{Request, State},
+ http::header::AUTHORIZATION,
+ middleware::Next,
+ response::Response,
+};
+use crate::{error::AppError, state::AppState};
+
+#[derive(Clone, Debug)]
+pub struct AuthUser { pub id: uuid::Uuid }
+
+pub async fn require_auth(
+ State(state): State<AppState>,
+ mut request: Request,
+ next: Next,
+) -> Result<Response, AppError> {
+ let token = request.headers()
+ .get(AUTHORIZATION)
+ .and_then(|v| v.to_str().ok())
+ .and_then(|s| s.strip_prefix("Bearer "))
+ .ok_or(AppError::Unauthorized)?;
+
+ let claims = verify_jwt(token, &state.config.jwt_secret)?;
+ request.extensions_mut().insert(AuthUser { id: claims.sub });
+ Ok(next.run(request).await)
+}
+```
+
+Apply with `.route_layer(middleware::from_fn_with_state(state.clone(), require_auth))` on the subroutes that need it.
+
+## Testing handlers
+
+```rust
+// tests/users.rs
+#[tokio::test]
+async fn creates_user() {
+ let pool = test_db().await; // helper that spins up a transactional DB
+ let state = AppState::new_test(pool).await.unwrap();
+ let app = my_app::routes::router(state);
+
+ let request = axum::http::Request::builder()
+ .uri("/api/v1/users")
+ .method("POST")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ serde_json::to_vec(&serde_json::json!({"email": "[email protected]", "name": "A"})).unwrap()
+ )).unwrap();
+
+ let response = tower::ServiceExt::oneshot(app, request).await.unwrap();
+ assert_eq!(response.status(), 201);
+ let bytes = axum::body::to_bytes(response.into_body(), 1 << 20).await.unwrap();
+ let user: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(user["email"], "[email protected]");
+}
+```
+
+`tower::ServiceExt::oneshot` calls the router directly without binding a socket. Tests run in parallel without port collisions.
+
+## Config
+
+```rust
+// src/config.rs
+use secrecy::{Secret, ExposeSecret};
+
+#[derive(Debug, Clone, serde::Deserialize)]
+pub struct Settings {
+ pub bind: String,
+ pub db: Database,
+ pub jwt_secret: Secret<String>,
+}
+
+#[derive(Debug, Clone, serde::Deserialize)]
+pub struct Database {
+ pub url: Secret<String>,
+ pub max_connections: u32,
+}
+
+impl Settings {
+ pub fn load() -> anyhow::Result<Self> {
+ let cfg = config::Config::builder()
+ .add_source(config::File::with_name("config/default").required(false))
+ .add_source(config::File::with_name(&format!(
+ "config/{}", std::env::var("APP_ENV").unwrap_or_else(|_| "dev".into())
+ )).required(false))
+ .add_source(config::Environment::with_prefix("APP").separator("__"))
+ .build()?;
+ Ok(cfg.try_deserialize()?)
+ }
+}
+```
+
+`Secret<T>` from the `secrecy` crate hides the value in `Debug`/`Display` to prevent accidental log leakage. Access via `.expose_secret()` only where needed.
+
+## OpenAPI (optional)
+
+Add `utoipa` derive macros on your DTOs and handlers, mount Swagger UI at `/swagger-ui`:
+
+```rust
+use utoipa::OpenApi;
+use utoipa_axum::router::OpenApiRouter;
+use utoipa_swagger_ui::SwaggerUi;
+
+#[derive(OpenApi)]
+#[openapi(
+ paths(routes::users::create_user, routes::users::get_user),
+ components(schemas(routes::users::User, routes::users::CreateUser))
+)]
+struct ApiDoc;
+
+let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi())
+ .routes(utoipa_axum::routes!(routes::users::create_user, routes::users::get_user))
+ .split_for_parts();
+
+let app = router.merge(SwaggerUi::new("/swagger-ui").url("/api-docs/openapi.json", api));
+```
+
+## Production checklist
+
+- Bind to `0.0.0.0` in containers, `127.0.0.1` for local-only services.
+- Set `RUST_LOG=info,sqlx=warn` (or use `EnvFilter` defaults as shown).
+- Send logs to stdout in JSON. Ingest via Vector / Fluent Bit / Loki.
+- Run migrations on startup (`sqlx::migrate!` block). Fail fast on schema mismatch.
+- Health endpoint **must hit the DB** (so load balancers know if the pool is dead).
+- Add `tower::limit::RateLimitLayer` or token-bucket middleware for public endpoints.
+- Set `tower_http::limit::RequestBodyLimitLayer` to bound request size.
+- Compress with brotli + gzip via `CompressionLayer`.
+- Tighten CORS, do not ship `CorsLayer::permissive()` to production.
+- Strip sensitive headers from traces via `SetSensitiveHeadersLayer`.
+- Set up SIGTERM-driven `with_graceful_shutdown` so deploys roll without dropping requests.
+- Containerize with `cargo chef` for incremental Docker builds.
+
+## Common mistakes
+
+1. **Forgetting `error_for_status()?` on outbound `reqwest`** — 4xx silently succeeds.
+2. **Returning `Result<T, sqlx::Error>` from handlers** — leak DB details to clients. Always go through `AppError`.
+3. **`Json<T>` extractor before validation** — invalid JSON returns axum's default 422 with no body shape. Wrap in a `ValidatedJson<T>` extractor that runs `validator` and returns `AppError`.
+4. **Holding DB connections across `.await` on slow external calls** — exhausts the pool. Acquire late, release early.
+5. **Skipping `tracing::instrument`** on handlers — losing per-request span correlation.
+6. **No `RequestBodyLimitLayer`** — DoS surface. Default axum has no limit.
diff --git a/plugins/omo/skills/programming/references/rust/cargo-strict.md b/plugins/omo/skills/programming/references/rust/cargo-strict.md
new file mode 100644
index 00000000..ce1dd2a3
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust/cargo-strict.md
@@ -0,0 +1,317 @@
+# Cargo Strict Configuration
+
+The exact knobs every new Rust project gets. Drop these in unmodified.
+
+## `rust-toolchain.toml`
+
+```toml
+[toolchain]
+channel = "stable"
+components = ["rustfmt", "clippy", "rust-src"]
+profile = "default"
+```
+
+Pin nightly separately when miri runs:
+
+```bash
+rustup install nightly
+rustup component add miri rust-src --toolchain nightly
+```
+
+## `Cargo.toml` — `[lints]` section
+
+```toml
+[lints.rust]
+unsafe_op_in_unsafe_fn = "deny"
+missing_docs = "warn"
+missing_debug_implementations = "warn"
+unreachable_pub = "warn"
+unused_must_use = "deny"
+elided_lifetimes_in_paths = "warn"
+non_ascii_idents = "deny"
+trivial_numeric_casts = "warn"
+unused_lifetimes = "warn"
+single_use_lifetimes = "warn"
+
+[lints.clippy]
+# Groups
+all = { level = "deny", priority = -1 }
+pedantic = { level = "warn", priority = -1 }
+nursery = { level = "warn", priority = -1 }
+cargo = { level = "warn", priority = -1 }
+
+# Hard denies - turn warnings into errors for sharp tools
+undocumented_unsafe_blocks = "deny"
+multiple_unsafe_ops_per_block = "deny"
+unwrap_used = "deny"
+expect_used = "deny"
+panic = "deny"
+todo = "deny"
+unimplemented = "deny"
+unreachable = "deny"
+indexing_slicing = "deny"
+mem_forget = "deny"
+arithmetic_side_effects = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+as_underscore = "deny"
+as_ptr_cast_mut = "deny"
+ptr_as_ptr = "warn"
+borrow_as_ptr = "warn"
+fn_to_numeric_cast_any = "deny"
+clone_on_ref_ptr = "warn"
+mutex_atomic = "warn"
+rc_buffer = "warn"
+rc_mutex = "warn"
+exit = "warn"
+allow_attributes_without_reason = "warn"
+dbg_macro = "warn"
+print_stderr = "warn"
+print_stdout = "warn"
+use_debug = "warn"
+
+# Stylistic relaxations (project-wide opinions only)
+module_name_repetitions = "allow"
+must_use_candidate = "allow"
+missing_errors_doc = "allow" # we use anyhow::Result with .context() everywhere; doc rule is noisy
+
+# Restriction lints - opt-in soundness rails
+unreachable = "deny"
+mod_module_files = "warn" # prefer foo.rs over foo/mod.rs
+empty_drop = "warn"
+empty_structs_with_brackets = "warn"
+empty_enum = "warn"
+exhaustive_enums = "warn" # public enums should consider #[non_exhaustive]
+exhaustive_structs = "warn"
+```
+
+The `priority = -1` trick: group-level levels are weak; specific lints below them win. This lets us deny `unwrap_used` while still allowing `pedantic` group warnings instead of denies.
+
+## `Cargo.toml` — release profile
+
+```toml
+[profile.release]
+opt-level = 3
+lto = "fat"
+codegen-units = 1
+strip = "symbols"
+panic = "abort" # smaller, faster - if you need unwinding (FFI catch), set "unwind"
+debug = "line-tables-only"
+
+[profile.dev]
+opt-level = 0
+debug = true
+incremental = true
+codegen-units = 256
+split-debuginfo = "unpacked"
+
+# A profile for miri - opt-level 1 keeps simulation bearable while still
+# exercising real codegen patterns. miri ignores most profile keys but reads
+# overflow-checks.
+[profile.miri]
+inherits = "test"
+opt-level = 1
+overflow-checks = true
+```
+
+## `Cargo.toml` — workspace level
+
+```toml
+[workspace]
+resolver = "3"
+
+[workspace.package]
+edition = "2024"
+rust-version = "1.83" # bump only when a needed feature lands
+license = "Apache-2.0 OR MIT"
+
+[workspace.lints]
+# Then in each member crate:
+# [lints]
+# workspace = true
+```
+
+## `rustfmt.toml`
+
+```toml
+edition = "2024"
+max_width = 100
+imports_granularity = "Module"
+group_imports = "StdExternalCrate"
+reorder_imports = true
+reorder_modules = true
+newline_style = "Unix"
+use_field_init_shorthand = true
+use_try_shorthand = true
+unstable_features = false
+```
+
+Most options come from stable rustfmt. `imports_granularity` and `group_imports` are nightly-only but ignored cleanly on stable; CI runs `cargo +nightly fmt --check` for the import grouping.
+
+## `clippy.toml`
+
+```toml
+# Reduce cognitive load thresholds.
+cognitive-complexity-threshold = 25
+type-complexity-threshold = 250
+too-many-arguments-threshold = 6
+too-many-lines-threshold = 100
+
+# msrv - keeps clippy from suggesting features past our MSRV
+msrv = "1.83"
+
+# Avoid `panic` lint complaining about derived Debug impls calling unreachable_unchecked etc.
+allow-unwrap-in-tests = true
+allow-expect-in-tests = true
+allow-panic-in-tests = true
+allow-dbg-in-tests = true
+allow-print-in-tests = true
+
+# Force named arguments above N params
+single-char-binding-names-threshold = 4
+```
+
+## `deny.toml` (cargo-deny)
+
+```toml
+[advisories]
+db-path = "~/.cargo/advisory-db"
+db-urls = ["https://github.com/rustsec/advisory-db"]
+yanked = "deny"
+ignore = []
+
+[licenses]
+allow = [
+ "MIT",
+ "Apache-2.0",
+ "Apache-2.0 WITH LLVM-exception",
+ "BSD-2-Clause",
+ "BSD-3-Clause",
+ "ISC",
+ "Unicode-DFS-2016",
+ "Unicode-3.0",
+ "Zlib",
+ "MPL-2.0",
+ "CC0-1.0",
+]
+confidence-threshold = 0.93
+exceptions = []
+
+[bans]
+multiple-versions = "warn"
+wildcards = "deny"
+highlight = "all"
+deny = [
+ # Pin out unmaintained alternatives
+ { name = "async-std", reason = "use tokio" },
+ { name = "actix-web", reason = "use axum" },
+ { name = "chrono", reason = "use jiff" },
+]
+
+[sources]
+unknown-registry = "deny"
+unknown-git = "warn"
+allow-registry = ["https://github.com/rust-lang/crates.io-index"]
+```
+
+## CI Workflow (`.github/workflows/ci.yml`)
+
+```yaml
+name: ci
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+env:
+ CARGO_TERM_COLOR: always
+ RUST_BACKTRACE: 1
+
+jobs:
+ fmt:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@nightly
+ with:
+ components: rustfmt
+ - run: cargo +nightly fmt --all -- --check
+
+ clippy:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ components: clippy
+ - uses: Swatinem/rust-cache@v2
+ - run: cargo clippy --all-targets --all-features --workspace -- -D warnings
+
+ test:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ - uses: Swatinem/rust-cache@v2
+ - uses: taiki-e/install-action@nextest
+ - run: cargo nextest run --all-targets --all-features --workspace
+
+ miri:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@nightly
+ with:
+ components: miri, rust-src
+ - uses: Swatinem/rust-cache@v2
+ - uses: taiki-e/install-action@nextest
+ - env:
+ MIRIFLAGS: "-Zmiri-strict-provenance -Zmiri-symbolic-alignment-check"
+ run: cargo +nightly miri nextest run --all-features --workspace
+
+ machete:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ - uses: bnjbvr/cargo-machete@main
+
+ deny:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: EmbarkStudios/cargo-deny-action@v2
+ with:
+ command: check all
+
+ audit:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: rustsec/audit-check@v1
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+```
+
+## Project bootstrap
+
+```bash
+cargo new --bin my-app --edition 2024
+cd my-app
+cargo install cargo-nextest cargo-machete cargo-deny cargo-edit cargo-watch
+rustup install nightly
+rustup component add miri --toolchain nightly
+# drop the configs above
+git add . && git commit -m "chore: bootstrap strict toolchain"
+```
+
+After every change:
+
+```bash
+cargo fmt --all -- --check && \
+cargo clippy --all-targets --all-features -- -D warnings && \
+cargo nextest run && \
+cargo +nightly miri nextest run # only if unsafe is involved
+```
diff --git a/plugins/omo/skills/programming/references/rust/clap-stack.md b/plugins/omo/skills/programming/references/rust/clap-stack.md
new file mode 100644
index 00000000..70fa6523
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust/clap-stack.md
@@ -0,0 +1,409 @@
+# CLI Stack — clap + color-eyre + tracing + indicatif + dialoguer
+
+The default for any new CLI tool. Strict typing on arguments, beautiful errors, progress feedback, interactive prompts when needed.
+
+## Cargo.toml
+
+```toml
+[package]
+name = "mytool"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+clap = { version = "4", features = ["derive", "env", "wrap_help", "color", "unicode"] }
+clap_complete = "4"
+color-eyre = "0.6"
+tracing = "0.1"
+tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
+anyhow = "1"
+indicatif = { version = "0.17", features = ["tokio"] }
+dialoguer = { version = "0.11", features = ["fuzzy-select"] }
+console = "0.15"
+tokio = { version = "1", features = ["macros", "rt-multi-thread", "fs", "process", "signal"] }
+
+[profile.release]
+opt-level = 3
+lto = "fat"
+codegen-units = 1
+strip = "symbols"
+panic = "abort"
+```
+
+## Command structure
+
+```rust
+// src/cli.rs
+use clap::{Parser, Subcommand, ValueEnum};
+use std::path::PathBuf;
+
+#[derive(Debug, Parser)]
+#[command(
+ name = "mytool",
+ author,
+ version,
+ about = "A short description",
+ long_about = "A longer description that appears in --help",
+ arg_required_else_help = true,
+)]
+pub struct Cli {
+ /// Configuration file path
+ #[arg(short, long, env = "MYTOOL_CONFIG", default_value = "config.toml", global = true)]
+ pub config: PathBuf,
+
+ /// Increase verbosity (-v info, -vv debug, -vvv trace)
+ #[arg(short, long, action = clap::ArgAction::Count, global = true)]
+ pub verbose: u8,
+
+ /// Suppress all non-error output
+ #[arg(short, long, global = true, conflicts_with = "verbose")]
+ pub quiet: bool,
+
+ /// Force colored output even when stdout is not a terminal
+ #[arg(long, global = true, value_enum, default_value_t = ColorChoice::Auto)]
+ pub color: ColorChoice,
+
+ /// Output format
+ #[arg(short, long, global = true, value_enum, default_value_t = OutputFormat::Pretty)]
+ pub format: OutputFormat,
+
+ #[command(subcommand)]
+ pub command: Command,
+}
+
+#[derive(Debug, Clone, ValueEnum)]
+pub enum ColorChoice { Auto, Always, Never }
+
+#[derive(Debug, Clone, ValueEnum)]
+pub enum OutputFormat { Pretty, Json, Plain }
+
+#[derive(Debug, Subcommand)]
+pub enum Command {
+ /// Build the thing
+ Build(BuildArgs),
+ /// Watch and rebuild
+ Watch(WatchArgs),
+ /// Generate shell completions
+ Completions { #[arg(value_enum)] shell: clap_complete::Shell },
+}
+
+#[derive(Debug, clap::Args)]
+pub struct BuildArgs {
+ /// Target directory
+ #[arg(short, long, default_value = "target")]
+ pub target: PathBuf,
+ /// Build mode
+ #[arg(short, long, value_enum, default_value_t = Mode::Release)]
+ pub mode: Mode,
+ /// Specific files to build (default: all)
+ pub files: Vec<PathBuf>,
+}
+
+#[derive(Debug, clap::Args)]
+pub struct WatchArgs {
+ /// Glob pattern to watch
+ #[arg(short, long, default_value = "**/*.rs")]
+ pub pattern: String,
+}
+
+#[derive(Debug, Clone, ValueEnum)]
+pub enum Mode { Debug, Release }
+```
+
+Key clap derive patterns:
+
+- `env = "VAR"` — falls back to env var if flag not given.
+- `global = true` — flag inherits to subcommands.
+- `arg_required_else_help = true` — running with no args prints help instead of erroring.
+- `value_enum` on an enum — case-insensitive parsing + auto-completion.
+- `action = clap::ArgAction::Count` — `-v` is 1, `-vv` is 2, etc.
+- `conflicts_with` — incompatible flags.
+
+## Main + tracing init
+
+```rust
+// src/main.rs
+use clap::Parser;
+use mytool::cli::{Cli, Command, ColorChoice};
+use tracing::Level;
+use tracing_subscriber::EnvFilter;
+
+fn main() -> color_eyre::Result<()> {
+ color_eyre::install()?;
+ let cli = Cli::parse();
+ init_tracing(&cli);
+
+ if matches!(cli.color, ColorChoice::Always) {
+ console::set_colors_enabled(true);
+ } else if matches!(cli.color, ColorChoice::Never) {
+ console::set_colors_enabled(false);
+ }
+
+ match cli.command {
+ Command::Build(args) => mytool::commands::build::run(&cli, args),
+ Command::Watch(args) => mytool::commands::watch::run(&cli, args),
+ Command::Completions { shell } => {
+ let mut cmd = <Cli as clap::CommandFactory>::command();
+ clap_complete::generate(shell, &mut cmd, "mytool", &mut std::io::stdout());
+ Ok(())
+ }
+ }
+}
+
+fn init_tracing(cli: &Cli) {
+ let level = if cli.quiet {
+ Level::ERROR
+ } else {
+ match cli.verbose {
+ 0 => Level::WARN,
+ 1 => Level::INFO,
+ 2 => Level::DEBUG,
+ _ => Level::TRACE,
+ }
+ };
+ let filter = EnvFilter::try_from_default_env()
+ .unwrap_or_else(|_| EnvFilter::new(format!("mytool={level}")));
+ tracing_subscriber::fmt()
+ .with_env_filter(filter)
+ .with_target(false)
+ .without_time()
+ .compact()
+ .with_writer(std::io::stderr)
+ .init();
+}
+```
+
+Tracing on a CLI:
+- **Write to stderr.** stdout is for the tool's actual output (which the user might pipe). Logs and progress bars go to stderr.
+- **Verbosity from `-v`, not from `RUST_LOG`.** Users expect `-v` on a CLI; `RUST_LOG` is a developer escape hatch (kept, but secondary).
+
+## Progress bars — `indicatif`
+
+```rust
+use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
+use std::time::Duration;
+
+let mp = MultiProgress::new();
+let pb = mp.add(ProgressBar::new(files.len() as u64));
+pb.set_style(
+ ProgressStyle::with_template(
+ "{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {pos}/{len} ({eta}) {msg}"
+ )?
+ .progress_chars("=>-")
+);
+
+for file in files {
+ pb.set_message(file.display().to_string());
+ process(&file)?;
+ pb.inc(1);
+}
+pb.finish_with_message("done");
+```
+
+For unbounded operations:
+
+```rust
+let spinner = ProgressBar::new_spinner();
+spinner.enable_steady_tick(Duration::from_millis(80));
+spinner.set_message("connecting…");
+let result = connect().await?;
+spinner.finish_and_clear();
+```
+
+With multiple parallel tasks:
+
+```rust
+let mp = MultiProgress::new();
+let bars: Vec<_> = (0..workers).map(|i| {
+ let pb = mp.add(ProgressBar::new(unit));
+ pb.set_style(ProgressStyle::with_template("worker {prefix}: {pos}/{len}")?);
+ pb.set_prefix(i.to_string());
+ pb
+}).collect();
+```
+
+`MultiProgress` keeps bars stacked and redraws cleanly even with concurrent updates from multiple tasks.
+
+When stdout is not a terminal, indicatif silently disables animation. Force on/off with `pb.set_draw_target(ProgressDrawTarget::stdout())` / `hidden()`.
+
+## Interactive prompts — `dialoguer`
+
+```rust
+use dialoguer::{theme::ColorfulTheme, Confirm, Input, Password, Select, FuzzySelect, MultiSelect};
+
+let name: String = Input::with_theme(&ColorfulTheme::default())
+ .with_prompt("Project name")
+ .validate_with(|input: &String| -> Result<(), &str> {
+ if input.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') {
+ Ok(())
+ } else {
+ Err("alphanumeric, dash, underscore only")
+ }
+ })
+ .interact_text()?;
+
+let secret = Password::with_theme(&ColorfulTheme::default())
+ .with_prompt("API key")
+ .with_confirmation("Repeat", "passwords don't match")
+ .interact()?;
+
+let go: bool = Confirm::with_theme(&ColorfulTheme::default())
+ .with_prompt(format!("Delete {}? This cannot be undone.", path.display()))
+ .default(false)
+ .interact()?;
+if !go { return Ok(()); }
+
+let items = ["yes", "no", "maybe"];
+let idx = Select::with_theme(&ColorfulTheme::default())
+ .with_prompt("Pick one")
+ .items(&items)
+ .default(0)
+ .interact()?;
+
+let picks = MultiSelect::with_theme(&ColorfulTheme::default())
+ .with_prompt("Toggle features")
+ .items(&["alpha", "beta", "gamma"])
+ .defaults(&[true, false, false])
+ .interact()?;
+```
+
+Detect non-TTY before prompting:
+
+```rust
+if !console::user_attended() {
+ return Err(anyhow::anyhow!("input required but stdin is not a terminal"));
+}
+```
+
+For automated tests, expose a `--non-interactive` flag and gate all prompts behind it.
+
+## Structured output
+
+```rust
+match cli.format {
+ OutputFormat::Json => {
+ serde_json::to_writer(std::io::stdout().lock(), &result)?;
+ println!();
+ }
+ OutputFormat::Plain => {
+ for row in &result.rows {
+ println!("{}\t{}\t{}", row.a, row.b, row.c);
+ }
+ }
+ OutputFormat::Pretty => {
+ use console::{style, Term};
+ let term = Term::stdout();
+ for row in &result.rows {
+ term.write_line(&format!(
+ "{} {} {}",
+ style(&row.a).green(),
+ style(&row.b).yellow(),
+ style(&row.c).dim(),
+ ))?;
+ }
+ }
+}
+```
+
+Always offer `--format json` for piping into `jq`, scripts, and other tools.
+
+## Shell completions
+
+Already shown in the `Completions` subcommand above. Distribute completions by adding to the install script:
+
+```bash
+mytool completions bash > /etc/bash_completion.d/mytool
+mytool completions fish > ~/.config/fish/completions/mytool.fish
+mytool completions zsh > "${fpath[1]}/_mytool"
+```
+
+## Signal handling
+
+```rust
+// In an async CLI command
+use tokio::signal::ctrl_c;
+
+tokio::select! {
+ _ = ctrl_c() => {
+ tracing::warn!("interrupted, cleaning up");
+ cleanup().await?;
+ std::process::exit(130); // standard exit code for SIGINT
+ }
+ result = long_running_task() => {
+ result
+ }
+}
+```
+
+For sync CLIs, install a one-shot handler with `ctrlc` crate:
+
+```rust
+let interrupted = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+let i = interrupted.clone();
+ctrlc::set_handler(move || i.store(true, std::sync::atomic::Ordering::SeqCst))?;
+
+while !interrupted.load(std::sync::atomic::Ordering::Relaxed) {
+ do_step()?;
+}
+```
+
+## Error reporting with color-eyre
+
+```rust
+fn main() -> color_eyre::Result<()> {
+ color_eyre::config::HookBuilder::default()
+ .display_env_section(false) // hide SPANTRACE/BACKTRACE env hints by default
+ .display_location_section(false) // hide file:line section
+ .panic_section("If this is a bug, please report at https://github.com/me/mytool/issues")
+ .install()?;
+ real_main()
+}
+```
+
+Errors with `.wrap_err("...")` from `eyre::WrapErr` (compatible with anyhow's `.context`) show as a numbered chain. `RUST_BACKTRACE=1` shows the full trace; `RUST_SPANTRACE=1` shows tracing spans where the error fired.
+
+## Distribution
+
+- Add `cargo dist init` for prebuilt binary release pipeline (cross-platform tarballs + installers).
+- Publish to Homebrew tap, AUR, scoop, Chocolatey via dist.
+- Sign Linux binaries with `cosign` if your audience is enterprise.
+- Build single static binary on Linux with `--target x86_64-unknown-linux-musl` (or `aarch64-unknown-linux-musl`).
+- For wasm-runnable CLIs (`wasi-cli`), add `--target wasm32-wasip1`.
+
+## Common mistakes
+
+1. **Mixing stdout and stderr.** Tool output goes to stdout; logs and progress go to stderr.
+2. **No `--non-interactive` flag.** Interactive prompts block automation.
+3. **Printing colored output unconditionally.** Honor `NO_COLOR` env var, detect TTY with `console::user_attended()`.
+4. **`println!` for errors.** Use `tracing::error!` so logs go to stderr automatically and respect verbosity.
+5. **`unwrap()` on `Cli::parse()`.** clap returns clean errors with `--help` text; `parse()` exits on its own.
+6. **Long subcommand handlers in `main.rs`.** Split into `src/commands/<name>.rs` per command.
+7. **Missing exit code semantics.** Use `std::process::exit(1)` (general error), `2` (usage), `130` (SIGINT) appropriately. Or return `Result` and let main map.
+
+## Testing CLIs
+
+```rust
+// tests/cli.rs
+use assert_cmd::Command;
+use predicates::prelude::*;
+
+#[test]
+fn shows_help() {
+ Command::cargo_bin("mytool").unwrap()
+ .arg("--help")
+ .assert()
+ .success()
+ .stdout(predicate::str::contains("Usage:"));
+}
+
+#[test]
+fn rejects_unknown_subcommand() {
+ Command::cargo_bin("mytool").unwrap()
+ .arg("nope")
+ .assert()
+ .failure()
+ .stderr(predicate::str::contains("unrecognized subcommand"));
+}
+```
+
+`assert_cmd` builds the binary once per test run and gives a fluent assertion API.
diff --git a/plugins/omo/skills/programming/references/rust/concurrency.md b/plugins/omo/skills/programming/references/rust/concurrency.md
new file mode 100644
index 00000000..475412f7
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust/concurrency.md
@@ -0,0 +1,375 @@
+# Concurrency Primitives
+
+Locks, atomics, channels, and the loom model checker. The decision tree that keeps the agent out of soundness trouble.
+
+## The pyramid
+
+```
+Highest level tokio::sync::mpsc / broadcast / watch
+ (message passing — default for new code)
+
+ Arc<Mutex<T>> / Arc<RwLock<T>>
+ (shared mutable state — common, easy to get right)
+
+ parking_lot::{Mutex, RwLock, Condvar}
+ (faster sync locks, no poisoning)
+
+ Atomics (AtomicUsize, AtomicBool, AtomicPtr)
+ (single-word lock-free state)
+
+Lowest level UnsafeCell + unsafe + loom + miri
+ (custom lock-free / wait-free primitives)
+```
+
+**Always start at the top.** Drop a level only when you have measured a real bottleneck.
+
+## Decision tree
+
+```
+Need to share state between tasks?
+├── State is configuration (read-only after start)
+│ └── Arc<Config> (no lock needed)
+├── State is a queue of work
+│ └── tokio::sync::mpsc::channel(cap)
+├── State is "latest value" published to many readers
+│ └── tokio::sync::watch::channel(initial)
+├── State is broadcast (every consumer sees every value)
+│ └── tokio::sync::broadcast::channel(cap)
+├── State is request-response within one task tree
+│ └── tokio::sync::oneshot::channel()
+├── State is a counter
+│ └── AtomicU64 (or AtomicUsize)
+├── State is a flag / set-once
+│ └── AtomicBool / OnceLock<T> / OnceCell<T>
+├── State needs mutation across many tasks/threads, cheap critical sections
+│ ├── async context → tokio::sync::Mutex<T>
+│ └── sync context (no .await held) → parking_lot::Mutex<T>
+├── State needs mutation, many readers, few writers
+│ ├── async context → tokio::sync::RwLock<T>
+│ └── sync context → parking_lot::RwLock<T>
+└── State is a custom lock-free primitive (channels, hazard pointers)
+ └── UnsafeCell + atomics + loom-tested + miri-tested + a co-author
+```
+
+## Atomics — when and how
+
+Use atomics for:
+- Counters incremented from many threads (`AtomicU64`).
+- Single-shot flags (`AtomicBool`).
+- Pointer publication (`AtomicPtr<T>`).
+
+### Memory orderings
+
+```rust
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+let c = AtomicUsize::new(0);
+
+// Just need a count, no synchronization with other data
+c.fetch_add(1, Ordering::Relaxed);
+
+// Reading a counter that was incremented from elsewhere
+let n = c.load(Ordering::Relaxed);
+```
+
+| Ordering | When |
+|---|---|
+| `Relaxed` | Standalone counters, no other memory needs to be synchronized. |
+| `Acquire` (loads) / `Release` (stores) | Publish/consume pattern: you write some data then release a flag, readers acquire the flag then read the data. |
+| `AcqRel` | RMW that both reads-and-publishes (e.g., `fetch_add` on a sequence number). |
+| `SeqCst` | Total ordering across all `SeqCst` ops. Strongest, slowest. Use when in doubt and switch to a weaker ordering after testing under loom. |
+
+**Default to `SeqCst` if unsure.** Performance difference is usually negligible. Going weaker requires loom.
+
+### Publish-then-load pattern
+
+```rust
+static READY: AtomicBool = AtomicBool::new(false);
+static mut DATA: Option<Config> = None;
+
+// Producer thread:
+unsafe { DATA = Some(load_config()); }
+READY.store(true, Ordering::Release);
+
+// Consumer thread:
+if READY.load(Ordering::Acquire) {
+ // SAFETY: producer's Release pairs with our Acquire; if we see READY=true,
+ // we are guaranteed to also see the DATA write that happened-before it.
+ let cfg = unsafe { DATA.as_ref().unwrap() };
+}
+```
+
+This is the canonical Release/Acquire pattern. **Use `OnceLock<Config>` instead** in new code — it encapsulates exactly this with safe API.
+
+## Std vs parking_lot vs tokio for locks
+
+| | std::sync::Mutex | parking_lot::Mutex | tokio::sync::Mutex |
+|---|---|---|---|
+| Speed | Slowest (OS futex direct) | Fastest (smarter parking) | Slow (await-aware) |
+| Poisoning | Yes (`PoisonError`) | No | No |
+| Hold across `.await` | Dangerous (deadlock under current-thread runtime) | Dangerous | Safe |
+| Drop guard releases | Yes | Yes | Yes |
+| RAII | Yes (`MutexGuard`) | Yes | Yes |
+| Const constructor | Yes (since 1.63) | Yes | No |
+| Async | No | No | Yes |
+
+**Rule of thumb:**
+
+- Hot, short critical section, no await inside → `parking_lot::Mutex`.
+- Shared state held across `.await` → `tokio::sync::Mutex`.
+- Static init / app config → `OnceLock` or `LazyLock`.
+- Avoid `std::sync::Mutex` for new code; the poisoning behavior is more annoying than useful and `parking_lot` is strictly faster.
+
+### Common deadlock — async + sync mutex
+
+```rust
+let m = std::sync::Mutex::new(0u64);
+let guard = m.lock().unwrap();
+something_async().await; // ❌ guard is held across await
+*guard += 1;
+```
+
+Under `current_thread` runtime this deadlocks (the future suspends while holding the lock; another future on the same thread tries to acquire, blocks the executor). Under `multi_thread` it works but serializes the system.
+
+Fix:
+
+```rust
+{
+ let mut guard = m.lock().unwrap();
+ *guard += 1;
+} // guard released
+something_async().await;
+```
+
+Or switch to `tokio::sync::Mutex` whose guard is `Send` across awaits.
+
+## Channels
+
+### Mpsc — the workhorse
+
+```rust
+let (tx, mut rx) = tokio::sync::mpsc::channel::<Job>(256);
+
+tokio::spawn(async move {
+ while let Some(job) = rx.recv().await {
+ process(job).await;
+ }
+});
+
+tx.send(Job::new()).await?; // backpressure: awaits if full
+```
+
+Capacity is the backpressure budget. **Never `unbounded_channel()`** unless you have a hard upper bound elsewhere; otherwise it is a slow-leak memory bomb.
+
+### Watch — latest-value pubsub
+
+```rust
+let (tx, mut rx) = tokio::sync::watch::channel(Config::default());
+
+// Producer:
+tx.send(new_config)?;
+
+// Consumer:
+loop {
+ rx.changed().await?;
+ let cfg = rx.borrow();
+ apply(&cfg);
+}
+```
+
+Receivers see only the latest value (older updates are dropped). Perfect for config reload, leadership changes, "current time" propagation.
+
+### Broadcast — fanout queue
+
+```rust
+let (tx, _) = tokio::sync::broadcast::channel::<Event>(1024);
+let mut rx1 = tx.subscribe();
+let mut rx2 = tx.subscribe();
+
+while let Ok(event) = rx1.recv().await {
+ // ...
+}
+```
+
+Each subscriber has its own buffer. If a subscriber falls behind by more than the buffer size, it gets `RecvError::Lagged(n)` and skips messages. Decide explicitly: log + continue, or drop the subscriber and reconnect.
+
+### Oneshot — single value
+
+```rust
+let (tx, rx) = tokio::sync::oneshot::channel::<Response>();
+worker.send(Request { reply: tx }).await?;
+let response = rx.await?;
+```
+
+The standard request/response pattern over an actor.
+
+## Semaphores
+
+Bound concurrent operations:
+
+```rust
+let sem = Arc::new(tokio::sync::Semaphore::new(10));
+
+for task in tasks {
+ let permit = sem.clone().acquire_owned().await?;
+ tokio::spawn(async move {
+ let _hold = permit; // released when task exits
+ process(task).await
+ });
+}
+```
+
+Use cases:
+- "Max 10 outbound HTTP requests in flight."
+- "Max 3 DB connections doing writes."
+- "Max N tokio tasks running heavy CPU."
+
+A semaphore with `permits=1` is a mutex. Use the actual `Mutex` for that — clearer intent.
+
+## Arc and Rc
+
+`Arc<T>` for cross-thread shared ownership, `Rc<T>` for single-thread (never spans threads).
+
+```rust
+let shared = Arc::new(BigData::new());
+for _ in 0..workers {
+ let s = shared.clone();
+ tokio::spawn(async move { use_data(&s).await });
+}
+```
+
+`Arc::clone(&s)` is just a reference-count increment; the data is not copied.
+
+**Do not clone in hot loops** if you can pass a reference. `&Arc<T>` is fine to pass; only call `Arc::clone` when you need to move ownership across a thread/task boundary.
+
+`Weak<T>` for back-references in graphs / parent pointers to avoid cycles.
+
+## Once-init primitives
+
+```rust
+use std::sync::{OnceLock, LazyLock};
+
+// Lazy initialization, computed on first read
+static CONFIG: LazyLock<Config> = LazyLock::new(|| Config::load_from_env().unwrap());
+
+fn get_config() -> &'static Config {
+ &CONFIG
+}
+
+// One-shot publication, set explicitly
+static DB: OnceLock<sqlx::PgPool> = OnceLock::new();
+
+#[tokio::main]
+async fn main() {
+ let pool = sqlx::PgPool::connect(&env_url()).await.unwrap();
+ DB.set(pool).expect("only set once");
+ // Now everywhere: DB.get().unwrap()
+}
+```
+
+`OnceLock` is `std::sync` and stable. `LazyLock` is in `std::sync` since 1.80. Avoid the older `once_cell` crate for new code.
+
+## Loom — model-checking lock-free code
+
+When `unsafe` participates in a concurrent algorithm, miri's single-thread model is insufficient. Loom exhaustively explores thread interleavings.
+
+`Cargo.toml`:
+
+```toml
+[target.'cfg(loom)'.dev-dependencies]
+loom = "0.7"
+```
+
+In code, switch between real and loom primitives:
+
+```rust
+#[cfg(loom)]
+use loom::sync::atomic::{AtomicUsize, Ordering};
+#[cfg(not(loom))]
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+#[cfg(loom)]
+use loom::sync::Arc;
+#[cfg(not(loom))]
+use std::sync::Arc;
+```
+
+Write a test:
+
+```rust
+#[cfg(loom)]
+mod loom_tests {
+ use super::*;
+ use loom::thread;
+
+ #[test]
+ fn concurrent_push_pop_preserves_order() {
+ loom::model(|| {
+ let queue = Arc::new(MyQueue::new());
+ let q1 = queue.clone();
+ let q2 = queue.clone();
+ let h1 = thread::spawn(move || q1.push(1));
+ let h2 = thread::spawn(move || q2.pop());
+ h1.join().unwrap();
+ h2.join().unwrap();
+ // Assert the invariant: queue is in a coherent state.
+ });
+ }
+}
+```
+
+Run:
+
+```bash
+RUSTFLAGS="--cfg loom" cargo test --release -- --test-threads 1
+```
+
+Loom explores every legal scheduling of the threads, including those a real scheduler would rarely produce. If your code has a race, loom will find it deterministically.
+
+### Loom's limits
+
+- Slow. Each `loom::model` invocation explores many schedules; keep tests tiny (2-3 threads, a few operations each).
+- Single-machine only. Doesn't model distributed systems.
+- Doesn't catch UB inside `unsafe` blocks the way miri does. **Run both: miri for memory safety, loom for thread schedules.**
+- Doesn't handle `tokio` directly. Loom replaces stdlib's sync primitives; tokio's are independent.
+
+## Send and Sync — what they mean
+
+- `T: Send` — `T` can be moved between threads safely.
+- `T: Sync` — `&T` can be shared between threads safely.
+
+These are auto-derived for composite types if all components implement them. Manual `unsafe impl Send/Sync` is required only for raw pointer types and FFI handles.
+
+```rust
+struct MyHandle { raw: *mut FfiObject }
+
+// SAFETY: FfiObject's documented contract states that move-between-threads
+// is safe as long as concurrent use is externally synchronized. We do not
+// implement Sync because the FFI object is single-threaded once obtained.
+unsafe impl Send for MyHandle {}
+// Do NOT impl Sync — the FFI is not thread-safe.
+```
+
+When the compiler complains that "T: Send is not satisfied", the cause is usually a raw pointer, an `Rc` (not `Arc`), or a `RefCell` (use `Mutex`).
+
+## Common mistakes
+
+1. **Holding a `std::sync::Mutex` guard across `.await`.** Compiles, deadlocks at runtime under `current_thread`.
+2. **`Arc::clone` in a tight loop.** Refcount bump is cheap but not free; pass `&Arc<T>` when possible.
+3. **`Mutex<HashMap<K, V>>` for hot reads.** Switch to `RwLock` or `Arc<dashmap::DashMap>`.
+4. **Atomic operations with `Ordering::Relaxed` for happens-before publication.** You need `Release`/`Acquire`. Run under loom to be sure.
+5. **Unbounded channels.** Always set capacity. If you "know it won't backlog", you don't, and it will.
+6. **Spawning detached tokio tasks for fire-and-forget cleanup.** Use `JoinSet` so panics surface.
+7. **`std::mem::transmute` to fake `Send`/`Sync`.** Use `unsafe impl` with a SAFETY comment instead. Transmute breaks Stacked Borrows and miri.
+8. **Locking order inversion across two mutexes.** Always acquire in a globally consistent order. For more than three locks, switch to a single mutex around a struct.
+
+## When to escape to lock-free
+
+You should reach for atomics + `UnsafeCell` only when:
+1. The hot path is **measured** to be bottlenecked on lock contention.
+2. There is no existing library (crossbeam, atomic-queue, hazardous) that solves your problem.
+3. You can write loom tests that pass.
+4. You can write miri tests that pass.
+5. You have at least one other engineer who can review the algorithm.
+
+Practically all "I want to write a lock-free queue" projects fail (3) or (4). When in doubt, take the lock and move on.
diff --git a/plugins/omo/skills/programming/references/rust/libraries.md b/plugins/omo/skills/programming/references/rust/libraries.md
new file mode 100644
index 00000000..4124b9d6
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust/libraries.md
@@ -0,0 +1,439 @@
+# Library Defaults — Full Decision Tree
+
+The opinionated, audited-in-prod stack for 2026 Rust. Every entry has a one-line rationale and a canonical code snippet so the agent does not have to relearn each library's idioms.
+
+## Async runtime — `tokio`
+
+The default. Use `tokio` for new work. Multi-thread runtime unless you have a measured reason to go single-thread.
+
+```rust
+#[tokio::main(flavor = "multi_thread", worker_threads = 8)]
+async fn main() -> anyhow::Result<()> {
+ tracing_subscriber::fmt::init();
+ run().await
+}
+```
+
+Avoid:
+- `async-std` — unmaintained, last release ages ago. crates.io download counts are misleading because of historical inertia.
+- `smol` — fine for embedded-ish niches; outside that, the ecosystem is on tokio.
+- Mixing runtimes in one binary. Pick one and stay.
+
+## Errors — `anyhow` (apps) + `thiserror` (libs)
+
+Application boundaries get `anyhow::Error` with `.context("...")` at every layer that adds meaning. Libraries expose `#[derive(thiserror::Error)]` enums with `#[non_exhaustive]`.
+
+```rust
+// Application code
+use anyhow::Context as _;
+
+pub async fn load_config(path: &Path) -> anyhow::Result<Config> {
+ let text = tokio::fs::read_to_string(path)
+ .await
+ .with_context(|| format!("reading config from {}", path.display()))?;
+ let cfg: Config = toml::from_str(&text)
+ .with_context(|| format!("parsing config at {}", path.display()))?;
+ Ok(cfg)
+}
+
+// Library code
+#[derive(Debug, thiserror::Error)]
+#[non_exhaustive]
+pub enum ParseError {
+ #[error("expected {expected}, found {found} at position {position}")]
+ Mismatch { expected: &'static str, found: String, position: usize },
+ #[error("unexpected end of input after {context}")]
+ UnexpectedEof { context: &'static str },
+ #[error(transparent)]
+ Io(#[from] std::io::Error),
+}
+```
+
+`#[non_exhaustive]` on enums prevents downstream `match` from breaking when you add variants. `#[error(transparent)]` on a wrapper variant forwards Display + cause to the inner error.
+
+## CLI — `clap` with derive
+
+```rust
+use clap::{Parser, Subcommand};
+
+#[derive(Parser, Debug)]
+#[command(author, version, about, long_about = None)]
+struct Cli {
+ /// Path to the config file
+ #[arg(short, long, env = "MYAPP_CONFIG", default_value = "config.toml")]
+ config: PathBuf,
+
+ /// Enable verbose output (-v, -vv, -vvv)
+ #[arg(short, long, action = clap::ArgAction::Count)]
+ verbose: u8,
+
+ #[command(subcommand)]
+ command: Command,
+}
+
+#[derive(Subcommand, Debug)]
+enum Command {
+ /// Run the server
+ Serve {
+ #[arg(short, long, default_value_t = 8080)]
+ port: u16,
+ },
+ /// Migrate the database
+ Migrate {
+ #[arg(long)]
+ dry_run: bool,
+ },
+}
+```
+
+Avoid `structopt` (deprecated, merged into clap), `argh` (less ergonomic), `pico-args` (only when binary size matters more than DX).
+
+## Logging — `tracing` + `tracing-subscriber`
+
+Not `log` + `env_logger`. `tracing` supports spans (structured context that follows async tasks) and structured fields - `log` cannot.
+
+```rust
+use tracing::{info, instrument, warn, Level};
+use tracing_subscriber::{fmt, EnvFilter};
+
+fn init_tracing() {
+ let filter = EnvFilter::try_from_default_env()
+ .unwrap_or_else(|_| EnvFilter::new("info,sqlx=warn,hyper=warn"));
+ fmt()
+ .with_env_filter(filter)
+ .with_target(false)
+ .with_thread_ids(true)
+ .with_line_number(true)
+ .compact()
+ .init();
+}
+
+#[instrument(skip(db), fields(user_id = %user.id))]
+async fn process_user(db: &Pool, user: &User) -> anyhow::Result<()> {
+ info!("processing user");
+ if user.is_banned() {
+ warn!(reason = "banned", "skipping");
+ return Ok(());
+ }
+ // ... body ...
+ Ok(())
+}
+```
+
+Replace `println!` with `info!`/`warn!`/`error!`. Replace `eprintln!` with `tracing::error!`.
+
+## Error reporting (binaries) — `color-eyre`
+
+For binary `main()`, hook `color-eyre` to give pretty panics + nice `Result` printing:
+
+```rust
+fn main() -> color_eyre::Result<()> {
+ color_eyre::install()?;
+ tracing_subscriber::fmt::init();
+ real_main()
+}
+```
+
+Library code stays on `anyhow`/`thiserror`. `color-eyre` is purely a display layer for the binary.
+
+## Serialization — `serde` + `serde_json`
+
+The default for any data crossing a process boundary (file, network, IPC, database column).
+
+```rust
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(deny_unknown_fields, rename_all = "snake_case")]
+pub struct ApiResponse {
+ pub user_id: UserId,
+ pub created_at: jiff::Timestamp,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub display_name: Option<String>,
+ #[serde(flatten)]
+ pub extra: HashMap<String, serde_json::Value>,
+}
+```
+
+`deny_unknown_fields` catches typos in inputs. `rename_all = "snake_case"` aligns with REST/JSON conventions while keeping idiomatic Rust field names. `#[serde(flatten)]` for forward-compatible extra fields.
+
+Alternatives:
+- `serde_yaml` (YAML — note: YAML's "deserialize anything" surface is a security trap; prefer JSON/TOML where possible)
+- `toml` (config files)
+- `rmp-serde` (MessagePack — binary, fast)
+- `ciborium` (CBOR)
+- `bincode 2` (binary, smaller; no serde required in v2 but interop fine)
+
+## HTTP client — `reqwest`
+
+```rust
+let client = reqwest::Client::builder()
+ .timeout(std::time::Duration::from_secs(30))
+ .user_agent(concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")))
+ .https_only(true)
+ .pool_max_idle_per_host(8)
+ .build()?;
+
+#[derive(serde::Deserialize)]
+struct Repo { full_name: String, stargazers_count: u64 }
+
+let repo: Repo = client
+ .get("https://api.github.com/repos/rust-lang/rust")
+ .send().await?
+ .error_for_status()?
+ .json().await?;
+```
+
+`error_for_status()?` turns 4xx/5xx into `Err`. Always include a User-Agent. `https_only(true)` is a soundness toggle - prevents accidental http:// downgrade.
+
+## Web framework — `axum`
+
+```rust
+use axum::{Router, routing::get, extract::State, response::Json};
+use std::sync::Arc;
+
+#[derive(Clone)]
+struct AppState { db: sqlx::PgPool }
+
+async fn health(State(state): State<Arc<AppState>>) -> Json<serde_json::Value> {
+ let ok = sqlx::query_scalar!("SELECT 1::int4").fetch_one(&state.db).await.is_ok();
+ Json(serde_json::json!({ "ok": ok }))
+}
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ tracing_subscriber::fmt::init();
+ let state = Arc::new(AppState { db: sqlx::PgPool::connect(&env_db()).await? });
+ let app = Router::new()
+ .route("/health", get(health))
+ .with_state(state)
+ .layer(tower_http::trace::TraceLayer::new_for_http())
+ .layer(tower_http::compression::CompressionLayer::new());
+ let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
+ axum::serve(listener, app).await?;
+ Ok(())
+}
+```
+
+Avoid `actix-web` (legacy patterns, separate runtime model), `warp` (filter explosion in non-trivial apps), `rocket` (slow release cadence). Pair `axum` with `tower-http` for middleware (trace, compression, CORS, timeout, request-id).
+
+## Database — `sqlx` (compile-time checked SQL)
+
+```rust
+use sqlx::PgPool;
+
+#[derive(Debug, sqlx::FromRow)]
+pub struct User { pub id: uuid::Uuid, pub email: String, pub created_at: jiff::Timestamp }
+
+pub async fn find_user(pool: &PgPool, email: &str) -> Result<Option<User>, sqlx::Error> {
+ sqlx::query_as!(
+ User,
+ r#"SELECT id, email, created_at as "created_at: jiff::Timestamp"
+ FROM users WHERE email = $1"#,
+ email
+ )
+ .fetch_optional(pool)
+ .await
+}
+```
+
+`query_as!` checks the SQL against the live database at compile time. To work without a live DB during builds, generate offline metadata: `cargo sqlx prepare`. Commit the resulting `.sqlx/` directory.
+
+Avoid `diesel` (sync-first, heavy DSL), raw `tokio-postgres` (loses type checks), `sea-orm` (more magic, less control).
+
+For migrations: `sqlx migrate add <name>` + `sqlx::migrate!("./migrations").run(&pool).await?`.
+
+## Time — `jiff`
+
+The 2025+ choice. Single crate, sane defaults, civil time / instant / span distinction.
+
+```rust
+use jiff::{Timestamp, Span, ToSpan, Zoned};
+
+let now: Timestamp = Timestamp::now();
+let in_one_hour = now.checked_add(1.hour())?;
+let local: Zoned = now.in_tz("Asia/Seoul")?;
+let span: Span = local - some_earlier.in_tz("Asia/Seoul")?;
+```
+
+Avoid `chrono` (old API, generic-heavy, time zone story still painful), `time` crate (split ecosystem, weaker docs). `jiff` is the post-`chrono` consolidation.
+
+## UUID — `uuid` with v7
+
+```rust
+use uuid::Uuid;
+
+// v7 for IDs (sortable, time-ordered, monotonic-ish, RFC 9562)
+let id = Uuid::now_v7();
+```
+
+v4 is fine for nonces, v7 for primary keys (better index locality). Never v1 (leaks MAC). Cargo features: `uuid = { version = "1", features = ["v4", "v7", "serde"] }`.
+
+## DataFrames / analytics — `polars`
+
+For columnar data, joins, group-by, lazy plans:
+
+```rust
+use polars::prelude::*;
+
+let df = LazyCsvReader::new("events.csv")
+ .finish()?
+ .group_by([col("user_id")])
+ .agg([col("amount").sum().alias("total")])
+ .sort(["total"], Default::default())
+ .collect()?;
+```
+
+The Rust API mirrors the Python one. Use the lazy API by default; materialize with `.collect()` at the end.
+
+## Channels
+
+- Single-producer single-consumer or bounded MPSC → `tokio::sync::mpsc` (async) or `flume` (sync + async).
+- Broadcast → `tokio::sync::broadcast`.
+- Watch (latest-value pubsub) → `tokio::sync::watch`.
+- Oneshot → `tokio::sync::oneshot`.
+
+Avoid raw `std::sync::mpsc` (sync only, fewer features), `crossbeam-channel` (good but heavier; use only if you need rendezvous semantics).
+
+## Coordinate spaces / 2D math — `euclid`
+
+```rust
+use euclid::{Point2D, Size2D, default::Box2D};
+struct ScreenSpace;
+struct WorldSpace;
+
+type ScreenPoint = Point2D<f32, ScreenSpace>;
+type WorldPoint = Point2D<f32, WorldSpace>;
+
+let cursor: ScreenPoint = Point2D::new(120.0, 240.0);
+let player: WorldPoint = Point2D::new(3.5, 1.2);
+
+// let mistake = cursor + player; // ❌ type error
+```
+
+Generalize the pattern to your own domains (see `references/type-state.md`).
+
+## Property tests — `proptest`
+
+```rust
+use proptest::prelude::*;
+
+proptest! {
+ #[test]
+ fn parse_roundtrips(s in r"[a-zA-Z0-9_-]{1,50}") {
+ let parsed = parse(&s).unwrap();
+ let back = parsed.to_string();
+ prop_assert_eq!(back, s);
+ }
+}
+```
+
+Avoid `quickcheck` (older, less ergonomic). proptest gives shrinking + regression corpus + integration with `criterion`.
+
+## Snapshot tests — `insta`
+
+```rust
+#[test]
+fn renders_help() {
+ let output = render(&example_input());
+ insta::assert_snapshot!(output);
+}
+
+#[test]
+fn serializes_well() {
+ insta::assert_json_snapshot!(serializable_value());
+}
+```
+
+`cargo insta review` (after `cargo install cargo-insta`) — interactive review of changed snapshots.
+
+## Benchmarks — `criterion`
+
+Stable Rust friendly (no nightly `#[bench]`).
+
+```rust
+use criterion::{black_box, criterion_group, criterion_main, Criterion};
+
+fn bench_parse(c: &mut Criterion) {
+ let input = std::fs::read_to_string("samples/large.txt").unwrap();
+ c.bench_function("parse_large", |b| b.iter(|| parse(black_box(&input))));
+}
+
+criterion_group!(benches, bench_parse);
+criterion_main!(benches);
+```
+
+Run with `cargo bench`. HTML reports under `target/criterion/`. Pair with `cargo bench -- --save-baseline main` then `--baseline main` for comparison.
+
+## Concurrency model — `loom`
+
+For lock-free or atomic-heavy code (channels, refcounts, hazard pointers). See `references/concurrency.md` for the full pattern.
+
+## Arena allocator — `bumpalo`
+
+```rust
+use bumpalo::Bump;
+
+let bump = Bump::new();
+let node = bump.alloc(Node { value: 42, next: None });
+let s: &str = bump.alloc_str("hello");
+// All allocations freed at once when `bump` drops.
+```
+
+For parser nodes, AST construction, per-request scratch. Outperforms heap allocation for short-lived owned data by an order of magnitude.
+
+## Web client (browser, WASM-bound) — `gloo` ecosystem
+
+If targeting WASM browser, use `gloo-net` for fetch and `gloo-storage` for localStorage; not `web-sys` directly unless you need DOM-level APIs.
+
+## Lazy statics — `std::sync::LazyLock` (since 1.80)
+
+```rust
+use std::sync::LazyLock;
+static CONFIG: LazyLock<Config> = LazyLock::new(|| Config::load_from_env().unwrap());
+```
+
+Avoid `lazy_static!` (macro-heavy, predates std), `once_cell` (now in std as `LazyLock`/`OnceLock`).
+
+## Hash maps — `std::collections::HashMap` + `ahash` for hot paths
+
+```rust
+use std::collections::HashMap;
+use ahash::RandomState;
+
+type FastMap<K, V> = HashMap<K, V, RandomState>;
+let mut counters: FastMap<String, u64> = FastMap::default();
+```
+
+`HashMap` defaults to SipHash (DoS-resistant). For internal hot loops where you trust the keys, `ahash` is 2-5x faster.
+
+For sorted iteration, use `BTreeMap`. For small keys with known small N, `Vec<(K, V)>` may beat both.
+
+## File I/O — `tokio::fs` (async) or `std::fs` (sync utility)
+
+```rust
+let contents = tokio::fs::read_to_string("data.json").await?;
+```
+
+For large files: `tokio::fs::File` + `tokio::io::BufReader`. For random access, `memmap2` (with the unsafe-discipline wrappers).
+
+## Decision tree
+
+```
+Need to ship the thing?
+├── HTTP server → axum + sqlx + tracing + jiff + tokio
+├── HTTP client → reqwest (+ tokio)
+├── CLI → clap + color-eyre + tracing + indicatif (progress) + dialoguer (prompts)
+├── TUI → ratatui + crossterm
+├── Background worker → tokio + ETL → polars + duckdb
+├── Game / graphics → wgpu + winit + euclid (or bevy if you want the engine)
+├── WASM front-end → leptos (or dioxus / yew) + wasm-bindgen + gloo
+├── Embedded → embassy (async on bare metal)
+├── FFI to C / Python → cxx (C++) / pyo3 (Python) / cbindgen (header gen)
+└── Just a script → rust-script (see one-liners.md)
+```
+
+When in doubt, search crates.io for the latest version, then check:
+1. Is it maintained? (`cargo deny check` will scream if it's yanked or unmaintained)
+2. Does it have `serde` feature? (boundary types should always serde)
+3. Does it have `tokio` integration? (avoid runtime mixing)
+4. Is it on `tokio::io::AsyncRead`/`AsyncWrite` (the std for async I/O)?
+5. Are there safety-critical `unsafe` regions? If yes, has the author shipped miri proofs?
diff --git a/plugins/omo/skills/programming/references/rust/one-liners.md b/plugins/omo/skills/programming/references/rust/one-liners.md
new file mode 100644
index 00000000..c2edd4ba
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust/one-liners.md
@@ -0,0 +1,291 @@
+# One-Liners and Disposable Scripts
+
+Production hygiene with throwaway ergonomics. Rust scripts get the same strict lints, the same miri rule when `unsafe` is touched, the same type discipline. The difference is dependency declaration lives inline.
+
+## `rust-script` — the recommended path
+
+Install once:
+
+```bash
+cargo install rust-script
+```
+
+Write a script:
+
+```rust
+#!/usr/bin/env rust-script
+//! Fetch a URL and print its body length.
+//!
+//! Usage:
+//! ./fetch.rs <url>
+//!
+//! ```cargo
+//! [dependencies]
+//! anyhow = "1"
+//! reqwest = { version = "0.12", features = ["blocking"] }
+//! ```
+
+use std::env;
+
+fn main() -> anyhow::Result<()> {
+ let url = env::args().nth(1).context("usage: fetch.rs <url>")?;
+ let body = reqwest::blocking::get(&url)?.error_for_status()?.text()?;
+ println!("{} bytes", body.len());
+ Ok(())
+}
+```
+
+Make executable: `chmod +x fetch.rs`. Run: `./fetch.rs https://example.com`.
+
+The `//! \`\`\`cargo` block is parsed as inline `Cargo.toml`. Everything else is normal Rust.
+
+## With async
+
+```rust
+#!/usr/bin/env rust-script
+//! ```cargo
+//! [dependencies]
+//! anyhow = "1"
+//! tokio = { version = "1", features = ["full"] }
+//! reqwest = "0.12"
+//! ```
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ let urls = [
+ "https://example.com",
+ "https://example.org",
+ ];
+ let client = reqwest::Client::new();
+ let bodies = futures::future::join_all(urls.iter().map(|u| {
+ let c = client.clone();
+ async move { c.get(*u).send().await?.text().await }
+ })).await;
+ for (url, body) in urls.iter().zip(bodies) {
+ match body {
+ Ok(b) => println!("{url}: {} bytes", b.len()),
+ Err(e) => eprintln!("{url}: error {e}"),
+ }
+ }
+ Ok(())
+}
+```
+
+## With CLI parsing
+
+```rust
+#!/usr/bin/env rust-script
+//! ```cargo
+//! [dependencies]
+//! anyhow = "1"
+//! clap = { version = "4", features = ["derive"] }
+//! ```
+
+use clap::Parser;
+
+#[derive(Parser, Debug)]
+#[command(version, about = "rename files by pattern")]
+struct Cli {
+ /// Glob to match
+ pattern: String,
+ /// Replacement template (use {n} for sequence)
+ template: String,
+ /// Show what would happen without doing it
+ #[arg(long)]
+ dry_run: bool,
+}
+
+fn main() -> anyhow::Result<()> {
+ let cli = Cli::parse();
+ let entries: Vec<_> = glob::glob(&cli.pattern)?.collect::<Result<_, _>>()?;
+ for (n, entry) in entries.iter().enumerate() {
+ let target = cli.template.replace("{n}", &n.to_string());
+ if cli.dry_run {
+ println!("{} -> {target}", entry.display());
+ } else {
+ std::fs::rename(entry, &target)?;
+ }
+ }
+ Ok(())
+}
+```
+
+## Caching
+
+`rust-script` caches the compiled binary in `~/.cache/rust-script/`. First run is slow (full compile), subsequent runs are instant.
+
+To clear: `rust-script --clear-cache`.
+
+Pin a script's compile target into the script directory for portability:
+
+```bash
+rust-script --build-only --base-path . ./script.rs
+```
+
+This drops a `target/` next to the script with the prebuilt binary.
+
+## `cargo-script` (RFC 3424, stable since Rust 1.85)
+
+The official replacement that landed in cargo proper. Same idea, slightly different syntax:
+
+```rust
+#!/usr/bin/env -S cargo +nightly -Zscript
+---
+package:
+ name = "fetch"
+ edition = "2024"
+
+dependencies:
+ anyhow = "1"
+ reqwest = { version = "0.12", features = ["blocking"] }
+---
+
+fn main() -> anyhow::Result<()> {
+ let url = std::env::args().nth(1).context("url required")?;
+ println!("{}", reqwest::blocking::get(&url)?.text()?.len());
+ Ok(())
+}
+```
+
+Status as of 2026-05: stabilization in progress. Use `rust-script` for production now, migrate when `cargo script` is stable everywhere your tools live.
+
+## Strict mode for scripts
+
+Add a lints block in the inline `Cargo.toml`:
+
+```rust
+//! ```cargo
+//! [dependencies]
+//! anyhow = "1"
+//!
+//! [lints.rust]
+//! unsafe_code = "forbid"
+//!
+//! [lints.clippy]
+//! all = "deny"
+//! pedantic = "warn"
+//! unwrap_used = "deny"
+//! expect_used = "deny"
+//! panic = "deny"
+//! ```
+```
+
+Now the script gets the same strictness as the main project. If you need a one-line `unwrap()` for prototype velocity, switch the lint to `warn` for that one script - never blanket `allow`.
+
+Run with lints visible:
+
+```bash
+RUSTFLAGS="-D warnings" rust-script ./script.rs
+```
+
+## When NOT to use a script
+
+- It is going to live longer than a week → make it a real crate with `cargo new --bin`.
+- It needs custom build scripts (`build.rs`) → real crate.
+- It needs binary distribution to other machines → real crate with `cargo dist`.
+- It needs to be tested → real crate (scripts can technically run `#[test]`s under `cargo test`, but the workflow is awkward).
+
+A reasonable migration path: start as a script, when complexity grows past ~200 lines or you reach for a second `.rs` file, run `rust-script --emit ./script.rs` to dump a regular Cargo project skeleton and continue from there.
+
+## Inline tests in a script
+
+```rust
+#!/usr/bin/env rust-script
+//! ```cargo
+//! [dependencies]
+//! ```
+
+fn double(x: i32) -> i32 { x * 2 }
+
+fn main() {
+ println!("{}", double(21));
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn doubles_ints() {
+ assert_eq!(double(5), 10);
+ }
+}
+```
+
+Run tests: `rust-script --test ./script.rs`.
+
+## A useful "Rust as awk" pattern
+
+For ad-hoc data processing on stdin:
+
+```rust
+#!/usr/bin/env rust-script
+//! ```cargo
+//! [dependencies]
+//! serde_json = "1"
+//! ```
+
+use std::io::{self, BufRead, Write};
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let stdin = io::stdin();
+ let stdout = io::stdout();
+ let mut out = stdout.lock();
+ for line in stdin.lock().lines() {
+ let line = line?;
+ let value: serde_json::Value = serde_json::from_str(&line)?;
+ if let Some(s) = value.get("level").and_then(|v| v.as_str()) {
+ if s == "error" {
+ writeln!(out, "{line}")?;
+ }
+ }
+ }
+ Ok(())
+}
+```
+
+`cat logs.jsonl | ./filter-errors.rs` — filter JSON logs by `level == "error"`. Faster than `jq` for big files, type-safe.
+
+For numerics:
+
+```rust
+#!/usr/bin/env rust-script
+//! sum a column of numbers from stdin
+use std::io::{self, BufRead};
+fn main() {
+ let total: f64 = io::stdin().lock().lines()
+ .filter_map(|l| l.ok())
+ .filter_map(|l| l.trim().parse::<f64>().ok())
+ .sum();
+ println!("{total}");
+}
+```
+
+## The `rust-script` shebang trick on macOS
+
+macOS does not support multi-arg shebangs without `env -S`. Use:
+
+```rust
+#!/usr/bin/env -S rust-script --
+```
+
+The `--` lets clap-style argument parsers see the user's args, not the rust-script arguments.
+
+## Editor support
+
+VS Code / Helix / Vim with `rust-analyzer`: open the script file as if it were `src/main.rs` of an inferred crate. Most editors auto-detect the inline manifest. If not, hand-create a `Cargo.toml` next to the script with matching deps for the duration of editing, then delete it.
+
+## When `rust-script` is too heavy
+
+For absolutely throwaway "one expression on stdin" use cases, a Rust REPL like `evcxr_jupyter` (Jupyter kernel) or `irust` (terminal REPL) is more appropriate:
+
+```bash
+cargo install irust
+irust
+```
+
+But these are interactive playgrounds, not scriptable. For shell pipelines, stay with `rust-script`.
+
+## The Promise
+
+Same strict lints. Same `clippy::pedantic` enforcement. Same `unsafe`-requires-SAFETY rule. The agent does not get a free pass on a 30-line script. The whole point of strict scripts is that **production hygiene is cheap when the toolchain enforces it**.
diff --git a/plugins/omo/skills/programming/references/rust/proptest-insta.md b/plugins/omo/skills/programming/references/rust/proptest-insta.md
new file mode 100644
index 00000000..4d7f0953
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust/proptest-insta.md
@@ -0,0 +1,429 @@
+# Property Tests (proptest) + Snapshot Tests (insta)
+
+Two test types every Rust project should have alongside unit tests. Proptest hunts for inputs your unit tests forgot to try. Insta locks down output shapes you do not want to silently change.
+
+## When to reach for each
+
+| Want to test… | Use |
+|---|---|
+| One specific behavior with a known input | `#[test]` + `assert_eq!` |
+| All inputs of a certain shape work | `proptest!` |
+| Output structure stays stable across refactors | `insta::assert_*_snapshot!` |
+| Parser/serializer round-trips | `proptest!` (the round-trip property) |
+| CLI help text, JSON response shape, debug output | `insta::assert_snapshot!` |
+| Concurrency under all interleavings | `loom` (see `concurrency.md`) |
+
+Use all three. They cover different bug classes.
+
+## Proptest — setup
+
+`Cargo.toml`:
+
+```toml
+[dev-dependencies]
+proptest = "1"
+proptest-derive = "0.5" # for #[derive(Arbitrary)]
+```
+
+`proptest.toml` at project root (optional, sane defaults):
+
+```toml
+cases = 256 # number of random inputs per property
+max_local_rejects = 65536
+max_global_rejects = 1024
+max_shrink_iters = 1024
+max_shrink_time = 60_000 # ms
+failure_persistence = { source_file = "proptest-regressions/", file_name = "regressions.txt" }
+verbose = 0
+```
+
+`failure_persistence` is the killer feature: every failure is written to a regression file. On the next run, those exact inputs are replayed first, so once a bug is found it never escapes again.
+
+## Basic property test
+
+```rust
+use proptest::prelude::*;
+
+fn parse(s: &str) -> Result<Color, ParseError> { /* ... */ }
+fn render(c: &Color) -> String { /* ... */ }
+
+proptest! {
+ #[test]
+ fn parse_render_roundtrips(red in 0u8..=255, green in 0u8..=255, blue in 0u8..=255) {
+ let color = Color { red, green, blue };
+ let rendered = render(&color);
+ let parsed = parse(&rendered).expect("our render should always parse");
+ prop_assert_eq!(parsed, color);
+ }
+}
+```
+
+`proptest!` macro takes `(arg in strategy, ...)` pairs. Each strategy produces values; proptest runs the body with random samples, then shrinks failing cases to minimal forms.
+
+## Strategies — the value-generation language
+
+| Strategy | Produces |
+|---|---|
+| `any::<T>()` | Any value of `T` (if `T: Arbitrary`) |
+| `0u32..100` | Integer ranges |
+| `prop::sample::select(slice)` | Pick from a list |
+| `prop::collection::vec(elem, range)` | Vec of length in range |
+| `prop::collection::hash_map(k, v, n..m)` | HashMap |
+| `prop::option::of(strategy)` | Option |
+| `prop::result::maybe_ok(ok, err)` | Result |
+| `(s1, s2).prop_map(\|(a, b)\| ...)` | Combine, transform |
+| `s.prop_filter("reason", \|v\| pred)` | Reject values |
+| `s.prop_flat_map(\|v\| dependent)` | Sequential dependency |
+| `prop_oneof![strategy1, strategy2]` | Union of strategies |
+| `r"[a-z]{3,10}"` | Regex-generated string |
+| `"\\PC*"` | Any printable non-control string |
+
+Example combining several:
+
+```rust
+fn config_strategy() -> impl Strategy<Value = Config> {
+ (
+ prop::sample::select(vec!["dev", "staging", "prod"]),
+ 0u16..=65535,
+ prop::collection::hash_map(
+ r"[a-z_]{1,20}",
+ any::<String>(),
+ 0..5,
+ ),
+ ).prop_map(|(env, port, vars)| Config {
+ env: env.into(),
+ port,
+ env_vars: vars,
+ })
+}
+
+proptest! {
+ #[test]
+ fn config_validates(cfg in config_strategy()) {
+ let result = validate(&cfg);
+ if cfg.port == 0 {
+ prop_assert!(result.is_err());
+ } else {
+ prop_assert!(result.is_ok());
+ }
+ }
+}
+```
+
+## Properties to write for every parser
+
+1. **Round-trip:** `parse(render(x)) == x` for all valid `x`.
+2. **No-panic:** `parse(arbitrary_string)` never panics, always returns `Result`.
+3. **Idempotent:** `parse(parse(x).unwrap().render()) == parse(x).unwrap()`.
+4. **Whitespace insensitivity:** `parse(x) == parse(strip_whitespace(x))` (if applicable).
+
+For every serializer:
+
+1. **Length bound:** `render(x).len() <= bound(x)`.
+2. **Charset:** `render(x).chars().all(|c| ALLOWED.contains(&c))`.
+
+For every collection operation:
+
+1. **Identity:** `op_identity(x) == x` (sort an already-sorted, dedupe a unique).
+2. **Idempotence:** `op(op(x)) == op(x)`.
+3. **Commutativity:** `op(a, b) == op(b, a)` (set union, etc).
+4. **Length:** `op(a, b).len() == known_relation(a.len(), b.len())`.
+
+For every numeric op:
+
+1. **Monotonicity:** `a <= b => f(a) <= f(b)`.
+2. **Identity element:** `f(x, identity) == x`.
+
+Write these mechanically. The agent should reach for proptest the moment any of these properties is checkable.
+
+## Derive `Arbitrary`
+
+```rust
+use proptest_derive::Arbitrary;
+
+#[derive(Debug, Clone, PartialEq, Arbitrary)]
+struct Vec3 {
+ #[proptest(strategy = "-100.0..=100.0")]
+ x: f32,
+ #[proptest(strategy = "-100.0..=100.0")]
+ y: f32,
+ #[proptest(strategy = "-100.0..=100.0")]
+ z: f32,
+}
+
+proptest! {
+ #[test]
+ fn dot_product_is_commutative(a: Vec3, b: Vec3) {
+ prop_assert!((dot(&a, &b) - dot(&b, &a)).abs() < 1e-5);
+ }
+}
+```
+
+`#[derive(Arbitrary)]` auto-implements the strategy. Per-field `#[proptest(strategy = "...")]` overrides.
+
+## Stateful / state machine tests
+
+For data structures with operations (queues, maps, trees), use `proptest-state-machine`:
+
+```rust
+use proptest_state_machine::{ReferenceStateMachine, StateMachineTest};
+
+struct MyQueueRef { state: VecDeque<i32> }
+struct MyQueueSut { sut: MyQueue<i32> }
+
+#[derive(Debug, Clone)]
+enum Op { Push(i32), Pop }
+
+impl ReferenceStateMachine for MyQueueRef {
+ type State = VecDeque<i32>;
+ type Transition = Op;
+
+ fn init_state() -> BoxedStrategy<Self::State> {
+ Just(VecDeque::new()).boxed()
+ }
+ fn transitions(_: &Self::State) -> BoxedStrategy<Self::Transition> {
+ prop_oneof![
+ any::<i32>().prop_map(Op::Push),
+ Just(Op::Pop),
+ ].boxed()
+ }
+ fn apply(mut state: Self::State, transition: &Self::Transition) -> Self::State {
+ match transition {
+ Op::Push(x) => state.push_back(*x),
+ Op::Pop => { state.pop_front(); }
+ }
+ state
+ }
+}
+
+impl StateMachineTest for MyQueueSut {
+ type SystemUnderTest = MyQueue<i32>;
+ type Reference = MyQueueRef;
+
+ fn init_test(_: &<Self::Reference as ReferenceStateMachine>::State) -> Self::SystemUnderTest {
+ MyQueue::new()
+ }
+ fn apply(mut sut: Self::SystemUnderTest, _: &VecDeque<i32>, transition: Op) -> Self::SystemUnderTest {
+ match transition {
+ Op::Push(x) => sut.push(x),
+ Op::Pop => { sut.pop(); }
+ }
+ sut
+ }
+ fn check_invariants(sut: &Self::SystemUnderTest, state: &VecDeque<i32>) {
+ assert_eq!(sut.len(), state.len());
+ // also check head/tail/iteration order...
+ }
+}
+
+proptest_state_machine::prop_state_machine! {
+ #[test]
+ fn queue_matches_vecdeque(sequential 1..50 => MyQueueSut);
+}
+```
+
+You define a reference implementation (`VecDeque` here), proptest fuzzes operations against both, asserts invariants every step. This is the technique for finding bugs in lock-free or complex containers.
+
+## Shrinking
+
+When a property fails, proptest reduces the input to a minimal counter-example. For built-in strategies this is automatic. For custom strategies built with `prop_map`, shrinking goes through the underlying strategy. Avoid breaking shrinking with `prop_filter` (rejection sampling) over wide spaces; prefer `prop_flat_map` or directly-shaped strategies.
+
+## Regression corpus
+
+When a property test fails, proptest writes the failing input to `proptest-regressions/<test_name>.txt`. Commit this directory. Future runs replay these failing inputs first, so the bug stays fixed forever.
+
+```
+proptest-regressions/
+└── parse_color.txt # commit this
+```
+
+## Insta — setup
+
+`Cargo.toml`:
+
+```toml
+[dev-dependencies]
+insta = { version = "1", features = ["yaml", "json", "redactions", "filters"] }
+
+[dependencies.serde_yaml]
+version = "0.9"
+optional = true
+```
+
+Install the CLI:
+
+```bash
+cargo install cargo-insta
+```
+
+## Insta — basic snapshots
+
+```rust
+#[test]
+fn renders_default_help() {
+ let output = render_help();
+ insta::assert_snapshot!(output);
+}
+```
+
+First run: creates `src/snapshots/mycrate__renders_default_help.snap.new`. Run `cargo insta review`, press `a` to accept, the `.new` extension is dropped. Subsequent runs diff against the committed snapshot; mismatches fail the test.
+
+## Insta — typed snapshots
+
+```rust
+#[derive(Debug, serde::Serialize)]
+struct Result {
+ status: String,
+ user: User,
+ duration_ms: u64,
+}
+
+#[test]
+fn json_response() {
+ let value = compute();
+ insta::assert_json_snapshot!(value);
+}
+
+#[test]
+fn yaml_response() {
+ insta::assert_yaml_snapshot!(value);
+}
+
+#[test]
+fn debug_repr() {
+ insta::assert_debug_snapshot!(value);
+}
+```
+
+Choose:
+- `assert_snapshot!` for `String`/`Display` output (CLI help, error messages, generated code).
+- `assert_debug_snapshot!` for `{:?}` (Rust-internal data).
+- `assert_json_snapshot!` for structured data crossing process boundaries.
+- `assert_yaml_snapshot!` when YAML is easier to read in diffs.
+
+## Insta — redactions and filters
+
+For values that change every run (timestamps, UUIDs, paths):
+
+```rust
+#[test]
+fn with_redactions() {
+ let value = ApiResponse {
+ id: uuid::Uuid::now_v7(),
+ created_at: jiff::Timestamp::now(),
+ body: "hello".into(),
+ };
+ insta::assert_json_snapshot!(value, {
+ ".id" => "[uuid]",
+ ".created_at" => "[timestamp]",
+ });
+}
+```
+
+For regex filters applied to all snapshots in a test:
+
+```rust
+#[test]
+fn with_filters() {
+ let mut settings = insta::Settings::clone_current();
+ settings.add_filter(r"/tmp/[a-z0-9-]+", "[TMP]");
+ settings.add_filter(r"\d+\.\d+ms", "[TIMING]");
+ settings.bind(|| {
+ let output = run_command();
+ insta::assert_snapshot!(output);
+ });
+}
+```
+
+`Settings::bind` scopes filters to the closure.
+
+## Insta workflow
+
+1. Write the test, run it. First run creates `.snap.new`.
+2. `cargo insta review` → interactive UI. Show diff, accept/reject.
+3. Accepted snapshots commit to the repo.
+4. Refactor code. Tests run; mismatches show as diffs.
+5. If the new output is correct, `cargo insta accept` (or selective `review`). If wrong, fix the code.
+
+Pair with CI to fail builds when uncommitted `.snap.new` files exist:
+
+```bash
+cargo nextest run
+if find . -name "*.snap.new" | grep -q .; then
+ echo "Pending snapshots, run 'cargo insta review'"
+ exit 1
+fi
+```
+
+## Inline snapshots
+
+```rust
+#[test]
+fn small_output() {
+ let value = compute();
+ insta::assert_snapshot!(value, @"hello world");
+}
+```
+
+The trailing `@"..."` string is the expected snapshot, stored in source. Useful when the value is short enough that pulling out a separate file is overkill. `cargo insta accept` updates them in-place.
+
+## Inline JSON snapshots
+
+```rust
+#[test]
+fn json_inline() {
+ insta::assert_json_snapshot!(value, @r###"
+ {
+ "status": "ok",
+ "count": 3
+ }
+ "###);
+}
+```
+
+## Anti-patterns
+
+1. **Snapshots of unstable output.** If `HashMap` iteration order changes per run, snapshots will fail. Switch to `BTreeMap` or sort before snapshotting.
+2. **Massive snapshots.** A 10KB JSON dump where you really care about 3 fields. Either narrow to the fields, or accept that any refactor will require re-reviewing 10KB.
+3. **Snapshots that bake in implementation details.** "function called 3 times" is not a snapshot - it's a behavior assertion. Use a real assertion.
+4. **Skipping `cargo insta review`.** Accepting blind via `cargo insta accept --all` defeats the purpose. Always review.
+
+## Combining proptest + insta
+
+```rust
+proptest! {
+ #[test]
+ fn random_inputs_render_consistently(input: ValidInput) {
+ let mut settings = insta::Settings::clone_current();
+ settings.set_snapshot_suffix(format!("{}", input.hash()));
+ settings.bind(|| {
+ insta::assert_snapshot!(render(&input));
+ });
+ }
+}
+```
+
+But honestly, this is rarely a fit. Proptest tests properties, insta tests output shape. Don't snapshot random inputs - that defeats both tools.
+
+## CI matrix recommendation
+
+```yaml
+- name: Tests
+ run: cargo nextest run --all-features
+
+- name: Property regressions (replay)
+ run: |
+ # The regression files in proptest-regressions/ replay first.
+ # Failures here mean a previously-fixed bug came back.
+ cargo nextest run --all-features --test-threads 1
+```
+
+When a proptest finds a new failure, the regression file appears as a git diff - check it in.
+
+## What proptest cannot do
+
+- Find bugs that require multi-process / multi-network coordination → integration tests + fault injection.
+- Find concurrency bugs → use `loom` (see `concurrency.md`).
+- Find performance regressions → use `criterion`.
+
+But for any function with a domain (inputs to outputs), proptest can find more bugs than your unit tests. **Write the property first, derive the unit test second.**
diff --git a/plugins/omo/skills/programming/references/rust/type-state.md b/plugins/omo/skills/programming/references/rust/type-state.md
new file mode 100644
index 00000000..8780774b
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust/type-state.md
@@ -0,0 +1,354 @@
+# Type-State and Newtype Patterns
+
+The single highest-leverage thing Rust gives a coding agent: encode invariants in the type system so the compiler refuses incorrect code. The agent does not have to "remember" rules - the rules are physical.
+
+## The Two Core Patterns
+
+1. **Newtype wrappers for distinct semantic units.** Money, IDs, byte offsets, coordinate spaces - each gets its own tuple struct. The agent cannot pass meters where feet are expected, even though both are `f64` under the hood. This is the `euclid::Point<Screen>` vs `euclid::Point<World>` example Chris Allen called out.
+2. **Type-state for state machines.** Instead of a struct with a `status: enum { Draft, Validated, Persisted }` field and methods that check `if self.status == ...`, model each state as its own type. Transitions are method calls that consume `self` and return a new type. Illegal transitions become unrepresentable.
+
+## Newtype Wrapper Cookbook
+
+### Domain IDs
+
+```rust
+use uuid::Uuid;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
+#[serde(transparent)]
+pub struct UserId(Uuid);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
+#[serde(transparent)]
+pub struct ProductId(Uuid);
+
+impl UserId {
+ pub fn new() -> Self { Self(Uuid::now_v7()) }
+ pub fn as_uuid(&self) -> &Uuid { &self.0 }
+}
+
+impl ProductId {
+ pub fn new() -> Self { Self(Uuid::now_v7()) }
+ pub fn as_uuid(&self) -> &Uuid { &self.0 }
+}
+
+// `fn buy(user: UserId, product: ProductId)` cannot be called with arguments swapped.
+```
+
+`#[serde(transparent)]` keeps JSON/SQL round-trips identical to a bare `Uuid` - the wrapper is purely a compile-time discipline.
+
+### Quantities with Phantom Type Tags
+
+```rust
+use core::marker::PhantomData;
+use core::ops::{Add, Sub, Mul};
+
+#[derive(Debug, Clone, Copy)]
+pub struct Quantity<Unit> {
+ raw: f64,
+ _unit: PhantomData<Unit>,
+}
+
+// Tag types - zero-sized, never instantiated.
+pub struct Meters;
+pub struct Feet;
+pub struct Seconds;
+
+impl<U> Quantity<U> {
+ pub const fn new(value: f64) -> Self {
+ Self { raw: value, _unit: PhantomData }
+ }
+ pub fn raw(self) -> f64 { self.raw }
+}
+
+// Adding same-unit quantities: allowed.
+impl<U> Add for Quantity<U> {
+ type Output = Self;
+ fn add(self, rhs: Self) -> Self { Self::new(self.raw + rhs.raw) }
+}
+
+// Subtraction: allowed.
+impl<U> Sub for Quantity<U> {
+ type Output = Self;
+ fn sub(self, rhs: Self) -> Self { Self::new(self.raw - rhs.raw) }
+}
+
+// Multiplying by scalar: allowed.
+impl<U> Mul<f64> for Quantity<U> {
+ type Output = Self;
+ fn mul(self, rhs: f64) -> Self { Self::new(self.raw * rhs) }
+}
+
+// Conversions are explicit, named methods - never `From`/`Into` between units.
+impl Quantity<Meters> {
+ pub fn to_feet(self) -> Quantity<Feet> {
+ Quantity::new(self.raw * 3.280_84)
+ }
+}
+```
+
+Now:
+
+```rust
+let distance: Quantity<Meters> = Quantity::new(100.0);
+let height: Quantity<Feet> = Quantity::new(50.0);
+let combined = distance + height; // ❌ compile error
+let combined = distance + height.to_feet().to_meters_oops(); // ❌ no such method
+let combined = distance + distance; // ✅
+```
+
+The agent cannot accidentally mix units. Refactors that change a quantity's underlying unit are caught at compile time everywhere the type flows.
+
+### Byte Offsets vs Character Offsets
+
+```rust
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub struct ByteOffset(pub u32);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+pub struct CharOffset(pub u32);
+
+impl ByteOffset {
+ pub fn add(self, delta: u32) -> Self { Self(self.0 + delta) }
+}
+
+// Converting between them is a function on the actual text.
+pub fn byte_to_char(text: &str, byte: ByteOffset) -> Option<CharOffset> {
+ text.get(..byte.0 as usize).map(|prefix| CharOffset(prefix.chars().count() as u32))
+}
+```
+
+A function signature `fn slice(text: &str, start: ByteOffset, end: ByteOffset)` cannot be called with character offsets. The UTF-8 boundary bug is now a compile error.
+
+### Currency
+
+```rust
+use rust_decimal::Decimal;
+
+pub struct Krw;
+pub struct Usd;
+pub struct Jpy;
+
+#[derive(Debug, Clone, Copy)]
+pub struct Money<Currency> {
+ amount: Decimal,
+ _ccy: PhantomData<Currency>,
+}
+
+impl<C> Money<C> {
+ pub const fn new(amount: Decimal) -> Self { Self { amount, _ccy: PhantomData } }
+}
+
+impl<C> Add for Money<C> {
+ type Output = Self;
+ fn add(self, rhs: Self) -> Self { Self::new(self.amount + rhs.amount) }
+}
+
+// No blanket From<Money<X>> for Money<Y> - conversions go through an explicit
+// FX rate function that takes a `Rate<From, To>` argument.
+
+pub struct Rate<From, To> {
+ factor: Decimal,
+ _from: PhantomData<From>,
+ _to: PhantomData<To>,
+}
+
+impl<From, To> Money<From> {
+ pub fn convert(self, rate: Rate<From, To>) -> Money<To> {
+ Money::new(self.amount * rate.factor)
+ }
+}
+```
+
+The agent cannot add KRW and USD by accident. They cannot convert without a rate. They cannot apply a USD→JPY rate to a KRW value.
+
+### Paths Rooted at Different Bases
+
+```rust
+use std::path::{Path, PathBuf};
+
+/// A path guaranteed to be relative to the project root.
+#[derive(Debug, Clone)]
+pub struct ProjectRel(PathBuf);
+
+/// A path guaranteed to be relative to the user's home directory.
+#[derive(Debug, Clone)]
+pub struct HomeRel(PathBuf);
+
+impl ProjectRel {
+ pub fn new(path: impl AsRef<Path>) -> Result<Self, PathError> {
+ let path = path.as_ref();
+ if path.is_absolute() { return Err(PathError::NotRelative); }
+ if path.components().any(|c| matches!(c, std::path::Component::ParentDir)) {
+ return Err(PathError::EscapesRoot);
+ }
+ Ok(Self(path.to_path_buf()))
+ }
+
+ pub fn resolve(&self, project_root: &Path) -> PathBuf {
+ project_root.join(&self.0)
+ }
+}
+```
+
+The agent's path-handling code now distinguishes between project-relative and home-relative paths at the type level. A function taking `ProjectRel` cannot be called with a `HomeRel`.
+
+## Type-State State Machines
+
+Encode the lifecycle of a value as a sequence of types. Each transition consumes the previous state and returns the next.
+
+### HTTP Request Builder
+
+```rust
+pub struct RequestBuilder<State> {
+ url: String,
+ method: Method,
+ headers: HeaderMap,
+ body: Option<Vec<u8>>,
+ _state: PhantomData<State>,
+}
+
+pub struct NeedsUrl;
+pub struct NeedsMethod;
+pub struct Ready;
+
+impl RequestBuilder<NeedsUrl> {
+ pub fn new() -> Self {
+ Self {
+ url: String::new(),
+ method: Method::GET,
+ headers: HeaderMap::new(),
+ body: None,
+ _state: PhantomData,
+ }
+ }
+ pub fn url(mut self, url: impl Into<String>) -> RequestBuilder<NeedsMethod> {
+ self.url = url.into();
+ RequestBuilder { url: self.url, method: self.method, headers: self.headers, body: self.body, _state: PhantomData }
+ }
+}
+
+impl RequestBuilder<NeedsMethod> {
+ pub fn method(mut self, method: Method) -> RequestBuilder<Ready> {
+ self.method = method;
+ RequestBuilder { url: self.url, method: self.method, headers: self.headers, body: self.body, _state: PhantomData }
+ }
+}
+
+// .header(), .body() available in any state that has at least URL.
+impl<S> RequestBuilder<S> {
+ pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
+ self.headers.insert(name, value);
+ self
+ }
+}
+
+// .send() only available once URL and method are set.
+impl RequestBuilder<Ready> {
+ pub async fn send(self, client: &Client) -> reqwest::Result<Response> { /* ... */ }
+}
+```
+
+`client.send(RequestBuilder::new().send(...))` - compile error. The agent has to fill in the required steps. The IDE autocomplete also reflects only the legal next steps.
+
+### File Handles
+
+```rust
+pub struct File<State> {
+ fd: RawFd,
+ _state: PhantomData<State>,
+}
+
+pub struct Open;
+pub struct Locked;
+pub struct Closed;
+
+impl File<Open> {
+ pub fn open(path: &Path) -> std::io::Result<Self> { /* ... */ }
+ pub fn lock_exclusive(self) -> std::io::Result<File<Locked>> { /* flock */ }
+ pub fn close(self) -> std::io::Result<File<Closed>> { /* ... */ }
+}
+
+impl File<Locked> {
+ pub fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { /* ... */ }
+ pub fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { /* ... */ }
+ pub fn unlock(self) -> std::io::Result<File<Open>> { /* ... */ }
+}
+
+impl File<Closed> {
+ // No methods. The type only exists to be dropped.
+}
+```
+
+You cannot `read()` an unlocked file. You cannot `close()` while holding a lock without unlocking first. You cannot use a closed file at all - it has no methods.
+
+## Sealed Traits
+
+Sometimes you want a closed set of types implementing a trait, defined by the crate, not extensible by downstream. The sealed trait pattern:
+
+```rust
+mod sealed {
+ pub trait Sealed {}
+}
+
+pub trait Renderer: sealed::Sealed {
+ fn render(&self, frame: &mut Frame);
+}
+
+pub struct OpenGl;
+pub struct Vulkan;
+pub struct Metal;
+
+impl sealed::Sealed for OpenGl {}
+impl sealed::Sealed for Vulkan {}
+impl sealed::Sealed for Metal {}
+
+impl Renderer for OpenGl { fn render(&self, f: &mut Frame) { /* ... */ } }
+impl Renderer for Vulkan { fn render(&self, f: &mut Frame) { /* ... */ } }
+impl Renderer for Metal { fn render(&self, f: &mut Frame) { /* ... */ } }
+```
+
+Downstream code cannot add new `impl Renderer for Whatever` because they cannot implement `sealed::Sealed` (its module is private). Useful when you want trait dispatch but maintain the invariant that you control all implementations.
+
+## NonEmpty Collections
+
+```rust
+pub struct NonEmptyVec<T> {
+ head: T,
+ tail: Vec<T>,
+}
+
+#[derive(Debug, thiserror::Error)]
+#[error("vector was empty")]
+pub struct Empty;
+
+impl<T> NonEmptyVec<T> {
+ pub fn try_from_vec(mut v: Vec<T>) -> Result<Self, Empty> {
+ if v.is_empty() { return Err(Empty); }
+ let tail = v.split_off(1);
+ let head = v.into_iter().next().expect("checked non-empty");
+ Ok(Self { head, tail })
+ }
+
+ pub fn first(&self) -> &T { &self.head }
+ pub fn len(&self) -> usize { self.tail.len() + 1 }
+}
+```
+
+Functions taking `NonEmptyVec<T>` cannot receive an empty vector. The `first()` method returns `&T`, not `Option<&T>`. The agent never has to write `match v.first() { Some(x) => ..., None => panic!(...) }` again.
+
+## When NOT to Newtype
+
+- For one-off internal computations where the unit lives in a single function and never crosses a boundary.
+- When the wrapper does not change behavior or invariants vs. the underlying type (e.g., a `struct Count(u32)` that is only ever used in one struct).
+- When `From`/`Into` conversions would be ergonomic but would defeat the purpose (if you find yourself wanting `impl From<UserId> for Uuid`, you do not want a newtype - you want a type alias).
+
+The cost of a newtype is one tuple struct + the impls you need. The break-even is around three uses across different functions, or any use that crosses an API boundary.
+
+## When NOT to Use Type-State
+
+- When the state space is small and transitions are simple (`Option<T>` and `Result<T, E>` are state machines already).
+- When the type-state would force runtime branching upward (e.g., reading "should this run as Open or Locked?" from config means you store `Box<dyn FileLike>` anyway).
+- When the API is consumed by code that does not know the state at compile time (heterogeneous collections, dynamic dispatch boundaries).
+
+In those cases, regular enum-tagged states are correct. The line is: **can the call site know the state statically?** If yes, type-state. If no, enum-with-tag.
diff --git a/plugins/omo/skills/programming/references/rust/unsafe-discipline.md b/plugins/omo/skills/programming/references/rust/unsafe-discipline.md
new file mode 100644
index 00000000..67eb2ffb
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust/unsafe-discipline.md
@@ -0,0 +1,250 @@
+# Unsafe Discipline
+
+The reason Chris Allen's "implementing a persistent memory arena in Rust was not hard" works: the unsafe surface area is microscopic, it lives behind one newtype with one constructor, and every block has a SAFETY comment that names a specific invariant. Coding agents follow the pattern mechanically once the shape is established.
+
+## The Three Required Components
+
+Every `unsafe` block needs all three. No exceptions.
+
+1. **Safe wrapper.** No `unsafe fn` or raw pointer types in the crate's public API. If a caller needs to construct an instance, the constructor either does the work safely or is `unsafe` with a documented contract.
+2. **SAFETY comment.** A `// SAFETY:` line within 5 lines above the `unsafe { ... }` block, stating which invariant is upheld and where it comes from. Generic phrases ("this is safe because we checked") fail review.
+3. **miri proof.** A test that exercises the unsafe path under `cargo +nightly miri nextest run`. If the path cannot be exercised under miri (FFI, syscalls), provide an alternate proof and gate behind a feature flag ending in `-skip-miri`.
+
+## The Wrapper Pattern (`NonNull<T>` style)
+
+Reference the screenshot Chris Allen quoted - `std::ptr::NonNull<T>`. Mirror this shape for every raw pointer, raw slice, raw transmute, or uninit memory operation in your own code.
+
+```rust
+use core::marker::PhantomData;
+use core::ptr::NonNull;
+
+/// A non-null, properly aligned, initialized pointer that does not alias.
+///
+/// All invariants are upheld by [`Self::new`] (checked) or [`Self::new_unchecked`]
+/// (delegated to the caller's contract). Once you hold an `InitPtr<T>`, every
+/// public method on it is safe to call.
+#[derive(Debug)]
+#[repr(transparent)]
+pub struct InitPtr<T> {
+ inner: NonNull<T>,
+ _marker: PhantomData<T>,
+}
+
+// Send/Sync are NOT automatic for raw-pointer-bearing types. Decide deliberately.
+// SAFETY: `InitPtr<T>` owns no concurrency state of its own; whether it is
+// Send/Sync depends on `T`. The bounds below mirror `Box<T>`.
+unsafe impl<T: Send> Send for InitPtr<T> {}
+unsafe impl<T: Sync> Sync for InitPtr<T> {}
+
+impl<T> InitPtr<T> {
+ /// Wrap a raw pointer after checking alignment and non-null. The
+ /// initialization invariant is not statically checkable here; callers must
+ /// only feed pointers to memory that was written before this call.
+ pub fn new(ptr: *mut T) -> Option<Self> {
+ if !ptr.is_aligned() {
+ return None;
+ }
+ // SAFETY: alignment checked above; `NonNull::new` filters null. The
+ // caller is documented to provide an initialized location.
+ NonNull::new(ptr).map(|inner| Self { inner, _marker: PhantomData })
+ }
+
+ /// Wrap a raw pointer the caller asserts is valid.
+ ///
+ /// # Safety
+ ///
+ /// - `ptr` is non-null.
+ /// - `ptr` is aligned to `align_of::<T>()`.
+ /// - `*ptr` is initialized at the time of this call.
+ /// - For the lifetime of the returned value, no other `&T` or `&mut T`
+ /// aliases `*ptr`.
+ pub unsafe fn new_unchecked(ptr: *mut T) -> Self {
+ // SAFETY: caller upholds non-null per the function contract.
+ Self { inner: unsafe { NonNull::new_unchecked(ptr) }, _marker: PhantomData }
+ }
+
+ pub fn as_ref(&self) -> &T {
+ // SAFETY: the constructor's invariants guarantee `inner` points at an
+ // initialized, aligned, non-aliased `T`. Reborrowing through `&self`
+ // ties the resulting lifetime to `self`, enforcing the rest via
+ // standard borrow rules.
+ unsafe { self.inner.as_ref() }
+ }
+
+ pub fn as_mut(&mut self) -> &mut T {
+ // SAFETY: `&mut self` proves no other reference can alias `inner` for
+ // the lifetime of the returned `&mut T`; remaining invariants come
+ // from construction.
+ unsafe { self.inner.as_mut() }
+ }
+}
+```
+
+The list of features this single shape gives you:
+
+- The agent cannot construct `InitPtr<T>` without going through a checked path or accepting the `unsafe` obligation explicitly.
+- The agent cannot leak the raw pointer; `as_ref` / `as_mut` return safe references with proper lifetimes.
+- The agent cannot accidentally Send/Sync where it shouldn't - the `unsafe impl` is explicit per-bound.
+- `#[repr(transparent)]` means the type is layout-compatible with `*mut T` for FFI, without exposing the raw pointer.
+
+## SAFETY Comment Grammar
+
+Every comment maps one-to-one to an invariant. Format:
+
+```rust
+// SAFETY: <which invariant is upheld>: <how it is established here>.
+```
+
+Anti-examples (do not pass review):
+
+```rust
+// SAFETY: this is fine
+// SAFETY: we know what we're doing
+// SAFETY: the caller will not pass null
+// SAFETY: tested
+```
+
+Good examples:
+
+```rust
+// SAFETY: `len <= self.capacity` was checked at line 87 and `self.ptr` was
+// allocated by the same allocator we are reading through.
+
+// SAFETY: `read_volatile` requires alignment and non-null; both hold because
+// `self.inner` is an `InitPtr<T>` whose constructor enforced them.
+
+// SAFETY: We hold `&mut self`, so no concurrent reader exists. The slice
+// reference is dropped before the next `&self` borrow because we shrink the
+// returned scope manually.
+```
+
+## Persistent Memory Arena Pattern (the Chris Allen example)
+
+A persistent memory arena (PMA) is an `mmap`-backed bump allocator that survives process restarts. It is the classic "lots of unsafe under one safe surface" project.
+
+Shape:
+
+```rust
+pub struct Arena {
+ map: Mmap, // wraps `mmap(2)` - safe wrapper from `memmap2` crate
+ head: AtomicUsize, // current bump offset, atomic for multi-writer if needed
+}
+
+impl Arena {
+ pub fn open(path: &Path, capacity: usize) -> std::io::Result<Self> { /* mmap, init header */ }
+
+ pub fn alloc<T>(&self, value: T) -> Result<Handle<T>, ArenaFull> {
+ let layout = Layout::new::<T>();
+ let aligned = align_up(self.head.load(Acquire), layout.align());
+ let next = aligned.checked_add(layout.size()).ok_or(ArenaFull)?;
+ if next > self.map.len() { return Err(ArenaFull); }
+ // CAS the head forward; retry on contention.
+ // ... omitted for brevity ...
+
+ // SAFETY: `aligned + layout.size() <= self.map.len()` was just proven.
+ // The mmap region is exclusively owned by this arena while we hold the
+ // bump. `aligned` is aligned to `layout.align()` by `align_up`. No
+ // other writer can have observed this offset because the CAS above
+ // returned `Ok`.
+ let ptr = unsafe { self.map.as_mut_ptr().add(aligned) as *mut T };
+ // SAFETY: `ptr` is non-null (mmap base + offset), aligned (above),
+ // exclusively owned (CAS), and we are about to initialize it.
+ unsafe { ptr::write(ptr, value) };
+
+ // SAFETY: same invariants; we wrap the now-initialized pointer in the
+ // safe handle which encapsulates further accesses.
+ Ok(unsafe { Handle::new_unchecked(ptr, self) })
+ }
+}
+
+pub struct Handle<'a, T> {
+ inner: InitPtr<T>,
+ _arena: PhantomData<&'a Arena>,
+}
+```
+
+Three `unsafe` blocks, three SAFETY comments, one safe handle type emerging on the other side. The agent now uses `Handle<T>` everywhere - never `*mut T`.
+
+## Miri Invocation
+
+```bash
+# install once
+rustup install nightly
+rustup component add miri rust-src --toolchain nightly
+
+# run on every change that touches unsafe
+MIRIFLAGS="-Zmiri-strict-provenance -Zmiri-symbolic-alignment-check" \
+ cargo +nightly miri nextest run --all-features
+```
+
+What miri catches that the borrow checker cannot:
+
+- Use-after-free
+- Double-free
+- Reads of uninitialized memory
+- Pointer-from-integer reconstruction that violates strict provenance
+- Alignment lies (transmuting unaligned data)
+- Stacked borrows / Tree borrows aliasing violations
+- Data races (single-threaded model, but catches concurrent access through `UnsafeCell` misuse)
+- Atomic ordering bugs in some patterns
+- Memory leaks (with `-Zmiri-track-pointer-tag`)
+
+## When Miri Cannot Run
+
+Certain paths are off-limits for miri: most syscalls beyond a curated allowlist, real network I/O, `std::process` calls, OS-specific FFI, hardware-dependent intrinsics on non-x86. Strategy:
+
+1. **Isolate.** Put the un-mirifiable code in its own module behind `#[cfg(feature = "ffi-real")]` or similar.
+2. **Mock at the boundary.** For everything below the FFI boundary, write a safe Rust fake (a `Vec<u8>`-backed "disk", a fake clock, an in-memory socket pair). Expose it as a trait the production code consumes.
+3. **Test the fake under miri.** The fake implementation exercises the same logic minus the syscall. If the logic is unsafe (raw pointer manipulation in the fake "disk" buffer), miri catches the bug.
+4. **Test the real path under regular `cargo test`.** With `cargo nextest run --features ffi-real`. No miri, but the surface area is now just the syscall boundary.
+5. **Document.** A `# Safety` section in the rustdoc names the obligations the FFI puts on us, and a `# Testing` section explains the mock-vs-real split.
+
+## Loom for Concurrency
+
+When `unsafe` participates in a concurrent algorithm (lock-free queue, hazard pointers, custom Arc), miri's single-thread model is insufficient. Use `loom`:
+
+```rust
+#[cfg(loom)]
+use loom::sync::atomic::{AtomicUsize, Ordering};
+#[cfg(not(loom))]
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ #[cfg(loom)]
+ fn concurrent_push_pop() {
+ loom::model(|| {
+ let queue = std::sync::Arc::new(MyQueue::new());
+ let q1 = queue.clone();
+ let q2 = queue.clone();
+ let h1 = loom::thread::spawn(move || q1.push(1));
+ let h2 = loom::thread::spawn(move || q2.pop());
+ h1.join().unwrap();
+ h2.join().unwrap();
+ });
+ }
+}
+```
+
+Run: `RUSTFLAGS="--cfg loom" cargo test --release`. Loom exhaustively explores thread interleavings for the test scope. Combined with miri on the single-thread paths, you have machine-checked soundness over the full state space.
+
+## The Forbidden List
+
+Reject in code review, automatic CI fail:
+
+- `unsafe { ... }` with no SAFETY comment within 5 lines above.
+- `unsafe { unsafe_op_a(); unsafe_op_b(); }` (multiple unsafe ops in one block - split them, one SAFETY each). Clippy: `multiple_unsafe_ops_per_block`.
+- `unsafe fn` exposed publicly without a documented `# Safety` section in rustdoc.
+- `std::mem::transmute` for anything but lifetime extension on the same layout (and that should usually be `core::mem::transmute_copy` or `bytemuck::cast` if the relayout is well-defined).
+- `std::ptr::read_unaligned` / `write_unaligned` without a comment explaining why aligned access is impossible.
+- `from_raw_parts` / `from_raw_parts_mut` without proving the source pointer's provenance covers the entire slice.
+- `Arc::get_mut_unchecked`, `Box::leak` to bypass ownership, `MaybeUninit::assume_init` on partially-initialized data.
+- `unsafe impl Send`, `unsafe impl Sync` on types containing raw pointers, without a comment naming exactly which interior-mutability rule is upheld.
+- Any `unsafe` block whose justification depends on "in practice this never happens".
+
+## The One-Line Summary
+
+> Wrap once. Prove once. Test under miri. Never let `unsafe` escape.
diff --git a/plugins/omo/skills/programming/references/rust/zero-cost-safety.md b/plugins/omo/skills/programming/references/rust/zero-cost-safety.md
new file mode 100644
index 00000000..876ffa58
--- /dev/null
+++ b/plugins/omo/skills/programming/references/rust/zero-cost-safety.md
@@ -0,0 +1,527 @@
+# Zero-Cost Safety — Zig Ergonomics in Rust
+
+Rust already owns memory safety. This reference adds the patterns that give you Zig's *ergonomic* safety — explicit allocation control, compile-time computation, zero-hidden-cost APIs, bit-level layout, and deterministic cleanup — without leaving the Rust toolchain.
+
+**When to load this file:** arena, allocator, bumpalo, const fn, const generics, comptime, zero-alloc, no-alloc, slice-based API, `#[repr]`, packed struct, bitfield, scopeguard, errdefer, RAII cleanup, Zig-like patterns.
+
+---
+
+## 1. Explicit Allocators — Arena Pattern
+
+Zig passes `allocator: Allocator` to every function. Rust's stable equivalent: arena crates that make allocation scope visible and bulk-freeable.
+
+### bumpalo — The Default Arena
+
+```rust
+use bumpalo::Bump;
+
+fn parse_tokens<'a>(arena: &'a Bump, input: &[u8]) -> Vec<&'a str> {
+ // All allocations go into `arena`. Caller controls lifetime.
+ // When `arena` drops, everything frees in one shot.
+ let token = arena.alloc_str("hello");
+ let slice = arena.alloc_slice_copy(&[1u8, 2, 3]);
+ vec![token] // Vec itself is on heap; contents point into arena
+}
+
+// Usage: caller owns the arena, decides when memory dies.
+let arena = Bump::new();
+let tokens = parse_tokens(&arena, b"...");
+drop(arena); // all arena memory freed, zero individual deallocations
+```
+
+**When to use:** parsers, compilers, game frame allocators, request-scoped web handlers, any hot loop where individual `Box`/`Vec` alloc+free overhead matters.
+
+### typed-arena — Homogeneous Arena
+
+```rust
+use typed_arena::Arena;
+
+struct AstNode { kind: u8, children: Vec<&'static AstNode> } // simplified
+
+let node_arena: Arena<AstNode> = Arena::new();
+let root = node_arena.alloc(AstNode { kind: 0, children: vec![] });
+// All nodes share arena lifetime. No individual free.
+```
+
+**When to use:** tree/graph structures where all nodes have the same type and same lifetime.
+
+### allocator_api (nightly) — Full Zig Parity
+
+```rust
+#![feature(allocator_api)]
+use std::alloc::Global;
+
+// Vec parameterized by allocator — exactly like Zig.
+let v: Vec<u8, &Bump> = Vec::new_in(&arena);
+
+// Custom allocator for tracking, limiting, or redirecting allocation
+struct CountingAlloc { inner: Global, count: AtomicUsize }
+unsafe impl Allocator for CountingAlloc { /* ... */ }
+```
+
+**When to use:** when you need allocator-generic data structures on nightly. For stable code, prefer `bumpalo` directly.
+
+### Decision Tree
+
+```
+Need arena allocation?
+├── All items same type, same lifetime → typed-arena
+├── Mixed types, same lifetime → bumpalo
+├── Need allocator-generic containers → allocator_api (nightly)
+└── Just need fewer allocations → SmallVec / ArrayVec / tinyvec (stack-first)
+```
+
+### Cargo.toml
+
+```toml
+bumpalo = { version = "3", features = ["collections"] }
+typed-arena = "2"
+smallvec = { version = "1", features = ["union", "const_generics"] }
+tinyvec = { version = "1", features = ["alloc"] }
+```
+
+---
+
+## 2. Compile-Time Computation — const fn, const generics, proc macros
+
+Zig's `comptime` runs arbitrary code at compile time. Rust splits this across three mechanisms.
+
+### const fn — Compile-Time Pure Functions
+
+```rust
+const fn fibonacci(n: usize) -> usize {
+ match n {
+ 0 => 0,
+ 1 => 1,
+ _ => fibonacci(n - 1) + fibonacci(n - 2),
+ }
+}
+
+const FIB_20: usize = fibonacci(20); // computed at compile time: 6765
+
+// Use in array sizes
+const LOOKUP: [u8; 256] = {
+ let mut table = [0u8; 256];
+ let mut i = 0;
+ while i < 256 {
+ table[i] = (i as u8).wrapping_mul(7);
+ i += 1;
+ }
+ table
+};
+```
+
+**Stable since Rust 1.82:** `const fn` supports `match`, loops, `if`, references, mutable locals — nearly full Rust. Use `const { }` blocks (Rust 1.79+) for inline compile-time assertions.
+
+```rust
+fn process<const N: usize>(data: &[u8; N]) {
+ const { assert!(N > 0, "N must be positive") }; // compile-time panic if N == 0
+ // ...
+}
+```
+
+### const generics — Type-Level Values
+
+```rust
+struct Buffer<const N: usize> {
+ data: [u8; N],
+ len: usize,
+}
+
+impl<const N: usize> Buffer<N> {
+ const fn new() -> Self {
+ Self { data: [0; N], len: 0 }
+ }
+
+ fn push(&mut self, byte: u8) -> Result<(), BufferFullError> {
+ if self.len >= N { return Err(BufferFullError); }
+ self.data[self.len] = byte;
+ self.len += 1;
+ Ok(())
+ }
+}
+
+// Compiler enforces: Buffer<16> and Buffer<32> are distinct types.
+let small: Buffer<16> = Buffer::new();
+let large: Buffer<1024> = Buffer::new();
+```
+
+### proc macros — Code Generation (Zig comptime type creation)
+
+When `const fn` is not enough (generating struct fields, impl blocks, or derive logic), proc macros fill the gap.
+
+```rust
+// In a proc-macro crate:
+use proc_macro::TokenStream;
+use quote::quote;
+use syn::{parse_macro_input, DeriveInput};
+
+#[proc_macro_derive(Builder)]
+pub fn derive_builder(input: TokenStream) -> TokenStream {
+ let input = parse_macro_input!(input as DeriveInput);
+ let name = &input.ident;
+ // ... generate builder struct and impl
+ TokenStream::from(quote! {
+ impl #name {
+ pub fn builder() -> #name##Builder { /* ... */ }
+ }
+ })
+}
+```
+
+**Decision tree:**
+
+```
+Need compile-time value computation? → const fn
+Need type parameterized by value? → const generics
+Need to generate new types/impls? → proc macro (derive or attribute)
+Need compile-time string processing? → proc macro
+Need typenum-level arithmetic? → typenum / generic-array (rare)
+```
+
+---
+
+## 3. Zero-Allocation API Design — No Hidden Costs
+
+Zig's philosophy: no operator overloading, no hidden allocation, every cost visible. Rust achieves this with discipline.
+
+### Slice-Based APIs — Caller Owns Memory
+
+```rust
+// BAD: hidden allocation in return type
+fn process(input: &str) -> String {
+ input.to_uppercase() // allocates
+}
+
+// GOOD: caller provides output buffer, zero allocation
+fn process(input: &[u8], output: &mut [u8]) -> usize {
+ let len = input.len().min(output.len());
+ for i in 0..len {
+ output[i] = input[i].to_ascii_uppercase();
+ }
+ len // returns bytes written
+}
+
+// GOOD: return borrowed data when possible
+fn find_token<'a>(input: &'a str) -> Option<&'a str> {
+ input.split_whitespace().next() // no allocation — borrows from input
+}
+```
+
+### try_* APIs — Fallible Allocation
+
+```rust
+// Allocation can fail explicitly (like Zig's allocator returning error)
+let mut v = Vec::new();
+v.try_reserve(1_000_000)?; // returns Result, not panic
+
+// For Box:
+let b = Box::try_new(42)?; // nightly, or use allocator_api
+```
+
+### SmallVec / ArrayVec — Stack-First Collections
+
+```rust
+use smallvec::SmallVec;
+use arrayvec::ArrayVec;
+
+// SmallVec: stack for small counts, heap spillover for large
+let mut tags: SmallVec<[u8; 8]> = SmallVec::new();
+tags.push(1); // on stack if <= 8 elements
+
+// ArrayVec: purely stack, fixed capacity, no heap ever
+let mut buf: ArrayVec<u8, 64> = ArrayVec::new();
+buf.try_push(42).map_err(|_| "full")?; // returns error instead of panic
+```
+
+### Cow — Defer Allocation Until Mutation
+
+```rust
+use std::borrow::Cow;
+
+fn normalize(input: &str) -> Cow<'_, str> {
+ if input.contains('\t') {
+ Cow::Owned(input.replace('\t', " ")) // allocates only when needed
+ } else {
+ Cow::Borrowed(input) // zero-cost pass-through
+ }
+}
+```
+
+### The #![no_std] Discipline
+
+For maximum allocation control, go `#![no_std]`:
+
+```rust
+#![no_std]
+extern crate alloc; // opt-in to heap when needed
+
+use alloc::vec::Vec; // explicit: I chose to allocate
+use alloc::string::String; // explicit: I chose to allocate
+```
+
+Even in `std` code, the *mindset* applies: prefer `&[T]` over `Vec<T>` in function signatures, `&str` over `String`, `&Path` over `PathBuf`.
+
+### Clippy Lints for Hidden Allocations
+
+```toml
+# Cargo.toml — catch accidental allocations
+[lints.clippy]
+# These warn on patterns that allocate when a borrow would suffice:
+unnecessary_to_owned = "warn" # .to_string() / .to_vec() when borrow works
+redundant_clone = "warn" # .clone() that's immediately consumed
+large_stack_arrays = "warn" # accidental large stack usage
+vec_init_then_push = "warn" # Vec::new() + push instead of vec![]
+```
+
+---
+
+## 4. Bit-Level Layout — repr, Packed Structs, Bitfields
+
+Zig: `packed struct` with bit-level field control. Rust matches with `#[repr]` attributes and bitfield crates.
+
+### #[repr(C)] — Guaranteed C-Compatible Layout
+
+```rust
+#[repr(C)]
+struct Header {
+ magic: [u8; 4],
+ version: u16,
+ flags: u16,
+ length: u32,
+}
+// Layout is C ABI: fields in declaration order, C padding rules.
+// Safe to transmute from/to byte arrays via zerocopy.
+```
+
+### #[repr(C, packed)] — No Padding
+
+```rust
+#[repr(C, packed)]
+struct WireHeader {
+ tag: u8,
+ length: u16, // NOT aligned to 2-byte boundary
+ checksum: u32,
+}
+// Total size: exactly 7 bytes. No padding.
+// WARNING: taking &self.length is UB if unaligned. Use read_unaligned or zerocopy.
+```
+
+**Safe access pattern:**
+
+```rust
+use std::ptr;
+
+impl WireHeader {
+ fn length(&self) -> u16 {
+ // SAFETY: packed field may be unaligned; ptr::read_unaligned handles this.
+ unsafe { ptr::read_unaligned(ptr::addr_of!(self.length)) }
+ }
+}
+
+// Better: use zerocopy to avoid manual unsafe entirely
+use zerocopy::{FromBytes, IntoBytes, KnownLayout, Immutable};
+
+#[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
+#[repr(C, packed)]
+struct WireHeader {
+ tag: u8,
+ length: [u8; 2], // manual byte array avoids alignment issues
+ checksum: [u8; 4],
+}
+
+impl WireHeader {
+ fn length(&self) -> u16 { u16::from_le_bytes(self.length) }
+ fn checksum(&self) -> u32 { u32::from_le_bytes(self.checksum) }
+}
+```
+
+### bitfield — Bit-Level Flag Packing
+
+```rust
+use bitfield::bitfield;
+
+bitfield! {
+ pub struct Permissions(u8);
+ impl Debug;
+ pub bool, readable, set_readable: 0;
+ pub bool, writable, set_writable: 1;
+ pub bool, executable, set_executable: 2;
+ pub u8, level, set_level: 5, 3; // bits 3-5
+}
+
+let mut p = Permissions(0);
+p.set_readable(true);
+p.set_level(5);
+assert!(p.readable());
+assert_eq!(p.level(), 5);
+```
+
+### modular-bitfield — Richer Bitfield API
+
+```rust
+use modular_bitfield::prelude::*;
+
+#[bitfield(bits = 16)]
+#[derive(Debug)]
+pub struct StatusWord {
+ ready: bool, // 1 bit
+ error_code: B4, // 4 bits
+ #[skip] __: B3, // 3 bits padding
+ priority: B8, // 8 bits
+}
+```
+
+### zerocopy — Safe Zero-Copy Parsing
+
+```rust
+use zerocopy::{FromBytes, IntoBytes, KnownLayout, Immutable, Ref};
+
+#[derive(FromBytes, IntoBytes, KnownLayout, Immutable)]
+#[repr(C)]
+struct Packet {
+ header: [u8; 4],
+ payload_len: u32,
+}
+
+fn parse(bytes: &[u8]) -> Option<&Packet> {
+ Ref::<_, Packet>::from_prefix(bytes).map(|(pkt, _rest)| pkt.into_ref()).ok()
+}
+// Zero-copy, zero-allocation, fully safe. No transmute, no pointer cast.
+```
+
+### Cargo.toml
+
+```toml
+zerocopy = { version = "0.8", features = ["derive"] }
+bitfield = "0.17"
+modular-bitfield = "0.11"
+bytemuck = { version = "1", features = ["derive"] } # alternative to zerocopy
+```
+
+---
+
+## 5. Scope Guards — errdefer / Deterministic Cleanup
+
+Zig's `errdefer` runs cleanup only on error paths. Rust's `Drop` always runs, but `scopeguard` gives fine-grained control.
+
+### scopeguard — The errdefer Equivalent
+
+```rust
+use scopeguard::{defer, guard};
+use std::fs;
+
+fn create_and_process(path: &str) -> std::io::Result<()> {
+ let file = fs::File::create(path)?;
+ // If anything below fails, clean up the file.
+ // This is exactly Zig's errdefer.
+ let _cleanup = guard((), |_| {
+ let _ = fs::remove_file(path);
+ });
+
+ write_data(&file)?;
+ validate_data(path)?;
+
+ // Success: defuse the guard so it does NOT run cleanup.
+ std::mem::forget(_cleanup);
+ Ok(())
+}
+```
+
+### defer! — Always-Run Cleanup (like Zig's defer)
+
+```rust
+use scopeguard::defer;
+
+fn with_temp_dir() -> anyhow::Result<()> {
+ let dir = tempfile::tempdir()?;
+ defer! {
+ // Runs when scope exits, success or failure.
+ println!("Cleaning up {}", dir.path().display());
+ // dir's Drop also cleans up, but this shows the pattern.
+ }
+
+ do_work(dir.path())?;
+ Ok(())
+}
+```
+
+### Drop as RAII Cleanup
+
+```rust
+struct TempFile { path: std::path::PathBuf }
+
+impl TempFile {
+ fn new(path: impl Into<std::path::PathBuf>) -> std::io::Result<Self> {
+ let path = path.into();
+ std::fs::File::create(&path)?;
+ Ok(Self { path })
+ }
+}
+
+impl Drop for TempFile {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.path);
+ }
+}
+
+// Usage: file is auto-cleaned when `tmp` goes out of scope.
+let tmp = TempFile::new("/tmp/scratch.dat")?;
+```
+
+### The errdefer Pattern — Defuse on Success
+
+The key insight from Zig's `errdefer`: you want cleanup on error but NOT on success. In Rust:
+
+```rust
+use scopeguard::ScopeGuard;
+
+fn deploy(artifact: &Path) -> Result<(), DeployError> {
+ let backup = backup_current()?;
+
+ // errdefer: restore backup if anything fails
+ let rollback = guard(backup.clone(), |b| {
+ let _ = restore_from_backup(&b);
+ });
+
+ upload(artifact)?;
+ health_check()?;
+
+ // Success path: defuse the rollback guard
+ ScopeGuard::into_inner(rollback);
+ Ok(())
+}
+```
+
+### Cargo.toml
+
+```toml
+scopeguard = "1"
+tempfile = "3" # idiomatic RAII temp files/dirs
+```
+
+---
+
+## Summary: Zig Advantage → Rust Pattern
+
+| Zig Feature | Rust Equivalent | Difficulty | Reference |
+|---|---|---|---|
+| Explicit allocator passing | `bumpalo` / `typed-arena` / `allocator_api` | Easy | §1 |
+| `comptime` value computation | `const fn` + `const { }` blocks | Easy | §2 |
+| `comptime` type generation | proc macros (derive / attribute) | Medium | §2 |
+| No hidden allocations | `#![no_std]` / slice-based APIs / `Cow` | Style choice | §3 |
+| `packed struct` / bitfields | `#[repr(C, packed)]` / `bitfield` / `zerocopy` | Easy | §4 |
+| `errdefer` | `scopeguard::guard` + defuse on success | Easy | §5 |
+| `defer` | `scopeguard::defer!` / `Drop` | Easy | §5 |
+
+All achievable within Rust's single toolchain. You get Zig's explicitness **plus** the borrow checker, lifetime analysis, trait bounds, and `miri`. The combination is strictly more powerful than either alone.
+
+## When NOT to Use These Patterns
+
+- **Arena allocation** overkill for simple CLI tools that allocate once and exit.
+- **Zero-alloc APIs** hurt readability when the function naturally produces owned data. Don't force `&mut [u8]` output buffers on a function that logically returns `String`.
+- **`#[repr(packed)]`** only for wire formats and FFI. Never for regular domain types.
+- **Scope guards** unnecessary when `Drop` on the value itself handles cleanup (e.g., `tempfile::NamedTempFile` already does this).
+- **`const fn`** everything? No — only when the value is genuinely needed at compile time or the function is trivially const-eligible. Don't contort logic just to be const.
+
+The goal is **visible costs and explicit control**, not asceticism. Use `String` and `Vec` freely when they're the right tool. Reach for these patterns when allocation behavior matters for correctness or performance.
diff --git a/plugins/omo/skills/programming/references/typescript/README.md b/plugins/omo/skills/programming/references/typescript/README.md
new file mode 100644
index 00000000..e71b88fd
--- /dev/null
+++ b/plugins/omo/skills/programming/references/typescript/README.md
@@ -0,0 +1,195 @@
+
+# TypeScript Programmer
+
+Modern TypeScript. Type-strict, stack-first, async-correct.
+
+## Philosophy
+
+The compiler is your proof system. Make illegal states unrepresentable. Parse at boundaries. Every function has a contract; the type system enforces it.
+
+## Hard rules
+
+These are deliberate project choices. Violations are always wrong, not "style preferences".
+
+### Tooling
+
+| Category | Use | Never |
+|---|---|---|
+| Runtime | Bun (native TS, single binary) | ts-node, tsx |
+| Package manager | `pnpm` | npm, yarn (unless workspace requires it) |
+| Linter + formatter | Biome | ESLint, Prettier |
+| Type checker | `tsc --noEmit` with strict config | skip type checking |
+| Web framework | Hono | Express |
+| Validation | Zod | joi, yup, class-validator |
+| Testing | `bun test` or vitest | jest |
+| ORM | Drizzle | TypeORM, Prisma (unless already in project) |
+
+### The iron list
+
+1. **Readonly by default** — all `type`/`interface` properties are `readonly`. Arrays are `readonly T[]`. Mutable only when mutation is the documented purpose.
+2. **Branded types for distinct IDs** — `type UserId = Brand<string, "UserId">`. Never pass raw `string` where a branded type exists.
+3. **Exhaustive switch** — every `switch` on a discriminated union ends with `default: assertNever(x)`. No fall-through.
+4. **No any** — `any` is banned in annotations, returns, and parameters. Use `unknown` and narrow.
+5. **No type assertions** — `as any`, `as unknown` banned. `as const` and `satisfies` are fine.
+6. **No non-null assertion** — `x!` is banned. Use narrowing or optional chaining (`x?.y`).
+7. **No @ts-ignore / @ts-expect-error** — fix the type.
+8. **No enum** — use `as const` objects + literal union types.
+9. **Zod at boundaries** — external input (API, user, file) → Zod schema. Internal → plain types.
+10. **Typed errors** — Error subclasses with typed fields. No `throw new Error("bare string")` for domain errors. Use Result for expected failures within 1-2 call levels; throw for propagation across many layers.
+11. **as const for constants** — module-level constant objects and arrays use `as const`.
+12. **import type** — type-only imports use `import type`. Enforced by `verbatimModuleSyntax`.
+13. **Named exports only** — no `export default`. Exception: framework requirement (Next.js pages, etc.).
+14. **No empty catch, no catch-and-swallow** — every `catch` block must either (a) narrow the error with `instanceof` and handle each case, or (b) re-throw. Empty catch blocks and `catch (e) { console.error(e) }` without narrowing or re-throw are banned — they hide bugs. At top-level boundaries (CLI entry, HTTP handler), opt out with `// no-excuse-ok: catch`.
+
+### Data modeling — which construct, when
+
+| Situation | Use |
+|---|---|
+| User input, API request/response | Zod schema + `z.infer` |
+| Internal value object | `type` with `readonly` properties |
+| Function with multiple outcomes | Discriminated union (`kind` field) |
+| Contract for implementations | `interface` |
+| Fixed constants | `as const` + literal union |
+| Distinct primitive (UserId vs OrderId) | Branded type |
+| Key-value map | `Record<K, V>` or index signature |
+
+**The one rule**: data crosses trust boundary → Zod. Everything else → plain `type` with `readonly`.
+
+Load `data-modeling.md` for the full decision flowchart and comparison.
+
+### When readonly does not apply
+
+- **Framework state** (React `useState`, signals) — managed by framework.
+- **Builder / accumulator** — object exists to be mutated (buffer, cache). Document why.
+- **ORM mutations** — Drizzle insert/update objects.
+
+### Why empty/unhandled catch is banned
+
+In TypeScript, every `catch` receives `unknown`. The language gives you no type safety in catch blocks — you must earn it with `instanceof`. A bare `catch (e) { console.error(e) }` swallows `TypeError`, `RangeError`, and your domain errors identically. When a new error type appears, nothing warns you.
+
+```typescript
+// BANNED — empty catch
+try { await fetchData() } catch {}
+try { await fetchData() } catch (e) { /* will fix later */ }
+
+// BANNED — catch-and-swallow (no narrowing, no rethrow)
+try {
+ const data = await api.get("/users")
+} catch (e) {
+ console.error("failed", e)
+}
+
+// GOOD — narrow with instanceof
+try {
+ const data = await api.get("/users")
+} catch (e) {
+ if (e instanceof HttpError) {
+ logger.warn(`API ${e.status}: ${e.message}`)
+ return fallback
+ }
+ throw e // unknown errors propagate
+}
+
+// GOOD — top-level boundary (only place catch-all is acceptable)
+async function main(): Promise<void> { // no-excuse-ok: catch
+ try {
+ await run()
+ } catch (e) {
+ console.error("unhandled:", e)
+ process.exit(1)
+ }
+}
+```
+
+### Libraries
+
+| Domain | Library | Why |
+|---|---|---|
+| HTTP framework | Hono | Lightweight, multi-runtime, middleware, OpenAPI |
+| Validation | Zod | Runtime validation + type inference |
+| ORM | Drizzle | Type-safe SQL, no codegen |
+| HTTP client | `ky` | Thin fetch wrapper (5KB); auto-throw on non-2xx, retry, timeout, hooks, prefixUrl. Browser + Node + Bun + Deno |
+| HTTP client (perf) | `undici` (direct API) | Node backend에서 connection pooling, HTTP/2, pipelining 필요 시 |
+
+> **HTTP client 규칙** — 프로덕션 코드에서 bare `fetch()`는 사용 금지. retry·timeout·에러 핸들링이 전무하여 장애 시 silent failure를 유발한다. **`ky`** 를 기본으로 설치하고, Node backend에서 대량 요청·커넥션 풀·HTTP/2 파이프라이닝이 필요하면 **`undici`** direct API를 쓴다. ~~`axios`~~ 는 supply-chain compromise(2026-03) 이후 사용 금지. `node-fetch`는 Node 18+ 내장 fetch로 대체되어 불필요.
+| Testing | `bun test` / vitest | Fast, ESM-native |
+| Logging | `pino` | Structured JSON, fast |
+| CLI | `@clack/prompts` + `commander` | Interactive + parsing |
+
+## tsconfig — the one true config
+
+Scaffold a new project with all strict defaults pre-configured:
+
+```bash
+bun run ../../scripts/typescript/new-project.ts my-api
+bun run ../../scripts/typescript/new-project.ts my-api --path ./projects
+```
+
+Creates: `package.json` (Hono + Zod + Biome), `tsconfig.json` (ultra-strict), `biome.json`, `src/index.ts`, `.gitignore`. Works on macOS, Linux, Windows.
+
+For manual setup: `bunx tsc --init`, then load `tsconfig-strict.md` for the full strict config.
+
+Key flags beyond `"strict": true`:
+
+| Flag | What it catches |
+|---|---|
+| `noUncheckedIndexedAccess` | `arr[0]` is `T \| undefined`, forces check |
+| `exactOptionalPropertyTypes` | `{ x?: string }` ≠ `{ x: string \| undefined }` |
+| `verbatimModuleSyntax` | Forces `import type` for type-only imports |
+| `noFallthroughCasesInSwitch` | Forgotten `break` / `return` |
+| `noPropertyAccessFromIndexSignature` | `.key` on index sig → bracket notation |
+
+## Reference loading
+
+Load on demand — not all at once.
+
+| Need | Load |
+|---|---|
+| Strict tsconfig + Biome config | `tsconfig-strict.md` |
+| Type patterns (branded, as const, satisfies, narrowing, assertNever) | `type-patterns.md` |
+| Data modeling (type vs interface vs Zod, readonly, parse-don't-validate) | `data-modeling.md` |
+| Error handling (Result, typed errors, union vs throw) | `error-handling.md` |
+| Bootstrapping a new project (Bun, pnpm, Hono, Vite) | `bootstrap.md` |
+| Hono backend stack (hono-openapi, Scalar, Swagger) | `backend-hono.md` |
+
+## No-excuse audit
+
+Violations caught by `../../scripts/typescript/check-no-excuse-rules.ts`. Run after every edit session.
+
+| Rule ID | Catches | Opt-out |
+|---|---|---|
+| `no-any-assertion` | `as any` | None — redesign types |
+| `no-unknown-assertion` | `as unknown` | None — redesign types |
+| `no-ts-ignore` | `@ts-ignore` | None — fix the type |
+| `no-ts-expect-error` | `@ts-expect-error` | None — fix the type |
+| `no-enum` | `enum` declarations | None — use `as const` |
+| `no-non-null-assertion` | `x!` postfix | None — narrow or `?.` |
+| `no-throw-literal` | `throw "string"` / `throw 123` | None — throw Error subclass |
+| `no-mutable-export` | `export let` / `export var` | None — use `export const` |
+| `no-any-annotation` | `: any` in parameter/return/variable types | `// no-excuse-ok: any` |
+| `no-explicit-any-return` | `(): any` or `(): Promise<any>` return types | `// no-excuse-ok: any` |
+| `empty-catch` | `catch { }` or `catch (e) { }` with empty body | `// no-excuse-ok: catch` |
+| `catch-without-narrowing` | `catch (e)` used without `instanceof` or re-throw | `// no-excuse-ok: catch` |
+
+Biome enforces additional rules (noExplicitAny, noNonNullAssertion, noDefaultExport, useImportType). The script catches what Biome cannot.
+
+## In tests
+
+Tests are strict too, with these exceptions (configure in `biome.jsonc` overrides):
+
+| In tests you may | Why |
+|---|---|
+| Use `expect()` assertions | That's how testing works |
+| Use magic numbers | Test data |
+| Access private members via bracket notation | Testing internals |
+| Skip readonly on test fixtures | Mutable setup/teardown |
+
+Tests still follow the iron list — branded types, typed errors, exhaustive switch.
+
+## Existing codebases
+
+When editing an existing file that doesn't follow these rules: **write new code in strict style, don't refactor existing code in the same change.**
+
+## Activation
+
+This skill activates whenever you are writing or modifying any `.ts` or `.tsx` file. Even one-off scripts get the strict treatment.
diff --git a/plugins/omo/skills/programming/references/typescript/backend-hono.md b/plugins/omo/skills/programming/references/typescript/backend-hono.md
new file mode 100644
index 00000000..821754fd
--- /dev/null
+++ b/plugins/omo/skills/programming/references/typescript/backend-hono.md
@@ -0,0 +1,672 @@
+# Hono Backend Stack Reference (2026)
+
+> **Canonical stack**: `hono` + `hono-openapi` + `@scalar/hono-api-reference` + `@hono/swagger-ui`
+> **Runtime**: Bun (TypeScript-first)
+> **Validator**: Zod v4 (Standard Schema compliant, zero extra deps for OpenAPI)
+
+---
+
+## 1. Package Versions (Latest Stable)
+
+| Package | Version | Source |
+|---------|---------|--------|
+| `hono` | `^4.12.5` | [peer dep of scalar](https://github.com/scalar/scalar/blob/8bcf8bf52a0da667d44eeec08648e3b1da044f97/integrations/hono/package.json#L66) |
+| `hono-openapi` | `^1.3.0` | [npm](https://registry.npmjs.org/hono-openapi) — published Mar 2, 2026 |
+| `@scalar/hono-api-reference` | `^0.10.11` | [npm](https://www.npmjs.com/package/@scalar/hono-api-reference) — published Apr 28, 2026 |
+| `@hono/swagger-ui` | `^0.6.1` | [npm](https://www.npmjs.com/package/@hono/swagger-ui) — published Apr 2026 |
+| `zod` | `^4.4.1` | [npm registry](https://registry.npmjs.org/zod) — latest stable v4 |
+
+### `package.json` dependency block
+
+```json
+{
+ "dependencies": {
+ "hono": "^4.12.5",
+ "hono-openapi": "^1.3.0",
+ "@scalar/hono-api-reference": "^0.10.11",
+ "@hono/swagger-ui": "^0.6.1",
+ "zod": "^4.4.1"
+ },
+ "devDependencies": {
+ "typescript": "^5.8.0",
+ "@types/bun": "latest"
+ }
+}
+```
+
+> **Peer dependencies auto-installed by `hono-openapi`**:
+> - `@hono/standard-validator@^0.2.0`
+> - `@standard-community/standard-json@^0.3.5`
+> - `@standard-community/standard-openapi@^0.2.9`
+> - `openapi-types@^12.1.3`
+>
+> [Source: `hono-openapi/package.json` peerDependencies](https://github.com/rhinobase/hono-openapi/blob/10f45a66ede3764b5e6065805fb60fd5df090466/package.json#L50-L65)
+
+---
+
+## 2. Complete `app.ts` — Copy-Pasteable
+
+```typescript
+import { Hono } from 'hono'
+import { describeRoute, openAPIRouteHandler, resolver, validator } from 'hono-openapi'
+import { Scalar } from '@scalar/hono-api-reference'
+import { swaggerUI } from '@hono/swagger-ui'
+import { z } from 'zod'
+
+// ───────────────────────────────────────────────────────────────
+// 1. Schema definitions (Zod v4 — Standard Schema native)
+// ───────────────────────────────────────────────────────────────
+
+const QuerySchema = z.object({
+ name: z.string().optional(),
+})
+
+const ResponseSchema = z.object({
+ message: z.string(),
+})
+
+const JsonBodySchema = z.object({
+ name: z.string(),
+ age: z.number().int().min(0),
+})
+
+// ───────────────────────────────────────────────────────────────
+// 2. Hono app with described routes
+// ───────────────────────────────────────────────────────────────
+
+const app = new Hono()
+
+// Health check (no validation)
+app.get('/health', (c) => c.json({ status: 'ok' }))
+
+// A fully-documented route
+app.get(
+ '/hello',
+ describeRoute({
+ tags: ['Greetings'],
+ summary: 'Say hello',
+ description: 'Returns a greeting message',
+ responses: {
+ 200: {
+ description: 'Successful greeting',
+ content: {
+ 'application/json': {
+ schema: resolver(ResponseSchema),
+ },
+ },
+ },
+ },
+ }),
+ validator('query', QuerySchema),
+ (c) => {
+ const query = c.req.valid('query')
+ return c.json({ message: `Hello ${query.name ?? 'Hono'}!` })
+ },
+)
+
+// A POST route with JSON body validation
+app.post(
+ '/users',
+ describeRoute({
+ tags: ['Users'],
+ summary: 'Create a user',
+ responses: {
+ 200: {
+ description: 'User created',
+ content: {
+ 'application/json': {
+ schema: resolver(ResponseSchema),
+ },
+ },
+ },
+ },
+ }),
+ validator('json', JsonBodySchema),
+ (c) => {
+ const body = c.req.valid('json')
+ return c.json({ message: `Created user ${body.name}` })
+ },
+)
+
+// ───────────────────────────────────────────────────────────────
+// 3. OpenAPI spec endpoint
+// ───────────────────────────────────────────────────────────────
+
+app.get(
+ '/openapi.json',
+ openAPIRouteHandler(app, {
+ documentation: {
+ info: {
+ title: 'Hono API',
+ version: '1.0.0',
+ description: 'Example Hono API with OpenAPI',
+ },
+ servers: [
+ { url: 'http://localhost:3000', description: 'Local server' },
+ ],
+ },
+ }),
+)
+
+// ───────────────────────────────────────────────────────────────
+// 4. Scalar API Reference UI
+// ───────────────────────────────────────────────────────────────
+
+app.get(
+ '/scalar',
+ Scalar({
+ url: '/openapi.json',
+ theme: 'saturn',
+ pageTitle: 'Hono API Reference',
+ }),
+)
+
+// ───────────────────────────────────────────────────────────────
+// 5. Swagger UI (parallel mount)
+// ───────────────────────────────────────────────────────────────
+
+app.get(
+ '/swagger',
+ swaggerUI({
+ url: '/openapi.json',
+ title: 'Swagger UI',
+ }),
+)
+
+// ───────────────────────────────────────────────────────────────
+// 6. Bun canonical entrypoint
+// ───────────────────────────────────────────────────────────────
+
+export default app
+```
+
+---
+
+## 3. `hono-openapi` API Reference
+
+### Import paths
+
+**There is only one import path.** `hono-openapi` exports everything from its root:
+
+```typescript
+import {
+ describeRoute, // middleware to annotate a route with OpenAPI metadata
+ describeResponse, // attach response schemas directly to a handler
+ validator, // validation middleware (wraps @hono/standard-validator)
+ resolver, // wrap a Zod/Valibot/etc schema for OpenAPI responses
+ openAPIRouteHandler, // serve the generated OpenAPI JSON document
+ generateSpecs, // programmatically generate the spec (for build-time caching)
+} from 'hono-openapi'
+```
+
+**Evidence** ([`src/index.ts`](https://github.com/rhinobase/hono-openapi/blob/10f45a66ede3764b5e6065805fb60fd5df090466/src/index.ts#L1-L9)):
+
+```typescript
+export { generateSpecs, openAPIRouteHandler } from "./handler.js";
+export {
+ describeResponse,
+ describeRoute,
+ loadVendor,
+ resolver,
+ validator,
+} from "./middlewares.js";
+```
+
+> **No subpath exports** such as `hono-openapi/zod` or `hono-openapi/valibot`. The package uses Standard Schema and auto-detects the validator vendor.
+
+### `describeRoute()` middleware
+
+Attach OpenAPI metadata to any Hono route. Use `resolver()` for response body schemas.
+
+```typescript
+app.get(
+ '/path',
+ describeRoute({
+ tags: ['Users'],
+ summary: 'Get user',
+ description: 'Retrieve a single user by ID',
+ responses: {
+ 200: {
+ description: 'User found',
+ content: {
+ 'application/json': {
+ schema: resolver(UserSchema),
+ },
+ },
+ },
+ 404: {
+ description: 'User not found',
+ },
+ },
+ }),
+ handler,
+)
+```
+
+**Evidence** ([`src/middlewares.ts`](https://github.com/rhinobase/hono-openapi/blob/10f45a66ede3764b5e6065805fb60fd5df090466/src/middlewares.ts#L244-L254)):
+
+```typescript
+export function describeRoute(spec: DescribeRouteOptions): MiddlewareHandler {
+ const middleware: MiddlewareHandler = async (_c, next) => {
+ await next();
+ };
+ return Object.assign(middleware, {
+ [uniqueSymbol]: { spec },
+ });
+}
+```
+
+### `validator()` middleware
+
+Validates `query`, `json`, `param`, or `form` and **automatically** injects the request schema into the OpenAPI document. No manual `request` block in `describeRoute()` is required.
+
+```typescript
+validator('query', QuerySchema) // ?name=foo
+validator('json', JsonBodySchema) // POST body
+validator('param', ParamSchema) // /users/:id
+validator('form', FormSchema) // multipart/form-data
+```
+
+**Evidence** ([`src/middlewares.ts`](https://github.com/rhinobase/hono-openapi/blob/10f45a66ede3764b5e6065805fb60fd5df090466/src/middlewares.ts#L199-L237)):
+
+```typescript
+export function validator<Schema extends StandardSchemaV1, ...>(
+ target: Target,
+ schema: Schema,
+ hook?: Hook<...>,
+ options?: ResolverReturnType["options"],
+): MiddlewareHandler<E, P, V> {
+ const middleware = sValidator(target, schema, hook);
+ return Object.assign(middleware, {
+ [uniqueSymbol]: { target, ...resolver(schema, options), options },
+ });
+}
+```
+
+### `openAPIRouteHandler()` — serving the spec
+
+```typescript
+app.get(
+ '/openapi.json',
+ openAPIRouteHandler(app, {
+ documentation: {
+ info: { title: 'Hono API', version: '1.0.0' },
+ servers: [{ url: 'http://localhost:3000' }],
+ },
+ }),
+)
+```
+
+**Evidence** ([`src/handler.ts`](https://github.com/rhinobase/hono-openapi/blob/10f45a66ede3764b5e6065805fb60fd5df090466/src/handler.ts#L42-L59)):
+
+```typescript
+export function openAPIRouteHandler<...>(
+ hono: Hono<E, S, P>,
+ options?: Partial<GenerateSpecOptions>,
+): MiddlewareHandler<E, P, I> {
+ let specs: OpenAPIV3_1.Document;
+ return async (c) => {
+ if (specs) return c.json(specs);
+ specs = await generateSpecs(hono, options, c);
+ return c.json(specs);
+ };
+}
+```
+
+> **Mount path convention**: `/openapi.json` is the most common. Some projects use `/openapi/spec.json` (e.g. [NamesMT/starter-monorepo](https://github.com/NamesMT/starter-monorepo/blob/main/apps/backend/src/openAPI.ts)).
+
+---
+
+## 4. `@scalar/hono-api-reference` Setup
+
+### Import path and package name
+
+```typescript
+import { Scalar } from '@scalar/hono-api-reference'
+```
+
+> **Deprecated**: `apiReference` is still exported but deprecated in favor of `Scalar` ([PR #5297](https://github.com/scalar/scalar/pull/5297)).
+
+**Evidence** ([`integrations/hono/src/index.ts`](https://github.com/scalar/scalar/blob/8bcf8bf52a0da667d44eeec08648e3b1da044f97/integrations/hono/src/index.ts#L1-L9)):
+
+```typescript
+import { Scalar } from './scalar'
+export {
+ Scalar,
+ /**
+ * @deprecated Use `Scalar` instead.
+ */
+ Scalar as apiReference,
+}
+```
+
+### Mount path convention
+
+Common choices:
+- `/scalar` — matches the middleware name
+- `/docs` — generic documentation endpoint
+- `/openapi/ui` — nested under the OpenAPI prefix
+
+### Configuration options
+
+The Hono middleware accepts the **universal Scalar configuration** plus Hono-specific overrides (`pageTitle`, `cdn`).
+
+```typescript
+app.get('/scalar', Scalar({
+ // ── Source (required) ──
+ url: '/openapi.json', // URL to the OpenAPI spec
+
+ // ── Appearance ──
+ theme: 'saturn', // 'alternate' | 'default' | 'moon' | 'purple'
+ // | 'solarized' | 'bluePlanet' | 'deepSpace'
+ // | 'saturn' | 'kepler' | 'elysiajs' | 'fastify'
+ // | 'mars' | 'laserwave' | 'none'
+ pageTitle: 'My API Docs', // HTML <title>
+ customCss: '.sidebar { ... }', // injected <style> block
+ metaData: { title: '...' }, // SEO meta tags (unhead format)
+ favicon: '/favicon.svg',
+
+ // ── Behavior ──
+ layout: 'modern', // 'modern' | 'classic'
+ darkMode: true,
+ forceDarkModeState: 'dark', // 'dark' | 'light'
+ hideDarkModeToggle: false,
+ hideModels: false,
+ hideSearch: false,
+ hideTestRequestButton: false,
+ showOperationId: false,
+ showSidebar: true,
+
+ // ── Proxy / Server ──
+ proxyUrl: 'https://proxy.scalar.com',
+ baseServerURL: 'http://localhost:3000',
+ servers: [{ url: 'http://localhost:3000' }],
+
+ // ── CDN ──
+ cdn: 'https://cdn.jsdelivr.net/npm/@scalar/api-reference',
+
+ // ── Advanced ──
+ authentication: { ... },
+ hiddenClients: ['unirest'],
+ defaultHttpClient: { targetKey: 'js', clientKey: 'fetch' },
+ plugins: [...],
+ pathRouting: { basePath: '/reference' },
+ mcp: { name: 'My MCP', url: '...' },
+}))
+```
+
+**Evidence** — Scalar types define the full schema:
+- [Base configuration (themes, proxy, etc.)](https://github.com/scalar/scalar/blob/8bcf8bf52a0da667d44eeec08648e3b1da044f97/packages/types/src/api-reference/base-configuration.ts#L110-L129)
+- [HTML rendering configuration (`pageTitle`, `cdn`)](https://github.com/scalar/scalar/blob/8bcf8bf52a0da667d44eeec08648e3b1da044f97/packages/types/src/api-reference/html-rendering-configuration.ts#L8-L23)
+- [Source configuration (`url`, `content`)](https://github.com/scalar/scalar/blob/8bcf8bf52a0da667d44eeec08648e3b1da044f97/packages/types/src/api-reference/source-configuration.ts#L8-L55)
+- [Full API reference configuration](https://github.com/scalar/scalar/blob/8bcf8bf52a0da667d44eeec08648e3b1da044f97/packages/types/src/api-reference/api-reference-configuration.ts#L22-L379)
+
+### Dynamic configuration (request-aware)
+
+```typescript
+app.get('/scalar', Scalar((c) => ({
+ url: '/openapi.json',
+ proxyUrl: c.env.ENVIRONMENT === 'development'
+ ? 'https://proxy.scalar.com'
+ : undefined,
+})))
+```
+
+**Evidence** ([`integrations/hono/src/scalar.ts`](https://github.com/scalar/scalar/blob/8bcf8bf52a0da667d44eeec08648e3b1da044f97/integrations/hono/src/scalar.ts#L75-L94)):
+
+```typescript
+export const Scalar = <E extends Env>(configOrResolver: Configuration<E>): MiddlewareHandler<E> => {
+ return async (c) => {
+ let resolvedConfig: Partial<ApiReferenceConfiguration> = {}
+ if (typeof configOrResolver === 'function') {
+ resolvedConfig = await configOrResolver(c)
+ } else {
+ resolvedConfig = configOrResolver
+ }
+ // ...
+ }
+}
+```
+
+---
+
+## 5. `@hono/swagger-ui` Setup
+
+### Import path and package name
+
+```typescript
+import { swaggerUI } from '@hono/swagger-ui'
+```
+
+**Evidence** ([`packages/swagger-ui/src/index.ts`](https://github.com/honojs/middleware/blob/eb443a2fbda674bbe12d3f30e96854bb0cad6232/packages/swagger-ui/src/index.ts#L93)):
+
+```typescript
+export { middleware as swaggerUI, SwaggerUI }
+```
+
+### Mount path convention
+
+Common choices:
+- `/swagger` — explicit
+- `/ui` — used in Hono official examples
+- `/docs` — generic
+
+### Configuration options
+
+```typescript
+app.get('/swagger', swaggerUI({
+ url: '/openapi.json', // URL to the OpenAPI spec (required)
+ title: 'Swagger UI', // HTML page title
+ version: 'latest', // Swagger UI CDN version
+ // Any standard Swagger UI option also works:
+ // presets, plugins, urls, etc.
+}))
+```
+
+**Evidence** ([`packages/swagger-ui/src/index.ts`](https://github.com/honojs/middleware/blob/eb443a2fbda674bbe12d3f30e96854bb0cad6232/packages/swagger-ui/src/index.ts#L8-L43)):
+
+```typescript
+type SwaggerUIOptions = OriginalSwaggerUIOptions & DistSwaggerUIOptions
+
+const middleware = <E extends Env>(options: SwaggerUIOptions): MiddlewareHandler<E> =>
+ async (c) => {
+ const title = options?.title ?? 'SwaggerUI'
+ return c.html(/* html */ `...`)
+ }
+```
+
+---
+
+## 6. Bun Runtime Entrypoint
+
+### Canonical shape for `bun run`
+
+```typescript
+import { Hono } from 'hono'
+
+const app = new Hono()
+// ... routes ...
+
+export default app
+```
+
+**Evidence** ([Hono Bun docs](https://hono.dev/docs/getting-started/bun)):
+
+> ```ts
+> import { Hono } from 'hono'
+> const app = new Hono()
+> app.get('/', (c) => c.text('Hello Bun!'))
+> export default app
+> ```
+
+### Custom port
+
+```typescript
+export default {
+ port: 3000,
+ fetch: app.fetch,
+}
+```
+
+**Evidence** ([Hono Bun docs — Change port number](https://hono.dev/docs/getting-started/bun)):
+
+> ```ts
+> export default {
+> port: 3000,
+> fetch: app.fetch,
+> }
+> ```
+
+### `package.json` scripts for Bun
+
+```json
+{
+ "scripts": {
+ "dev": "bun run --hot src/index.ts",
+ "start": "bun run src/index.ts",
+ "build": "tsc --noEmit"
+ }
+}
+```
+
+---
+
+## 7. OpenAPI Version
+
+### `hono-openapi` emits **OpenAPI 3.1.0** by default
+
+This is **hardcoded** in the source and **not configurable** at runtime:
+
+**Evidence** ([`src/handler.ts` line 120](https://github.com/rhinobase/hono-openapi/blob/10f45a66ede3764b5e6065805fb60fd5df090466/src/handler.ts#L120)):
+
+```typescript
+return {
+ openapi: "3.1.0",
+ ..._documentation,
+ // ...
+} satisfies OpenAPIV3_1.Document;
+```
+
+> If you need OpenAPI 3.0.x, you must post-process the generated spec or use `@hono/zod-openapi` (the older package) instead. The user explicitly requested `hono-openapi`, so document that 3.1.0 is the only output.
+
+---
+
+## 8. Zod v3 vs Zod v4
+
+| Feature | Zod v3 | Zod v4 |
+|---------|--------|--------|
+| Standard Schema | ❌ No | ✅ Yes (native) |
+| `hono-openapi` extra deps | `zod-openapi@4` | None |
+| Import path | `import { z } from 'zod'` | `import { z } from 'zod'` (or `zod/v4` for explicit) |
+
+**For Zod v3 users**, install the compatibility layer:
+
+```bash
+npm install zod-openapi@4
+```
+
+Then use `zod-openapi`'s `.openapi()` for metadata and `.meta({ ref: 'Name' })` for component references. `hono-openapi`'s `resolver()` will still work, but the underlying schema conversion relies on `zod-openapi@4`.
+
+**Evidence** ([HonoHub Zod docs](https://honohub.dev/docs/openapi/zod)):
+
+> "For zod v3, you can use the `zod-openapi` library. You need to install `zod-openapi@4` for this to work properly."
+
+**For Zod v4 users** (recommended in 2026), no extra packages are needed. `z.date()` is automatically converted to `{ type: 'string', format: 'date-time' }`.
+
+**Evidence** ([`src/middlewares.ts` Zod v4 date override](https://github.com/rhinobase/hono-openapi/blob/10f45a66ede3764b5e6065805fb60fd5df090466/src/middlewares.ts#L63-L71)):
+
+```typescript
+const zodV4DateOverride = (ctx: { ... }) => {
+ if (ctx.zodSchema._zod.def.type === "date") {
+ ctx.jsonSchema.type = "string";
+ ctx.jsonSchema.format = "date-time";
+ }
+};
+```
+
+---
+
+## 9. Real-World Example
+
+**NamesMT/starter-monorepo** — a public monorepo starter using `hono-openapi` + `@scalar/hono-api-reference` together:
+
+- File: [`apps/backend/src/openAPI.ts`](https://github.com/NamesMT/starter-monorepo/blob/main/apps/backend/src/openAPI.ts)
+- Pattern: mounts spec at `/openapi/spec.json` and Scalar UI at `/openapi/ui`
+
+```typescript
+import type { Hono } from 'hono'
+import { Scalar } from '@scalar/hono-api-reference'
+import { openAPIRouteHandler } from 'hono-openapi'
+
+export function setupOpenAPI(app: Hono<any, any>, prefix = '/openapi') {
+ app.get(
+ `${prefix}/spec.json`,
+ openAPIRouteHandler(app, {
+ documentation: {
+ info: {
+ title: `starter-monorepo's backend`,
+ version: '1.0.0',
+ description: 'My amazing API',
+ },
+ },
+ }),
+ )
+
+ app.get(
+ `${prefix}/ui`,
+ Scalar({
+ theme: 'deepSpace',
+ url: `${prefix}/spec.json`,
+ }),
+ )
+}
+```
+
+> **Note**: No public repo was found using all four (`hono-openapi` + `Scalar` + `swagger-ui` + `hono`) in a single file. The canonical combination in the wild is `hono-openapi` + `Scalar`. Adding `swagger-ui` is a trivial parallel mount (shown in the `app.ts` above).
+
+---
+
+## 10. Common Pitfalls
+
+1. **Using `openAPISpecs` instead of `openAPIRouteHandler`**
+ Some docs (e.g. HONC) use `openAPISpecs` — this is **not** the current export name. The correct function is `openAPIRouteHandler` ([source](https://github.com/rhinobase/hono-openapi/blob/10f45a66ede3764b5e6065805fb60fd5df090466/src/index.ts#L1)).
+
+2. **Importing from `hono-openapi/zod`**
+ There are **no subpath exports**. Always import from `hono-openapi` directly.
+
+3. **Forgetting `@hono/standard-validator`**
+ It is a peer dependency of `hono-openapi`. Modern package managers (npm ≥ 7, pnpm, bun) auto-install it. If you see validation errors, ensure it is present in `node_modules`.
+
+4. **Using `@hono/zod-openapi` (the OLD package)**
+ The user explicitly wants `hono-openapi` (the newer, middleware-based, Standard Schema package). Do not confuse with `@hono/zod-openapi` which wraps the `Hono` class into `OpenAPIHono`.
+
+5. **Swagger UI `spec` option**
+ `@hono/swagger-ui` does **not** accept a `spec` option to embed the document directly. It only accepts `url` (or `urls`) pointing to an external spec endpoint. If you need embedded specs, use Scalar's `content` option instead.
+
+---
+
+## 11. Quick Start Commands
+
+```bash
+# 1. Create project
+mkdir my-api && cd my-api
+bun init -y
+
+# 2. Install dependencies
+bun add hono hono-openapi @scalar/hono-api-reference @hono/swagger-ui zod
+
+# 3. Add TypeScript
+bun add -d typescript @types/bun
+
+# 4. Write app.ts (copy from section 2 above)
+# 5. Run
+bun run --hot app.ts
+```
+
+Endpoints after startup:
+- `GET /health` — health check
+- `GET /hello?name=world` — documented route
+- `POST /users` — validated JSON body route
+- `GET /openapi.json` — raw OpenAPI 3.1.0 spec
+- `GET /scalar` — Scalar API Reference UI
+- `GET /swagger` — Swagger UI
diff --git a/plugins/omo/skills/programming/references/typescript/bootstrap.md b/plugins/omo/skills/programming/references/typescript/bootstrap.md
new file mode 100644
index 00000000..f0981b79
--- /dev/null
+++ b/plugins/omo/skills/programming/references/typescript/bootstrap.md
@@ -0,0 +1,199 @@
+# Bootstrap — Runtime, Package Manager, Tooling
+
+When starting a new TypeScript project (or scripting against the world), the choice of runtime, package manager, framework, and toolchain compounds. The wrong default at minute zero costs hours every week. The right defaults for 2026:
+
+## Runtime decision tree
+
+```
+Is this a CLI / script / single-binary tool?
+└─ Yes → Bun (single executable, hot reload, native TS)
+ Use `bun run script.ts` directly. No build step.
+
+Is this a backend service?
+├─ Edge (Cloudflare Workers / Vercel / Deno Deploy) → match the platform
+├─ Bun-supported runtime → Bun + Hono
+├─ Need Node-only deps (sharp, native modules without Bun support) → Node + Hono
+└─ Otherwise → Bun + Hono
+
+Is this a frontend?
+└─ Vite (regardless of framework). Bun for the package manager.
+
+Is this a library to publish to npm?
+└─ tsdown (or unbuild). Targets Node 20+. Use pnpm for monorepo workspaces.
+```
+
+## Bun is the default runtime
+
+Use Bun for:
+- Scripts and CLIs (`bun run` is faster than `tsx` and `ts-node`)
+- New backends (Hono runs natively, hot reload via `bun --hot`)
+- Test runner (`bun test` is built-in, faster than vitest for small suites)
+- Package manager (`bun install` is faster than `pnpm` and far faster than `npm`)
+
+Use Node when:
+- A dependency uses native modules Bun can't load (rare in 2026; check the dep's release notes)
+- Production target is a Node-specific platform (some serverless platforms don't run Bun yet)
+- You're contributing to a Node-only project
+
+`bunx` replaces `npx`. `bun create` scaffolds projects.
+
+## Package manager — pnpm > npm
+
+If you must use Node, use pnpm. NEVER npm except in legacy projects you don't control.
+
+Why pnpm:
+- Content-addressable store: 10x less disk usage on a machine with many projects
+- Strict node_modules layout: phantom dependencies fail at install time, not at runtime
+- Workspaces are first-class
+- Significantly faster than npm
+
+Why not yarn:
+- Yarn classic is unmaintained
+- Yarn berry's "PnP" mode breaks with editor tooling more often than it should
+- pnpm has caught up on every yarn berry feature people actually use
+
+Why not npm:
+- Slowest of the three
+- No proper workspace story until very recently
+- Phantom dependencies allowed by default
+
+```bash
+# Convert npm/yarn → pnpm
+pnpm import # reads package-lock.json or yarn.lock and produces pnpm-lock.yaml
+rm -rf node_modules package-lock.json yarn.lock
+pnpm install
+```
+
+## Backend framework — Hono
+
+Use Hono for any new HTTP service. It is:
+- Type-safe end-to-end (request/response types flow through middleware)
+- Edge-compatible (runs on Bun, Node, Cloudflare Workers, Deno, AWS Lambda)
+- Faster than Express, Fastify, and most of its peers in synthetic benchmarks
+- Maintained, opinionated, and documented well
+
+When Hono → ALWAYS pair with `hono-openapi` + `@scalar/hono-api-reference` + `@hono/swagger-ui`. Full setup with copy-pasteable `app.ts`: [backend-hono.md](backend-hono.md).
+
+NEVER:
+- Express for new services. Express is the COBOL of Node — works, but writes itself out of every benchmark.
+- Fastify for new services. Hono ships with better TypeScript ergonomics.
+- NestJS for new services. The Angular-flavoured DI/decorator stack is overkill for ~95% of services.
+- Bare `Bun.serve` or `node:http` unless you have a specific reason. Lose middleware, routing, validation. Reinvent everything.
+
+## Frontend tooling — Vite
+
+Vite for any frontend. Replaces webpack, parcel, rollup-as-app-bundler. Works with React, Vue, Svelte, Solid, Preact, vanilla.
+
+```bash
+bun create vite my-app -- --template react-ts
+cd my-app
+bun install
+bun run dev
+```
+
+## Lint + format — Biome
+
+Biome replaces ESLint + Prettier with one tool, written in Rust, ~30x faster.
+
+```bash
+bun add --dev @biomejs/biome
+bun biome init
+```
+
+`biome.json`:
+
+```json
+{
+ "$schema": "https://biomejs.dev/schemas/1.9.0/schema.json",
+ "organizeImports": { "enabled": true },
+ "linter": { "enabled": true, "rules": { "recommended": true } },
+ "formatter": { "enabled": true, "indentStyle": "space", "indentWidth": 2 }
+}
+```
+
+Use ESLint only when:
+- You have an ESLint plugin Biome doesn't replicate (rare in 2026)
+- You're contributing to an existing ESLint project
+
+Never run both — pick one.
+
+## Test runner — bun test or vitest
+
+| Runner | Use when |
+|---|---|
+| `bun test` | Bun project, simple unit tests, no TypeScript path aliases that need vite-style resolution |
+| `vitest` | Vite-based frontend, complex test infrastructure (DOM testing, snapshot, in-browser tests), or you need vitest-specific features |
+
+NEVER Jest for a new project. Jest's CommonJS-first design fights every modern Node/TS project.
+
+## TypeScript
+
+`tsconfig.json` for a Bun + Hono backend:
+
+```json
+{
+ "compilerOptions": {
+ "target": "ESNext",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "lib": ["ESNext"],
+ "types": ["bun-types"],
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noImplicitReturns": true,
+ "noFallthroughCasesInSwitch": true,
+ "exactOptionalPropertyTypes": true,
+ "esModuleInterop": true,
+ "isolatedModules": true,
+ "resolveJsonModule": true,
+ "skipLibCheck": true,
+ "verbatimModuleSyntax": true,
+ "noEmit": true
+ },
+ "include": ["src/**/*", "tests/**/*"]
+}
+```
+
+`verbatimModuleSyntax: true` enforces explicit `import type { ... }` for type-only imports — pairs with the no-excuse rule on type-only imports.
+
+`noEmit: true` because `bun run` and `bun build` handle compilation. The `tsc` command becomes a typechecker only.
+
+## Quick-start: Bun + Hono backend
+
+```bash
+mkdir my-api && cd my-api
+bun init -y
+bun add hono hono-openapi @scalar/hono-api-reference @hono/swagger-ui zod
+bun add --dev @biomejs/biome typescript
+bun biome init
+```
+
+`package.json` scripts:
+
+```json
+{
+ "scripts": {
+ "dev": "bun run --hot src/index.ts",
+ "start": "bun run src/index.ts",
+ "build": "bun build src/index.ts --target bun --outdir dist",
+ "typecheck": "tsc --noEmit",
+ "lint": "biome check --write src tests",
+ "test": "bun test"
+ }
+}
+```
+
+Wire the `app.ts` from [backend-hono.md](backend-hono.md). You have a documented, validated, OpenAPI-spec-emitting service in ~15 minutes.
+
+## When NOT to bootstrap from scratch
+
+| Situation | Use |
+|---|---|
+| Internal tool with auth/admin/dashboards | Next.js (full-stack) - lots of free wiring |
+| Documentation site | Astro or VitePress |
+| Real-time features (WebRTC, complex sockets) | Bun + Hono + a real-time library |
+| Data-heavy SPA | Vite + React + TanStack Query + TanStack Router |
+
+For greenfield backend services, Bun + Hono. Always.
diff --git a/plugins/omo/skills/programming/references/typescript/data-modeling.md b/plugins/omo/skills/programming/references/typescript/data-modeling.md
new file mode 100644
index 00000000..9e697311
--- /dev/null
+++ b/plugins/omo/skills/programming/references/typescript/data-modeling.md
@@ -0,0 +1,202 @@
+# Data Modeling
+
+Which construct to use, how to structure data, and why readonly is the default.
+
+---
+
+## Decision flowchart
+
+```
+Is it a fixed set of named constants?
+ YES → as const object + literal union type
+ NO ↓
+Is it just branding a primitive (string, number)?
+ YES → Branded type
+ NO ↓
+Is it an interface / contract?
+ YES → interface (structural typing is the default in TS)
+ NO ↓
+Does the data cross a trust boundary (user input, API, file)?
+ YES → Zod schema + z.infer<typeof schema>
+ NO ↓
+Is it a union of possible outcomes?
+ YES → Discriminated union (kind/type field)
+ NO ↓
+Is it structured data with named fields?
+ YES → type alias with readonly properties
+ NO → you probably don't need a new type
+```
+
+---
+
+## Container reference
+
+### type alias — internal data
+
+The default for structured data inside your codebase. Zero runtime cost.
+
+```typescript
+type User = {
+ readonly id: UserId
+ readonly name: string
+ readonly email: string
+}
+
+type Point = {
+ readonly x: number
+ readonly y: number
+}
+```
+
+All properties `readonly`. Mutable only when mutation is the documented purpose.
+
+### interface — contracts and extension
+
+Use when you need declaration merging or `extends`.
+
+```typescript
+interface Repository<T> {
+ get(id: string): Promise<T | null>
+ save(entity: T): Promise<void>
+}
+
+interface UserRepository extends Repository<User> {
+ findByEmail(email: string): Promise<User | null>
+}
+```
+
+### interface vs type — when to use which
+
+| Use | When |
+|---|---|
+| `type` | Union types, intersections, mapped types, utility types, internal data shapes |
+| `interface` | Contracts that will be `implements`ed or `extends`ed, declaration merging needed |
+| **Default** | **`type` — unless you have a specific reason for `interface`** |
+
+### Zod schema — trust boundary guardian
+
+Use when data enters your system. Validates at runtime, infers types at compile time.
+
+```typescript
+import { z } from "zod"
+
+const CreateUserSchema = z.object({
+ name: z.string().min(1),
+ email: z.string().email(),
+ age: z.number().int().min(0),
+})
+type CreateUser = z.infer<typeof CreateUserSchema>
+
+const UserResponseSchema = z.object({
+ id: z.string().uuid(),
+ name: z.string(),
+ email: z.string(),
+})
+type UserResponse = z.infer<typeof UserResponseSchema>
+```
+
+**The one rule**: data crosses a trust boundary → Zod. Everything else → plain type/interface.
+Never use Zod for internal-only data. The runtime validation cost and Zod coupling are unnecessary.
+
+### as const — fixed constants
+
+Replaces `enum` entirely. Type-safe, tree-shakeable, no runtime overhead.
+
+```typescript
+const ROLES = ["admin", "user", "guest"] as const
+type Role = (typeof ROLES)[number]
+
+const STATUS = {
+ ACTIVE: "active",
+ INACTIVE: "inactive",
+ DELETED: "deleted",
+} as const
+type Status = (typeof STATUS)[keyof typeof STATUS]
+```
+
+### Discriminated union — multiple outcomes
+
+```typescript
+type GetUserResult =
+ | { readonly kind: "found"; readonly user: User }
+ | { readonly kind: "not_found"; readonly id: UserId }
+ | { readonly kind: "forbidden"; readonly reason: string }
+```
+
+Each variant has a `kind` discriminant. TypeScript narrows on `switch (result.kind)`.
+
+---
+
+## Quick lookup
+
+| Situation | Use |
+|---|---|
+| User input, API request/response | Zod schema + `z.infer` |
+| Internal value object | `type` with `readonly` properties |
+| Function with multiple outcomes | Discriminated union |
+| Contract for implementations | `interface` |
+| Fixed constants | `as const` + literal union |
+| Distinct primitive (UserId vs OrderId) | Branded type |
+| Dict shape / key-value map | `Record<K, V>` or index signature |
+
+---
+
+## Readonly by default
+
+Every property is `readonly` unless mutation is the documented purpose.
+
+```typescript
+// DEFAULT — readonly
+type Config = {
+ readonly apiUrl: string
+ readonly timeout: number
+}
+
+// Arrays too
+function getUsers(): readonly User[] { ... }
+
+// Utility for existing types
+type ReadonlyUser = Readonly<User>
+type DeepReadonlyConfig = Readonly<Config>
+```
+
+For mutable state (rare), document why:
+
+```typescript
+/** Counter state — mutation is the entire purpose. */
+type CounterState = {
+ count: number // intentionally mutable
+}
+```
+
+---
+
+## Parse, don't validate
+
+Validate at the boundary. Inside the boundary, types are proof of validity.
+
+```typescript
+// BAD — validate then pass raw data
+function processEmail(email: string): void {
+ if (!email.includes("@")) throw new Error("invalid")
+ // still a raw string downstream
+}
+
+// GOOD — parse into typed value at boundary
+const EmailSchema = z.string().email().brand("Email")
+type Email = z.infer<typeof EmailSchema>
+
+function sendWelcome(email: Email): void { ... }
+
+// Boundary code
+const parsed = EmailSchema.parse(rawInput) // Email or throws
+sendWelcome(parsed) // no re-validation needed
+```
+
+---
+
+## Sources
+
+- TypeScript Handbook: [Object Types](https://www.typescriptlang.org/docs/handbook/2/objects.html)
+- Zod: [docs](https://zod.dev)
+- Total TypeScript: [Type vs Interface](https://www.totaltypescript.com/type-vs-interface-which-should-you-use)
diff --git a/plugins/omo/skills/programming/references/typescript/error-handling.md b/plugins/omo/skills/programming/references/typescript/error-handling.md
new file mode 100644
index 00000000..81d0661c
--- /dev/null
+++ b/plugins/omo/skills/programming/references/typescript/error-handling.md
@@ -0,0 +1,169 @@
+# Error Handling
+
+Typed errors, exhaustive matching, Result pattern, and resource safety.
+
+---
+
+## Typed errors — no bare strings
+
+Error classes carry structured data. Callers know exactly what can go wrong.
+
+```typescript
+class UserNotFoundError extends Error {
+ readonly name = "UserNotFoundError"
+ constructor(readonly userId: UserId) {
+ super(`user ${userId} not found`)
+ }
+}
+
+class PermissionDeniedError extends Error {
+ readonly name = "PermissionDeniedError"
+ constructor(
+ readonly userId: UserId,
+ readonly requiredRole: string,
+ ) {
+ super(`user ${userId} needs role ${requiredRole}`)
+ }
+}
+```
+
+```typescript
+// BAD
+throw new Error("user not found")
+throw new Error("permission denied")
+
+// GOOD
+throw new UserNotFoundError(userId)
+throw new PermissionDeniedError(userId, "admin")
+```
+
+Always set `readonly name` explicitly — `instanceof` checks survive minification, but `error.name` is more reliable for logging and serialization.
+
+---
+
+## Result pattern — expected failures without exceptions
+
+For failures that are **expected** (not found, validation), return a discriminated union instead of throwing.
+
+```typescript
+type Result<T, E = Error> =
+ | { readonly ok: true; readonly value: T }
+ | { readonly ok: false; readonly error: E }
+
+function ok<T>(value: T): Result<T, never> {
+ return { ok: true, value }
+}
+
+function err<E>(error: E): Result<never, E> {
+ return { ok: false, error }
+}
+```
+
+### Usage
+
+```typescript
+type UserError =
+ | { readonly kind: "not_found"; readonly id: UserId }
+ | { readonly kind: "forbidden"; readonly reason: string }
+
+function getUser(id: UserId): Result<User, UserError> {
+ const user = db.find(id)
+ if (!user) return err({ kind: "not_found", id })
+ if (!user.active) return err({ kind: "forbidden", reason: "deactivated" })
+ return ok(user)
+}
+
+// Caller must handle both cases
+const result = getUser(userId)
+if (!result.ok) {
+ switch (result.error.kind) {
+ case "not_found":
+ log.warn(`missing: ${result.error.id}`)
+ break
+ case "forbidden":
+ log.error(`denied: ${result.error.reason}`)
+ break
+ default:
+ assertNever(result.error)
+ }
+ return
+}
+const user = result.value // narrowed to User
+```
+
+### When to use which
+
+**The heuristic**: caller is 1-2 levels away and MUST handle it → Result. Error should propagate up many layers → throw.
+
+| Scenario | Pattern | Why |
+|---|---|---|
+| Repository → service (caller handles it) | Result | Caller is right there, must handle both |
+| Validation at boundary (parsing input) | throw (Zod throws) | Propagates up to HTTP handler |
+| Infrastructure failure (network, OOM) | throw | Can't handle locally |
+| Service → service (deep internal) | throw (typed Error subclass) | Result boilerplate across many layers is worse |
+| HTTP handler → response | Catch errors, convert to response | Boundary code catches and translates |
+
+**Practical tradeoff**: Result is safest (compiler forces handling) but creates boilerplate when every caller in a chain must check `.ok`. If the error would just propagate through 3+ layers unchanged, use a typed Error subclass instead.
+
+### Library or roll your own?
+
+Roll your own with the `Result`, `ok`, `err` above. It's 10 lines. Libraries like `neverthrow` add chaining (`.map`, `.andThen`) — use them only if you actually chain results frequently.
+
+---
+
+## Error cause — chain context
+
+Use the `cause` option to chain errors without losing the original stack.
+
+```typescript
+try {
+ await db.query(sql)
+} catch (error) {
+ throw new DatabaseError("query failed", { cause: error })
+}
+```
+
+The `cause` is available on `error.cause` and shows up in stack traces.
+
+---
+
+## Exhaustive error handling at boundaries
+
+HTTP handlers catch and translate:
+
+```typescript
+app.onError((error, c) => {
+ if (error instanceof UserNotFoundError) {
+ return c.json({ error: error.message }, 404)
+ }
+ if (error instanceof PermissionDeniedError) {
+ return c.json({ error: error.message }, 403)
+ }
+ console.error("unhandled:", error)
+ return c.json({ error: "internal server error" }, 500)
+})
+```
+
+---
+
+## Async error patterns
+
+```typescript
+// Promise.allSettled — when partial failure is OK
+const results = await Promise.allSettled(urls.map(fetch))
+const successes = results
+ .filter((r): r is PromiseFulfilledResult<Response> => r.status === "fulfilled")
+ .map((r) => r.value)
+
+// AbortSignal — cancellation
+async function fetchWithTimeout(url: string, ms: number): Promise<Response> {
+ return fetch(url, { signal: AbortSignal.timeout(ms) })
+}
+```
+
+---
+
+## Sources
+
+- MDN: [Error cause](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause)
+- MDN: [Promise.allSettled](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled)
diff --git a/plugins/omo/skills/programming/references/typescript/tsconfig-strict.md b/plugins/omo/skills/programming/references/typescript/tsconfig-strict.md
new file mode 100644
index 00000000..eb755d25
--- /dev/null
+++ b/plugins/omo/skills/programming/references/typescript/tsconfig-strict.md
@@ -0,0 +1,152 @@
+# Strict tsconfig + Biome
+
+The canonical ultra-strict config. Copy-paste, then add your own paths.
+
+---
+
+## tsconfig.json
+
+```jsonc
+{
+ "compilerOptions": {
+ // ── Strict core ──────────────────────────────────────────
+ "strict": true, // enables all strict* flags below
+ // strict includes: strictNullChecks, strictFunctionTypes,
+ // strictBindCallApply, strictPropertyInitialization,
+ // noImplicitAny, noImplicitThis, alwaysStrict, useUnknownInCatchVariables
+
+ // ── Additional strict flags (NOT included in "strict") ──
+ "noUncheckedIndexedAccess": true, // obj[key] is T | undefined, not T
+ "exactOptionalPropertyTypes": true, // { x?: string } !== { x: string | undefined }
+ "noFallthroughCasesInSwitch": true, // switch fall-through is an error
+ "noPropertyAccessFromIndexSignature": true, // forces bracket notation for index sigs
+ "forceConsistentCasingInFileNames": true, // prevents case-sensitivity bugs on macOS/Win
+
+ // ── Module system ────────────────────────────────────────
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "verbatimModuleSyntax": true, // forces `import type` for type-only imports
+ "isolatedModules": true, // safe for esbuild / swc / Bun transpilation
+ "esModuleInterop": true,
+ "resolveJsonModule": true,
+
+ // ── Target ───────────────────────────────────────────────
+ "target": "ESNext",
+ "lib": ["ESNext"],
+
+ // ── Emit ─────────────────────────────────────────────────
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true,
+ "outDir": "dist",
+ "rootDir": "src",
+
+ // ── Performance ──────────────────────────────────────────
+ "skipLibCheck": true, // skip checking .d.ts files for speed
+ "incremental": true
+ },
+ "include": ["src"],
+ "exclude": ["node_modules", "dist"]
+}
+```
+
+### What each extra flag catches
+
+| Flag | What it prevents |
+|---|---|
+| `noUncheckedIndexedAccess` | `arr[0]` is `T \| undefined`, not `T`. Forces you to check before using. |
+| `exactOptionalPropertyTypes` | `{ x?: string }` means "missing or string", NOT "string \| undefined". Assigns `undefined` explicitly? Type error. |
+| `noFallthroughCasesInSwitch` | Forgetting `break` / `return` in a switch case. |
+| `noPropertyAccessFromIndexSignature` | `obj.foo` on `Record<string, X>` is an error. Use `obj["foo"]`. |
+| `verbatimModuleSyntax` | Forces `import type { X }` for type-only imports. Prevents runtime import of types. |
+
+### Bun-specific additions
+
+For Bun projects, add to `compilerOptions`:
+```jsonc
+{
+ "types": ["bun-types"],
+ "moduleDetection": "force"
+}
+```
+
+---
+
+## biome.jsonc
+
+```jsonc
+{
+ "$schema": "https://biomejs.dev/schemas/2.0.6/schema.json",
+ "organizeImports": {
+ "enabled": true
+ },
+ "linter": {
+ "enabled": true,
+ "rules": {
+ "recommended": true,
+ "suspicious": {
+ "noExplicitAny": "error",
+ "noConfusingVoidType": "error",
+ "noFallthroughSwitchClause": "error"
+ },
+ "style": {
+ "noDefaultExport": "error",
+ "useImportType": "error",
+ "noNonNullAssertion": "error",
+ "useEnumInitializers": "off",
+ "noParameterAssign": "error"
+ },
+ "correctness": {
+ "noUnusedVariables": "error",
+ "noUnusedImports": "error"
+ },
+ "complexity": {
+ "noBannedTypes": "error"
+ }
+ }
+ },
+ "formatter": {
+ "enabled": true,
+ "indentStyle": "space",
+ "indentWidth": 2,
+ "lineWidth": 100
+ },
+ "javascript": {
+ "formatter": {
+ "quoteStyle": "double",
+ "semicolons": "asNeeded"
+ }
+ },
+ "files": {
+ "ignore": ["node_modules", "dist", "build", ".next", ".nuxt", "coverage"]
+ }
+}
+```
+
+### Key Biome rules
+
+| Rule | What |
+|---|---|
+| `noExplicitAny` | `any` in annotations is an error |
+| `noNonNullAssertion` | `x!` is an error |
+| `noDefaultExport` | Forces named exports |
+| `useImportType` | Forces `import type` for type-only imports |
+| `noParameterAssign` | No mutation of function parameters |
+
+---
+
+## CI gate
+
+```bash
+bunx biome check .
+bunx tsc --noEmit
+bun test
+```
+
+---
+
+## Sources
+
+- TypeScript: [tsconfig reference](https://www.typescriptlang.org/tsconfig)
+- Biome: [configuration](https://biomejs.dev/reference/configuration/)
+- Total TypeScript: [tsconfig cheat sheet](https://www.totaltypescript.com/tsconfig-cheat-sheet)
diff --git a/plugins/omo/skills/programming/references/typescript/type-patterns.md b/plugins/omo/skills/programming/references/typescript/type-patterns.md
new file mode 100644
index 00000000..7b8e11b4
--- /dev/null
+++ b/plugins/omo/skills/programming/references/typescript/type-patterns.md
@@ -0,0 +1,196 @@
+# Type Patterns
+
+How to use TypeScript's type system to catch bugs at compile time.
+
+---
+
+## Branded types — distinct primitives
+
+Same runtime type, different meaning. The compiler prevents mixing.
+
+```typescript
+declare const brand: unique symbol
+type Brand<T, B extends string> = T & { readonly [brand]: B }
+
+type UserId = Brand<string, "UserId">
+type OrderId = Brand<string, "OrderId">
+type Milliseconds = Brand<number, "Milliseconds">
+type Seconds = Brand<number, "Seconds">
+
+function UserId(value: string): UserId { return value as UserId }
+function OrderId(value: string): OrderId { return value as OrderId }
+
+function getUser(id: UserId): User { ... }
+
+getUser(UserId("abc")) // OK
+getUser(OrderId("abc")) // type error: OrderId is not UserId
+getUser("abc") // type error: string is not UserId
+```
+
+With Zod (preferred at boundaries):
+```typescript
+import { z } from "zod"
+
+const UserIdSchema = z.string().uuid().brand("UserId")
+type UserId = z.infer<typeof UserIdSchema>
+```
+
+**Use when**: IDs, indices, units of measurement — any pair where swapping is a bug.
+
+---
+
+## as const — literal types from values
+
+Freezes a value to its narrowest possible type. The foundation for enum-free TypeScript.
+
+```typescript
+const ROLES = ["admin", "user", "guest"] as const
+type Role = (typeof ROLES)[number] // "admin" | "user" | "guest"
+
+const HTTP_STATUS = {
+ OK: 200,
+ NOT_FOUND: 404,
+ INTERNAL: 500,
+} as const
+type HttpStatus = (typeof HTTP_STATUS)[keyof typeof HTTP_STATUS] // 200 | 404 | 500
+```
+
+**Use when**: fixed set of constants. Replaces `enum` entirely.
+**Skip when**: the set is open-ended or user-defined.
+
+---
+
+## satisfies — validate without widening
+
+Type-checks a value against a type while preserving the literal type. Best of both worlds.
+
+```typescript
+type Config = Record<string, string | number>
+
+// BAD — widens to Record<string, string | number>
+const config: Config = { api: "https://api.example.com", timeout: 30 }
+config.api // string | number — lost the narrowing
+
+// GOOD — validates AND preserves literal types
+const config = {
+ api: "https://api.example.com",
+ timeout: 30,
+} satisfies Config
+config.api // string (narrowed)
+config.timeout // number (narrowed)
+```
+
+**Use when**: you want type validation on a value without losing narrowing.
+
+---
+
+## Discriminated unions — algebraic data types
+
+Model every outcome as a type. Force the caller to handle all cases.
+
+```typescript
+type GetUserResult =
+ | { readonly kind: "found"; readonly user: User }
+ | { readonly kind: "not_found"; readonly id: UserId }
+ | { readonly kind: "forbidden"; readonly reason: string }
+```
+
+The `kind` field (or `type`, `status`, `_tag`) is the discriminant. TypeScript narrows on it automatically.
+
+---
+
+## Exhaustive switch — assertNever
+
+Every switch on a discriminated union ends with a default that calls `assertNever`.
+
+```typescript
+function assertNever(x: never): never {
+ throw new Error(`Unexpected value: ${JSON.stringify(x)}`)
+}
+
+function handleResult(result: GetUserResult): string {
+ switch (result.kind) {
+ case "found":
+ return result.user.name
+ case "not_found":
+ return `No user ${result.id}`
+ case "forbidden":
+ return `Denied: ${result.reason}`
+ default:
+ return assertNever(result)
+ }
+}
+```
+
+Add a new variant to `GetUserResult`? The compiler errors on the `assertNever` call until you handle it.
+
+---
+
+## Narrowing — let the compiler follow your logic
+
+TypeScript narrows types through `typeof`, `instanceof`, `in`, equality checks, and discriminants.
+
+```typescript
+function process(value: string | number | null): string {
+ if (value === null) return "nothing"
+ // compiler knows: string | number
+
+ if (typeof value === "string") return value.toUpperCase()
+ // compiler knows: number
+
+ return String(value * 2)
+}
+```
+
+### Custom type guards
+
+```typescript
+function isNonNull<T>(value: T | null | undefined): value is T {
+ return value != null
+}
+
+const items = [1, null, 2, undefined, 3]
+const clean = items.filter(isNonNull) // number[]
+```
+
+---
+
+## import type — separate values from types
+
+Always use `import type` for type-only imports. Enforced by `verbatimModuleSyntax`.
+
+```typescript
+import type { User, Config } from "./types" // erased at runtime
+import { createUser } from "./services" // kept at runtime
+```
+
+For mixed imports:
+```typescript
+import { createUser, type User } from "./users"
+```
+
+---
+
+## Utility types — quick reference
+
+| Need | Use |
+|---|---|
+| All properties readonly | `Readonly<T>` |
+| All properties optional | `Partial<T>` |
+| All properties required | `Required<T>` |
+| Pick specific properties | `Pick<T, "a" \| "b">` |
+| Omit specific properties | `Omit<T, "a" \| "b">` |
+| Key-value map | `Record<K, V>` |
+| Extract from union | `Extract<T, U>` |
+| Exclude from union | `Exclude<T, U>` |
+| Return type of function | `ReturnType<typeof fn>` |
+| Parameters of function | `Parameters<typeof fn>` |
+| Awaited type | `Awaited<Promise<T>>` → `T` |
+
+---
+
+## Sources
+
+- TypeScript Handbook: [Narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html)
+- TypeScript Handbook: [Template Literal Types](https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html)
+- Total TypeScript: [as const](https://www.totaltypescript.com/as-const)
diff --git a/plugins/omo/skills/programming/scripts/go/check-no-excuse-rules.sh b/plugins/omo/skills/programming/scripts/go/check-no-excuse-rules.sh
new file mode 100755
index 00000000..7455dc42
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/go/check-no-excuse-rules.sh
@@ -0,0 +1,173 @@
+#!/usr/bin/env bash
+# No-excuse rule checker for Go files.
+# Mirrors the philosophy of python-programmer / typescript-programmer / rust-programmer scripts:
+# only rules that can be enforced via pure text matching live here.
+# Everything semantic is on golangci-lint + nilaway + go test -race.
+
+set -euo pipefail
+
+if [ $# -eq 0 ]; then
+ echo "Usage: $0 <file.go> [file.go ...]" >&2
+ exit 2
+fi
+
+violations=0
+report() {
+ local file="$1"
+ local line="$2"
+ local rule="$3"
+ local detail="$4"
+ echo "::error file=${file},line=${line}::[${rule}] ${detail}" >&2
+ violations=$((violations + 1))
+}
+
+is_test_file() {
+ case "$1" in
+ *_test.go) return 0 ;;
+ esac
+ return 1
+}
+
+is_generated_file() {
+ local file="$1"
+ case "$file" in
+ *.pb.go|*.connect.go|*.gen.go) return 0 ;;
+ *_string.go) return 0 ;;
+ esac
+ # First-line check for "Code generated ... DO NOT EDIT." (the official marker)
+ if [ -f "$file" ]; then
+ head -n 5 "$file" 2>/dev/null | grep -qE "^// Code generated .* DO NOT EDIT\.$" && return 0
+ fi
+ return 1
+}
+
+for file in "$@"; do
+ [ -f "$file" ] || continue
+ case "$file" in
+ *.go) ;;
+ *) continue ;;
+ esac
+
+ if is_generated_file "$file"; then
+ continue
+ fi
+
+ in_test=0
+ if is_test_file "$file"; then
+ in_test=1
+ fi
+
+ line_no=0
+ while IFS= read -r raw_line || [ -n "$raw_line" ]; do
+ line_no=$((line_no + 1))
+ line="$raw_line"
+
+ # Strip line comments before pattern checks
+ # (block comments are not handled — keep the rules robust to that limitation).
+ code_only="${line%%//*}"
+
+ # ── Exemption marker: // no-excuse-ok: <reason> ──────────────────
+ if [[ "$line" =~ //[[:space:]]*no-excuse-ok:[[:space:]]*.+ ]]; then
+ continue
+ fi
+
+ # ── Rule: no `_ = err` (silent error swallow) ────────────────────
+ # The errcheck linter catches most of these but the `_ = err` form
+ # specifically slips through if used with named returns.
+ if [[ "$code_only" =~ ^[[:space:]]*_[[:space:]]*=[[:space:]]*err[[:space:]]*$ ]] ||
+ [[ "$code_only" =~ ^[[:space:]]*_[[:space:]]*=[[:space:]]*err[[:space:]]*[^a-zA-Z0-9_].*$ ]]; then
+ if [ "$in_test" -eq 0 ]; then
+ report "$file" "$line_no" "silent-err" "discarding err with '_ = err' — handle the error"
+ fi
+ fi
+
+ # ── Rule: no `panic(` in non-test, non-main code ─────────────────
+ # Allowed in main(), allowed in tests, allowed with explicit marker.
+ if [[ "$code_only" =~ [^a-zA-Z0-9_]panic\( ]] || [[ "$code_only" =~ ^[[:space:]]*panic\( ]]; then
+ if [ "$in_test" -eq 0 ]; then
+ # main package main.go is the one exception
+ pkg_line=$(head -n 5 "$file" 2>/dev/null | grep -m1 "^package ")
+ if [[ "$pkg_line" != "package main" ]]; then
+ report "$file" "$line_no" "panic-in-lib" "panic outside main/test — return error instead"
+ fi
+ fi
+ fi
+
+ # ── Rule: no `log.Fatal` / `log.Panic` in library code ───────────
+ if [[ "$code_only" =~ log\.(Fatal|Panic)(f|ln)?\( ]]; then
+ if [ "$in_test" -eq 0 ]; then
+ pkg_line=$(head -n 5 "$file" 2>/dev/null | grep -m1 "^package ")
+ if [[ "$pkg_line" != "package main" ]]; then
+ report "$file" "$line_no" "log-fatal-in-lib" "log.Fatal/Panic outside main — return error"
+ fi
+ fi
+ fi
+
+ # ── Rule: no init() functions ─────────────────────────────────
+ # init() ruins testability and creates hidden global state.
+ # Exception: //go:build constraint files and generated code.
+ if [[ "$code_only" =~ ^func[[:space:]]+init\(\)[[:space:]]*\{ ]]; then
+ report "$file" "$line_no" "no-init-func" "init() ruins testability — use explicit constructor"
+ fi
+
+ # ── Rule: no `time.Sleep` in non-test code ──────────────────────
+ if [[ "$code_only" =~ time\.Sleep\( ]]; then
+ if [ "$in_test" -eq 0 ]; then
+ report "$file" "$line_no" "time-sleep" "time.Sleep in production code — use ticker/timer with ctx"
+ fi
+ fi
+
+ # ── Rule: no `context.Background()` inside functions (only in main/init/test) ──
+ if [[ "$code_only" =~ context\.Background\(\) ]]; then
+ if [ "$in_test" -eq 0 ]; then
+ pkg_line=$(head -n 5 "$file" 2>/dev/null | grep -m1 "^package ")
+ if [[ "$pkg_line" != "package main" ]]; then
+ report "$file" "$line_no" "ctx-background-in-lib" "context.Background() outside main — propagate ctx as parameter"
+ fi
+ fi
+ fi
+
+ # ── Rule: no `interface{}` (use `any`, the alias from Go 1.18+) ──
+ if [[ "$code_only" =~ interface\{\} ]]; then
+ report "$file" "$line_no" "old-interface-empty" "use 'any' instead of 'interface{}' (Go 1.18+)"
+ fi
+
+ # ── Rule: no bare `fmt.Println` for logging (use slog) ───────────
+ # Acceptable in main.go (CLI output) and tests. Reject in libraries.
+ if [[ "$code_only" =~ fmt\.(Print|Println|Printf)\( ]]; then
+ if [ "$in_test" -eq 0 ]; then
+ pkg_line=$(head -n 5 "$file" 2>/dev/null | grep -m1 "^package ")
+ if [[ "$pkg_line" != "package main" ]]; then
+ report "$file" "$line_no" "fmt-print-in-lib" "fmt.Print* in library — use slog for structured logs"
+ fi
+ fi
+ fi
+
+ # ── Rule: no `nolint` directive without reason ───────────────────
+ if [[ "$line" =~ //nolint(:|$| ) ]]; then
+ if ! [[ "$line" =~ //nolint:[a-zA-Z0-9_,-]+[[:space:]]+//[[:space:]]*[^[:space:]] ]]; then
+ report "$file" "$line_no" "nolint-no-reason" "//nolint requires a // reason after the linter list"
+ fi
+ fi
+
+ # ── Rule: no TODO / FIXME without an issue link or owner ─────────
+ # Check the full line — TODOs live in comments, which $code_only has stripped.
+ if echo "$line" | grep -qE '(TODO|FIXME|XXX)([[:space:]]|:)'; then
+ if ! echo "$line" | grep -qE '(TODO|FIXME|XXX).*[(@[]'; then
+ report "$file" "$line_no" "todo-no-owner" "TODO/FIXME requires (#issue) or @owner attribution"
+ fi
+ fi
+ done < "$file"
+done
+
+if [ "$violations" -gt 0 ]; then
+ echo "" >&2
+ echo "go-programmer: $violations violation(s). Run also:" >&2
+ echo " gofumpt -l ." >&2
+ echo " golangci-lint run --timeout 5m ./..." >&2
+ echo " nilaway ./..." >&2
+ echo " go test -race -shuffle=on -count=1 ./..." >&2
+ exit 1
+fi
+
+echo "go-programmer: no-excuse rules passed for $# file(s)."
diff --git a/plugins/omo/skills/programming/scripts/go/new-project.py b/plugins/omo/skills/programming/scripts/go/new-project.py
new file mode 100755
index 00000000..6a5f9462
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/go/new-project.py
@@ -0,0 +1,138 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "typer",
+# "rich",
+# ]
+# ///
+
+# ─── How to run ───
+# 1. Install uv (if not installed):
+# curl -LsSf https://astral.sh/uv/install.sh | sh
+# 2. Run:
+# uv run new-project.py myservice
+# uv run new-project.py myservice --module github.com/your-org/myservice
+# ──────────────────
+#
+# Creates a new Go project with the canonical strict layout:
+# - go.mod with go 1.23
+# - .golangci.yml (v2, strict bundle)
+# - Taskfile.yml (fmt + lint + test + build)
+# - cmd/server/main.go entrypoint
+# - internal/{cmd,config,api,domain,obs} skeletons
+# - .github/workflows/ci.yml
+#
+# Templates live in ./templates/ — keep this script under 250 pure LOC.
+
+from __future__ import annotations
+
+import subprocess
+import sys
+from pathlib import Path
+from string import Template
+
+import typer
+from rich.console import Console
+
+console = Console(stderr=True)
+
+TEMPLATES_DIR = Path(__file__).parent / "templates"
+
+
+def _render(template_file: str, **subs: str) -> str:
+ """Read a template file and apply $placeholder substitutions.
+
+ Uses string.Template ($name) so Go/YAML curly braces stay literal.
+ """
+ raw = (TEMPLATES_DIR / template_file).read_text()
+ if not subs:
+ return raw
+ return Template(raw).substitute(**subs)
+
+
+# (template-file → relative output path; is_format = .format() is run)
+FILES: list[tuple[str, str, bool]] = [
+ (".golangci.yml", ".golangci.yml", False),
+ ("Taskfile.yml", "Taskfile.yml", False),
+ (".editorconfig", ".editorconfig", False),
+ ("gitignore", ".gitignore", False),
+ ("ci.yml", ".github/workflows/ci.yml", False),
+ ("run.go", "internal/cmd/run.go", False),
+ ("config.go", "internal/config/config.go", False),
+ ("main.go.tmpl", "cmd/server/main.go", True),
+ ("AGENTS.md.tmpl", "AGENTS.md", True),
+ ("README.md.tmpl", "README.md", True),
+]
+
+
+def _init_go_module(project_dir: Path, module: str) -> None:
+ try:
+ subprocess.run(
+ ["go", "mod", "init", module],
+ cwd=project_dir,
+ check=True,
+ capture_output=True,
+ )
+ console.print(f" [dim]ran[/] go mod init {module}")
+ except (subprocess.CalledProcessError, FileNotFoundError) as e:
+ console.print(f" [yellow]warn[/] go mod init failed ({e}); writing fallback go.mod")
+ (project_dir / "go.mod").write_text(f"module {module}\n\ngo 1.23\n")
+
+
+def _create_layout(project_dir: Path) -> None:
+ """Create the canonical internal/ tree."""
+ subdirs = [
+ "cmd/server",
+ "internal/cmd",
+ "internal/config",
+ "internal/api",
+ "internal/domain",
+ "internal/obs",
+ ".github/workflows",
+ ]
+ for sd in subdirs:
+ (project_dir / sd).mkdir(parents=True)
+
+
+def _write_files(project_dir: Path, name: str, module: str, purpose: str) -> None:
+ """Render every template into the project tree."""
+ for tmpl_name, out_rel, is_format in FILES:
+ subs = (
+ {"name": name, "module": module, "short_purpose": purpose}
+ if is_format
+ else {}
+ )
+ content = _render(tmpl_name, **subs)
+ out_path = project_dir / out_rel
+ out_path.parent.mkdir(parents=True, exist_ok=True)
+ out_path.write_text(content)
+ console.print(f" [dim]wrote[/] {out_rel}")
+
+
+def main(
+ name: str,
+ path: str = typer.Option(".", help="Parent dir"),
+ module: str = typer.Option("", help="Go module path; default: <name>"),
+ purpose: str = typer.Option("HTTP", help="Short purpose for AGENTS.md"),
+) -> None:
+ """Scaffold a new Go project with the strict toolchain."""
+ project_dir = Path(path) / name
+ if project_dir.exists():
+ console.print(f"[red]✗[/red] {project_dir} already exists")
+ sys.exit(1)
+
+ module_path = module or name
+
+ project_dir.mkdir(parents=True)
+ _create_layout(project_dir)
+ _init_go_module(project_dir, module_path)
+ _write_files(project_dir, name, module_path, purpose)
+
+ console.print(f"\n[bold green]Done![/] cd {project_dir}")
+ console.print(" go get github.com/caarlos0/env/v11")
+ console.print(" task # fmt + lint + test")
+
+
+if __name__ == "__main__":
+ typer.run(main)
diff --git a/plugins/omo/skills/programming/scripts/go/templates/.editorconfig b/plugins/omo/skills/programming/scripts/go/templates/.editorconfig
new file mode 100644
index 00000000..7b485350
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/go/templates/.editorconfig
@@ -0,0 +1,13 @@
+root = true
+
+[*]
+indent_style = tab
+indent_size = 4
+end_of_line = lf
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+
+[*.{yml,yaml,json,md}]
+indent_style = space
+indent_size = 2
diff --git a/plugins/omo/skills/programming/scripts/go/templates/.golangci.yml b/plugins/omo/skills/programming/scripts/go/templates/.golangci.yml
new file mode 100644
index 00000000..4eee6949
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/go/templates/.golangci.yml
@@ -0,0 +1,95 @@
+version: "2"
+
+run:
+ timeout: 5m
+ tests: true
+ modules-download-mode: readonly
+
+linters:
+ default: none
+ enable:
+ - govet
+ - staticcheck
+ - errcheck
+ - errorlint
+ - nilerr
+ - nilnil
+ - bodyclose
+ - rowserrcheck
+ - sqlclosecheck
+ - contextcheck
+ - fatcontext
+ - copyloopvar
+ - intrange
+ - usetesting
+ - testifylint
+ - gofumpt
+ - goimports
+ - whitespace
+ - misspell
+ - unconvert
+ - unparam
+ - ineffassign
+ - dupword
+ - gocognit
+ - gocyclo
+ - funlen
+ - lll
+ - nestif
+ - dupl
+ - revive
+ - unused
+ - exhaustive
+ - gosec
+ - sloglint
+ - perfsprint
+ - prealloc
+ - makezero
+
+linters-settings:
+ errcheck:
+ check-type-assertions: true
+ check-blank: true
+ errorlint:
+ errorf: true
+ asserts: true
+ comparison: true
+ gocognit:
+ min-complexity: 25
+ gocyclo:
+ min-complexity: 15
+ funlen:
+ lines: 90
+ statements: 60
+ lll:
+ line-length: 120
+ tab-width: 4
+ nestif:
+ min-complexity: 4
+ exhaustive:
+ default-signifies-exhaustive: false
+ check: [switch, map]
+ sloglint:
+ no-mixed-args: true
+ attr-only: true
+ no-global: all
+ context: scope
+ static-msg: true
+ no-raw-keys: true
+ key-naming-case: snake
+
+formatters:
+ enable:
+ - gofumpt
+ - goimports
+
+issues:
+ max-issues-per-linter: 0
+ max-same-issues: 0
+ exclude-rules:
+ - path: _test\\.go
+ linters: [funlen, lll, dupl, gosec]
+ - path: \\.pb\\.go$
+ linters: [all]
+ - path: \\.connect\\.go$
+ linters: [all]
diff --git a/plugins/omo/skills/programming/scripts/go/templates/AGENTS.md.tmpl b/plugins/omo/skills/programming/scripts/go/templates/AGENTS.md.tmpl
new file mode 100644
index 00000000..3f23b418
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/go/templates/AGENTS.md.tmpl
@@ -0,0 +1,24 @@
+# AGENTS.md
+
+Go 1.23+ $short_purpose service.
+
+## Commands
+- `task` — fmt + lint + test
+- `task build` — produce ./bin/server
+- `task ci` — full CI pipeline locally
+
+## Architecture
+- `cmd/server/main.go` — entrypoint, ≤50 LOC
+- `internal/cmd/` — root command, signal wiring
+- `internal/api/` — HTTP handlers + middleware (gin)
+- `internal/domain/` — smart-constructor types, no I/O
+- `internal/store/` — DB layer (sqlc-generated, never hand-edited)
+- `internal/config/` — env-driven Config
+- `internal/obs/` — slog setup, observability
+
+## Conventions
+- `slog` for all logs; never `log.*`, never `fmt.Println` in libs
+- `context.Context` first arg for every public function with I/O
+- Errors wrapped with `%w`; check with `errors.Is/As`
+- 250 pure LOC ceiling per file
+- Tests follow Given/When/Then; less mock the better
diff --git a/plugins/omo/skills/programming/scripts/go/templates/README.md.tmpl b/plugins/omo/skills/programming/scripts/go/templates/README.md.tmpl
new file mode 100644
index 00000000..fce8b6f6
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/go/templates/README.md.tmpl
@@ -0,0 +1,12 @@
+# $name
+
+Bootstrapped with the `programming` skill's Go scaffold.
+
+## Run
+
+```bash
+task # fmt + lint + test
+task run # build + run server
+```
+
+See `AGENTS.md` for architecture conventions.
diff --git a/plugins/omo/skills/programming/scripts/go/templates/Taskfile.yml b/plugins/omo/skills/programming/scripts/go/templates/Taskfile.yml
new file mode 100644
index 00000000..daa1d59b
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/go/templates/Taskfile.yml
@@ -0,0 +1,40 @@
+version: '3'
+
+vars:
+ BINARY: server
+ PKG: ./cmd/server
+
+tasks:
+ default:
+ deps: [fmt, lint, test]
+
+ fmt:
+ cmds:
+ - gofumpt -w .
+ - goimports -w -local "$(go list -m)" .
+
+ lint:
+ cmds:
+ - golangci-lint run --timeout 5m ./...
+ - nilaway ./... || true
+
+ test:
+ cmds:
+ - go test -race -shuffle=on -count=1 ./...
+
+ test-cover:
+ cmds:
+ - go test -race -shuffle=on -count=1 -coverprofile=coverage.out ./...
+ - go tool cover -html=coverage.out -o coverage.html
+
+ build:
+ cmds:
+ - go build -trimpath -ldflags="-s -w" -o bin/{{.BINARY}} {{.PKG}}
+
+ run:
+ deps: [build]
+ cmds:
+ - ./bin/{{.BINARY}}
+
+ ci:
+ deps: [fmt, lint, test, build]
diff --git a/plugins/omo/skills/programming/scripts/go/templates/ci.yml b/plugins/omo/skills/programming/scripts/go/templates/ci.yml
new file mode 100644
index 00000000..3cdf9011
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/go/templates/ci.yml
@@ -0,0 +1,37 @@
+name: ci
+on:
+ pull_request:
+ push:
+ branches: [main]
+
+jobs:
+ ci:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-go@v5
+ with:
+ go-version: '1.23'
+ cache: true
+
+ - name: Install tools
+ run: |
+ go install mvdan.cc/gofumpt@latest
+ go install github.com/golangci/golangci-lint/cmd/[email protected]
+ go install go.uber.org/nilaway/cmd/nilaway@latest
+ go install github.com/go-task/task/v3/cmd/task@latest
+
+ - name: Format check
+ run: gofumpt -l . | (! grep .)
+
+ - name: Lint
+ run: golangci-lint run --timeout 5m ./...
+
+ - name: Nilaway
+ run: nilaway ./... || true
+
+ - name: Test
+ run: go test -race -shuffle=on -count=1 ./...
+
+ - name: Build
+ run: go build -trimpath ./...
diff --git a/plugins/omo/skills/programming/scripts/go/templates/config.go b/plugins/omo/skills/programming/scripts/go/templates/config.go
new file mode 100644
index 00000000..f104c9e7
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/go/templates/config.go
@@ -0,0 +1,24 @@
+// Package config loads typed config from env.
+package config
+
+import (
+ "time"
+
+ "github.com/caarlos0/env/v11"
+)
+
+type Config struct {
+ Host string `env:"HOST" envDefault:"0.0.0.0"`
+ Port int `env:"PORT" envDefault:"8080"`
+ ShutdownTimeout time.Duration `env:"SHUTDOWN_TIMEOUT" envDefault:"20s"`
+ LogLevel string `env:"LOG_LEVEL" envDefault:"info"`
+ LogFormat string `env:"LOG_FORMAT" envDefault:"json"`
+}
+
+func Load() (Config, error) {
+ var cfg Config
+ if err := env.Parse(&cfg); err != nil {
+ return Config{}, err
+ }
+ return cfg, nil
+}
diff --git a/plugins/omo/skills/programming/scripts/go/templates/gitignore b/plugins/omo/skills/programming/scripts/go/templates/gitignore
new file mode 100644
index 00000000..d009c99b
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/go/templates/gitignore
@@ -0,0 +1,15 @@
+bin/
+coverage.out
+coverage.html
+*.test
+*.prof
+
+.idea/
+.vscode/
+*.swp
+
+.env
+.env.local
+
+*.pem
+*.key
diff --git a/plugins/omo/skills/programming/scripts/go/templates/main.go.tmpl b/plugins/omo/skills/programming/scripts/go/templates/main.go.tmpl
new file mode 100644
index 00000000..460befb1
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/go/templates/main.go.tmpl
@@ -0,0 +1,22 @@
+package main
+
+import (
+ "context"
+ "log/slog"
+ "os"
+ "os/signal"
+ "syscall"
+
+ "$module/internal/cmd"
+)
+
+func main() {
+ ctx, stop := signal.NotifyContext(context.Background(),
+ syscall.SIGINT, syscall.SIGTERM)
+ defer stop()
+
+ if err := cmd.Execute(ctx); err != nil {
+ slog.Error("fatal", slog.Any("err", err))
+ os.Exit(1)
+ }
+}
diff --git a/plugins/omo/skills/programming/scripts/go/templates/run.go b/plugins/omo/skills/programming/scripts/go/templates/run.go
new file mode 100644
index 00000000..fe9d88dc
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/go/templates/run.go
@@ -0,0 +1,15 @@
+// Package cmd wires the root command and subcommands.
+package cmd
+
+import (
+ "context"
+ "log/slog"
+ "os"
+)
+
+// Execute runs the root command. Wire cobra/subcommands here.
+func Execute(ctx context.Context) error {
+ slog.New(slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo}))
+ slog.InfoContext(ctx, "starting")
+ return nil
+}
diff --git a/plugins/omo/skills/programming/scripts/python/check-no-excuse-rules.py b/plugins/omo/skills/programming/scripts/python/check-no-excuse-rules.py
new file mode 100644
index 00000000..4270ef32
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/python/check-no-excuse-rules.py
@@ -0,0 +1,687 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.11"
+# dependencies = []
+# ///
+# noqa: SIZE_OK — single self-contained checker, splitting adds import ceremony for no readability gain
+"""Check Python files for no-excuse violations.
+
+The python-programmer skill enforces these rules. Run after editing.
+
+Rules:
+ cast-any - cast(Any, ...) / cast(typing.Any, ...) / typing.cast(Any, ...)
+ type-ignore - `# type: ignore` comments (any variant)
+ pyright-ignore - `# pyright: ignore` comments (any variant)
+ bare-except - `except:` with no class
+ silent-except - `except X: pass` or `except X: ...` (single statement)
+ no-asyncio - `import asyncio` / `from asyncio import ...`
+ Opt out per import line: trailing `# noqa: ANYIO_OK`
+ no-pandas - `import pandas` / `from pandas import ...`
+ Opt out per import line: trailing `# noqa: PANDAS_OK`
+ mutable-dataclass - @dataclass without frozen=True
+ Opt out: trailing `# noqa: MUTABLE_OK`
+ missing-slots - @dataclass without slots=True
+ Opt out: trailing `# noqa: SLOTS_OK`
+ raw-dict-return - function returns bare `dict` type
+ Opt out: trailing `# noqa: DICT_OK`
+ missing-assert-never - match statement without assert_never in default case
+ Opt out: `# noqa: MATCH_OK` on the match line
+ generic-exception - raise ValueError/TypeError/RuntimeError with bare string
+ Opt out: trailing `# noqa: GENERIC_ERR_OK`
+ no-object - `object` used as type annotation (param, return, variable)
+ Opt out: trailing `# noqa: OBJECT_OK`
+ if-elif-on-variant - isinstance/enum-comparison if/elif chain (should be match/case)
+ Opt out: trailing `# noqa: IF_VARIANT_OK`
+ oversized-module - file exceeds 250 pure LOC (non-blank, non-comment)
+ Opt out: `# noqa: SIZE_OK` in first 10 lines
+ broad-except - `except Exception` / `except BaseException` (too broad)
+ Opt out: trailing `# noqa: BROAD_EXCEPT_OK`
+
+Usage:
+ check-no-excuse-rules.py <file-or-dir>...
+
+Exit codes:
+ 0 - no violations
+ 1 - one or more violations
+ 2 - input error (path missing, etc.)
+"""
+from __future__ import annotations
+
+import ast
+import io
+import re
+import sys
+import tokenize
+from collections.abc import Iterable
+from dataclasses import dataclass
+from pathlib import Path
+
+EXCLUDED_DIRS = frozenset({
+ ".git", ".hg", ".svn", ".venv", "venv", "env", ".env",
+ "__pycache__", ".tox", ".nox", "dist", "build", ".eggs",
+ ".ruff_cache", ".mypy_cache", ".pytest_cache", ".basedpyright",
+ "node_modules",
+})
+
+SUPPRESSION_RE = re.compile(r"#\s*(type|pyright)\s*:\s*ignore\b")
+ANYIO_OK_RE = re.compile(r"#\s*noqa:\s*ANYIO_OK\b")
+PANDAS_OK_RE = re.compile(r"#\s*noqa:\s*PANDAS_OK\b")
+
+BANNED_IMPORTS: dict[str, tuple[str, re.Pattern[str], str]] = {
+ "asyncio": (
+ "no-asyncio",
+ ANYIO_OK_RE,
+ "import asyncio - use anyio (opt out: trailing `# noqa: ANYIO_OK`)",
+ ),
+ "pandas": (
+ "no-pandas",
+ PANDAS_OK_RE,
+ "import pandas - use polars (opt out: trailing `# noqa: PANDAS_OK`)",
+ ),
+}
+
+# Opt-out patterns for new Rust-like rules
+MUTABLE_OK_RE: re.Pattern[str] = re.compile(r"#\s*noqa:\s*MUTABLE_OK")
+SLOTS_OK_RE: re.Pattern[str] = re.compile(r"#\s*noqa:\s*SLOTS_OK")
+DICT_OK_RE: re.Pattern[str] = re.compile(r"#\s*noqa:\s*DICT_OK")
+MATCH_OK_RE: re.Pattern[str] = re.compile(r"#\s*noqa:\s*MATCH_OK")
+GENERIC_ERR_OK_RE: re.Pattern[str] = re.compile(r"#\s*noqa:\s*GENERIC_ERR_OK")
+OBJECT_OK_RE: re.Pattern[str] = re.compile(r"#\s*noqa:\s*OBJECT_OK")
+IF_VARIANT_OK_RE: re.Pattern[str] = re.compile(r"#\s*noqa:\s*IF_VARIANT_OK")
+SIZE_OK_RE: re.Pattern[str] = re.compile(r"#\s*noqa:\s*SIZE_OK")
+BROAD_EXCEPT_OK_RE: re.Pattern[str] = re.compile(r"#\s*noqa:\s*BROAD_EXCEPT_OK")
+
+PURE_LOC_LIMIT: int = 250
+
+
+@dataclass(frozen=True, slots=True)
+class Violation:
+ rule: str
+ file: Path
+ line: int
+ col: int
+ message: str
+
+ def render(self) -> str:
+ return f"{self.file}:{self.line}:{self.col}: [{self.rule}] {self.message}"
+
+
+def discover_files(inputs: Iterable[Path]) -> list[Path]:
+ seen: set[Path] = set()
+ for raw in inputs:
+ path = raw.resolve()
+ if not path.exists():
+ print(f"check-no-excuse-rules: input does not exist: {path}", file=sys.stderr)
+ sys.exit(2)
+ if path.is_file():
+ if path.suffix == ".py":
+ seen.add(path)
+ continue
+ for child in path.rglob("*.py"):
+ if any(part in EXCLUDED_DIRS for part in child.parts):
+ continue
+ seen.add(child)
+ return sorted(seen)
+
+
+def is_any_node(node: ast.AST) -> bool:
+ if isinstance(node, ast.Name):
+ return node.id == "Any"
+ if isinstance(node, ast.Attribute):
+ return node.attr == "Any"
+ return False
+
+
+def is_cast_callable(node: ast.AST) -> bool:
+ if isinstance(node, ast.Name):
+ return node.id == "cast"
+ if isinstance(node, ast.Attribute):
+ return node.attr == "cast"
+ return False
+
+
+def find_node_violations(tree: ast.AST, file: Path) -> list[Violation]:
+ violations: list[Violation] = []
+
+ for node in ast.walk(tree):
+ if (
+ isinstance(node, ast.Call)
+ and is_cast_callable(node.func)
+ and node.args
+ and is_any_node(node.args[0])
+ ):
+ violations.append(Violation(
+ rule="cast-any",
+ file=file,
+ line=node.lineno,
+ col=node.col_offset + 1,
+ message="cast(Any, ...) - narrow with isinstance/TypeGuard or use a Protocol/TypedDict",
+ ))
+
+ if isinstance(node, ast.ExceptHandler):
+ if node.type is None:
+ violations.append(Violation(
+ rule="bare-except",
+ file=file,
+ line=node.lineno,
+ col=node.col_offset + 1,
+ message="bare `except:` - catch the narrowest exception you mean",
+ ))
+
+ if len(node.body) != 1:
+ continue
+
+ body = node.body[0]
+ if isinstance(body, ast.Pass):
+ violations.append(Violation(
+ rule="silent-except",
+ file=file,
+ line=body.lineno,
+ col=body.col_offset + 1,
+ message="silent `except: pass` - log, re-raise, or actually handle the error",
+ ))
+ elif (
+ isinstance(body, ast.Expr)
+ and isinstance(body.value, ast.Constant)
+ and body.value.value is Ellipsis
+ ):
+ violations.append(Violation(
+ rule="silent-except",
+ file=file,
+ line=body.lineno,
+ col=body.col_offset + 1,
+ message="silent `except: ...` - log, re-raise, or actually handle the error",
+ ))
+
+ return violations
+
+
+def find_import_violations(tree: ast.AST, source_lines: list[str], file: Path) -> list[Violation]:
+ violations: list[Violation] = []
+
+ def line_text(lineno: int) -> str:
+ index = lineno - 1
+ return source_lines[index] if 0 <= index < len(source_lines) else ""
+
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import): # noqa: IF_VARIANT_OK — filtering walk, not closed union
+ for alias in node.names:
+ top = alias.name.split(".")[0]
+ if top not in BANNED_IMPORTS:
+ continue
+ rule, opt_re, message = BANNED_IMPORTS[top]
+ if opt_re.search(line_text(node.lineno)):
+ continue
+ violations.append(Violation(
+ rule=rule,
+ file=file,
+ line=node.lineno,
+ col=node.col_offset + 1,
+ message=message,
+ ))
+ elif isinstance(node, ast.ImportFrom):
+ top = (node.module or "").split(".")[0]
+ if top not in BANNED_IMPORTS:
+ continue
+ rule, opt_re, message = BANNED_IMPORTS[top]
+ if opt_re.search(line_text(node.lineno)):
+ continue
+ violations.append(Violation(
+ rule=rule,
+ file=file,
+ line=node.lineno,
+ col=node.col_offset + 1,
+ message=message,
+ ))
+
+ return violations
+
+
+def find_comment_violations(source: str, file: Path) -> list[Violation]:
+ """Use tokenize so we don't false-match `# type: ignore` inside string literals."""
+ violations: list[Violation] = []
+ try:
+ tokens = list(tokenize.generate_tokens(io.StringIO(source).readline))
+ except tokenize.TokenError as exc:
+ print(f"check-no-excuse-rules: tokenize failed for {file}: {exc}", file=sys.stderr)
+ return violations
+
+ for tok in tokens:
+ if tok.type != tokenize.COMMENT:
+ continue
+ match = SUPPRESSION_RE.search(tok.string)
+ if not match:
+ continue
+ kind = match.group(1)
+ rule = "type-ignore" if kind == "type" else "pyright-ignore"
+ violations.append(Violation(
+ rule=rule,
+ file=file,
+ line=tok.start[0],
+ col=tok.start[1] + match.start() + 1,
+ message=f"`# {kind}: ignore` - fix the underlying type instead",
+ ))
+ return violations
+
+
+# ─────────────────────────────────────────────────────────────────
+# Rust-like pattern checks
+# ─────────────────────────────────────────────────────────────────
+
+
+def _has_keyword(decorator_node: ast.Call, keyword: str) -> bool | None:
+ """Check if a decorator call has a specific keyword argument.
+
+ Returns True if keyword is True, False if keyword is False or absent, None if not a Call.
+ """
+ for kw in decorator_node.keywords:
+ if kw.arg == keyword and isinstance(kw.value, ast.Constant):
+ return bool(kw.value.value)
+ return False
+
+
+def _is_dataclass_decorator(node: ast.expr) -> tuple[bool, ast.Call | None]:
+ """Return (is_dataclass, call_node_or_None)."""
+ if isinstance(node, ast.Name) and node.id == "dataclass":
+ return True, None
+ if isinstance(node, ast.Attribute) and node.attr == "dataclass":
+ return True, None
+ if isinstance(node, ast.Call):
+ inner, _ = _is_dataclass_decorator(node.func)
+ if inner:
+ return True, node
+ return False, None
+
+
+def find_dataclass_violations(
+ tree: ast.Module, source_lines: list[str], file: Path,
+) -> list[Violation]:
+ """Check @dataclass decorators for frozen=True and slots=True."""
+ violations: list[Violation] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.ClassDef):
+ continue
+ for dec in node.decorator_list:
+ is_dc, call_node = _is_dataclass_decorator(dec)
+ if not is_dc:
+ continue
+
+ # Get the line of the decorator for opt-out check
+ dec_line = source_lines[dec.lineno - 1] if dec.lineno <= len(source_lines) else ""
+
+ if call_node is not None:
+ has_frozen = _has_keyword(call_node, "frozen")
+ has_slots = _has_keyword(call_node, "slots")
+ else:
+ # bare @dataclass with no arguments
+ has_frozen = False
+ has_slots = False
+
+ if not has_frozen and not MUTABLE_OK_RE.search(dec_line):
+ violations.append(Violation(
+ rule="mutable-dataclass",
+ file=file,
+ line=dec.lineno,
+ col=dec.col_offset + 1,
+ message=f"class {node.name}: @dataclass without frozen=True",
+ ))
+
+ if not has_slots and not SLOTS_OK_RE.search(dec_line):
+ violations.append(Violation(
+ rule="missing-slots",
+ file=file,
+ line=dec.lineno,
+ col=dec.col_offset + 1,
+ message=f"class {node.name}: @dataclass without slots=True",
+ ))
+ return violations
+
+
+def find_dict_return_violations(
+ tree: ast.Module, source_lines: list[str], file: Path,
+) -> list[Violation]:
+ """Check for functions returning bare `dict` type."""
+ violations: list[Violation] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ ret = node.returns
+ if ret is None:
+ continue
+ # Check for bare `dict` return annotation
+ is_bare_dict = (
+ (isinstance(ret, ast.Name) and ret.id == "dict")
+ or (isinstance(ret, ast.Attribute) and ret.attr == "dict")
+ )
+ if not is_bare_dict:
+ continue
+
+ func_line = source_lines[node.lineno - 1] if node.lineno <= len(source_lines) else ""
+ if DICT_OK_RE.search(func_line):
+ continue
+
+ violations.append(Violation(
+ rule="raw-dict-return",
+ file=file,
+ line=node.lineno,
+ col=node.col_offset + 1,
+ message=f"`{node.name}` returns bare dict - use TypedDict/dataclass/Pydantic model",
+ ))
+ return violations
+
+
+def find_match_violations(
+ tree: ast.Module, source_lines: list[str], file: Path,
+) -> list[Violation]:
+ """Check match statements for assert_never in default case."""
+ violations: list[Violation] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Match):
+ continue
+
+ match_line = source_lines[node.lineno - 1] if node.lineno <= len(source_lines) else ""
+ if MATCH_OK_RE.search(match_line):
+ continue
+
+ has_assert_never = False
+ for case in node.cases:
+ # Wildcard: `case _:` -> MatchAs(pattern=None, name=None)
+ # `case _ as x:` -> MatchAs(pattern=MatchAs(pattern=None, name=None), name="x")
+ pattern = case.pattern
+ is_wildcard = (
+ isinstance(pattern, ast.MatchAs)
+ and (
+ pattern.pattern is None
+ or (
+ isinstance(pattern.pattern, ast.MatchAs)
+ and pattern.pattern.pattern is None
+ and pattern.pattern.name is None
+ )
+ )
+ )
+ if not is_wildcard:
+ continue
+ # Check if body contains assert_never call
+ for stmt in case.body:
+ if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call):
+ func = stmt.value.func
+ if (
+ (isinstance(func, ast.Name) and func.id == "assert_never")
+ or (isinstance(func, ast.Attribute) and func.attr == "assert_never")
+ ):
+ has_assert_never = True
+ break
+
+ if not has_assert_never:
+ violations.append(Violation(
+ rule="missing-assert-never",
+ file=file,
+ line=node.lineno,
+ col=node.col_offset + 1,
+ message="match without `case _: assert_never(x)` default",
+ ))
+ return violations
+
+
+def find_generic_exception_violations(
+ tree: ast.Module, source_lines: list[str], file: Path,
+) -> list[Violation]:
+ """Check for raise ValueError/TypeError/RuntimeError with bare string or f-string."""
+ GENERIC_EXCEPTIONS = {"ValueError", "TypeError", "RuntimeError", "KeyError"}
+ violations: list[Violation] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Raise) or node.exc is None:
+ continue
+ exc = node.exc
+ # Match: raise SomeError("string literal")
+ if not isinstance(exc, ast.Call):
+ continue
+ func = exc.func
+ exc_name: str | None = None
+ if isinstance(func, ast.Name) and func.id in GENERIC_EXCEPTIONS:
+ exc_name = func.id
+ elif isinstance(func, ast.Attribute) and func.attr in GENERIC_EXCEPTIONS:
+ exc_name = func.attr
+ if exc_name is None:
+ continue
+ # Check if all arguments are string literals or f-strings
+ if not exc.args:
+ continue
+ all_str = all(
+ (isinstance(arg, ast.Constant) and isinstance(arg.value, str))
+ or isinstance(arg, ast.JoinedStr)
+ for arg in exc.args
+ )
+ if not all_str:
+ continue
+
+ raise_line = source_lines[node.lineno - 1] if node.lineno <= len(source_lines) else ""
+ if GENERIC_ERR_OK_RE.search(raise_line):
+ continue
+
+ violations.append(Violation(
+ rule="generic-exception",
+ file=file,
+ line=node.lineno,
+ col=node.col_offset + 1,
+ message=f"`raise {exc_name}(\"...\")` - define a typed error class instead",
+ ))
+ return violations
+
+
+def _is_isinstance_test(node: ast.expr) -> bool:
+ """Check if node is an isinstance() call."""
+ return (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "isinstance"
+ )
+
+
+def _is_enum_comparison(node: ast.expr) -> bool:
+ """Check if node is `x == Enum.VALUE` or `x is Enum.VALUE`."""
+ if isinstance(node, ast.Compare) and len(node.ops) == 1:
+ op = node.ops[0]
+ if isinstance(op, (ast.Eq, ast.Is)):
+ comparator = node.comparators[0]
+ # x == Enum.VALUE (attribute access on the right)
+ if isinstance(comparator, ast.Attribute):
+ return True
+ # Enum.VALUE == x (attribute access on the left)
+ if isinstance(node.left, ast.Attribute):
+ return True
+ return False
+
+
+def find_object_annotation_violations(
+ tree: ast.Module, source_lines: list[str], file: Path,
+) -> list[Violation]:
+ """Check for `object` used as a type annotation."""
+ violations: list[Violation] = []
+
+ def _check_annotation(ann: ast.expr | None) -> None:
+ if ann is None:
+ return
+ for child in ast.walk(ann):
+ if isinstance(child, ast.Name) and child.id == "object":
+ line = source_lines[child.lineno - 1] if child.lineno <= len(source_lines) else ""
+ if OBJECT_OK_RE.search(line):
+ return
+ violations.append(Violation(
+ rule="no-object",
+ file=file,
+ line=child.lineno,
+ col=child.col_offset + 1,
+ message="`object` as type annotation \u2014 use Protocol, TypeVar, or union",
+ ))
+
+ for node in ast.walk(tree):
+ match node: # noqa: MATCH_OK — filtering walk, not discriminating a closed union
+ case ast.FunctionDef() | ast.AsyncFunctionDef():
+ all_args = (
+ node.args.args
+ + node.args.posonlyargs
+ + node.args.kwonlyargs
+ )
+ for arg in all_args:
+ _check_annotation(arg.annotation)
+ if node.args.vararg:
+ _check_annotation(node.args.vararg.annotation)
+ if node.args.kwarg:
+ _check_annotation(node.args.kwarg.annotation)
+ _check_annotation(node.returns)
+ case ast.AnnAssign():
+ _check_annotation(node.annotation)
+ return violations
+
+
+def find_if_elif_variant_violations(
+ tree: ast.Module, source_lines: list[str], file: Path,
+) -> list[Violation]:
+ """Check for if/elif chains on isinstance or enum comparison."""
+ violations: list[Violation] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.If):
+ continue
+
+ line = source_lines[node.lineno - 1] if node.lineno <= len(source_lines) else ""
+ if IF_VARIANT_OK_RE.search(line):
+ continue
+
+ is_variant_test = _is_isinstance_test(node.test) or _is_enum_comparison(node.test)
+ if not is_variant_test:
+ continue
+
+ # Must have at least one elif that is also a variant test
+ orelse = node.orelse
+ while orelse and len(orelse) == 1 and isinstance(orelse[0], ast.If):
+ elif_node = orelse[0]
+ if _is_isinstance_test(elif_node.test) or _is_enum_comparison(elif_node.test):
+ violations.append(Violation(
+ rule="if-elif-on-variant",
+ file=file,
+ line=node.lineno,
+ col=node.col_offset + 1,
+ message="isinstance/enum if/elif chain \u2014 use match/case + assert_never",
+ ))
+ break
+ orelse = elif_node.orelse
+ return violations
+
+
+def find_broad_except_violations(
+ tree: ast.Module, source_lines: list[str], file: Path,
+) -> list[Violation]:
+ """Check for except Exception / except BaseException (too broad)."""
+ BROAD_EXCEPTIONS = {"Exception", "BaseException"}
+ violations: list[Violation] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.ExceptHandler):
+ continue
+ if node.type is None:
+ continue # already caught by bare-except
+
+ exc_name: str | None = None
+ if isinstance(node.type, ast.Name) and node.type.id in BROAD_EXCEPTIONS:
+ exc_name = node.type.id
+ elif isinstance(node.type, ast.Attribute) and node.type.attr in BROAD_EXCEPTIONS:
+ exc_name = node.type.attr
+ if exc_name is None:
+ continue
+
+ line = source_lines[node.lineno - 1] if node.lineno <= len(source_lines) else ""
+ if BROAD_EXCEPT_OK_RE.search(line):
+ continue
+
+ violations.append(Violation(
+ rule="broad-except",
+ file=file,
+ line=node.lineno,
+ col=node.col_offset + 1,
+ message=f"`except {exc_name}` is too broad \u2014 catch the specific exception you expect",
+ ))
+ return violations
+
+
+def find_oversized_module_violations(
+ source_lines: list[str], file: Path,
+) -> list[Violation]:
+ """Check if file exceeds 250 pure LOC (non-blank, non-comment)."""
+ # File-level opt-out in first 10 lines (shebang + script metadata can push it down)
+ for line in source_lines[:10]:
+ if SIZE_OK_RE.search(line):
+ return []
+
+ pure_loc = sum(
+ 1 for line in source_lines
+ if line.strip() and not line.strip().startswith("#")
+ )
+ if pure_loc > PURE_LOC_LIMIT:
+ return [Violation(
+ rule="oversized-module",
+ file=file,
+ line=1,
+ col=1,
+ message=f"{pure_loc} pure LOC (limit: {PURE_LOC_LIMIT}) \u2014 split by responsibility",
+ )]
+ return []
+
+
+def check_file(file: Path) -> list[Violation]:
+ source = file.read_text(encoding="utf-8")
+ try:
+ tree = ast.parse(source, filename=str(file))
+ except SyntaxError as exc:
+ return [Violation(
+ rule="syntax-error",
+ file=file,
+ line=exc.lineno or 1,
+ col=exc.offset or 1,
+ message=f"SyntaxError: {exc.msg}",
+ )]
+
+ source_lines = source.splitlines()
+ return [
+ *find_node_violations(tree, file),
+ *find_import_violations(tree, source_lines, file),
+ *find_comment_violations(source, file),
+ *find_dataclass_violations(tree, source_lines, file),
+ *find_dict_return_violations(tree, source_lines, file),
+ *find_match_violations(tree, source_lines, file),
+ *find_generic_exception_violations(tree, source_lines, file),
+ *find_object_annotation_violations(tree, source_lines, file),
+ *find_if_elif_variant_violations(tree, source_lines, file),
+ *find_oversized_module_violations(source_lines, file),
+ *find_broad_except_violations(tree, source_lines, file),
+ ]
+
+
+def main() -> int:
+ if len(sys.argv) < 2:
+ print("usage: check-no-excuse-rules.py <file-or-dir>...", file=sys.stderr)
+ return 2
+
+ files = discover_files(Path(arg) for arg in sys.argv[1:])
+ if not files:
+ print("check-no-excuse-rules: no .py files found", file=sys.stderr)
+ return 0
+
+ violations: list[Violation] = []
+ for file in files:
+ violations.extend(check_file(file))
+
+ if not violations:
+ print(f"no violations in {len(files)} file(s)")
+ return 0
+
+ for violation in violations:
+ print(violation.render(), file=sys.stderr)
+ print(
+ f"\n{len(violations)} violation(s) in {len(files)} file(s)",
+ file=sys.stderr,
+ )
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/plugins/omo/skills/programming/scripts/python/new-project.py b/plugins/omo/skills/programming/scripts/python/new-project.py
new file mode 100644
index 00000000..da0f74d3
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/python/new-project.py
@@ -0,0 +1,172 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "typer",
+# "rich",
+# ]
+# ///
+
+# ─── How to run ───
+# 1. Install uv (if not installed):
+# curl -LsSf https://astral.sh/uv/install.sh | sh
+# 2. Run:
+# uv run new-project.py myproject
+# uv run new-project.py myproject --path ./workspace
+# uv run new-project.py myproject --lib # library (publishable)
+# ──────────────────
+
+"""Scaffold a new Python project with ultra-strict config from pyproject-strict.md.
+
+Creates via `uv init`, then injects basedpyright + ruff ALL + pytest config.
+"""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+from pathlib import Path
+
+import typer
+from rich import print as rprint
+
+# ── Strict tool config (from pyproject-strict.md) ──
+
+TOOL_CONFIG = '''
+[dependency-groups]
+dev = [
+ "basedpyright>=1.21",
+ "ruff>=0.8",
+ "pytest>=8",
+ "pytest-cov>=5",
+]
+
+[tool.basedpyright]
+typeCheckingMode = "all"
+pythonVersion = "3.13"
+reportMissingTypeStubs = false
+reportUnknownMemberType = false
+reportUnknownArgumentType = false
+reportUnknownVariableType = false
+reportUnknownLambdaType = false
+reportUnknownParameterType = false
+reportMissingParameterType = false
+reportUnnecessaryIsInstance = false
+reportUnusedCallResult = false
+reportImplicitOverride = false
+
+[tool.ruff]
+target-version = "py313"
+line-length = 120
+
+[tool.ruff.lint]
+select = ["ALL"]
+ignore = [
+ "COM812", # trailing comma (conflicts with formatter)
+ "ISC001", # single-line string concat (conflicts with formatter)
+ "D1", # undocumented-public-* (too noisy early on)
+ "ANN101", # deprecated: self annotation
+ "ANN102", # deprecated: cls annotation
+ "S101", # assert used (pytest needs it)
+ "PLR2004", # magic-value-comparison (test data)
+ "FBT", # boolean-trap (too strict for CLIs)
+ "TD", # flake8-todos (noisy)
+ "FIX", # fixme (noisy)
+]
+
+[tool.ruff.lint.per-file-ignores]
+"tests/**/*.py" = ["S101", "PLR2004", "SLF001", "D", "ARG", "ANN"]
+
+[tool.ruff.lint.pydocstyle]
+convention = "google"
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+addopts = "-ra --strict-markers --strict-config"
+'''
+
+GITIGNORE = """\
+__pycache__/
+*.py[cod]
+*.so
+.venv/
+dist/
+*.egg-info/
+.coverage
+htmlcov/
+.basedpyright/
+.ruff_cache/
+"""
+
+
+def main(
+ name: str = typer.Argument(help="Project name"),
+ path: Path = typer.Option(Path("."), "--path", "-p", help="Parent directory"),
+ lib: bool = typer.Option(False, "--lib", help="Create as publishable library (uv init --lib)"),
+) -> None:
+ """Create a new Python project with ultra-strict config."""
+ project_dir = path / name
+
+ if project_dir.exists():
+ rprint(f"[red]Error:[/red] {project_dir} already exists")
+ raise SystemExit(1)
+
+ # Run uv init
+ cmd = ["uv", "init", "--lib" if lib else "--app", str(project_dir)]
+ result = subprocess.run(cmd, capture_output=True, text=True)
+ if result.returncode != 0:
+ rprint(f"[red]uv init failed:[/red] {result.stderr}")
+ raise SystemExit(1)
+
+ # Read existing pyproject.toml
+ pyproject_path = project_dir / "pyproject.toml"
+ content = pyproject_path.read_text()
+
+ # Remove the default [dependency-groups] if uv init created one
+ # (we'll replace it with our strict version)
+ lines = content.splitlines(keepends=True)
+ filtered: list[str] = []
+ skip = False
+ for line in lines:
+ if line.strip().startswith("[dependency-groups]"):
+ skip = True
+ continue
+ if skip and line.strip().startswith("["):
+ skip = False
+ if not skip:
+ filtered.append(line)
+
+ content = "".join(filtered).rstrip("\n") + "\n"
+
+ # Append strict tool config
+ content += TOOL_CONFIG
+
+ pyproject_path.write_text(content)
+
+ # Add dev dependencies
+ subprocess.run(
+ ["uv", "add", "--dev", "basedpyright", "ruff", "pytest", "pytest-cov"],
+ cwd=project_dir,
+ capture_output=True,
+ )
+
+ # Create tests directory
+ tests_dir = project_dir / "tests"
+ tests_dir.mkdir(exist_ok=True)
+ (tests_dir / "__init__.py").touch()
+
+ # Overwrite .gitignore
+ (project_dir / ".gitignore").write_text(GITIGNORE)
+
+ # Create py.typed marker for libraries
+ if lib:
+ src_dir = project_dir / "src" / name.replace("-", "_")
+ if src_dir.exists():
+ (src_dir / "py.typed").touch()
+
+ rprint(f"[green]✓[/green] Created: [bold]{project_dir}[/bold]")
+ rprint(f" cd {name} && uv sync && uv run basedpyright . && uv run ruff check .")
+
+
+if __name__ == "__main__":
+ typer.run(main)
diff --git a/plugins/omo/skills/programming/scripts/python/new-script.py b/plugins/omo/skills/programming/scripts/python/new-script.py
new file mode 100644
index 00000000..3e997368
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/python/new-script.py
@@ -0,0 +1,116 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "typer",
+# "rich",
+# ]
+# ///
+
+# ─── How to run ───
+# 1. Install uv (if not installed):
+# curl -LsSf https://astral.sh/uv/install.sh | sh
+# 2. Run:
+# uv run new-script.py my_tool
+# uv run new-script.py my_tool --output ./scripts/my_tool.py
+# uv run new-script.py my_tool --deps 'httpx2[http2,brotli,zstd]' --deps rich --deps polars
+# uv run new-script.py my_tool --py 3.13
+# ──────────────────
+
+"""Generate a PEP 723 Python script with all boilerplate pre-filled.
+
+Creates a new .py file with:
+ - uv shebang
+ - PEP 723 inline metadata (requires-python + dependencies)
+ - Mandatory "How to run" comment block
+ - from __future__ import annotations
+ - main() + if __name__ guard
+
+By default writes to a temp directory and prints the path.
+"""
+
+from __future__ import annotations
+
+import os
+import stat
+import sys
+import tempfile
+from pathlib import Path
+
+import typer
+from rich import print as rprint
+
+
+TEMPLATE = '''\
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">={python_version}"
+# dependencies = [
+{deps_block}# ]
+# ///
+
+# ─── How to run ───
+# 1. Install uv (if not installed):
+# curl -LsSf https://astral.sh/uv/install.sh | sh
+# 2. Run directly (no venv, no pip install needed):
+# uv run {filename} {args_hint}
+# 3. Or make executable and run:
+# chmod +x {filename} && ./{filename}
+# ──────────────────
+
+from __future__ import annotations
+
+
+def main() -> None:
+ """TODO: implement."""
+
+
+if __name__ == "__main__":
+ main()
+'''
+
+
+def main(
+ name: str = typer.Argument(help="Script name (without .py extension)"),
+ output: Path | None = typer.Option(None, "--output", "-o", help="Output path. Default: OS temp directory."),
+ deps: list[str] = typer.Option([], "--deps", "-d", help="Dependencies to include (repeat --deps for each)."),
+ py: str = typer.Option("3.13", "--py", help="Minimum Python version."),
+) -> None:
+ """Generate a new PEP 723 script with all boilerplate pre-filled."""
+ filename = f"{name}.py" if not name.endswith(".py") else name
+ stem = filename.removesuffix(".py")
+
+ if output is not None:
+ dest = Path(output)
+ else:
+ tmp_dir = Path(tempfile.gettempdir()) / "uv-scripts"
+ tmp_dir.mkdir(exist_ok=True)
+ dest = tmp_dir / filename
+
+ dep_list = deps or []
+ if dep_list:
+ deps_block = "".join(f'# "{d}",\n' for d in dep_list)
+ else:
+ deps_block = '# # add deps here, e.g.: "httpx2[http2,brotli,zstd]"\n'
+
+ content = TEMPLATE.format(
+ python_version=py,
+ deps_block=deps_block,
+ filename=filename,
+ args_hint="",
+ )
+
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_text(content)
+
+ # Make executable on Unix
+ if sys.platform != "win32":
+ st = dest.stat()
+ dest.chmod(st.st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
+
+ rprint(f"[green]✓[/green] Created: [bold]{dest}[/bold]")
+ rprint(f" Run: [cyan]uv run {dest}[/cyan]")
+
+
+if __name__ == "__main__":
+ typer.run(main)
diff --git a/plugins/omo/skills/programming/scripts/rust/check-no-excuse-rules.py b/plugins/omo/skills/programming/scripts/rust/check-no-excuse-rules.py
new file mode 100755
index 00000000..2c2c5413
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/rust/check-no-excuse-rules.py
@@ -0,0 +1,296 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.11"
+# dependencies = []
+# ///
+#
+# How to run:
+# uv run --script check-no-excuse-rules.py src/lib.rs src/main.rs
+# uv run --script check-no-excuse-rules.py src/ # recursively finds .rs files
+# uv run --script check-no-excuse-rules.py . # entire tree
+#
+# No-excuse rule checker for Rust files — Python rewrite of check-no-excuse-rules.sh.
+# Only rules enforceable via pure text matching live here.
+# Everything semantic is on clippy + miri + nextest.
+#
+# Rules:
+# unwrap .unwrap() outside tests without // SAFE-UNWRAP:
+# expect .expect() outside tests without // SAFE-EXPECT:
+# placeholder-macro todo!/unimplemented!/unreachable!/unreachable_unchecked! in committed code
+# box-dyn-error Box<dyn Error> in non-test code
+# lib-panic panic!() in library code
+# unsafe-no-safety unsafe { without // SAFETY: in preceding 5 lines
+# unjustified-clippy-allow #[allow(clippy::...)] without // CLIPPY-ALLOW:
+# narrowing-as-cast possible narrowing 'as' cast
+#
+# Opt-out: place the appropriate comment on the previous line:
+# // SAFE-UNWRAP: <reason>
+# // SAFE-EXPECT: <reason>
+# // SAFETY: <reason> (for unsafe blocks, within 5 lines above)
+# // CLIPPY-ALLOW: <reason>
+#
+# Test paths (exempt from unwrap/expect/placeholder/box-dyn-error/lib-panic):
+# tests/, benches/, examples/, build.rs, *_test.rs, #[cfg(test)] regions
+
+from __future__ import annotations
+
+import re
+import sys
+from pathlib import Path
+
+# ---------------------------------------------------------------------------
+# Patterns (compiled once)
+# ---------------------------------------------------------------------------
+
+RE_UNWRAP = re.compile(r"\.unwrap\(\)")
+RE_EXPECT = re.compile(r"\.expect\(")
+RE_PLACEHOLDER = re.compile(r"\b(todo!|unimplemented!|unreachable!|unreachable_unchecked!)")
+RE_BOX_DYN_ERROR = re.compile(r"Box<dyn\s+Error")
+RE_PANIC = re.compile(r"\bpanic!\(")
+RE_UNSAFE_BLOCK = re.compile(r"\bunsafe\s*\{")
+RE_CLIPPY_ALLOW = re.compile(r"#\[allow\(clippy::")
+RE_CFG_TEST = re.compile(r"#\[cfg\(test\)\]")
+RE_SAFE_UNWRAP = re.compile(r"//\s*SAFE-UNWRAP:")
+RE_SAFE_EXPECT = re.compile(r"//\s*SAFE-EXPECT:")
+RE_SAFETY = re.compile(r"//\s*SAFETY:")
+RE_CLIPPY_ALLOW_JUST = re.compile(r"//\s*CLIPPY-ALLOW:")
+
+# Narrowing cast: (wider) as (narrower)
+# Wider types that lose bits when cast to narrower targets.
+# No leading \b — must match e.g. `999u64 as u32` where a digit precedes the type.
+_WIDER = r"(?:u16|u32|u64|u128|usize|i16|i32|i64|i128|isize)"
+_NARROWER = r"(?:u8|u16|u32|i8|i16|i32)"
+RE_NARROWING_CAST = re.compile(
+ rf"{_WIDER}\s+as\s+{_NARROWER}"
+)
+
+# Test-path fragments.
+_TEST_PATH_PARTS = {"tests", "benches", "examples"}
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+violations = 0
+
+
+def report(file: str, line: int, rule: str, detail: str) -> None:
+ """Emit a GitHub-Actions-compatible error annotation to stderr."""
+ global violations
+ print(f"::error file={file},line={line}::[{rule}] {detail}", file=sys.stderr)
+ violations += 1
+
+
+def is_test_path(path: Path) -> bool:
+ """Return True if *path* is in a test/bench/example directory or is a test file."""
+ parts = path.parts
+ for part in parts:
+ if part in _TEST_PATH_PARTS:
+ return True
+ if path.name == "build.rs":
+ return True
+ if path.name.endswith("_test.rs"):
+ return True
+ return False
+
+
+def is_lib_path(file: Path) -> bool:
+ """Heuristic: is this file library code (not main.rs, not src/bin/*)."""
+ parts = path_parts_str(file)
+ # Must live under src/
+ if "src" not in parts:
+ return False
+ if file.name == "main.rs":
+ return False
+ # src/bin/* is binary code
+ try:
+ src_idx = parts.index("src")
+ if src_idx + 1 < len(parts) and parts[src_idx + 1] == "bin":
+ return False
+ except ValueError:
+ return False
+ return True
+
+
+def path_parts_str(p: Path) -> list[str]:
+ return list(p.parts)
+
+
+def strip_line_comment(line: str) -> str:
+ """Return the portion of *line* before any ``//`` line comment.
+
+ This is a crude heuristic — it does not handle ``//`` inside string
+ literals, but matches the behaviour of the bash version.
+ """
+ idx = line.find("//")
+ if idx == -1:
+ return line
+ return line[:idx]
+
+
+def collect_rs_files(args: list[str]) -> list[Path]:
+ """Expand CLI arguments: files are kept as-is, directories are walked."""
+ result: list[Path] = []
+ for arg in args:
+ p = Path(arg)
+ if p.is_file():
+ if p.suffix == ".rs":
+ result.append(p)
+ elif p.is_dir():
+ result.extend(sorted(p.rglob("*.rs")))
+ # Ignore non-existent / non-.rs
+ return result
+
+
+# ---------------------------------------------------------------------------
+# Main checker
+# ---------------------------------------------------------------------------
+
+def check_file(file: Path) -> None:
+ in_test_file = is_test_path(file)
+ in_cfg_test = False
+ cfg_test_brace_depth = 0
+
+ try:
+ lines = file.read_text(encoding="utf-8", errors="replace").splitlines()
+ except OSError as exc:
+ print(f"warning: cannot read {file}: {exc}", file=sys.stderr)
+ return
+
+ for line_no_0, raw_line in enumerate(lines):
+ line_no = line_no_0 + 1 # 1-indexed
+
+ # --- #[cfg(test)] region tracker ---
+ if RE_CFG_TEST.search(raw_line):
+ in_cfg_test = True
+ cfg_test_brace_depth = 0
+
+ if in_cfg_test:
+ opens = raw_line.count("{")
+ closes = raw_line.count("}")
+ cfg_test_brace_depth += opens - closes
+ if cfg_test_brace_depth <= 0 and not RE_CFG_TEST.search(raw_line):
+ in_cfg_test = False
+
+ exempt = in_test_file or in_cfg_test
+ code_only = strip_line_comment(raw_line)
+
+ if not exempt:
+ # .unwrap()
+ if RE_UNWRAP.search(code_only):
+ prev = lines[line_no_0 - 1] if line_no_0 > 0 else ""
+ if not RE_SAFE_UNWRAP.search(prev):
+ report(
+ str(file), line_no, "unwrap",
+ ".unwrap() outside tests - use ? / ok_or / pattern match "
+ "or annotate previous line with // SAFE-UNWRAP: <reason>",
+ )
+
+ # .expect(...)
+ if RE_EXPECT.search(code_only):
+ prev = lines[line_no_0 - 1] if line_no_0 > 0 else ""
+ if not RE_SAFE_EXPECT.search(prev):
+ report(
+ str(file), line_no, "expect",
+ ".expect() outside tests - use ? or annotate previous "
+ "line with // SAFE-EXPECT: <reason>",
+ )
+
+ # todo!/unimplemented!/unreachable!/unreachable_unchecked!
+ if RE_PLACEHOLDER.search(code_only):
+ report(
+ str(file), line_no, "placeholder-macro",
+ "todo!/unimplemented!/unreachable! in committed code",
+ )
+
+ # Box<dyn Error>
+ if RE_BOX_DYN_ERROR.search(code_only):
+ report(
+ str(file), line_no, "box-dyn-error",
+ "Box<dyn Error> in non-test code - use anyhow::Error (apps) "
+ "or thiserror enum (libs)",
+ )
+
+ # panic!() in library code
+ if is_lib_path(file) and RE_PANIC.search(code_only):
+ report(
+ str(file), line_no, "lib-panic",
+ "panic!() in library code - return Result",
+ )
+
+ # unsafe { without // SAFETY: — always enforced, even in tests
+ if RE_UNSAFE_BLOCK.search(code_only):
+ start = max(0, line_no_0 - 5)
+ window = "\n".join(lines[start : line_no_0 + 1])
+ if not RE_SAFETY.search(window):
+ report(
+ str(file), line_no, "unsafe-no-safety-comment",
+ "unsafe block without // SAFETY: comment in preceding 5 lines",
+ )
+
+ # #[allow(clippy::...)] without // CLIPPY-ALLOW: — always enforced
+ if RE_CLIPPY_ALLOW.search(code_only):
+ prev = lines[line_no_0 - 1] if line_no_0 > 0 else ""
+ if not RE_CLIPPY_ALLOW_JUST.search(prev):
+ report(
+ str(file), line_no, "unjustified-clippy-allow",
+ "#[allow(clippy::...)] without // CLIPPY-ALLOW: <reason> on "
+ "previous line",
+ )
+
+ # Narrowing numeric `as` casts
+ if RE_NARROWING_CAST.search(code_only):
+ report(
+ str(file), line_no, "narrowing-as-cast",
+ "possible narrowing 'as' cast - use TryFrom / try_into() for "
+ "fallible conversion",
+ )
+
+
+# ---------------------------------------------------------------------------
+# Entry point
+# ---------------------------------------------------------------------------
+
+def main() -> None:
+ global violations
+
+ if len(sys.argv) < 2:
+ print(f"Usage: {sys.argv[0]} <file.rs|dir> [file.rs|dir ...]", file=sys.stderr)
+ sys.exit(2)
+
+ files = collect_rs_files(sys.argv[1:])
+ if not files:
+ print("warning: no .rs files found in the given arguments", file=sys.stderr)
+ sys.exit(0)
+
+ for f in files:
+ check_file(f)
+
+ if violations > 0:
+ print("", file=sys.stderr)
+ print(
+ f"rust-programmer: {violations} violation(s). Fix before declaring work done.",
+ file=sys.stderr,
+ )
+ print("", file=sys.stderr)
+ print("Then run the full toolchain gate:", file=sys.stderr)
+ print(" cargo +stable fmt --all -- --check", file=sys.stderr)
+ print(
+ " cargo +stable clippy --all-targets --all-features -- -D warnings",
+ file=sys.stderr,
+ )
+ print(" cargo nextest run --all-targets --all-features", file=sys.stderr)
+ print(
+ " cargo +nightly miri nextest run --all-features # if unsafe touched",
+ file=sys.stderr,
+ )
+ print(" cargo machete", file=sys.stderr)
+ print(" cargo deny check", file=sys.stderr)
+ sys.exit(1)
+
+ print(f"rust-programmer: no-excuse rules passed for {len(files)} file(s).")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/plugins/omo/skills/programming/scripts/rust/check-no-excuse-rules.sh b/plugins/omo/skills/programming/scripts/rust/check-no-excuse-rules.sh
new file mode 100755
index 00000000..d4fa8e91
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/rust/check-no-excuse-rules.sh
@@ -0,0 +1,158 @@
+#!/usr/bin/env bash
+# No-excuse rule checker for Rust files.
+# Mirrors the philosophy of python-programmer / typescript-programmer scripts:
+# only rules that can be enforced via pure text matching live here.
+# Everything semantic is on clippy + miri + nextest.
+
+set -euo pipefail
+
+if [ $# -eq 0 ]; then
+ echo "Usage: $0 <file.rs> [file.rs ...]" >&2
+ exit 2
+fi
+
+violations=0
+report() {
+ local file="$1"
+ local line="$2"
+ local rule="$3"
+ local detail="$4"
+ echo "::error file=${file},line=${line}::[${rule}] ${detail}" >&2
+ violations=$((violations + 1))
+}
+
+is_test_path() {
+ local path="$1"
+ case "$path" in
+ */tests/*|*/benches/*|*/examples/*|*/build.rs|*_test.rs|tests/*|benches/*|examples/*) return 0 ;;
+ esac
+ # In-file #[cfg(test)] modules are handled per-line below.
+ return 1
+}
+
+for file in "$@"; do
+ [ -f "$file" ] || continue
+ case "$file" in
+ *.rs) ;;
+ *) continue ;;
+ esac
+
+ if is_test_path "$file"; then
+ # Test files are exempt from unwrap/expect/todo rules.
+ # Still enforce unsafe-comment, allow-comment, panic-in-lib rules below
+ # by setting a marker - keeping the loop unified.
+ in_test_file=1
+ else
+ in_test_file=0
+ fi
+
+ # Track #[cfg(test)] regions for per-line exemptions.
+ in_cfg_test=0
+ cfg_test_brace_depth=0
+ line_no=0
+
+ while IFS= read -r raw_line || [ -n "$raw_line" ]; do
+ line_no=$((line_no + 1))
+ line="$raw_line"
+
+ # Crude #[cfg(test)] region tracker: when we see #[cfg(test)] on a
+ # line followed by a mod with `{`, count braces until depth returns
+ # to zero. This is approximate but matches typical formatting.
+ if [[ "$line" =~ \#\[cfg\(test\)\] ]]; then
+ in_cfg_test=1
+ cfg_test_brace_depth=0
+ fi
+ if [ "$in_cfg_test" -eq 1 ]; then
+ opens=$(printf '%s' "$line" | tr -cd '{' | wc -c)
+ closes=$(printf '%s' "$line" | tr -cd '}' | wc -c)
+ cfg_test_brace_depth=$((cfg_test_brace_depth + opens - closes))
+ if [ "$cfg_test_brace_depth" -le 0 ] && [[ ! "$line" =~ \#\[cfg\(test\)\] ]]; then
+ in_cfg_test=0
+ fi
+ fi
+
+ exempt=0
+ [ "$in_test_file" -eq 1 ] && exempt=1
+ [ "$in_cfg_test" -eq 1 ] && exempt=1
+
+ # Strip line comments before pattern checks - so doc comments and
+ # explanatory prose do not trip the regexes.
+ code_only="${line%%//*}"
+
+ if [ "$exempt" -eq 0 ]; then
+ # .unwrap()
+ if [[ "$code_only" =~ \.unwrap\(\) ]]; then
+ # Allow if previous line had // SAFE-UNWRAP: comment
+ prev_line=$(sed -n "$((line_no - 1))p" "$file" 2>/dev/null || true)
+ if [[ ! "$prev_line" =~ //[[:space:]]*SAFE-UNWRAP: ]]; then
+ report "$file" "$line_no" "unwrap" ".unwrap() outside tests - use ? / ok_or / pattern match or annotate previous line with // SAFE-UNWRAP: <reason>"
+ fi
+ fi
+
+ # .expect("...")
+ if [[ "$code_only" =~ \.expect\( ]]; then
+ prev_line=$(sed -n "$((line_no - 1))p" "$file" 2>/dev/null || true)
+ if [[ ! "$prev_line" =~ //[[:space:]]*SAFE-EXPECT: ]]; then
+ report "$file" "$line_no" "expect" ".expect() outside tests - use ? or annotate previous line with // SAFE-EXPECT: <reason>"
+ fi
+ fi
+
+ # todo!() / unimplemented!() / unreachable!()
+ if [[ "$code_only" =~ (todo!|unimplemented!|unreachable!|unreachable_unchecked!) ]]; then
+ report "$file" "$line_no" "placeholder-macro" "todo!/unimplemented!/unreachable! in committed code"
+ fi
+
+ # Box<dyn Error
+ if [[ "$code_only" =~ Box\<dyn[[:space:]]+Error ]]; then
+ report "$file" "$line_no" "box-dyn-error" "Box<dyn Error> in non-test code - use anyhow::Error (apps) or thiserror enum (libs)"
+ fi
+
+ # panic!( in lib
+ if [[ "$file" == */src/lib.rs || "$file" == */src/*/mod.rs || ( "$file" == */src/*.rs && "$file" != */src/main.rs && "$file" != */src/bin/* ) ]]; then
+ if [[ "$code_only" =~ panic!\( ]]; then
+ report "$file" "$line_no" "lib-panic" "panic!() in library code - return Result"
+ fi
+ fi
+ fi
+
+ # unsafe { without preceding // SAFETY: in the last 5 lines (always enforced)
+ if [[ "$code_only" =~ unsafe[[:space:]]*\{ ]]; then
+ start=$((line_no > 5 ? line_no - 5 : 1))
+ window=$(sed -n "${start},${line_no}p" "$file" 2>/dev/null || true)
+ if [[ ! "$window" =~ //[[:space:]]*SAFETY: ]]; then
+ report "$file" "$line_no" "unsafe-no-safety-comment" "unsafe block without // SAFETY: comment in preceding 5 lines"
+ fi
+ fi
+
+ # #[allow(clippy::...)] without preceding // CLIPPY-ALLOW: justification
+ if [[ "$code_only" =~ \#\[allow\(clippy:: ]]; then
+ prev_line=$(sed -n "$((line_no - 1))p" "$file" 2>/dev/null || true)
+ if [[ ! "$prev_line" =~ //[[:space:]]*CLIPPY-ALLOW: ]]; then
+ report "$file" "$line_no" "unjustified-clippy-allow" "#[allow(clippy::...)] without // CLIPPY-ALLOW: <reason> on previous line"
+ fi
+ fi
+
+ # Narrowing numeric `as` casts - heuristic flag for human review.
+ # Catches the common shapes; precise type analysis belongs to clippy::cast_possible_truncation.
+ if [[ "$code_only" =~ as[[:space:]]+(u8|u16|u32|i8|i16|i32) ]] && \
+ [[ "$code_only" =~ (u16|u32|u64|u128|usize|i16|i32|i64|i128|isize)[[:space:]]+as[[:space:]]+(u8|u16|u32|i8|i16|i32) ]]; then
+ report "$file" "$line_no" "narrowing-as-cast" "possible narrowing 'as' cast - use TryFrom / try_into() for fallible conversion"
+ fi
+ done < "$file"
+done
+
+if [ "$violations" -gt 0 ]; then
+ echo "" >&2
+ echo "rust-programmer: ${violations} violation(s). Fix before declaring work done." >&2
+ echo "" >&2
+ echo "Then run the full toolchain gate:" >&2
+ echo " cargo +stable fmt --all -- --check" >&2
+ echo " cargo +stable clippy --all-targets --all-features -- -D warnings" >&2
+ echo " cargo nextest run --all-targets --all-features" >&2
+ echo " cargo +nightly miri nextest run --all-features # if unsafe touched" >&2
+ echo " cargo machete" >&2
+ echo " cargo deny check" >&2
+ exit 1
+fi
+
+echo "rust-programmer: no-excuse rules passed for $# file(s)."
diff --git a/plugins/omo/skills/programming/scripts/rust/new-project.py b/plugins/omo/skills/programming/scripts/rust/new-project.py
new file mode 100755
index 00000000..2445f805
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/rust/new-project.py
@@ -0,0 +1,175 @@
+#!/usr/bin/env -S uv run --script
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "typer",
+# "rich",
+# ]
+# ///
+
+# ─── How to run ───
+# 1. Install uv (if not installed):
+# curl -LsSf https://astral.sh/uv/install.sh | sh
+# 2. Run:
+# uv run new-project.py myproject
+# uv run new-project.py myproject --path ./workspace
+# ──────────────────
+#
+# Creates a new Rust project with strict lints, deny.toml, rustfmt.toml,
+# rust-toolchain.toml, and .cargo/config.toml pre-configured.
+
+from __future__ import annotations
+
+import subprocess
+import sys
+from pathlib import Path
+
+import typer
+from rich.console import Console
+
+console = Console(stderr=True)
+
+# ── Embedded config contents ─────────────────────────────────────────────
+
+RUST_TOOLCHAIN_TOML = """\
+[toolchain]
+channel = "stable"
+components = ["rustfmt", "clippy", "rust-src"]
+profile = "default"
+"""
+
+CARGO_TOML_LINTS = """
+[lints.rust]
+unsafe_op_in_unsafe_fn = "deny"
+missing_docs = "warn"
+missing_debug_implementations = "warn"
+unreachable_pub = "warn"
+unused_must_use = "deny"
+elided_lifetimes_in_paths = "warn"
+non_ascii_idents = "deny"
+trivial_numeric_casts = "warn"
+unused_lifetimes = "warn"
+single_use_lifetimes = "warn"
+
+[lints.clippy]
+all = { level = "deny", priority = -1 }
+pedantic = { level = "warn", priority = -1 }
+nursery = { level = "warn", priority = -1 }
+cargo = { level = "warn", priority = -1 }
+undocumented_unsafe_blocks = "deny"
+multiple_unsafe_ops_per_block = "deny"
+unwrap_used = "deny"
+expect_used = "deny"
+panic = "deny"
+todo = "deny"
+unimplemented = "deny"
+dbg_macro = "deny"
+print_stdout = "warn"
+print_stderr = "warn"
+module_name_repetitions = { level = "allow" }
+must_use_candidate = { level = "allow" }
+missing_errors_doc = { level = "allow" }
+missing_panics_doc = { level = "allow" }
+"""
+
+CARGO_CONFIG_TOML = """\
+[build]
+rustflags = ["-C", "link-arg=-fuse-ld=lld"]
+
+[target.x86_64-unknown-linux-gnu]
+linker = "clang"
+rustflags = ["-C", "link-arg=-fuse-ld=lld"]
+
+[target.aarch64-apple-darwin]
+rustflags = []
+"""
+
+DENY_TOML = """\
+[advisories]
+vulnerability = "deny"
+unmaintained = "warn"
+yanked = "deny"
+
+[licenses]
+unlicensed = "deny"
+allow = ["MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "ISC", "Unicode-3.0", "Zlib"]
+
+[bans]
+multiple-versions = "warn"
+wildcards = "deny"
+
+[sources]
+unknown-registry = "deny"
+unknown-git = "deny"
+"""
+
+RUSTFMT_TOML = """\
+edition = "2024"
+max_width = 100
+use_field_init_shorthand = true
+use_try_shorthand = true
+"""
+
+# ── Main ─────────────────────────────────────────────────────────────────
+
+app = typer.Typer(add_completion=False)
+
+
+def main(
+ name: str = typer.Argument(help="Name of the new Rust project"),
+ path: Path = typer.Option(
+ Path.cwd(),
+ "--path",
+ "-p",
+ help="Parent directory where the project folder is created",
+ ),
+) -> None:
+ """Scaffold a new Rust project with strict lints and tooling configs."""
+ project_dir = path / name
+
+ # ── cargo init ───────────────────────────────────────────────────
+ console.print(f"[bold green]Creating[/] project [cyan]{name}[/] at [dim]{project_dir}[/]")
+ try:
+ subprocess.run(
+ ["cargo", "init", str(project_dir), "--name", name],
+ check=True,
+ capture_output=True,
+ text=True,
+ )
+ except FileNotFoundError:
+ console.print("[bold red]Error:[/] cargo not found. Install Rust via https://rustup.rs")
+ sys.exit(1)
+ except subprocess.CalledProcessError as exc:
+ console.print(f"[bold red]cargo init failed:[/]\n{exc.stderr}")
+ sys.exit(1)
+
+ # ── rust-toolchain.toml ──────────────────────────────────────────
+ (project_dir / "rust-toolchain.toml").write_text(RUST_TOOLCHAIN_TOML)
+ console.print(" [dim]wrote[/] rust-toolchain.toml")
+
+ # ── Append [lints] to Cargo.toml ─────────────────────────────────
+ cargo_toml = project_dir / "Cargo.toml"
+ with cargo_toml.open("a") as f:
+ f.write(CARGO_TOML_LINTS)
+ console.print(" [dim]appended[/] [lints] to Cargo.toml")
+
+ # ── .cargo/config.toml ───────────────────────────────────────────
+ cargo_config_dir = project_dir / ".cargo"
+ cargo_config_dir.mkdir(parents=True, exist_ok=True)
+ (cargo_config_dir / "config.toml").write_text(CARGO_CONFIG_TOML)
+ console.print(" [dim]wrote[/] .cargo/config.toml")
+
+ # ── deny.toml ────────────────────────────────────────────────────
+ (project_dir / "deny.toml").write_text(DENY_TOML)
+ console.print(" [dim]wrote[/] deny.toml")
+
+ # ── rustfmt.toml ─────────────────────────────────────────────────
+ (project_dir / "rustfmt.toml").write_text(RUSTFMT_TOML)
+ console.print(" [dim]wrote[/] rustfmt.toml")
+
+ console.print(f"\n[bold green]Done![/] cd {project_dir} && cargo check")
+
+
+if __name__ == "__main__":
+ app()
diff --git a/plugins/omo/skills/programming/scripts/typescript/check-no-excuse-rules.ts b/plugins/omo/skills/programming/scripts/typescript/check-no-excuse-rules.ts
new file mode 100644
index 00000000..4ad7875f
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/typescript/check-no-excuse-rules.ts
@@ -0,0 +1,282 @@
+#!/usr/bin/env bun
+/**
+ * Check TypeScript files for no-excuse violations.
+ *
+ * Rules:
+ * no-any-assertion - `as any`
+ * no-unknown-assertion - `as unknown`
+ * no-ts-ignore - `@ts-ignore` comments
+ * no-ts-expect-error - `@ts-expect-error` comments
+ * no-enum - `enum` declarations
+ * no-non-null-assertion - `x!` postfix operator
+ * no-throw-literal - `throw "string"` / `throw 123`
+ * no-mutable-export - `export let` / `export var`
+ * no-any-annotation - `: any` in annotations (opt out: `// no-excuse-ok: any`)
+ * no-explicit-any-return - `(): any` return types (opt out: `// no-excuse-ok: any`)
+ * empty-catch - `catch { }` or `catch (e) { }` with empty body
+ * catch-without-narrowing - catch block that uses error without instanceof narrowing
+ *
+ * Usage:
+ * bun run scripts/check-no-excuse-rules.ts <file-or-dir>...
+ *
+ * Exit codes:
+ * 0 - no violations
+ * 1 - violations found
+ * 2 - input error
+ */
+
+import fs from "node:fs"
+import path from "node:path"
+import process from "node:process"
+import ts from "typescript"
+
+type RuleId =
+ | "no-any-assertion"
+ | "no-unknown-assertion"
+ | "no-ts-ignore"
+ | "no-ts-expect-error"
+ | "no-enum"
+ | "no-non-null-assertion"
+ | "no-throw-literal"
+ | "no-mutable-export"
+ | "no-any-annotation"
+ | "no-explicit-any-return"
+ | "empty-catch"
+ | "catch-without-narrowing"
+
+type Violation = {
+ readonly ruleId: RuleId
+ readonly filePath: string
+ readonly line: number
+ readonly column: number
+ readonly message: string
+}
+
+const INCLUDED_EXTENSIONS = new Set([".ts", ".tsx", ".mts", ".cts"])
+const IGNORED_DIRECTORIES = new Set([
+ ".git", ".next", ".nuxt", ".turbo", ".yarn",
+ "coverage", "dist", "build", "node_modules",
+])
+
+const OPT_OUT_RE = /\/\/\s*no-excuse-ok:\s*any/
+const CATCH_OK_RE = /\/\/\s*no-excuse-ok:\s*catch/
+
+function isIncludedFile(filePath: string): boolean {
+ return INCLUDED_EXTENSIONS.has(path.extname(filePath).toLowerCase())
+}
+
+function isDeclarationFile(filePath: string): boolean {
+ return filePath.endsWith(".d.ts") || filePath.endsWith(".d.mts") || filePath.endsWith(".d.cts")
+}
+
+function discoverFiles(inputs: string[]): string[] {
+ const files: string[] = []
+ for (const input of inputs) {
+ const resolved = path.resolve(input)
+ if (!fs.existsSync(resolved)) {
+ console.error(`Path does not exist: ${resolved}`)
+ process.exit(2)
+ }
+ if (fs.statSync(resolved).isFile()) {
+ if (isIncludedFile(resolved) && !isDeclarationFile(resolved)) files.push(resolved)
+ continue
+ }
+ const walk = (dir: string): void => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ if (entry.isDirectory()) {
+ if (!IGNORED_DIRECTORIES.has(entry.name)) walk(path.join(dir, entry.name))
+ } else if (isIncludedFile(entry.name) && !isDeclarationFile(entry.name)) {
+ files.push(path.join(dir, entry.name))
+ }
+ }
+ }
+ walk(resolved)
+ }
+ return files
+}
+
+function getLineText(sourceFile: ts.SourceFile, line: number): string {
+ const lineStarts = sourceFile.getLineStarts()
+ const start = lineStarts[line]
+ const end = line + 1 < lineStarts.length ? lineStarts[line + 1] : sourceFile.getEnd()
+ return sourceFile.text.slice(start, end)
+}
+
+function analyzeFile(filePath: string): Violation[] {
+ const source = fs.readFileSync(filePath, "utf-8")
+ const sourceFile = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true)
+ const violations: Violation[] = []
+
+ function pos(node: ts.Node): { line: number; column: number } {
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile))
+ return { line: line + 1, column: character + 1 }
+ }
+
+ function lineHasOptOut(node: ts.Node): boolean {
+ const { line } = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile))
+ return OPT_OUT_RE.test(getLineText(sourceFile, line))
+ }
+
+ function visit(node: ts.Node): void {
+ // ── as any / as unknown ──
+ if (ts.isAsExpression(node)) {
+ const typeText = node.type.getText(sourceFile)
+ if (typeText === "any") {
+ const p = pos(node)
+ violations.push({ ruleId: "no-any-assertion", filePath, ...p, message: "`as any` — narrow with type guards or redesign the types" })
+ }
+ if (typeText === "unknown") {
+ const p = pos(node)
+ violations.push({ ruleId: "no-unknown-assertion", filePath, ...p, message: "`as unknown` — redesign the types" })
+ }
+ }
+
+ // ── enum ──
+ if (ts.isEnumDeclaration(node)) {
+ const p = pos(node)
+ violations.push({ ruleId: "no-enum", filePath, ...p, message: "`enum` — use `as const` object + literal union type" })
+ }
+
+ // ── x! non-null assertion ──
+ if (ts.isNonNullExpression(node)) {
+ const p = pos(node)
+ violations.push({ ruleId: "no-non-null-assertion", filePath, ...p, message: "`x!` — use narrowing or optional chaining" })
+ }
+
+ // ── throw "literal" ──
+ if (ts.isThrowStatement(node) && node.expression) {
+ const expr = node.expression
+ if (ts.isStringLiteral(expr) || ts.isNumericLiteral(expr) || ts.isNoSubstitutionTemplateLiteral(expr)) {
+ const p = pos(node)
+ violations.push({ ruleId: "no-throw-literal", filePath, ...p, message: "`throw literal` — throw an Error subclass" })
+ }
+ if (ts.isTemplateExpression(expr)) {
+ const p = pos(node)
+ violations.push({ ruleId: "no-throw-literal", filePath, ...p, message: "`throw template` — throw an Error subclass" })
+ }
+ }
+
+ // ── export let / export var ──
+ if (ts.isVariableStatement(node)) {
+ const hasExport = node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
+ if (hasExport) {
+ const flags = node.declarationList.flags
+ if (!(flags & ts.NodeFlags.Const)) {
+ const p = pos(node)
+ violations.push({ ruleId: "no-mutable-export", filePath, ...p, message: "`export let/var` — use `export const`" })
+ }
+ }
+ }
+
+ // ── : any in annotations ──
+ if (ts.isTypeReferenceNode(node) || node.kind === ts.SyntaxKind.AnyKeyword) {
+ if (node.kind === ts.SyntaxKind.AnyKeyword && !lineHasOptOut(node)) {
+ const parent = node.parent
+ // Skip `as any` — already caught by no-any-assertion
+ if (parent && ts.isAsExpression(parent)) {
+ // already handled
+ } else if (parent && (
+ ts.isParameter(parent) ||
+ ts.isVariableDeclaration(parent) ||
+ ts.isPropertyDeclaration(parent) ||
+ ts.isPropertySignature(parent)
+ )) {
+ const p = pos(node)
+ violations.push({ ruleId: "no-any-annotation", filePath, ...p, message: "`: any` annotation — use `unknown` and narrow" })
+ } else if (parent && (
+ ts.isFunctionDeclaration(parent) ||
+ ts.isMethodDeclaration(parent) ||
+ ts.isArrowFunction(parent) ||
+ ts.isFunctionExpression(parent)
+ )) {
+ const p = pos(node)
+ violations.push({ ruleId: "no-explicit-any-return", filePath, ...p, message: "`(): any` return — use a specific type" })
+ }
+ }
+ }
+
+ // ── empty catch / catch without narrowing ──
+ if (ts.isCatchClause(node)) {
+ const catchLine = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line
+ const catchLineText = getLineText(sourceFile, catchLine)
+ if (!CATCH_OK_RE.test(catchLineText)) {
+ const body = node.block
+ const stmts = body.statements
+
+ if (stmts.length === 0) {
+ // Empty catch — swallows everything silently
+ const p = pos(node)
+ violations.push({ ruleId: "empty-catch", filePath, ...p, message: "empty `catch` block — handle, re-throw, or remove the try/catch" })
+ } else if (node.variableDeclaration) {
+ // Has a bound variable — check if it's narrowed with instanceof
+ const varName = node.variableDeclaration.name.getText(sourceFile)
+ const blockText = body.getText(sourceFile)
+ const hasInstanceof = blockText.includes(`instanceof`)
+ const hasRethrow = blockText.includes(`throw ${varName}`) || blockText.includes(`throw new`)
+ if (!hasInstanceof && !hasRethrow) {
+ const p = pos(node)
+ violations.push({ ruleId: "catch-without-narrowing", filePath, ...p, message: "`catch` without `instanceof` narrowing or re-throw — narrow the error type or re-throw" })
+ }
+ }
+ }
+ }
+
+ ts.forEachChild(node, visit)
+ }
+
+ visit(sourceFile)
+
+ // ── @ts-ignore / @ts-expect-error in comments ──
+ const commentRanges = [
+ ...(ts.getLeadingCommentRanges(source, 0) ?? []),
+ ]
+ // Scan all comments via regex for reliability
+ const commentRegex = /\/\/\s*@ts-(ignore|expect-error)/g
+ let match: RegExpExecArray | null
+ while ((match = commentRegex.exec(source)) !== null) {
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(match.index)
+ const kind = match[1]
+ violations.push({
+ ruleId: kind === "ignore" ? "no-ts-ignore" : "no-ts-expect-error",
+ filePath,
+ line: line + 1,
+ column: character + 1,
+ message: `\`@ts-${kind}\` — fix the underlying type`,
+ })
+ }
+
+ return violations
+}
+
+function formatViolation(v: Violation): string {
+ return `${v.filePath}:${v.line}:${v.column}: [${v.ruleId}] ${v.message}`
+}
+
+function main(): void {
+ const args = process.argv.slice(2)
+ if (args.length === 0) {
+ console.error("usage: check-no-excuse-rules.ts <file-or-dir>...")
+ process.exit(2)
+ }
+
+ const files = discoverFiles(args)
+ if (files.length === 0) {
+ console.error("No TypeScript files found.")
+ process.exit(2)
+ }
+
+ const violations = files.flatMap((f) => analyzeFile(f))
+
+ if (violations.length === 0) {
+ console.log(`No violations in ${files.length} file(s).`)
+ return
+ }
+
+ for (const v of violations) {
+ console.error(formatViolation(v))
+ }
+ console.error(`\n${violations.length} violation(s) in ${files.length} file(s).`)
+ process.exit(1)
+}
+
+main()
diff --git a/plugins/omo/skills/programming/scripts/typescript/new-project.ts b/plugins/omo/skills/programming/scripts/typescript/new-project.ts
new file mode 100644
index 00000000..9bb2a3e7
--- /dev/null
+++ b/plugins/omo/skills/programming/scripts/typescript/new-project.ts
@@ -0,0 +1,177 @@
+#!/usr/bin/env bun
+/**
+ * Scaffold a new TypeScript project with ultra-strict defaults.
+ *
+ * ─── How to run ───
+ * 1. Install Bun: curl -fsSL https://bun.sh/install | bash
+ * 2. Run:
+ * bun run scripts/new-project.ts my-api
+ * bun run scripts/new-project.ts my-api --path ./projects
+ * ──────────────────
+ *
+ * Creates:
+ * <name>/
+ * package.json (Bun + Hono + Zod + Drizzle + Biome)
+ * tsconfig.json (ultra-strict from tsconfig-strict.md)
+ * biome.json (strict from tsconfig-strict.md)
+ * src/index.ts (minimal Hono entrypoint)
+ * .gitignore
+ */
+
+import { mkdirSync, writeFileSync, existsSync } from "node:fs";
+import { join, resolve } from "node:path";
+import { parseArgs } from "node:util";
+
+const { values, positionals } = parseArgs({
+ args: Bun.argv.slice(2),
+ options: {
+ path: { type: "string", default: "." },
+ help: { type: "boolean", short: "h", default: false },
+ },
+ allowPositionals: true,
+ strict: true,
+});
+
+if (values.help || positionals.length === 0) {
+ console.log(`Usage: bun run new-project.ts <name> [--path <dir>]
+
+Arguments:
+ name Project directory name (kebab-case)
+
+Options:
+ --path Parent directory (default: current dir)
+ -h, --help Show this help`);
+ process.exit(positionals.length === 0 ? 2 : 0);
+}
+
+const name = positionals[0]!;
+const root = resolve(values.path!, name);
+
+if (existsSync(root)) {
+ console.error(`Error: ${root} already exists`);
+ process.exit(1);
+}
+
+// ── Directory structure ──
+mkdirSync(join(root, "src"), { recursive: true });
+
+// ── package.json ──
+const pkg = {
+ name,
+ version: "0.0.1",
+ private: true,
+ type: "module",
+ scripts: {
+ dev: "bun --hot src/index.ts",
+ start: "bun src/index.ts",
+ check: "bunx biome check . && bunx tsc --noEmit && bun test",
+ "check:fix": "bunx biome check --write .",
+ test: "bun test",
+ },
+ dependencies: {
+ hono: "^4.12.5",
+ zod: "^3.24.0",
+ },
+ devDependencies: {
+ "@biomejs/biome": "^1.9.0",
+ "@types/bun": "latest",
+ typescript: "^5.8.0",
+ },
+};
+writeFileSync(join(root, "package.json"), JSON.stringify(pkg, null, 2) + "\n");
+
+// ── tsconfig.json (ultra-strict) ──
+const tsconfig = {
+ compilerOptions: {
+ strict: true,
+ noUncheckedIndexedAccess: true,
+ exactOptionalPropertyTypes: true,
+ noFallthroughCasesInSwitch: true,
+ forceConsistentCasingInFileNames: true,
+ verbatimModuleSyntax: true,
+ isolatedModules: true,
+ esModuleInterop: true,
+ resolveJsonModule: true,
+ target: "ESNext",
+ lib: ["ESNext"],
+ declaration: true,
+ declarationMap: true,
+ sourceMap: true,
+ outDir: "dist",
+ rootDir: "src",
+ module: "ESNext",
+ moduleResolution: "bundler",
+ types: ["bun-types"],
+ skipLibCheck: true,
+ noEmit: true,
+ },
+ include: ["src/**/*.ts"],
+ exclude: ["node_modules", "dist"],
+};
+writeFileSync(
+ join(root, "tsconfig.json"),
+ JSON.stringify(tsconfig, null, 2) + "\n",
+);
+
+// ── biome.json (strict) ──
+const biome = {
+ $schema: "https://biomejs.dev/schemas/1.9.0/schema.json",
+ organizeImports: { enabled: true },
+ formatter: {
+ enabled: true,
+ indentStyle: "space",
+ indentWidth: 2,
+ lineWidth: 100,
+ },
+ linter: {
+ enabled: true,
+ rules: {
+ recommended: true,
+ complexity: {
+ noBannedTypes: "error",
+ noExtraBooleanCast: "error",
+ noUselessConstructor: "error",
+ noUselessRename: "error",
+ noVoid: "error",
+ },
+ correctness: {
+ noUnusedVariables: "error",
+ noUnusedImports: "error",
+ useExhaustiveDependencies: "warn",
+ },
+ style: {
+ noNonNullAssertion: "error",
+ useConst: "error",
+ noParameterAssign: "error",
+ },
+ suspicious: {
+ noExplicitAny: "error",
+ noAssertion: "warn",
+ },
+ },
+ },
+};
+writeFileSync(join(root, "biome.json"), JSON.stringify(biome, null, 2) + "\n");
+
+// ── src/index.ts ──
+const indexTs = `import { Hono } from "hono";
+
+const app = new Hono();
+
+app.get("/", (c) => c.json({ status: "ok" }));
+
+export default app;
+`;
+writeFileSync(join(root, "src/index.ts"), indexTs);
+
+// ── .gitignore ──
+const gitignore = `node_modules/
+dist/
+*.tsbuildinfo
+.env
+.env.*
+`;
+writeFileSync(join(root, ".gitignore"), gitignore);
+
+console.log(`✓ Created: ${root}`);
+console.log(` cd ${name} && bun install && bun run check`);
diff --git a/plugins/omo/skills/refactor/SKILL.md b/plugins/omo/skills/refactor/SKILL.md
new file mode 100644
index 00000000..9fcbdd6b
--- /dev/null
+++ b/plugins/omo/skills/refactor/SKILL.md
@@ -0,0 +1,779 @@
+---
+name: refactor
+description: "Intelligent refactor command. Triggers: refactor, refactoring, cleanup, restructure, extract, simplify, modernize."
+---
+
+## Codex Harness Tool Compatibility
+
+This skill may include examples copied from the OpenCode harness. In Codex, do not call OpenCode-only tools such as `call_omo_agent(...)`, `task(...)`, `background_output(...)`, or `team_*(...)` literally. Translate those examples to Codex native tools:
+
+| OpenCode example | Codex tool to use |
+| --- | --- |
+| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent(agent_type="explorer", task_name="...", message="...")` |
+| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent(agent_type="librarian", task_name="...", message="...")` |
+| `task(subagent_type="plan", ...)` | `spawn_agent(agent_type="plan", task_name="...", message="...")` |
+| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...")` |
+| `task(category="...", ...)` for implementation or QA | `spawn_agent(agent_type="worker", task_name="...", message="...")` |
+| `background_output(task_id="...")` | `wait_agent(...)` to wait for subagent completion and mailbox updates |
+| `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |
+
+When translating `load_skills=[...]`, include the requested skill names in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.
+
+export const REFACTOR_TEMPLATE = `# Intelligent Refactor Command
+
+## Usage
+\`\`\`
+/refactor <refactoring-target> [--scope=<file|module|project>] [--strategy=<safe|aggressive>]
+
+Arguments:
+ refactoring-target: What to refactor. Can be:
+ - File path: src/auth/handler.ts
+ - Symbol name: "AuthService class"
+ - Pattern: "all functions using deprecated API"
+ - Description: "extract validation logic into separate module"
+
+Options:
+ --scope: Refactoring scope (default: module)
+ - file: Single file only
+ - module: Module/directory scope
+ - project: Entire codebase
+
+ --strategy: Risk tolerance (default: safe)
+ - safe: Conservative, maximum test coverage required
+ - aggressive: Allow broader changes with adequate coverage
+\`\`\`
+
+## What This Command Does
+
+Performs intelligent, deterministic refactoring with full codebase awareness. Unlike blind search-and-replace, this command:
+
+1. **Understands your intent** - Analyzes what you actually want to achieve
+2. **Maps the codebase** - Builds a definitive codemap before touching anything
+3. **Assesses risk** - Evaluates test coverage and determines verification strategy
+4. **Plans meticulously** - Creates a detailed plan with Plan agent
+5. **Executes precisely** - Step-by-step refactoring with LSP and AST-grep
+6. **Verifies constantly** - Runs tests after each change to ensure zero regression
+
+---
+
+# PHASE 0: INTENT GATE (MANDATORY FIRST STEP)
+
+**BEFORE ANY ACTION, classify and validate the request.**
+
+## Step 0.1: Parse Request Type
+
+| Signal | Classification | Action |
+|--------|----------------|--------|
+| Specific file/symbol | Explicit | Proceed to codebase analysis |
+| "Refactor X to Y" | Clear transformation | Proceed to codebase analysis |
+| "Improve", "Clean up" | Open-ended | **MUST ask**: "What specific improvement?" |
+| Ambiguous scope | Uncertain | **MUST ask**: "Which modules/files?" |
+| Missing context | Incomplete | **MUST ask**: "What's the desired outcome?" |
+
+## Step 0.2: Validate Understanding
+
+Before proceeding, confirm:
+- [ ] Target is clearly identified
+- [ ] Desired outcome is understood
+- [ ] Scope is defined (file/module/project)
+- [ ] Success criteria can be articulated
+
+**If ANY of above is unclear, ASK CLARIFYING QUESTION:**
+
+\`\`\`
+I want to make sure I understand the refactoring goal correctly.
+
+**What I understood**: [interpretation]
+**What I'm unsure about**: [specific ambiguity]
+
+Options I see:
+1. [Option A] - [implications]
+2. [Option B] - [implications]
+
+**My recommendation**: [suggestion with reasoning]
+
+Should I proceed with [recommendation], or would you prefer differently?
+\`\`\`
+
+## Step 0.3: Create Initial Todos
+
+**IMMEDIATELY after understanding the request, create todos:**
+
+\`\`\`
+TodoWrite([
+ {"id": "phase-1", "content": "PHASE 1: Codebase Analysis - launch parallel explore agents", "status": "pending", "priority": "high"},
+ {"id": "phase-2", "content": "PHASE 2: Build Codemap - map dependencies and impact zones", "status": "pending", "priority": "high"},
+ {"id": "phase-3", "content": "PHASE 3: Test Assessment - analyze test coverage and verification strategy", "status": "pending", "priority": "high"},
+ {"id": "phase-4", "content": "PHASE 4: Plan Generation - invoke Plan agent for detailed refactoring plan", "status": "pending", "priority": "high"},
+ {"id": "phase-5", "content": "PHASE 5: Execute Refactoring - step-by-step with continuous verification", "status": "pending", "priority": "high"},
+ {"id": "phase-6", "content": "PHASE 6: Final Verification - full test suite and regression check", "status": "pending", "priority": "high"}
+])
+\`\`\`
+
+---
+
+# PHASE 1: CODEBASE ANALYSIS (PARALLEL EXPLORATION)
+
+**Mark phase-1 as in_progress.**
+
+## 1.1: Launch Parallel Explore Agents (BACKGROUND)
+
+Fire ALL of these simultaneously using \`call_omo_agent\`:
+
+\`\`\`
+// Agent 1: Find the refactoring target
+call_omo_agent(
+ subagent_type="explore",
+ run_in_background=true,
+ prompt="Find all occurrences and definitions of [TARGET].
+ Report: file paths, line numbers, usage patterns."
+)
+
+// Agent 2: Find related code
+call_omo_agent(
+ subagent_type="explore",
+ run_in_background=true,
+ prompt="Find all code that imports, uses, or depends on [TARGET].
+ Report: dependency chains, import graphs."
+)
+
+// Agent 3: Find similar patterns
+call_omo_agent(
+ subagent_type="explore",
+ run_in_background=true,
+ prompt="Find similar code patterns to [TARGET] in the codebase.
+ Report: analogous implementations, established conventions."
+)
+
+// Agent 4: Find tests
+call_omo_agent(
+ subagent_type="explore",
+ run_in_background=true,
+ prompt="Find all test files related to [TARGET].
+ Report: test file paths, test case names, coverage indicators."
+)
+
+// Agent 5: Architecture context
+call_omo_agent(
+ subagent_type="explore",
+ run_in_background=true,
+ prompt="Find architectural patterns and module organization around [TARGET].
+ Report: module boundaries, layer structure, design patterns in use."
+)
+\`\`\`
+
+## 1.2: Direct Tool Exploration (WHILE AGENTS RUN)
+
+While background agents are running, use direct tools:
+
+### LSP Tools for Precise Analysis:
+
+\`\`\`typescript
+// Find definition(s)
+LspGotoDefinition(filePath, line, character) // Where is it defined?
+
+// Find ALL usages across workspace
+LspFindReferences(filePath, line, character, includeDeclaration=true)
+
+// Get file structure
+LspDocumentSymbols(filePath) // Hierarchical outline
+LspWorkspaceSymbols(filePath, query="[target_symbol]") // Search by name
+
+// Get current diagnostics
+lsp_diagnostics(filePath) // Errors, warnings before we start
+\`\`\`
+
+### AST-Grep for Pattern Analysis:
+
+\`\`\`typescript
+// Find structural patterns
+ast_grep_search(
+ pattern="function $NAME($$$) { $$$ }", // or relevant pattern
+ lang="typescript", // or relevant language
+ paths=["src/"]
+)
+
+// Preview refactoring (DRY RUN)
+ast_grep_replace(
+ pattern="[old_pattern]",
+ rewrite="[new_pattern]",
+ lang="[language]",
+ dryRun=true // ALWAYS preview first
+)
+\`\`\`
+
+### Grep for Text Patterns:
+
+\`\`\`
+grep(pattern="[search_term]", path="src/", include="*.ts")
+\`\`\`
+
+## 1.3: Collect Background Results
+
+\`\`\`
+background_output(task_id="[agent_1_id]")
+background_output(task_id="[agent_2_id]")
+...
+\`\`\`
+
+**Mark phase-1 as completed after all results collected.**
+
+---
+
+# PHASE 2: BUILD CODEMAP (DEPENDENCY MAPPING)
+
+**Mark phase-2 as in_progress.**
+
+## 2.1: Construct Definitive Codemap
+
+Based on Phase 1 results, build:
+
+\`\`\`
+## CODEMAP: [TARGET]
+
+### Core Files (Direct Impact)
+- \`path/to/file.ts:L10-L50\` - Primary definition
+- \`path/to/file2.ts:L25\` - Key usage
+
+### Dependency Graph
+\`\`\`
+[TARGET]
+├── imports from:
+│ ├── module-a (types)
+│ └── module-b (utils)
+├── imported by:
+│ ├── consumer-1.ts
+│ ├── consumer-2.ts
+│ └── consumer-3.ts
+└── used by:
+ ├── handler.ts (direct call)
+ └── service.ts (dependency injection)
+\`\`\`
+
+### Impact Zones
+| Zone | Risk Level | Files Affected | Test Coverage |
+|------|------------|----------------|---------------|
+| Core | HIGH | 3 files | 85% covered |
+| Consumers | MEDIUM | 8 files | 70% covered |
+| Edge | LOW | 2 files | 50% covered |
+
+### Established Patterns
+- Pattern A: [description] - used in N places
+- Pattern B: [description] - established convention
+\`\`\`
+
+## 2.2: Identify Refactoring Constraints
+
+Based on codemap:
+- **MUST follow**: [existing patterns identified]
+- **MUST NOT break**: [critical dependencies]
+- **Safe to change**: [isolated code zones]
+- **Requires migration**: [breaking changes impact]
+
+**Mark phase-2 as completed.**
+
+---
+
+# PHASE 3: TEST ASSESSMENT (VERIFICATION STRATEGY)
+
+**Mark phase-3 as in_progress.**
+
+## 3.1: Detect Test Infrastructure
+
+\`\`\`bash
+# Check for test commands
+cat package.json | jq '.scripts | keys[] | select(test("test"))'
+
+# Or for Python
+ls -la pytest.ini pyproject.toml setup.cfg
+
+# Or for Go
+ls -la *_test.go
+\`\`\`
+
+## 3.2: Analyze Test Coverage
+
+\`\`\`
+// Find all tests related to target
+call_omo_agent(
+ subagent_type="explore",
+ run_in_background=false, // Need this synchronously
+ prompt="Analyze test coverage for [TARGET]:
+ 1. Which test files cover this code?
+ 2. What test cases exist?
+ 3. Are there integration tests?
+ 4. What edge cases are tested?
+ 5. Estimated coverage percentage?"
+)
+\`\`\`
+
+## 3.3: Determine Verification Strategy
+
+Based on test analysis:
+
+| Coverage Level | Strategy |
+|----------------|----------|
+| HIGH (>80%) | Run existing tests after each step |
+| MEDIUM (50-80%) | Run tests + add safety assertions |
+| LOW (<50%) | **PAUSE**: Propose adding tests first |
+| NONE | **BLOCK**: Refuse aggressive refactoring |
+
+**If coverage is LOW or NONE, ask user:**
+
+\`\`\`
+Test coverage for [TARGET] is [LEVEL].
+
+**Risk Assessment**: Refactoring without adequate tests is dangerous.
+
+Options:
+1. Add tests first, then refactor (RECOMMENDED)
+2. Proceed with extra caution, manual verification required
+3. Abort refactoring
+
+Which approach do you prefer?
+\`\`\`
+
+## 3.4: Document Verification Plan
+
+\`\`\`
+## VERIFICATION PLAN
+
+### Test Commands
+- Unit: \`bun test\` / \`npm test\` / \`pytest\` / etc.
+- Integration: [command if exists]
+- Type check: \`tsc --noEmit\` / \`pyright\` / etc.
+
+### Verification Checkpoints
+After each refactoring step:
+1. lsp_diagnostics → zero new errors
+2. Run test command → all pass
+3. Type check → clean
+
+### Regression Indicators
+- [Specific test that must pass]
+- [Behavior that must be preserved]
+- [API contract that must not change]
+\`\`\`
+
+**Mark phase-3 as completed.**
+
+---
+
+# PHASE 4: PLAN GENERATION (PLAN AGENT)
+
+**Mark phase-4 as in_progress.**
+
+## 4.1: Invoke Plan Agent
+
+\`\`\`
+Task(
+ subagent_type="plan",
+ prompt="Create a detailed refactoring plan:
+
+ ## Refactoring Goal
+ [User's original request]
+
+ ## Codemap (from Phase 2)
+ [Insert codemap here]
+
+ ## Test Coverage (from Phase 3)
+ [Insert verification plan here]
+
+ ## Constraints
+ - MUST follow existing patterns: [list]
+ - MUST NOT break: [critical paths]
+ - MUST run tests after each step
+
+ ## Requirements
+ 1. Break down into atomic refactoring steps
+ 2. Each step must be independently verifiable
+ 3. Order steps by dependency (what must happen first)
+ 4. Specify exact files and line ranges for each step
+ 5. Include rollback strategy for each step
+ 6. Define commit checkpoints"
+)
+\`\`\`
+
+## 4.2: Review and Validate Plan
+
+After receiving plan from Plan agent:
+
+1. **Verify completeness**: All identified files addressed?
+2. **Verify safety**: Each step reversible?
+3. **Verify order**: Dependencies respected?
+4. **Verify verification**: Test commands specified?
+
+## 4.3: Register Detailed Todos
+
+Convert Plan agent output into granular todos:
+
+\`\`\`
+TodoWrite([
+ // Each step from the plan becomes a todo
+ {"id": "refactor-1", "content": "Step 1: [description]", "status": "pending", "priority": "high"},
+ {"id": "verify-1", "content": "Verify Step 1: run tests", "status": "pending", "priority": "high"},
+ {"id": "refactor-2", "content": "Step 2: [description]", "status": "pending", "priority": "medium"},
+ {"id": "verify-2", "content": "Verify Step 2: run tests", "status": "pending", "priority": "medium"},
+ // ... continue for all steps
+])
+\`\`\`
+
+**Mark phase-4 as completed.**
+
+---
+
+# PHASE 5: EXECUTE REFACTORING (DETERMINISTIC EXECUTION)
+
+**Mark phase-5 as in_progress.**
+
+## 5.1: Execution Protocol
+
+For EACH refactoring step:
+
+### Pre-Step
+1. Mark step todo as \`in_progress\`
+2. Read current file state
+3. Verify lsp_diagnostics is baseline
+
+### Execute Step
+Use appropriate tool:
+
+**For Symbol Renames:**
+\`\`\`typescript
+lsp_prepare_rename(filePath, line, character) // Validate rename is possible
+lsp_rename(filePath, line, character, newName) // Execute rename
+\`\`\`
+
+**For Pattern Transformations:**
+\`\`\`typescript
+// Preview first
+ast_grep_replace(pattern, rewrite, lang, dryRun=true)
+
+// If preview looks good, execute
+ast_grep_replace(pattern, rewrite, lang, dryRun=false)
+\`\`\`
+
+**For Structural Changes:**
+\`\`\`typescript
+// Use Edit tool for precise changes
+edit(filePath, oldString, newString)
+\`\`\`
+
+### Post-Step Verification (MANDATORY)
+
+\`\`\`typescript
+// 1. Check diagnostics
+lsp_diagnostics(filePath) // Must be clean or same as baseline
+
+// 2. Run tests
+bash("bun test") // Or appropriate test command
+
+// 3. Type check
+bash("tsc --noEmit") // Or appropriate type check
+\`\`\`
+
+### Step Completion
+1. If verification passes → Mark step todo as \`completed\`
+2. If verification fails → **STOP AND FIX**
+
+## 5.2: Failure Recovery Protocol
+
+If ANY verification fails:
+
+1. **STOP** immediately
+2. **REVERT** the failed change
+3. **DIAGNOSE** what went wrong
+4. **OPTIONS**:
+ - Fix the issue and retry
+ - Skip this step (if optional)
+ - Consult oracle agent for help
+ - Ask user for guidance
+
+**NEVER proceed to next step with broken tests.**
+
+## 5.3: Commit Checkpoints
+
+After each logical group of changes:
+
+\`\`\`bash
+git add [changed-files]
+git commit -m "refactor(scope): description
+
+[details of what was changed and why]"
+\`\`\`
+
+**Mark phase-5 as completed when all refactoring steps done.**
+
+---
+
+# PHASE 6: FINAL VERIFICATION (REGRESSION CHECK)
+
+**Mark phase-6 as in_progress.**
+
+## 6.1: Full Test Suite
+
+\`\`\`bash
+# Run complete test suite
+bun test # or npm test, pytest, go test, etc.
+\`\`\`
+
+## 6.2: Type Check
+
+\`\`\`bash
+# Full type check
+tsc --noEmit # or equivalent
+\`\`\`
+
+## 6.3: Lint Check
+
+\`\`\`bash
+# Run linter
+eslint . # or equivalent
+\`\`\`
+
+## 6.4: Build Verification (if applicable)
+
+\`\`\`bash
+# Ensure build still works
+bun run build # or npm run build, etc.
+\`\`\`
+
+## 6.5: Final Diagnostics
+
+\`\`\`typescript
+// Check all changed files
+for (file of changedFiles) {
+ lsp_diagnostics(file) // Must all be clean
+}
+\`\`\`
+
+## 6.6: Generate Summary
+
+\`\`\`markdown
+## Refactoring Complete
+
+### What Changed
+- [List of changes made]
+
+### Files Modified
+- \`path/to/file.ts\` - [what changed]
+- \`path/to/file2.ts\` - [what changed]
+
+### Verification Results
+- Tests: PASSED (X/Y passing)
+- Type Check: CLEAN
+- Lint: CLEAN
+- Build: SUCCESS
+
+### No Regressions Detected
+All existing tests pass. No new errors introduced.
+\`\`\`
+
+**Mark phase-6 as completed.**
+
+---
+
+# CRITICAL RULES
+
+## NEVER DO
+- Skip lsp_diagnostics check after changes
+- Proceed with failing tests
+- Make changes without understanding impact
+- Use \`as any\`, \`@ts-ignore\`, \`@ts-expect-error\`
+- Delete tests to make them pass
+- Commit broken code
+- Refactor without understanding existing patterns
+
+## ALWAYS DO
+- Understand before changing
+- Preview before applying (ast_grep dryRun=true)
+- Verify after every change
+- Follow existing codebase patterns
+- Keep todos updated in real-time
+- Commit at logical checkpoints
+- Report issues immediately
+
+## ABORT CONDITIONS
+If any of these occur, **STOP and consult user**:
+- Test coverage is zero for target code
+- Changes would break public API
+- Refactoring scope is unclear
+- 3 consecutive verification failures
+- User-defined constraints violated
+
+---
+
+# Tool Usage Philosophy
+
+You already know these tools. Use them intelligently:
+
+## LSP Tools
+Leverage LSP tools for precision analysis. Key patterns:
+- **Understand before changing**: \`LspGotoDefinition\` to grasp context
+- **Impact analysis**: \`LspFindReferences\` to map all usages before modification
+- **Safe refactoring**: \`lsp_prepare_rename\` → \`lsp_rename\` for symbol renames
+- **Continuous verification**: \`lsp_diagnostics\` after every change
+
+## AST-Grep
+Use \`ast_grep_search\` and \`ast_grep_replace\` for structural transformations.
+**Critical**: Always \`dryRun=true\` first, review, then execute.
+
+## Agents
+- \`explore\`: Parallel codebase pattern discovery
+- \`plan\`: Detailed refactoring plan generation
+- \`oracle\`: Read-only consultation for complex architectural decisions and debugging
+- \`librarian\`: **Use proactively** when encountering deprecated methods or library migration tasks. Query official docs and OSS examples for modern replacements.
+
+## Deprecated Code & Library Migration
+When you encounter deprecated methods/APIs during refactoring:
+1. Fire \`librarian\` to find the recommended modern alternative
+2. **DO NOT auto-upgrade to latest version** unless user explicitly requests migration
+3. If user requests library migration, use \`librarian\` to fetch latest API docs before making changes
+
+---
+
+**Remember: Refactoring without tests is reckless. Refactoring without understanding is destructive. This command ensures you do neither.**
+
+<user-request>
+$ARGUMENTS
+</user-request>
+`
+
+export const REFACTOR_TEAM_MODE_ADDENDUM = `
+---
+
+# Team Mode Protocol (active when team_* tools are present)
+
+Team mode is enabled for this session. The rules below **override Phase 4-6** above. Follow this protocol instead of the in-session step-by-step execution.
+
+## Phase 4 override: Plan agent staffing requirement
+
+When invoking the Plan agent in Phase 4.1, append this additional requirement to the prompt:
+
+\`\`\`
+7. (REQUIRED when team mode is active) Output a Team Staffing Recommendation section with these fields — missing fields fail Phase 5.0:
+ - total_atomic_steps: integer
+ - file_independent_steps: integer (parallelizable, no cross-file blocker)
+ - cross_file_dependent_steps: integer (has blockers)
+ - per_step_assignment: [{step_id, assigned_to: 'quick' | 'unspecified-low', blockedBy: [step_ids], rationale}]
+ - dispatch_path_recommendation: 'team' | 'legacy' with reason
+ - rationale for the composition
+\`\`\`
+
+**Classification rules** the plan agent must apply to each step:
+- \`quick\`: mechanical edits — LSP rename, extract variable, inline, simple move, signature change without call-site logic.
+- \`unspecified-low\`: logic-preserving refactors that need reasoning — extract function, restructure conditional, pattern transformation, cross-file API change.
+- Recommend \`team\` path when \`file_independent_steps >= 3\`; recommend \`legacy\` otherwise.
+
+## Phase 5 override: Dispatch path selection
+
+Read the Team Staffing Recommendation from Phase 4. If any required field is missing, fail here and re-request the plan with the exact missing field names. Do not proceed with a partial plan.
+
+Then choose the path:
+
+- **Team path (5.1-T)**: when the plan recommends \`team\` AND \`file_independent_steps >= 3\`. Members execute in parallel, Lead orchestrates, a \`deep\` verifier lives outside the team.
+- **Legacy path (5.1-L)**: otherwise. Use the original 5.1 / 5.2 / 5.3 flow from above.
+
+Record the chosen path in the TodoWrite list.
+
+## Phase 5.1-T: \`refactor-squad\` team execution
+
+**Precondition checks** (fail hard if any step fails):
+
+1. Load the \`team-mode\` skill via the \`skill\` tool for lifecycle, message protocol, and limits.
+2. Call \`team_list\` and verify no active \`refactor-squad\` run exists; if one does, shutdown + delete the orphan before proceeding.
+3. If \`~/.omo/teams/refactor-squad/config.json\` is missing, write it using the spec below.
+
+**Team spec** (\`~/.omo/teams/refactor-squad/config.json\`):
+
+\`\`\`json
+{
+ "name": "refactor-squad",
+ "lead": { "kind": "subagent_type", "subagent_type": "sisyphus" },
+ "members": [
+ {
+ "kind": "category",
+ "category": "quick",
+ "prompt": "You handle mechanical refactoring steps (LSP rename, extract variable, inline, simple move, signature change). Use LSP tools for correctness. Apply the task description's per-step instructions verbatim — no scope expansion. After edits, run lsp_diagnostics on touched files. Report via team_send_message(teamRunId=<id>, to=\"lead\", summary=<files touched>, body=<lsp status + diff summary>) + team_task_update(status=completed). Never run tests — the external verifier handles that. Never git add, never --continue."
+ },
+ { "kind": "category", "category": "quick", "prompt": "Same contract as peer quick worker." },
+ {
+ "kind": "category",
+ "category": "unspecified-low",
+ "prompt": "You handle logic-preserving refactors that need reasoning (extract function, restructure conditional, pattern transformation, cross-file API change). Read the task description's plan step carefully. Use ast_grep_replace with dryRun=true first, review the preview, then execute. If the step is ambiguous or would require out-of-scope changes, STOP and send team_send_message(teamRunId=<id>, to=\"lead\", summary=\"UNCLEAR\", body=<reason>) + team_task_update(status=pending). Same reporting contract as peer quick workers. Never run tests."
+ },
+ { "kind": "category", "category": "unspecified-low", "prompt": "Same contract as peer unspecified-low worker." }
+ ]
+}
+\`\`\`
+
+Rationale for this composition:
+- **4 workers = team mode's parallel cap.** 5+ just queues.
+- **No verifier team member.** Verification needs \`deep\` reasoning (or \`unspecified-high\` fallback). In-team category routing downcasts to sisyphus-junior, which is weaker than required — the verifier runs OUTSIDE the team as a \`task(category="deep")\`.
+- **quick × 2** for mechanical edits, **unspecified-low × 2** for reasoning edits — mirrors the plan's split.
+
+**Team lifecycle** (one team, reused until Phase 6 cleanup):
+
+1. \`team_create(teamName="refactor-squad")\`. Record \`teamRunId\`.
+2. Broadcast the refactor Intent Card ONCE (keep task descriptions slim):
+ \`\`\`
+ team_send_message(
+ teamRunId=<id>, to="*", kind="announcement",
+ summary="refactor-intent",
+ body=<codemap summary + constraints + established patterns from Phase 2>
+ )
+ \`\`\`
+3. Broadcast the verification spec ONCE:
+ \`\`\`
+ team_send_message(
+ teamRunId=<id>, to="*", kind="announcement",
+ summary="verify-spec",
+ body=<exact test/typecheck/lint commands + expected pass counts + regression indicators from Phase 3.4>
+ )
+ \`\`\`
+4. For each plan step, \`team_task_create(teamRunId=<id>, subject="refactor step <N>: <short>", description=<per-step instructions from plan, including target files and line ranges, rollback strategy>, blockedBy=<from plan's per_step_assignment>)\`.
+
+**Lead monitoring loop**:
+
+While any team task is \`pending | claimed | in_progress\`:
+
+- Wait for \`<system-reminder>\` or member messages. Avoid tight polling; a single \`team_status\` check is acceptable if no notification arrives within roughly 10 seconds of expected completion.
+- On a worker completion report, immediately dispatch an **external verifier** — verification runs OUTSIDE the team because team-member category routing downcasts to sisyphus-junior:
+ \`\`\`
+ task(
+ category="deep",
+ load_skills=[],
+ run_in_background=true,
+ description="verify step <N>",
+ prompt=<files touched + verify-spec commands + instruction to return "PASS" or "FAIL:<failing test + specific error + suggested revert hunks>">
+ )
+ \`\`\`
+ If \`deep\` is unavailable, fall back to \`category="unspecified-high"\`. Do not create a commit checkpoint until the verifier returns PASS.
+- On a verifier PASS: make the commit checkpoint for that step (see original 5.3). Proceed.
+- On a verifier FAIL: Lead decides:
+ - **Retry with fix hint**: \`team_task_update(status=pending)\` on the original step + \`team_send_message(teamRunId=<id>, to=<original member>, summary="retry", body=<specific failure from verifier>)\`. Runtime reassigns.
+ - **Escalate**: after three FAIL cycles on the same step, STOP and consult the user with full evidence.
+- On a member UNCLEAR message: re-harvest context via a targeted \`task()\` outside the team, broadcast an updated Intent Card fragment, then reassign.
+
+Proceed to Phase 6 only when every team task is \`completed\` AND every paired verifier task returned PASS.
+
+## Phase 6 override: Team cleanup before summary
+
+If Phase 5 used the team path, dismantle \`refactor-squad\` BEFORE producing the 6.6 summary. Every exit path — success, escalation, abort — must cleanup; orphan teams poison the next session's precondition check.
+
+1. \`team_shutdown_request\` for each member, then \`team_approve_shutdown\` if members do not self-approve within a reasonable window.
+2. \`team_delete(teamRunId=<id>)\`.
+3. \`team_list\` to confirm no residual \`refactor-squad\` run.
+
+The \`~/.omo/teams/refactor-squad/config.json\` declaration stays on disk; next session reuses it.
+
+Append to the 6.6 summary a "Dispatch path" line and, when team path was used, team metrics (teamRunId, tasks created, verifier runs, team lifetime).
+
+## MUST NOT (team mode)
+
+- Lead never edits files directly — orchestrate only.
+- Do not inline the Intent Card or verify-spec into task descriptions — rely on the broadcasts.
+- Do not recreate the team mid-session.
+- Do not run tests from Lead — the external verifier owns that lane.
+- Do not put \`oracle\` / \`librarian\` / \`deep\` into the team spec — oracle/librarian are team-ineligible, and \`deep\` under category routing downcasts to sisyphus-junior. Use them via \`task()\` outside the team when needed.
+`
diff --git a/plugins/omo/skills/remove-ai-slops/SKILL.md b/plugins/omo/skills/remove-ai-slops/SKILL.md
new file mode 100644
index 00000000..453b2e59
--- /dev/null
+++ b/plugins/omo/skills/remove-ai-slops/SKILL.md
@@ -0,0 +1,333 @@
+---
+name: remove-ai-slops
+description: Remove AI-generated code smells (slop) from branch changes or an explicit file list. Locks behavior with regression tests FIRST, then runs categorized cleanup via parallel `deep` agents in batches of 5, then verifies with quality gates. Covers 10 slop categories including performance equivalences, excessive complexity (object annotations, if/elif variant chains), and oversized modules (250+ pure LOC with mandatory modular refactoring). MUST USE when the user asks to "remove slop", "clean AI code", "deslop", "AI 코드 정리", "AI 슬롭 제거", or wants to clean up AI-generated patterns from recent changes. Triggers - "remove ai slops", "clean ai code", "deslop", "cleanup AI generated", "AI 슬롭 제거", "AI 코드 정리해줘", "슬롭 빼라", "ai-slop 정리".
+---
+
+## Codex Harness Tool Compatibility
+
+This skill may include examples copied from the OpenCode harness. In Codex, do not call OpenCode-only tools such as `call_omo_agent(...)`, `task(...)`, `background_output(...)`, or `team_*(...)` literally. Translate those examples to Codex native tools:
+
+| OpenCode example | Codex tool to use |
+| --- | --- |
+| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent(agent_type="explorer", task_name="...", message="...")` |
+| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent(agent_type="librarian", task_name="...", message="...")` |
+| `task(subagent_type="plan", ...)` | `spawn_agent(agent_type="plan", task_name="...", message="...")` |
+| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...")` |
+| `task(category="...", ...)` for implementation or QA | `spawn_agent(agent_type="worker", task_name="...", message="...")` |
+| `background_output(task_id="...")` | `wait_agent(...)` to wait for subagent completion and mailbox updates |
+| `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |
+
+When translating `load_skills=[...]`, include the requested skill names in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.
+
+# Remove AI Slops Skill
+
+## Inputs
+
+- **Default scope**: branch diff vs `merge-base main` (no arguments needed)
+- **Optional scope**: explicit file list passed by the caller (e.g., a Ralph workflow's changed-files set)
+
+## What this skill does
+
+Cleans AI-generated slop from a bounded set of changed files while strictly preserving behavior. Locks behavior with regression tests first, then runs a categorized multi-pass cleanup, then verifies with quality gates and a critical review. Reverts and direct-edits when verification fails.
+
+The core safety invariant: **behavior is locked by green tests before a single line is removed**. A checklist alone is not safety; a passing regression test is.
+
+---
+
+## Categories (what counts as slop)
+
+The agent looks for these nine categories. The first three are stylistic, the next three are structural, the next two are about hidden cost, and the last is about behavior coverage.
+
+### Stylistic
+1. **Obvious comments** — comments restating code, trivial docstrings, section dividers, commented-out code, vague TODOs/Notes.
+ - KEEP: comments explaining WHY (business logic, edge cases, workarounds), ticket links, regex/algorithm explanations.
+ - KEEP: BDD markers (`# given`, `# when`, `# then`, `# when/then`).
+
+2. **Over-defensive code** — null checks for guaranteed values, try/except around code that cannot raise, isinstance checks for statically typed params, default values for required params, backward-compat shims, redundant validation duplicated at multiple layers, **broad exception catching** (`except Exception`/`except BaseException` in Python, empty `catch {}` or `catch (e) { console.error(e) }` without narrowing in TypeScript/JavaScript).
+ - KEEP: validation at system boundaries (user input, external APIs), I/O error handling, nullable DB fields. Top-level boundary catch-all (CLI `main()`, HTTP handler) with explicit logging + re-raise is acceptable.
+ - REFACTOR: `except Exception` → catch the specific exception you expect. Empty `catch {}` → add `instanceof` narrowing or re-throw. `catch (e) { log(e) }` → narrow with `instanceof`, handle known cases, re-throw unknown.
+
+3. **Excessive complexity** — deep nesting (>3 levels), nested ternaries, complex boolean expressions (combine 4+ predicates), long parameter lists (>5 args without a struct/dataclass/object), god functions (>50 lines doing many things), overly clever one-liners that sacrifice readability, `if/elif/else` chains for type/enum/literal discrimination (must be `match/case` + `assert_never`), `object` used as a type annotation (must be `Protocol`, `TypeVar`, or explicit union).
+ - KEEP: established complexity patterns in this codebase, performance-critical hot paths that intentionally use a complex idiom. `if/else` for boolean conditions and range checks (not variant discrimination).
+ - REFACTOR: nested if-chains → guard clauses / early returns. Complex ternaries → explicit if/else. isinstance/enum if/elif chains → `match/case` with `assert_never` on the wildcard. `object` annotations → `Protocol` (structural), `TypeVar` (generic), or union (known variants).
+
+### Structural
+4. **Needless abstraction** — pass-through wrappers, single-use helpers, speculative indirection ("we might need this later"), interfaces with one implementer where the interface adds no testability win, factory functions that just call a constructor.
+ - KEEP: abstractions that provide a real seam (testability, multiple implementers, framework-required boundaries).
+
+5. **Boundary violations** — wrong-layer imports (UI importing DB driver), leaky responsibilities (handler doing business logic that belongs in a service), hidden coupling (module A reads module B's private state), side effects in pure-named functions.
+ - KEEP: pragmatic short-circuits already established as a pattern in this codebase. Flag for human judgment if unsure.
+
+6. **Dead code** — unused imports, unused private functions/methods, unreachable branches, stale feature flags, debug leftovers (`console.log`, `print(...)`, `dbg!`), removed-but-still-referenced code.
+ - KEEP: code referenced via reflection, dynamic dispatch, or string lookup. Code intentionally kept as a feature flag rollback path (verify with the user).
+
+### Hidden cost
+7. **Duplication** — copy-pasted branches with trivial differences, redundant helpers that do the same thing in two places, repeated literal/magic-number sequences.
+ - KEEP: incidental duplication (two pieces of code that look similar but serve different intents that could diverge). Prefer leaving them separate over forcing a premature shared abstraction.
+
+8. **Performance equivalences (behavior-preserving optimizations)** — changes that are provably equivalent in semantics but cheaper in time/space:
+ - O(n²) → O(n) when correctness preserved (e.g., set lookup vs list scan)
+ - Repeated computation inside a loop → hoist outside
+ - Unnecessary intermediate collections (eager `list(...)` when only iterated once → generator)
+ - String concatenation in loop → `join`
+ - Redundant DB/API calls in a loop → batch
+ - Redundant deep copies / clones
+ - `.length` / `len()` recomputed inside loop → cache
+
+ **Hard rule**: only apply when behavior equivalence is obvious. Do NOT change algorithms with subtle correctness implications. Do NOT micro-optimize hot paths without a benchmark. If in doubt, SKIP.
+
+### Behavior coverage
+9. **Missing tests** — behavior present in changed files that is not locked by any regression test. The fix is not to remove code but to ADD the narrowest test that pins the behavior.
+
+### Structural
+10. **Oversized modules** — any source file exceeding **250 pure LOC** (non-blank, non-comment lines). This is an architectural defect, not a style preference. Measure: `awk '!/^[[:space:]]*$/ && !/^[[:space:]]*(#|\/\/)/' <file> | wc -l`.
+
+ **When found, do NOT just flag it. Execute a full modular refactoring:**
+ 1. Run `check-no-excuse-rules.py` recursively on scope to list all violations.
+ 2. For each oversized file, identify distinct responsibilities (single-responsibility principle).
+ 3. Plan the split: name each new file after the concept it owns (never `utils.py`, `helpers.py`, `common.py`, `part_1.py`).
+ 4. Present the split plan to the user before executing.
+ 5. Extract into clean modules with explicit `__init__.py` re-exports (re-exports ONLY, no logic in `__init__.py`).
+ 6. Verify: run `check-no-excuse-rules.py` again — every file must be ≤250 pure LOC. Run tests, typecheck, lint.
+
+ **Forbidden escapes**:
+ - Counting blanks/comments toward budget.
+ - Splitting by token count (`foo_1.py`, `foo_2.py`) — split by what each file DOES.
+ - Catch-all dump files (`utils.py`, `helpers.py`, `service.py`).
+ - "It's generated" — only valid if the file lives in a build output directory.
+ - "230 LOC, close enough" — a 230-LOC file about to grow is already over. Split now.
+
+ KEEP: genuinely self-contained single-responsibility scripts (e.g., a standalone CLI checker). Opt out with `# noqa: SIZE_OK` in first 5 lines and a comment explaining why.
+
+---
+
+## Quality Gates
+
+A pass is complete only when all applicable gates are green. Skip gates that are genuinely N/A for the project (e.g., no security scanner configured), and report `N/A` explicitly — do not silently skip.
+
+| Gate | Tool | Pass condition |
+|---|---|---|
+| Regression tests | project's test runner | all green |
+| Lint | project's linter | zero errors (warnings OK if pre-existing) |
+| Typecheck | `lsp_diagnostics` on changed files + project type-checker | zero new errors |
+| Unit/integration tests | project's test runner | all green (pre-existing failures noted, not introduced) |
+| Static/security scan | project's scanner | zero new findings, or `N/A` if not configured |
+
+---
+
+## Process
+
+### Phase 0: Plan with TodoWrite
+
+Create todos for all phases below. Mark `in_progress` one at a time.
+
+### Phase 1: Determine scope
+
+If file paths were passed as arguments, that is the scope. Otherwise:
+
+```bash
+git diff $(git merge-base main HEAD)..HEAD --name-only
+```
+
+Filter out: deleted files, binary files, generated/vendored files (`node_modules/`, `dist/`, `target/`, lockfiles). List the final scope.
+
+### Phase 2: Lock behavior with regression tests (NEW — non-negotiable)
+
+For each in-scope source file:
+
+1. Identify the public/observable behavior the file exposes (exported functions, HTTP handlers, CLI commands, classes used elsewhere).
+2. Check whether existing tests cover that behavior. Use `git grep` / project test conventions to find related test files.
+3. **If behavior is uncovered or weakly covered, write the narrowest regression test that pins current behavior BEFORE editing the file.** Tests should pin observable outputs, not implementation details.
+4. Run the test suite (or at minimum the relevant tests). They must be **green** before any cleanup begins.
+
+If you cannot establish a green baseline (e.g., test runner is broken), STOP and report. Do not proceed with cleanup on unverified ground.
+
+### Phase 3: Cleanup plan
+
+Produce an explicit plan **before** spawning the removal agents:
+
+```
+File: src/foo.py
+ Categories: dead code, excessive complexity, performance
+ Order: dead code → complexity → performance
+ Risk: medium (touches caching layer)
+
+File: src/bar.py
+ Categories: obvious comments, over-defensive
+ Order: comments → defensive
+ Risk: low
+```
+
+Order rule (safest → riskiest): comments → dead code → defensive → duplication → complexity → abstraction/boundary → performance → tests → oversized-modules. This minimizes blast radius of any one change.
+
+### Phase 4: Parallel slop removal via `deep` agents in batches of 5
+
+Files are processed by `deep` category agents with the `ai-slop-remover` skill loaded, **batched 5 at a time in parallel**. The `deep` category gives the agent enough thoroughness to correctly evaluate the 9 categories and respect the KEEP rules without slipping into surface fixes; the 5-wide batch is the sweet spot — more than 5 creates result-merging noise and context contention, fewer wastes parallelism.
+
+**Batching protocol** (strict):
+
+1. Slice the in-scope file list into chunks of up to 5 files.
+2. For each chunk, launch all `task` calls **in a single message**, every one with `run_in_background=true`.
+3. End your turn. Wait for the system to send `<system-reminder>` notifications as each task finishes.
+4. Once all 5 in the batch complete, collect each result via `background_output(task_id=...)`.
+5. Launch the next batch of 5. Repeat until every file is processed.
+6. If total files ≤ 5, launch all in one batch.
+
+**Never** launch all files at once when there are more than 5; **never** launch them serially when more than one remains in the current batch.
+
+**Per-file invocation** (one of the 5 in a batch):
+
+```
+task(
+ category="deep",
+ load_skills=["ai-slop-remover"],
+ run_in_background=true,
+ description="Slop removal: {filename}",
+ prompt="""
+Remove AI slops from: {file_path}
+
+In addition to your default categories (obvious comments, over-defensive code, spaghetti nesting), also evaluate these categories:
+- Excessive complexity: god functions, long parameter lists, complex booleans, nested ternaries
+- Needless abstraction: pass-through wrappers, single-use helpers, speculative indirection
+- Boundary violations: wrong-layer imports, leaky responsibilities, hidden coupling
+- Dead code: unused imports, unreachable branches, stale flags, debug leftovers
+- Duplication: copy-paste branches, redundant helpers
+- Performance equivalences: O(n²)→O(n) via set lookup, hoist computation out of loops, eager→lazy collections, batch redundant calls, cache repeated len()/length
+
+Apply changes in this order (safest → riskiest): comments → dead code → defensive → duplication → complexity → abstraction/boundary → performance → oversized-modules.
+
+Hard constraints:
+- Behavior MUST be preserved. When equivalence is not obvious, SKIP.
+- Do NOT change public API signatures.
+- Do NOT remove type hints.
+- Do NOT introduce new abstractions or dependencies.
+- Diff stays minimal and scoped to slop removal.
+
+Report changes grouped by category. For each change, give before/after, why-slop, why-safe.
+For each skipped issue, give reason.
+"""
+)
+```
+
+**Batch failure handling**: if a `deep` agent in a batch fails or times out, do NOT block the remaining 4 in that batch. Collect the successful results, mark the failed file for retry in a later batch (single retry max), and continue. If retry also fails, escalate that file under "Issues Found & Fixed" in the final report.
+
+### Phase 5: Verify with quality gates + critical review
+
+Run the five quality gates listed above. Then walk the critical review checklist:
+
+**Safety**:
+- [ ] No functional logic accidentally removed
+- [ ] All error handling preserved (especially around I/O, network, external APIs)
+- [ ] Type hints intact and correct
+- [ ] Imports still valid
+- [ ] No breaking changes to public APIs
+
+**Behavior**:
+- [ ] Return values unchanged (verified by Phase 2 regression tests)
+- [ ] Side effects unchanged
+- [ ] Exception behavior unchanged
+- [ ] Edge case handling preserved
+
+**Quality**:
+- [ ] Removed changes are genuinely slop, not intentional patterns
+- [ ] Remaining code follows project conventions
+- [ ] No orphaned code or dead references
+- [ ] Performance changes are obviously equivalent (no subtle algorithm shifts)
+- [ ] No new abstractions introduced
+
+### Phase 6: Fix issues
+
+If any gate fails or any checklist item flips:
+
+1. Identify the specific change that caused the failure.
+2. Explain why it broke things.
+3. `git checkout` the affected file (or use `git diff` + targeted `Edit` to revert just the problematic hunk).
+4. If genuine slop remains after revert, edit the file directly yourself — in parallel per file via multiple Edit calls — applying only the changes you can prove are safe.
+5. Re-run the failing gate and re-walk the checklist for the affected file.
+6. Repeat until all gates green AND checklist clean.
+
+If you fail three times on the same file, STOP and escalate to the user with: the file, what you tried, what failed, your hypothesis. Do not keep editing.
+
+---
+
+## Output Format
+
+```text
+AI SLOP REMOVAL REPORT
+======================
+
+Scope: [branch diff vs merge-base main / explicit file list]
+Files: [N files]
+ - path/to/file1.ts
+ - path/to/file2.py
+
+Behavior Lock:
+ - Existing coverage: [N files already covered]
+ - Tests added: [M new regression tests at path/to/test_X.py]
+ - Baseline status: GREEN
+
+Cleanup Plan:
+ - path/to/file1.ts: [dead code → complexity → performance]
+ - path/to/file2.py: [comments → defensive]
+
+Per-File Results:
+ path/to/file1.ts
+ - Dead code: 3 removed (lines X-Y, A-B, C)
+ - Excessive complexity: 1 simplified (nested ternary at L42 → if/else)
+ - Performance: 1 (line N: list scan → set lookup, O(n²)→O(n), behavior identical)
+ - Skipped (preserved): 2 (defensive null check at boundary; commented WHY at L88)
+
+ path/to/file2.py
+ - Obvious comments: 5 removed
+ - Over-defensive: 1 simplified (redundant isinstance on typed param)
+
+Quality Gates:
+ - Regression tests: PASS (12 tests, 0 failed)
+ - Lint: PASS
+ - Typecheck (lsp_diagnostics + project): PASS (0 new errors on changed files)
+ - Unit/integration tests: PASS (45 tests, 0 failed)
+ - Static/security scan: N/A (not configured)
+
+Critical Review:
+ - Safety: PASS
+ - Behavior: PASS
+ - Quality: PASS
+
+Issues Found & Fixed:
+ - [None] OR [Issue description → Fix applied]
+
+Remaining Risks / Deferred:
+ - [None] OR [e.g., "boundary violation in module X flagged but not refactored — needs human judgment"]
+
+Final Status: CLEAN | ISSUES FIXED | REQUIRES ATTENTION
+```
+
+---
+
+## Anti-Patterns (do not do these)
+
+- **Skipping Phase 2.** Removing code on uncovered ground is a behavior-change time bomb regardless of how careful the agent is. The regression test IS the safety mechanism; the checklist is its complement, not its replacement.
+- **Bundling unrelated refactors.** A single "cleanup" commit with dead code deletion + abstraction removal + performance change is impossible to review and impossible to bisect. Stay scoped to slop.
+- **Algorithm changes disguised as performance optimization.** If equivalence requires a proof, it is not a slop fix — it is a refactor and belongs in a separate change.
+- **Silent skips.** If a quality gate is N/A, say `N/A` and why. If a check failed and you could not fix it, say so. Never claim PASS without evidence.
+- **Removing comments that explain WHY.** "It is obvious from the code" is rarely true for the next reader. Only remove comments that restate WHAT.
+- **Touching files outside scope.** If a file was not in the branch diff or explicit list, do not edit it, even if you notice slop in passing. Report it under "Remaining Risks".
+
+---
+
+## Tool Persistence
+
+- When a tool call fails, retry with adjusted parameters.
+- Never silently skip a failed tool call.
+- Never claim a gate passed without running it and reading the output.
+- If correctness depends on further inspection, keep using `lsp_diagnostics`, the test runner, and direct file reads until the result is grounded.
+
+---
+
+## Quality Assurance
+
+- NEVER remove code that serves a functional purpose.
+- ALWAYS verify changes compile/parse and pass type-check.
+- ALWAYS preserve test coverage; add tests rather than remove them.
+- If uncertain about a change, err on the side of keeping the original code.
+- The default action when in doubt is SKIP, not GUESS.
diff --git a/plugins/omo/skills/review-work/SKILL.md b/plugins/omo/skills/review-work/SKILL.md
new file mode 100644
index 00000000..759b2c59
--- /dev/null
+++ b/plugins/omo/skills/review-work/SKILL.md
@@ -0,0 +1,549 @@
+---
+name: review-work
+description: "Post-implementation review orchestrator. Launches 5 parallel background sub-agents: Oracle (goal/constraint verification), Oracle (code quality), Oracle (security), unspecified-high (hands-on QA execution), unspecified-high (context mining from GitHub/git/Slack/Notion). All must pass for review to pass. MUST USE after completing any significant implementation work. Triggers: 'review work', 'review my work', 'review changes', 'QA my work', 'verify implementation', 'check my work', 'validate changes', 'post-implementation review'."
+---
+## Codex Harness Tool Compatibility
+
+This skill may include examples copied from the OpenCode harness. In Codex, do not call OpenCode-only tools such as `call_omo_agent(...)`, `task(...)`, `background_output(...)`, or `team_*(...)` literally. Translate those examples to Codex native tools:
+
+| OpenCode example | Codex tool to use |
+| --- | --- |
+| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent(agent_type="explorer", task_name="...", message="...")` |
+| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent(agent_type="librarian", task_name="...", message="...")` |
+| `task(subagent_type="plan", ...)` | `spawn_agent(agent_type="plan", task_name="...", message="...")` |
+| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent(agent_type="codex-ultrawork-reviewer", task_name="...", message="...")` |
+| `task(category="...", ...)` for implementation or QA | `spawn_agent(agent_type="worker", task_name="...", message="...")` |
+| `background_output(task_id="...")` | `wait_agent(...)` to wait for subagent completion and mailbox updates |
+| `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |
+
+When translating `load_skills=[...]`, include the requested skill names in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.
+
+# Review Work - 5-Agent Parallel Review Orchestrator
+
+Launch 5 specialized sub-agents in parallel to review completed implementation work from every angle. All 5 must pass for the review to pass. If even ONE fails, the review fails.
+
+The 5 agents cover complementary concerns - together they form a comprehensive review that no single reviewer could match:
+
+| # | Agent | Type | Role | Focus Level |
+|---|-------|------|------|-------------|
+| 1 | Goal Verifier | Oracle | Did we build what was asked? | MAIN |
+| 2 | QA Executor | unspecified-high | Does it actually work? | MAIN |
+| 3 | Code Reviewer | Oracle | Is the code well-written? | MAIN |
+| 4 | Security Auditor | Oracle | Is it secure? | SUB |
+| 5 | Context Miner | unspecified-high | Did we miss any context? | MAIN |
+
+---
+
+## Phase 0: Gather Review Context
+
+Before launching agents, collect these inputs. Extract from conversation history first - the user's original request, constraints discussed, and decisions made are usually already in the thread. Only ask if truly missing.
+
+<required_inputs>
+
+- **GOAL**: The original objective. What was the user trying to achieve? Pull from the initial request in this conversation.
+- **CONSTRAINTS**: Rules, requirements, or limitations. Tech stack restrictions, performance targets, API contracts, design patterns to follow, backward compatibility needs.
+- **BACKGROUND**: Why this work was needed. Business context, user stories, related systems, prior decisions that informed the approach.
+- **CHANGED_FILES**: Auto-collect via `git diff --name-only HEAD~1` or against the appropriate base (branch point, specific commit).
+- **DIFF**: Auto-collect via `git diff HEAD~1` or against the appropriate base.
+- **FILE_CONTENTS**: Read the full content of each changed file (not just the diff). Oracle agents cannot read files - they need full context in the prompt.
+- **RUN_COMMAND**: How to start/run the application. Check `package.json` scripts, `Makefile`, `docker-compose.yml`, or ask the user.
+
+</required_inputs>
+
+
+**NEVER CHECKOUT A PR BRANCH IN THE MAIN WORKTREE. ALWAYS CREATE A NEW GIT WORKTREE (`git worktree add`) AND WORK THERE. THIS PREVENTS CONTAMINATING THE USER'S WORKING DIRECTORY WITH UNRELATED BRANCH STATE.**
+
+**Auto-collection sequence:**
+
+```bash
+# 1. Get changed files
+git diff --name-only HEAD~1 # or: git diff --name-only main...HEAD
+
+# 2. Get diff
+git diff HEAD~1 # or: git diff main...HEAD
+
+# 3. Detect run command
+# Check package.json -> "scripts.dev" or "scripts.start"
+# Check Makefile -> default target
+# Check docker-compose.yml -> services
+```
+
+For GOAL, CONSTRAINTS, BACKGROUND - review the full conversation history. The user's original message almost always contains the goal. Constraints often emerge during discussion. If anything critical is ambiguous, ask ONE focused question - not a checklist.
+
+---
+
+## Phase 1: Launch 5 Agents
+
+Launch ALL 5 in a single turn. Every agent uses `run_in_background=true`. No sequential launches. No waiting between them.
+
+**Oracle agents receive everything in the prompt** (they cannot read files or run commands). Include DIFF + FILE_CONTENTS + all context directly in the prompt text.
+
+**unspecified-high agents are autonomous** - they can read files, run commands, and use tools. Give them goals and pointers, not raw content dumps.
+
+---
+
+### Agent 1: Goal & Constraint Verification (Oracle) - MAIN
+
+This agent answers: "Did we build exactly what was asked, within the rules we were given?"
+
+```
+task(
+ subagent_type="oracle",
+ run_in_background=true,
+ load_skills=[],
+ description="Verify implementation against original goal and constraints",
+ prompt="""
+<review_type>GOAL & CONSTRAINT VERIFICATION</review_type>
+
+<original_goal>
+{GOAL - paste the user's original request and any clarifications}
+</original_goal>
+
+<constraints>
+{CONSTRAINTS - every rule, requirement, or limitation discussed}
+</constraints>
+
+<background>
+{BACKGROUND - why this work was needed, broader context}
+</background>
+
+<changed_files>
+{CHANGED_FILES - list of modified file paths}
+</changed_files>
+
+<file_contents>
+{FILE_CONTENTS - full content of every changed file, clearly delimited per file}
+</file_contents>
+
+<diff>
+{DIFF - the actual git diff}
+</diff>
+
+Review whether this implementation correctly and completely achieves the stated goal within the given constraints. Be obsessively thorough - the point of this review is to catch what the implementer missed.
+
+REVIEW CHECKLIST:
+
+1. **Goal Completeness**: Break the goal into every sub-requirement (explicit AND implied). For each, mark ACHIEVED / MISSED / PARTIAL. Missing even one implied requirement that a reasonable engineer would have addressed = PARTIAL at minimum.
+
+2. **Constraint Compliance**: List every constraint. For each, verify compliance with specific code evidence. A constraint violated = automatic FAIL.
+
+3. **Requirement Gaps**: Requirements the user clearly wanted but didn't spell out. Things implied by the goal or background that a thoughtful engineer would have included.
+
+4. **Over-Engineering**: Anything added that wasn't requested - unnecessary abstractions, extra features, premature optimizations, speculative generality. Flag these as scope creep.
+
+5. **Edge Cases**: Given the goal, what inputs or scenarios would break this? Trace through at least 5 edge cases mentally.
+
+6. **Behavioral Correctness**: Walk through the code logic for 3+ representative scenarios. Does the code actually produce the expected behavior in each case?
+
+OUTPUT FORMAT:
+<verdict>PASS or FAIL</verdict>
+<confidence>HIGH / MEDIUM / LOW</confidence>
+<summary>1-3 sentence overall assessment</summary>
+<goal_breakdown>
+ For each sub-requirement:
+ - [ACHIEVED/MISSED/PARTIAL] Requirement description
+ - Evidence: specific code reference or gap
+</goal_breakdown>
+<constraint_compliance>
+ For each constraint:
+ - [ACHIEVED/MISSED] Constraint description - evidence
+</constraint_compliance>
+<findings>
+ - [PASS/FAIL/WARN] Category: Description
+ - File: path (line range if applicable)
+ - Evidence: specific code or logic reference
+</findings>
+<blocking_issues>Issues that MUST be fixed. Empty if PASS.</blocking_issues>
+""")
+```
+
+---
+
+### Agent 2: QA via App Execution (unspecified-high) - MAIN
+
+This agent answers: "Does it actually work when you run it?"
+
+The QA agent follows a structured process: brainstorm scenarios exhaustively first, then self-review and augment, then create a task list, then execute systematically.
+
+```
+task(
+ category="unspecified-high",
+ run_in_background=true,
+ load_skills=["playwright", "dev-browser"],
+ description="QA by actually running and using the application",
+ prompt="""
+<review_type>QA - HANDS-ON APP EXECUTION</review_type>
+
+<original_goal>
+{GOAL}
+</original_goal>
+
+<constraints>
+{CONSTRAINTS}
+</constraints>
+
+<changed_files>
+{CHANGED_FILES}
+</changed_files>
+
+<run_command>
+{RUN_COMMAND - how to start the application, or "unknown" if not determined}
+</run_command>
+
+You are a QA engineer. Your job is to RUN the application and verify it works through hands-on testing. You do not review code - you test behavior.
+
+MANDATORY PROCESS (follow in order):
+
+### Step 1: Scenario Brainstorm
+
+Before touching the app, write down EVERY test scenario you can think of. Be exhaustive. Think about:
+
+- **Happy paths**: The primary use cases this implementation enables. What's the main thing the user wanted to do?
+- **Boundary conditions**: Empty inputs, maximum-length inputs, zero values, negative numbers, special characters, unicode, very large datasets.
+- **Error paths**: Invalid inputs, network failures, missing files, permission denied, timeout conditions.
+- **Regression scenarios**: Existing features that touch the same code paths. Things that worked before and must still work.
+- **State transitions**: What happens when you do things out of order? Rapid repeated actions? Concurrent usage?
+- **UX scenarios** (if applicable): Layout on different sizes, keyboard navigation, screen reader compatibility, loading states, error messages.
+- **Integration points**: Does this feature interact with external services, databases, or other modules? Test those boundaries.
+
+Write each scenario as a one-liner with expected behavior. Aim for 15-30 scenarios minimum.
+
+### Step 2: Scenario Augmentation
+
+Review your scenario list with fresh eyes. For each scenario, ask:
+- "What could go wrong here that I haven't considered?"
+- "What would a malicious or careless user do?"
+- "What environmental conditions could affect this?" (disk full, slow network, expired tokens)
+
+Add at least 5 more scenarios from this reflection. Group scenarios by priority: P0 (must pass), P1 (should pass), P2 (nice to pass).
+
+### Step 3: Create Task List
+
+Convert your augmented scenario list into a structured task list (use TaskCreate/TaskUpdate or your todo system). Each task = one test scenario with:
+- Test name
+- Steps to execute
+- Expected result
+- Priority (P0/P1/P2)
+
+### Step 4: Execute Systematically
+
+Work through the task list in priority order (P0 first). For each test:
+
+1. Execute the test steps
+2. Record actual result
+3. Compare with expected result
+4. Mark PASS or FAIL
+5. If FAIL: capture evidence (screenshot, terminal output, error message)
+6. Mark the task complete
+
+**Execution guidance by app type:**
+- **Web app**: Use playwright/dev-browser to navigate, click, fill forms, verify visual output.
+- **CLI tool**: Run commands with various arguments, pipe inputs, check exit codes and output.
+- **Library/SDK**: Write and execute a test script that imports and exercises the public API.
+- **Backend API**: Use curl/httpie to hit endpoints with various payloads, verify response codes and bodies.
+- **Mobile/Desktop**: If not directly runnable, write integration tests and execute them.
+
+If the app cannot be started (build failure), that's an immediate FAIL - no need to continue.
+
+### Step 5: Compile Results
+
+OUTPUT FORMAT:
+<verdict>PASS or FAIL</verdict>
+<confidence>HIGH / MEDIUM / LOW</confidence>
+<summary>1-3 sentence overall assessment</summary>
+<scenario_coverage>
+ Total scenarios: N
+ P0: X tested, Y passed
+ P1: X tested, Y passed
+ P2: X tested, Y passed
+</scenario_coverage>
+<test_results>
+ For each test:
+ - [PASS/FAIL] Test name (Priority)
+ - Steps: What you did
+ - Expected: What should happen
+ - Actual: What actually happened
+ - Evidence: Screenshot path or terminal output snippet (if FAIL)
+</test_results>
+<blocking_issues>P0 or P1 failures only. Empty if PASS.</blocking_issues>
+""")
+```
+
+---
+
+### Agent 3: Code Quality Review (Oracle) - MAIN
+
+This agent answers: "Is the code well-written, maintainable, and consistent with the codebase?"
+
+```
+task(
+ subagent_type="oracle",
+ run_in_background=true,
+ load_skills=[],
+ description="Review overall code quality, patterns, and architecture",
+ prompt="""
+<review_type>CODE QUALITY REVIEW</review_type>
+
+<changed_files>
+{CHANGED_FILES}
+</changed_files>
+
+<file_contents>
+{FILE_CONTENTS - full content of changed files AND neighboring files that show existing patterns}
+</file_contents>
+
+<diff>
+{DIFF}
+</diff>
+
+<background>
+{BACKGROUND}
+</background>
+
+You are a senior staff engineer conducting a code review. Your standard: "Would I approve this PR without comments?"
+
+REVIEW DIMENSIONS (examine each):
+
+1. **Correctness**: Logic errors, off-by-one, null/undefined handling, race conditions, resource leaks, unhandled promise rejections.
+
+2. **Pattern Consistency**: Does new code follow the codebase's established patterns? Compare with the neighboring files provided. Introducing a new pattern where one already exists = finding.
+
+3. **Naming & Readability**: Clear variable/function/type names? Self-documenting code? Would another engineer understand this without explanation?
+
+4. **Error Handling**: Errors properly caught, logged, and propagated? No empty catch blocks? No swallowed errors? User-facing errors are helpful?
+
+5. **Type Safety**: Any `as any`, `@ts-ignore`, `@ts-expect-error`? Proper generic usage? Correct type narrowing? (If TypeScript/typed language)
+
+6. **Performance**: N+1 queries? Unnecessary re-renders? Blocking I/O on hot paths? Memory leaks? Unbounded growth?
+
+7. **Abstraction Level**: Right level of abstraction? No copy-paste duplication? But also no premature over-abstraction?
+
+8. **Testing**: New behaviors covered by tests? Tests are meaningful, not just coverage padding? Test names describe scenarios?
+
+9. **API Design**: Public interfaces clean and consistent with existing APIs? Breaking changes flagged?
+
+10. **Tech Debt**: Does this introduce new tech debt? Or create coupling that will be painful to change?
+
+Categorize each finding by severity:
+- **CRITICAL**: Will cause bugs, data loss, or crashes in production
+- **MAJOR**: Significant quality issue that should be fixed before merge
+- **MINOR**: Improvement worth making but not blocking
+- **NITPICK**: Style preference, optional
+
+OUTPUT FORMAT:
+<verdict>PASS or FAIL</verdict>
+<confidence>HIGH / MEDIUM / LOW</confidence>
+<summary>1-3 sentence overall assessment</summary>
+<findings>
+ - [CRITICAL/MAJOR/MINOR/NITPICK] Category: Description
+ - File: path (line range)
+ - Current: what the code does now
+ - Suggestion: how to improve
+</findings>
+<blocking_issues>CRITICAL and MAJOR items only. Empty if PASS.</blocking_issues>
+""")
+```
+
+---
+
+### Agent 4: Security Review (Oracle) - SUB
+
+This agent answers: "Are there security vulnerabilities in these changes?"
+
+This is supplementary - it focuses exclusively on security. It does NOT comment on code style, architecture, or functionality unless those directly create a security risk.
+
+```
+task(
+ subagent_type="oracle",
+ run_in_background=true,
+ load_skills=[],
+ description="Security-focused review of implementation changes",
+ prompt="""
+<review_type>SECURITY REVIEW (supplementary)</review_type>
+
+<changed_files>
+{CHANGED_FILES}
+</changed_files>
+
+<file_contents>
+{FILE_CONTENTS - full content of changed files}
+</file_contents>
+
+<diff>
+{DIFF}
+</diff>
+
+You are a security engineer. Review this diff exclusively for security vulnerabilities and anti-patterns. Ignore code style, naming, architecture - unless it directly creates a security risk.
+
+SECURITY CHECKLIST:
+
+1. **Input Validation**: User inputs sanitized? SQL injection, XSS, command injection, SSRF vectors?
+2. **Auth & AuthZ**: Authentication checks where needed? Authorization verified for each action? Privilege escalation paths?
+3. **Secrets & Credentials**: Hardcoded secrets, API keys, tokens in code or config? Secrets in logs?
+4. **Data Exposure**: Sensitive data in logs? PII in error messages? Over-exposed API responses?
+5. **Dependencies**: New dependencies added? Known CVEs? Suspicious or unnecessary packages?
+6. **Cryptography**: Proper algorithms? No custom crypto? Secure random? Proper key management?
+7. **File & Path**: Path traversal? Unsafe file operations? Symlink following?
+8. **Network**: CORS configured correctly? Rate limiting? TLS enforced? Certificate validation?
+9. **Error Leakage**: Stack traces exposed to users? Internal details in error responses?
+10. **Supply Chain**: Lockfile updated consistently? Dependency pinning?
+
+OUTPUT FORMAT:
+<verdict>PASS or FAIL</verdict>
+<severity>CRITICAL / HIGH / MEDIUM / LOW / NONE</severity>
+<summary>1-3 sentence overall assessment</summary>
+<findings>
+ - [CRITICAL/HIGH/MEDIUM/LOW] Category: Description
+ - File: path (line range)
+ - Risk: What could an attacker do?
+ - Remediation: Specific fix
+</findings>
+<blocking_issues>CRITICAL and HIGH items only. Empty if PASS.</blocking_issues>
+""")
+```
+
+---
+
+### Agent 5: Context Mining (unspecified-high) - MAIN
+
+This agent answers: "Did we miss any context that should have informed this implementation?"
+
+```
+task(
+ category="unspecified-high",
+ run_in_background=true,
+ load_skills=["git-master"],
+ description="Mine all accessible contexts for missed requirements or background knowledge",
+ prompt="""
+<review_type>CONTEXT MINING - MISSED REQUIREMENTS & BACKGROUND</review_type>
+
+<original_goal>
+{GOAL}
+</original_goal>
+
+<constraints>
+{CONSTRAINTS}
+</constraints>
+
+<changed_files>
+{CHANGED_FILES}
+</changed_files>
+
+<background>
+{BACKGROUND}
+</background>
+
+You are an investigator. Your mission: search every accessible information source to find context that should have informed this implementation but might have been missed. The question: "Is there something we should have known but didn't?"
+
+SOURCES TO SEARCH (use every available tool):
+
+1. **Git History** (ALWAYS search):
+ - `git log --oneline -20 -- {each changed file}` - recent changes and their reasons
+ - `git blame {critical sections}` - who wrote what and when
+ - `git log --all --grep="{keywords from goal}"` - related commits
+ - Look for reverted commits, TODO/FIXME/HACK comments in history
+
+2. **GitHub** (if `gh` CLI available):
+ - `gh issue list --search "{keywords}"` - related open/closed issues
+ - `gh pr list --search "{keywords}" --state all` - related PRs and their review comments
+ - Check if any issue is specifically linked to this work
+ - Look at review comments on past PRs touching these files
+
+3. **Communication Channels** (if MCP tools available):
+ - Slack: search for messages mentioning the feature, file names, or related keywords
+ - Notion: search for design docs, RFCs, ADRs related to this feature
+ - Discord: relevant discussions
+
+4. **Codebase Cross-References** (ALWAYS search):
+ - Files that import or reference the changed modules
+ - Tests that might need updating due to behavior changes
+ - Documentation (README, docs/, comments) that references changed behavior
+ - Config files that might need corresponding updates
+ - Related features in the same domain
+
+WHAT TO LOOK FOR:
+
+- Requirements mentioned in issues/PRs that the implementation misses
+- Past decisions explaining WHY code was written a certain way - and whether new changes respect those reasons
+- Related systems or features affected by these changes
+- Warnings from previous developers (PR review comments, inline TODOs, commit messages)
+- Migration or deprecation notes that affect the changed code
+- Design decisions documented outside the codebase (Notion, Slack, ADRs)
+
+OUTPUT FORMAT:
+<verdict>PASS or FAIL</verdict>
+<confidence>HIGH / MEDIUM / LOW</confidence>
+<summary>1-3 sentence overall assessment</summary>
+<sources_searched>
+ - [SEARCHED/SKIPPED] Source name - what was searched (or why it wasn't accessible)
+</sources_searched>
+<discovered_context>
+ For each discovery:
+ - Source: Where found (git commit abc123, GitHub issue #42, Slack message, etc.)
+ - Finding: What was found
+ - Relevance: How it relates to the current work
+ - Impact: [BLOCKING / IMPORTANT / FYI]
+</discovered_context>
+<missed_requirements>Requirements the implementation should address but doesn't. Empty if none.</missed_requirements>
+<blocking_issues>BLOCKING items only. Empty if PASS.</blocking_issues>
+""")
+```
+
+---
+
+## Phase 2: Wait & Collect
+
+After launching all 5 agents in one turn, **end your response**. Wait for system notifications as each agent completes.
+
+As each completes, collect via `background_output(task_id="bg_...")`. Store each verdict:
+
+| Agent | Verdict | Notes |
+|-------|---------|-------|
+| 1. Goal Verification | pending | - |
+| 2. QA Execution | pending | - |
+| 3. Code Quality | pending | - |
+| 4. Security | pending | - |
+| 5. Context Mining | pending | - |
+
+Do NOT deliver the final report until ALL 5 have completed.
+
+---
+
+## Phase 3: Deliver Verdict
+
+<verdict_logic>
+
+ALL 5 agents returned PASS → **REVIEW PASSED**
+ANY agent returned FAIL → **REVIEW FAILED - criteria not met**
+
+</verdict_logic>
+
+Compile the final report in this format:
+
+```markdown
+# Review Work - Final Report
+
+## Overall Verdict: PASSED / FAILED
+
+| # | Review Area | Agent Type | Verdict | Confidence |
+|---|------------|------------|---------|------------|
+| 1 | Goal & Constraint Verification | Oracle | PASS/FAIL | HIGH/MED/LOW |
+| 2 | QA Execution | unspecified-high | PASS/FAIL | HIGH/MED/LOW |
+| 3 | Code Quality | Oracle | PASS/FAIL | HIGH/MED/LOW |
+| 4 | Security (supplementary) | Oracle | PASS/FAIL | Severity |
+| 5 | Context Mining | unspecified-high | PASS/FAIL | HIGH/MED/LOW |
+
+## Blocking Issues
+[Aggregated from all agents - deduplicated, prioritized]
+
+## Key Findings
+[Top 5-10 most important findings across all agents, grouped by theme]
+
+## Recommendations
+[If FAILED: exactly what to fix, in priority order]
+[If PASSED: non-blocking suggestions worth considering]
+```
+
+If FAILED - be specific. The user should know exactly what to fix and in what order. No vague "consider improving X" - state the problem, the file, and the fix.
+
+If PASSED - keep it short. Highlight any non-blocking suggestions, but don't turn a passing review into a lecture.
\ No newline at end of file
diff --git a/plugins/omo/skills/rules/SKILL.md b/plugins/omo/skills/rules/SKILL.md
new file mode 100644
index 00000000..3ac40130
--- /dev/null
+++ b/plugins/omo/skills/rules/SKILL.md
@@ -0,0 +1,34 @@
+---
+name: rules
+description: Use when the user asks about Codex Rules behavior, injected project rules, supported rule file locations, matching, or environment configuration.
+---
+
+# Codex Rules
+
+Codex Rules is automatic once the plugin is enabled. It injects:
+
+- static project instructions on `SessionStart` and `UserPromptSubmit`
+- matching file-specific rules after Codex `apply_patch` by default
+
+Dynamic `PostToolUse` output is injected as additional context and is deduplicated per plugin data session. Codex Rules does not rewrite tool output.
+
+Supported project sources:
+
+- `AGENTS.md`
+- `CLAUDE.md`
+- `CONTEXT.md`
+- `.sisyphus/rules/**/*.md`
+- `.claude/rules/**/*.md`
+- `.cursor/rules/**/*.md`
+- `.github/instructions/**/*.md`
+- `.github/copilot-instructions.md`
+
+Supported environment knobs:
+
+- `CODEX_RULES_DISABLED=1`
+- `CODEX_RULES_MODE=both|static|dynamic|off`
+- `CODEX_RULES_MAX_RULE_CHARS=<number>`
+- `CODEX_RULES_MAX_RESULT_CHARS=<number>`
+- `CODEX_RULES_ENABLED_SOURCES=AGENTS.md,.sisyphus/rules`
+
+The legacy `PI_RULES_*` variables are accepted as fallbacks for users migrating from `pi-rules`.
diff --git a/plugins/omo/skills/ultragoal/.gitkeep b/plugins/omo/skills/ultragoal/.gitkeep
new file mode 100644
index 00000000..e69de29b
diff --git a/plugins/omo/skills/ultragoal/SKILL.md b/plugins/omo/skills/ultragoal/SKILL.md
new file mode 100644
index 00000000..47e8784a
--- /dev/null
+++ b/plugins/omo/skills/ultragoal/SKILL.md
@@ -0,0 +1,157 @@
+---
+name: ultragoal
+description: Durable repo-native multi-goal plans with embedded success criteria and evidence audit.
+---
+
+## Role
+Expert goal orchestration agent. Plan multi-goal work that survives across turns and sessions.
+Use GPT-5.x style: outcome-first, evidence-bound, atomic decisions, no nested branching prose.
+
+## Goal
+Deliver every goal in `.omo/ultragoal/goals.json` end-to-end.
+Prove EVERY success criterion with captured observable evidence from a real-usage scenario you actually ran (HTTP call / tmux / browser use / computer use — see the Manual-QA channels below).
+TESTS ALONE NEVER PROVE DONE. A green test suite is supporting evidence, not completion proof.
+Audit each pass, fail, block, steering change, and checkpoint in `.omo/ultragoal/ledger.jsonl`.
+
+## Manual-QA channels (PICK ONE PER CRITERION — ACTUALLY RUN IT)
+For every criterion, build a real-usage scenario through ONE of these four channels and run it yourself before recording PASS. The full test suite being green is NEVER verification on its own.
+
+1. **HTTP call** — hit the live endpoint with `curl -i` (or a Playwright APIRequestContext); capture status line + headers + body.
+2. **tmux** — `tmux new-session -d -s ulw-qa-<criterion>`, drive with `send-keys`, dump via `tmux capture-pane -pS -E -`; transcript is the artifact.
+3. **Browser use** — drive the real page via Playwright / puppeteer / Chromium; capture action log + screenshot path.
+4. **Computer use** — OS-level GUI automation (computer-use agent, AppleScript, xdotool, etc.) against the running app; capture action log + screenshot.
+
+Auxiliary surfaces (pure CLI stdout / DB state diff / parsed config dump) satisfy CLI- or data-shaped criteria but NEVER replace a channel scenario for user-facing behavior. `--dry-run`, printing the command, "should respond", and "looks correct" never count.
+
+## Artifacts
+- `.omo/ultragoal/brief.md`: original brief and durable constraints.
+- `.omo/ultragoal/goals.json`: goals with embedded `successCriteria` per goal.
+- `.omo/ultragoal/ledger.jsonl`: append-only audit trail.
+- Read artifacts before resuming, steering, or checkpointing.
+- Never invent state outside `.omo/ultragoal` artifacts or `omo ultragoal status --json`.
+
+## Bootstrap
+Do all three steps before execution. No edits, goal tools, or checkpointing before bootstrap completes.
+
+### 1. Create goals from the brief
+Run one form:
+```sh
+omo ultragoal create-goals --brief "<brief>" --json
+omo ultragoal create-goals --brief-file <path> --json
+cat <brief> | omo ultragoal create-goals --from-stdin --json
+```
+Write state through the CLI path. Do not hand-edit state files.
+
+### 2. Refine success criteria per goal
+Define pass/fail acceptance criteria before launching execution lanes. Include the command, artifact, or manual check that will prove success.
+Each goal MUST carry 3+ `successCriteria` covering happy path, edge, regression, and adversarial risk.
+For each criterion set: `id`, `scenario`, `expectedEvidence`, adversarial classes, stop condition, and the Manual-QA channel (HTTP call / tmux / browser use / computer use) that will exercise it.
+Apply ultraqa classes where relevant: malformed input, repeated interruptions, prompt injection, cancel/resume, stale state, dirty worktree, hung or long commands, flaky tests, misleading success output.
+Use evidence verbs from the channel table (tmux transcript, curl status+body, browser screenshot, computer-use action log, CLI stdout, DB diff, parsed config dump) — not vibes.
+"Tests pass" is supporting signal, NEVER completion proof. Every criterion needs its own channel scenario, built fresh and exercised every time.
+Record manual QA notes when behavior is user-visible.
+Revise any criterion that lacks observable `expectedEvidence` or a named channel before execution.
+
+### 3. Inspect state
+Run `omo ultragoal status --json`.
+Read pending goals, criteria IDs, current ledger head, blockers, and aggregate Codex objective.
+
+## Execution Loop
+Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures at 3.
+
+### Acquire Next Goal
+1. Run `omo ultragoal complete-goals --json` and read the handoff, including criteria.
+2. Call `get_goal` and inspect active Codex state.
+3. Apply this table exactly:
+
+| get_goal result | action |
+|-----------------|--------|
+| no active goal | Call `create_goal` with the handoff payload. |
+| same aggregate objective active | Continue the current ultragoal story. |
+| different goal active | STOP. Checkpoint blocked and surface the conflict. |
+4. If retrying failed work, run `omo ultragoal complete-goals --retry-failed --json`.
+5. Never create a second Codex goal for the same aggregate objective.
+
+### Per-Criterion Cycle
+1. PLAN: read `criterion.scenario`, `criterion.expectedEvidence`, prior ledger entries, and safety bounds.
+2. Register atomic todos: `path: <action> for <criterion> - verify by <check>`.
+3. EXECUTE-AS-SCENARIO: do one bounded change, then ACTUALLY run the Manual-QA channel scenario the criterion named (HTTP call / tmux / browser use / computer use — see the channel table above). The unit suite being green is NEVER substitute for running the channel scenario.
+4. CAPTURE: collect the observable artifact path: transcript, stdout, screenshot, assertion, status+body, diff, or parsed dump.
+5. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 3 spawned BEFORE recording — server PIDs (`kill`, verify `kill -0` fails), `tmux` sessions (`tmux kill-session -t ulw-qa-<criterion>`; confirm `tmux ls`), browser / Playwright contexts (`.close()`), containers (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env vars. Embed a one-line cleanup receipt in the evidence string, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo; rm -rf /tmp/ulw.aB12cD`. Missing receipt → record BLOCKED, not PASS.
+6. RECORD exactly one result:
+ - PASS: `omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status pass --evidence "<observable> | <cleanup receipt>" --json`
+ - FAIL: `omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status fail --evidence "<observable> | <cleanup receipt>" --notes "<diagnosis>" --json`
+ - BLOCKED: `omo ultragoal record-evidence --goal-id <id> --criterion-id <id> --status blocked --evidence "<observable>" --notes "<safety/blocker/leftover-state>" --json`
+7. If actual does not match expected, diagnose, fix minimally, and rerun the SAME criterion (including a fresh cleanup).
+8. After 3 same-criterion failures, exit the goal with diagnosis.
+9. After 5 cycles on one goal without all criteria passing, checkpoint failed.
+10. Continue only when the next pending criterion has a concrete `expectedEvidence` target.
+
+### Goal Completion
+1. Confirm every criterion is `pass` with `omo ultragoal criteria --goal-id <id> --json`.
+2. Call `get_goal` for a fresh snapshot.
+3. Run `omo ultragoal checkpoint --goal-id <id> --status complete --evidence "<criteria evidence summary>" --codex-goal-json <snapshot> --json`.
+4. If blocked or failed, checkpoint with `--status blocked` or `--status failed` and include diagnosis evidence.
+5. If this is the final goal, run the final quality gate first and pass `--quality-gate-json`.
+
+## Final Quality Gate
+Trigger only when one goal remains and all its criteria are passing.
+1. Run targeted verification for changed behavior.
+2. Run `ai-slop-cleaner` on changed files. If no relevant edits exist, record a passed no-op cleaner report.
+3. Rerun verification after cleanup.
+4. Run `$code-review`.
+5. Clean review means `codeReview.recommendation == "APPROVE"` and `codeReview.architectStatus == "CLEAR"`.
+6. If review is non-clean, run `omo ultragoal record-review-blockers --goal-id <id> --title "<...>" --objective "<...>" --evidence "<review findings>" --codex-goal-json <snapshot> --json`.
+7. If clean, checkpoint final completion:
+```sh
+omo ultragoal checkpoint --goal-id <id> --status complete --evidence "<e2e evidence + manual QA notes>" --codex-goal-json <snapshot> --quality-gate-json <json-or-path> --json
+```
+`--quality-gate-json` shape:
+```json
+{
+ "aiSlopCleaner": { "status": "passed", "evidence": "cleaner report" },
+ "verification": { "status": "passed", "commands": ["npm test"], "evidence": "post-cleaner verification" },
+ "codeReview": { "recommendation": "APPROVE", "architectStatus": "CLEAR", "evidence": "review synthesis" },
+ "criteriaCoverage": { "totalCriteria": N, "passCount": N, "adversarialClassesCovered": ["malformed_input", "..."] }
+}
+```
+
+## Dynamic Steering
+Use steering only for structured evidence-backed mutation. Reject natural-language steering requests.
+
+| Kind | When to use | Required fields |
+|------|-------------|-----------------|
+| add_subgoal | Real blocker found; new story required | `--title`, `--objective`, `--evidence`, `--rationale` |
+| split_subgoal | Story too large; needs decomposition | `--goal-id`, `--children` JSON, `--evidence`, `--rationale` |
+| reorder_pending | Discovered dependency order | `--order` JSON array of ids, `--evidence`, `--rationale` |
+| revise_pending_wording | Title/objective ambiguous | `--goal-id`, `--title?`, `--objective?`, `--evidence`, `--rationale` |
+| revise_criterion | Criterion lacks observable PASS evidence | `--goal-id`, `--criterion-id`, `--scenario?`, `--expected-evidence?`, `--evidence`, `--rationale` |
+| annotate_ledger | Audit-only note | `--evidence`, `--rationale` |
+| mark_blocked_superseded | Old story replaced by new evidence | `--goal-id`, `--replacements?`, `--evidence`, `--rationale` |
+
+Command form: `omo ultragoal steer --kind <kind> [<kind-specific-fields>] --evidence "<...>" --rationale "<...>" --json`.
+Structured prompt directives accepted: `OMO_ULTRAGOAL_STEER: { ... }`, `omo.ultragoal.steer: {...}`, `omo ultragoal steer: {...}`.
+
+## Constraints
+1. NEVER call `update_goal` mid-aggregate; only on final story after the quality gate passes.
+2. NEVER call `create_goal` when `get_goal` shows a different active goal.
+3. NEVER mark `criterion.status == "pass"` without captured observable evidence in `record-evidence`.
+4. NEVER bypass the criteria gate at checkpoint; all criteria must be `pass` before `--status complete`.
+5. Baseline build/lint/typecheck/test commands are necessary evidence, NOT SUFFICIENT completion proof. Criteria coverage with observable evidence is the gate.
+6. Treat `.omo/ultragoal/ledger.jsonl` as the durable audit trail; checkpoint after every success or failure.
+7. Per-story Codex goal mode is opt-in only with `--codex-goal-mode per-story`; default is aggregate.
+8. Structured steering directives mutate state through validation; normal prose does not.
+9. Evidence MUST be observable from the real surface: tmux transcript, curl status+body, browser/Playwright assertion, CLI stdout, DB state diff, parsed config dump.
+10. Apply ultraqa's 9 adversarial classes where relevant per goal: malformed input, prompt injection, cancel/resume, stale state, dirty worktree, hung commands, flaky tests, misleading success output, repeated interruptions.
+11. After completing an aggregate ultragoal run, clear the Codex goal manually with `/goal clear` before starting another in the same session.
+12. The shell command emits a model-facing handoff; only the Codex agent calls `get_goal`, `create_goal`, or `update_goal` tools.
+13. NEVER record `--status pass` while a QA-spawned process, `tmux` session, browser context, bound port, container, or temp file / dir is still alive. The evidence string MUST include the cleanup receipt. Leftover runtime state = BLOCKED, not PASS.
+
+## Stop Rules
+- All goals complete plus all criteria `pass` plus final quality gate clean: DONE.
+- 3x same criterion failure: checkpoint failed, surface diagnosis.
+- 5 cycles on one goal without all-pass: checkpoint failed, surface.
+- Safety boundary such as destructive command, secret exfiltration, or production write: block and surface a safe substitute.
+- Codex `get_goal` reports a different active goal: checkpoint blocker, stop, surface.
+- Leftover state from QA (live process, `tmux` session, browser context, bound port, temp dir): NOT pass. Clean up, append the receipt, then continue.
+- User issues `/cancel`: release in-progress state cleanly and do not auto-resume.
diff --git a/plugins/omo/test/aggregate.test.mjs b/plugins/omo/test/aggregate.test.mjs
new file mode 100644
index 00000000..cf7630d5
--- /dev/null
+++ b/plugins/omo/test/aggregate.test.mjs
@@ -0,0 +1,162 @@
+import assert from "node:assert/strict";
+import { readdir, readFile, stat } from "node:fs/promises";
+import { basename, dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const root = dirname(dirname(fileURLToPath(import.meta.url)));
+
+async function readJson(relativePath) {
+ return JSON.parse(await readFile(join(root, relativePath), "utf8"));
+}
+
+function findSpawnAgentTypes(content) {
+ const agentTypes = new Set();
+ const regex = /spawn_agent\(agent_type="([^"]+)"/g;
+ for (const match of content.matchAll(regex)) {
+ agentTypes.add(match[1]);
+ }
+ return [...agentTypes].sort();
+}
+
+test("#given aggregate plugin manifest #when inspected #then it owns the omo namespace", async () => {
+ // given
+ const manifest = await readJson(".codex-plugin/plugin.json");
+
+ // when
+ const hookPath = manifest.hooks;
+ const skillsPath = manifest.skills;
+ const mcpPath = manifest.mcpServers;
+
+ // then
+ assert.equal(manifest.name, "omo");
+ assert.equal(hookPath, "./hooks/hooks.json");
+ assert.equal(skillsPath, "./skills/");
+ assert.equal(mcpPath, "./.mcp.json");
+});
+
+test("#given isolated components #when hooks are inspected #then commands stay inside component roots", async () => {
+ // given
+ const hooks = await readJson("hooks/hooks.json");
+ const text = JSON.stringify(hooks);
+
+ // when
+ const componentMarkers = [
+ "components/comment-checker/dist/cli.js",
+ "components/lsp/dist/cli.js",
+ "components/rules/dist/cli.js",
+ "components/telemetry/dist/cli.js",
+ "components/ultragoal/dist/cli.js",
+ "components/ultrawork/hooks/ultrawork-detector.py",
+ ];
+
+ // then
+ for (const marker of componentMarkers) {
+ assert.match(text, new RegExp(marker.replaceAll("/", "\\/")));
+ }
+ assert.doesNotMatch(text, /codex-(comment-checker|lsp|rules|telemetry|ultragoal|ultrawork)@/);
+});
+
+test("#given aggregate MCP config #when inspected #then lsp server stays component isolated", async () => {
+ // given
+ const mcp = await readJson(".mcp.json");
+
+ // when
+ const server = mcp.mcpServers.lsp;
+
+ // then
+ assert.equal(server.command, "node");
+ assert.deepEqual(server.args, ["./components/lsp/packages/lsp-tools-mcp/dist/cli.js", "mcp"]);
+ assert.equal(server.cwd, ".");
+});
+
+test("#given aggregate plugin build script #when inspected #then telemetry sync runs before workspace builds", async () => {
+ // given
+ const packageJson = await readJson("package.json");
+ const telemetrySyncScript = await readFile(join(root, "..", "scripts", "sync-telemetry-component.mjs"), "utf8");
+
+ // when
+ const buildScript = packageJson.scripts.build;
+
+ // then
+ assert.equal(buildScript, "node scripts/sync-skills.mjs && node ../scripts/sync-telemetry-component.mjs && npm run build --workspaces --if-present");
+ assert.match(telemetrySyncScript, /syncTelemetryComponent/);
+});
+
+test("#given component directories #when scanned #then only intentional resource roots declare plugin manifests", async () => {
+ // given
+ const components = await readdir(join(root, "components"), { withFileTypes: true });
+ const expectedComponentManifests = new Map([["rules", { hooks: "./hooks/hooks.json" }]]);
+
+ // when
+ const componentNames = components.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
+
+ // then
+ assert.deepEqual(componentNames, ["comment-checker", "lsp", "rules", "telemetry", "ultragoal", "ultrawork"]);
+ for (const name of componentNames) {
+ const expectedManifest = expectedComponentManifests.get(name);
+ if (expectedManifest !== undefined) {
+ assert.deepEqual(await readJson(join("components", name, ".codex-plugin", "plugin.json")), expectedManifest);
+ continue;
+ }
+
+ await assert.rejects(
+ readFile(join(root, "components", name, ".codex-plugin", "plugin.json"), "utf8"),
+ /code: 'ENOENT'|ENOENT/,
+ );
+ }
+});
+
+test("#given bundled Codex agents #when components/ultrawork/agents directory is scanned #then explorer librarian and reviewer TOMLs are present and match expected schema keys", async () => {
+ const agentsDir = join(root, "components", "ultrawork", "agents");
+ const entries = (await readdir(agentsDir, { withFileTypes: true }))
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".toml"))
+ .map((entry) => entry.name)
+ .sort();
+
+ assert.deepEqual(entries, [
+ "codex-ultrawork-reviewer.toml",
+ "explorer.toml",
+ "librarian.toml",
+ "plan.toml",
+ ]);
+
+ for (const fileName of entries) {
+ const content = await readFile(join(agentsDir, fileName), "utf8");
+ assert.match(content, /^name\s*=\s*".+"$/m);
+ assert.match(content, /^description\s*=\s*".+"$/m);
+ assert.match(content, /^nickname_candidates\s*=\s*\[.+\]$/m);
+ assert.match(content, /^model\s*=\s*".+"$/m);
+ assert.match(content, /^model_reasoning_effort\s*=\s*".+"$/m);
+ assert.match(content, /^developer_instructions\s*=\s*"""/m);
+ }
+});
+
+test("#given synced skills with Codex compatibility guidance #when explorer/librarian agent_type is referenced #then a matching TOML is bundled", async () => {
+ const skillsDir = join(root, "skills");
+ const skillEntries = await readdir(skillsDir, { withFileTypes: true });
+ const skillFiles = skillEntries
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => join(skillsDir, entry.name, "SKILL.md"));
+
+ const referencedAgentTypes = new Set();
+ for (const skillPath of skillFiles) {
+ const content = await readFile(skillPath, "utf8");
+ for (const agentType of findSpawnAgentTypes(content)) {
+ if (agentType === "worker" || agentType === "codex-ultrawork-reviewer") {
+ continue;
+ }
+ referencedAgentTypes.add(agentType);
+ }
+ }
+
+ const expected = [...referencedAgentTypes].sort();
+ assert.deepEqual(expected, ["explorer", "librarian", "plan"]);
+
+ for (const agentType of expected) {
+ const tomlPath = join(root, "components", "ultrawork", "agents", `${agentType}.toml`);
+ const fileStat = await stat(tomlPath);
+ assert.equal(fileStat.isFile(), true);
+ assert.equal(basename(tomlPath), `${agentType}.toml`);
+ }
+});
diff --git a/plugins/omo/test/sync-skills.test.mjs b/plugins/omo/test/sync-skills.test.mjs
new file mode 100644
index 00000000..7ff99f05
--- /dev/null
+++ b/plugins/omo/test/sync-skills.test.mjs
@@ -0,0 +1,64 @@
+import assert from "node:assert/strict";
+import { readdir, readFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+const root = dirname(dirname(fileURLToPath(import.meta.url)));
+
+const expectedSkills = [
+ "ai-slop-remover",
+ "comment-checker",
+ "debugging",
+ "frontend-ui-ux",
+ "lsp",
+ "programming",
+ "refactor",
+ "remove-ai-slops",
+ "review-work",
+ "rules",
+ "ultragoal",
+];
+
+test("#given synced aggregate Codex skills #when inspected #then component and shared skills are present", async () => {
+ // given
+ const skillsRoot = join(root, "skills");
+
+ // when
+ const skillNames = (await readdir(skillsRoot, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => entry.name)
+ .sort();
+
+ // then
+ assert.deepEqual(skillNames, expectedSkills);
+ for (const skillName of expectedSkills) {
+ const content = await readFile(join(skillsRoot, skillName, "SKILL.md"), "utf8");
+ assert.match(content, /^---\n/);
+ }
+});
+
+test("#given synced aggregate Codex skills #when they contain OpenCode orchestration examples #then Codex tool compatibility guidance is injected", async () => {
+ // given
+ const skillsRoot = join(root, "skills");
+ const opencodeOnlyToolPattern = /\b(?:call_omo_agent|background_output|team_[a-z_]+|task)\s*\(/;
+
+ // when
+ const skillNames = (await readdir(skillsRoot, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => entry.name)
+ .sort();
+
+ // then
+ for (const skillName of skillNames) {
+ const content = await readFile(join(skillsRoot, skillName, "SKILL.md"), "utf8");
+ if (!opencodeOnlyToolPattern.test(content)) continue;
+
+ const compatibilityIndex = content.indexOf("## Codex Harness Tool Compatibility");
+ assert.notEqual(compatibilityIndex, -1, `${skillName} is missing Codex compatibility guidance`);
+ assert.ok(
+ compatibilityIndex < content.search(opencodeOnlyToolPattern),
+ `${skillName} must explain Codex tool translation before OpenCode-only examples`,
+ );
+ }
+});