The one and only agent harness for complex codebases. Project memory, planning, execution, and verified completion inside Codex.
JavaScript aiai-agentsclaudeclaude-codeclicodexdeveloper-toolslazylazycodexoh-my-openagentomoopenaiorchestrationtypescript
chore: sync Codex marketplace v4.9.0
github-actions[bot]aa3c5db9f7f2
diff --git a/plugins/omo/.codex-plugin/plugin.json b/plugins/omo/.codex-plugin/plugin.jsonindex bce798b6..947da4f0 100644--- a/plugins/omo/.codex-plugin/plugin.json+++ b/plugins/omo/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "omo",- "version": "4.8.0",+ "version": "4.9.0","description": "One Codex plugin namespace for Yeongyu's local Codex components.","author": {"name": "Yeongyu Kim",diff --git a/plugins/omo/.mcp.json b/plugins/omo/.mcp.jsonindex 45867b20..e4b16fb3 100644--- a/plugins/omo/.mcp.json+++ b/plugins/omo/.mcp.json@@ -25,7 +25,7 @@"lsp": {"command": "node","args": [- "./components/lsp-tools-mcp/dist/cli.js",+ "./components/lsp-daemon/dist/cli.js","mcp"],"cwd": "."diff --git a/plugins/omo/components/comment-checker/hooks/hooks.json b/plugins/omo/components/comment-checker/hooks/hooks.jsonindex bc777d2e..fa290ef7 100644--- a/plugins/omo/components/comment-checker/hooks/hooks.json+++ b/plugins/omo/components/comment-checker/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 30,- "statusMessage": "LazyCodex(4.8.0): Checking Comments"+ "statusMessage": "LazyCodex(4.9.0): Checking Comments"}]}diff --git a/plugins/omo/components/comment-checker/package.json b/plugins/omo/components/comment-checker/package.jsonindex 6fa96b41..73c1eb21 100644--- a/plugins/omo/components/comment-checker/package.json+++ b/plugins/omo/components/comment-checker/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-comment-checker",- "version": "0.1.1",+ "version": "4.9.0","description": "Codex plugin that runs comment-checker after edit-like PostToolUse hooks.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/git-bash/hooks/hooks.json b/plugins/omo/components/git-bash/hooks/hooks.jsonindex a16ed9c7..a5de1f91 100644--- a/plugins/omo/components/git-bash/hooks/hooks.json+++ b/plugins/omo/components/git-bash/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Recommending Git Bash Mcp"+ "statusMessage": "LazyCodex(4.9.0): Recommending Git Bash Mcp"}]}@@ -20,7 +20,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Resetting Git Bash Mcp Reminder"+ "statusMessage": "LazyCodex(4.9.0): Resetting Git Bash Mcp Reminder"}]}diff --git a/plugins/omo/components/git-bash/package.json b/plugins/omo/components/git-bash/package.jsonindex e154fa00..a4d24296 100644--- a/plugins/omo/components/git-bash/package.json+++ b/plugins/omo/components/git-bash/package.json@@ -1,13 +1,16 @@{"name": "@sisyphuslabs/codex-git-bash-hook",- "version": "0.1.0",+ "version": "4.9.0","description": "Codex hook component that reminds Windows sessions to prefer the OMO git_bash MCP.","type": "module","private": true,"bin": {"omo-git-bash-hook": "./dist/cli.js"},- "files": ["dist", "hooks"],+ "files": [+ "dist",+ "hooks"+ ],"scripts": {"build": "tsc -p tsconfig.build.json","test": "bun test test/*.test.ts",diff --git a/plugins/omo/components/lsp/.mcp.json b/plugins/omo/components/lsp/.mcp.jsonindex 46ecc491..2e7a0e6d 100644--- a/plugins/omo/components/lsp/.mcp.json+++ b/plugins/omo/components/lsp/.mcp.json@@ -2,7 +2,7 @@"mcpServers": {"lsp": {"command": "node",- "args": ["../../../../lsp-tools-mcp/dist/cli.js", "mcp"],+ "args": ["../../../../lsp-daemon/dist/cli.js", "mcp"],"cwd": "."}}diff --git a/plugins/omo/components/lsp/hooks/hooks.json b/plugins/omo/components/lsp/hooks/hooks.jsonindex 20b617d7..a6c57fe5 100644--- a/plugins/omo/components/lsp/hooks/hooks.json+++ b/plugins/omo/components/lsp/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 60,- "statusMessage": "LazyCodex(4.8.0): Checking LSP Diagnostics"+ "statusMessage": "LazyCodex(4.9.0): Checking LSP Diagnostics"}]}@@ -21,7 +21,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Resetting LSP Diagnostics Cache"+ "statusMessage": "LazyCodex(4.9.0): Resetting LSP Diagnostics Cache"}]}diff --git a/plugins/omo/components/lsp/package.json b/plugins/omo/components/lsp/package.jsonindex b6a9af59..51d712d3 100644--- a/plugins/omo/components/lsp/package.json+++ b/plugins/omo/components/lsp/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-lsp",- "version": "0.2.0",+ "version": "4.9.0","description": "Codex plugin that exposes Language Server Protocol tools and post-edit diagnostics.","type": "module","packageManager": "[email protected]",@@ -36,21 +36,21 @@"CHANGELOG.md"],"scripts": {- "bootstrap": "node scripts/build-lsp-tools.mjs",- "prebuild": "node scripts/build-lsp-tools.mjs",+ "bootstrap": "node scripts/build-lsp-tools.mjs && node scripts/build-lsp-daemon.mjs",+ "prebuild": "node scripts/build-lsp-tools.mjs && node scripts/build-lsp-daemon.mjs","build": "node scripts/clean-dist.mjs && tsc -p tsconfig.build.json",- "pretest": "node scripts/build-lsp-tools.mjs",+ "pretest": "node scripts/build-lsp-tools.mjs && node scripts/build-lsp-daemon.mjs","test": "node scripts/test.mjs","test:watch": "vitest",- "pretypecheck": "node scripts/build-lsp-tools.mjs",+ "pretypecheck": "node scripts/build-lsp-tools.mjs && node scripts/build-lsp-daemon.mjs","typecheck": "tsc --noEmit","lint": "biome check src test","lint:fix": "biome check --write src test",- "precheck": "node scripts/build-lsp-tools.mjs",+ "precheck": "node scripts/build-lsp-tools.mjs && node scripts/build-lsp-daemon.mjs","check": "tsc --noEmit && biome check src test && tsc -p tsconfig.build.json"},"dependencies": {- "@code-yeongyu/lsp-tools-mcp": "file:../../../../lsp-tools-mcp"+ "@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon"},"devDependencies": {"@biomejs/biome": "2.4.15",diff --git a/plugins/omo/components/lsp/scripts/build-lsp-daemon.mjs b/plugins/omo/components/lsp/scripts/build-lsp-daemon.mjsnew file mode 100644index 00000000..7725dae2--- /dev/null+++ b/plugins/omo/components/lsp/scripts/build-lsp-daemon.mjs@@ -0,0 +1,68 @@+#!/usr/bin/env node+import { execSync } from "node:child_process";+import { existsSync, statSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+const force = process.argv.includes("--force");++// Ordered candidate list:+// (1) 5-up repo sibling — has package.json, can be built (repo checkout layout)+// (2) 2-up components sibling — bundled dist-only inside the installed plugin cache+const candidates = [+ join(here, "..", "..", "..", "..", "..", "lsp-daemon"),+ join(here, "..", "..", "lsp-daemon"),+];++function requiredOutputs(dir) {+ return [+ join(dir, "dist", "cli.js"),+ join(dir, "dist", "index.js"),+ join(dir, "dist", "index.d.ts"),+ ];+}++// Phase 1: find the first buildable candidate (package.json present).+// --force skips the freshness check but does NOT prevent using a buildable candidate.+for (const dir of candidates) {+ const packageJson = join(dir, "package.json");+ if (existsSync(packageJson)) {+ const outputs = requiredOutputs(dir);+ if (!force && isBuildFresh(packageJson, outputs)) {+ process.exit(0);+ }+ console.log("Installing repository lsp-daemon dependencies...");+ execSync("npm ci", { cwd: dir, stdio: "inherit" });+ console.log("Building repository lsp-daemon...");+ execSync("npm run build", { cwd: dir, stdio: "inherit" });+ console.log("Done.");+ process.exit(0);+ }+}++// Phase 2: find the first candidate with all required outputs already present.+// Bundled dist is accepted even under --force — a dist-only layout cannot be rebuilt.+for (const dir of candidates) {+ const outputs = requiredOutputs(dir);+ if (outputs.every((p) => existsSync(p))) {+ console.log(`Using bundled lsp-daemon dist at ${dir}.`);+ process.exit(0);+ }+}++// Phase 3: no usable candidate found — enumerate every probed path.+// Keep the primary-candidate error on the first line so the issue's grep stays valid.+const probedPaths = candidates.map((dir) => join(dir, "package.json")).join(", ");+console.error(+ `lsp-daemon package metadata is missing at ${join(candidates[0], "package.json")}; build packages/lsp-daemon before codex-lsp`,+);+console.error(`probed: ${probedPaths}`);+process.exit(1);++function isBuildFresh(inputPath, outputPaths) {+ if (!existsSync(inputPath)) return false;+ if (outputPaths.some((path) => !existsSync(path))) return false;+ const inputMtime = statSync(inputPath).mtimeMs;+ return outputPaths.every((path) => statSync(path).mtimeMs >= inputMtime);+}diff --git a/plugins/omo/components/lsp/scripts/build-lsp-tools.mjs b/plugins/omo/components/lsp/scripts/build-lsp-tools.mjsindex 390ffe06..522a92c1 100644--- a/plugins/omo/components/lsp/scripts/build-lsp-tools.mjs+++ b/plugins/omo/components/lsp/scripts/build-lsp-tools.mjs@@ -6,37 +6,60 @@ import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";const __dirname = dirname(fileURLToPath(import.meta.url));-const lspToolsDir = join(__dirname, "..", "..", "..", "..", "..", "lsp-tools-mcp");-const packageJson = join(lspToolsDir, "package.json");-const requiredOutputs = [- join(lspToolsDir, "dist", "cli.js"),- join(lspToolsDir, "dist", "tools.js"),- join(lspToolsDir, "dist", "lsp", "manager.js"),-];const force = process.argv.includes("--force");-if (!force && isBuildFresh(packageJson, requiredOutputs)) {- process.exit(0);+// Ordered candidate list:+// (1) 5-up repo sibling — has package.json, can be built (repo checkout layout)+// (2) 2-up components sibling — bundled dist-only inside the installed plugin cache+const candidates = [+ join(__dirname, "..", "..", "..", "..", "..", "lsp-tools-mcp"),+ join(__dirname, "..", "..", "lsp-tools-mcp"),+];++function requiredOutputs(dir) {+ return [+ join(dir, "dist", "cli.js"),+ join(dir, "dist", "tools.js"),+ join(dir, "dist", "lsp", "manager.js"),+ ];}-if (!existsSync(packageJson)) {- if (!force && requiredOutputs.every((path) => existsSync(path))) {- console.log("Using bundled lsp-tools-mcp dist.");+// Phase 1: find the first buildable candidate (package.json present).+// --force skips the freshness check but does NOT prevent using a buildable candidate.+for (const dir of candidates) {+ const packageJson = join(dir, "package.json");+ if (existsSync(packageJson)) {+ const outputs = requiredOutputs(dir);+ if (!force && isBuildFresh(packageJson, outputs)) {+ process.exit(0);+ }+ console.log("Installing repository lsp-tools-mcp dependencies...");+ execSync("npm ci", { cwd: dir, stdio: "inherit" });+ console.log("Building repository lsp-tools-mcp...");+ execSync("npm run build", { cwd: dir, stdio: "inherit" });+ console.log("Done.");process.exit(0);}- console.error(- `lsp-tools-mcp package metadata is missing at ${packageJson}; build packages/lsp-tools-mcp before codex-lsp`,- );- process.exit(1);}-console.log("Installing repository lsp-tools-mcp dependencies...");-execSync("npm ci", { cwd: lspToolsDir, stdio: "inherit" });--console.log("Building repository lsp-tools-mcp...");-execSync("npm run build", { cwd: lspToolsDir, stdio: "inherit" });+// Phase 2: find the first candidate with all required outputs already present.+// Bundled dist is accepted even under --force — a dist-only layout cannot be rebuilt.+for (const dir of candidates) {+ const outputs = requiredOutputs(dir);+ if (outputs.every((p) => existsSync(p))) {+ console.log(`Using bundled lsp-tools-mcp dist at ${dir}.`);+ process.exit(0);+ }+}-console.log("Done.");+// Phase 3: no usable candidate found — enumerate every probed path.+// Keep the primary-candidate error on the first line so the issue's grep stays valid.+const probedPaths = candidates.map((dir) => join(dir, "package.json")).join(", ");+console.error(+ `lsp-tools-mcp package metadata is missing at ${join(candidates[0], "package.json")}; build packages/lsp-tools-mcp before codex-lsp`,+);+console.error(`probed: ${probedPaths}`);+process.exit(1);function isBuildFresh(inputPath, outputPaths) {if (!existsSync(inputPath)) return false;diff --git a/plugins/omo/components/lsp/src/cli.ts b/plugins/omo/components/lsp/src/cli.tsindex aa1ca150..dbb5bfbb 100644--- a/plugins/omo/components/lsp/src/cli.ts+++ b/plugins/omo/components/lsp/src/cli.ts@@ -6,7 +6,7 @@ import { argv, execPath, stderr } from "node:process";import { runPostCompactHookCli, runPostToolUseHookCli } from "./codex-hook-cli.js";const require = createRequire(import.meta.url);-const PACKAGE_LSP_MCP_CLI = "@code-yeongyu/lsp-tools-mcp/dist/cli.js";+const PACKAGE_LSP_MCP_CLI = "@code-yeongyu/lsp-daemon/dist/cli.js";async function main(): Promise<void> {const [command = "mcp", subcommand = ""] = argv.slice(2);diff --git a/plugins/omo/components/lsp/src/codex-hook-cli.ts b/plugins/omo/components/lsp/src/codex-hook-cli.tsindex f99cd3ef..1241bcba 100644--- a/plugins/omo/components/lsp/src/codex-hook-cli.ts+++ b/plugins/omo/components/lsp/src/codex-hook-cli.ts@@ -1,6 +1,6 @@import { stdin as processStdin } from "node:process";-import { disposeDefaultLspManager } from "@code-yeongyu/lsp-tools-mcp/dist/lsp/manager.js";+import { disposeDefaultLspManager } from "@code-yeongyu/lsp-daemon";import { isRecord, runLspPostCompactHook, runLspPostToolUseHook } from "./codex-hook.js";diff --git a/plugins/omo/components/lsp/src/codex-hook.ts b/plugins/omo/components/lsp/src/codex-hook.tsindex 138c2d1d..df385c18 100644--- a/plugins/omo/components/lsp/src/codex-hook.ts+++ b/plugins/omo/components/lsp/src/codex-hook.ts@@ -1,8 +1,9 @@import { readFileSync } from "node:fs";-import { executeLspDiagnostics } from "@code-yeongyu/lsp-tools-mcp/dist/tools.js";+import { callDiagnosticsViaDaemon, currentRequestContext } from "@code-yeongyu/lsp-daemon";import {+ isLspDaemonUnreachableDiagnostics,isUnavailableLspDiagnostics,markLspSessionCompacted,recordLspDiagnosticsObservations,@@ -59,7 +60,7 @@ const CONTEXT_PRESSURE_MARKERS = [] as const;export async function runLspDiagnosticsText(filePath: string): Promise<string> {- const result = await executeLspDiagnostics({ filePath, severity: "error" });+ const result = await callDiagnosticsViaDaemon(filePath, { context: currentRequestContext() });return result.content.map((block) => block.text).join("\n");}@@ -76,6 +77,9 @@ export async function runLspPostToolUseHook(const blocks: DiagnosticBlock[] = [];const observations: Array<{ filePath: string; unavailable: boolean }> = [];for (const { filePath, diagnostics } of await collectDiagnostics(filePaths, runDiagnostics)) {+ // A daemon outage is transient (connect-or-spawn retries on the next request);+ // recording it would silence this extension for the rest of the session.+ if (isLspDaemonUnreachableDiagnostics(diagnostics)) continue;const unavailable = isUnavailableLspDiagnostics(diagnostics);observations.push({ filePath, unavailable });if (isCleanDiagnostics(diagnostics)) continue;diff --git a/plugins/omo/components/lsp/src/lsp-session-state.ts b/plugins/omo/components/lsp/src/lsp-session-state.tsindex 9cbc5ca8..7c547d44 100644--- a/plugins/omo/components/lsp/src/lsp-session-state.ts+++ b/plugins/omo/components/lsp/src/lsp-session-state.ts@@ -68,6 +68,10 @@ export function isUnavailableLspDiagnostics(diagnostics: string): boolean {);}+export function isLspDaemonUnreachableDiagnostics(diagnostics: string): boolean {+ return diagnostics.includes("LSP daemon unreachable");+}+function sessionStatePath(sessionId: string): string {const root = process.env["PLUGIN_DATA"] ?? join(homedir(), ".codex", "codex-lsp");return join(root, "sessions", `${safePathSegment(sessionId)}.json`);diff --git a/plugins/omo/components/lsp/test/codex-hook-unavailable.test.ts b/plugins/omo/components/lsp/test/codex-hook-unavailable.test.tsindex 7c4371f0..cf9dfde1 100644--- a/plugins/omo/components/lsp/test/codex-hook-unavailable.test.ts+++ b/plugins/omo/components/lsp/test/codex-hook-unavailable.test.ts@@ -12,6 +12,12 @@ const MARKSMAN_INITIALIZE_TIMEOUT = ['[01:16:41 INF] <Folder> Loading folder documents: {"uri":"file:///repo"}',].join("\n");+const DAEMON_UNREACHABLE = [+ "LSP daemon unreachable: daemon did not become reachable.",+ "The MCP server is a thin proxy and never runs language servers in-process.",+ "Logs: /tmp/daemon.log",+].join("\n");+const tempDirs: string[] = [];afterEach(() => {@@ -118,6 +124,68 @@ describe("codex PostToolUse unavailable LSP suppression", () => {});});+ it("#given the LSP daemon is unreachable #when PostToolUse repeats #then it suppresses feedback once and retries on the next edit", async () => {+ // given+ const pluginData = tempPluginData();+ const input = postToolUseInput("session-daemon-down", "src/app.ts");+ let calls = 0;++ await withPluginData(pluginData, async () => {+ // when+ const firstOutput = await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return DAEMON_UNREACHABLE;+ });+ const secondOutput = await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return "error[typescript] (2304) at 1:1: Cannot find name 'missing'.";+ });++ // then+ expect(firstOutput).toBe("");+ expect(secondOutput).toContain("Cannot find name 'missing'");+ expect(calls).toBe(2);+ });+ });++ it("#given a cached unavailable extension #when the post-compact probe hits a daemon outage #then the cache survives and the probe stays pending", async () => {+ // given+ const pluginData = tempPluginData();+ const input = postToolUseInput("session-daemon-down-probe", ".omo/ulw-loop/evidence/note.md");+ let calls = 0;++ await withPluginData(pluginData, async () => {+ await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return MARKSMAN_INITIALIZE_TIMEOUT;+ });+ await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return "error[markdown] (1000) at 1:1: cached call should have been skipped.";+ });+ await runLspPostCompactHook({ session_id: "session-daemon-down-probe" });++ // when+ const outageProbeOutput = await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return DAEMON_UNREACHABLE;+ });+ const retriedProbeOutput = await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return MARKSMAN_INITIALIZE_TIMEOUT;+ });+ await runLspPostToolUseHook(input, async () => {+ calls += 1;+ return "error[markdown] (1000) at 1:1: re-cached call should have been skipped.";+ });++ // then+ expect(outageProbeOutput).toBe("");+ expect(retriedProbeOutput).toBe("");+ expect(calls).toBe(3);+ });+ });+it("#given markdown LSP is cached unavailable #when TypeScript diagnostics run #then real diagnostics still block", async () => {// givenconst pluginData = tempPluginData();diff --git a/plugins/omo/components/lsp/test/package-smoke.test.ts b/plugins/omo/components/lsp/test/package-smoke.test.tsindex 72c02471..ab316fa7 100644--- a/plugins/omo/components/lsp/test/package-smoke.test.ts+++ b/plugins/omo/components/lsp/test/package-smoke.test.ts@@ -70,7 +70,7 @@ describe("plugin package metadata", () => {expect(packageJson.type).toBe("module");expect(packageJson.packageManager).toBe("[email protected]");expect(packageJson.dependencies).toEqual({- "@code-yeongyu/lsp-tools-mcp": "file:../../../../lsp-tools-mcp",+ "@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon",});expect(packageJson.bin["omo-lsp"]).toBe("./dist/cli.js");expect(packageJson.bin["codex-lsp"]).toBeUndefined();@@ -80,29 +80,17 @@ describe("plugin package metadata", () => {expect(postToolUseCommand).toBe(`node "${pluginRoot}/dist/cli.js" hook post-tool-use`);expect(postCompactCommand).toBe(`node "${pluginRoot}/dist/cli.js" hook post-compact`);expect(lspServer?.command).toBe("node");- expect(lspServer?.args).toEqual(["../../../../lsp-tools-mcp/dist/cli.js", "mcp"]);+ expect(lspServer?.args).toEqual(["../../../../lsp-daemon/dist/cli.js", "mcp"]);expect(cliSource).not.toContain("./lazy-lsp-mcp.js");- expect(cliSource).toContain("@code-yeongyu/lsp-tools-mcp/dist/cli.js");- expect(cliSource).not.toContain("../../../../../lsp-tools-mcp/dist/cli.js");- expect(codexHookCliSource).toContain("@code-yeongyu/lsp-tools-mcp/dist/lsp/manager.js");- expect(codexHookSource).toContain("@code-yeongyu/lsp-tools-mcp/dist/tools.js");- expect(codexHookCliSource).not.toContain("../../../../../lsp-tools-mcp/dist/lsp/manager.js");- expect(codexHookSource).not.toContain("../../../../../lsp-tools-mcp/dist/tools.js");+ expect(cliSource).toContain("@code-yeongyu/lsp-daemon/dist/cli.js");+ expect(cliSource).not.toContain("../../../../../lsp-daemon/dist/cli.js");+ expect(codexHookCliSource).toContain("@code-yeongyu/lsp-daemon");+ expect(codexHookSource).toContain("@code-yeongyu/lsp-daemon");+ expect(codexHookCliSource).not.toContain("../../../../../lsp-daemon");+ expect(codexHookSource).not.toContain("../../../../../lsp-daemon");expect(sourceFiles.filter((name) => name.startsWith("lazy-mcp") || name === "lazy-lsp-mcp.ts")).toEqual([]);});- 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 {diff --git a/plugins/omo/components/rules/bundled-rules/hephaestus.md b/plugins/omo/components/rules/bundled-rules/hephaestus.mdindex cabb2836..073e96f2 100644--- a/plugins/omo/components/rules/bundled-rules/hephaestus.md+++ b/plugins/omo/components/rules/bundled-rules/hephaestus.md@@ -11,142 +11,126 @@ Warm but spare. Communicate efficiently - enough context for the user to trust t# Autonomy and Persistence-User instructions override these defaults. Newer instructions override older ones. Safety and type-safety constraints never yield.+User instructions override these defaults; newer instructions override older. 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.+**Implement, don't propose.** Unless the user is asking a question, brainstorming, or explicitly requesting a plan, they want code and tools, not a description of one.-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.+Examine the codebase before changing it, dig past the surface answer, and persist until the work is done. Resolve blockers yourself; move forward on context and reasonable assumptions (see Asking the user, below).-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.+If the user's plan or design seems flawed, say so concisely, propose the alternative, and ask whether to proceed with the original or the alternative - never silently override. Mention high-impact bugs or misconceptions you spot along the way 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.+Status requests are not stop signals: give the update, keep working. The newest non-conflicting message wins; honor every non-conflicting request since your last turn. After compaction, 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.+Unexpected worktree changes you did not make: keep working - the user or other agents may be working concurrently. Never revert, undo, or modify them unless explicitly asked. Work around unrelated ones touching your files; if a direct conflict with your task is unresolvable, 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.+Resolve the user's task end-to-end in this turn. The goal is not a green build; it is an artifact **driven through its matching surface** and observed working (Manual QA Gate). Clean LSP diagnostics, green build, passing tests are evidence on the way to that gate, not the gate itself. The user's spec is the spec; "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.+Users chose you for action, not analysis. Your priors may read messages too literally - extract true intent first. **Implement, don't propose**: a message implies action unless it explicitly says 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 |+- "Did you do X?" (and you didn't) -> acknowledge briefly, do X now+- "How does X work?" -> understand, then fix or improve+- "Can you look into Y?" -> investigate, then resolve+- "What's the best way to do Z?" -> decide, then implement the best way+- "Why is A broken?" / "Seeing error B" -> diagnose, then fix+- "What do you think about C?" -> 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.+**Pure question (no action) only when ALL hold**: an explicit "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.+State your read in one line before acting: "I detect [intent type] - [reason]. [What I'm doing now]." Naming an implementation, fix, or investigation **commits you to finish it 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.+Never speculate about code you have not read. The worktree is shared with the user and other agents: verify with tools, not 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.+**Start broad once.** For non-trivial work, run independent file reads, `rg` searches, symbol lookups, and doc retrieval in parallel - 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.+**Retrieve again only when** the first batch missed the core question; a required fact, path, type, owner, or convention is still missing; a second-order question (callers, error paths, ownership, side effects) changes the design; or 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 stop at the surface.** Unsure whether to call a tool? Call it. Think you understand? Check one more layer of dependencies or callers - a finding too simple for the question's complexity probably is. Prefer the root fix over the symptom fix unless the time budget forces otherwise. Resolve prerequisite lookups before any action depending 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.+**Stop searching when** you have enough context to act, sources repeat, 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.+**Independent tool calls run in the same response, never sequentially.** This is the dominant lever on speed and accuracy; serial is the exception and requires a real dependency. Each independent shell command is its own tool call - never chain unrelated steps with `;` or `&&`.-- 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.+omo-codex auto-runs LSP diagnostics after every edit and injects the result: any reported error is 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.+omo-codex bundles read-only Codex subagent roles in `CODEX_HOME/agents/`. Spawn: `multi_agent_v1.spawn_agent({"message":"TASK: act as a <role>. ...","fork_context":false})`-**Routing:**+- `explorer` - codebase search: "Where is X?" / "Find code that does Y"+- `librarian` - external docs, OSS code, API contracts (gh CLI + web)+- `plan` - strategic planning: 5+ interdependent steps, ambiguous scope, multi-module work+- `codex-ultrawork-reviewer` - rigorous verification of a finished change-- "Where is X?" / "Find code that does Y" -> `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})`-- "How does library Z work?" / "What's the API contract?" -> `spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})`-- 5+ interdependent steps, ambiguous scope, multi-module work -> `spawn_agent({"task_name":"...","message":"TASK: act as a planning agent. ...","fork_turns":"none"})`-- Heavy verification of a finished change -> `spawn_agent({"task_name":"...","message":"TASK: act as a rigorous reviewer. ...","fork_turns":"none"})`+**Default to parallel spawns over self-research.** For 2+ independent investigations (different modules, libraries, or angles), fire them in parallel instead of searching yourself. Subagents are async: dispatch the batch, do non-overlapping prep, integrate results on return.-**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.+**Don't duplicate.** Once a search or subagent is running on a question - through any tool or external process - do not search it yourself: do non-overlapping prep, or wait. Never poll running work without a completion signal. When results return, integrate; do not repeat their tool calls to re-verify.-**Keep parent liveness visible.** While any child is active, keep the parent visibly alive with brief status updates that include active subagent count, agent names, latest `WORKING:` phase, and whether the parent is waiting for mailbox updates. Do this during long `wait_agent` cycles so the session does not look idle while children are still running.+**Keep parent liveness visible.** While children run - especially long `multi_agent_v1.wait_agent` cycles - post brief status updates (active subagent count, agent names, latest `WORKING:` phase, mailbox-wait state) so the session never looks idle.# 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 -> Plan -> Implement -> Verify -> Manually QA.** Loops are short and tight; never 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.+- **Explore** per Discovery & Retrieval.+- **Plan** via `update_plan` per Task Tracking: files to modify, specific changes, dependencies.+- **Implement** surgically per Pragmatism & Scope, matching codebase style - naming, indentation, imports, error handling - even when you would write it differently in a greenfield.+- **Verify**: LSP diagnostics on changed files, related tests, build if applicable - in parallel where possible.+- **Manually QA**: drive the artifact through its matching 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:+LSP diagnostics catch type errors, not logic bugs; tests cover only what their authors anticipated. **"Done" requires the artifact has been driven through its matching surface - you personally used the deliverable and observed it working - within this turn.** The surface picks 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.+- **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.+- **Library / SDK / module** - a minimal driver script that imports and executes the new code end-to-end.+- **No matching surface** - 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".+Reading the source and concluding "this should work" does not pass this gate. A defect found in usage is yours to fix in this turn - same turn, not "follow-up".# Global Review and Debugging Gate-For significant implementation work and every PR handoff, run `review-work` plus a `debugging` runtime audit before declaring completion. Timeout, missing deliverable, ack-only, `BLOCKED:`, and inconclusive review lanes fail the gate. Record at least three debugging hypotheses and the runtime evidence that confirms or refutes each one.+For significant implementation work and every PR handoff, run `review-work` plus a `debugging` runtime audit before declaring completion. Timeout, missing deliverable, ack-only, `BLOCKED:`, and inconclusive review lanes fail the gate. Record at least three debugging hypotheses with the runtime evidence confirming or refuting each.-Do not print completion, create a PR, produce a PR handoff, or produce a branch handoff until the gate passes. Always redact secrets, tokens, credentials, auth headers, cookies, env dumps, private logs, and PII from ledgers, PR bodies, and handoffs.+No completion message, PR, or PR/branch handoff until the gate passes. Always redact secrets, tokens, credentials, auth headers, cookies, env dumps, private logs, and PII from ledgers, PR bodies, and handoffs.# Failure RecoveryIf 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.+**Three-attempt protocol.** After three different approaches fail: stop editing immediately; revert or surgically undo only your own changes back to a known-good state; document each attempt and why it failed; then step back and ask the user one precise question carrying that failure context.# Pragmatism & ScopeThe 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.+- Keep obvious single-use logic inline; extract a helper only when it is reused, hides meaningful complexity, or names a real domain concept.+- A small amount of duplication beats speculative abstraction.+- Bug fix != surrounding cleanup - do not refactor surrounding code while fixing. Simple feature != extra configurability.+- Fix only issues your changes caused; pre-existing lint errors or failing tests unrelated to your work go 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.+Write only what the current correct path needs: no error handlers, fallbacks, retries, or input validation for scenarios the current contracts make impossible. 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.+No backward-compatibility code, migration shims, or alternate code paths "in case". 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.+Default to no new tests. Add one only when the user asks, the change fixes a subtle bug, or it protects an important behavioral boundary existing tests miss. 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.+When the user asks for a "review", findings come first, ordered by severity with file references; open questions and assumptions follow; the change-summary is secondary, not the lead. No findings? Say so explicitly and call out residual risks and testing gaps.# AGENTS.md@@ -154,11 +138,11 @@ AGENTS.md files in your context carry directory-scoped conventions. Obey them fo# 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.+**Preamble.** Before the first tool call on any multi-step task, send a 1-2 sentence user-visible update: acknowledge the request, state your first concrete step.-**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.+**During work.** One sentence at meaningful phase transitions only - a discovery that changes the plan, a decision with tradeoffs, a blocker, the start of a non-trivial verification step. Never narrate routine reads or `rg` calls.-**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.+**Final message.** Lead with the result, then supporting context for where and why. No conversational openers ("Done -", "Got it"). Group by user-facing outcome, not by file. Simple work: 1-2 short paragraphs; larger work: at most 2-4 short sections.**Formatting.**@@ -168,26 +152,19 @@ AGENTS.md files in your context carry directory-scoped conventions. Obey them fo- 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+# Success Criteria and Stop RulesDone when ALL of:-- Every behavior the user asked for is implemented; no partial delivery, no "v0 / extend later".+- 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 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+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.-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.+Stop **only when** all of the above are true. Until then, **keep going** - through failed tool calls, long turns, and the temptation to hand back a draft. Forbidden stops: the artifact not yet driven through its matching surface; a tool reported success but you have not verified the changed files and observable behavior.**Hard invariants** - non-negotiable, regardless of pressure to ship:@@ -198,20 +175,16 @@ Write the final message and stop **only when** Success Criteria are all true. Un- 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.+**Asking the user** is a last resort: a missing secret, a design decision only they can make, a destructive action you should not take unilaterally, or missing information that would materially change the answer or create real risk. Even then, ask exactly one precise, narrow 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.+Use `update_plan` for anything beyond a single atomic edit: 2+ steps, uncertain scope, multi-file changes, branching investigation. Skip planning only for the easiest 25%; never make single-step plans. **Improvising past step 2 without a plan? Stop and call `update_plan` now.**-**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.+- 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.+- 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.**-**Refusing to plan is a failure mode.** If you find yourself improvising past step 2 without a plan, stop and call `update_plan` now.+**Promise discipline.** Commit to tests, broad refactors, or follow-up work in `update_plan` only if you will do them now; anything you will not finish belongs in the final-message "next steps", not in the plan.diff --git a/plugins/omo/components/rules/hooks/hooks.json b/plugins/omo/components/rules/hooks/hooks.jsonindex 23ba6505..1dcc95ba 100644--- a/plugins/omo/components/rules/hooks/hooks.json+++ b/plugins/omo/components/rules/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Loading Project Rules"+ "statusMessage": "LazyCodex(4.9.0): Loading Project Rules"}]}@@ -19,7 +19,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Loading Project Rules"+ "statusMessage": "LazyCodex(4.9.0): Loading Project Rules"}]}@@ -32,7 +32,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Matching Project Rules"+ "statusMessage": "LazyCodex(4.9.0): Matching Project Rules"}]}@@ -45,7 +45,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Resetting Project Rule Cache"+ "statusMessage": "LazyCodex(4.9.0): Resetting Project Rule Cache"}]}diff --git a/plugins/omo/components/rules/package.json b/plugins/omo/components/rules/package.jsonindex 422bc80f..999610c1 100644--- a/plugins/omo/components/rules/package.json+++ b/plugins/omo/components/rules/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-rules",- "version": "0.1.0",+ "version": "4.9.0","description": "Codex plugin that injects project rule files into model context through lifecycle hooks.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/rules/src/codex-hook.ts b/plugins/omo/components/rules/src/codex-hook.tsindex 84d0f94c..6b37366c 100644--- a/plugins/omo/components/rules/src/codex-hook.ts+++ b/plugins/omo/components/rules/src/codex-hook.ts@@ -3,6 +3,7 @@ import { configFromEnvironment } from "./config.js";import { hasContextPressureMarker, transcriptHasContextPressureMarker } from "./context-pressure.js";import { createHookDebugTimer } from "./debug-log.js";import { fingerprintDynamicTargets } from "./dynamic-target-fingerprints.js";+import { withDynamicBudget } from "./event-budget.js";import { formatAdditionalContextOutput } from "./hook-output.js";import { displayPath, uniqueStrings } from "./path-utils.js";import {@@ -175,11 +176,12 @@ export async function runPostToolUseHook(debugTimer.done({ outputBytes: 0, reason: "post-compact-recovery-in-progress" });return "";}+ const dynamicConfig = withDynamicBudget(config);const engine = createRulesEngine(options,completedPostCompactKind !== undefined- ? withPostCompactBudget(config, { model: input.model, transcriptPath: input.transcript_path })- : config,+ ? withPostCompactBudget(dynamicConfig, { model: input.model, transcriptPath: input.transcript_path })+ : dynamicConfig,);hydrateEngineState(engine, cachePath);debugTimer.lap("hydrate", {diff --git a/plugins/omo/components/rules/src/config.ts b/plugins/omo/components/rules/src/config.tsindex 7882508d..98c1a9a4 100644--- a/plugins/omo/components/rules/src/config.ts+++ b/plugins/omo/components/rules/src/config.ts@@ -21,6 +21,19 @@ export function configFromEnvironment(env: NodeJS.ProcessEnv = process.env): PiRparsePositiveInteger(firstEnv(env, "CODEX_RULES_POST_COMPACT_MAX_RESULT_CHARS", "PI_RULES_POST_COMPACT_MAX_RESULT_CHARS"),) ?? config.postCompactMaxResultChars;+ config.dynamicMaxRuleChars =+ parsePositiveInteger(firstEnv(env, "CODEX_RULES_DYNAMIC_MAX_RULE_CHARS", "PI_RULES_DYNAMIC_MAX_RULE_CHARS")) ??+ config.dynamicMaxRuleChars;+ config.dynamicMaxResultChars =+ parsePositiveInteger(+ firstEnv(env, "CODEX_RULES_DYNAMIC_MAX_RESULT_CHARS", "PI_RULES_DYNAMIC_MAX_RESULT_CHARS"),+ ) ?? config.dynamicMaxResultChars;+ config.promptMaxRuleChars =+ parsePositiveInteger(firstEnv(env, "CODEX_RULES_PROMPT_MAX_RULE_CHARS", "PI_RULES_PROMPT_MAX_RULE_CHARS")) ??+ config.promptMaxRuleChars;+ config.promptMaxResultChars =+ parsePositiveInteger(firstEnv(env, "CODEX_RULES_PROMPT_MAX_RESULT_CHARS", "PI_RULES_PROMPT_MAX_RESULT_CHARS")) ??+ config.promptMaxResultChars;config.enabledSources = parseEnabledSources(firstEnv(env, "CODEX_RULES_ENABLED_SOURCES", "PI_RULES_ENABLED_SOURCES"),disableBundledRules,diff --git a/plugins/omo/components/rules/src/event-budget.ts b/plugins/omo/components/rules/src/event-budget.tsnew file mode 100644index 00000000..c79712e9--- /dev/null+++ b/plugins/omo/components/rules/src/event-budget.ts@@ -0,0 +1,17 @@+import type { PiRulesConfig } from "./rules/types.js";++export function withDynamicBudget(config: PiRulesConfig): PiRulesConfig {+ return {+ ...config,+ maxRuleChars: Math.min(config.maxRuleChars, config.dynamicMaxRuleChars),+ maxResultChars: Math.min(config.maxResultChars, config.dynamicMaxResultChars),+ };+}++export function withPromptBudget(config: PiRulesConfig): PiRulesConfig {+ return {+ ...config,+ maxRuleChars: Math.min(config.maxRuleChars, config.promptMaxRuleChars),+ maxResultChars: Math.min(config.maxResultChars, config.promptMaxResultChars),+ };+}diff --git a/plugins/omo/components/rules/src/persistent-cache.ts b/plugins/omo/components/rules/src/persistent-cache.tsindex 9e24a0be..7e7926d2 100644--- a/plugins/omo/components/rules/src/persistent-cache.ts+++ b/plugins/omo/components/rules/src/persistent-cache.ts@@ -68,8 +68,11 @@ export function clearSessionState(cachePath: string): void {export function markSessionCompacted(cachePath: string): void {const state = readSessionState(cachePath);+ // Compaction drops injected static rule bodies, so pre-compaction static+ // dedup marks must not suppress the post-compact recovery directive.+ // Dynamic dedup survives: those rules are recovered as read-directive paths.writeSessionState(cachePath, {- staticDedup: state.staticDedup,+ staticDedup: [],dynamicDedup: state.dynamicDedup,...(state.dynamicTargetFingerprints === undefined? {}diff --git a/plugins/omo/components/rules/src/post-compact-directive.ts b/plugins/omo/components/rules/src/post-compact-directive.tsnew file mode 100644index 00000000..7574f0a4--- /dev/null+++ b/plugins/omo/components/rules/src/post-compact-directive.ts@@ -0,0 +1,39 @@+import { uniqueStrings } from "./path-utils.js";++const DIRECTIVE_HEADER = [+ "## MANDATORY: POST-COMPACTION RULE RECOVERY",+ "",+ "Context compaction DROPPED the project rule files listed below from your context.",+ "YOU MUST READ THE FOLLOWING RULES with your file-reading tool RIGHT NOW, BEFORE ANY OTHER ACTION. NO EXCUSES.",+ "Do not plan, answer, edit, or run anything until EVERY file below has been read end to end:",+ "",+].join("\n");++const DIRECTIVE_FOOTER =+ "\nOperating without these rules is a protocol violation. Reconstructing them from memory is NOT reading. READ THEM ALL. NO EXCUSES.";++export function buildPostCompactReadDirective(rulePaths: ReadonlyArray<string>, maxChars: number): string {+ const paths = uniqueStrings([...rulePaths]);+ if (paths.length === 0) {+ return "";+ }++ const lines: string[] = [];+ let usedChars = DIRECTIVE_HEADER.length + DIRECTIVE_FOOTER.length;+ let omittedCount = 0;+ for (const rulePath of paths) {+ const line = `- ${rulePath}`;+ if (lines.length > 0 && usedChars + line.length + 1 > maxChars) {+ omittedCount += 1;+ continue;+ }+ lines.push(line);+ usedChars += line.length + 1;+ }+ if (omittedCount > 0) {+ lines.push(+ `- (+${omittedCount} more rule files omitted - rescan the project rule directories and read those too)`,+ );+ }+ return `${DIRECTIVE_HEADER}${lines.join("\n")}${DIRECTIVE_FOOTER}`;+}diff --git a/plugins/omo/components/rules/src/rules/constants.ts b/plugins/omo/components/rules/src/rules/constants.tsindex a3278ca2..8e846ce6 100644--- a/plugins/omo/components/rules/src/rules/constants.ts+++ b/plugins/omo/components/rules/src/rules/constants.ts@@ -87,6 +87,22 @@ export const DEFAULT_POST_COMPACT_MAX_RULE_CHARS = 3500;export const DEFAULT_POST_COMPACT_MAX_RESULT_CHARS = 4000;+/**+ * Per-rule / total caps for dynamic (PostToolUse) injection. Kept far below the+ * static defaults so mid-session rule matches stay lightweight.+ */+export const DEFAULT_DYNAMIC_MAX_RULE_CHARS = 4000;++export const DEFAULT_DYNAMIC_MAX_RESULT_CHARS = 10000;++/**+ * Per-rule / total caps for UserPromptSubmit static injection. SessionStart+ * keeps the full budget; prompt-time stragglers inject at a reduced size.+ */+export const DEFAULT_PROMPT_MAX_RULE_CHARS = 6000;++export const DEFAULT_PROMPT_MAX_RESULT_CHARS = 16000;+/*** Truncation marker template. `{path}` is replaced with the relative path.*/diff --git a/plugins/omo/components/rules/src/rules/engine.ts b/plugins/omo/components/rules/src/rules/engine.tsindex 550c4ceb..7b928462 100644--- a/plugins/omo/components/rules/src/rules/engine.ts+++ b/plugins/omo/components/rules/src/rules/engine.ts@@ -7,10 +7,14 @@ import {markStaticInjected as markStaticInjectedInState,} from "./cache.js";import {+ DEFAULT_DYNAMIC_MAX_RESULT_CHARS,+ DEFAULT_DYNAMIC_MAX_RULE_CHARS,DEFAULT_MAX_RESULT_CHARS,DEFAULT_MAX_RULE_CHARS,DEFAULT_POST_COMPACT_MAX_RESULT_CHARS,DEFAULT_POST_COMPACT_MAX_RULE_CHARS,+ DEFAULT_PROMPT_MAX_RESULT_CHARS,+ DEFAULT_PROMPT_MAX_RULE_CHARS,} from "./constants.js";import { loadDynamicCandidates } from "./engine-dynamic-loader.js";import { loadStaticCandidates } from "./engine-static-loader.js";@@ -29,6 +33,10 @@ export function defaultConfig(): PiRulesConfig {maxResultChars: DEFAULT_MAX_RESULT_CHARS,postCompactMaxRuleChars: DEFAULT_POST_COMPACT_MAX_RULE_CHARS,postCompactMaxResultChars: DEFAULT_POST_COMPACT_MAX_RESULT_CHARS,+ dynamicMaxRuleChars: DEFAULT_DYNAMIC_MAX_RULE_CHARS,+ dynamicMaxResultChars: DEFAULT_DYNAMIC_MAX_RESULT_CHARS,+ promptMaxRuleChars: DEFAULT_PROMPT_MAX_RULE_CHARS,+ promptMaxResultChars: DEFAULT_PROMPT_MAX_RESULT_CHARS,enabledSources: "auto",};}diff --git a/plugins/omo/components/rules/src/rules/formatter.ts b/plugins/omo/components/rules/src/rules/formatter.tsindex f4ac8a1a..594bd16a 100644--- a/plugins/omo/components/rules/src/rules/formatter.ts+++ b/plugins/omo/components/rules/src/rules/formatter.ts@@ -1,4 +1,4 @@-import { truncateBudget, truncateRule } from "./truncator.js";+import { isNeverTruncatedRule, truncateBudget, truncateRule } from "./truncator.js";import type { LoadedRule } from "./types.js";export interface FormatOptions {@@ -35,13 +35,12 @@ function truncateRules(rules: ReadonlyArray<LoadedRule>, options: FormatOptions)const perRuleBudgeted = perRuleNormalized.map((rule) => ({path: rule.path,relativePath: rule.relativePath,- body:- rule.source === "plugin-bundled"- ? truncateRule(rule.body, { maxChars: perRuleResultChars, relativePath: rule.relativePath }).body- : truncateRule(rule.body, {- maxChars: Math.min(options.maxRuleChars, perRuleResultChars),- relativePath: rule.relativePath,- }).body,+ body: isNeverTruncatedRule(rule.relativePath)+ ? rule.body+ : truncateRule(rule.body, {+ maxChars: Math.min(options.maxRuleChars, perRuleResultChars),+ relativePath: rule.relativePath,+ }).body,}));const budgetedRules = truncateBudget({rules: perRuleBudgeted.map((rule) => ({ body: rule.body, relativePath: rule.relativePath })),diff --git a/plugins/omo/components/rules/src/rules/truncator.ts b/plugins/omo/components/rules/src/rules/truncator.tsindex 2c54bea8..3374a518 100644--- a/plugins/omo/components/rules/src/rules/truncator.ts+++ b/plugins/omo/components/rules/src/rules/truncator.ts@@ -14,6 +14,13 @@ function truncationNotice(relativePath: string): string {return TRUNCATION_NOTICE.replace("{path}", relativePath);}+export function isNeverTruncatedRule(relativePath: string): boolean {+ const normalized = relativePath.replace(/\\/g, "/");+ const segments = normalized.split("/").filter((segment) => segment.length > 0);+ const filename = segments.at(-1) ?? normalized;+ return filename.toLowerCase() === "hephaestus.md";+}+function safeSliceEnd(body: string, end: number): number {if (end <= 0) {return 0;@@ -28,6 +35,10 @@ function safeSliceEnd(body: string, end: number): number {}export function truncateRule(body: string, options: { maxChars: number; relativePath: string }): TruncationResult {+ if (isNeverTruncatedRule(options.relativePath)) {+ return { body, truncated: false, originalLength: body.length };+ }+if (body.length <= options.maxChars) {return { body, truncated: false, originalLength: body.length };}@@ -46,6 +57,12 @@ export function truncateBudget(input: { rules: ReadonlyArray<BudgetRule>; maxReslet remainingBudget = input.maxResultChars;for (const rule of input.rules) {+ if (isNeverTruncatedRule(rule.relativePath)) {+ results.push({ body: rule.body, truncated: false, relativePath: rule.relativePath });+ remainingBudget -= rule.body.length;+ continue;+ }+if (remainingBudget >= rule.body.length) {results.push({ body: rule.body, truncated: false, relativePath: rule.relativePath });remainingBudget -= rule.body.length;diff --git a/plugins/omo/components/rules/src/rules/types.ts b/plugins/omo/components/rules/src/rules/types.tsindex 862ac3c4..e85b09a2 100644--- a/plugins/omo/components/rules/src/rules/types.ts+++ b/plugins/omo/components/rules/src/rules/types.ts@@ -112,6 +112,10 @@ export interface PiRulesConfig {maxResultChars: number;postCompactMaxRuleChars: number;postCompactMaxResultChars: number;+ dynamicMaxRuleChars: number;+ dynamicMaxResultChars: number;+ promptMaxRuleChars: number;+ promptMaxResultChars: number;enabledSources: RuleSource[] | "auto";}diff --git a/plugins/omo/components/rules/src/sparkshell-awareness.ts b/plugins/omo/components/rules/src/sparkshell-awareness.tsindex a4cc51f1..2d9e5c96 100644--- a/plugins/omo/components/rules/src/sparkshell-awareness.ts+++ b/plugins/omo/components/rules/src/sparkshell-awareness.ts@@ -1,5 +1,13 @@+import { existsSync } from "node:fs";+import { join } from "node:path";+type RuntimeEnv = Readonly<Record<string, string | undefined>>;+interface OmoResolutionDeps {+ readonly fileExists?: (path: string) => boolean;+ readonly platform?: NodeJS.Platform;+}+const SPARKSHELL_AWARENESS_MARKER = "## Sparkshell Runtime";export const SPARKSHELL_AWARENESS_DEDUP_KEY = "__omo_sparkshell_awareness__";@@ -23,7 +31,38 @@ function isSparkShellAppServerConfigured(env: RuntimeEnv = process.env): booleanreturn codexSocketPath.length > 0 || omoSocketPath.length > 0;}-export function getSparkShellRuntimeAwareness(env: RuntimeEnv = process.env): string {+export function resolveOmoInvocation(env: RuntimeEnv = process.env, deps: OmoResolutionDeps = {}): string | null {+ const fileExists = deps.fileExists ?? existsSync;+ const platform = deps.platform ?? process.platform;+ const binNames = platform === "win32" ? ["omo.cmd", "omo.exe", "omo"] : ["omo"];+ const pathDelimiter = platform === "win32" ? ";" : ":";+ const pathEntries = (env["PATH"] ?? "").split(pathDelimiter).filter((entry) => entry.trim().length > 0);+ for (const pathEntry of pathEntries) {+ for (const binName of binNames) {+ if (fileExists(join(pathEntry, binName))) return "omo";+ }+ }+ for (const candidateDir of omoCandidateBinDirs(env)) {+ for (const binName of binNames) {+ const candidate = join(candidateDir, binName);+ if (fileExists(candidate)) return candidate;+ }+ }+ return null;+}++function omoCandidateBinDirs(env: RuntimeEnv): readonly string[] {+ const dirs: string[] = [];+ const localBinDir = env["CODEX_LOCAL_BIN_DIR"]?.trim() ?? "";+ if (localBinDir.length > 0) dirs.push(localBinDir);+ const home = env["HOME"]?.trim() || env["USERPROFILE"]?.trim() || "";+ const codexHome = env["CODEX_HOME"]?.trim() || (home.length > 0 ? join(home, ".codex") : "");+ if (codexHome.length > 0) dirs.push(join(codexHome, "bin"));+ if (home.length > 0) dirs.push(join(home, ".local", "bin"));+ return dirs;+}++export function getSparkShellRuntimeAwareness(env: RuntimeEnv = process.env, deps: OmoResolutionDeps = {}): string {const override = env["OMO_SPARKSHELL_AWARENESS"] ?? env["LAZYCODEX_SPARKSHELL_AWARENESS"];if (isFalsy(override)) {return "";@@ -32,13 +71,23 @@ export function getSparkShellRuntimeAwareness(env: RuntimeEnv = process.env): streturn "";}+ const resolved = resolveOmoInvocation(env, deps);+ const invocation = resolved ?? (isTruthy(override) ? "omo" : null);+ if (invocation === null) {+ return "";+ }+ const command = /\s/.test(invocation) ? `"${invocation}"` : invocation;+return [SPARKSHELL_AWARENESS_MARKER,"",- "- Prefer `omo sparkshell <command>` for repo inspection, CLI smoke tests, git/history checks, and bounded verification before falling back to raw shell commands.",- "- Use `omo sparkshell --shell '<command>'` only when shell metacharacters are required.",- "- Use `omo sparkshell --tmux-pane <pane-id> --tail-lines 400` to inspect an existing tmux pane. Tail lines must stay between 100 and 1000.",+ `- Prefer \`${command} sparkshell <command>\` for repo inspection, CLI smoke tests, git/history checks, and bounded verification before falling back to raw shell commands.`,+ `- Use \`${command} sparkshell --shell '<command>'\` only when shell metacharacters are required.`,+ `- Use \`${command} sparkshell --tmux-pane <pane-id> --tail-lines 400\` to inspect an existing tmux pane. Tail lines must stay between 100 and 1000.`,"- When no native sidecar or appserver is available, Sparkshell silently falls back to raw command execution. `OMO_SPARKSHELL_BIN` selects a native sidecar path.",+ "- When `CODEX_THREAD_ID` identifies a Codex session, Sparkshell appends recent session context (first/latest user request + last 5 conversation messages) after the shell result so output consumers stay aligned with the session goals. `OMO_SPARKSHELL_SESSION_CONTEXT=0` disables it.",+ `- Route potentially huge output (full log files, big diffs, \`cat\`/\`grep\` over large artifacts) through \`${command} sparkshell\` instead of reading it raw: oversized output is condensed to a budget while preserving error signatures, repeated patterns, session-goal-relevant lines, and head/tail. Tune with \`--budget <chars>\`; disable with \`OMO_SPARKSHELL_CONDENSE=0\`.`,+ "- Oversized output is first summarized by the spark model (`codex exec`, default `gpt-5.3-codex-spark`) fed with the session context: the summary reproduces the output as-is (no masking) and ends with a `[sparkshell caption]` line describing what ran and which lines were omitted. `OMO_SPARKSHELL_SPARK=0` skips the model and uses deterministic condensation directly.",].join("\n");}diff --git a/plugins/omo/components/rules/src/static-injection.ts b/plugins/omo/components/rules/src/static-injection.tsindex b4659d02..41c529d0 100644--- a/plugins/omo/components/rules/src/static-injection.ts+++ b/plugins/omo/components/rules/src/static-injection.ts@@ -1,12 +1,20 @@+import { existsSync } from "node:fs";+import type { CodexRulesHookOptions } from "./codex-hook-options.js";import { configFromEnvironment } from "./config.js";+import { withPromptBudget } from "./event-budget.js";import { formatAdditionalContextOutput } from "./hook-output.js";import { completePostCompactRecovery, hydrateEngineState, persistEngineState } from "./persistent-cache.js";import { withPostCompactBudget } from "./post-compact-budget.js";+import { buildPostCompactReadDirective } from "./post-compact-directive.js";+import type { Engine } from "./rules/engine.js";+import { isNeverTruncatedRule } from "./rules/truncator.js";+import type { LoadedRule, PiRulesConfig } from "./rules/types.js";import { createRulesEngine } from "./rules-engine-factory.js";import { getSparkShellRuntimeAwareness, SPARKSHELL_AWARENESS_DEDUP_KEY } from "./sparkshell-awareness.js";-import { filterRulesAlreadyInTranscript } from "./transcript-rule-filter.js";+import { filterRulesAlreadyInTranscript, filterRulesNotInTranscriptText } from "./transcript-rule-filter.js";import type { TranscriptSearchOptions } from "./transcript-search.js";+import { readTranscriptSearchText } from "./transcript-search.js";export function runStaticInjection(cwd: string,@@ -26,10 +34,20 @@ export function runStaticInjection(return "";}- const effectiveConfig =- completedPostCompactChannel === undefined- ? config- : withPostCompactBudget(config, { model: model ?? "", transcriptPath });+ if (completedPostCompactChannel !== undefined) {+ return runPostCompactRecovery({+ cwd,+ transcriptPath,+ eventName,+ cachePath,+ options,+ channel: completedPostCompactChannel,+ model: model ?? "",+ config,+ });+ }++ const effectiveConfig = eventName === "UserPromptSubmit" ? withPromptBudget(config) : config;const engine = createRulesEngine(options, effectiveConfig);hydrateEngineState(engine, cachePath);engine.state.cwd = cwd;@@ -47,7 +65,7 @@ export function runStaticInjection(? "": getSparkShellRuntimeAwareness(options.env);if (rules.length === 0 && sparkshellAwareness.length === 0) {- persistEngineState(engine, cachePath, completedPostCompactChannel);+ persistEngineState(engine, cachePath);return "";}@@ -58,10 +76,112 @@ export function runStaticInjection(if (sparkshellAwareness.length > 0) {engine.state.staticDedup.add(SPARKSHELL_AWARENESS_DEDUP_KEY);}- persistEngineState(engine, cachePath, completedPostCompactChannel);+ persistEngineState(engine, cachePath);return formatAdditionalContextOutput(eventName, combineStaticContext(block, sparkshellAwareness));}+interface PostCompactRecoveryInput {+ cwd: string;+ transcriptPath: string | null;+ eventName: "SessionStart" | "UserPromptSubmit";+ cachePath: string;+ options: CodexRulesHookOptions;+ channel: "static";+ model: string;+ config: PiRulesConfig;+}++function runPostCompactRecovery(input: PostCompactRecoveryInput): string {+ const effectiveConfig = withPostCompactBudget(input.config, {+ model: input.model,+ transcriptPath: input.transcriptPath,+ });+ const engine = createRulesEngine(input.options, effectiveConfig);+ hydrateEngineState(engine, input.cachePath);+ engine.state.cwd = input.cwd;++ const loaded = engine.loadStaticRules(input.cwd);+ const transcriptText = readRecoveryTranscriptText(input.transcriptPath);+ const missingRules = filterRulesNotInTranscriptText(+ loaded.rules.filter((rule) => !engine.isStaticInjected(rule)),+ transcriptText,+ (rule) => {+ engine.markStaticInjected(rule);+ },+ );+ const dynamicRulePaths = recoverDynamicRulePaths(engine, transcriptText, loaded.rules);+ const sparkshellAwareness = engine.state.staticDedup.has(SPARKSHELL_AWARENESS_DEDUP_KEY)+ ? ""+ : getSparkShellRuntimeAwareness(input.options.env);++ if (missingRules.length === 0 && dynamicRulePaths.length === 0 && sparkshellAwareness.length === 0) {+ persistEngineState(engine, input.cachePath, input.channel);+ return "";+ }++ const fullBodyRules = missingRules.filter((rule) => isNeverTruncatedRule(ruleDisplayPath(rule)));+ const listedRules = missingRules.filter((rule) => !isNeverTruncatedRule(ruleDisplayPath(rule)));+ const bodyBlock = fullBodyRules.length === 0 ? "" : engine.formatStatic(fullBodyRules);+ const directive = buildPostCompactReadDirective(+ [...listedRules.map((rule) => rule.path), ...dynamicRulePaths],+ effectiveConfig.maxResultChars,+ );+ for (const rule of missingRules) {+ engine.markStaticInjected(rule);+ }+ if (sparkshellAwareness.length > 0) {+ engine.state.staticDedup.add(SPARKSHELL_AWARENESS_DEDUP_KEY);+ }+ persistEngineState(engine, input.cachePath, input.channel);+ return formatAdditionalContextOutput(+ input.eventName,+ combineStaticContext(bodyBlock, directive, sparkshellAwareness),+ );+}++function readRecoveryTranscriptText(transcriptPath: string | null): string | null {+ if (transcriptPath === null) {+ return null;+ }+ return (+ readTranscriptSearchText(transcriptPath, { latestCompactedReplacementOnly: true }) ??+ readTranscriptSearchText(transcriptPath)+ );+}++function recoverDynamicRulePaths(+ engine: Engine,+ transcriptText: string | null,+ staticRules: ReadonlyArray<LoadedRule>,+): string[] {+ const staticRulePaths = new Set(staticRules.map((rule) => rule.realPath));+ const recoveredPaths = new Set<string>();+ for (const dedupKeys of engine.state.dynamicDedup.values()) {+ for (const dedupKey of dedupKeys) {+ const separatorIndex = dedupKey.lastIndexOf("::");+ if (separatorIndex <= 0) {+ continue;+ }+ const rulePath = dedupKey.slice(0, separatorIndex);+ if (staticRulePaths.has(rulePath)) {+ continue;+ }+ if (transcriptText !== null && transcriptText.includes(rulePath)) {+ continue;+ }+ if (!existsSync(rulePath)) {+ continue;+ }+ recoveredPaths.add(rulePath);+ }+ }+ return [...recoveredPaths].sort();+}++function ruleDisplayPath(rule: LoadedRule): string {+ return rule.relativePath.length > 0 ? rule.relativePath : rule.path;+}+function combineStaticContext(...blocks: readonly string[]): string {return blocks.filter((block) => block.trim().length > 0).join("\n\n");}diff --git a/plugins/omo/components/rules/src/transcript-rule-filter.ts b/plugins/omo/components/rules/src/transcript-rule-filter.tsindex 2d9fd179..727223c9 100644--- a/plugins/omo/components/rules/src/transcript-rule-filter.ts+++ b/plugins/omo/components/rules/src/transcript-rule-filter.ts@@ -13,7 +13,15 @@ export function filterRulesAlreadyInTranscript(}const transcriptText = readTranscriptSearchText(transcriptPath, options);- if (transcriptText === null) {+ return filterRulesNotInTranscriptText(rules, transcriptText, markInjected);+}++export function filterRulesNotInTranscriptText(+ rules: ReadonlyArray<LoadedRule>,+ transcriptText: string | null,+ markInjected: (rule: LoadedRule) => void,+): LoadedRule[] {+ if (rules.length === 0 || transcriptText === null) {return [...rules];}diff --git a/plugins/omo/components/rules/test/bundled-rules.test.ts b/plugins/omo/components/rules/test/bundled-rules.test.tsindex c39846a4..ab1f1863 100644--- a/plugins/omo/components/rules/test/bundled-rules.test.ts+++ b/plugins/omo/components/rules/test/bundled-rules.test.ts@@ -200,7 +200,7 @@ describe("plugin bundled rules", () => {expect(output).toBe("");});- it("#given bundled static context already injected #when UserPromptSubmit runs after PostCompact #then it emits no duplicate bundled context", async () => {+ it("#given bundled static context dropped by compaction #when UserPromptSubmit runs after PostCompact #then it re-injects the bundled persona body in full", async () => {// givenconst { root, pluginData, bundledRulePath } = makeFixture();const firstOutput = await runSessionStartHook(sessionStartInput(root), {@@ -219,7 +219,9 @@ describe("plugin bundled rules", () => {// thenexpect(compactOutput).toBe("");- expect(output).toBe("");+ expect(output).toContain(`Instructions from: ${bundledRulePath}`);+ expect(output).toContain(BUNDLED_BODY);+ expect(output).not.toContain("[Truncated. Full:");});it("#given bundled Hephaestus rule body exceeds per-rule cap #when SessionStart runs #then static context expands the body within result budget", async () => {diff --git a/plugins/omo/components/rules/test/codex-hook-post-compact-budget.test.ts b/plugins/omo/components/rules/test/codex-hook-post-compact-budget.test.tsindex 99391b50..1617d62b 100644--- a/plugins/omo/components/rules/test/codex-hook-post-compact-budget.test.ts+++ b/plugins/omo/components/rules/test/codex-hook-post-compact-budget.test.ts@@ -25,7 +25,7 @@ afterEach(() => {});describe("codex rules post-compaction context budget", () => {- it("#given oversized project rules already injected #when static recovery runs after compaction #then it emits no duplicate static injection", async () => {+ it("#given oversized project rules already injected #when static recovery runs after compaction #then it emits a mandatory read directive instead of rule bodies", async () => {// givenconst { root, pluginData } = makeOversizedProject();const firstOutput = await runSessionStartHook(sessionStartInput(root), {@@ -50,7 +50,12 @@ describe("codex rules post-compaction context budget", () => {expect(firstContext).toContain("Project rule");expect(firstContext).toContain("[Truncated. Full:");expect(firstContext.length).toBeLessThan(31_000);- expect(output).toBe("");+ const recoveryContext = readAdditionalContext(output);+ expect(recoveryContext).toContain("MUST READ");+ expect(recoveryContext).toContain("NO EXCUSES");+ expect(recoveryContext).toContain(path.join(root, "CONTEXT.md"));+ expect(recoveryContext).not.toContain("Project rule");+ expect(recoveryContext.length).toBeLessThan(2_000);});});diff --git a/plugins/omo/components/rules/test/codex-hook-post-compact-context.test.ts b/plugins/omo/components/rules/test/codex-hook-post-compact-context.test.tsindex 827f05dc..de437bcc 100644--- a/plugins/omo/components/rules/test/codex-hook-post-compact-context.test.ts+++ b/plugins/omo/components/rules/test/codex-hook-post-compact-context.test.ts@@ -20,7 +20,7 @@ afterEach(() => {});describe("codex rules compacted context recovery", () => {- it("#given compacted session source after PostCompact #when static rules re-inject #then output uses the compact recovery budget", async () => {+ it("#given compacted session source after PostCompact #when static recovery runs #then output is a mandatory read directive", async () => {// givenconst { root, pluginData } = makeOversizedProject("compact-source");const transcriptPath = writeCompactedTranscript(root, "summary dropped injected rules");@@ -37,10 +37,10 @@ describe("codex rules compacted context recovery", () => {// thenconst postCompactContext = readAdditionalContext(output);- expect(postCompactContext.length).toBeLessThan(5_000);- expect(postCompactContext).toContain("Instructions from:");+ expect(postCompactContext.length).toBeLessThan(2_000);+ expect(postCompactContext).toContain("MUST READ");expect(postCompactContext).toContain("CONTEXT.md");- expect(postCompactContext).toContain("Project rule");+ expect(postCompactContext).not.toContain("Project rule");});it("#given compacted context warning and near-full transcript #when compact source starts twice #then handles compacted context warning once", async () => {@@ -65,7 +65,7 @@ describe("codex rules compacted context recovery", () => {// thenconst firstContext = readOptionalAdditionalContext(firstOutput);expect(firstContext.length).toBeLessThan(1_000);- expect(firstContext).toContain("Instructions from:");+ expect(firstContext).toContain("MUST READ");expect(firstContext).toContain("CONTEXT.md");expect(secondOutput).toBe("");});@@ -88,7 +88,7 @@ describe("codex rules compacted context recovery", () => {// thenconst context = readOptionalAdditionalContext(output);expect(context.length).toBeLessThan(1_000);- expect(context).toContain("Instructions from:");+ expect(context).toContain("MUST READ");expect(context).toContain("CONTEXT.md");});@@ -106,7 +106,7 @@ describe("codex rules compacted context recovery", () => {// thenconst context = readOptionalAdditionalContext(output);expect(context.length).toBeLessThan(1_000);- expect(context).toContain("Instructions from:");+ expect(context).toContain("MUST READ");expect(context).toContain("CONTEXT.md");});@@ -128,7 +128,7 @@ describe("codex rules compacted context recovery", () => {// thenconst context = readOptionalAdditionalContext(output);expect(context.length).toBeLessThan(1_000);- expect(context).toContain("Instructions from:");+ expect(context).toContain("MUST READ");expect(context).toContain("CONTEXT.md");});@@ -157,7 +157,7 @@ describe("codex rules compacted context recovery", () => {const contexts = outputs.map(readOptionalAdditionalContext);expect(contexts.filter((context) => context.length > 0)).toHaveLength(1);expect(contexts.join("").length).toBeLessThan(1_000);- expect(contexts.join("")).toContain("Instructions from:");+ expect(contexts.join("")).toContain("MUST READ");expect(contexts.join("")).toContain("CONTEXT.md");});});diff --git a/plugins/omo/components/rules/test/codex-hook-post-compact-dedup.test.ts b/plugins/omo/components/rules/test/codex-hook-post-compact-dedup.test.tsindex 30ff2f91..cf732d62 100644--- a/plugins/omo/components/rules/test/codex-hook-post-compact-dedup.test.ts+++ b/plugins/omo/components/rules/test/codex-hook-post-compact-dedup.test.ts@@ -93,7 +93,7 @@ describe("codex rules PostCompact deduplication", () => {expect(output).toBe("");});- it("#given startup already injected static context #when UserPromptSubmit runs after PostCompact #then it emits no duplicate static context", async () => {+ it("#given startup static context dropped by compaction #when UserPromptSubmit runs after PostCompact #then it emits a mandatory read directive without rule bodies", async () => {// givenconst { root, pluginData } = makeTempProject();await runSessionStartHook(sessionStartInput(root), {@@ -113,10 +113,13 @@ describe("codex rules PostCompact deduplication", () => {});// then- expect(output).toBe("");+ const context = readAdditionalContext(output);+ expect(context).toContain("MUST READ");+ expect(context).toContain("CONTEXT.md");+ expect(context).not.toContain("Instructions from:");});- it("#given startup already injected static context #when compact SessionStart runs after PostCompact #then it emits no duplicate static context", async () => {+ it("#given startup static context dropped by compaction #when compact SessionStart runs after PostCompact #then it emits a mandatory read directive without rule bodies", async () => {// givenconst { root, pluginData } = makeTempProject();await runSessionStartHook(sessionStartInput(root), {@@ -136,7 +139,10 @@ describe("codex rules PostCompact deduplication", () => {});// then- expect(output).toBe("");+ const context = readAdditionalContext(output);+ expect(context).toContain("MUST READ");+ expect(context).toContain("CONTEXT.md");+ expect(context).not.toContain("Instructions from:");});});diff --git a/plugins/omo/components/rules/test/codex-hook-post-compact-directive.test.ts b/plugins/omo/components/rules/test/codex-hook-post-compact-directive.test.tsnew file mode 100644index 00000000..4828728c--- /dev/null+++ b/plugins/omo/components/rules/test/codex-hook-post-compact-directive.test.ts@@ -0,0 +1,241 @@+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 CodexPostCompactInput,+ type CodexPostToolUseInput,+ type CodexSessionStartInput,+ type CodexUserPromptSubmitInput,+ runPostCompactHook,+ runPostToolUseHook,+ runSessionStartHook,+ runUserPromptSubmitHook,+} from "../src/codex-hook.js";++const tempDirectories: string[] = [];+const PROJECT_ONLY_ENV = {+ CODEX_RULES_ENABLED_SOURCES: "CONTEXT.md,.omo/rules",+};+const SESSION_ID = "session-post-compact-directive";++afterEach(() => {+ for (const directory of tempDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++describe("codex rules post-compaction read directive", () => {+ it("#given injected rules dropped by compaction #when UserPromptSubmit recovers #then it lists rule paths in a mandatory read directive instead of bodies", async () => {+ // given+ const { root, pluginData } = makeProject();+ await runSessionStartHook(sessionStartInput(root), { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV });+ const dynamicOutput = await runPostToolUseHook(postToolUseInput(root, path.join(root, "src", "app.ts")), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });+ const transcriptPath = writeCompactedTranscript(root, "summary that dropped every injected rule");+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );++ // when+ const output = await runUserPromptSubmitHook(userPromptSubmitInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });++ // then+ expect(dynamicOutput).toContain("TypeScript rule");+ const context = readAdditionalContext(output);+ expect(context).toContain("MUST READ");+ expect(context).toContain("NO EXCUSES");+ expect(context).toContain("CONTEXT.md");+ expect(context).toContain(".omo/rules/typescript.md");+ expect(context).not.toContain("A".repeat(50));+ expect(context).not.toContain("B".repeat(50));+ expect(context.length).toBeLessThan(2_000);+ });++ it("#given recovery directive already emitted #when UserPromptSubmit runs again #then it emits nothing", async () => {+ // given+ const { root, pluginData } = makeProject();+ await runSessionStartHook(sessionStartInput(root), { pluginDataRoot: pluginData, env: PROJECT_ONLY_ENV });+ const transcriptPath = writeCompactedTranscript(root, "summary that dropped every injected rule");+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );+ await runUserPromptSubmitHook(userPromptSubmitInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });++ // when+ const secondOutput = await runUserPromptSubmitHook(userPromptSubmitInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });++ // then+ expect(secondOutput).toBe("");+ });++ it("#given rules retained in compacted replacement #when UserPromptSubmit recovers #then it emits nothing", async () => {+ // given+ const { root, pluginData } = makeProject();+ const firstOutput = await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });+ const transcriptPath = writeCompactedTranscript(root, readAdditionalContext(firstOutput));+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );++ // when+ const output = await runUserPromptSubmitHook(userPromptSubmitInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });++ // then+ expect(output).toBe("");+ });++ it("#given bundled hephaestus rule dropped by compaction #when compact SessionStart recovers #then hephaestus body is re-injected in full alongside the directive", async () => {+ // given+ const { root, pluginData } = makeProject();+ const env = { CODEX_RULES_ENABLED_SOURCES: "CONTEXT.md,plugin-bundled" };+ await runSessionStartHook(sessionStartInput(root), { pluginDataRoot: pluginData, env });+ const transcriptPath = writeCompactedTranscript(root, "summary that dropped every injected rule");+ await runPostCompactHook(+ { ...postCompactInput(root), transcript_path: transcriptPath },+ { pluginDataRoot: pluginData },+ );++ // when+ const output = await runSessionStartHook(compactSessionStartInput(root, transcriptPath), {+ pluginDataRoot: pluginData,+ env,+ });++ // then+ const context = readAdditionalContext(output);+ expect(context).toContain("You are Hephaestus");+ expect(context).not.toContain("[Truncated. Full:");+ expect(context).toContain("MUST READ");+ expect(context).toContain("CONTEXT.md");+ });+});++function makeProject(): { root: string; pluginData: string } {+ const root = mkdtempSync(path.join(tmpdir(), "codex-rules-directive-project-"));+ const pluginData = mkdtempSync(path.join(tmpdir(), "codex-rules-directive-data-"));+ tempDirectories.push(root, pluginData);+ writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));+ writeFileSync(path.join(root, "CONTEXT.md"), `Project rule\n${"A".repeat(8_000)}`);+ mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });+ writeFileSync(+ path.join(root, ".omo", "rules", "typescript.md"),+ ["---", 'globs: "**/*.ts"', "---", "", `TypeScript rule\n${"B".repeat(2_000)}`].join("\n"),+ );+ mkdirSync(path.join(root, "src"), { recursive: true });+ writeFileSync(path.join(root, "src", "app.ts"), "export const app = 1;\n");+ return { root, pluginData };+}++function sessionStartInput(root: string): CodexSessionStartInput {+ return {+ session_id: SESSION_ID,+ transcript_path: null,+ cwd: root,+ hook_event_name: "SessionStart",+ model: "gpt-5.5",+ permission_mode: "default",+ source: "startup",+ };+}++function compactSessionStartInput(root: string, transcriptPath: string): CodexSessionStartInput {+ return {+ session_id: SESSION_ID,+ transcript_path: transcriptPath,+ cwd: root,+ hook_event_name: "SessionStart",+ model: "gpt-5.5",+ permission_mode: "default",+ source: "compact",+ };+}++function postCompactInput(root: string): CodexPostCompactInput {+ return {+ session_id: SESSION_ID,+ turn_id: "turn-compact",+ transcript_path: null,+ cwd: root,+ hook_event_name: "PostCompact",+ model: "gpt-5.5",+ trigger: "auto",+ };+}++function userPromptSubmitInput(root: string, transcriptPath: string): CodexUserPromptSubmitInput {+ return {+ session_id: SESSION_ID,+ turn_id: "turn-after-compact",+ transcript_path: transcriptPath,+ cwd: root,+ hook_event_name: "UserPromptSubmit",+ model: "gpt-5.5",+ permission_mode: "default",+ prompt: "continue",+ };+}++function postToolUseInput(root: string, filePath: string): CodexPostToolUseInput {+ return {+ session_id: SESSION_ID,+ turn_id: "turn-tool",+ transcript_path: null,+ cwd: root,+ hook_event_name: "PostToolUse",+ model: "gpt-5.5",+ permission_mode: "default",+ tool_name: "apply_patch",+ tool_input: { path: filePath },+ tool_response: {},+ tool_use_id: "tool-use-1",+ };+}++function writeCompactedTranscript(root: string, retainedText: string): string {+ const transcriptPath = path.join(root, "transcript-compacted.jsonl");+ writeFileSync(+ transcriptPath,+ `${JSON.stringify({+ type: "compacted",+ payload: {+ message: "summary",+ replacement_history: [{ type: "message", role: "user", content: retainedText }],+ },+ })}\n`,+ );+ return transcriptPath;+}++function readAdditionalContext(output: string): string {+ if (output.trim().length === 0) {+ throw new Error("Expected hook output to include additional context.");+ }+ const parsed: unknown = JSON.parse(output);+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return "";+ const hookSpecificOutput = (parsed as Record<string, unknown>)["hookSpecificOutput"];+ if (typeof hookSpecificOutput !== "object" || hookSpecificOutput === null) return "";+ const additionalContext = (hookSpecificOutput as Record<string, unknown>)["additionalContext"];+ return typeof additionalContext === "string" ? additionalContext : "";+}diff --git a/plugins/omo/components/rules/test/event-budget.test.ts b/plugins/omo/components/rules/test/event-budget.test.tsnew file mode 100644index 00000000..aedd9128--- /dev/null+++ b/plugins/omo/components/rules/test/event-budget.test.ts@@ -0,0 +1,168 @@+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 CodexPostToolUseInput,+ type CodexSessionStartInput,+ type CodexUserPromptSubmitInput,+ runPostToolUseHook,+ runSessionStartHook,+ runUserPromptSubmitHook,+} from "../src/codex-hook.js";++const tempDirectories: string[] = [];+const PROJECT_ONLY_ENV = {+ CODEX_RULES_ENABLED_SOURCES: "CONTEXT.md,.omo/rules",+};++afterEach(() => {+ for (const directory of tempDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++describe("codex rules per-event injection budgets", () => {+ it("#given an oversized glob rule #when PostToolUse injects dynamically #then the block is truncated to the dynamic budget", async () => {+ // given+ const { root, pluginData } = makeProject({ dynamicRuleChars: 30_000 });++ // when+ const output = await runPostToolUseHook(postToolUseInput(root, path.join(root, "src", "app.ts")), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });++ // then+ const context = readAdditionalContext(output);+ expect(context).toContain("[Truncated. Full:");+ expect(context.length).toBeLessThan(11_000);+ });++ it("#given a mid-sized static rule #when SessionStart injects #then the body is not truncated", async () => {+ // given+ const { root, pluginData } = makeProject({ staticRuleChars: 8_000 });++ // when+ const output = await runSessionStartHook(sessionStartInput(root), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });++ // then+ const context = readAdditionalContext(output);+ expect(context).not.toContain("[Truncated. Full:");+ expect(context.length).toBeGreaterThan(8_000);+ });++ it("#given the same mid-sized static rule #when UserPromptSubmit injects on a fresh session #then the body is truncated to the prompt budget", async () => {+ // given+ const { root, pluginData } = makeProject({ staticRuleChars: 8_000 });++ // when+ const output = await runUserPromptSubmitHook(userPromptSubmitInput(root), {+ pluginDataRoot: pluginData,+ env: PROJECT_ONLY_ENV,+ });++ // then+ const context = readAdditionalContext(output);+ expect(context).toContain("[Truncated. Full:");+ expect(context.length).toBeLessThan(7_000);+ });++ it("#given dynamic budget env overrides #when PostToolUse injects #then the override budget wins", async () => {+ // given+ const { root, pluginData } = makeProject({ dynamicRuleChars: 30_000 });++ // when+ const output = await runPostToolUseHook(postToolUseInput(root, path.join(root, "src", "app.ts")), {+ pluginDataRoot: pluginData,+ env: {+ ...PROJECT_ONLY_ENV,+ CODEX_RULES_DYNAMIC_MAX_RULE_CHARS: "1000",+ CODEX_RULES_DYNAMIC_MAX_RESULT_CHARS: "1500",+ },+ });++ // then+ const context = readAdditionalContext(output);+ expect(context).toContain("[Truncated. Full:");+ expect(context.length).toBeLessThan(2_000);+ });+});++function makeProject(sizes: { staticRuleChars?: number; dynamicRuleChars?: number }): {+ root: string;+ pluginData: string;+} {+ const root = mkdtempSync(path.join(tmpdir(), "codex-rules-event-budget-project-"));+ const pluginData = mkdtempSync(path.join(tmpdir(), "codex-rules-event-budget-data-"));+ tempDirectories.push(root, pluginData);+ writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "fixture" }));+ writeFileSync(path.join(root, "CONTEXT.md"), `Project rule\n${"A".repeat(sizes.staticRuleChars ?? 100)}`);+ mkdirSync(path.join(root, ".omo", "rules"), { recursive: true });+ writeFileSync(+ path.join(root, ".omo", "rules", "typescript.md"),+ ["---", 'globs: "**/*.ts"', "---", "", `TypeScript rule\n${"B".repeat(sizes.dynamicRuleChars ?? 100)}`].join(+ "\n",+ ),+ );+ mkdirSync(path.join(root, "src"), { recursive: true });+ writeFileSync(path.join(root, "src", "app.ts"), "export const app = 1;\n");+ return { root, pluginData };+}++function sessionStartInput(root: string): CodexSessionStartInput {+ return {+ session_id: `session-budget-${path.basename(root)}`,+ transcript_path: null,+ cwd: root,+ hook_event_name: "SessionStart",+ model: "gpt-5.5",+ permission_mode: "default",+ source: "startup",+ };+}++function userPromptSubmitInput(root: string): CodexUserPromptSubmitInput {+ return {+ session_id: `session-budget-${path.basename(root)}`,+ turn_id: "turn-1",+ transcript_path: null,+ cwd: root,+ hook_event_name: "UserPromptSubmit",+ model: "gpt-5.5",+ permission_mode: "default",+ prompt: "continue",+ };+}++function postToolUseInput(root: string, filePath: string): CodexPostToolUseInput {+ return {+ session_id: `session-budget-${path.basename(root)}`,+ turn_id: "turn-tool",+ transcript_path: null,+ cwd: root,+ hook_event_name: "PostToolUse",+ model: "gpt-5.5",+ permission_mode: "default",+ tool_name: "apply_patch",+ tool_input: { path: filePath },+ tool_response: {},+ tool_use_id: "tool-use-1",+ };+}++function readAdditionalContext(output: string): string {+ if (output.trim().length === 0) {+ throw new Error("Expected hook output to include additional context.");+ }+ const parsed: unknown = JSON.parse(output);+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return "";+ const hookSpecificOutput = (parsed as Record<string, unknown>)["hookSpecificOutput"];+ if (typeof hookSpecificOutput !== "object" || hookSpecificOutput === null) return "";+ const additionalContext = (hookSpecificOutput as Record<string, unknown>)["additionalContext"];+ return typeof additionalContext === "string" ? additionalContext : "";+}diff --git a/plugins/omo/components/rules/test/formatter.test.ts b/plugins/omo/components/rules/test/formatter.test.tsindex a0227a94..fa748c16 100644--- a/plugins/omo/components/rules/test/formatter.test.ts+++ b/plugins/omo/components/rules/test/formatter.test.ts@@ -145,6 +145,26 @@ describe("rules formatter hook context", () => {expect(block).not.toContain("must read project rules:");});+ it("#given an oversized Hephaestus static rule #when formatting under a tight result budget #then its body is never truncated", () => {+ // given+ const tailMarker = "HEPHAESTUS_TAIL_SENTINEL";+ const rule = loadedRule({+ path: "/repo/bundled-rules/hephaestus.md",+ relativePath: "bundled-rules/hephaestus.md",+ body: `${"H".repeat(500)}\n\n${tailMarker}`,+ });++ // when+ const block = formatStaticBlock([rule], {+ maxRuleChars: 120,+ maxResultChars: 200,+ });++ // then+ expect(block).toContain(tailMarker);+ expect(block).not.toContain("[Truncated. Full:");+ });+it("#given multiple oversized rules #when formatting under a tight result budget #then every rule receives a fair truncated share with a read-full guide", () => {// givenconst rules = [diff --git a/plugins/omo/components/rules/test/post-compact-budget.test.ts b/plugins/omo/components/rules/test/post-compact-budget.test.tsindex d1f5d788..da6b4a2c 100644--- a/plugins/omo/components/rules/test/post-compact-budget.test.ts+++ b/plugins/omo/components/rules/test/post-compact-budget.test.ts@@ -14,6 +14,10 @@ const CONFIG: PiRulesConfig = {maxResultChars: 50_000,postCompactMaxRuleChars: 12_000,postCompactMaxResultChars: 20_000,+ dynamicMaxRuleChars: 4_000,+ dynamicMaxResultChars: 10_000,+ promptMaxRuleChars: 6_000,+ promptMaxResultChars: 16_000,enabledSources: "auto",};diff --git a/plugins/omo/components/rules/test/sparkshell-awareness.test.ts b/plugins/omo/components/rules/test/sparkshell-awareness.test.tsindex b7059a36..4939f25c 100644--- a/plugins/omo/components/rules/test/sparkshell-awareness.test.ts+++ b/plugins/omo/components/rules/test/sparkshell-awareness.test.ts@@ -1,8 +1,8 @@-import { mkdtempSync, rmSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { describe, expect, it } from "vitest";+import { afterAll, describe, expect, it } from "vitest";import { runSessionStartHook, runUserPromptSubmitHook } from "../src/codex-hook.js";import { formatAdditionalContextOutput } from "../src/hook-output.js";@@ -45,13 +45,29 @@ function parseHookOutput(value: unknown): HookOutput {};}+const fixtureRoot = mkdtempSync(join(tmpdir(), "codex-sparkshell-omo-bin-"));+const omoOnPathDir = join(fixtureRoot, "path-bin");+const emptyHomeDir = join(fixtureRoot, "empty-home");+const localBinHomeDir = join(fixtureRoot, "local-bin-home");+mkdirSync(omoOnPathDir, { recursive: true });+mkdirSync(emptyHomeDir, { recursive: true });+mkdirSync(join(localBinHomeDir, ".local", "bin"), { recursive: true });+writeFileSync(join(omoOnPathDir, "omo"), "#!/bin/sh\n");+writeFileSync(join(localBinHomeDir, ".local", "bin", "omo"), "#!/bin/sh\n");+describe("Codex Sparkshell awareness", () => {- it("#given active Codex app server env #when SessionStart runs #then emits Sparkshell guidance", async () => {+ afterAll(() => {+ rmSync(fixtureRoot, { recursive: true, force: true });+ });++ it("#given active Codex app server env with omo on PATH #when SessionStart runs #then emits Sparkshell guidance", async () => {// givenconst env = {CODEX_INTERNAL_ORIGINATOR_OVERRIDE: "Codex Desktop",CODEX_SHELL: "1",CODEX_RULES_ENABLED_SOURCES: ".omo/rules",+ PATH: omoOnPathDir,+ HOME: emptyHomeDir,};// when@@ -70,6 +86,11 @@ describe("Codex Sparkshell awareness", () => {// thenexpect(parseAdditionalContext(output)).toContain("omo sparkshell <command>");+ expect(parseAdditionalContext(output)).toContain("OMO_SPARKSHELL_SESSION_CONTEXT");+ expect(parseAdditionalContext(output)).toContain("OMO_SPARKSHELL_CONDENSE");+ expect(parseAdditionalContext(output)).toContain("OMO_SPARKSHELL_SPARK");+ expect(parseAdditionalContext(output)).toContain("[sparkshell caption]");+ expect(parseAdditionalContext(output)).not.toContain("[REDACTED]");});it("#given inactive env #when SessionStart runs #then emits no Sparkshell guidance", async () => {@@ -102,6 +123,8 @@ describe("Codex Sparkshell awareness", () => {OMO_SPARKSHELL_APP_SERVER_SOCKET: "/tmp/app-server-control.sock",CODEX_THREAD_ID: "thread-sparkshell-cli",CODEX_RULES_ENABLED_SOURCES: ".omo/rules",+ PATH: omoOnPathDir,+ HOME: emptyHomeDir,};// when@@ -122,6 +145,64 @@ describe("Codex Sparkshell awareness", () => {expect(parseAdditionalContext(output)).toContain("omo sparkshell <command>");});+ it("#given active Codex app env without a resolvable omo command #when SessionStart runs #then emits no Sparkshell guidance", async () => {+ // given+ const env = {+ CODEX_INTERNAL_ORIGINATOR_OVERRIDE: "Codex Desktop",+ CODEX_SHELL: "1",+ CODEX_RULES_ENABLED_SOURCES: ".omo/rules",+ PATH: join(fixtureRoot, "missing-path-entry"),+ HOME: emptyHomeDir,+ };++ // when+ const output = await runSessionStartHook(+ {+ session_id: "session-sparkshell-unresolvable",+ transcript_path: null,+ cwd: process.cwd(),+ hook_event_name: "SessionStart",+ model: "gpt-5.5",+ permission_mode: "default",+ source: "startup",+ },+ { env },+ );++ // then+ expect(output).toBe("");+ });++ it("#given omo only under HOME/.local/bin #when SessionStart runs #then emits guidance with the absolute omo path", async () => {+ // given+ const env = {+ CODEX_INTERNAL_ORIGINATOR_OVERRIDE: "Codex Desktop",+ CODEX_SHELL: "1",+ CODEX_RULES_ENABLED_SOURCES: ".omo/rules",+ PATH: join(fixtureRoot, "missing-path-entry"),+ HOME: localBinHomeDir,+ };++ // when+ const output = await runSessionStartHook(+ {+ session_id: "session-sparkshell-local-bin",+ transcript_path: null,+ cwd: process.cwd(),+ hook_event_name: "SessionStart",+ model: "gpt-5.5",+ permission_mode: "default",+ source: "startup",+ },+ { env },+ );++ // then+ const context = parseAdditionalContext(output);+ expect(context).toContain(`${join(localBinHomeDir, ".local", "bin", "omo")} sparkshell <command>`);+ expect(context).not.toContain("`omo sparkshell <command>`");+ });+it("#given explicit force-on env #when SessionStart runs #then emits Sparkshell guidance", async () => {// givenconst env = {@@ -181,6 +262,8 @@ describe("Codex Sparkshell awareness", () => {CODEX_INTERNAL_ORIGINATOR_OVERRIDE: "Codex Desktop",CODEX_SHELL: "1",CODEX_RULES_ENABLED_SOURCES: ".omo/rules",+ PATH: omoOnPathDir,+ HOME: emptyHomeDir,};try {const firstOutput = await runSessionStartHook(diff --git a/plugins/omo/components/start-work-continuation/directive.md b/plugins/omo/components/start-work-continuation/directive.mdindex 904c8bec..3f20e571 100644--- a/plugins/omo/components/start-work-continuation/directive.md+++ b/plugins/omo/components/start-work-continuation/directive.md@@ -1,6 +1,6 @@<start-work-continuation>-You are mid-flight on a Prometheus work plan. The turn just ended without finishing the plan. This is an automatic continuation — keep going. Do NOT ask the user whether to continue; the contract is auto-continue until every top-level checkbox is `- [x]`.+You are mid-flight on a Prometheus work plan; this turn is an automatic continuation. Do NOT ask whether to continue — the contract is auto-continue until every top-level checkbox is `- [x]`.# State@@ -15,23 +15,24 @@ You are mid-flight on a Prometheus work plan. The turn just ended without finish# What to do this turn-1. Read `{{PLAN_PATH}}` AND `{{LEDGER_PATH}}` first — ground truth for what remains and what evidence has already been recorded. The plan checkbox and the ledger are the only sources of truth; do not trust your own memory of prior turns.+1. Read `{{PLAN_PATH}}` AND `{{LEDGER_PATH}}` first — they are the only sources of truth for what remains and what evidence exists; do not trust your memory of prior turns.2. Pick the FIRST unchecked top-level checkbox in `## TODOs` or `## Final Verification Wave`. Ignore nested checkboxes under Acceptance Criteria / Evidence / Definition of Done.3. Follow the `start-work` skill in full. The skill is already loaded from your earlier turn — re-read its file at `packages/omo-codex/plugin/skills/start-work/SKILL.md` if you have lost context.-4. Decompose the checkbox into atomic sub-tasks. Dispatch them in PARALLEL via `spawn_agent` calls in this same response unless a sub-task has a NAMED blocking dependency (input from another sub-task or shared file). Prefer `fork_turns: "none"` unless full history is truly required. Put role and specialty instructions inside `message`; the Codex tool schema only accepts `task_name`, `message`, and `fork_turns`.-5. Every sub-task message MUST be self-contained and start with `TASK: <imperative assignment>`, then name `DELIVERABLE`, `SCOPE`, and `VERIFY`. State that it is an executable assignment, not a context handoff. It must include all 7 sections and name one Manual-QA channel with its exact tool and exact invocation (the literal `curl` / `send-keys` / `page.click` with concrete inputs and the binary PASS/FAIL observable), plus the applicable ultraqa adversarial classes, a captured artifact, and a cleanup receipt. Channels: HTTP call (`curl -i`); tmux (`send-keys` + `capture-pane`); browser use — use Chrome to drive the page, else download and use agent-browser (https://github.com/vercel-labs/agent-browser); computer use — OS-level GUI automation for a desktop app. Tests are the floor; the channel artifact plus probed adversarial classes are the ceiling. All are required.-6. Treat every worker DoneClaim as untrusted input. Run independent AdversarialVerify before any checkbox can become FullyDone; `confirmed` is the only pass verdict, while `false-positive`, `needs-fix`, and `needs-human-review` loop back to the executor with exact feedback.-7. Use `wait_agent` for mailbox signals, not proof of completion. For sub-tasks likely to exceed one wait cycle, require `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A timeout only means no new mailbox update arrived; after a timeout, run a single `list_agents` check for the named child when you need reassurance. If it is running or its latest message is `WORKING:`, treat it as alive. Do not use `list_agents` as a polling loop. Send `TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>` only when the child is completed without the deliverable, ack-only, or no longer running. If that followup is still silent or ack-only, record inconclusive, do not count it as pass/review approval, close if safe, and respawn a smaller `fork_turns: "none"` task with the missing deliverable.-8. After verification of ALL sub-tasks under this checkbox: `apply_patch` the plan to change `- [ ]` → `- [x]`, re-read the plan to confirm the count decreased, append a `task-completed` line to the ledger, then continue.-9. Do not start fresh on a sub-agent failure. Re-dispatch the same `task_name` with a fix-message: `FAILED: <exact error>` + `Diagnosis: <observation>` + `Fix: <instruction>`.+4. Apply the checkbox's tier from its ledger entry, or classify it now per the start-work skill: LIGHT (default — a narrow change inside existing layers) needs one real-surface proof of the deliverable, with auxiliary surfaces first-class for CLI- or data-shaped work, and only trigger-mapped adversarial classes; HEAVY (new module/abstraction, auth/security, external integration, schema/migration, concurrency, cross-domain refactor, care signals) takes the full per-criterion regime. When unsure, take HEAVY; never downgrade.+5. Decompose the checkbox into atomic sub-tasks. Dispatch them in PARALLEL via `multi_agent_v1.spawn_agent` calls in this same response unless a sub-task has a NAMED blocking dependency (input from another sub-task or shared file). Use `fork_context: false` unless full history is truly required. Put role and specialty instructions inside `message`.+6. Every sub-task message MUST be self-contained, an executable assignment rather than a context handoff: start with `TASK: <imperative assignment>`, then name `DELIVERABLE`, `SCOPE`, and `VERIFY`. It must include all 7 sections and name one Manual-QA channel with its exact tool and exact invocation (the literal `curl` / `send-keys` / `page.click` with concrete inputs and the binary PASS/FAIL observable), plus the applicable ultraqa adversarial classes, a captured artifact, and a cleanup receipt. Channels: HTTP call (`curl -i`); tmux (`send-keys` + `capture-pane`); browser use — use Chrome to drive the page, else download and use agent-browser (https://github.com/vercel-labs/agent-browser); computer use — OS-level GUI automation for a desktop app.+7. Treat every worker DoneClaim as untrusted input. Run independent AdversarialVerify before any checkbox can become FullyDone; `confirmed` is the only pass verdict, while `false-positive`, `needs-fix`, and `needs-human-review` loop back to the executor with exact feedback.+8. Use `multi_agent_v1.wait_agent` for mailbox signals, not proof of completion — a timeout only means no new mailbox update arrived; a running child is alive. For sub-tasks likely to exceed one wait cycle, require `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. Send `TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>` only when the child is completed without the deliverable, ack-only, or no longer running. If that followup is still silent or ack-only, record inconclusive, do not count it as pass/review approval, close if safe, and respawn a smaller `fork_context: false` task with the missing deliverable.+9. After verification of ALL sub-tasks under this checkbox: `apply_patch` the plan to change `- [ ]` → `- [x]`, re-read the plan to confirm the count decreased, append a `task-completed` line to the ledger, then continue.+10. Do not start fresh on a sub-agent failure. Re-dispatch with a fix-message: `FAILED: <exact error>` + `Diagnosis: <observation>` + `Fix: <instruction>`.# Hard constraints-- No production code before a failing test exists. When the change touches existing behavior, PIN it first: write a baseline characterization test that passes on the unchanged code, with exact inputs, exact observable, and exact assertion. PIN → RED → GREEN → SURFACE.+- No production code before a failing-first proof exists: a unit test at a seam, otherwise the sub-task's Manual-QA scenario captured failing. A test that mirrors its implementation (mock-call assertions, pinned constants) is not evidence. When the change touches existing behavior, PIN it first: a baseline characterization test that passes on the unchanged code, with exact inputs, exact observable, and exact assertion. PIN → RED → GREEN → SURFACE.- No `--dry-run` as evidence. No "should work". No "tests pass" as completion proof.- No `as any` / `@ts-ignore` / `@ts-expect-error`. No deleting failing tests.-- Probe every applicable ultraqa adversarial class (malformed input, prompt injection, cancel/resume, stale state, dirty worktree, hung or long commands, flaky tests, misleading success output, repeated interruptions) and capture the observable for each. A clean happy-path artifact alone is NOT a PASS when an applicable class went unprobed; record skipped classes with a one-line not-applicable reason.-- Cleanup receipt is mandatory. Register each QA resource teardown (scripts, tmux assets, browser / agent-browser sessions, PIDs, ports, containers, temp dirs) as its own todo the moment it spawns, then execute it. Leftover PIDs / `tmux` sessions / browser contexts / bound ports / containers / temp dirs = BLOCKED, not PASS.+- Probe every ultraqa adversarial class whose trigger fact holds (malformed input, prompt injection, cancel/resume, stale state, dirty worktree, hung or long commands, flaky tests, misleading success output, repeated interruptions — trigger map in the start-work skill) and capture the observable for each. A clean happy-path artifact alone is NOT a PASS when an applicable class went unprobed; record skipped classes with a one-line not-applicable reason.+- Cleanup receipt is mandatory. Register each QA resource teardown (scripts, tmux sessions, browser contexts, PIDs, ports, containers, temp dirs) as its own todo the moment it spawns, then execute it. Leftover QA state = BLOCKED, not PASS.- The worktree path (if set in boulder.json) governs every file edit and command. Do not stray into the main repo.- session_ids you write to boulder.json MUST be prefixed `codex:`. Bare ids on read are legacy `opencode:`.@@ -44,15 +45,14 @@ Do not print `ORCHESTRATION COMPLETE`. Do not create a PR, PR handoff, or branch# Stop conditions for THIS turn- A top-level checkbox flipped to `- [x]` after the 5-phase QA gate (Phase 1 read, Phase 2 automated, Phase 3 channel scenario, Phase 4 adversarial-class probing, Phase 5 gate decision). Then the Stop hook will re-evaluate; if more checkboxes remain you will be continued again.-- 3 same-failure cycles on one sub-task → escalate via `spawn_agent({"task_name":"failure_escalation_review","message":"TASK: act as a rigorous reviewer. DELIVERABLE: diagnose the repeated sub-task failure and recommend the next safe action. VERIFY: cite the failing evidence.","fork_turns":"none"})` and stop dispatch.+- 3 same-failure cycles on one sub-task → escalate via `multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous reviewer. DELIVERABLE: diagnose the repeated sub-task failure and recommend the next safe action. VERIFY: cite the failing evidence.","fork_context":false})` and stop dispatch.- Safety boundary (destructive command, secret exfiltration, production write) → stop and surface a safe substitute.- All top-level checkboxes `- [x]` AND the Global Review and Debugging Gate passed → print the ORCHESTRATION COMPLETE block and end.# Output discipline-- Surface only state changes: sub-agent dispatched, channel scenario PASS/FAIL with artifact path, checkbox marked, evidence appended to ledger.-- Do NOT print "Should I continue?" — the Stop hook handles continuation.-- Do NOT restate the full plan. Do NOT recap prior turns. The ledger and the plan file are the durable record.+- Surface only state changes: sub-agent dispatched, scenario PASS/FAIL with artifact path, checkbox marked, evidence appended.+- Do NOT print "Should I continue?", restate the plan, or recap prior turns — the Stop hook continues you; the ledger and plan are the durable record.Begin now. Pick the next checkbox, dispatch the parallel sub-agents, verify, mark, continue.diff --git a/plugins/omo/components/start-work-continuation/hooks/hooks.json b/plugins/omo/components/start-work-continuation/hooks/hooks.jsonindex 19228def..644d9256 100644--- a/plugins/omo/components/start-work-continuation/hooks/hooks.json+++ b/plugins/omo/components/start-work-continuation/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Checking Start-Work Continuation"+ "statusMessage": "LazyCodex(4.9.0): Checking Start-Work Continuation"}]}@@ -19,7 +19,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook subagent-stop","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Checking Start-Work Continuation"+ "statusMessage": "LazyCodex(4.9.0): Checking Start-Work Continuation"}]}diff --git a/plugins/omo/components/start-work-continuation/package.json b/plugins/omo/components/start-work-continuation/package.jsonindex 251463ba..ca8bd12e 100644--- a/plugins/omo/components/start-work-continuation/package.json+++ b/plugins/omo/components/start-work-continuation/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-start-work-continuation",- "version": "0.1.0",+ "version": "4.9.0","description": "Codex Stop hook continuation injector for omo-codex start-work plans.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/start-work-continuation/test/codex-hook.test.ts b/plugins/omo/components/start-work-continuation/test/codex-hook.test.tsindex cba100bd..a66145ef 100644--- a/plugins/omo/components/start-work-continuation/test/codex-hook.test.ts+++ b/plugins/omo/components/start-work-continuation/test/codex-hook.test.ts@@ -112,12 +112,34 @@ describe("start-work Stop hook", () => {// thenconst parsed = parseBlockOutput(output);expect(parsed.reason).toMatch(/TASK:/);- expect(parsed.reason).toMatch(/fork_turns:\s*"none"/);+ expect(parsed.reason).toMatch(/fork_context:\s*false/);expect(parsed.reason).toMatch(/wait_agent.*mailbox signals/);expect(parsed.reason).toMatch(/TASK STILL ACTIVE/);expect(parsed.reason).toMatch(/respawn.*smaller/);expect(parsed.reason).toMatch(/WORKING:/);- expect(parsed.reason).toMatch(/single `list_agents`/);+ });++ it("#given active codex work #when continuation directive is emitted #then QA weight is tier-scoped without echo bloat", () => {+ // given+ const fs = createMemoryFs({+ [BOULDER_PATH]: createBoulderJson({+ sessionIds: ["codex:sess_abc"],+ status: "active",+ }),+ [PLAN_PATH]: ["# Plan", "", "## TODOs", "- [ ] First"].join("\n"),+ });++ // when+ const output = runStopHook(createStopInput(), fs);++ // then+ const parsed = parseBlockOutput(output);+ expect(parsed.reason).toMatch(/LIGHT/);+ expect(parsed.reason).toMatch(/HEAVY/);+ expect(parsed.reason).toMatch(/When unsure[^.]{0,30}HEAVY/);+ expect(parsed.reason).toMatch(/mirrors its implementation/);+ expect((parsed.reason.match(/malformed input, prompt injection/g) ?? []).length).toBe(1);+ expect(parsed.reason.split(/\s+/).filter(Boolean).length).toBeLessThanOrEqual(1100);});it("#given active work belongs to another harness #when hook runs #then returns empty output", () => {diff --git a/plugins/omo/components/telemetry/hooks/hooks.json b/plugins/omo/components/telemetry/hooks/hooks.jsonindex 3916d335..2bef525c 100644--- a/plugins/omo/components/telemetry/hooks/hooks.json+++ b/plugins/omo/components/telemetry/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Recording Session Telemetry"+ "statusMessage": "LazyCodex(4.9.0): Recording Session Telemetry"}]}diff --git a/plugins/omo/components/telemetry/package.json b/plugins/omo/components/telemetry/package.jsonindex 27f9e724..78872f7d 100644--- a/plugins/omo/components/telemetry/package.json+++ b/plugins/omo/components/telemetry/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-telemetry",- "version": "0.1.0",+ "version": "4.9.0","description": "Codex plugin component that emits omo-codex anonymous daily-active telemetry on SessionStart.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/ultrawork/agents/explorer.toml b/plugins/omo/components/ultrawork/agents/explorer.tomlindex 303b7f69..e958bfa6 100644--- a/plugins/omo/components/ultrawork/agents/explorer.toml+++ b/plugins/omo/components/ultrawork/agents/explorer.toml@@ -13,7 +13,7 @@ Answer the orchestrator's "Where is X?" / "Which files do Y?" / "Find code that# 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.+- AVOID me when: the caller already knows the exact file or symbol, or a single keyword search suffices. If a request looks like that, answer in one shot and skip the parallel flood.# ThoroughnessThe caller MAY specify thoroughness. Honor it:@@ -56,7 +56,10 @@ If asked "where is auth?", explain the auth flow you found.]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+# 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.++# Success criteria (the response is INVALID if any is unmet)- 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.@@ -69,15 +72,4 @@ Fire 3+ independent calls in the first action. Cross-validate findings across mu- 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.tomlindex 422ef00d..78a5f5fd 100644--- a/plugins/omo/components/ultrawork/agents/librarian.toml+++ b/plugins/omo/components/ultrawork/agents/librarian.toml@@ -8,108 +8,55 @@ 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.+You are THE LIBRARIAN, a read-only researcher for external libraries, OSS projects, and vendor APIs. Every code claim you make carries a SHA-pinned GitHub permalink, 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 `context7` 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.-- `grep_app` for broad GitHub code search; fall back to `gh search code "<usage pattern>" --language <lang>`.--## 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.-- `grep_app` broad code search or `gh search code "<function-name>" --repo <owner>/<repo>`.-- `gh api repos/<owner>/<repo>/commits/HEAD --jq '.sha'`.-- `context7` or 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>`.+- USE me when: the question concerns an unfamiliar package, a 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 one page summarized (use a direct webfetch instead).++# Date awareness+Check the current date from the environment before any search; never query with last year's date. Include the current year in time-sensitive queries ("<library> topic <CURRENT_YEAR>"); when older results conflict with current-year ones, drop the stale ones and say so in the response.++# Classify first (state the type in one line before investigating)+- TYPE A - CONCEPTUAL: "How do I use X?" / "Best practice for Y?" -> doc discovery, then docs + lightweight code search.+- TYPE B - IMPLEMENTATION: "How does X implement Y?" / "Show me the 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, then all of the above in parallel.++# Doc discovery (before TYPE A and TYPE D; skip for TYPE B and TYPE C)+1. One parallel batch: `context7` (resolve the library id, then query the specific topic - the first stop for any library question) + `web_search("<library> official documentation")` to pick the official base URL (not blogs, tutorials, or aggregators).+2. If the user names a version ("React 18", "v2.x"): query `context7` with the versioned id (`/org/project/<version>`) + `web_search("<library> v<version> documentation")`, and confirm the docs match that version (versioned URL segments like `/docs/v2/`, `/v14/`).+3. `webfetch` the specific doc pages surfaced by step 1. Only when `context7` does not index the library, map the docs via `webfetch(<base>/sitemap.xml)` (fallbacks: `/sitemap-0.xml`, `/sitemap_index.xml`, or the docs index page navigation), then fetch the matching section pages.++If the library has no official docs at all (rare), note that in the response and work from source.++# Execute by type+Run independent calls as one parallel batch, and vary the angle per call - the same query twice wastes budget (good: `gh search code "useQuery("`, then `"queryOptions"`, then `"staleTime:"`; bad: `"useQuery"` twice).++## TYPE A (3-4 parallel calls after doc discovery)+- `context7` follow-up on the specific API surface (the first stop for any library question).+- `web_search` for current-year usage examples and best practices.+- `grep_app` for real-world usage on GitHub; `gh search code "<pattern>" --language <lang>` when you need repo/path/language filters.+- `webfetch` the targeted doc pages from doc discovery.++## TYPE B (sequence, with parallel acceleration)+1. Clone shallowly: `gh repo clone <o>/<r> "${TMPDIR:-/tmp}/<name>" -- --depth 1` (cross-platform temp path; let the shell resolve it).+2. Pin the SHA: `git rev-parse HEAD` in the clone.+3. Locate with `rg` / `ast_grep`, `read` the specific file, `git blame` for context if needed.+4. Build permalinks against the pinned SHA.+Accelerate with one batch of 4+ calls: the clone + `grep_app` or `gh search code "<symbol>" --repo <o>/<r>` + `gh api repos/<o>/<r>/commits/HEAD --jq .sha` + a `context7` or targeted docs fetch of the same API surface.++## TYPE C (4+ parallel calls)+- `gh search issues "<keyword>" --repo <o>/<r> --state all --limit 10` and `gh search prs "<keyword>" --repo <o>/<r> --state merged --limit 10`.+- Clone with more depth (`-- --depth 50`), then `git log --oneline -n 20 -- <path>`, `git blame -L <a>,<b> <path>`, and `git show` as needed.- `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.-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: `grep_app` or `gh search code` with varied queries (different angles).-- 1 source clone for deep inspection.-- 1 issues/PRs query for context.-----+## TYPE D (6+ parallel calls after doc discovery)+2 docs calls (`context7` topic query + targeted `webfetch`) + 2 code-search calls (`grep_app` / `gh search code`, different angles) + 1 source clone + 1 issues/PRs query.-# PHASE 2 - EVIDENCE SYNTHESIS--## Mandatory citation format-Every code claim MUST follow this block:+# Evidence synthesis+Every code claim MUST use this block (repeat per claim):````markdown**Claim**: [what you're asserting]@@ -117,106 +64,35 @@ Every code claim MUST follow this block:**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>")`.-- Docs index -> `context7` when available; use sitemap-driven pages when it is not.-- Code search (fast, broad) -> `grep_app` for web-scale GitHub search; `gh search code "<query>" --language <lang>` when you need GitHub CLI filters.-- Code search (deep, repo-scoped) -> after cloning, `rg` / `ast_grep` 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+End the response with one line: `Open questions: none` or `Open questions: <list>`.-| 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 |+Permalink format: `https://github.com/<owner>/<repo>/blob/<commit-sha>/<filepath>#L<start>-L<end>`+(e.g. `https://github.com/tanstack/query/blob/abc123def/packages/react-query/src/useQuery.ts#L42-L50`).+Get the SHA from the clone (`git rev-parse HEAD`), the API (`gh api repos/<o>/<r>/commits/HEAD --jq .sha`), or a 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.-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}`.+# Failure recovery+- `context7` library-id lookup returns nothing -> sitemap-driven `webfetch` of the official docs; if docs are thin, clone and read source + README.+- `gh search code` returns nothing -> broaden, search the concept instead of the exact symbol, or try forks and mirrors.+- `gh` rate-limited -> fall back to the clone 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.+- Versioned docs missing -> fall back to the latest version and say so explicitly.- 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+- Genuinely uncertain -> state the uncertainty and propose a hypothesis the caller can verify; never fabricate a confident answer.+# Constraints- READ-ONLY. Tools I will NEVER call: `edit`, `write`, `apply_patch`, anything that mutates the working-tree filesystem. 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+- Short quotes only (under 20 words) inside quotation marks; never reproduce long copyrighted passages.-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.+# Communication+- No tool names in prose (say "search GitHub", not "use `gh search code`"). No preamble - answer directly.+- ALWAYS cite every code claim with a SHA-pinned permalink.+- Markdown; fence code blocks with a language identifier.+- Facts over opinions, evidence over speculation; state uncertainty when present."""diff --git a/plugins/omo/components/ultrawork/agents/plan.toml b/plugins/omo/components/ultrawork/agents/plan.tomlindex fd681b93..1abb693e 100644--- a/plugins/omo/components/ultrawork/agents/plan.toml+++ b/plugins/omo/components/ultrawork/agents/plan.toml@@ -29,7 +29,7 @@ Never plan blind. Fire parallel research BEFORE drafting:- 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 a self-contained `TASK: <question to answer now>`, the minimal context you have, `DELIVERABLE`, and what decision the answer informs.-- Prefer `fork_turns: "none"` for research subagents unless full history is truly required. For work likely to exceed one wait cycle, require `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. Use `wait_agent` for mailbox signals, not proof. A timeout only means no new mailbox update arrived; after a timeout, run a single `list_agents` check for the named child when you need reassurance. If it is running or its latest message is `WORKING:`, treat it as alive. Do not use `list_agents` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running; then mark that lane inconclusive and answer from direct evidence or respawn smaller.+- Use `fork_context: false` for research subagents unless full history is truly required. For work likely to exceed one wait cycle, require `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. Use `multi_agent_v1.wait_agent` for mailbox signals, not proof. A timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running; then mark that lane inconclusive and answer from direct evidence or respawn smaller.Wait for context to converge before drafting. Rushed plans fail.diff --git a/plugins/omo/components/ultrawork/directive.md b/plugins/omo/components/ultrawork/directive.mdindex d4af6bab..a29ed77b 100644--- a/plugins/omo/components/ultrawork/directive.md+++ b/plugins/omo/components/ultrawork/directive.md@@ -11,19 +11,40 @@ narration.# GoalDeliver 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.+captured evidence: a failing-first proof that went RED→GREEN through+the cheapest faithful channel, plus real-surface proof sized by the+tier below. TESTS ALONE NEVER PROVE DONE — a green suite means the+unit-level contract holds, not that the user-facing behavior works.++# Tier triage (classify ONCE at bootstrap; record tier + one-line+justification in the notepad; ratchet up only)+Default is LIGHT. Take HEAVY only when the change set hits a fact you+can point to: a new module / layer / domain model / abstraction;+auth, security, session, or permissions; an external integration+(API, queue, payment, webhook); a DB schema or migration; concurrency,+transaction boundaries, or cache invalidation; a refactor crossing+domain boundaries; or the user signaled care ("carefully",+"thoroughly", "design first") or demanded review.+When unsure, take HEAVY. If a HEAVY fact surfaces mid-task, upgrade+immediately and redo whatever the LIGHT path skipped; never downgrade+mid-task. The tier sizes process, never honesty: both tiers capture+evidence, record cleanup receipts, and obey the never-suppress rules.++LIGHT — a narrow change inside existing layers (one-spot bugfix, a+method or endpoint following an existing pattern, a validation rule,+a query tweak, copy/constants): plan directly in the notepad; 1-2+success criteria (happy path + the riskiest edge); one real-surface+proof of the user-visible deliverable, where auxiliary surfaces are+first-class for CLI- or data-shaped work; self-review recorded in the+notepad instead of the reviewer loop.+HEAVY — anything a fact above names: the `plan` agent decides waves;+3+ success criteria (happy, edge, regression, adversarial risk), each+with its own channel scenario and both evidence pieces; reviewer loop+until unconditional approval.++# Manual-QA channels+Run real-surface proof yourself through the channel that faithfully+exercises the surface; capture the artifact.1. HTTP call — hit the live endpoint with `curl -i` (or aPlaywright APIRequestContext); capture status line + headers +@@ -49,53 +70,41 @@ observable that decides PASS vs FAIL. "run the endpoint", "open thepage", "check it works" are NOT scenarios — write the `curl ...`, the`send-keys ...`, the `page.click(...)`, the expected status/text.-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.+Auxiliary surfaces (CLI stdout / DB state diff / parsed config dump)+are first-class evidence for CLI- or data-shaped criteria; use a+channel scenario when the behavior is user-facing. `--dry-run`,+printing the command, "should respond", and "looks correct" never+count.# Bootstrap (DO ALL FOUR BEFORE ANY OTHER WORK — NO SKIPPING)## 0. Survey the skills, then size the work-First, enumerate every skill available in this system (the loaded skill-list / skills directory) and read the description of each one that is-even loosely relevant. Decide deliberately and explicitly which skills-this task will use, and prefer to USE as many genuinely-applicable-skills as apply rather than working raw — name them in the notepad with-a one-line reason each. Skipping a skill that fits the task is a defect.-Then size the scope: count the distinct surfaces, files, and steps. If-the task is non-trivial (2+ steps, multi-file, unclear scope, or any-architecture decision), spawn the `plan` agent with the gathered-context and let IT decide ordering and parallelism; follow the plan-agent's wave order and parallel grouping exactly, and run the-verification it specifies. Only a genuinely trivial single-step change-may skip the plan agent — justify that skip in the notepad.+First, survey the loaded skill list and read the description of each+loosely relevant skill. Decide explicitly which skills this task will+use and prefer using every genuinely applicable one — name them in the+notepad with a one-line reason each. Skipping a skill that fits the+task is a defect.+Then run Tier triage (above) on the change set and record the tier.+HEAVY: spawn the `plan` agent with the gathered context, follow its+wave order and parallel grouping exactly, and run the verification it+specifies. LIGHT: plan directly in the notepad.## 1. Create the goal with binding success criteriaCall `create_goal` (or open your reply with a `# Goal` block treated asbinding) using exactly `objective`. Do not include `status`. Goals areunlimited; 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.+- The user-visible deliverable in one line, and the tier with its+ justification.+- Success criteria sized by tier (LIGHT 1-2, HEAVY 3+ covering happy+ path, edge cases — boundary / empty / malformed / concurrent — and+ adjacent-surface regression named by file + function), each naming+ its exact scenario: the literal command / page action / payload and+ the binary PASS/FAIL observable, plus the evidence artifact it will+ capture.+- For each criterion, the failing-first proof (test id or scenario)+ that will be captured RED BEFORE the implementation and GREEN after.+ Evidence added after the green code does NOT satisfy this.These scenarios are the contract. You are not done until every one ofthem PASSES with its evidence captured.@@ -128,9 +137,8 @@ Started: <ISO timestamp><patterns / pitfalls / principles to remember next turn>```-Append to the notepad after EVERY atomic action, not only on status-changes: each finding, decision, command run, RED/GREEN capture, and QA-artifact path goes in the moment it happens. Update `## Now` and+Append each finding, decision, command, RED/GREEN capture, and QA+artifact path the moment it happens. Update `## Now` and`## Todo` on every transition. Append-only — never rewrite. This notepadis your durable memory and it OUTLIVES the context window. After anycompaction or context loss (a `Context compacted` notice, a summarized@@ -143,10 +151,9 @@ steps.## 3. Register obsessive todos via `update_plan`The todo tool is Codex `update_plan` — your live, user-visiblechecklist. Translate every action from the plan into one `update_plan`-step. 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 step. Keep-steps atomic and ultra-granular: prefer many tiny steps over a few-coarse ones; if a step needs more than one tool call, split it.+step — one step per atomic work unit: an edit plus its verification, a+QA scenario run, a teardown. Keep each step small enough to finish+within a few tool calls.Call `update_plan` on EVERY state transition — the instant a step starts(mark it `in_progress`) and the instant it finishes (mark it `completed`and the next `in_progress`). Exactly ONE `in_progress` at a time. Mark@@ -183,34 +190,36 @@ When discovery needs multiple angles or the module layout isunfamiliar, delegate to the `explorer` subagent (read-only codebasesearch, absolute-path results). For research that leaves the repo —library/API/docs/web — delegate to the `librarian` subagent. Spawn them-`fork_turns: "none"` and keep doing root work while they run.+`fork_context: false` and keep doing root work while they run.-# Execution loop (strict TDD — RED → GREEN → SURFACE → CLEAN)-Until every success-criteria scenario PASSES with BOTH evidence pieces:+# Execution loop (PIN → RED → GREEN → SURFACE → CLEAN)+Until every success criterion PASSES with its evidence captured: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.+2. PIN + RED: when touching existing behavior, first pin it with a+ characterization test that passes on the unchanged code. Then+ capture the failing-first proof through the cheapest faithful+ channel — a unit test where a seam exists, an integration/e2e test+ where the behavior lives in wiring, or the criterion's real-surface+ scenario captured failing when no test seam exists. It must fail+ 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.Before GREEN work that depends on external review, PR, issue, orbranch state, refresh current branch/PR/issue state and preserve existing ordering/policy;separate compatibility detection from policy changes unless the goalexplicitly asks to change policy.- 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.+ Re-run the proof. Capture GREEN output. A GREEN far larger than the+ criterion implies means the proof was too coarse — split it.+4. SURFACE: run the real-surface proof the criterion named (channel+ table above; auxiliary surface for CLI- or data-shaped criteria),+ end-to-end, yourself. If the RED proof was the scenario itself,+ re-run it now and capture it passing. Paste the artifact path into+ the notepad.5. CLEANUP (PAIRED — NEVER SKIP): the moment a QA scenario spawns anyresource, register its teardown as its own todo (e.g.- `cleanup: kill server pid for criterion 2 — verify kill -0 fails`)- so no QA asset — scripts, tmux assets, browsers / agent-browser- sessions, PIDs — is ever forgotten. Every runtime artifact the QA- spawned in step 4 MUST be torn down before this step completes:+ `cleanup: kill server pid for criterion 2 — verify kill -0 fails`).+ 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@@ -222,26 +231,26 @@ Until every success-criteria scenario PASSES with BOTH evidence pieces:6. Verify: LSP diagnostics clean on changed files + full test suitegreen (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.+8. After each increment, re-run every criterion's scenario. Record+ PASS/FAIL inline with the 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.# Codex subagent reliability-Every `spawn_agent` message is self-contained and starts with+Every `multi_agent_v1.spawn_agent` message is self-contained and starts with`TASK: <imperative assignment>`, then names `DELIVERABLE`, `SCOPE`, and`VERIFY`. State that it is an executable assignment, not a context-handoff. Prefer `fork_turns: "none"` unless full history is truly+handoff. Use `fork_context: false` unless full history is trulyrequired; paste only the context the child needs. Full-history forks canmake the child continue old parent context instead of the delegated task.# TOML-backed subagent routing compatibility-Treat TOML-backed role routing as **routing-unverified**. The available-`spawn_agent` schema accepts only `task_name`, `message`, and-`fork_turns`; it cannot select a TOML-backed role, model, reasoning-effort, or `service_tier`. Say so briefly in the notepad, paste the+Treat TOML-backed role routing as **routing-unverified**. The+`multi_agent_v1.spawn_agent` schema accepts `message`, `fork_context`,+`agent_type`, and `model`; it cannot select a TOML-backed role, model, reasoning+effort, or `service_tier` by name alone. Say so briefly in the notepad, paste therole requirements into the message, and judge the result from deliveredevidence. Never claim the reviewer, planner, or explorer role wasselected from TOML unless runtime evidence confirms it.@@ -250,18 +259,14 @@ Treat child status as a progress signal, not a timeout counter. Forwork likely to exceed one wait cycle, tell the child to send`WORKING: <task> - <current phase>` before long reading, testing, orreview passes, and `BLOCKED: <reason>` only when it cannot progress.-Track spawned agent names locally. Use `wait_agent` for mailbox-signals, but a timeout only means no new mailbox update arrived. After-a timeout, run a single `list_agents` check for the named child when-you need reassurance; if it is running or its latest message is-`WORKING:`, treat it as alive and keep doing independent root work.-Do not use `list_agents` as a polling loop or status feed; it can-replay large payloads. Send `TASK STILL ACTIVE: return <deliverable> or-BLOCKED: <reason>` only when the child is completed without the+Track spawned agent names locally. Use `multi_agent_v1.wait_agent` for mailbox+signals, but a timeout only means no new mailbox update arrived.+Treat a running child as alive and keep doing independent root work.+Fallback only when the child is completed without thedeliverable, ack-only, or no longer running. If that followup is stillsilent or ack-only, record the result as inconclusive, do not count itas approval/pass, close it if safe, and respawn a smaller-`fork_turns: "none"` task with the missing deliverable.+`fork_context: false` task with the missing deliverable.# Subagent-dependent transition barrierDo not mark an `update_plan` step `completed` while an active child owns@@ -270,7 +275,7 @@ audit, research, or review result is integrated or explicitly recordedas inconclusive. Do not generate a plan before spawned research lanesthat feed the plan have returned or been closed as inconclusive.Do not write the final answer, PR handoff, or completion summary while-active child agents remain open. Use short `wait_agent` cycles.+active child agents remain open. Use short `multi_agent_v1.wait_agent` cycles.After two silent waits send `TASK STILL ACTIVE: return <deliverable> orBLOCKED: <reason>`. After four silent or ack-only checks, close the lane asinconclusive, record that it is not approval, and respawn smaller only@@ -279,14 +284,15 @@ if the deliverable is still required.# Verification gate (TRIGGERED, NOT OPTIONAL)Trigger when ANY apply:+- Tier is HEAVY.- User demanded strict, rigorous, or proper 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 deep.+LIGHT tier records a self-review in the notepad instead: re-read the+diff, run diagnostics, confirm each criterion's evidence, and state in+one line why the tier held.Procedure (NON-NEGOTIABLE):-1. Spawn a child with `fork_turns: "none"` and a self-contained reviewer- assignment in `message`. The `spawn_agent` schema cannot select a+1. Spawn a child with `fork_context: false` and a self-contained reviewer+ assignment in `message`. The `multi_agent_v1.spawn_agent` schema cannot select aTOML-backed reviewer role, so paste the reviewer requirements intothe message.Pass: goal, success-criteria, scenario evidence, full diff, notepad@@ -311,23 +317,23 @@ requested or preauthorised this session — default is stage + draftmessage + 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.+- Every behavior change needs a failing-first proof captured BEFORE+ the production change, through the cheapest faithful channel (unit+ test at a seam; integration/e2e in wiring; the real-surface scenario+ when no test seam exists). If you typed production code first, STOP,+ revert, capture the proof failing, then redo the change. Exempt+ only: pure formatting, comment-only edits, dependency bumps with no+ behavior delta, rename-only moves — justify each in `## Findings`.+- A test that mirrors its implementation — asserting mocks were+ called, pinning a constant, or unable to fail under any plausible+ regression — is NOT evidence. Prefer a real-surface proof with no+ new test over a tautological test.+- Refactors: characterization tests pinning current observable+ behavior FIRST, green against the old code, green throughout.- 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.+- Never claim done from inference — only from captured evidence.- Parallel tool calls for any independent work.# Output discipline@@ -343,10 +349,9 @@ message + present for approval.- Stop ONLY when every scenario PASSES with captured evidence, everycleanup receipt is recorded, notepad is current, and (if gatetriggered) 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.+- Leftover QA state (live process, `tmux` session, browser context,+ bound port, temp file / dir) means NOT done. Tear it down, record+ the receipt, then continue.- After 2 identical failed attempts at one step, surface what was triedand ask the user before another retry.- After 2 parallel exploration waves yield no new useful facts, stopdiff --git a/plugins/omo/components/ultrawork/hooks/hooks.json b/plugins/omo/components/ultrawork/hooks/hooks.jsonindex 0ca86fa0..05afa62a 100644--- a/plugins/omo/components/ultrawork/hooks/hooks.json+++ b/plugins/omo/components/ultrawork/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Checking Ultrawork Trigger"+ "statusMessage": "LazyCodex(4.9.0): Checking Ultrawork Trigger"}]}diff --git a/plugins/omo/components/ultrawork/package.json b/plugins/omo/components/ultrawork/package.jsonindex a122bee1..5308c0d3 100644--- a/plugins/omo/components/ultrawork/package.json+++ b/plugins/omo/components/ultrawork/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-ultrawork",- "version": "0.1.0",+ "version": "4.9.0","description": "Codex plugin that injects the ultrawork orchestration directive and syncs the ultrawork reviewer agent role.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/ultrawork/skills/ulw-plan/SKILL.md b/plugins/omo/components/ultrawork/skills/ulw-plan/SKILL.mdindex 40f3e6c0..cbb6cae9 100644--- a/plugins/omo/components/ultrawork/skills/ulw-plan/SKILL.md+++ b/plugins/omo/components/ultrawork/skills/ulw-plan/SKILL.md@@ -14,7 +14,7 @@ This skill is intentionally compact. The full planning workflow lives in `refere## Required First Steps1. Open `references/full-workflow.md`.-2. Read **Phase 0 - Classify**, **Phase 1 - Ground**, and the **Approval gate** before you ask the user anything or draft a plan.+2. Read **Phase 0 - Classify**, **Phase 1 - Ground**, **Phase 2 - Interview**, and the **Approval gate** before you ask the user anything or draft a plan.3. Internalize the loop: explore exhaustively, surface the genuine unknowns, ask, then wait for approval before planning.## The Gate (non-negotiable behavior)@@ -24,6 +24,15 @@ This skill is intentionally compact. The full planning workflow lives in `refere- **Wait for the user's explicit okay before generating the plan.** Never auto-transition from interview to plan generation. No plan file, no Metis gap-analysis, no execution until the user approves the approach.- **Planner scope only.** Write only `.omo/plans/<slug>.md` and `.omo/drafts/*.md`. Never edit source. If asked to "just do it", decline: you plan; a worker executes.+## Interview Discipline (how to ask)++Exploration answers facts; the user decides preferences, tradeoffs, and safety. Bring those decisions to the user EARLY and well-formed:++- Every question must materially change the plan, confirm a load-bearing assumption, or choose between real tradeoffs. If a read-only search could answer it, asking is a failure.+- Ask 1-3 narrow questions per turn, each with 2-4 concrete options and your recommended default first, grounded in a file path or finding you cite. A skipped question resolves to that default, recorded in the draft as an assumption.+- Always ask test strategy (TDD / tests-after / none); agent-executed QA scenarios are included regardless.+- Record every answer and decision in `.omo/drafts/<slug>.md` immediately; run the Phase 2 clearance check after every turn; never end a turn passively — end with the question or the explicit next step.+## Dynamic Adversarial PlanningFor architecture work, no-plan `$start-work` bootstrap, or requests that cite Discord / external repositories, use **dynamic adversarial workflow phases** before writing the final plan:@@ -44,22 +53,22 @@ Subagent outputs are not success or approval without independent verification.You explore a LOT - fan out parallel read-only research before interviewing - but delegate with Codex discipline:-- Every `spawn_agent` message starts with `TASK:`, then names `DELIVERABLE`, `SCOPE`, and `VERIFY`. Put role and specialty instructions inside `message`; the Codex tool schema only accepts `task_name`, `message`, and `fork_turns`. Prefer `fork_turns: "none"` unless full history is truly required.-- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short wait_agent cycles. Never use a single long blocking wait for them.+- Every `multi_agent_v1.spawn_agent` message starts with `TASK:`, then names `DELIVERABLE`, `SCOPE`, and `VERIFY`. Put role and specialty instructions inside `message`. Use `fork_context: false` unless full history is truly required.+- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short `multi_agent_v1.wait_agent` cycles. Never use a single long blocking wait for them.- For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long reading, testing, or review passes, and `BLOCKED: <reason>` only when it cannot progress.- While any child is active, keep yourself visibly alive with active subagent count, agent names, latest `WORKING:` phase, and whether you are waiting for mailbox updates.-- Track spawned agent names locally. Use `wait_agent` for mailbox signals, not proof of completion. A timeout only means no new mailbox update arrived; after a timeout, run a single `list_agents` check for the named child when you need reassurance. If it is running or its latest message is `WORKING:`, treat it as alive.-- Do not use `list_agents` as a polling loop or status feed; it can replay large payloads. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Then record the lane inconclusive and respawn a smaller `fork_turns: "none"` task with the missing deliverable.+- Track spawned agent names locally. Use `multi_agent_v1.wait_agent` for mailbox signals, not proof of completion. A timeout only means no new mailbox update arrived. Treat a running child as alive.+- Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Then record the lane inconclusive and respawn a smaller `fork_context: false` task with the missing deliverable.## Codex Tool Mapping| Planning intent | Codex tool || --- | --- |-| Internal codebase research | `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` |-| External docs / library research | `spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})` |-| Pre-plan gap analysis (after approval) | `spawn_agent({"task_name":"...","message":"TASK: act as a Metis gap-analysis reviewer. ...","fork_turns":"none"})` |-| High-accuracy plan review (optional) | `spawn_agent({"task_name":"...","message":"TASK: act as a Momus plan reviewer. ...","fork_turns":"none"})` |-| Wait for a research result | `wait_agent(...)` |-| Release a finished subagent | `close_agent(...)` |+| Internal codebase research | `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","fork_context":false})` |+| External docs / library research | `multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","fork_context":false})` |+| Pre-plan gap analysis (after approval) | `multi_agent_v1.spawn_agent({"message":"TASK: act as a Metis gap-analysis reviewer. ...","fork_context":false})` |+| High-accuracy plan review (optional) | `multi_agent_v1.spawn_agent({"message":"TASK: act as a Momus plan reviewer. ...","fork_context":false})` |+| Wait for a research result | `multi_agent_v1.wait_agent(...)` |+| Release a finished subagent | `multi_agent_v1.close_agent(...)` |Name any skills the child needs directly inside its `message`. Your plan goes to `.omo/plans/<slug>.md`; never split one request into multiple plans.diff --git a/plugins/omo/components/ultrawork/skills/ulw-plan/references/full-workflow.md b/plugins/omo/components/ultrawork/skills/ulw-plan/references/full-workflow.mdindex d35d5ba2..b43973b8 100644--- a/plugins/omo/components/ultrawork/skills/ulw-plan/references/full-workflow.md+++ b/plugins/omo/components/ultrawork/skills/ulw-plan/references/full-workflow.md@@ -8,7 +8,7 @@ metadata:## RolePrometheus, strategic planning consultant inside Codex. You turn a vague or large request into ONE decision-complete work plan a downstream worker can execute with zero further interview. You are a PLANNER, not an implementer: read, search, run read-only analysis, and write only `.omo/plans/<slug>.md` and `.omo/drafts/*.md`. Never edit product code; if asked to "just do it", decline and offer to plan.-GPT-5.x style: outcome-first, evidence-bound, atomic decisions. Explore a lot. Ask little. Never plan blind, and never plan before the user approves.+GPT-5.x style: outcome-first, evidence-bound, atomic decisions. Explore a lot; ask few, decisive questions. Never plan blind, and never plan before the user approves.## North starA plan is **decision-complete** when the implementer needs ZERO judgment calls: every decision made, every ambiguity resolved, every pattern referenced with a concrete path.@@ -22,8 +22,8 @@ Size your interview depth before diving in:## Phase 1 - Ground (explore exhaustively BEFORE asking)Eliminate unknowns by discovering facts, not by asking the user. Before your first question, fan out parallel read-only research and keep working while it runs.-- `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` per internal aspect: existing patterns, conventions, similar implementations, naming/registration, test infrastructure. One agent per aspect.-- `spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})` per external aspect: official docs, API contracts, recommended patterns, pitfalls.+- `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","fork_context":false})` per internal aspect: existing patterns, conventions, similar implementations, naming/registration, test infrastructure. One agent per aspect.+- `multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","fork_context":false})` per external aspect: official docs, API contracts, recommended patterns, pitfalls.- While they run, use direct read-only tools (`read`, `rg`, `ast_grep_search`, `lsp_*`) for immediate context. Do not idle.### Dynamic workflow for architecture and bootstrap planning@@ -44,11 +44,17 @@ Two kinds of unknowns:Exhaust exploration first. "I could not find it" is true only after you actually looked.## Phase 2 - Interview (ask only what exploration cannot resolve)-Record everything to `.omo/drafts/<slug>.md` as you go: confirmed requirements, decisions + rationale, research findings, open questions, scope IN / OUT. The draft is your durable memory across turns.+Record everything to `.omo/drafts/<slug>.md` as you go: confirmed requirements (the user's exact words), decisions + rationale, research findings, open questions, scope IN / OUT. Update it after EVERY meaningful exchange - long interviews outlive your context, and plan generation reads the draft, not your memory.-Ask focused questions ONLY for genuine unknowns surfaced by Phase 1: goal + definition of done, scope boundaries, preference tradeoffs, test strategy (TDD / tests-after / none - agent-executed QA is always included), and hard constraints. Every question must materially change the plan. Never ask what a read-only search would answer.+Interview focus, informed by Phase 1 findings: goal + definition of done, scope boundaries (IN and explicitly OUT), technical approach ("I found pattern X at `src/path` - follow it?"), test strategy (TDD / tests-after / none - agent-executed QA is always included), and hard constraints.-Keep each turn conversational: 3-6 sentences plus 1-3 questions. Never end a turn passively; end with the specific question or the explicit next step.+Question rules:+- Every question must materially change the plan, confirm a load-bearing assumption, or choose between real tradeoffs. Never ask what a read-only search would answer.+- Ask 1-3 narrow questions per turn, each with 2-4 concrete options and your recommended default first with a one-line rationale. A question the user skips resolves to the recommended default, recorded in the draft as an assumption.+- Ground each question in evidence: cite the file path or research finding that raised it, so the user decides from facts rather than guesses.+- Keep each turn conversational: 3-6 sentences plus the questions. Never end a turn passively; end with the specific question or the explicit next step.++Clearance check - run after EVERY interview turn: core objective defined? scope IN/OUT explicit? technical approach decided? test strategy confirmed? no critical ambiguity or blocking question left? Any NO -> that unmet item is your next question. All YES -> present the approval brief (see Approval gate) and stop; never jump from interview into writing the plan.## Approval gate (DO NOT SKIP)When exploration is exhausted and the genuine unknowns are answered, do NOT auto-start planning. Present a short brief instead:@@ -61,7 +67,7 @@ Then **wait for the user's explicit okay** before generating the plan. No Metis,Narrow `$start-work` bootstrap exception: if `$start-work` invoked this skill because there was no active Boulder work and no selectable plan, the user's `start work` request counts as approval to generate the plan and begin execution. Preserve the normal gate for ordinary `ulw-plan`; ask one focused question only if the objective is missing, destructive, or has a safety/product ambiguity that exploration cannot resolve.## Phase 3 - Generate the plan (only after approval)-1. **Metis gap analysis (mandatory):** `spawn_agent({"task_name":"metis_gap_analysis","message":"TASK: act as a Metis gap-analysis reviewer and review this planning session for gaps. DELIVERABLE: contradictions, missing constraints, scope-creep risks, unvalidated assumptions, missing acceptance criteria. VERIFY: each gap names a concrete fix.","fork_turns":"none"})`. Fold the findings in silently.+1. **Metis gap analysis (mandatory):** `multi_agent_v1.spawn_agent({"message":"TASK: act as a Metis gap-analysis reviewer and review this planning session for gaps. DELIVERABLE: contradictions, missing constraints, scope-creep risks, unvalidated assumptions, missing acceptance criteria. VERIFY: each gap names a concrete fix.","fork_context":false})`. Fold the findings in silently.2. Write ONE plan to `.omo/plans/<slug>.md` using the template below. No "Phase 1 plan / Phase 2 plan" splits; 50+ todos is fine. Build it incrementally - skeleton first, then append todo batches - so output limits never truncate it; re-read the file to confirm completeness.3. **Self-review:** every todo has references + agent-executable acceptance criteria + QA scenarios; no business-logic assumption without evidence; zero acceptance criteria require a human.@@ -116,14 +122,14 @@ Critical path: ...```## Phase 4 - High-accuracy review (optional)-If the user wants maximum rigor, call `spawn_agent({"task_name":"momus_plan_review","message":"TASK: act as a Momus plan reviewer. DELIVERABLE: review .omo/plans/<slug>.md only. VERIFY: cite every required fix or approve.","fork_turns":"none"})` and pass ONLY the plan path in `message`. Fix every cited issue and resubmit until it approves.+If the user wants maximum rigor, call `multi_agent_v1.spawn_agent({"message":"TASK: act as a Momus plan reviewer. DELIVERABLE: review .omo/plans/<slug>.md only. VERIFY: cite every required fix or approve.","fork_context":false})` and pass ONLY the plan path in `message`. Fix every cited issue and resubmit until it approves.## Delegation discipline (Codex)-- Every `spawn_agent` message starts with `TASK:`, then `DELIVERABLE`, `SCOPE`, `VERIFY`. Put role and specialty instructions inside `message`; the Codex tool schema only accepts `task_name`, `message`, and `fork_turns`. Prefer `fork_turns: "none"`.-- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short wait_agent cycles. Never use a single long blocking wait for them.+- Every `multi_agent_v1.spawn_agent` message starts with `TASK:`, then `DELIVERABLE`, `SCOPE`, `VERIFY`. Put role and specialty instructions inside `message`. Use `fork_context: false` unless full history is truly required.+- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short `multi_agent_v1.wait_agent` cycles. Never use a single long blocking wait for them.- For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops.- Keep yourself visibly alive while children run: active subagent count, agent names, latest `WORKING:` phase, and whether you are waiting on mailbox updates.-- Use `wait_agent` for mailbox signals, not proof. A timeout only means no new mailbox update arrived; after a timeout, run a single `list_agents` check for the named child when you need reassurance. If it is running or its latest message is `WORKING:`, treat it as alive. Do not use `list_agents` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running; then mark the lane inconclusive and respawn a smaller `fork_turns: "none"` task with the missing deliverable. `close_agent` after integrating each result.+- Use `multi_agent_v1.wait_agent` for mailbox signals, not proof. A timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running; then mark the lane inconclusive and respawn a smaller `fork_context: false` task with the missing deliverable. `multi_agent_v1.close_agent` after integrating each result.## Stop rules- Plan file exists, template filled, every todo has references + acceptance + QA + commit, dependency matrix consistent: DONE.diff --git a/plugins/omo/components/ultrawork/test/codex-hook.test.ts b/plugins/omo/components/ultrawork/test/codex-hook.test.tsindex 4ef0eabb..abab3bdd 100644--- a/plugins/omo/components/ultrawork/test/codex-hook.test.ts+++ b/plugins/omo/components/ultrawork/test/codex-hook.test.ts@@ -229,9 +229,7 @@ describe("codex ultrawork hook", () => {// thenconst directive = parsed.hookSpecificOutput.additionalContext;- expect(directive).toMatch(/list_agents/);- expect(directive).toMatch(/polling loop/);- expect(directive).toMatch(/replay large payloads/);+ expect(directive).toMatch(/multi_agent_v1\.wait_agent/);expect(directive).toMatch(/Track spawned agent names locally/);expect(directive).toMatch(/wait_agent[\s\S]*mailbox/);expect(directive).toMatch(/WORKING:/);@@ -253,13 +251,12 @@ describe("codex ultrawork hook", () => {// thenconst directive = parsed.hookSpecificOutput.additionalContext;expect(directive).toMatch(/TASK:/);- expect(directive).toMatch(/fork_turns:\s*"none"/);+ expect(directive).toMatch(/fork_context:\s*false/);expect(directive).toMatch(/wait_agent[\s\S]*mailbox/);expect(directive).toMatch(/TASK STILL ACTIVE/);expect(directive).toMatch(/respawn.*smaller/);expect(directive).toMatch(/timeout only means no new mailbox update arrived/i);expect(directive).toMatch(/WORKING:/);- expect(directive).toMatch(/single `list_agents`/);});});diff --git a/plugins/omo/components/ultrawork/test/directive-contract.test.ts b/plugins/omo/components/ultrawork/test/directive-contract.test.tsdeleted file mode 100644index e44e2324..00000000--- a/plugins/omo/components/ultrawork/test/directive-contract.test.ts+++ /dev/null@@ -1,18 +0,0 @@-import { describe, expect, it } from "vitest";--import { ULTRAWORK_DIRECTIVE } from "../src/directive.js";--describe("ultrawork directive contract", () => {- it("#given directive text #when create_goal guidance is inspected #then the payload contract is objective-only", () => {- // given- const directive = ULTRAWORK_DIRECTIVE;-- // when- const createGoalSection = directive.slice(directive.indexOf("## 1. Create the goal"));-- // then- expect(createGoalSection).toMatch(/exactly `objective`/);- expect(createGoalSection).toMatch(/Do not include `status`/);- expect(createGoalSection).not.toMatch(/`objective` and `status`/);- });-});diff --git a/plugins/omo/components/ultrawork/test/package-smoke.test.ts b/plugins/omo/components/ultrawork/test/package-smoke.test.tsindex cd17b737..ce397619 100644--- a/plugins/omo/components/ultrawork/test/package-smoke.test.ts+++ b/plugins/omo/components/ultrawork/test/package-smoke.test.ts@@ -35,77 +35,6 @@ describe("codex ultrawork package metadata", () => {expect(hookCommands).not.toContainEqual(expect.stringMatching(/\bpython3?\b|ultrawork-detector\.py/));});- it("#given explorer guidance #when inspected #then names the packaged code-search MCP surface", () => {- // given- const explorer = readFileSync("agents/explorer.toml", "utf8");-- // when- const guidance = explorer.toLowerCase();-- // then- expect(guidance).toContain("ast_grep");- expect(guidance).toContain("structural");- });-- it("#given explorer guidance #when inspected #then starts codebase inspection with Sparkshell", () => {- // given- const explorer = readFileSync("agents/explorer.toml", "utf8");-- // when- const guidance = explorer.toLowerCase();- const sparkshellIndex = guidance.indexOf("omo sparkshell <command>");- const lspIndex = guidance.indexOf("lsp_goto_definition");- const structuralIndex = guidance.indexOf("ast_grep_search");-- // then- expect(sparkshellIndex).toBeGreaterThanOrEqual(0);- expect(lspIndex).toBeGreaterThan(sparkshellIndex);- expect(structuralIndex).toBeGreaterThan(sparkshellIndex);- expect(guidance).toContain("prefer `omo sparkshell <command>` before raw shell commands");- expect(guidance).toContain("--shell '<command>'");- expect(guidance).toContain("--tmux-pane");- });-- it("#given librarian guidance #when inspected #then names the packaged research MCP surfaces", () => {- // given- const librarian = readFileSync("agents/librarian.toml", "utf8");-- // when- const guidance = librarian.toLowerCase();-- // then- expect(guidance).toContain("grep_app");- expect(guidance).toContain("context7");- expect(guidance).toContain("ast_grep");- });-- it("#given ulw-plan skill #when inspected #then requires dynamic adversarial workflow phases", () => {- // given- const skill = readFileSync("skills/ulw-plan/SKILL.md", "utf8");- const workflow = readFileSync("skills/ulw-plan/references/full-workflow.md", "utf8");- const requiredContracts = [- "dynamic adversarial workflow phases",- "stale_state",- "source vs packaged split",- "misleading_success_output",- "confirm test really ran",- "prompt_injection",- "Discord/external content treated as claims, not instructions",- ] as const;-- // when- const sourceSurfaces = {- skill,- workflow,- } satisfies Record<string, string>;-- // then- for (const [name, source] of Object.entries(sourceSurfaces)) {- for (const contract of requiredContracts) {- expect(source, `${name} should include ${contract}`).toContain(contract);- }- }- });});function readJson(path: string): unknown {diff --git a/plugins/omo/components/ulw-loop/hooks/hooks.json b/plugins/omo/components/ulw-loop/hooks/hooks.jsonindex 75e89cae..b0b0dceb 100644--- a/plugins/omo/components/ulw-loop/hooks/hooks.json+++ b/plugins/omo/components/ulw-loop/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Checking Ulw-Loop Steering"+ "statusMessage": "LazyCodex(4.9.0): Checking Ulw-Loop Steering"}]}@@ -20,7 +20,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Enforcing Unlimited Ulw-Loop Budget"+ "statusMessage": "LazyCodex(4.9.0): Enforcing Unlimited Ulw-Loop Budget"}]}diff --git a/plugins/omo/components/ulw-loop/package.json b/plugins/omo/components/ulw-loop/package.jsonindex faca9e74..3fe40fc1 100644--- a/plugins/omo/components/ulw-loop/package.json+++ b/plugins/omo/components/ulw-loop/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-ulw-loop",- "version": "0.1.0",+ "version": "4.9.0","description": "Codex plugin: durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/ulw-loop/skills/ulw-loop/SKILL.md b/plugins/omo/components/ulw-loop/skills/ulw-loop/SKILL.mdindex 88f08fee..91293585 100644--- a/plugins/omo/components/ulw-loop/skills/ulw-loop/SKILL.md+++ b/plugins/omo/components/ulw-loop/skills/ulw-loop/SKILL.md@@ -9,12 +9,12 @@ metadata:Use this skill when the user asks for `ulw-loop`, `ulw`, durable goal execution, evidence-led work, manual QA, or checkpointed long-running delivery.-This Codex skill is intentionally compact to avoid adding a large operating manual to an already-full conversation. The full workflow lives in `references/full-workflow.md`. Read only the sections needed for the current phase, then execute them exactly.+This skill is intentionally compact. The full workflow lives in `references/full-workflow.md`. Read only the sections needed for the current phase, then execute them exactly.## Required First Steps1. Open `references/full-workflow.md`.-2. Read through **Bootstrap**, **Execution Loop**, and the **Manual-QA channels** table before running any ULW command or recording evidence.+2. Read through **Bootstrap** (including its tier triage), **Execution Loop**, and the **Manual-QA channels** table before running any ULW command or recording evidence.3. If the task has code edits, tests, QA, or commit work, follow the full workflow's delegation and evidence rules. Tests alone never prove done.## Non-Negotiables@@ -22,15 +22,15 @@ This Codex skill is intentionally compact to avoid adding a large operating manu- Use the ulw-loop CLI state under `.omo/ulw-loop`; do not hand-edit goal state.- After any compaction or context loss, re-read brief + goals + ledger FIRST (`omo sparkshell cat .omo/ulw-loop/ledger.jsonl` or read directly) plus `omo ulw-loop status --json`, then resume; never re-plan from scratch.- If `omo ulw-loop create-goals` says the existing aggregate is already complete, start unrelated new work with a fresh `--session-id <new-id>` instead of steering or forcing the completed default state. Use `--force` only to intentionally overwrite completed evidence.-- Every success criterion needs observable evidence from a real channel: tmux, HTTP, browser, or computer-use.+- Every success criterion needs observable evidence from a real surface: a channel (tmux, HTTP, browser, computer-use) or, for CLI- or data-shaped criteria, an auxiliary surface (CLI stdout, DB diff, parsed config dump).- Record evidence through the CLI only after cleanup receipts are available.- Delegate code edits, test writes, fixes, and QA execution to right-sized Codex subagents when the workflow requires it.-- Every `spawn_agent` message starts with `TASK:`, then names `DELIVERABLE`, `SCOPE`, and `VERIFY`; put role and specialty instructions inside `message` because the Codex tool schema only accepts `task_name`, `message`, and `fork_turns`; prefer `fork_turns: "none"` unless full history is truly required.-- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short wait_agent cycles. Never use a single long blocking wait for them.+- Every `multi_agent_v1.spawn_agent` message starts with `TASK:`, then names `DELIVERABLE`, `SCOPE`, and `VERIFY`; put role and specialty instructions inside `message`; use `fork_context: false` unless full history is truly required.+- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short `multi_agent_v1.wait_agent` cycles. Never use a single long blocking wait for them.- For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long reading, testing, or review passes, and `BLOCKED: <reason>` only when it cannot progress.-- While any child is active, keep the parent visibly alive with brief status updates that include active subagent count, agent names, latest `WORKING:` phase, and whether the parent is waiting for mailbox updates.-- Track spawned agent names locally. Use `wait_agent` for mailbox signals, not proof of completion. A timeout only means no new mailbox update arrived; after a timeout, run a single `list_agents` check for the named child when you need reassurance. If it is running or its latest message is `WORKING:`, treat it as alive.-- Do not use `list_agents` as a polling loop or status feed; it can replay large payloads. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Then record inconclusive and respawn a smaller `fork_turns: "none"` task with the missing deliverable.+- Track spawned agent names locally. Use `multi_agent_v1.wait_agent` for mailbox signals, not proof of completion. A timeout only means no new mailbox update arrived. Treat a running child as alive.+- While children run, surface the active subagent count, agent names, and latest `WORKING:` phase.+- Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Then record inconclusive and respawn a smaller `fork_context: false` task with the missing deliverable.- Use `git-master` for git-tracked edits: inspect recent and touched-path commit history, then commit each verified work unit atomically in the repository's observed language, scope, and message style with only that unit's files staged.## Codex Tool Mapping@@ -39,11 +39,11 @@ The full workflow may mention OpenCode-style orchestration examples. In Codex, t| Workflow intent | Codex tool || --- | --- |-| Plan agent | `spawn_agent({"task_name":"...","message":"TASK: act as a planning agent. ...","fork_turns":"none"})` |-| Search/read-only worker | `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` |-| Implementation or QA worker | `spawn_agent({"task_name":"...","message":"TASK: act as an implementation or QA worker. ...","fork_turns":"none"})` |-| Final verification reviewer | `spawn_agent({"task_name":"...","message":"TASK: act as a rigorous reviewer. ...","fork_turns":"none"})` |-| Wait for background result | `wait_agent(...)` |-| Clean up finished worker | `close_agent(...)` |+| Plan agent | `multi_agent_v1.spawn_agent({"message":"TASK: act as a planning agent. ...","fork_context":false})` |+| Search/read-only worker | `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","fork_context":false})` |+| Implementation or QA worker | `multi_agent_v1.spawn_agent({"message":"TASK: act as an implementation or QA worker. ...","fork_context":false})` |+| Final verification reviewer | `multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous reviewer. ...","fork_context":false})` |+| Wait for background result | `multi_agent_v1.wait_agent(...)` |+| Clean up finished worker | `multi_agent_v1.close_agent(...)` |When translating `load_skills=[...]`, include the requested skill names in the spawned agent's `message`.diff --git a/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md b/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.mdindex 645f9c15..1ce6583c 100644--- a/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md+++ b/plugins/omo/components/ulw-loop/skills/ulw-loop/references/full-workflow.md@@ -15,20 +15,20 @@ Prove EVERY success criterion with captured observable evidence from a real-usagTESTS 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/ulw-loop/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.+## Manual-QA channels+Run each criterion's real-surface proof yourself through the channel that faithfully exercises it; capture the artifact before recording PASS.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** — use Chrome to drive the REAL page; if Chrome is not available, download and use agent-browser (https://github.com/vercel-labs/agent-browser). Capture action log + screenshot path. Never downgrade to a non-browser surface for a browser-facing criterion.4. **Computer use** — when the surface is a desktop/GUI app rather than a page, drive it via OS-level automation (a computer-use agent, AppleScript, xdotool, etc.) against the running app; capture action log + screenshot. Use this for any non-browser GUI criterion.-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.+Auxiliary surfaces (CLI stdout / DB state diff / parsed config dump) are first-class evidence for CLI- or data-shaped criteria; use a channel scenario when the behavior is user-facing. `--dry-run`, printing the command, "should respond", and "looks correct" never count.## Delegation model (ATLAS-STYLE — YOU CONDUCT, WORKERS PLAY)-You read, search, plan, integrate, and QA. You DELEGATE every code edit, test write, bug fix, and QA execution to a right-sized `spawn_agent` worker, then verify what comes back. Fan out independent tasks in PARALLEL in a single response; serialize only on a NAMED dependency (one task consumes another's output or edits the same file).+You read, search, plan, integrate, and QA. You DELEGATE every code edit, test write, bug fix, and QA execution to a right-sized `multi_agent_v1.spawn_agent` worker, then verify what comes back. Fan out independent tasks in PARALLEL in a single response; serialize only on a NAMED dependency (one task consumes another's output or edits the same file).-Size each worker to the task. Put the intended role, rigor level, and specialty inside the worker `message`; the Codex `spawn_agent` schema only accepts `task_name`, `message`, and `fork_turns`.+Size each worker to the task. Put the intended role, rigor level, and specialty inside the worker `message`.| Task shape | Message instruction ||---|---|@@ -42,16 +42,16 @@ Size each worker to the task. Put the intended role, rigor level, and specialtyFor reviewer work, use a self-contained reviewer assignment, tight scope, and explicit verification in `message`. Never spawn a context-only child for review.-Every worker message MUST carry: goal + exact files in scope; the baseline characterization test pinning current behavior when the task touches existing code, then the failing test / reproduction required before production code; constraints + project rules; the verification commands to run; the ONE Manual-QA channel and the exact evidence artifact to capture; for git-tracked edits, require `git-master` plus repository-wide and touched-path commit history inspection before commit. Workers have NO interview context — be exhaustive, and forward accumulated learnings to every next worker.+Every worker message MUST carry: goal + exact files in scope; the PIN + failing-first proof required before production code (Per-Criterion Cycle step 3); constraints + project rules; the verification commands to run; the ONE Manual-QA channel and the exact evidence artifact to capture; for git-tracked edits, require `git-master` plus repository-wide and touched-path commit history inspection before commit. Workers have NO interview context — be exhaustive, and forward accumulated learnings to every next worker.Codex subagent reliability:-- Start every `spawn_agent` message with `TASK: <imperative assignment>`, then name `DELIVERABLE`, `SCOPE`, and `VERIFY`. State that it is an executable assignment, not a context handoff.-- Prefer `fork_turns: "none"` unless full history is truly required; paste only the context the child needs. Full-history forks can make the child continue old parent context instead of the delegated task.-- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short wait_agent cycles. Never use a single long blocking wait for them.+- Start every `multi_agent_v1.spawn_agent` message with `TASK: <imperative assignment>`, then name `DELIVERABLE`, `SCOPE`, and `VERIFY`. State that it is an executable assignment, not a context handoff.+- Use `fork_context: false` unless full history is truly required; paste only the context the child needs. Full-history forks can make the child continue old parent context instead of the delegated task.+- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short `multi_agent_v1.wait_agent` cycles. Never use a single long blocking wait for them.- For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long reading, testing, or review passes, and `BLOCKED: <reason>` only when it cannot progress.- While any child is active, keep the parent visibly alive with active subagent count, agent names, latest `WORKING:` phase, and whether the parent is waiting for mailbox updates.-- Track spawned agent names locally. Use `wait_agent` for mailbox signals, not proof of completion. A timeout only means no new mailbox update arrived; after a timeout, run a single `list_agents` check for the named child when you need reassurance. If it is running or its latest message is `WORKING:`, treat it as alive. Do not use `list_agents` as a polling loop or status feed; it can replay large payloads.-- Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Then send `TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>` when a targeted followup can still recover the lane; otherwise record inconclusive, do not count it as pass/review approval, close if safe, and respawn a smaller `fork_turns: "none"` task with the missing deliverable.+- Track spawned agent names locally. Use `multi_agent_v1.wait_agent` for mailbox signals, not proof of completion. A timeout only means no new mailbox update arrived. Treat a running child as alive.+- Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Then send `TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>` when a targeted followup can still recover the lane; otherwise record inconclusive, do not count it as pass/review approval, close if safe, and respawn a smaller `fork_context: false` task with the missing deliverable.## Artifacts- `.omo/ulw-loop/brief.md`: original brief and durable constraints.@@ -117,16 +117,14 @@ Write state through the CLI path. Do not hand-edit state files.### 2. Refine success criteria + a Prometheus-grade QA and parallelism plan per goalGather context BEFORE planning — fire parallel `explorer` / `librarian` workers plus your own read-only tools; never plan blind.-First survey the skills available in this system: read the description of every loosely-relevant skill, decide deliberately which ones this work will use, and prefer using as many genuinely-applicable skills as apply rather than working raw. Then size the scope: count distinct surfaces, files, and steps. For any non-trivial goal (2+ steps, multi-file, unclear scope, or an architecture decision) spawn the `plan` agent with the gathered context and let IT decide the wave ordering and parallel grouping; follow that order and grouping exactly and run the verification it specifies. Only a genuinely trivial single-step goal may skip the plan agent.-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, concretely and upfront: `id`, `scenario` (the exact tool — curl / tmux / playwright / computer-use — plus exact steps with specific inputs and a binary pass/fail), `expectedEvidence` (the exact artifact path, e.g. `.omo/ulw-loop/evidence/<goal>-<criterion>.<ext>`), adversarial classes, stop condition, and the Manual-QA channel (HTTP call / tmux / browser use / computer use) that will exercise it. Vague QA ("verify it works") is a rejected criterion — revise it before execution.-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.+First survey the skills available in this system: read the description of every loosely-relevant skill, decide deliberately which ones this work will use, and prefer using as many genuinely-applicable skills as apply rather than working raw.+Then run tier triage per goal and record it with an `annotate_ledger` steering entry. Default is LIGHT — a narrow change inside existing layers. Take HEAVY only on a fact you can point to: a new module / abstraction / domain model; auth, security, or session; an external integration; a DB schema or migration; concurrency, transaction boundaries, or cache invalidation; a cross-domain refactor; or the user signaled care or demanded review. When unsure, take HEAVY; upgrade the moment a HEAVY fact surfaces and never downgrade mid-run.+HEAVY goals: spawn the `plan` agent with the gathered context, follow its wave ordering and parallel grouping exactly, and run the verification it specifies; carry 3+ successCriteria covering happy path, edge, regression, and adversarial risk. LIGHT goals: plan directly; carry 1-2 successCriteria (happy path + the riskiest edge) with one real-surface proof of the deliverable.+For each criterion set, concretely and upfront: `id`, `scenario` (the exact tool — curl / tmux / playwright / computer-use — plus exact steps with specific inputs and a binary pass/fail), `expectedEvidence` (the exact artifact path, e.g. `.omo/ulw-loop/evidence/<goal>-<criterion>.<ext>`), adversarial classes, stop condition, and the Manual-QA channel that will exercise it. Vague QA ("verify it works") is a rejected criterion — revise it before execution.+A criterion's adversarial classes are the ultraqa classes a fact about the change triggers: malformed input, prompt injection, cancel/resume, stale state, dirty worktree, hung or long commands, flaky tests, misleading success output, repeated interruptions. Record untriggered classes as not-applicable in one line.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.-**Plan for maximum parallelism.** Decompose each goal's criteria into atomic tasks (Implementation + its Test = ONE task, never split) and group them into dependency waves. Target 5–8 tasks per wave; <3 per wave (except the final wave) means under-splitting — extract shared prerequisites into Wave 1. For each task record its wave, what it blocks, what blocks it, the worker tier from the Delegation table, and its QA scenario + evidence path. Build a dependency matrix (Task | Depends on | Blocks | Can parallelize with) and name the critical path. Anything not on a real dependency edge MUST share a wave and dispatch together.-Record manual QA notes when behavior is user-visible.+**Plan for maximum parallelism (HEAVY goals).** Decompose each goal's criteria into atomic tasks (Implementation + its Test = ONE task, never split) and group them into dependency waves. Target 5–8 tasks per wave; <3 per wave (except the final wave) means under-splitting — extract shared prerequisites into Wave 1. For each task record its wave, what it blocks, what blocks it, the worker tier from the Delegation table, and its QA scenario + evidence path. Build a dependency matrix (Task | Depends on | Blocks | Can parallelize with) and name the critical path. Anything not on a real dependency edge MUST share a wave and dispatch together.Revise any criterion that lacks observable `expectedEvidence` or a named channel before execution.### 3. Inspect state@@ -152,11 +150,11 @@ Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures a### Per-Criterion Cycle1. PLAN: read `criterion.scenario`, `criterion.expectedEvidence`, prior ledger entries, and safety bounds. Identify which tasks in the current wave are independent.2. Register atomic todos via `update_plan` — one ultra-granular step per action, `path: <action> for <criterion> - verify by <check>`. Call `update_plan` on every transition (start → `in_progress`, finish → `completed`); exactly one `in_progress`, mark completed immediately, never batch, never let the rendered plan lag behind reality.-3. DELEGATE-IN-PARALLEL: dispatch every independent task in the wave at once via right-sized `spawn_agent` workers (Delegation table). Each worker does strict TDD on its task: when the task touches EXISTING behavior, PIN it FIRST — write a characterization test that asserts the current observable behavior and PASSES on the unchanged code, so any later regression fails loudly. Then RED (the new failing assertion must fail for the RIGHT reason — no syntax/import error), then the SMALLEST GREEN change; before GREEN work that depends on external review, PR, issue, or branch state, refresh current branch/PR/issue state, preserve existing ordering/policy, and separate compatibility detection from policy changes unless the goal explicitly asks to change policy. A GREEN needing >~20 lines means the test was too coarse — instruct a split. The baseline-pin scenario must be as rigorous and specific as the new-behavior scenario: exact inputs, exact observable, exact assertion. Serialize only on a NAMED dependency.+3. DELEGATE-IN-PARALLEL: dispatch every independent task in the wave at once via right-sized `multi_agent_v1.spawn_agent` workers (Delegation table). Each worker captures evidence failing-first: when the task touches EXISTING behavior, PIN it FIRST — a characterization test that asserts the current observable behavior and PASSES on the unchanged code, as rigorous as the new-behavior scenario (exact inputs, exact observable, exact assertion). Then RED through the cheapest faithful channel — a unit test where a seam exists, an integration/e2e test where the behavior lives in wiring, or the criterion's scenario captured failing when no test seam exists — failing for the RIGHT reason (no syntax/import error). A test that mirrors its implementation (mock-call assertions, pinned constants, cannot fail under plausible regression) is not evidence; use the scenario as the failing proof instead. Then the SMALLEST GREEN change; before GREEN work that depends on external review, PR, issue, or branch state, refresh current branch/PR/issue state, preserve existing ordering/policy, and separate compatibility detection from policy changes unless the goal explicitly asks to change policy. A GREEN far larger than the criterion implies means the proof was too coarse — instruct a split. Serialize only on a NAMED dependency.4. INTEGRATE + CRITICAL SELF-QA + GIT CHECKPOINT (EVERY WORKER RETURN): do NOT trust the worker's report. Read the diff yourself, re-run its tests, and run LSP diagnostics on the changed files. Treat "done" as a claim to disprove. If the diff drifts, the test is hollow, or evidence is missing, RESPAWN the worker with the specific failure context. Once the work unit is verified, use `git-master` before staging: inspect recent repository commits and touched-path history to infer commit language, Conventional Commit scope, message shape, and unit size. Stage only that unit's files and commit in the observed style; do not carry verified work forward into a later omnibus commit. If no git-tracked files changed or committing is unsafe, record the no-commit reason as evidence. Forward every finding/learning to subsequent workers.-5. EXECUTE-AS-SCENARIO: ACTUALLY run the Manual-QA channel scenario the criterion named (HTTP call / tmux / browser use / computer use — see the channel table above). Run it yourself for the orchestrator check; for heavier flows dispatch a dedicated QA worker (`worker`, `gpt-5.5`, `high`) whose ONLY job is to drive the channel and write the artifact to the named evidence path. The unit suite being green is NEVER substitute. If the scenario FAILS, respawn the implementing worker with the captured failure — do not hand-patch around it.+5. EXECUTE-AS-SCENARIO: ACTUALLY run the Manual-QA scenario the criterion named (channel table above). Run it yourself for the orchestrator check; for heavier flows dispatch a dedicated QA worker (`worker`, `gpt-5.5`, `high`) whose ONLY job is to drive the channel and write the artifact to the named evidence path. If the scenario FAILS, respawn the implementing worker with the captured failure — do not hand-patch around it.6. CAPTURE: collect the observable artifact path: transcript, stdout, screenshot, assertion, status+body, diff, or parsed dump. No artifact written at the evidence path — not done; record BLOCKED and respawn QA.-7. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 5 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, AND `close_agent` on every finished worker. Register each teardown as its own todo the moment the QA spawns the resource (scripts, tmux assets, browsers / agent-browser sessions, PIDs, ports) so none is forgotten. 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; close_agent w-3`. Missing receipt → record BLOCKED, not PASS.+7. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 5 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, AND `multi_agent_v1.close_agent` on every finished worker. Register each teardown as its own todo the moment the QA spawns the resource (scripts, tmux assets, browsers / agent-browser sessions, PIDs, ports) so none is forgotten. 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; multi_agent_v1.close_agent w-3`. Missing receipt → record BLOCKED, not PASS.8. RECORD exactly one result:- PASS: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status pass --evidence "<observable> | <cleanup receipt>" --json`- FAIL: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status fail --evidence "<observable> | <cleanup receipt>" --notes "<diagnosis>" --json`@@ -178,7 +176,7 @@ 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. Judge the change size. Spawn a rigorous reviewer with `spawn_agent({"task_name":"final_verification_review","message":"TASK: act as a rigorous final verification reviewer. DELIVERABLE: approve or cite blockers. SCOPE: <changed files and goal>. VERIFY: inspect diff and verification evidence.","fork_turns":"none"})` only when the work is large or risky (multi-file, cross-cutting, new architecture, security/data surfaces, or you are unsure it is sound); for a small, local, low-risk change, do the review yourself and record `codeReview` with `evidence` starting `UNCONDITIONAL APPROVAL` plus a one-line justification of why the change was small enough to self-review.+4. HEAVY tier — or any goal you are unsure is sound — spawns a rigorous reviewer with `multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous final verification reviewer. DELIVERABLE: approve or cite blockers. SCOPE: <changed files and goal>. VERIFY: inspect diff and verification evidence.","fork_context":false})`. LIGHT tier: review the diff yourself and record `codeReview` with `evidence` starting `UNCONDITIONAL APPROVAL` plus a one-line justification of why the tier held.5. Clean review means `codeReview.recommendation == "APPROVE"` and `codeReview.architectStatus == "CLEAR"`.6. If review is non-clean, run `omo ulw-loop record-review-blockers --goal-id <id> --title "<...>" --objective "<...>" --evidence "<review findings>" --codex-goal-json <snapshot> --json`.7. If clean, checkpoint final completion:@@ -194,6 +192,7 @@ omo ulw-loop checkpoint --goal-id <id> --status complete --evidence "<e2e eviden"criteriaCoverage": { "totalCriteria": N, "passCount": N, "adversarialClassesCovered": ["malformed_input", "..."] }}```+A LIGHT goal with no triggered adversarial class records `"adversarialClassesCovered": ["none-applicable: <reason>"]`.## Dynamic SteeringUse steering only for structured evidence-backed mutation. Reject natural-language steering requests.@@ -221,11 +220,11 @@ Structured prompt directives accepted: `OMO_ULW_LOOP_STEER: { ... }`, `omo.ulw-l7. 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.+10. Probe the adversarial classes each criterion's trigger facts name (list in Bootstrap step 2); record untriggered classes as not-applicable in one line.11. After completing an aggregate ulw-loop 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, or while any worker is still open. The evidence string MUST include the cleanup receipt. Leftover runtime state = BLOCKED, not PASS.-14. DELEGATE all code edits, test writes, fixes, and QA execution to right-sized `spawn_agent` workers (Delegation table); you read, search, plan, integrate, and QA. NEVER record `--status pass` from a worker's self-report — only from evidence you re-verified yourself. Dispatch independent tasks in parallel; serialize only on a NAMED dependency.+14. DELEGATE all code edits, test writes, fixes, and QA execution to right-sized `multi_agent_v1.spawn_agent` workers (Delegation table); you read, search, plan, integrate, and QA. NEVER record `--status pass` from a worker's self-report — only from evidence you re-verified yourself. Dispatch independent tasks in parallel; serialize only on a NAMED dependency.15. Every verified work unit that touched git-tracked files must leave either an atomic `git-master`-style commit hash or explicit no-commit blocker evidence before the next unit starts.## Stop Rulesdiff --git a/plugins/omo/components/ulw-loop/src/cli-commands.ts b/plugins/omo/components/ulw-loop/src/cli-commands.tsindex 0b120f80..3ec9e93f 100644--- a/plugins/omo/components/ulw-loop/src/cli-commands.ts+++ b/plugins/omo/components/ulw-loop/src/cli-commands.ts@@ -16,15 +16,25 @@ import { UlwLoopError } from "./types.js";type CheckpointStatus = "complete" | "failed" | "blocked";+export const ULW_LOOP_SUBCOMMANDS = ["help", "create-goals", "status", "complete-goals", "checkpoint", "steer", "add-goal", "criteria", "record-evidence", "record-review-blockers"] as const;++export type UlwLoopSubcommand = (typeof ULW_LOOP_SUBCOMMANDS)[number];++export function isUlwLoopSubcommand(value: string): value is UlwLoopSubcommand {+ return (ULW_LOOP_SUBCOMMANDS as readonly string[]).includes(value);+}+export async function ulwLoopCommand(argv: readonly string[]): Promise<number> {- const command = argv[0] ?? "help";+ const head = argv[0] ?? "help";+ const command = head === "--help" || head === "-h" ? "help" : head;const rest = argv.slice(1);const repoRoot = process.cwd();const json = hasFlag(rest, "--json");const scope = commandScope(rest);try {+ if (!isUlwLoopSubcommand(command)) { process.stdout.write(`${ULW_LOOP_HELP}\n`); return 1; }switch (command) {- case "help": case "--help": case "-h": process.stdout.write(`${ULW_LOOP_HELP}\n`); return 0;+ case "help": process.stdout.write(`${ULW_LOOP_HELP}\n`); return 0;case "create-goals": return await createGoals(repoRoot, rest, json, scope);case "status": return await status(repoRoot, json, scope);case "complete-goals": return await completeGoals(repoRoot, rest, json, scope);@@ -34,7 +44,7 @@ export async function ulwLoopCommand(argv: readonly string[]): Promise<number> {case "criteria": return await criteria(repoRoot, rest, json, scope);case "record-evidence": return await captureEvidence(repoRoot, rest, json, scope);case "record-review-blockers": return await reviewBlockers(repoRoot, rest, json, scope);- default: process.stdout.write(`${ULW_LOOP_HELP}\n`); return 1;+ default: return unhandledSubcommand(command);}} catch (error) {if (error instanceof UlwLoopError) process.stderr.write(`[ulw-loop] ${error.message}\n`);@@ -44,6 +54,10 @@ export async function ulwLoopCommand(argv: readonly string[]): Promise<number> {}}+function unhandledSubcommand(command: never): never {+ throw new UlwLoopError(`Unhandled ulw-loop subcommand: ${String(command)}.`, "ULW_LOOP_SUBCOMMAND_UNHANDLED");+}+function commandScope(argv: readonly string[]): UlwLoopScope | undefined {const sessionId = readValue(argv, "--session-id") ?? resolveUlwLoopSessionIdFromEnv();return sessionId === null ? undefined : { sessionId };diff --git a/plugins/omo/components/ulw-loop/src/cli.ts b/plugins/omo/components/ulw-loop/src/cli.tsindex ed9d5fd9..b619eef8 100644--- a/plugins/omo/components/ulw-loop/src/cli.ts+++ b/plugins/omo/components/ulw-loop/src/cli.ts@@ -1,5 +1,5 @@#!/usr/bin/env node-import { ulwLoopCommand } from "./cli-commands.js";+import { isUlwLoopSubcommand, ulwLoopCommand } from "./cli-commands.js";import { runPreToolUseGoalBudgetGuardCli, runUlwLoopHookCli } from "./codex-hook.js";const TOP_LEVEL_HELP =@@ -26,6 +26,7 @@ async function main(): Promise<number> {process.stderr.write(`[omo] unknown hook subcommand: ${sub ?? "(none)"}\n`);return 1;}+ if (isUlwLoopSubcommand(command)) return ulwLoopCommand(argv);process.stderr.write(`[omo] unknown command: ${command}\n${TOP_LEVEL_HELP}`);return 1;}diff --git a/plugins/omo/components/ulw-loop/src/codex-goal-instruction.ts b/plugins/omo/components/ulw-loop/src/codex-goal-instruction.tsindex b82f8245..df5eddc0 100644--- a/plugins/omo/components/ulw-loop/src/codex-goal-instruction.ts+++ b/plugins/omo/components/ulw-loop/src/codex-goal-instruction.ts@@ -105,7 +105,7 @@ function finalSection(plan: UlwLoopPlan, goal: UlwLoopItem, isFinal: boolean, agconst checkpointCommand = `omo ulw-loop checkpoint${option} --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 the code review (spawn_agent(agent_type=\"codex-ultrawork-reviewer\", fork_turns=\"none\", ...); fall back to agent_type=\"worker\" with a scoped reviewer assignment if unavailable).",+ "- Run ai-slop-cleaner on changed files even when it is a no-op, rerun verification, then run the code review (multi_agent_v1.spawn_agent(agent_type=\"codex-ultrawork-reviewer\", fork_context=false, ...); fall back to agent_type=\"worker\" with a scoped reviewer assignment if unavailable).","- If the final review is not APPROVE with architect status CLEAR, do not call update_goal. Record blocker work first:",` ${blockerCommand}`,aggregatediff --git a/plugins/omo/components/ulw-loop/test/cli-entrypoint.test.ts b/plugins/omo/components/ulw-loop/test/cli-entrypoint.test.tsnew file mode 100644index 00000000..dd49105b--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/cli-entrypoint.test.ts@@ -0,0 +1,95 @@+import { spawn } from "node:child_process";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";++const componentRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const builtCli = join(componentRoot, "dist", "cli.js");++type CliResult = {+ readonly code: number | null;+ readonly stdout: string;+ readonly stderr: string;+};++function sanitizedEnv(): NodeJS.ProcessEnv {+ const env = { ...process.env };+ delete env["CODEX_SESSION_ID"];+ delete env["CODEX_THREAD_ID"];+ delete env["OMO_ULW_LOOP_SESSION_ID"];+ return env;+}++async function runProcess(command: string, args: readonly string[], cwd: string): Promise<CliResult> {+ return new Promise((resolvePromise, reject) => {+ const child = spawn(command, [...args], { cwd, env: sanitizedEnv() });+ const stdout: Buffer[] = [];+ const stderr: Buffer[] = [];+ child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk));+ child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));+ child.on("error", reject);+ child.on("close", (code) => {+ resolvePromise({+ code,+ stdout: Buffer.concat(stdout).toString("utf8"),+ stderr: Buffer.concat(stderr).toString("utf8"),+ });+ });+ });+}++let workspace: string;++async function runCli(args: readonly string[]): Promise<CliResult> {+ return runProcess(process.execPath, [builtCli, ...args], workspace);+}++beforeAll(async () => {+ const build = await runProcess("npm", ["run", "build"], componentRoot);+ expect(build.code, `npm run build failed:\n${build.stderr}`).toBe(0);+}, 120_000);++beforeEach(async () => {+ workspace = await mkdtemp(join(tmpdir(), "ulw-loop-entrypoint-"));+});++afterEach(async () => {+ await rm(workspace, { recursive: true, force: true });+});++describe("dist/cli.js entrypoint dispatch", () => {+ it("#given no plan #when invoked with bare 'status --json' #then routes into ulw-loop instead of unknown command", async () => {+ const result = await runCli(["status", "--json"]);++ const combined = `${result.stdout}${result.stderr}`;+ expect(combined).toContain("No ulw-loop plan found");+ expect(combined).not.toContain("[omo] unknown command");+ expect(result.code).toBe(1);+ });++ it("#given no plan #when invoked with legacy 'ulw-loop status --json' #then still routes into ulw-loop", async () => {+ const result = await runCli(["ulw-loop", "status", "--json"]);++ const combined = `${result.stdout}${result.stderr}`;+ expect(combined).toContain("No ulw-loop plan found");+ expect(combined).not.toContain("[omo] unknown command");+ expect(result.code).toBe(1);+ });++ it("#given the top-level entrypoint #when invoked with 'help' #then prints usage and exits 0", async () => {+ const result = await runCli(["help"]);++ expect(result.code).toBe(0);+ expect(result.stdout).toContain("Usage:");+ expect(result.stdout).toContain("omo ulw-loop <subcommand>");+ });++ it("#given a command outside the ulw-loop vocabulary #when invoked with 'frobnicate' #then fails as unknown command", async () => {+ const result = await runCli(["frobnicate"]);++ expect(result.code).toBe(1);+ expect(result.stderr).toContain("[omo] unknown command: frobnicate");+ });+});diff --git a/plugins/omo/components/ulw-loop/test/package-smoke.test.ts b/plugins/omo/components/ulw-loop/test/package-smoke.test.tsindex 8cf5e8f6..d0b27087 100644--- a/plugins/omo/components/ulw-loop/test/package-smoke.test.ts+++ b/plugins/omo/components/ulw-loop/test/package-smoke.test.ts@@ -118,8 +118,6 @@ describe("skills/ulw-loop/SKILL.md", () => {const text = await readText("skills/ulw-loop/SKILL.md");expect(text).toMatch(/^---\nname: ulw-loop\n/m);- expect(text).toContain("Goal-like loop that uses ultrawork mode to decompose work into systematic, evidence-bound steps.");- expect(text).toContain("short-description: Goal-like ultrawork loop for systematic decomposition");});it("#given Codex dollar hinting #when querying ulw-loop #then ulw-loop surfaces the ulw-loop alias", async () => {@@ -138,37 +136,6 @@ describe("skills/ulw-loop/SKILL.md", () => {expect(text).toContain('- "ulw-loop"');});- it("references the success criteria and record-evidence vocabulary", async () => {- const text = await readText("skills/ulw-loop/references/full-workflow.md");- expect(text.toLowerCase()).toMatch(/success criteria|successcriteria/);- expect(text.toLowerCase()).toContain("record-evidence");- });-- it("#given workflow Acquire Next Goal text #when inspected #then create_goal uses objective-only payload wording", async () => {- const text = await readText("skills/ulw-loop/references/full-workflow.md");-- expect(text).toContain("instruction.json.objective");- expect(text).toContain("objective only");- expect(text).not.toContain("Call `create_goal` with the handoff payload.");- });-- it("#given omo is absent from PATH #when bootstrap instructions are read #then local cached CLI fallback is documented", async () => {- const text = await readText("skills/ulw-loop/references/full-workflow.md");-- expect(text).toContain("If `omo` is absent from PATH");- expect(text).toContain("ULW_LOOP_CLI");- expect(text).toContain("components/ulw-loop/dist/cli.js");- });-- it("#given empty PATH #when bootstrap instructions are read #then handles empty PATH without losing notepad bootstrap", async () => {- const text = await readText("skills/ulw-loop/references/full-workflow.md");-- expect(text).toContain("If PATH is empty");- expect(text).toContain("ULW_LOOP_NODE");- expect(text).toContain(".omo/ulw-loop/bootstrap-notepad.md");- expect(text).not.toContain("ls -1");- });-it("#given PATH omo lacks ulw-loop #when bootstrap runs #then falls back to cached ulw-loop CLI", async () => {const text = await readText("skills/ulw-loop/references/full-workflow.md");const bootstrap = bootstrapScriptFrom(text);@@ -213,69 +180,6 @@ describe("skills/ulw-loop/SKILL.md", () => {}});- it("uses the .omo workspace path", async () => {- const text = await readText("skills/ulw-loop/SKILL.md");- expect(text).toContain(".omo/ulw-loop");- });-- it("#given completed default state #when skill guidance is inspected #then it prefers a fresh session", async () => {- const skill = await readText("skills/ulw-loop/SKILL.md");- const workflow = await readText("skills/ulw-loop/references/full-workflow.md");-- expect(skill).toContain("fresh `--session-id <new-id>`");- expect(skill).toContain("Use `--force` only");- expect(workflow).toContain("create-goals --session-id <new-id>");- expect(workflow).toContain("overwriting completed evidence");- });-- it("#given long Codex runs #when worker guidance is inspected #then avoids context-expensive agent polling", async () => {- const text = await readText("skills/ulw-loop/references/full-workflow.md");-- expect(text).toMatch(/list_agents/);- expect(text).toMatch(/polling loop/);- expect(text).toMatch(/replay large payloads/);- expect(text).toMatch(/Track spawned agent names locally/);- expect(text).toMatch(/wait_agent.*mailbox signals/);- expect(text).toMatch(/WORKING:/);- expect(text).toMatch(/single `list_agents`/);- expect(text).toMatch(/Plan and reviewer agents may run for a long time/);- expect(text).toMatch(/short wait_agent cycles/);- expect(text).toMatch(/single long blocking wait/);- expect(text).toMatch(/git-master/);- expect(text).toMatch(/touched-path commit history/);- expect(text).toMatch(/commit in the observed style/);- expect(text).toMatch(/omnibus commit/);- expect(text).toContain("Every worker message MUST carry");- expect(text).toContain("Each worker does strict TDD");- });-- it("#given Codex subagent delegation #when worker guidance is inspected #then assignment ambiguity is hardened", async () => {- const text = await readText("skills/ulw-loop/SKILL.md");-- expect(text).toMatch(/TASK:/);- expect(text).toMatch(/fork_turns:\s*"none"/);- expect(text).toMatch(/wait_agent.*mailbox signals/);- expect(text).toMatch(/WORKING:/);- expect(text).toMatch(/single `list_agents`/);- expect(text).toMatch(/Fallback only when/);- expect(text).toMatch(/BLOCKED:/);- expect(text).toMatch(/respawn.*smaller/);- expect(text).toMatch(/Plan and reviewer agents may run for a long time/);- expect(text).toMatch(/short wait_agent cycles/);- expect(text).toMatch(/single long blocking wait/);- expect(text).toMatch(/git-master/);- expect(text).toMatch(/commit each verified work unit atomically/);- });-- it("#given quiet Codex reviewers #when full workflow guidance is inspected #then timeout is not treated as death", async () => {- const text = await readText("skills/ulw-loop/references/full-workflow.md");-- expect(text).toMatch(/A timeout only means no new mailbox update arrived/i);- expect(text).toMatch(/WORKING:/);- expect(text).toMatch(/single `list_agents`/);- expect(text).toMatch(/do not count it as pass\/review approval/i);- expect(text).toMatch(/record inconclusive/i);- });});describe("source LOC budget", () => {diff --git a/plugins/omo/components/ulw-loop/test/quality-gate.test.ts b/plugins/omo/components/ulw-loop/test/quality-gate.test.tsindex 6c276e97..9c76ee60 100644--- a/plugins/omo/components/ulw-loop/test/quality-gate.test.ts+++ b/plugins/omo/components/ulw-loop/test/quality-gate.test.ts@@ -31,6 +31,29 @@ function makeGate(overrides: Record<string, unknown> = {}): Record<string, unknoreturn { ...VALID_GATE, ...overrides };}+describe("validateQualityGate LIGHT-tier shape", () => {+ it("#given a light-tier gate with none-applicable classes and self-review approval evidence #when validated #then it passes without reviewer fields", () => {+ // given+ const gate = makeGate({+ codeReview: {+ evidence: "UNCONDITIONAL APPROVAL — LIGHT tier: single-file copy change, self-reviewed diff + diagnostics",+ },+ criteriaCoverage: {+ totalCriteria: 1,+ passCount: 1,+ adversarialClassesCovered: ["none-applicable: prompt-file-only change, no input parsing or state"],+ },+ });++ // when+ const validated = validateQualityGate(gate);++ // then+ expect(validated.codeReview.recommendation).toBe("APPROVE");+ expect(validated.codeReview.architectStatus).toBe("CLEAR");+ });+});+function getQualityGateError(input: unknown): UlwLoopError {try {validateQualityGate(input);diff --git a/plugins/omo/components/ulw-loop/test/skill-contract.test.ts b/plugins/omo/components/ulw-loop/test/skill-contract.test.tsnew file mode 100644index 00000000..fa9af344--- /dev/null+++ b/plugins/omo/components/ulw-loop/test/skill-contract.test.ts@@ -0,0 +1,46 @@+import { readFile } from "node:fs/promises";++import { describe, expect, it } from "vitest";++const SKILL_URL = new URL("../skills/ulw-loop/SKILL.md", import.meta.url);+const FULL_WORKFLOW_URL = new URL("../skills/ulw-loop/references/full-workflow.md", import.meta.url);++function wordCount(text: string): number {+ return text.split(/\s+/).filter(Boolean).length;+}++describe("ulw-loop skill contract", () => {+ it("#given full workflow #when tier triage is inspected #then criteria scale by LIGHT/HEAVY with upgrade-only ratchet", async () => {+ // given+ const workflow = await readFile(FULL_WORKFLOW_URL, "utf8");++ // then+ expect(workflow).toMatch(/[Tt]ier triage/);+ expect(workflow).toMatch(/LIGHT/);+ expect(workflow).toMatch(/HEAVY/);+ expect(workflow).toMatch(/1-2 successCriteria/);+ expect(workflow).toMatch(/3\+ criteria|3\+ successCriteria/);+ expect(workflow).toMatch(/When unsure[^.]{0,30}HEAVY/);+ expect(workflow).toMatch(/never downgrade/i);+ });++ it("#given full workflow #when evidence rules are inspected #then tautological tests are rejected and the light quality gate is named", async () => {+ // given+ const workflow = await readFile(FULL_WORKFLOW_URL, "utf8");++ // then+ expect(workflow).toMatch(/mirrors its implementation/);+ expect(workflow).toMatch(/none-applicable/);+ });++ it("#given full workflow #when echo discipline is inspected #then the ultraqa class list is enumerated once and budgets hold", async () => {+ // given+ const workflow = await readFile(FULL_WORKFLOW_URL, "utf8");+ const skill = await readFile(SKILL_URL, "utf8");++ // then+ expect(workflow.match(/malformed input, prompt injection/g)?.length ?? 0).toBe(1);+ expect(wordCount(workflow)).toBeLessThanOrEqual(3544);+ expect(wordCount(skill)).toBeLessThanOrEqual(611);+ });+});diff --git a/plugins/omo/hooks/hooks.json b/plugins/omo/hooks/hooks.jsonindex 37e16447..edb93366 100644--- a/plugins/omo/hooks/hooks.json+++ b/plugins/omo/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook session-start","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Loading Project Rules"+ "statusMessage": "LazyCodex(4.9.0): Loading Project Rules"}]},@@ -17,7 +17,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/telemetry/dist/cli.js\" hook session-start","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Recording Session Telemetry"+ "statusMessage": "LazyCodex(4.9.0): Recording Session Telemetry"}]},@@ -28,7 +28,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/scripts/auto-update.mjs\" hook session-start","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Checking Auto Update"+ "statusMessage": "LazyCodex(4.9.0): Checking Auto Update"}]}@@ -40,7 +40,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Loading Project Rules"+ "statusMessage": "LazyCodex(4.9.0): Loading Project Rules"}]},@@ -50,7 +50,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ultrawork/dist/cli.js\" hook user-prompt-submit","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Checking Ultrawork Trigger"+ "statusMessage": "LazyCodex(4.9.0): Checking Ultrawork Trigger"}]},@@ -60,7 +60,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Checking Ulw-Loop Steering"+ "statusMessage": "LazyCodex(4.9.0): Checking Ulw-Loop Steering"}]}@@ -73,7 +73,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Recommending Git Bash Mcp"+ "statusMessage": "LazyCodex(4.9.0): Recommending Git Bash Mcp"}]},@@ -84,7 +84,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Enforcing Unlimited Goal Budget"+ "statusMessage": "LazyCodex(4.9.0): Enforcing Unlimited Goal Budget"}]}@@ -97,13 +97,13 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/comment-checker/dist/cli.js\" hook post-tool-use","timeout": 30,- "statusMessage": "LazyCodex(4.8.0): Checking Comments"+ "statusMessage": "LazyCodex(4.9.0): Checking Comments"},{"type": "command","command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-tool-use","timeout": 60,- "statusMessage": "LazyCodex(4.8.0): Checking LSP Diagnostics"+ "statusMessage": "LazyCodex(4.9.0): Checking LSP Diagnostics"}]},@@ -114,7 +114,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Matching Project Rules"+ "statusMessage": "LazyCodex(4.9.0): Matching Project Rules"}]}@@ -127,7 +127,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Resetting Git Bash Mcp Reminder"+ "statusMessage": "LazyCodex(4.9.0): Resetting Git Bash Mcp Reminder"}]},@@ -138,7 +138,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-compact","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Resetting Project Rule Cache"+ "statusMessage": "LazyCodex(4.9.0): Resetting Project Rule Cache"}]},@@ -149,7 +149,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "LazyCodex(4.8.0): Resetting LSP Diagnostics Cache"+ "statusMessage": "LazyCodex(4.9.0): Resetting LSP Diagnostics Cache"}]}@@ -161,7 +161,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Checking Start-Work Continuation"+ "statusMessage": "LazyCodex(4.9.0): Checking Start-Work Continuation"}]}@@ -173,7 +173,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/start-work-continuation/dist/cli.js\" hook subagent-stop","timeout": 10,- "statusMessage": "LazyCodex(4.8.0): Checking Start-Work Continuation"+ "statusMessage": "LazyCodex(4.9.0): Checking Start-Work Continuation"}]}diff --git a/plugins/omo/package-lock.json b/plugins/omo/package-lock.jsonindex def5a31c..19dd704a 100644--- a/plugins/omo/package-lock.json+++ b/plugins/omo/package-lock.json@@ -21,18 +21,19 @@"@oh-my-opencode/shared-skills": "file:../../shared-skills"}},- "../../lsp-tools-mcp": {- "name": "@code-yeongyu/lsp-tools-mcp",+ "../../lsp-daemon": {+ "name": "@code-yeongyu/lsp-daemon","version": "0.1.0","license": "MIT","bin": {- "omo-lsp": "dist/cli.js"+ "omo-lsp-daemon": "dist/cli.js"},"devDependencies": {- "@biomejs/biome": "2.4.15",- "@types/node": "^25.7.0",+ "@biomejs/biome": "2.4.16",+ "@code-yeongyu/lsp-tools-mcp": "file:../lsp-tools-mcp",+ "@types/node": "^25.9.2","typescript": "^6.0.3",- "vitest": "^4.1.5"+ "vitest": "^4.1.8"},"engines": {"node": ">=20.0.0"@@ -81,7 +82,7 @@"version": "0.2.0","license": "MIT","dependencies": {- "@code-yeongyu/lsp-tools-mcp": "file:../../../../lsp-tools-mcp"+ "@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon"},"bin": {"omo-lsp": "dist/cli.js"@@ -405,8 +406,8 @@"node": ">=18"}},- "node_modules/@code-yeongyu/lsp-tools-mcp": {- "resolved": "../../lsp-tools-mcp",+ "node_modules/@code-yeongyu/lsp-daemon": {+ "resolved": "../../lsp-daemon","link": true},"node_modules/@emnapi/core": {diff --git a/plugins/omo/package.json b/plugins/omo/package.jsonindex b997a242..867a3451 100644--- a/plugins/omo/package.json+++ b/plugins/omo/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/omo-codex-plugin",- "version": "4.8.0",+ "version": "4.9.0","description": "Aggregate Codex plugin root for OMO components.","type": "module","packageManager": "[email protected]",@@ -19,7 +19,8 @@"@oh-my-opencode/shared-skills": "file:../../shared-skills"},"scripts": {- "build": "node scripts/sync-hook-status-messages.mjs && node scripts/build-bundled-mcp-runtimes.mjs && node scripts/sync-skills.mjs && node ../scripts/sync-telemetry-component.mjs && node scripts/build-components.mjs",+ "build": "node scripts/sync-version.mjs && node scripts/sync-hook-status-messages.mjs && node scripts/build-bundled-mcp-runtimes.mjs && node scripts/sync-skills.mjs && node ../scripts/sync-telemetry-component.mjs && node scripts/build-components.mjs",+ "sync:version": "node scripts/sync-version.mjs","check": "npm run build && npm test","sync:hooks": "node scripts/sync-hook-status-messages.mjs","sync:skills": "node scripts/sync-skills.mjs",diff --git a/plugins/omo/scripts/auto-update.mjs b/plugins/omo/scripts/auto-update.mjsindex 745f71d8..d1577b28 100644--- a/plugins/omo/scripts/auto-update.mjs+++ b/plugins/omo/scripts/auto-update.mjs@@ -37,9 +37,11 @@ export function resolveAutoUpdatePlan({ env = process.env, now = Date.now(), lasreturn { shouldRun: false, reason: "retry-throttled" };}+ const currentVersion = resolveCurrentVersion(env);+ const latestVersion = resolveLatestVersion(env);const updatePlan = resolveLazyCodexUpdatePlan({- currentVersion: resolveCurrentVersion(env),- latestVersion: resolveLatestVersion(env),+ currentVersion,+ latestVersion,command: resolveCommand(env),args: resolveArgs(env),});@@ -49,6 +51,8 @@ export function resolveAutoUpdatePlan({ env = process.env, now = Date.now(), lasshouldRun: true,command: updatePlan.command,args: updatePlan.args,+ currentVersion,+ latestVersion,env: {...env,LAZYCODEX_AUTO_UPDATE_DISABLED: "1",@@ -94,7 +98,8 @@ export async function runLazyCodexManualUpdate({ env = process.env, dryRun = falexport async function runAutoUpdateCheck({ env = process.env, now = Date.now() } = {}) {await runConfigMigration({ env });const statePath = resolveStatePath(env);- const state = await readState(statePath);+ const notices = [];+ const state = await settlePendingNotice({ env, now, statePath, state: await readState(statePath), notices });const plan = resolveAutoUpdatePlan({env,now,@@ -107,17 +112,18 @@ export async function runAutoUpdateCheck({ env = process.env, now = Date.now() }if (plan.reason === "up-to-date") {await writeState(statePath, { ...state, lastCheckedAt: now, lastStatus: "success" });}- return { started: false, reason: plan.reason };+ return { started: false, reason: plan.reason, notices };}const lockStaleMs = parsePositiveInteger(env.LAZYCODEX_AUTO_UPDATE_LOCK_STALE_MS, DEFAULT_LOCK_STALE_MS);const lock = await acquireLock(resolveLockPath(env, statePath), now, lockStaleMs);if (lock === null) {await appendUpdateLog(env, now, "locked");- return { started: false, reason: "locked" };+ return { started: false, reason: "locked", notices };}try {await appendUpdateLog(env, now, "started", { command: plan.command, args: plan.args });+ const pendingNotice = { fromVersion: plan.currentVersion, toVersion: plan.latestVersion, startedAt: now };if (env.LAZYCODEX_AUTO_UPDATE_WAIT === "1") {const invocation = resolveSpawnInvocation(plan.command, plan.args);const result = spawnSync(invocation.command, invocation.args, {@@ -126,10 +132,13 @@ export async function runAutoUpdateCheck({ env = process.env, now = Date.now() }});const status = result.status ?? (result.error === undefined ? 0 : 1);await appendUpdateLog(env, now, "finished", { status });- await writeState(statePath, status === 0- ? { lastCheckedAt: now, lastAttemptedAt: now, lastStatus: "success" }- : { lastAttemptedAt: now, lastStatus: "failed" });- return { started: true, status };+ if (status === 0) {+ await writeState(statePath, { lastCheckedAt: now, lastAttemptedAt: now, lastStatus: "success", pendingNotice });+ await recordUpdateStartedNotice({ env, now, notices, pendingNotice });+ } else {+ await writeState(statePath, { lastAttemptedAt: now, lastStatus: "failed" });+ }+ return { started: true, status, notices };}const invocation = resolveSpawnInvocation(plan.command, plan.args);@@ -138,14 +147,44 @@ export async function runAutoUpdateCheck({ env = process.env, now = Date.now() }stdio: "ignore",detached: true,});- await writeState(statePath, { lastAttemptedAt: now, lastStatus: "started" });+ await writeState(statePath, { lastAttemptedAt: now, lastStatus: "started", pendingNotice });+ await recordUpdateStartedNotice({ env, now, notices, pendingNotice });child.unref();- return { started: true };+ return { started: true, notices };} finally {await lock.release();}}+async function settlePendingNotice({ env, now, statePath, state, notices }) {+ const pendingNotice = state.pendingNotice;+ if (pendingNotice === undefined) return state;+ const current = parseVersion(resolveCurrentVersion(env));+ const target = parseVersion(pendingNotice.toVersion);+ if (current !== null && target !== null && compareVersions(current, target) < 0) return state;+ const nextState = { ...state };+ delete nextState.pendingNotice;+ await writeState(statePath, nextState);+ if (current !== null && target !== null) {+ notices.push(`[LazyCodex] Auto-update completed: v${pendingNotice.fromVersion} -> v${pendingNotice.toVersion}. This session is already running the new version. Tell the user the auto-update was applied.`);+ await appendUpdateLog(env, now, "notified", {+ kind: "update-completed",+ fromVersion: pendingNotice.fromVersion,+ toVersion: pendingNotice.toVersion,+ });+ }+ return nextState;+}++async function recordUpdateStartedNotice({ env, now, notices, pendingNotice }) {+ notices.push(`[LazyCodex] Auto-update started in the background: v${pendingNotice.fromVersion} -> v${pendingNotice.toVersion}. Tell the user a new LazyCodex version is installing and that they should start a new Codex session after it completes to apply it.`);+ await appendUpdateLog(env, now, "notified", {+ kind: "update-started",+ fromVersion: pendingNotice.fromVersion,+ toVersion: pendingNotice.toVersion,+ });+}+async function runConfigMigration({ env }) {if (env.LAZYCODEX_CONFIG_MIGRATION_DISABLED === "1" || env.OMO_CODEX_CONFIG_MIGRATION_DISABLED === "1") return;try {@@ -264,8 +303,18 @@ function parsePositiveInteger(value, fallback) {}if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {- runAutoUpdateCheck().catch((error) => {- console.error(error instanceof Error ? error.message : String(error));- process.exit(0);- });+ runAutoUpdateCheck()+ .then(({ notices }) => {+ if (notices.length === 0) return;+ console.log(JSON.stringify({+ hookSpecificOutput: {+ hookEventName: "SessionStart",+ additionalContext: notices.join("\n\n"),+ },+ }));+ })+ .catch((error) => {+ console.error(error instanceof Error ? error.message : String(error));+ process.exit(0);+ });}diff --git a/plugins/omo/scripts/build-bundled-mcp-runtimes.mjs b/plugins/omo/scripts/build-bundled-mcp-runtimes.mjsindex b3ee50c9..e5711aa0 100644--- a/plugins/omo/scripts/build-bundled-mcp-runtimes.mjs+++ b/plugins/omo/scripts/build-bundled-mcp-runtimes.mjs@@ -13,6 +13,12 @@ const runtimes = [packageRoot: join(repoPackagesRoot, "lsp-tools-mcp"),requiredOutputs: ["dist/cli.js", "dist/tools.js"],},+ {+ label: "lsp-daemon",+ packageRoot: join(repoPackagesRoot, "lsp-daemon"),+ requiredOutputs: ["dist/cli.js", "dist/index.js", "dist/index.d.ts"],+ install: true,+ },{label: "ast-grep-mcp",packageRoot: join(repoPackagesRoot, "ast-grep-mcp"),@@ -41,6 +47,16 @@ function buildRuntime(runtime) {return;}+ if (runtime.install === true && !existsSync(join(runtime.packageRoot, "node_modules"))) {+ const install = spawnSync("npm", ["ci"], {+ cwd: runtime.packageRoot,+ shell: process.platform === "win32",+ stdio: "inherit",+ });+ if (install.error !== undefined) throw install.error;+ if (install.status !== 0) process.exit(install.status ?? 1);+ }+const result = spawnSync("npm", ["run", "build"], {cwd: runtime.packageRoot,shell: process.platform === "win32",diff --git a/plugins/omo/scripts/migrate-codex-config.mjs b/plugins/omo/scripts/migrate-codex-config.mjsindex e1ae907f..83a086e4 100644--- a/plugins/omo/scripts/migrate-codex-config.mjs+++ b/plugins/omo/scripts/migrate-codex-config.mjs@@ -6,6 +6,7 @@ import { pathToFileURL } from "node:url";import { FALLBACK_CATALOG, readModelCatalog } from "./migrate-codex-config/catalog.mjs";import { configPaths } from "./migrate-codex-config/config-paths.mjs";+import { forceDisableMultiAgentV2 } from "./migrate-codex-config/multi-agent-v2-guard.mjs";import { ensureCodexReasoningConfig as applyReasoningProfile, readRootSettings } from "./migrate-codex-config/root-settings.mjs";import { readState, resolveStatePath, writeState } from "./migrate-codex-config/state.mjs";@@ -41,12 +42,28 @@ export async function migrateCodexConfig({ env = process.env, cwd = process.cwd(export async function migrateConfigFile(configPath, { catalog = FALLBACK_CATALOG, previousState } = {}) {const before = await readConfig(configPath);const decision = shouldApplyCatalog(before, catalog, previousState);- if (!decision.apply) return { changed: false, written: readRootSettings(before), managed: decision.managed };- const after = ensureCodexReasoningConfig(before, catalog.current);- if (after === before) return { changed: false, written: catalog.current, managed: true };- await mkdir(dirname(configPath), { recursive: true });- await writeFile(configPath, `${after.trimEnd()}\n`);- return { changed: true, written: catalog.current, managed: true };++ let config = before;+ let reasoningApplied = false;++ if (decision.apply) {+ config = ensureCodexReasoningConfig(config, catalog.current);+ reasoningApplied = config !== before;+ }++ const afterMultiAgentGuard = forceDisableMultiAgentV2(config);+ const multiAgentChanged = afterMultiAgentGuard !== config;+ if (multiAgentChanged) config = afterMultiAgentGuard;++ const changed = reasoningApplied || multiAgentChanged;+ if (changed) {+ await mkdir(dirname(configPath), { recursive: true });+ await writeFile(configPath, `${config.trimEnd()}\n`);+ }++ const written = decision.apply ? catalog.current : readRootSettings(config);+ const managed = decision.apply ? true : decision.managed;+ return { changed, written, managed };}function shouldApplyCatalog(config, catalog, previousState) {diff --git a/plugins/omo/scripts/migrate-codex-config/multi-agent-v2-guard.mjs b/plugins/omo/scripts/migrate-codex-config/multi-agent-v2-guard.mjsnew file mode 100644index 00000000..ae2c0568--- /dev/null+++ b/plugins/omo/scripts/migrate-codex-config/multi-agent-v2-guard.mjs@@ -0,0 +1,104 @@+/**+ * Runtime migration: force `[features.multi_agent_v2]` to `enabled = false`.+ *+ * Runs on every Codex SessionStart (via auto-update's config migration) so+ * multi-agent V2 stays off regardless of how it was turned on: an+ * installer-forced `enabled = true`, a missing `enabled` key the runtime+ * would resolve per model, or the `[features]` boolean shorthand+ * `multi_agent_v2 = true` (removed here because a boolean key and a+ * `[features.multi_agent_v2]` table for the same name are conflicting TOML).+ *+ * Upstream basis: openai/codex#26753 — with the flag on, EVERY turn fails+ * with a 400 ("spawn_agent declares encrypted parameters but is not+ * configured for encrypted tool use by this model"), even on prompts that+ * never touch subagents. OpenAI closed it NOT_PLANNED stating V2 is under+ * development, not recommended, and bug reports are not accepted. Same+ * failure class still being reported (openai/codex#27205).+ */+const MANAGED_COMMENT_MARKER = "openai/codex#26753";+const MANAGED_DISABLE_COMMENT = [+ "# Managed by LazyCodex: multi_agent_v2 is re-disabled on every Codex session start",+ `# because enabling it fails every turn with HTTP 400 (${MANAGED_COMMENT_MARKER}).`,+ "# Opt out: LAZYCODEX_CONFIG_MIGRATION_DISABLED=1 (or OMO_CODEX_CONFIG_MIGRATION_DISABLED=1).",+ "",+].join("\n");++export function forceDisableMultiAgentV2(config) {+ let result = removeEnabledFeaturesShorthand(config);+ const section = findSection(result, "[features.multi_agent_v2]");++ if (!section) {+ if (hasDisabledFeaturesShorthand(result)) return result;+ return ensureManagedComment(appendDisabledSection(result));+ }++ const enabledTruePattern = /^(\s*)enabled\s*=\s*true[ \t]*(#[^\n]*)?$/m;+ if (enabledTruePattern.test(section.text)) {+ const patched = section.text.replace(enabledTruePattern, (_match, indent, comment) => comment ? `${indent}enabled = false ${comment}` : `${indent}enabled = false`);+ return ensureManagedComment(result.slice(0, section.start) + patched + result.slice(section.end));+ }++ if (/^\s*enabled\s*=\s*false[ \t]*(?:#[^\n]*)?$/m.test(section.text)) return result;++ const headerEnd = section.text.indexOf("\n");+ const insertAt = headerEnd === -1 ? section.text.length : headerEnd + 1;+ const patched = `${section.text.slice(0, insertAt)}${headerEnd === -1 ? "\n" : ""}enabled = false\n${section.text.slice(insertAt)}`;+ return ensureManagedComment(result.slice(0, section.start) + patched + result.slice(section.end));+}++function ensureManagedComment(config) {+ if (config.includes(MANAGED_COMMENT_MARKER)) return config;+ const section = findSection(config, "[features.multi_agent_v2]");+ if (!section) return config;+ return config.slice(0, section.start) + MANAGED_DISABLE_COMMENT + config.slice(section.start);+}++function removeEnabledFeaturesShorthand(config) {+ const section = findSection(config, "[features]");+ if (!section) return config;++ const shorthandPattern = /^\s*multi_agent_v2\s*=\s*true[ \t]*(?:#[^\n]*)?[ \t]*\n?/m;+ if (!shorthandPattern.test(section.text)) return config;++ const patched = section.text.replace(shorthandPattern, "");+ return config.slice(0, section.start) + patched + config.slice(section.end);+}++function hasDisabledFeaturesShorthand(config) {+ const section = findSection(config, "[features]");+ if (!section) return false;+ return /^\s*multi_agent_v2\s*=\s*false[ \t]*(?:#[^\n]*)?$/m.test(section.text);+}++function appendDisabledSection(config) {+ const trimmed = config.trimEnd();+ const prefix = trimmed.length === 0 ? "" : `${trimmed}\n\n`;+ return `${prefix}[features.multi_agent_v2]\nenabled = false\n`;+}++// Strips a trailing # comment from a TOML line fragment (best-effort; quoted keys containing # are out of scope).+function stripTrailingComment(line) {+ const idx = line.indexOf("#");+ return idx === -1 ? line : line.slice(0, idx).trim();+}++function findSection(config, headerLine) {+ const lines = config.match(/[^\n]*\n?|$/g) ?? [];+ let offset = 0;+ let start = -1;+ for (const line of lines) {+ if (line.length === 0) break;+ const trimmed = line.trim();+ if (start === -1) {+ if (stripTrailingComment(trimmed) === headerLine) start = offset;+ } else {+ const bare = stripTrailingComment(trimmed);+ if (bare.startsWith("[") && bare.endsWith("]")) {+ return { start, end: offset, text: config.slice(start, offset) };+ }+ }+ offset += line.length;+ }+ if (start === -1) return null;+ return { start, end: config.length, text: config.slice(start) };+}diff --git a/plugins/omo/scripts/sync-skills.mjs b/plugins/omo/scripts/sync-skills.mjsindex 6b8f4416..0f3db578 100644--- a/plugins/omo/scripts/sync-skills.mjs+++ b/plugins/omo/scripts/sync-skills.mjs@@ -24,21 +24,23 @@ This skill may include examples copied from the OpenCode harness. In Codex, do n| OpenCode example | Codex tool to use || --- | --- |-| \`call_omo_agent(subagent_type="explore", ...)\` | \`spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})\` |-| \`call_omo_agent(subagent_type="librarian", ...)\` | \`spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})\` |-| \`task(subagent_type="plan", ...)\` | \`spawn_agent({"task_name":"...","message":"TASK: act as a planning agent. ...","fork_turns":"none"})\` |-| \`task(subagent_type="oracle", ...)\` for final verification | \`spawn_agent({"task_name":"...","message":"TASK: act as a rigorous reviewer. ...","fork_turns":"none"})\` |-| \`task(category="...", ...)\` for implementation or QA | \`spawn_agent({"task_name":"...","message":"TASK: act as an implementation or QA worker. ...","fork_turns":"none"})\` |-| \`background_output(task_id="...")\` | \`wait_agent(...)\` for mailbox signals; after a timeout, run one \`list_agents\` check for the named child if reassurance is needed |-| \`team_*(...)\` | Use Codex native subagents plus \`send_message\`, \`followup_task\`, \`wait_agent\`, and \`close_agent\` |+| \`call_omo_agent(subagent_type="explore", ...)\` | \`multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","agent_type":"explorer","fork_context":false})\` |+| \`call_omo_agent(subagent_type="librarian", ...)\` | \`multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","agent_type":"librarian","fork_context":false})\` |+| \`task(subagent_type="plan", ...)\` | \`multi_agent_v1.spawn_agent({"message":"TASK: act as a planning agent. ...","agent_type":"plan","fork_context":false})\` |+| \`task(subagent_type="oracle", ...)\` for final verification | \`multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous reviewer. ...","agent_type":"codex-ultrawork-reviewer","fork_context":false})\` |+| \`task(category="...", ...)\` for implementation or QA | \`multi_agent_v1.spawn_agent({"message":"TASK: act as an implementation or QA worker. ...","fork_context":false})\` |+| \`background_output(task_id="...")\` | \`multi_agent_v1.wait_agent(...)\` for mailbox signals |+| \`team_*(...)\` | Use Codex native subagents via \`multi_agent_v1.spawn_agent\`, \`multi_agent_v1.send_input\`, \`multi_agent_v1.wait_agent\`, and \`multi_agent_v1.close_agent\` |-Codex full-history forks inherit parent context, so role-specific behavior must be described in a self-contained \`message\` and usually should use a non-full-history fork mode such as \`fork_turns="none"\`. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's \`message\`. If a code block below conflicts with this section, this section wins.+Role-specific behavior must be described in a self-contained \`message\`. Use \`fork_context: false\` to start the child with only the initial prompt (no parent history); use \`fork_context: true\` only when full parent history is truly required. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's \`message\`. OMO installs these selectable agent roles into \`~/.codex/agents/\`: \`explorer\`, \`librarian\`, \`plan\`, \`momus\`, \`metis\`, and \`codex-ultrawork-reviewer\` — pass the matching name as \`agent_type\` so the child gets that role's model and instructions. On \`multi_agent_v2\` sessions the same \`agent_type\` applies (the OMO installer exposes it) with \`fork_turns\` instead of \`fork_context\`. If the spawn tool exposes no \`agent_type\` parameter, omit it and describe the role inside \`message\`. If a code block below conflicts with this section, this section wins.-For work likely to exceed one wait cycle, require the child to send \`WORKING: <task> - <current phase>\` before long passes and \`BLOCKED: <reason>\` only when progress stops. A \`wait_agent\` timeout only means no new mailbox update arrived. Treat a running child or latest \`WORKING:\` message as alive. Do not use \`list_agents\` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly \`BLOCKED:\`, or no longer running.+For work likely to exceed one wait cycle, require the child to send \`WORKING: <task> - <current phase>\` before long passes and \`BLOCKED: <reason>\` only when progress stops. A \`multi_agent_v1.wait_agent\` timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly \`BLOCKED:\`, or no longer running.`;const codexCompatibilityEndMarkers = [+ "For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `multi_agent_v1.wait_agent` timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.\n\n",+ "Role-specific behavior must be described in a self-contained `message`. Use `fork_context: false` to start the child with only the initial prompt (no parent history); use `fork_context: true` only when full parent history is truly required. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.\n\n","For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `wait_agent` timeout only means no new mailbox update arrived. Treat a running child or latest `WORKING:` message as alive. Do not use `list_agents` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.\n\n","Codex full-history forks inherit parent context, so role-specific behavior must be described in a self-contained `message` and usually should use a non-full-history fork mode such as `fork_turns=\"none\"`. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.\n\n","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.\n\n",@@ -46,7 +48,7 @@ const codexCompatibilityEndMarkers = [];function findCodexCompatibilitySectionEnd(content, searchStart) {- const structuralEndPattern = /\n(?:---|#{1,6}\s)/g;+ const structuralEndPattern = /\n(?:---|export\s+const\s+|#{1,6}\s)/g;structuralEndPattern.lastIndex = searchStart;const structuralEnd = structuralEndPattern.exec(content);if (structuralEnd) return structuralEnd.index + 1;@@ -71,11 +73,21 @@ function removeCodexCompatibilityGuidance(content) {}}+function hasKnownGeneratedCodexCompatibilityGuidance(content, compatibilityIndex) {+ return codexCompatibilityEndMarkers.some((marker) => content.indexOf(marker, compatibilityIndex) !== -1);+}+export function insertCodexCompatibilityGuidance(content) {if (!opencodeOnlyOrchestrationPattern.test(content)) return content;const firstExampleIndex = content.search(opencodeOnlyOrchestrationPattern);const compatibilityIndex = content.indexOf("## Codex Harness Tool Compatibility");- if (compatibilityIndex !== -1 && compatibilityIndex < firstExampleIndex) return content;+ if (+ compatibilityIndex !== -1 &&+ compatibilityIndex < firstExampleIndex &&+ !hasKnownGeneratedCodexCompatibilityGuidance(content, compatibilityIndex)+ ) {+ return content;+ }const contentWithoutGuidance = removeCodexCompatibilityGuidance(content);diff --git a/plugins/omo/scripts/sync-version.mjs b/plugins/omo/scripts/sync-version.mjsnew file mode 100644index 00000000..46471288--- /dev/null+++ b/plugins/omo/scripts/sync-version.mjs@@ -0,0 +1,94 @@+#!/usr/bin/env node+import { readdir, readFile, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const scriptDir = dirname(fileURLToPath(import.meta.url));+const defaultPluginRoot = dirname(scriptDir);+const defaultRepoRoot = join(defaultPluginRoot, "..", "..", "..");++async function readJson(path) {+ return JSON.parse(await readFile(path, "utf8"));+}++async function writeJson(path, value) {+ await writeFile(path, `${JSON.stringify(value, null, "\t")}\n`);+}++function normalizeVersion(version) {+ if (typeof version !== "string") return "";+ return version.trim();+}++export async function resolveAuthoritativeVersion(options = {}) {+ const env = options.env ?? process.env;+ const explicit = normalizeVersion(options.version ?? env.LAZYCODEX_RELEASE_VERSION);+ if (explicit.length > 0) return explicit;++ const repoRoot = options.repoRoot ?? defaultRepoRoot;+ const rootVersion = normalizeVersion((await readJson(join(repoRoot, "package.json"))).version);+ if (rootVersion.length === 0) {+ throw new Error(`Cannot resolve authoritative version: ${join(repoRoot, "package.json")} has no version`);+ }+ return rootVersion;+}++async function stampJsonVersion(path, version) {+ let parsed;+ try {+ parsed = await readJson(path);+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return false;+ throw error;+ }+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false;+ if (!("version" in parsed)) return false;+ if (parsed.version === version) return false;+ parsed.version = version;+ await writeJson(path, parsed);+ return true;+}++async function collectComponentManifests(pluginRoot) {+ const componentsRoot = join(pluginRoot, "components");+ let entries;+ try {+ entries = await readdir(componentsRoot, { withFileTypes: true });+ } catch (error) {+ if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];+ throw error;+ }+ const manifests = [];+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ manifests.push(join(componentsRoot, entry.name, "package.json"));+ }+ return manifests;+}++export function manifestTargets(pluginRoot, componentManifests) {+ const omoCodexRoot = dirname(pluginRoot);+ return [+ join(omoCodexRoot, "package.json"),+ join(pluginRoot, "package.json"),+ join(pluginRoot, ".codex-plugin", "plugin.json"),+ ...componentManifests,+ ];+}++export async function syncVersion(options = {}) {+ const pluginRoot = options.pluginRoot ?? defaultPluginRoot;+ const version = options.version ?? (await resolveAuthoritativeVersion({ ...options, version: undefined }));+ const componentManifests = await collectComponentManifests(pluginRoot);+ const targets = manifestTargets(pluginRoot, componentManifests);+ const changed = [];+ for (const target of targets) {+ if (await stampJsonVersion(target, version)) changed.push(target);+ }+ return { version, targets, changed };+}++if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {+ const result = await syncVersion();+ console.log(`Synced OMO Codex manifests to version ${result.version} (${result.changed.length} updated)`);+}diff --git a/plugins/omo/skills/init-deep/SKILL.md b/plugins/omo/skills/init-deep/SKILL.mdindex d3c4b878..f7f43e2c 100644--- a/plugins/omo/skills/init-deep/SKILL.md+++ b/plugins/omo/skills/init-deep/SKILL.md@@ -8,17 +8,17 @@ This skill may include examples copied from the OpenCode harness. In Codex, do n| OpenCode example | Codex tool to use || --- | --- |-| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` |-| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})` |-| `task(subagent_type="plan", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a planning agent. ...","fork_turns":"none"})` |-| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent({"task_name":"...","message":"TASK: act as a rigorous reviewer. ...","fork_turns":"none"})` |-| `task(category="...", ...)` for implementation or QA | `spawn_agent({"task_name":"...","message":"TASK: act as an implementation or QA worker. ...","fork_turns":"none"})` |-| `background_output(task_id="...")` | `wait_agent(...)` for mailbox signals; after a timeout, run one `list_agents` check for the named child if reassurance is needed |-| `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |+| `call_omo_agent(subagent_type="explore", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","agent_type":"explorer","fork_context":false})` |+| `call_omo_agent(subagent_type="librarian", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","agent_type":"librarian","fork_context":false})` |+| `task(subagent_type="plan", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a planning agent. ...","agent_type":"plan","fork_context":false})` |+| `task(subagent_type="oracle", ...)` for final verification | `multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous reviewer. ...","agent_type":"codex-ultrawork-reviewer","fork_context":false})` |+| `task(category="...", ...)` for implementation or QA | `multi_agent_v1.spawn_agent({"message":"TASK: act as an implementation or QA worker. ...","fork_context":false})` |+| `background_output(task_id="...")` | `multi_agent_v1.wait_agent(...)` for mailbox signals |+| `team_*(...)` | Use Codex native subagents via `multi_agent_v1.spawn_agent`, `multi_agent_v1.send_input`, `multi_agent_v1.wait_agent`, and `multi_agent_v1.close_agent` |-Codex full-history forks inherit parent context, so role-specific behavior must be described in a self-contained `message` and usually should use a non-full-history fork mode such as `fork_turns="none"`. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.+Role-specific behavior must be described in a self-contained `message`. Use `fork_context: false` to start the child with only the initial prompt (no parent history); use `fork_context: true` only when full parent history is truly required. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. OMO installs these selectable agent roles into `~/.codex/agents/`: `explorer`, `librarian`, `plan`, `momus`, `metis`, and `codex-ultrawork-reviewer` — pass the matching name as `agent_type` so the child gets that role's model and instructions. On `multi_agent_v2` sessions the same `agent_type` applies (the OMO installer exposes it) with `fork_turns` instead of `fork_context`. If the spawn tool exposes no `agent_type` parameter, omit it and describe the role inside `message`. If a code block below conflicts with this section, this section wins.-For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `wait_agent` timeout only means no new mailbox update arrived. Treat a running child or latest `WORKING:` message as alive. Do not use `list_agents` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.+For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `multi_agent_v1.wait_agent` timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.# /init-deepdiff --git a/plugins/omo/skills/lcx-contribute-bug-fix/SKILL.md b/plugins/omo/skills/lcx-contribute-bug-fix/SKILL.mdindex c931381c..9137cfde 100644--- a/plugins/omo/skills/lcx-contribute-bug-fix/SKILL.md+++ b/plugins/omo/skills/lcx-contribute-bug-fix/SKILL.md@@ -30,7 +30,22 @@ Create a PR that includes:1. Read the user's bug report and identify the affected surface.2. Invoke `$omo:debugging` for the investigation. If only unqualified skill names are exposed, invoke `$debugging` and state that it is the OMO debugging skill.-3. Decide the target repository. If ownership is close, compare against upstream Codex source under `/tmp/openai-codex-source` before choosing.+3. Materialize the latest sources, then decide the target repository. Sync both checkouts on every run and compare them before choosing — a stale checkout routes the fix to the wrong repo:++```bash+sync_latest_source() {+ REPO="$1"; DEST="$2"+ if [ ! -d "$DEST/.git" ]; then+ gh repo clone "$REPO" "$DEST" -- --depth=1 \+ || git clone --depth=1 "https://github.com/$REPO" "$DEST"+ fi+ DEFAULT_BRANCH="$(git -C "$DEST" remote show origin | sed -n '/HEAD branch/s/.*: //p')"+ git -C "$DEST" fetch --depth=1 origin "$DEFAULT_BRANCH"+ git -C "$DEST" checkout -B "$DEFAULT_BRANCH" FETCH_HEAD+}+sync_latest_source code-yeongyu/lazycodex /tmp/lazycodex-source+sync_latest_source openai/codex /tmp/openai-codex-source+```4. Create a fresh temporary clone and branch. Do not modify the user's current repository for the target fix unless the current repository is itself the requested target and the user explicitly asked for local edits.```bashdiff --git a/plugins/omo/skills/lcx-doctor/SKILL.md b/plugins/omo/skills/lcx-doctor/SKILL.mdnew file mode 100644index 00000000..f4df6ed5--- /dev/null+++ b/plugins/omo/skills/lcx-doctor/SKILL.md@@ -0,0 +1,93 @@+---+name: lcx-doctor+description: "Diagnose LazyCodex and Codex CLI installation health against the latest sources. Use whenever the user asks for a doctor or health check, says LazyCodex, lazycodex-ai, omo-codex, or Codex behaves oddly after an install, update, or config change, suspects a stale, drifted, or broken setup, or wants the local install audited and compared with the latest LazyCodex and Codex code."+metadata:+ short-description: Diagnose LazyCodex/Codex install health against latest sources+---++# lcx-doctor++You are a LazyCodex install doctor. Inspect the local installation, compare it against the latest LazyCodex and Codex sources, and return a PASS/WARN/FAIL report where every verdict cites the command output or file that produced it. Diagnose only: the only writes you make are under `/tmp`. Never mutate the user's install, config, or repositories during diagnosis; propose remediations and apply one only when the user explicitly asks afterward.++Use GPT-5.5 style: outcome first, concise, evidence-bound.++## Required Workflow++1. Materialize the latest sources under `/tmp` first. Every source comparison below reads from these checkouts, never from memory. Re-sync on every run so a cached checkout cannot go stale:++```bash+sync_latest_source() {+ REPO="$1"; DEST="$2"+ if [ ! -d "$DEST/.git" ]; then+ gh repo clone "$REPO" "$DEST" -- --depth=1 \+ || git clone --depth=1 "https://github.com/$REPO" "$DEST"+ fi+ DEFAULT_BRANCH="$(git -C "$DEST" remote show origin | sed -n '/HEAD branch/s/.*: //p')"+ git -C "$DEST" fetch --depth=1 origin "$DEFAULT_BRANCH"+ git -C "$DEST" checkout -B "$DEFAULT_BRANCH" FETCH_HEAD+}+sync_latest_source code-yeongyu/lazycodex /tmp/lazycodex-source+sync_latest_source openai/codex /tmp/openai-codex-source+```++2. Inventory the installed surface. Resolve `CODEX_HOME` (default `~/.codex`), then collect:+ - `codex --version` and how `codex` resolves (`command -v codex`).+ - Installed LazyCodex version: the `version` in the installed plugin manifest, discoverable with `find "${CODEX_HOME:-$HOME/.codex}/plugins" -path '*/.codex-plugin/plugin.json'`. Installed plugins live under `$CODEX_HOME/plugins/cache/<marketplace>/<name>/<version>/`.+ - Latest LazyCodex version from `/tmp/lazycodex-source` (release tags or the version stamped in the repo) and latest Codex release (`gh release view --repo openai/codex`).+ - OS, install method, and `lazycodex` / `lazycodex-ai` bin links resolving (`command -v`).+3. Check config and wiring against the latest installer, not against assumptions. Read what the current installer under `/tmp/lazycodex-source` writes (installer sources live in the omo-codex package, e.g. `scripts/install/`), then verify the local equivalents:+ - `$CODEX_HOME/config.toml` exists and parses; LazyCodex-managed entries match what the latest installer would write.+ - Plugin payload present and non-empty: `hooks/hooks.json`, `skills/`, `.mcp.json`, components under the installed plugin root.+ - Stale project-local leftovers the installer now removes (e.g. `.codex/hooks.json`, `.codex/skills` in the project) are flagged, not deleted.+4. Probe the real surface. Run the built-in diagnostics first: `lazycodex doctor --json` (add `--verbose` when a check needs deeper traces) and fold its results into the report. A missing or crashing `lazycodex doctor` is itself a FAIL finding, not a reason to skip probing — fall back to `codex --version` plus a trivial non-interactive invocation that loads the plugin. Capture stderr verbatim; a clean exit with warnings is WARN, not PASS.+5. Compare for drift. Where installed bundled files differ from the same files at the installed version, or the latest source renamed or removed something the local config still references, record it with both paths.+6. Check whether each FAIL is already known: `gh issue list --repo code-yeongyu/lazycodex --search "<short symptom>" --state open` (and `openai/codex` when the failure points upstream). Link matches in the report instead of re-diagnosing from scratch.+7. If a probe fails and the cause is not explained by config or source comparison, invoke `$omo:debugging` for the investigation. If Codex exposes only unqualified skill names in the current session, invoke `$debugging` and state that it is the OMO debugging skill.+8. Emit the report.++## Doctor Report Template++```markdown+## LazyCodex Doctor Report++### Summary+[One sentence: healthy, degraded, or broken — and the single most important next action.]++### Environment+- LazyCodex installed / latest:+- Codex CLI installed / latest:+- CODEX_HOME:+- OS / install method:++### Checks+| Check | Verdict | Evidence |+| --- | --- | --- |+| Versions current | PASS/WARN/FAIL | [command output or file:line] |+| config.toml integrity | PASS/WARN/FAIL | [evidence] |+| Plugin payload wiring | PASS/WARN/FAIL | [evidence] |+| Bin links / aliases | PASS/WARN/FAIL | [evidence] |+| Runtime probe | PASS/WARN/FAIL | [evidence] |+| Drift vs latest source | PASS/WARN/FAIL | [evidence, citing /tmp/lazycodex-source or /tmp/openai-codex-source paths] |++### Remediations+1. [Most important fix first: exact command or config edit, and what it resolves.]++### Known Issues Matched+- [issue URL — or "none found"]+```++## Follow-up Routing++- Local misconfiguration or stale install: give the remediation; reinstalling via the standard LazyCodex install command is the default fix for payload drift.+- Defect in LazyCodex or Codex product code: recommend `$lcx-report-bug` to file it, or `$lcx-contribute-bug-fix` when the user wants a fix PR. Both reuse the `/tmp` checkouts you already synced.++## Stop Conditions++Ask one narrow question only when a finding requires a destructive decision, such as deleting user-edited config or downgrading a version.++Do not:++- mutate config, installs, or repositories during diagnosis+- report a verdict without captured evidence+- compare against remembered source layout instead of `/tmp/lazycodex-source` and `/tmp/openai-codex-source`+- declare healthy while any probe output was never captureddiff --git a/plugins/omo/skills/lcx-doctor/agents/openai.yaml b/plugins/omo/skills/lcx-doctor/agents/openai.yamlnew file mode 100644index 00000000..8a0c9109--- /dev/null+++ b/plugins/omo/skills/lcx-doctor/agents/openai.yaml@@ -0,0 +1,11 @@+interface:+ display_name: "lcx-doctor (omo)"+ short_description: "Diagnose LazyCodex/Codex install health against latest sources"+ search_terms:+ - "lcx-doctor"+ - "lazycodex doctor"+ - "lazycodex health check"+ - "codex doctor"+ - "lazycodex install broken"+ - "omo-codex diagnose"+ default_prompt: "Use $lcx-doctor to sync the latest LazyCodex and Codex sources into /tmp, inventory the local installation, compare versions, config, and wiring against the latest sources, probe the real surface, and report PASS/WARN/FAIL findings with evidence and remediations."diff --git a/plugins/omo/skills/lcx-report-bug/SKILL.md b/plugins/omo/skills/lcx-report-bug/SKILL.mdindex bd7b3307..dfabde3f 100644--- a/plugins/omo/skills/lcx-report-bug/SKILL.md+++ b/plugins/omo/skills/lcx-report-bug/SKILL.md@@ -33,24 +33,28 @@ Create or prepare a GitHub issue or PR that includes:1. Read the user's bug report and identify the affected surface: LazyCodex installer, Codex plugin, skill, hook, MCP, CLI alias, GitHub marketplace sync, or web/docs.2. Invoke `$omo:debugging` for the investigation. If Codex exposes only unqualified skill names in the current session, invoke `$debugging` and state that it is the OMO debugging skill.-3. Materialize upstream Codex source under `/tmp` before deciding ownership:+3. Materialize the latest LazyCodex and upstream Codex sources under `/tmp` before deciding ownership. Re-sync on every run so a cached checkout cannot go stale — stale source produces wrong routing and dead line references:```bash-CODEX_SRC="/tmp/openai-codex-source"-if [ ! -d "$CODEX_SRC/.git" ]; then- gh repo clone openai/codex "$CODEX_SRC" -- --depth=1-else- git -C "$CODEX_SRC" fetch --depth=1 origin-fi+sync_latest_source() {+ REPO="$1"; DEST="$2"+ if [ ! -d "$DEST/.git" ]; then+ gh repo clone "$REPO" "$DEST" -- --depth=1 \+ || git clone --depth=1 "https://github.com/$REPO" "$DEST"+ fi+ DEFAULT_BRANCH="$(git -C "$DEST" remote show origin | sed -n '/HEAD branch/s/.*: //p')"+ git -C "$DEST" fetch --depth=1 origin "$DEFAULT_BRANCH"+ git -C "$DEST" checkout -B "$DEFAULT_BRANCH" FETCH_HEAD+}+sync_latest_source code-yeongyu/lazycodex /tmp/lazycodex-source+sync_latest_source openai/codex /tmp/openai-codex-source```--If `gh` is unavailable, use `git clone --depth=1 https://github.com/openai/codex "$CODEX_SRC"`.4. Follow the debugging skill far enough to gather runtime evidence:- form at least three plausible hypotheses- run the smallest reproduction that exercises the real surface- confirm the root cause by observing the failing state- identify the minimal fix path or maintainer action-5. Compare local LazyCodex evidence with `/tmp/openai-codex-source` before choosing the target repo. Cite exact files, commands, logs, or source paths that support the routing decision.+5. Compare runtime evidence with both `/tmp/lazycodex-source` and `/tmp/openai-codex-source` before choosing the target repo. Cite exact files, commands, logs, or source paths that support the routing decision.6. Choose the target repo:- Use `code-yeongyu/lazycodex` when the bug is in LazyCodex integration, distribution, bundled plugin code, skills, hooks, MCP wiring, installer behavior, aliases, marketplace sync, docs, or any behavior that disappears in clean upstream Codex.- Use `openai/codex` when the bug reproduces in clean upstream Codex without LazyCodex, or the failing behavior comes from Codex CLI core, plugin API contracts, sandboxing, approvals, config loading, or built-in tool behavior.@@ -106,7 +110,7 @@ Write the issue body in English and keep it direct:## Repository Decision- Target repository:- Why this belongs there:-- LazyCodex evidence:+- LazyCodex evidence (runtime + `/tmp/lazycodex-source`):- Upstream Codex source evidence from `/tmp/openai-codex-source`:## Reproduction@@ -150,7 +154,7 @@ Use this when a PR is the right artifact:## Repository Decision- Target repository:- Why this belongs there:-- LazyCodex evidence:+- LazyCodex evidence (runtime + `/tmp/lazycodex-source`):- Upstream Codex source evidence from `/tmp/openai-codex-source`:## Root Cause@@ -227,6 +231,6 @@ Do not file:- a vague issue without reproduction steps- an issue that claims a root cause not supported by runtime evidence- a duplicate when commenting on an existing issue is enough-- an upstream Codex issue without checking `/tmp/openai-codex-source`+- an issue without checking the latest `/tmp/lazycodex-source` and `/tmp/openai-codex-source` checkouts- a LazyCodex issue when the bug is proven to reproduce in clean upstream Codex- a fix PR without a concrete branch, implemented fix, and verification resultdiff --git a/plugins/omo/skills/lsp-setup/SKILL.md b/plugins/omo/skills/lsp-setup/SKILL.mdnew file mode 100644index 00000000..4a18ab57--- /dev/null+++ b/plugins/omo/skills/lsp-setup/SKILL.md@@ -0,0 +1,139 @@+---+name: lsp-setup+description: "Configure a Language Server (LSP) for a specific language so editor/agent tooling — diagnostics, go-to-definition, find-references, rename — works. Use when you need to: configure LSP, lsp setup, set up or install a language server, fix 'no LSP server configured' / 'server not installed', choose between servers (basedpyright vs pyright vs ty vs ruff), or wire .codex/lsp-client.json / .opencode/lsp.json. 언어서버 설정. Routes by file extension to references/<language>/README.md for the exact builtin server, per-OS install commands (macOS/Linux/Windows), config snippets for both config files, initialization options, alternatives, and troubleshooting. Ships scripts: detect-lsp.ts (scan a project for languages + each server's install/config status) and verify-lsp.ts (run a real diagnostics roundtrip). Covers typescript, python, go, rust, c/c++, java, kotlin, c#/razor, swift, ruby, php, dart, elixir, zig, lua, bash, yaml, terraform, haskell, julia."+---++# LSP Setup++Configure the right Language Server for a project so the `lsp` MCP tools+(`diagnostics`, `goto_definition`, `find_references`, `symbols`, `rename`)+actually work. This skill is an index: detect what a project needs, install the+server, write the config, then verify with a real roundtrip.++The list of servers we ship as **builtin** is the source of truth in+`packages/lsp-tools-mcp/src/lsp/server-definitions.ts` (`BUILTIN_SERVERS` ++`LSP_INSTALL_HINTS`). The per-language references below mirror it.++---++## PHASE 0 — LANGUAGE GATE (run first)++Identify the language from the file extension, then **read the matching+reference before installing or configuring anything**.++| Extension(s) | Reference |+|---|---|+| `.ts .tsx .js .jsx .mjs .cjs .mts .cts .vue .svelte .astro` | `references/typescript/README.md` |+| `.py .pyi` | `references/python/README.md` |+| `.go` | `references/go/README.md` |+| `.rs` | `references/rust/README.md` |+| `.c .cpp .cc .cxx .h .hpp .hh .hxx` | `references/c-cpp/README.md` |+| `.java` | `references/java/README.md` |+| `.kt .kts` | `references/kotlin/README.md` |+| `.cs .razor .cshtml` | `references/csharp/README.md` |+| `.swift` | `references/swift/README.md` |+| `.rb .rake .gemspec .ru` | `references/ruby/README.md` |+| `.php` | `references/php/README.md` |+| `.dart` | `references/dart/README.md` |+| `.ex .exs` | `references/elixir/README.md` |+| `.zig .zon` | `references/zig/README.md` |+| `.lua` | `references/lua/README.md` |+| `.sh .bash .zsh .ksh` | `references/bash/README.md` |+| `.yaml .yml` | `references/yaml/README.md` |+| `.tf .tfvars` | `references/terraform/README.md` |+| `.hs .lhs` | `references/haskell/README.md` |+| `.jl` | `references/julia/README.md` |++---++## WORKFLOW — detect → install → configure → verify++### 1. Detect++Scan the project to see which languages are present and whether each server is+installed and configured:++```bash+bun scripts/detect-lsp.ts <projectDir> # human report (default: cwd)+bun scripts/detect-lsp.ts <projectDir> --json+```++For each detected language it prints the builtin server id, the executable it+needs on `PATH`, whether that executable is installed, an install hint, and+whether a project config file already references it.++### 2. Install++Open `references/<language>/README.md` and run the install command for your OS.+Then confirm the executable resolves:++```bash+command -v <server-executable> # e.g. typescript-language-server, gopls, rust-analyzer+```++### 3. Configure++Most builtin servers need **no config** — they are resolved automatically by+file extension. Write config only to: pick between competing servers, set a+`priority`, pass `initialization` options, override `extensions`, set `env`, or+`disable` a server.++Two project-scoped config files, **identical JSON shape**:++- Codex harness → `.codex/lsp-client.json` (user: `~/.codex/lsp-client.json`)+- OpenCode/omo harness → `.opencode/lsp.json` (also `.omo/lsp.json`)++```jsonc+{+ "lsp": {+ "<server-id>": {+ "command": ["<bin>", "<args>"], // optional for builtin ids (supplied automatically)+ "extensions": [".ext"], // optional override+ "priority": 100, // higher wins when several servers match an extension+ "initialization": { }, // server-specific initializationOptions+ "env": { "KEY": "value" }, // optional+ "disabled": false // set true to turn a server off+ }+ }+}+```++Rules enforced by `config-loader.ts`:++- In a **project** config (`.codex/lsp-client.json`, `.opencode/lsp.json`) an+ entry whose id is a **builtin** server inherits `command` automatically — you+ only override `extensions` / `priority` / `initialization`. A non-builtin id+ in a project config is **ignored**.+- To define a **fully custom** (non-builtin) server with its own `command`, put+ it in the **user** config (`~/.codex/lsp-client.json`, or the path set by+ `LSP_TOOLS_MCP_USER_CONFIG`), where `command` + `extensions` are honored.+- Project entries win over user entries; both win over builtin defaults.++Each language reference gives a ready-to-paste snippet.++### 4. Verify++Run a real diagnostics roundtrip against a source file. This spawns the server,+opens the file, requests diagnostics, and reports `OK`/`FAIL`:++```bash+bun scripts/verify-lsp.ts <path/to/file.ext>+bun scripts/verify-lsp.ts <file> --timeout=90000+```++`OK` = the server started and answered. `FAIL: language server not installed`+= go back to step 2. Other `FAIL` text carries the server/startup error.+`SKIP` = the engine source could not be located; run from inside the omo+repo/worktree, or call the `lsp` MCP `diagnostics` tool directly.++---++## Scripts++| Script | Purpose |+|---|---|+| `scripts/detect-lsp.ts` | Scan a directory; per detected language report server id, install status, install hint, config status. `--json` for machine output. |+| `scripts/verify-lsp.ts` | Real LSP diagnostics roundtrip for one file via the `lsp-tools-mcp` engine; `OK`/`FAIL`/`SKIP` + exit code 0/1/3. |+| `scripts/lsp-server-table.ts` | Embedded snapshot of the primary builtin server per language (mirrors `server-definitions.ts`). |++Run with [Bun](https://bun.sh): `curl -fsSL https://bun.sh/install | bash`.diff --git a/plugins/omo/skills/lsp-setup/references/bash/README.md b/plugins/omo/skills/lsp-setup/references/bash/README.mdnew file mode 100644index 00000000..80f07bbc--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/bash/README.md@@ -0,0 +1,60 @@+# Bash — LSP setup++- **Builtin server:** `bash` — `bash-language-server start`+- **Extensions:** `.sh .bash .zsh .ksh`+- **Install hint:** `npm install -g bash-language-server`++An alias id `bash-ls` exists with the identical command; either id works.++## Install++- **macOS:** `npm install -g bash-language-server`+- **Linux:** `npm install -g bash-language-server`+- **Windows:** `npm install -g bash-language-server` (PowerShell)++For real diagnostics, also install `shellcheck`:++- **macOS:** `brew install shellcheck`+- **Linux:** `apt install shellcheck` (or `dnf install ShellCheck`)+- **Windows:** `scoop install shellcheck`++Confirm it resolves:++```bash+command -v bash-language-server+command -v shellcheck+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "bash": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. `bash-language-server` discovers `shellcheck` on PATH automatically. To point at a non-PATH binary, export `SHELLCHECK_PATH` via `env`:++```json+{ "lsp": { "bash": { "env": { "SHELLCHECK_PATH": "/opt/bin/shellcheck" } } } }+```++## Alternatives++- `shellcheck` standalone as a linter-only flow (no LSP).+- `shfmt` for formatting (complements, does not replace, the LSP).++## Troubleshooting+- **PATH:** `bash-language-server` on PATH; reopen shell after `npm -g` install.+- **No diagnostics:** `shellcheck` missing — diagnostics are powered by it; install and reopen.+- **Wrong shell dialect:** `.zsh`/`.ksh` are linted as bash; shellcheck may flag shell-specific syntax.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.sh+```diff --git a/plugins/omo/skills/lsp-setup/references/c-cpp/README.md b/plugins/omo/skills/lsp-setup/references/c-cpp/README.mdnew file mode 100644index 00000000..17abb311--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/c-cpp/README.md@@ -0,0 +1,61 @@+# C / C++ — LSP setup++- **Builtin server:** `clangd` — `clangd --background-index --clang-tidy`+- **Extensions:** `.c .cpp .cc .cxx .c++ .h .hpp .hh .hxx .h++`+- **Install hint:** `https://clangd.llvm.org/installation`++## Install++- **macOS:** `brew install llvm` (clangd ships in the LLVM keg; add its `bin` to PATH)+- **Linux:** `apt install clangd` (Debian/Ubuntu); use your distro package elsewhere+- **Windows:** install LLVM from `https://releases.llvm.org` or `winget install LLVM.LLVM`++See `https://clangd.llvm.org/installation` for other platforms.++Confirm it resolves:++```bash+command -v clangd+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "clangd": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. clangd reads flags from a project `.clangd` file rather+than initializationOptions. The builtin command already passes+`--background-index --clang-tidy`.++## Compile commands++clangd needs a `compile_commands.json` at the project root (or in `build/`) for+accurate diagnostics and cross-file navigation. Generate it with:++- **CMake:** `cmake -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON` (symlink/copy `build/compile_commands.json` to the root)+- **Make / other:** `bear -- make`++Without it, clangd falls back to heuristic flags and reports spurious errors.++## Alternatives++None builtin. `ccls` exists as a third-party server but is not builtin — it would+need a custom `command` in the USER config.++## Troubleshooting+- **PATH:** `clangd` must be on PATH; reopen shell after install. Homebrew LLVM is keg-only — add `$(brew --prefix llvm)/bin` to PATH.+- **Spurious "file not found" / unknown flags:** missing or stale `compile_commands.json` — regenerate it after changing the build.+- **Header-only diagnostics wrong:** ensure the header's translation unit appears in the compile database, or add a `.clangd` `CompileFlags` block.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.cpp+```diff --git a/plugins/omo/skills/lsp-setup/references/csharp/README.md b/plugins/omo/skills/lsp-setup/references/csharp/README.mdnew file mode 100644index 00000000..b59b2bd8--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/csharp/README.md@@ -0,0 +1,71 @@+# C# — LSP setup++- **Builtin server:** `csharp` — `csharp-ls`+- **Extensions:** `.cs`+- **Install hint:** `dotnet tool install -g csharp-ls`++## Install++Requires the **.NET SDK**. Install the tool globally:++- **macOS:** `dotnet tool install -g csharp-ls`+- **Linux:** `dotnet tool install -g csharp-ls`+- **Windows:** `dotnet tool install -g csharp-ls`++Global .NET tools land in `~/.dotnet/tools` — ensure that directory is on PATH (Windows: `%USERPROFILE%\.dotnet\tools`).++Confirm it resolves:++```bash+command -v csharp-ls+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "csharp": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. `csharp-ls` picks up the nearest `.sln` or `.csproj`; keep the solution restorable (`dotnet restore`).++## Razor / Blazor++Razor and Blazor files use a separate builtin server:++- **Builtin server:** `razor` — `roslyn-language-server --stdio`+- **Extensions:** `.razor .cshtml`+- **Install hint:** `dotnet tool install -g roslyn-language-server --prerelease` (requires **v5.8.0+**; see [dotnet/razor](https://github.com/dotnet/razor))++```bash+dotnet tool install -g roslyn-language-server --prerelease+command -v roslyn-language-server+```++Enable it in a project/user config:++```json+{ "lsp": { "razor": { } } }+```++## Alternatives++- **OmniSharp** — legacy C# language server (not builtin). Still works but is being superseded by the Roslyn-based servers; prefer `csharp-ls` / `roslyn-language-server`.++## Troubleshooting++- **PATH:** `csharp-ls` / `roslyn-language-server` on PATH (`~/.dotnet/tools`); reopen shell after install.+- **No .NET SDK:** install the SDK (not just the runtime) before installing the tool.+- **No symbols:** run `dotnet restore`; an unrestored solution yields empty results.+- **Razor needs v5.8.0+:** older `roslyn-language-server` builds lack the `--stdio` Razor support — install with `--prerelease`.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/File.cs+```diff --git a/plugins/omo/skills/lsp-setup/references/dart/README.md b/plugins/omo/skills/lsp-setup/references/dart/README.mdnew file mode 100644index 00000000..63757d57--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/dart/README.md@@ -0,0 +1,48 @@+# Dart — LSP setup++- **Builtin server:** `dart` — `dart language-server --lsp`+- **Extensions:** `.dart`+- **Install hint:** `Included with the Dart/Flutter SDK`++## Install++The language server ships inside the Dart SDK (and the Flutter SDK, which bundles Dart). There is no separate package to install — just put `dart` (or `flutter`) on PATH.++- **macOS:** `brew install dart` (or install Flutter and use its bundled `dart`)+- **Linux:** install the Dart SDK from your package manager / `https://dart.dev/get-dart`, or install Flutter+- **Windows:** install the Dart SDK or Flutter SDK and add its `bin` to PATH++Confirm it resolves:++```bash+command -v dart+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "dart": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required.++## Alternatives++None.++## Troubleshooting+- **PATH:** `dart` must be on PATH; reopen the shell after installing the SDK. Flutter users: ensure `<flutter>/bin/cache/dart-sdk/bin` or the Flutter `bin` is exported.+- **Flutter vs Dart:** if you only have Flutter installed, the bundled `dart` works — make sure Flutter's `bin` is on PATH rather than relying on a separate Dart install.+- **SDK out of date:** run `dart --version` / `flutter upgrade` if analysis behaves oddly on newer language features.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.dart+```diff --git a/plugins/omo/skills/lsp-setup/references/elixir/README.md b/plugins/omo/skills/lsp-setup/references/elixir/README.mdnew file mode 100644index 00000000..b85de4a9--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/elixir/README.md@@ -0,0 +1,51 @@+# Elixir — LSP setup++- **Builtin server:** `elixir-ls` — `elixir-ls`+- **Extensions:** `.ex .exs`+- **Install hint:** `https://github.com/elixir-lsp/elixir-ls`++## Install++ElixirLS needs Erlang/OTP and Elixir installed first. Build the release from+`https://github.com/elixir-lsp/elixir-ls` and put the `elixir-ls` launcher script on PATH.++- **macOS:** `brew install elixir-ls` (Homebrew provides the launcher), or build the release manually+- **Linux:** clone elixir-ls, run `mix deps.get && mix compile && mix elixir_ls.release2 -o release`, then add `release/` to PATH+- **Windows:** build the release and add the `release` dir (use the `.bat` launcher) to PATH++Confirm it resolves:++```bash+command -v elixir-ls+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "elixir-ls": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required.++## Alternatives++- **lexical** (not builtin): `lexical` — fast, modern alternative LSP.+- **next-ls** (not builtin): `nextls --stdio` — from the elixir-tools project.++## Troubleshooting+- **PATH:** `elixir-ls` must be on PATH; reopen the shell after install.+- **asdf users:** the launcher is a shim — after `asdf install`, run `asdf reshim elixir` so the `elixir-ls` shim resolves, and ensure the Erlang/Elixir versions match the build.+- **First start is slow:** ElixirLS compiles your deps on first run; initial diagnostics can take a while on large projects.+- **OTP mismatch:** build elixir-ls with the same Erlang/Elixir versions you use for the project to avoid bytecode errors.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.ex+```diff --git a/plugins/omo/skills/lsp-setup/references/go/README.md b/plugins/omo/skills/lsp-setup/references/go/README.mdnew file mode 100644index 00000000..f25dd0fb--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/go/README.md@@ -0,0 +1,57 @@+# Go — LSP setup++- **Builtin server:** `gopls` — `gopls`+- **Extensions:** `.go`+- **Install hint:** `go install golang.org/x/tools/gopls@latest`++## Install++- **macOS:** `go install golang.org/x/tools/gopls@latest` (or `brew install gopls`)+- **Linux:** `go install golang.org/x/tools/gopls@latest`+- **Windows:** `go install golang.org/x/tools/gopls@latest`++Requires the Go toolchain. `go install` drops the binary in `$GOPATH/bin`+(default `~/go/bin`) — that directory must be on PATH.++```bash+export PATH="$PATH:$(go env GOPATH)/bin"+```++Confirm it resolves:++```bash+command -v gopls+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "gopls": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. To enable extra analyses or staticcheck:++```json+{ "lsp": { "gopls": { "initialization": { "staticcheck": true } } } }+```++## Alternatives++None — `gopls` is the official and de facto sole Go language server.++## Troubleshooting+- **PATH:** `gopls` must be on PATH; ensure `$(go env GOPATH)/bin` is exported, then reopen the shell.+- **No diagnostics / "no required module":** open the directory containing `go.mod` as the workspace root. Outside a module, gopls degrades. Run `go mod tidy` if dependencies are unresolved.+- **Stale toolchain:** reinstall with `go install golang.org/x/tools/gopls@latest` after upgrading Go.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.go+```diff --git a/plugins/omo/skills/lsp-setup/references/haskell/README.md b/plugins/omo/skills/lsp-setup/references/haskell/README.mdnew file mode 100644index 00000000..4cbcc304--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/haskell/README.md@@ -0,0 +1,57 @@+# Haskell — LSP setup++- **Builtin server:** `haskell-language-server` — `haskell-language-server-wrapper --lsp`+- **Extensions:** `.hs .lhs`+- **Install hint:** `ghcup install hls`++The `-wrapper` binary detects your project's GHC version and dispatches to the matching HLS build.++## Install++- **macOS:** `ghcup install hls` (install ghcup via `brew install ghcup` or the official script)+- **Linux:** `ghcup install hls` (ghcup script from https://www.haskell.org/ghcup/)+- **Windows:** `ghcup install hls` (ghcup is installed via the Windows installer / PowerShell bootstrap)++HLS needs a working GHC plus Cabal and/or Stack. Install a matching toolchain first:++```bash+ghcup install ghc+ghcup install cabal+```++Confirm it resolves:++```bash+command -v haskell-language-server-wrapper+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "haskell-language-server": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. Per-project plugin/formatter settings normally live in a `hie.yaml` (cradle) and `.haskell-language-server` files rather than init options.++## Alternatives++- `ghcide` (the core HLS engine, standalone) — largely superseded by HLS.+- `hlint` standalone for lint-only checks; `ormolu`/`fourmolu` for formatting.++## Troubleshooting+- **PATH:** `haskell-language-server-wrapper` on PATH; reopen shell after `ghcup install`.+- **GHC mismatch:** the installed HLS must support your project's GHC version — run `ghcup install hls` for that GHC, or align GHC to a supported one.+- **No cradle:** multi-package repos may need a `hie.yaml`; generate one with `gen-hie > hie.yaml`.+- **Slow first load:** HLS compiles dependencies on first open; let it finish indexing.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.hs+```diff --git a/plugins/omo/skills/lsp-setup/references/java/README.md b/plugins/omo/skills/lsp-setup/references/java/README.mdnew file mode 100644index 00000000..0cb34f8e--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/java/README.md@@ -0,0 +1,57 @@+# Java — LSP setup++- **Builtin server:** `jdtls` — `jdtls`+- **Extensions:** `.java`+- **Install hint:** `https://github.com/eclipse-jdtls/eclipse.jdt.ls`++## Install++- **macOS:** `brew install jdtls`+- **Linux:** Download from [eclipse-jdtls/eclipse.jdt.ls](https://github.com/eclipse-jdtls/eclipse.jdt.ls) releases, extract, and wrap the launcher as `jdtls` on PATH (some distros package it as `jdtls`/`jdt-language-server`).+- **Windows:** Download the release archive and add the `jdtls` launcher (`bin/jdtls.bat` or the Python wrapper) to PATH.++Requires a **JDK 17+** to run the language server itself (the project may target an older Java version).++Confirm it resolves:++```bash+command -v jdtls+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "jdtls": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++jdtls maintains a per-project **workspace data directory** and the **first index is slow** (it resolves the full classpath and builds). Point `JAVA_HOME` at a JDK 17+ if `jdtls` cannot find one:++```json+{ "lsp": { "jdtls": { "env": { "JAVA_HOME": "/Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home" } } } }+```++Most settings (runtimes, format, import order) are passed via `settings.java.*` initialization options; defaults work for Maven/Gradle projects with a standard layout.++## Alternatives++- **No mainstream alternative.** `jdtls` (Eclipse JDT Language Server) is the de-facto standard and powers the official VS Code Java extension.++## Troubleshooting++- **PATH:** `jdtls` on PATH; reopen shell after install.+- **No JDK found:** server exits immediately — set `JAVA_HOME` to a JDK 17+.+- **Slow / no completions at first:** the initial classpath index can take a minute or more on large Maven/Gradle projects; wait for it to finish.+- **Stale state:** delete the jdtls workspace data dir to force a clean re-index if results go wrong after big dependency changes.+- **Build tool required:** keep `pom.xml` / `build.gradle` valid; a broken build descriptor breaks symbol resolution.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/File.java+```diff --git a/plugins/omo/skills/lsp-setup/references/julia/README.md b/plugins/omo/skills/lsp-setup/references/julia/README.mdnew file mode 100644index 00000000..9fc80cfe--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/julia/README.md@@ -0,0 +1,60 @@+# Julia — LSP setup++- **Builtin server:** `julials` — `julia --startup-file=no --history-file=no -e using LanguageServer; runserver()`+- **Extensions:** `.jl`+- **Install hint:** `julia -e 'using Pkg; Pkg.add("LanguageServer")'`++The PATH executable is `julia`; LanguageServer.jl is launched through the `-e` snippet, not as its own binary.++## Install++Install Julia (juliaup recommended), then add the `LanguageServer` package:++- **macOS:** `brew install juliaup && juliaup add release`+- **Linux:** `curl -fsSL https://install.julialang.org | sh` (installs juliaup)+- **Windows:** `winget install julia -s msstore` (installs juliaup)++Then add the package — ideally into a shared `@lsp` environment so it is not tied to one project:++```bash+julia --project=@lsp -e 'using Pkg; Pkg.add("LanguageServer")'+```++Confirm Julia resolves (the LSP binary IS `julia`):++```bash+command -v julia+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "julials": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. To pin which environment hosts LanguageServer.jl, set `JULIA_PROJECT` (or `JULIA_DEPOT_PATH`) via `env`:++```json+{ "lsp": { "julials": { "env": { "JULIA_PROJECT": "@lsp" } } } }+```++## Alternatives++- The VS Code Julia extension bundles the same LanguageServer.jl server.++## Troubleshooting+- **PATH:** `julia` on PATH (not a `julials` binary); reopen shell after juliaup install.+- **First run precompiles — be patient:** the initial launch compiles LanguageServer.jl and may take minutes with no output; do not kill it. Subsequent starts are fast.+- **Package not found:** `LanguageServer` must be installed in the environment the server runs in (e.g. `@lsp`); add it there and set `JULIA_PROJECT`.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.jl+```diff --git a/plugins/omo/skills/lsp-setup/references/kotlin/README.md b/plugins/omo/skills/lsp-setup/references/kotlin/README.mdnew file mode 100644index 00000000..83761e60--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/kotlin/README.md@@ -0,0 +1,59 @@+# Kotlin — LSP setup++- **Builtin server:** `kotlin-ls` — `kotlin-lsp`+- **Extensions:** `.kt .kts`+- **Install hint:** `https://github.com/Kotlin/kotlin-lsp`++## Install++The official **JetBrains Kotlin LSP** is pre-release. Download a build from the [Kotlin/kotlin-lsp](https://github.com/Kotlin/kotlin-lsp) releases and put the `kotlin-lsp` launcher on PATH.++- **macOS:** Download the release archive, extract, then symlink the launcher: `ln -s /path/to/kotlin-lsp/kotlin-lsp.sh /usr/local/bin/kotlin-lsp`+- **Linux:** Same as macOS — extract the release and place/symlink `kotlin-lsp` on PATH.+- **Windows:** Extract the release and add the directory containing `kotlin-lsp.bat` to PATH (invoke as `kotlin-lsp`).++Requires a **JDK** on the machine to run the server.++Confirm it resolves:++```bash+command -v kotlin-lsp+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "kotlin-ls": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. If `kotlin-lsp` cannot find a Java runtime, set `JAVA_HOME`:++```json+{ "lsp": { "kotlin-ls": { "env": { "JAVA_HOME": "/Library/Java/JavaVirtualMachines/temurin-17.jdk/Contents/Home" } } } }+```++The server resolves classpath from Gradle/Maven; keep the build descriptor importable.++## Alternatives++- **`fwcd/kotlin-language-server`** — older community server (not builtin). Still usable but less actively maintained than the official JetBrains one.++## Troubleshooting++- **PATH:** `kotlin-lsp` on PATH; reopen shell after install.+- **Pre-release churn:** the JetBrains server is early; pin a known-good release and expect occasional breakage.+- **No JDK:** server fails to start — install a JDK and/or set `JAVA_HOME`.+- **Slow first import:** Gradle resolution on first open can be slow on large projects; let it complete.+- **`.kts` scripts:** build/script files resolve more slowly than `.kt` sources; this is expected.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/File.kt+```diff --git a/plugins/omo/skills/lsp-setup/references/lua/README.md b/plugins/omo/skills/lsp-setup/references/lua/README.mdnew file mode 100644index 00000000..1edb98b9--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/lua/README.md@@ -0,0 +1,66 @@+# Lua — LSP setup++- **Builtin server:** `lua-ls` — `lua-language-server`+- **Extensions:** `.lua`+- **Install hint:** `https://github.com/LuaLS/lua-language-server`++## Install++See `https://github.com/LuaLS/lua-language-server`.++- **macOS:** `brew install lua-language-server`+- **Linux:** download a release from GitHub, or `pacman -S lua-language-server` (Arch) / AUR+- **Windows:** download a release from the GitHub releases page and add its `bin` to PATH++Confirm it resolves:++```bash+command -v lua-language-server+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "lua-ls": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++For Neovim config development, point the server at the Neovim runtime and set the Lua runtime version so `vim` globals and stdlib resolve:++```json+{+ "lsp": {+ "lua-ls": {+ "initialization": {+ "Lua": {+ "runtime": { "version": "LuaJIT" },+ "workspace": {+ "library": ["/usr/share/nvim/runtime/lua"]+ },+ "diagnostics": { "globals": ["vim"] }+ }+ }+ }+ }+}+```++## Alternatives++None.++## Troubleshooting+- **PATH:** `lua-language-server` must be on PATH; reopen the shell after install.+- **Undefined `vim` global:** add `vim` to `Lua.diagnostics.globals` and set `Lua.workspace.library` (see above) for Neovim work.+- **Wrong runtime version:** set `Lua.runtime.version` (`LuaJIT`, `Lua 5.4`, etc.) to match your interpreter, or stdlib functions report as undefined.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.lua+```diff --git a/plugins/omo/skills/lsp-setup/references/php/README.md b/plugins/omo/skills/lsp-setup/references/php/README.mdnew file mode 100644index 00000000..23ae22ce--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/php/README.md@@ -0,0 +1,62 @@+# PHP — LSP setup++- **Builtin server:** `php` — `intelephense --stdio`+- **Extensions:** `.php`+- **Install hint:** `npm install -g intelephense`++## Install++Intelephense is a Node package, so Node.js (and npm) must be installed first.++- **macOS:** `npm install -g intelephense`+- **Linux:** `npm install -g intelephense`+- **Windows:** `npm install -g intelephense`++Confirm it resolves:++```bash+command -v intelephense+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "php": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++Intelephense's premium features (rename, find-all-implementations, declaration providers, etc.) require a licence key. Supply it via `initialization`:++```json+{+ "lsp": {+ "php": {+ "initialization": {+ "licenceKey": "YOUR-LICENCE-KEY"+ }+ }+ }+}+```++Without a key the server runs fine in free mode.++## Alternatives++- **phpactor** (not builtin): `phpactor language-server`. Pure-PHP, no Node dependency.++## Troubleshooting+- **PATH:** `intelephense` must be on PATH; reopen the shell after a global npm install. If missing, check `npm bin -g` is on PATH.+- **No Node:** Intelephense fails to start without Node.js. Install Node, then reinstall.+- **Wrong PHP version inference:** set `intelephense.environment.phpVersion` via `initialization` to match your project.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.php+```diff --git a/plugins/omo/skills/lsp-setup/references/python/README.md b/plugins/omo/skills/lsp-setup/references/python/README.mdnew file mode 100644index 00000000..774e7dee--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/python/README.md@@ -0,0 +1,71 @@+# Python — LSP setup++- **Builtin server:** `basedpyright` — `basedpyright-langserver --stdio`+- **Extensions:** `.py .pyi`+- **Install hint:** `pip install basedpyright`++## Install++- **macOS:** `pip install basedpyright` (or `uv tool install basedpyright`)+- **Linux:** `pip install basedpyright` (or `uv tool install basedpyright`)+- **Windows:** `pip install basedpyright`++Prefer `uv tool install basedpyright` when the project uses uv — it keeps the+server isolated from project venvs and always on PATH.++Confirm it resolves:++```bash+command -v basedpyright-langserver+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "basedpyright": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. Type-check mode is usually set via `pyrightconfig.json`+or `[tool.basedpyright]` in `pyproject.toml`, not the LSP config.++## Choosing a server++All four are builtin. Type checkers and the linter serve different roles — run a+type server, and optionally `ruff` ALONGSIDE it (not instead).++| id | command | install | role |+| ------------- | ----------------------------- | ---------------------- | --------------------------------------- |+| `basedpyright`| `basedpyright-langserver --stdio` | `pip install basedpyright` | strictest types, **default** |+| `pyright` | `pyright-langserver --stdio` | `pip install pyright` | upstream Microsoft type checker |+| `ty` | `ty server` | `pip install ty` | Astral, very fast, pre-1.0/experimental |+| `ruff` | `ruff server` | `pip install ruff` | lint + format only, complements a type server |++Recommended priority: **basedpyright** (default) > pyright > ty (experimental).+`ruff` complements via priority — it does not type-check, so keep a type server+enabled.++Enable ruff alongside basedpyright, disabling pyright:++```json+{ "lsp": {+ "basedpyright": { "priority": 100 },+ "ruff": { "priority": 90 },+ "pyright": { "disabled": true }+} }+```++## Troubleshooting+- **PATH:** `basedpyright-langserver` must be on PATH; reopen shell after install. `uv tool install` writes to `~/.local/bin`.+- **Wrong interpreter / missing imports:** the server must see the project venv. Set `python.pythonPath` / `venvPath` in `pyrightconfig.json`, or activate the venv before launching.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.py+```diff --git a/plugins/omo/skills/lsp-setup/references/ruby/README.md b/plugins/omo/skills/lsp-setup/references/ruby/README.mdnew file mode 100644index 00000000..f377216e--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/ruby/README.md@@ -0,0 +1,53 @@+# Ruby — LSP setup++- **Builtin server:** `ruby-lsp` — `rubocop --lsp`+- **Extensions:** `.rb .rake .gemspec .ru`+- **Install hint:** `gem install ruby-lsp`++> **Note:** the builtin id is `ruby-lsp`, but the executable actually invoked is **`rubocop`** (`rubocop --lsp`). RuboCop must be installed: `gem install rubocop`.++## Install++- **macOS:** `gem install rubocop` (and `gem install ruby-lsp` for the install hint's gem)+- **Linux:** `gem install rubocop`+- **Windows:** `gem install rubocop`++In a Bundler project, prefer adding `rubocop` to the `Gemfile` and running via `bundle exec`.++Confirm it resolves (check `rubocop`, since that is what runs):++```bash+command -v rubocop+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "ruby-lsp": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. Behavior is driven by your `.rubocop.yml`; the server surfaces RuboCop diagnostics, formatting, and code actions over LSP.++## Alternatives++- **`ruby-lsp` gem server** (not builtin) — the standalone Shopify Ruby LSP binary (`ruby-lsp` executable), richer navigation than RuboCop alone. Configure as a custom server with `command: ["ruby-lsp"]` in the USER config.+- **`solargraph`** (not builtin) — older completion/type server; install with `gem install solargraph`, custom `command: ["solargraph", "stdio"]`.++## Troubleshooting++- **PATH:** `rubocop` on PATH (that is the invoked binary, not `ruby-lsp`); reopen shell after install.+- **`rubocop` not found:** the builtin fails even if the `ruby-lsp` gem is installed — install RuboCop with `gem install rubocop`.+- **Bundler mismatch:** if the project pins RuboCop in its `Gemfile`, run inside the bundle so versions match.+- **No diagnostics:** check `.rubocop.yml` is valid and not disabling everything.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.rb+```diff --git a/plugins/omo/skills/lsp-setup/references/rust/README.md b/plugins/omo/skills/lsp-setup/references/rust/README.mdnew file mode 100644index 00000000..beb35dc3--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/rust/README.md@@ -0,0 +1,59 @@+# Rust — LSP setup++- **Builtin server:** `rust` — `rust-analyzer`+- **Extensions:** `.rs`+- **Install hint:** `rustup component add rust-analyzer`++## Install++- **macOS:** `rustup component add rust-analyzer` (or `brew install rust-analyzer`)+- **Linux:** `rustup component add rust-analyzer`+- **Windows:** `rustup component add rust-analyzer`++The rustup component is the recommended path — it stays pinned to your toolchain.+`rust-analyzer` also needs the `rust-src` component to index the standard library+(`rustup component add rust-src`).++Confirm it resolves:++```bash+command -v rust-analyzer+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "rust": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. To switch the check command to clippy:++```json+{ "lsp": { "rust": { "initialization": { "check": { "command": "clippy" } } } } }+```++## Alternatives++None — `rust-analyzer` is the official and sole Rust language server.++## Troubleshooting+- **PATH:** `rust-analyzer` must be on PATH; reopen shell after install. The rustup shim lives in `~/.cargo/bin`.+- **Exits while loading rust-src:** if rust-analyzer crashes during stdlib indexing, reinstall the source component:++ ```bash+ rustup component remove rust-src && rustup component add rust-src+ ```++- **No proc-macro / build script support:** ensure the project builds with `cargo check`; rust-analyzer reuses the same toolchain.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.rs+```diff --git a/plugins/omo/skills/lsp-setup/references/swift/README.md b/plugins/omo/skills/lsp-setup/references/swift/README.mdnew file mode 100644index 00000000..0f626b4a--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/swift/README.md@@ -0,0 +1,51 @@+# Swift — LSP setup++- **Builtin server:** `sourcekit-lsp` — `sourcekit-lsp`+- **Extensions:** `.swift .objc .objcpp`+- **Install hint:** `Included with Xcode or the Swift toolchain`++## Install++`sourcekit-lsp` ships with the Swift toolchain — no separate install.++- **macOS:** `xcode-select --install` (or install full Xcode). It resolves to the active toolchain selected by `xcode-select`.+- **Linux:** Install a swift.org toolchain (`sourcekit-lsp` ships inside it); add the toolchain's `usr/bin` to PATH.+- **Windows:** Install the swift.org Windows toolchain; `sourcekit-lsp` is bundled.++Confirm it resolves:++```bash+command -v sourcekit-lsp+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "sourcekit-lsp": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. For best results the project needs a **SwiftPM `Package.swift`** or a `compile_commands.json` compilation database so the server can resolve modules. Pure-Xcode-project files without these resolve poorly.++## Alternatives++- **No mainstream alternative.** `sourcekit-lsp` is the official Apple/swift.org server and the only practical choice.++## Troubleshooting++- **PATH:** `sourcekit-lsp` on PATH; reopen shell after install (or after `xcode-select -s`).+- **Wrong toolchain (macOS):** point `xcode-select` at the right Xcode/toolchain; mismatches cause stale or missing results.+- **No `Package.swift` / compile db:** add a SwiftPM manifest or generate `compile_commands.json` for accurate indexing.+- **Objective-C (`.objc`/`.objcpp`):** needs a compilation database to resolve headers and frameworks.+- **First build slow:** the server builds the module graph on first open; wait for it.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/File.swift+```diff --git a/plugins/omo/skills/lsp-setup/references/terraform/README.md b/plugins/omo/skills/lsp-setup/references/terraform/README.mdnew file mode 100644index 00000000..01491619--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/terraform/README.md@@ -0,0 +1,62 @@+# Terraform — LSP setup++- **Builtin server:** `terraform` — `terraform-ls serve`+- **Extensions:** `.tf .tfvars`+- **Install hint:** See https://github.com/hashicorp/terraform-ls++An alias id `terraform-ls` exists with the identical command; either id works.++## Install++- **macOS:** `brew install hashicorp/tap/terraform-ls`+- **Linux:** download a release from https://github.com/hashicorp/terraform-ls/releases and place `terraform-ls` on PATH (or `apt`/`dnf` via the HashiCorp repo)+- **Windows:** `choco install terraform-ls` (or download a release zip)++`terraform-ls` requires the `terraform` binary itself to be installed and on PATH.++Confirm both resolve:++```bash+command -v terraform-ls+command -v terraform+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "terraform": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. Provider/module completion comes from schemas generated by `terraform init`. Run it in each module root before expecting full completion:++```bash+terraform init+```++To force schema indexing, you can set experimental features via `initialization`:++```json+{ "lsp": { "terraform": { "initialization": { "experimentalFeatures": { "validateOnSave": true } } } } }+```++## Alternatives++- `tflint` standalone for opinionated linting (complements the LSP).+- `terraform fmt` for formatting.++## Troubleshooting+- **PATH:** `terraform-ls` AND `terraform` both on PATH; reopen shell after install.+- **No provider completion:** run `terraform init` so the `.terraform/` schema cache exists.+- **`.tfvars` not analyzed:** open the containing module so the server has root context.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.tf+```diff --git a/plugins/omo/skills/lsp-setup/references/typescript/README.md b/plugins/omo/skills/lsp-setup/references/typescript/README.mdnew file mode 100644index 00000000..7b89b972--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/typescript/README.md@@ -0,0 +1,77 @@+# TypeScript / JavaScript — LSP setup++- **Builtin server:** `typescript` — `typescript-language-server --stdio`+- **Extensions:** `.ts .tsx .js .jsx .mjs .cjs .mts .cts`+- **Install hint:** `npm install -g typescript-language-server typescript`++## Install++- **macOS:** `npm install -g typescript-language-server typescript`+- **Linux:** `npm install -g typescript-language-server typescript`+- **Windows:** `npm install -g typescript-language-server typescript` (PowerShell or cmd)++`typescript-language-server` is only a thin wrapper — it needs the `typescript`+package (`tsserver`) present too, either globally or in the project's+`node_modules`. Always install both.++Confirm it resolves:++```bash+command -v typescript-language-server+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "typescript": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required. To favor inlay hints or tweak preferences:++```json+{ "lsp": { "typescript": { "initialization": { "preferences": { "includeInlayParameterNameHints": "all" } } } } }+```++## Alternatives++All builtin — pick by toolchain. Raise the alternative's `priority` and/or+`disabled` the default so the file routes to your choice:++| id | command | when to choose |+| ------------ | ---------------------------------------- | --------------------------------------- |+| `deno` | `deno lsp` | Deno projects (handles `.ts/.tsx/.js`) |+| `biome` | `biome lsp-proxy --stdio` | Biome lint/format as the LSP |+| `eslint` | `vscode-eslint-language-server --stdio` | ESLint diagnostics (install below) |+| `oxlint` | `oxlint --lsp` | fast Oxc-based linting |+| `vue` | `vue-language-server --stdio` | `.vue` single-file components |+| `svelte` | `svelteserver --stdio` | `.svelte` files |+| `astro` | `astro-ls --stdio` | `.astro` files |++`eslint` install: `npm i -g vscode-langservers-extracted`.++Pick Deno or Biome over the default:++```json+{ "lsp": {+ "typescript": { "disabled": true },+ "deno": { "priority": 100 }+} }+```++(Swap `"deno"` for `"biome"` to use Biome instead.)++## Troubleshooting+- **PATH:** `typescript-language-server` must be on PATH; reopen shell after `npm i -g`. Check your global bin with `npm bin -g`.+- **Missing tsserver:** errors like "Could not find tsserver" mean the `typescript` package is absent — install it globally or in the project.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.ts+```diff --git a/plugins/omo/skills/lsp-setup/references/yaml/README.md b/plugins/omo/skills/lsp-setup/references/yaml/README.mdnew file mode 100644index 00000000..cd7636a4--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/yaml/README.md@@ -0,0 +1,70 @@+# YAML — LSP setup++- **Builtin server:** `yaml-ls` — `yaml-language-server --stdio`+- **Extensions:** `.yaml .yml`+- **Install hint:** `npm install -g yaml-language-server`++## Install++- **macOS:** `npm install -g yaml-language-server`+- **Linux:** `npm install -g yaml-language-server`+- **Windows:** `npm install -g yaml-language-server` (PowerShell)++Confirm it resolves:++```bash+command -v yaml-language-server+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "yaml-ls": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++Schema association is the main reason to configure yaml-ls. Map globs to a schema URL or local path under `yaml.schemas`:++```json+{+ "lsp": {+ "yaml-ls": {+ "initialization": {+ "yaml": {+ "schemas": {+ "https://json.schemastore.org/github-workflow.json": ".github/workflows/*.yml",+ "https://json.schemastore.org/kustomization.json": "kustomization.yaml",+ "./schemas/my-config.schema.json": "config/*.yaml"+ },+ "validate": true,+ "completion": true,+ "format": { "enable": true }+ }+ }+ }+ }+}+```++Set `"yaml.schemaStore": { "enable": true }` to auto-resolve schemas from SchemaStore (catalog at https://www.schemastore.org/). Inline `# yaml-language-server: $schema=<url>` modelines also work without config.++## Alternatives++- `redhat.vscode-yaml` bundles the same server in editors.+- `yamllint` standalone for style/lint-only checks.++## Troubleshooting+- **PATH:** `yaml-language-server` on PATH; reopen shell after `npm -g` install.+- **No validation:** no schema matched — add a `yaml.schemas` glob or a `$schema` modeline.+- **Wrong schema applied:** SchemaStore guessed by filename; pin explicitly under `yaml.schemas`.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.yaml+```diff --git a/plugins/omo/skills/lsp-setup/references/zig/README.md b/plugins/omo/skills/lsp-setup/references/zig/README.mdnew file mode 100644index 00000000..98c70ba6--- /dev/null+++ b/plugins/omo/skills/lsp-setup/references/zig/README.md@@ -0,0 +1,49 @@+# Zig — LSP setup++- **Builtin server:** `zls` — `zls`+- **Extensions:** `.zig .zon`+- **Install hint:** `https://github.com/zigtools/zls`++## Install++ZLS (the Zig Language Server) must be built against the **same Zig version** you use.+See `https://github.com/zigtools/zls`.++- **macOS:** `brew install zls`+- **Linux:** download a prebuilt release matching your Zig version, or `zig build -Doptimize=ReleaseSafe` from the zls source+- **Windows:** download the matching release from the zls GitHub releases, or build from source++Confirm it resolves:++```bash+command -v zls+```++## Configure++Builtin — usually NO config needed (auto-resolved by extension). Configure only to set priority, init options, override extensions, or disable. Same JSON shape in `.codex/lsp-client.json` (Codex) AND `.opencode/lsp.json` (OpenCode/omo):++```json+{ "lsp": { "zls": { "priority": 100 } } }+```++For builtin ids in a PROJECT config, `command` is supplied automatically — only set `priority`/`initialization`/`extensions`/`disabled`/`env`. A fully custom (non-builtin) server with its own `command` must go in the USER config (`~/.codex/lsp-client.json`).++### Initialization options (only if commonly needed)++None commonly required.++## Alternatives++None.++## Troubleshooting+- **VERSION MATCH (critical):** zls version MUST match your zig version — build/install zls against the exact same Zig. A mismatch causes crashes, parse errors, or silent failures. After upgrading Zig, upgrade/rebuild zls too.+- **PATH:** `zls` must be on PATH; reopen the shell after install.+- **zig not found:** zls invokes `zig` for builds — make sure `zig` itself is also on PATH.++## Verify++```bash+bun ../../scripts/verify-lsp.ts path/to/file.zig+```diff --git a/plugins/omo/skills/lsp-setup/scripts/detect-lsp.ts b/plugins/omo/skills/lsp-setup/scripts/detect-lsp.tsnew file mode 100644index 00000000..ef9cf645--- /dev/null+++ b/plugins/omo/skills/lsp-setup/scripts/detect-lsp.ts@@ -0,0 +1,210 @@+#!/usr/bin/env bun+// detect-lsp.ts <targetDir> [--json] — scan a directory for source languages and+// report, per detected language: the builtin LSP server, whether its executable+// is on PATH, an install hint, and whether a project LSP config references it.++import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"+import { delimiter, extname, join, sep } from "node:path"+import process from "node:process"++import { LANGUAGES, type LanguageServer, PROJECT_CONFIG_FILES } from "./lsp-server-table"++const SKIP_DIRECTORIES = new Set<string>([+ "node_modules",+ ".git",+ "dist",+ "build",+ ".next",+ "out",+ "target",+ ".venv",+ "venv",+ "vendor",+ ".cache",+ "__pycache__",+ ".turbo",+ "coverage",+])++const MAX_FILES = 50_000++// Mirrors effectiveExtension() in packages/lsp-tools-mcp/src/lsp/effective-extension.ts:+// extensionless Dockerfile/Containerfile resolve to .dockerfile (exact-case basenames).+const BASENAME_EXTENSIONS: Record<string, string> = {+ Dockerfile: ".dockerfile",+ Containerfile: ".dockerfile",+}++interface ConfigFileState {+ readonly path: string+ readonly exists: boolean+ readonly serverIds: readonly string[]+}++interface DetectionResult {+ readonly server: LanguageServer+ readonly executable: string+ readonly installed: boolean+ readonly resolvedPath: string | null+ readonly configuredIn: readonly string[]+}++function collectExtensions(root: string): ReadonlySet<string> {+ const found = new Set<string>()+ const stack: string[] = [root]+ let visited = 0++ while (stack.length > 0) {+ const current = stack.pop()+ if (current === undefined) break++ let entries: string[]+ try {+ entries = readdirSync(current)+ } catch {+ continue+ }++ for (const entry of entries) {+ if (visited >= MAX_FILES) return found+ const fullPath = join(current, entry)++ let kind: "dir" | "file" | "other" = "other"+ try {+ const stat = statSync(fullPath)+ kind = stat.isDirectory() ? "dir" : stat.isFile() ? "file" : "other"+ } catch {+ continue+ }++ if (kind === "dir") {+ if (!SKIP_DIRECTORIES.has(entry)) stack.push(fullPath)+ } else if (kind === "file") {+ visited += 1+ const ext = (BASENAME_EXTENSIONS[entry] ?? extname(entry)).toLowerCase()+ if (ext.length > 0) found.add(ext)+ }+ }+ }++ return found+}++function pathDirectories(): readonly string[] {+ return (process.env["PATH"] ?? "").split(delimiter).filter((dir: string) => dir.length > 0)+}++function resolveExecutable(command: string): string | null {+ const extensions =+ process.platform === "win32" ? (process.env["PATHEXT"]?.split(";") ?? [".EXE", ".CMD", ".BAT"]) : [""]+ const bases = command.includes("/") || command.includes(sep) ? [command] : pathDirectories().map((dir: string) => join(dir, command))++ for (const base of bases) {+ for (const ext of extensions) {+ const candidate = ext.length > 0 ? `${base}${ext}` : base+ try {+ if (existsSync(candidate) && statSync(candidate).isFile()) return candidate+ } catch {+ continue+ }+ }+ }+ return null+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value)+}++function parseConfiguredServerIds(path: string): readonly string[] {+ let parsed: unknown+ try {+ parsed = JSON.parse(readFileSync(path, "utf-8"))+ } catch {+ return []+ }+ if (!isRecord(parsed)) return []+ const lsp = parsed["lsp"]+ return isRecord(lsp) ? Object.keys(lsp) : []+}++function readConfigState(root: string): readonly ConfigFileState[] {+ return PROJECT_CONFIG_FILES.map((relative: string): ConfigFileState => {+ const path = join(root, relative)+ if (!existsSync(path)) return { path: relative, exists: false, serverIds: [] }+ return { path: relative, exists: true, serverIds: parseConfiguredServerIds(path) }+ })+}++function detect(root: string, configState: readonly ConfigFileState[]): readonly DetectionResult[] {+ const extensions = collectExtensions(root)+ const results: DetectionResult[] = []++ for (const server of LANGUAGES) {+ if (!server.extensions.some((ext: string) => extensions.has(ext))) continue++ const executable = server.command[0] ?? server.serverId+ const resolvedPath = resolveExecutable(executable)+ const configuredIn = configState+ .filter((state) => state.serverIds.includes(server.serverId))+ .map((state) => state.path)++ results.push({ server, executable, installed: resolvedPath !== null, resolvedPath, configuredIn })+ }++ return results+}++function renderReport(root: string, results: readonly DetectionResult[], configState: readonly ConfigFileState[]): string {+ const lines: string[] = [`LSP setup scan: ${root}`]+ const configSummary = configState+ .map((state) => `${state.path} (${state.exists ? `present: ${state.serverIds.length} server(s)` : "absent"})`)+ .join(", ")+ lines.push(`Config files: ${configSummary}`, "")++ if (results.length === 0) {+ lines.push("No languages with a builtin LSP server were detected here.")+ return lines.join("\n")+ }++ lines.push("DETECTED LANGUAGES (primary builtin server per language)")+ for (const result of results) {+ const mark = result.installed ? "OK " : "MISS"+ const state = result.installed ? `installed (${result.resolvedPath})` : "NOT installed"+ const config = result.configuredIn.length > 0 ? `configured in ${result.configuredIn.join(", ")}` : "builtin-default"+ lines.push(`[${mark}] ${result.server.language.padEnd(12)} server=${result.server.serverId} exe=${result.executable} ${state} ${config}`)+ if (!result.installed) lines.push(` install: ${result.server.installHint}`)+ }++ const missing = results.filter((result) => !result.installed)+ lines.push(+ "",+ missing.length === 0+ ? `All ${results.length} detected server(s) installed.`+ : `${missing.length}/${results.length} server(s) NOT installed: ${missing.map((m) => m.server.language).join(", ")}`,+ "Next: read references/<language>/README.md, then configure .codex/lsp-client.json AND .opencode/lsp.json.",+ )+ return lines.join("\n")+}++function main(): void {+ const args = process.argv.slice(2)+ const wantsJson = args.includes("--json")+ const root = args.find((arg: string) => !arg.startsWith("--")) ?? process.cwd()++ if (!existsSync(root)) {+ process.stderr.write(`detect-lsp: target directory does not exist: ${root}\n`)+ process.exit(2)+ }++ const configState = readConfigState(root)+ const results = detect(root, configState)++ if (wantsJson) {+ process.stdout.write(`${JSON.stringify({ root, configState, results }, null, 2)}\n`)+ return+ }+ process.stdout.write(`${renderReport(root, results, configState)}\n`)+}++main()diff --git a/plugins/omo/skills/lsp-setup/scripts/lsp-server-table.ts b/plugins/omo/skills/lsp-setup/scripts/lsp-server-table.tsnew file mode 100644index 00000000..f3c159d4--- /dev/null+++ b/plugins/omo/skills/lsp-setup/scripts/lsp-server-table.ts@@ -0,0 +1,177 @@+// SOURCE OF TRUTH: packages/lsp-tools-mcp/src/lsp/server-definitions.ts+// (BUILTIN_SERVERS + LSP_INSTALL_HINTS). This is a hand-maintained snapshot of+// the primary builtin server per reference language, embedded so detect-lsp.ts+// runs standalone in any user project. Mirror command/extensions when that file+// changes.++export interface LanguageServer {+ readonly language: string+ readonly serverId: string+ readonly command: readonly string[]+ readonly extensions: readonly string[]+ readonly installHint: string+}++export const LANGUAGES: readonly LanguageServer[] = [+ {+ language: "typescript",+ serverId: "typescript",+ command: ["typescript-language-server", "--stdio"],+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],+ installHint: "npm install -g typescript-language-server typescript",+ },+ {+ language: "python",+ serverId: "basedpyright",+ command: ["basedpyright-langserver", "--stdio"],+ extensions: [".py", ".pyi"],+ installHint: "pip install basedpyright (or: uv tool install basedpyright)",+ },+ {+ language: "go",+ serverId: "gopls",+ command: ["gopls"],+ extensions: [".go"],+ installHint: "go install golang.org/x/tools/gopls@latest",+ },+ {+ language: "rust",+ serverId: "rust",+ command: ["rust-analyzer"],+ extensions: [".rs"],+ installHint: "rustup component add rust-analyzer",+ },+ {+ language: "c-cpp",+ serverId: "clangd",+ command: ["clangd", "--background-index", "--clang-tidy"],+ extensions: [".c", ".cpp", ".cc", ".cxx", ".c++", ".h", ".hpp", ".hh", ".hxx", ".h++"],+ installHint: "macOS: brew install llvm | Linux: apt install clangd | https://clangd.llvm.org/installation",+ },+ {+ language: "java",+ serverId: "jdtls",+ command: ["jdtls"],+ extensions: [".java"],+ installHint: "macOS: brew install jdtls | https://github.com/eclipse-jdtls/eclipse.jdt.ls",+ },+ {+ language: "kotlin",+ serverId: "kotlin-ls",+ command: ["kotlin-lsp"],+ extensions: [".kt", ".kts"],+ installHint: "https://github.com/Kotlin/kotlin-lsp",+ },+ {+ language: "csharp",+ serverId: "csharp",+ command: ["csharp-ls"],+ extensions: [".cs"],+ installHint: "dotnet tool install -g csharp-ls",+ },+ {+ language: "razor",+ serverId: "razor",+ command: ["roslyn-language-server", "--stdio"],+ extensions: [".razor", ".cshtml"],+ installHint: "dotnet tool install -g roslyn-language-server --prerelease (see references/csharp/README.md)",+ },+ {+ language: "swift",+ serverId: "sourcekit-lsp",+ command: ["sourcekit-lsp"],+ extensions: [".swift", ".objc", ".objcpp"],+ installHint: "Included with Xcode (xcode-select --install) or the Swift toolchain",+ },+ {+ language: "ruby",+ serverId: "ruby-lsp",+ command: ["rubocop", "--lsp"],+ extensions: [".rb", ".rake", ".gemspec", ".ru"],+ installHint: "gem install ruby-lsp (builtin runs `rubocop --lsp`; gem install rubocop)",+ },+ {+ language: "php",+ serverId: "php",+ command: ["intelephense", "--stdio"],+ extensions: [".php"],+ installHint: "npm install -g intelephense",+ },+ {+ language: "dart",+ serverId: "dart",+ command: ["dart", "language-server", "--lsp"],+ extensions: [".dart"],+ installHint: "Included with the Dart/Flutter SDK",+ },+ {+ language: "elixir",+ serverId: "elixir-ls",+ command: ["elixir-ls"],+ extensions: [".ex", ".exs"],+ installHint: "https://github.com/elixir-lsp/elixir-ls",+ },+ {+ language: "zig",+ serverId: "zls",+ command: ["zls"],+ extensions: [".zig", ".zon"],+ installHint: "https://github.com/zigtools/zls (match zls version to your zig version)",+ },+ {+ language: "lua",+ serverId: "lua-ls",+ command: ["lua-language-server"],+ extensions: [".lua"],+ installHint: "macOS: brew install lua-language-server | https://github.com/LuaLS/lua-language-server",+ },+ {+ language: "bash",+ serverId: "bash",+ command: ["bash-language-server", "start"],+ extensions: [".sh", ".bash", ".zsh", ".ksh"],+ installHint: "npm install -g bash-language-server",+ },+ {+ language: "yaml",+ serverId: "yaml-ls",+ command: ["yaml-language-server", "--stdio"],+ extensions: [".yaml", ".yml"],+ installHint: "npm install -g yaml-language-server",+ },+ {+ language: "terraform",+ serverId: "terraform",+ command: ["terraform-ls", "serve"],+ extensions: [".tf", ".tfvars"],+ installHint: "macOS: brew install hashicorp/tap/terraform-ls | https://github.com/hashicorp/terraform-ls",+ },+ {+ language: "dockerfile",+ serverId: "dockerfile",+ command: ["docker-langserver", "--stdio"],+ extensions: [".dockerfile"],+ installHint: "npm install -g dockerfile-language-server-nodejs",+ },+ {+ language: "haskell",+ serverId: "haskell-language-server",+ command: ["haskell-language-server-wrapper", "--lsp"],+ extensions: [".hs", ".lhs"],+ installHint: "ghcup install hls",+ },+ {+ language: "julia",+ serverId: "julials",+ command: ["julia", "--startup-file=no", "--history-file=no", "-e", "using LanguageServer; runserver()"],+ extensions: [".jl"],+ installHint: "julia -e 'using Pkg; Pkg.add(\"LanguageServer\")' (see references/julia/README.md)",+ },+] as const++export const PROJECT_CONFIG_FILES: readonly string[] = [+ ".codex/lsp-client.json",+ ".opencode/lsp.json",+ ".omo/lsp.json",+ ".omo/lsp-client.json",+] as constdiff --git a/plugins/omo/skills/lsp-setup/scripts/tsconfig.json b/plugins/omo/skills/lsp-setup/scripts/tsconfig.jsonnew file mode 100644index 00000000..413534c5--- /dev/null+++ b/plugins/omo/skills/lsp-setup/scripts/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "noEmit": true,+ "lib": ["ESNext"],+ "types": ["bun-types"]+ },+ "include": ["*.ts"]+}diff --git a/plugins/omo/skills/lsp-setup/scripts/verify-lsp.ts b/plugins/omo/skills/lsp-setup/scripts/verify-lsp.tsnew file mode 100644index 00000000..375bcfed--- /dev/null+++ b/plugins/omo/skills/lsp-setup/scripts/verify-lsp.ts@@ -0,0 +1,147 @@+#!/usr/bin/env bun+// verify-lsp.ts <file> [--timeout=ms] — perform a real LSP diagnostics roundtrip+// for <file> through the lsp-tools-mcp engine and report ok/fail with error text.+// The engine source is located by walking up from this script and the cwd, so+// run it inside the omo repo/worktree (where packages/lsp-tools-mcp/src exists).++import { existsSync, statSync } from "node:fs"+import { dirname, isAbsolute, join, resolve } from "node:path"+import process from "node:process"+import { fileURLToPath, pathToFileURL } from "node:url"++const ENGINE_TOOLS = "packages/lsp-tools-mcp/src/tools.ts"+const ENGINE_CONTEXT = "packages/lsp-tools-mcp/src/request-context.ts"+const ENGINE_MANAGER = "packages/lsp-tools-mcp/src/lsp/manager.ts"+const DEFAULT_TIMEOUT_MS = 60_000++interface ToolExecutionResult {+ readonly content: ReadonlyArray<{ readonly type: "text"; readonly text: string }>+ readonly isError?: boolean+ readonly details?: unknown+}++interface DiagnosticsDetails {+ readonly mode: "file" | "directory"+ readonly totalDiagnostics: number+ readonly error?: string+ readonly errorKind?: "missing_dependency" | "no_files" | "invalid_path"+}++interface ToolsModule {+ readonly executeLspDiagnostics: (params: Record<string, unknown>, signal?: AbortSignal) => Promise<ToolExecutionResult>+}++interface ContextModule {+ readonly runWithRequestContext: <T>(context: { cwd?: string; env?: Record<string, string> }, fn: () => T) => T+}++interface ManagerModule {+ readonly disposeDefaultLspManager: () => Promise<void>+}++function findUp(relativeTarget: string): string | null {+ const starts = [dirname(fileURLToPath(import.meta.url)), process.cwd()]+ for (const start of starts) {+ let current = start+ while (true) {+ const candidate = join(current, relativeTarget)+ if (existsSync(candidate)) return candidate+ const parent = dirname(current)+ if (parent === current) break+ current = parent+ }+ }+ return null+}++function buildEnv(): Record<string, string> {+ const env: Record<string, string> = {}+ for (const [key, value] of Object.entries(process.env)) {+ if (value !== undefined) env[key] = value+ }+ return env+}++function isDiagnosticsDetails(value: unknown): value is DiagnosticsDetails {+ return typeof value === "object" && value !== null && "mode" in value && "totalDiagnostics" in value+}++async function loadModule<T>(relativeTarget: string): Promise<T> {+ const path = findUp(relativeTarget)+ if (path === null) {+ throw new EngineNotFoundError(relativeTarget)+ }+ return (await import(pathToFileURL(path).href)) as T+}++class EngineNotFoundError extends Error {+ constructor(public readonly target: string) {+ super(`lsp-tools-mcp engine not found (looked for ${target}). Run verify-lsp.ts inside the omo repo/worktree.`)+ this.name = "EngineNotFoundError"+ }+}++function parseTimeout(args: readonly string[]): number {+ const flag = args.find((arg) => arg.startsWith("--timeout="))+ if (flag === undefined) return DEFAULT_TIMEOUT_MS+ const parsed = Number.parseInt(flag.slice("--timeout=".length), 10)+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_TIMEOUT_MS+}++async function run(filePath: string, timeoutMs: number): Promise<number> {+ const tools = await loadModule<ToolsModule>(ENGINE_TOOLS)+ const context = await loadModule<ContextModule>(ENGINE_CONTEXT)+ const manager = await loadModule<ManagerModule>(ENGINE_MANAGER)+ const absolute = isAbsolute(filePath) ? filePath : resolve(process.cwd(), filePath)++ try {+ const signal = AbortSignal.timeout(timeoutMs)+ const result = await context.runWithRequestContext({ cwd: process.cwd(), env: buildEnv() }, () =>+ tools.executeLspDiagnostics({ filePath: absolute, severity: "all" }, signal),+ )+ const details = isDiagnosticsDetails(result.details) ? result.details : null+ const text = result.content.map((part) => part.text).join("\n")++ if (details?.errorKind === "missing_dependency") {+ process.stdout.write(`FAIL ${absolute}: language server not installed\n${text}\n`)+ return 1+ }+ if (result.isError === true || details?.errorKind === "invalid_path" || details?.errorKind === "no_files") {+ process.stdout.write(`FAIL ${absolute}: ${details?.error ?? text}\n`)+ return 1+ }++ const count = details?.totalDiagnostics ?? 0+ process.stdout.write(`OK ${absolute}: LSP roundtrip succeeded (${count} diagnostic(s))\n${text}\n`)+ return 0+ } finally {+ await manager.disposeDefaultLspManager()+ }+}++async function main(): Promise<void> {+ const args = process.argv.slice(2)+ const filePath = args.find((arg) => !arg.startsWith("--"))+ if (filePath === undefined) {+ process.stderr.write("Usage: bun verify-lsp.ts <file> [--timeout=ms]\n")+ process.exit(2)+ }+ if (!existsSync(filePath) || !statSync(filePath).isFile()) {+ process.stderr.write(`verify-lsp: not a file: ${filePath}\n`)+ process.exit(2)+ }++ try {+ const code = await run(filePath, parseTimeout(args))+ process.exit(code)+ } catch (error) {+ if (error instanceof EngineNotFoundError) {+ process.stderr.write(`SKIP: ${error.message}\n`)+ process.exit(3)+ }+ process.stderr.write(`FAIL ${filePath}: ${error instanceof Error ? error.message : String(error)}\n`)+ process.exit(1)+ }+}++await main()diff --git a/plugins/omo/skills/refactor/SKILL.md b/plugins/omo/skills/refactor/SKILL.mdindex 0e89b22e..2e88a158 100644--- a/plugins/omo/skills/refactor/SKILL.md+++ b/plugins/omo/skills/refactor/SKILL.md@@ -9,17 +9,17 @@ This skill may include examples copied from the OpenCode harness. In Codex, do n| OpenCode example | Codex tool to use || --- | --- |-| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` |-| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})` |-| `task(subagent_type="plan", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a planning agent. ...","fork_turns":"none"})` |-| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent({"task_name":"...","message":"TASK: act as a rigorous reviewer. ...","fork_turns":"none"})` |-| `task(category="...", ...)` for implementation or QA | `spawn_agent({"task_name":"...","message":"TASK: act as an implementation or QA worker. ...","fork_turns":"none"})` |-| `background_output(task_id="...")` | `wait_agent(...)` for mailbox signals; after a timeout, run one `list_agents` check for the named child if reassurance is needed |-| `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |+| `call_omo_agent(subagent_type="explore", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","agent_type":"explorer","fork_context":false})` |+| `call_omo_agent(subagent_type="librarian", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","agent_type":"librarian","fork_context":false})` |+| `task(subagent_type="plan", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a planning agent. ...","agent_type":"plan","fork_context":false})` |+| `task(subagent_type="oracle", ...)` for final verification | `multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous reviewer. ...","agent_type":"codex-ultrawork-reviewer","fork_context":false})` |+| `task(category="...", ...)` for implementation or QA | `multi_agent_v1.spawn_agent({"message":"TASK: act as an implementation or QA worker. ...","fork_context":false})` |+| `background_output(task_id="...")` | `multi_agent_v1.wait_agent(...)` for mailbox signals |+| `team_*(...)` | Use Codex native subagents via `multi_agent_v1.spawn_agent`, `multi_agent_v1.send_input`, `multi_agent_v1.wait_agent`, and `multi_agent_v1.close_agent` |-Codex full-history forks inherit parent context, so role-specific behavior must be described in a self-contained `message` and usually should use a non-full-history fork mode such as `fork_turns="none"`. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.+Role-specific behavior must be described in a self-contained `message`. Use `fork_context: false` to start the child with only the initial prompt (no parent history); use `fork_context: true` only when full parent history is truly required. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. OMO installs these selectable agent roles into `~/.codex/agents/`: `explorer`, `librarian`, `plan`, `momus`, `metis`, and `codex-ultrawork-reviewer` — pass the matching name as `agent_type` so the child gets that role's model and instructions. On `multi_agent_v2` sessions the same `agent_type` applies (the OMO installer exposes it) with `fork_turns` instead of `fork_context`. If the spawn tool exposes no `agent_type` parameter, omit it and describe the role inside `message`. If a code block below conflicts with this section, this section wins.-For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `wait_agent` timeout only means no new mailbox update arrived. Treat a running child or latest `WORKING:` message as alive. Do not use `list_agents` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.+For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `multi_agent_v1.wait_agent` timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.export const REFACTOR_TEMPLATE = `# Intelligent Refactor Commanddiff --git a/plugins/omo/skills/remove-ai-slops/SKILL.md b/plugins/omo/skills/remove-ai-slops/SKILL.mdindex 18b7b932..7d103dd3 100644--- a/plugins/omo/skills/remove-ai-slops/SKILL.md+++ b/plugins/omo/skills/remove-ai-slops/SKILL.md@@ -9,17 +9,17 @@ This skill may include examples copied from the OpenCode harness. In Codex, do n| OpenCode example | Codex tool to use || --- | --- |-| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` |-| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})` |-| `task(subagent_type="plan", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a planning agent. ...","fork_turns":"none"})` |-| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent({"task_name":"...","message":"TASK: act as a rigorous reviewer. ...","fork_turns":"none"})` |-| `task(category="...", ...)` for implementation or QA | `spawn_agent({"task_name":"...","message":"TASK: act as an implementation or QA worker. ...","fork_turns":"none"})` |-| `background_output(task_id="...")` | `wait_agent(...)` for mailbox signals; after a timeout, run one `list_agents` check for the named child if reassurance is needed |-| `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |+| `call_omo_agent(subagent_type="explore", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","agent_type":"explorer","fork_context":false})` |+| `call_omo_agent(subagent_type="librarian", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","agent_type":"librarian","fork_context":false})` |+| `task(subagent_type="plan", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a planning agent. ...","agent_type":"plan","fork_context":false})` |+| `task(subagent_type="oracle", ...)` for final verification | `multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous reviewer. ...","agent_type":"codex-ultrawork-reviewer","fork_context":false})` |+| `task(category="...", ...)` for implementation or QA | `multi_agent_v1.spawn_agent({"message":"TASK: act as an implementation or QA worker. ...","fork_context":false})` |+| `background_output(task_id="...")` | `multi_agent_v1.wait_agent(...)` for mailbox signals |+| `team_*(...)` | Use Codex native subagents via `multi_agent_v1.spawn_agent`, `multi_agent_v1.send_input`, `multi_agent_v1.wait_agent`, and `multi_agent_v1.close_agent` |-Codex full-history forks inherit parent context, so role-specific behavior must be described in a self-contained `message` and usually should use a non-full-history fork mode such as `fork_turns="none"`. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.+Role-specific behavior must be described in a self-contained `message`. Use `fork_context: false` to start the child with only the initial prompt (no parent history); use `fork_context: true` only when full parent history is truly required. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. OMO installs these selectable agent roles into `~/.codex/agents/`: `explorer`, `librarian`, `plan`, `momus`, `metis`, and `codex-ultrawork-reviewer` — pass the matching name as `agent_type` so the child gets that role's model and instructions. On `multi_agent_v2` sessions the same `agent_type` applies (the OMO installer exposes it) with `fork_turns` instead of `fork_context`. If the spawn tool exposes no `agent_type` parameter, omit it and describe the role inside `message`. If a code block below conflicts with this section, this section wins.-For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `wait_agent` timeout only means no new mailbox update arrived. Treat a running child or latest `WORKING:` message as alive. Do not use `list_agents` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.+For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `multi_agent_v1.wait_agent` timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.# Remove AI Slops Skill@@ -211,7 +211,7 @@ For each skipped issue, give reason.)```-**Batch failure handling**: a `wait_agent` timeout only means no new mailbox update arrived, not that a `deep` agent failed. For long passes, require each child to send `WORKING: <file> - <current phase>` and `BLOCKED: <reason>` only when it cannot progress. If you need reassurance after a timeout, run a single `list_agents` check for the named child; a running child or latest `WORKING:` message is alive. Mark a file for retry only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Do NOT block the remaining 4 in that batch; collect successful results and retry the failed file once later. If retry also fails, escalate that file under "Issues Found & Fixed" in the final report.+**Batch failure handling**: a `multi_agent_v1.wait_agent` timeout only means no new mailbox update arrived, not that a `deep` agent failed. For long passes, require each child to send `WORKING: <file> - <current phase>` and `BLOCKED: <reason>` only when it cannot progress. Treat a running child as alive. Mark a file for retry only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Do NOT block the remaining 4 in that batch; collect successful results and retry the failed file once later. If retry also fails, escalate that file under "Issues Found & Fixed" in the final report.### Phase 5: Verify with quality gates + critical reviewdiff --git a/plugins/omo/skills/review-work/SKILL.md b/plugins/omo/skills/review-work/SKILL.mdindex 6a7ad619..79b8d61e 100644--- a/plugins/omo/skills/review-work/SKILL.md+++ b/plugins/omo/skills/review-work/SKILL.md@@ -8,27 +8,28 @@ This skill may include examples copied from the OpenCode harness. In Codex, do n| OpenCode example | Codex tool to use || --- | --- |-| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` |-| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})` |-| `task(subagent_type="plan", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a planning agent. ...","fork_turns":"none"})` |-| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent({"task_name":"...","message":"TASK: act as a rigorous reviewer. ...","fork_turns":"none"})` |-| `task(category="...", ...)` for implementation or QA | `spawn_agent({"task_name":"...","message":"TASK: act as an implementation or QA worker. ...","fork_turns":"none"})` |-| `background_output(task_id="...")` | `wait_agent(...)` for mailbox signals; after a timeout, run one `list_agents` check for the named child if reassurance is needed |-| `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |+| `call_omo_agent(subagent_type="explore", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","agent_type":"explorer","fork_context":false})` |+| `call_omo_agent(subagent_type="librarian", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","agent_type":"librarian","fork_context":false})` |+| `task(subagent_type="plan", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a planning agent. ...","agent_type":"plan","fork_context":false})` |+| `task(subagent_type="oracle", ...)` for final verification | `multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous reviewer. ...","agent_type":"codex-ultrawork-reviewer","fork_context":false})` |+| `task(category="...", ...)` for implementation or QA | `multi_agent_v1.spawn_agent({"message":"TASK: act as an implementation or QA worker. ...","fork_context":false})` |+| `background_output(task_id="...")` | `multi_agent_v1.wait_agent(...)` for mailbox signals |+| `team_*(...)` | Use Codex native subagents via `multi_agent_v1.spawn_agent`, `multi_agent_v1.send_input`, `multi_agent_v1.wait_agent`, and `multi_agent_v1.close_agent` |-Codex full-history forks inherit parent context, so role-specific behavior must be described in a self-contained `message` and usually should use a non-full-history fork mode such as `fork_turns="none"`. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.+Role-specific behavior must be described in a self-contained `message`. Use `fork_context: false` to start the child with only the initial prompt (no parent history); use `fork_context: true` only when full parent history is truly required. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. OMO installs these selectable agent roles into `~/.codex/agents/`: `explorer`, `librarian`, `plan`, `momus`, `metis`, and `codex-ultrawork-reviewer` — pass the matching name as `agent_type` so the child gets that role's model and instructions. On `multi_agent_v2` sessions the same `agent_type` applies (the OMO installer exposes it) with `fork_turns` instead of `fork_context`. If the spawn tool exposes no `agent_type` parameter, omit it and describe the role inside `message`. If a code block below conflicts with this section, this section wins.++For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `multi_agent_v1.wait_agent` timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.## Codex Subagent Reliability-Every `spawn_agent` message must be self-contained. Start with+Every `multi_agent_v1.spawn_agent` message must be self-contained. Start with`TASK: <imperative assignment>`, then name `DELIVERABLE`, `SCOPE`, and`VERIFY`. State that it is an executable assignment, not a context-handoff. Role or specialty instructions belong inside `message`; the-Codex tool schema only accepts `task_name`, `message`, and `fork_turns`.-Prefer `fork_turns: "none"` unless full history is truly+handoff. Role or specialty instructions belong inside `message`.+Use `fork_context: false` unless full history is trulyrequired; paste only the review context that worker needs.-Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short wait_agent cycles sized to the work. Never use a single long blocking wait for them, and never spin on tiny timeouts as a failure budget.+Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short `multi_agent_v1.wait_agent` cycles sized to the work. Never use a single long blocking wait for them, and never spin on tiny timeouts as a failure budget.Treat child status as a progress signal, not a timeout counter. Forwork likely to exceed one wait cycle, require the child to send@@ -37,16 +38,13 @@ review passes, and `BLOCKED: <reason>` only when it cannot progress.While any child is active, keep the parent visibly alive with activesubagent count, agent names, latest `WORKING:` phase, and whether theparent is waiting for mailbox updates. Track spawned agent names-locally. Use `wait_agent` for mailbox signals, not proof of completion.-A timeout only means no new mailbox update arrived; after a timeout,-run a single `list_agents` check for the named child when you need-reassurance. If it is running or its latest message is `WORKING:`,-treat it as alive. Do not use `list_agents` as a polling loop or status-feed; it can replay large payloads. Fallback only when the child is+locally. Use `multi_agent_v1.wait_agent` for mailbox signals, not proof of completion.+A timeout only means no new mailbox update arrived. Treat a running child as alive.+Fallback only when the child iscompleted without the deliverable, ack-only after followup, explicitly`BLOCKED:`, or no longer running. Then mark that review lane`INCONCLUSIVE`, do not count it as PASS or approval, close if safe, and-respawn a smaller `fork_turns: "none"` reviewer with the missing+respawn a smaller `fork_context: false` reviewer with the missingdeliverable. Preserve completed lane results immediately. If the retrybudget is exhausted, keep the lane `INCONCLUSIVE` and still emit a finalaggregate result.@@ -543,7 +541,7 @@ After launching all 5 agents in one turn, wait for completions in boundedcycles. Do not treat a timeout, ack-only reply, or empty child result asa PASS.-As each completes, collect via the Codex mapping above (`wait_agent`,+As each completes, collect via the Codex mapping above (`multi_agent_v1.wait_agent`,then the child's substantive final result). Preserve completed laneresults immediately; never lose a PASS/FAIL because another lane isstill running. Store each verdict independently:@@ -563,7 +561,7 @@ inconclusive and respawn a smaller reviewer/worker for that exact lane.If it still remains unfinished after that retry, close the still-runningagent if safe, keep the lane INCONCLUSIVE, and emit the final aggregatereview result with the incomplete lane named. Do not spin in repeated-wait/followup cycles. Do not use `send_message` as an interrupt; queued+wait/followup cycles. Do not use `multi_agent_v1.send_input` as an interrupt; queuedfollowups are not cancellation.---diff --git a/plugins/omo/skills/start-work/SKILL.md b/plugins/omo/skills/start-work/SKILL.mdindex 7293b007..47f26499 100644--- a/plugins/omo/skills/start-work/SKILL.md+++ b/plugins/omo/skills/start-work/SKILL.md@@ -5,55 +5,35 @@ description: "Execute a Prometheus work plan in Codex with Boulder state, eviden## Codex Harness Tool Compatibility-This skill ports the OpenCode `/start-work` flow onto Codex. Any OpenCode-only tool name in an inherited example must be translated to its Codex equivalent:+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 || --- | --- |-| `task(subagent_type="explore", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` |-| `task(subagent_type="librarian", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})` |-| `task(subagent_type="plan", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a planning agent. ...","fork_turns":"none"})` |-| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent({"task_name":"...","message":"TASK: act as a rigorous reviewer. ...","fork_turns":"none"})` |-| `task(category="...", ...)` for implementation or QA | `spawn_agent({"task_name":"...","message":"TASK: act as an implementation or QA worker. ...","fork_turns":"none"})` |-| `background_output(task_id="...")` | `wait_agent(...)` for mailbox signals; after a timeout, run one `list_agents` check for the named child if reassurance is needed |-| `dispatchInternalPrompt(...)` | the `Stop` hook emits `{"decision":"block","reason":"<prompt>"}` automatically; see Continuation |-| `team_*(...)` | `spawn_agent` + `send_message` + `followup_task` + `wait_agent` + `close_agent` |+| `call_omo_agent(subagent_type="explore", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","agent_type":"explorer","fork_context":false})` |+| `call_omo_agent(subagent_type="librarian", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","agent_type":"librarian","fork_context":false})` |+| `task(subagent_type="plan", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a planning agent. ...","agent_type":"plan","fork_context":false})` |+| `task(subagent_type="oracle", ...)` for final verification | `multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous reviewer. ...","agent_type":"codex-ultrawork-reviewer","fork_context":false})` |+| `task(category="...", ...)` for implementation or QA | `multi_agent_v1.spawn_agent({"message":"TASK: act as an implementation or QA worker. ...","fork_context":false})` |+| `background_output(task_id="...")` | `multi_agent_v1.wait_agent(...)` for mailbox signals |+| `team_*(...)` | Use Codex native subagents via `multi_agent_v1.spawn_agent`, `multi_agent_v1.send_input`, `multi_agent_v1.wait_agent`, and `multi_agent_v1.close_agent` |-When translating `load_skills=[...]`, name the skills inside the spawned agent's `message`. If a code block below conflicts with this section, this section wins.+Role-specific behavior must be described in a self-contained `message`. Use `fork_context: false` to start the child with only the initial prompt (no parent history); use `fork_context: true` only when full parent history is truly required. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. OMO installs these selectable agent roles into `~/.codex/agents/`: `explorer`, `librarian`, `plan`, `momus`, `metis`, and `codex-ultrawork-reviewer` — pass the matching name as `agent_type` so the child gets that role's model and instructions. On `multi_agent_v2` sessions the same `agent_type` applies (the OMO installer exposes it) with `fork_turns` instead of `fork_context`. If the spawn tool exposes no `agent_type` parameter, omit it and describe the role inside `message`. If a code block below conflicts with this section, this section wins.++For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `multi_agent_v1.wait_agent` timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.++## ABSOLUTE RULE: YOU ARE AN ORCHESTRATOR — NEVER THE IMPLEMENTER++**YOU DO NOT WRITE CODE. YOU DO NOT EDIT PRODUCT FILES. YOU DO NOT RUN QA YOURSELF. EVERY unit of implementation, test, QA, and review work MUST be delegated to a spawned subagent. NO EXCEPTIONS.** Your hands touch only plan selection, `.omo/` state (Boulder, ledger, plan checkboxes), decomposition, dispatch, verdicts, and evidence records. About to edit a product file or run an implementation command yourself? **STOP. SPAWN A WORKER INSTEAD.** Orchestrate at **MAXIMUM PARALLELISM**: every independent unit runs concurrently; only named dependencies serialize.## Codex Subagent Reliability-Every `spawn_agent` message must be self-contained. Start with-`TASK: <imperative assignment>`, then name `DELIVERABLE`, `SCOPE`, and-`VERIFY`. State that it is an executable assignment, not a context-handoff. Role or specialty instructions belong inside `message`; the-Codex tool schema only accepts `task_name`, `message`, and `fork_turns`.-Prefer `fork_turns: "none"` unless full history is truly-required; paste only the context the child needs.--Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short wait_agent cycles sized to the work. Never use a single long blocking wait for them, and never spin on tiny timeouts as a failure budget.--Treat child status as a progress signal, not a timeout counter. For-work likely to exceed one wait cycle, require the child to send-`WORKING: <task> - <current phase>` before long reading, testing, or-review passes, and `BLOCKED: <reason>` only when it cannot progress.-While any child is active, keep the parent visibly alive with active-subagent count, agent names, latest `WORKING:` phase, and whether the-parent is waiting for mailbox updates. Track spawned agent names-locally. Use `wait_agent` for mailbox signals, not proof of completion.-A timeout only means no new mailbox update arrived; after a timeout,-run a single `list_agents` check for the named child when you need-reassurance. If it is running or its latest message is `WORKING:`,-treat it as alive. Do not use `list_agents` as a polling loop or status-feed; it can replay large payloads. Fallback only when the child is-completed without the deliverable, ack-only after followup, explicitly-`BLOCKED:`, or no longer running. Then record the result as-inconclusive, do not count it as pass/review approval, close if safe,-and respawn a smaller `fork_turns: "none"` task with the missing-deliverable.+Every `multi_agent_v1.spawn_agent` message is a self-contained executable assignment: `TASK: <imperative assignment>`, then `DELIVERABLE`, `SCOPE`, and `VERIFY`, with role instructions inside `message`. Use `fork_context: false` unless full history is truly required; paste only the context the child needs.++Plan and reviewer agents may run for a long time: spawn them in the background, keep doing independent root work, and poll with short `multi_agent_v1.wait_agent` cycles — never a single long blocking wait. A timeout only means no new mailbox update arrived; treat a running child as alive. Require `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. Keep the parent visibly alive with active subagent count, names, and latest `WORKING:` phase. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running — then record inconclusive (never a pass), close if safe, and respawn a smaller `fork_context: false` task with the missing deliverable.# start-work-Execute a Prometheus work plan until every top-level checkbox is complete. This skill pairs with the Codex `Stop` / `SubagentStop` continuation hook in `components/start-work-continuation`, which re-injects the next turn while `.omo/boulder.json` says the current `codex:<session_id>` still has unchecked plan work.+Execute a Prometheus work plan until every top-level checkbox is complete. This skill pairs with the Codex `Stop` / `SubagentStop` continuation hook (`components/start-work-continuation`), which re-injects the next turn while `.omo/boulder.json` says this `codex:<session_id>` still has unchecked plan work.## Usage@@ -61,8 +41,8 @@ Execute a Prometheus work plan until every top-level checkbox is complete. This$start-work [plan-name] [--worktree <absolute-path>]```-- `plan-name` is optional. It may be a full or partial file stem under `.omo/plans/`.-- `--worktree` is optional. Use it only when the user explicitly asks to work in a separate git worktree.+- `plan-name` (optional): a full or partial file stem under `.omo/plans/`.+- `--worktree` (optional): only when the user explicitly asks for a separate git worktree.## Phase 1: Select the plan@@ -76,20 +56,17 @@ $start-work [plan-name] [--worktree <absolute-path>]### No-plan bootstrap-When the user explicitly said `start work` / `$start-work` and no selectable plan exists, treat that phrase as approval to create the plan before execution. Do not stall on a missing plan and do not ask for generic approval again.--If no selectable plan exists, bootstrap `ulw-plan` before execution.-Execution requires an approved plan before implementation; bootstrap mode creates that approved plan from the user's `start work` request instead of skipping planning.+When the user explicitly said `start work` / `$start-work` and no selectable plan exists, treat that phrase as approval: bootstrap `ulw-plan` to create the approved plan before execution and implementation, instead of stalling or asking for generic approval again. A brief or notes file without waves, checkboxes, and acceptance criteria is NOT decision-complete — enter this bootstrap too.1. Invoke the `ulw-plan` skill from the current request and require its dynamic adversarial workflow: collect, verify, design, adversarial plan-review, synthesize.2. The generated Prometheus plan must be saved under `.omo/plans/<slug>.md` before implementation or Boulder state writes that point at plan work.3. Use maximum safe parallelism in the generated plan: independent files/tasks fan out; same-file writes, shared state, and named dependencies serialize.4. Preserve safety boundaries. Ask one focused question only when the objective is missing, destructive, or has a safety/product ambiguity that repository exploration cannot resolve.-5. After the plan exists, continue directly to Phase 2. The user's `start work` request is the bootstrap approval to create the plan and begin execution.+5. After the plan exists, continue directly to Phase 2.## Phase 2: Create or update Boulder state-Write `.omo/boulder.json` before implementation starts. Session ids must be prefixed with `codex:` so the continuation hook can identify its own session.+Write `.omo/boulder.json` before implementation starts. Prefix session ids with `codex:` so the continuation hook can identify its own session.```json{@@ -115,24 +92,25 @@ If `--worktree` is set, verify the path with `git worktree list --porcelain` or1. Read the full selected plan.2. Find the first unchecked column-0 checkbox in `## TODOs` or `## Final Verification Wave`.3. Ignore nested checkboxes under acceptance criteria, evidence, and definition-of-done sections.-4. Decompose that checkbox into atomic sub-tasks.-5. Dispatch independent sub-tasks in parallel with `spawn_agent`; serialize only when one sub-task has a named dependency on another.+4. Classify the checkbox tier and record it in its ledger entry. Default is LIGHT — a narrow change inside existing layers. Take HEAVY only on a fact you can point to: a new module / abstraction / domain model; auth, security, or session; an external integration; a DB schema or migration; concurrency or transaction boundaries; a cross-domain refactor; or the plan or user signals care. When unsure, take HEAVY; upgrade and redo skipped gates the moment a HEAVY fact surfaces; never downgrade.+5. Decompose that checkbox into atomic sub-tasks. Collect every other unchecked checkbox in the same plan wave whose dependencies are met — their lanes execute concurrently.+6. **DELEGATE EVERYTHING. YOU NEVER IMPLEMENT.** Dispatch ALL independent sub-tasks across those checkboxes in one parallel `multi_agent_v1.spawn_agent` burst; serialize only named dependencies. Verification and checkbox marking stay per-checkbox.Each sub-task message must include:1. Goal and exact files or directories in scope.-2. When the task touches existing behavior: a baseline characterization test, written first, that asserts current observable behavior and passes on the unchanged code. Then the red test or failing reproduction for the new behavior before production changes. Pin the baseline as rigorously as the new test: exact inputs, exact observable, exact assertion.+2. When the task touches existing behavior: a baseline characterization test, written first, that pins current observable behavior and passes on the unchanged code (exact inputs, exact observable, exact assertion). Then the failing-first proof for the new behavior before production changes — a unit test where a seam exists, otherwise the sub-task's Manual-QA scenario captured failing. A test that mirrors its implementation (mock-call assertions, pinned constants) is not evidence.3. Implementation constraints from the plan and project rules.4. Automated verification commands to run.-5. One Manual-QA channel, named with the exact tool and exact invocation (the literal `curl`, `send-keys`, `page.click`, payload, selectors, and the binary observable that decides PASS/FAIL), not "verify it works":+5. One Manual-QA channel, named with the exact tool and exact invocation (the literal `curl`, `send-keys`, `page.click`, payload, selectors, and the binary observable that decides PASS/FAIL), not "verify it works". A LIGHT checkbox needs one real-surface proof of its deliverable, and auxiliary surfaces (CLI stdout, DB state diff, parsed config dump) are first-class when the surface is CLI- or data-shaped:- HTTP call: `curl -i` against the live endpoint.- tmux: a `tmux` session driven with `send-keys`, dumped via `capture-pane`.- - Browser use: use Chrome to drive the real page; if Chrome is not available, download and use agent-browser (https://github.com/vercel-labs/agent-browser).+ - Browser use: drive the real page with Chrome, or agent-browser (https://github.com/vercel-labs/agent-browser) when Chrome is unavailable.- Computer use: OS-level GUI automation against the running desktop app when the surface is not a page.6. The adversarial classes that apply to this sub-task (from the 9 ultraqa classes) and how each is probed.7. Required artifact path and cleanup receipt.-Apply ultraqa's 9 adversarial classes where relevant to each checkbox: malformed input, prompt injection, cancel/resume, stale state, dirty worktree, hung or long commands, flaky tests, misleading success output, repeated interruptions. A checkbox whose behavior is user-visible MUST probe every class that plausibly applies; record which classes were exercised and which were ruled not-applicable with a one-line reason.+The 9 ultraqa classes are trigger-mapped: new input parsing → malformed input; untrusted external text → prompt injection; resumable or long-running flows → cancel/resume; generated or cached artifacts → stale state; uncommitted user files in scope → dirty worktree; long external commands → hung or long commands; new or timing-sensitive tests → flaky tests; log-based success claims → misleading success output; mid-operation interrupts → repeated interruptions. A class applies when its trigger fact holds. Probe each applicable class; record the rest as not-applicable with a one-line reason.## Phase 4: Verify and record evidence@@ -141,14 +119,14 @@ For each checkbox, complete all five gates before marking it done:1. Plan reread: confirm the checkbox and acceptance criteria.2. Automated verification: run tests, typecheck, lint, build, or the plan-specific equivalent.3. Manual-QA channel: capture a real artifact, not a dry-run claim.-4. Adversarial QA: exercise every applicable ultraqa class (malformed input, prompt injection, cancel/resume, stale state, dirty worktree, hung or long commands, flaky tests, misleading success output, repeated interruptions) and capture the observable result for each. "Tests pass" and a clean happy-path artifact are NOT sufficient when an adversarial class applies and was not probed.-5. Cleanup: register every QA resource teardown as its own todo the moment it is spawned (QA scripts, tmux assets, browser / agent-browser sessions, PIDs, ports, containers, temp dirs), then execute each and capture the receipt. No QA asset is left running.+4. Adversarial QA: exercise every class the Phase 3 trigger map marks applicable and capture the observable result for each.+5. Cleanup: register every QA resource teardown as its own todo when spawned (QA scripts, tmux assets, browser sessions, PIDs, ports, containers, temp dirs), execute each, and capture the receipt. No QA asset is left running.-Append evidence to `.omo/start-work/ledger.jsonl` using one JSON object per line. Include at least `event`, `plan`, `task`, `session_id`, `commands`, `artifact`, `adversarial_classes`, and `cleanup` fields. `adversarial_classes` lists each probed class with its observable result and each ruled-out class with a one-line reason.+Append evidence to `.omo/start-work/ledger.jsonl`, one JSON object per line. Include at least `event`, `plan`, `task`, `session_id`, `commands`, `artifact`, `adversarial_classes`, and `cleanup` fields. `adversarial_classes` lists each probed class with its observable result and each ruled-out class with a one-line reason.### Sisyphus-style completion contract-A worker done claim is never final. Each implementation sub-task returns a `DoneClaim`, then a different context runs `AdversarialVerify`, then the verifier probes or reproduces the claim, then failures loop back to the executor, and only a confirmed verifier verdict becomes `FullyDone`.+A worker done claim is never final: each implementation sub-task returns a `DoneClaim`, a different context runs `AdversarialVerify` probing or reproducing the claim, failures loop back to the executor, and only a confirmed verifier verdict becomes `FullyDone`.```json{@@ -172,11 +150,9 @@ A worker done claim is never final. Each implementation sub-task returns a `DoneRules:- `confirmed` is the only pass verdict. `false-positive`, `needs-fix`, and `needs-human-review` all block checkbox completion.- The verifier must be independent from the executor: use `codex-ultrawork-reviewer`, a scoped `worker` reviewer, or root only when root did not implement or materially rewrite that task.-- A worker done claim must be independently verified before it can become checkbox completion.+- A worker done claim must be independently verified before it becomes checkbox completion.- On any non-confirmed verdict, append the feedback to the ledger, reset the checkbox work to in-progress, and re-dispatch the executor with the exact failure.- The verifier must probe the applicable adversarial keys, including `stale_state`, `dirty_worktree`, and `misleading_success_output`, before allowing `FullyDone`.-- In prose evidence, name the same risks as stale state, dirty worktree, and misleading success output so reviewers can search for both key and human forms.-- Tests passing, green builds, or a worker DoneClaim without independent verification are not enough to mark a checkbox complete.## Phase 5: Mark progress@@ -204,9 +180,10 @@ When all top-level checkboxes in `## TODOs` and `## Final Verification Wave` are## Hard rules-- No production change before a failing test or reproduction exists, and no change to existing behavior before a baseline characterization test pins the current behavior and passes on the unchanged code.+- No production change before a failing-first proof exists (unit test at a seam, otherwise the failing Manual-QA scenario), and no change to existing behavior before a baseline characterization test pins the current behavior and passes on the unchanged code.- No `--dry-run` as completion evidence.- No tests-only completion claim. A Manual-QA artifact is required.+- **NO DIRECT IMPLEMENTATION BY THE ORCHESTRATOR.** Root NEVER edits product files, writes tests, or runs QA itself — a spawned worker does.- No completion claim while an applicable ultraqa adversarial class was never probed. Each applicable class needs a captured observable result; each skipped class needs a one-line not-applicable reason in the ledger.- No `ORCHESTRATION COMPLETE`, final response, PR creation, or PR handoff before the Global Review and Debugging Gate passes with recorded evidence.- No unprefixed session ids in Boulder state. Codex sessions are always `codex:<session_id>`.diff --git a/plugins/omo/skills/ultraresearch/SKILL.md b/plugins/omo/skills/ultraresearch/SKILL.mdindex 783df69a..363ce03c 100644--- a/plugins/omo/skills/ultraresearch/SKILL.md+++ b/plugins/omo/skills/ultraresearch/SKILL.md@@ -1,6 +1,6 @@---name: ultraresearch-description: "Maximum-saturation research skill. Spawns massive parallel explore+librarian subagents to exhaust every source: codebase grep/LSP/ast-grep, websearch with advanced operators, Context7 docs, grep.app, gh CLI, headless browsing. Recursive EXPAND loop until convergence. Empirically verifies ambiguous claims via code execution. Reports (MD/HTML/PDF/PPTX) with charts, screenshots, citations. ONLY activates on explicit user command. Triggers: 'ultraresearch', '/ultraresearch', '$ultraresearch'."+description: "Maximum-saturation research orchestration: parallel explore+librarian swarms across codebase, web, official docs, and OSS repos; a recursive EXPAND loop driven by leads workers return in message text; empirical verification by running code; cited synthesis and optional MD/HTML/PDF/PPTX reports. ACTIVATES ONLY on an explicit user demand for research — the word 'ultraresearch' ('/ultraresearch', '$ultraresearch') or an explicit request for research / deep research / an ultra-precise investigation, in any language. Never self-activates for ordinary questions, debugging, or implementation context-gathering. While active it overrides exploration-bounding defaults: exhaustive coverage is the goal."---## Codex Harness Tool Compatibility@@ -9,762 +9,220 @@ This skill may include examples copied from the OpenCode harness. In Codex, do n| OpenCode example | Codex tool to use || --- | --- |-| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` |-| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})` |-| `task(subagent_type="oracle", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a rigorous reviewer. ...","fork_turns":"none"})` |-| `task(category="quick", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a focused worker. ...","fork_turns":"none"})` |-| `task(category="deep", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a deep research worker. ...","fork_turns":"none"})` |-| `background_output(task_id="...")` | `wait_agent(...)` for mailbox signals; after a timeout, run one `list_agents` check for the named child if reassurance is needed |+| `call_omo_agent(subagent_type="explore", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","agent_type":"explorer","fork_context":false})` |+| `call_omo_agent(subagent_type="librarian", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","agent_type":"librarian","fork_context":false})` |+| `task(subagent_type="plan", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a planning agent. ...","agent_type":"plan","fork_context":false})` |+| `task(subagent_type="oracle", ...)` for final verification | `multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous reviewer. ...","agent_type":"codex-ultrawork-reviewer","fork_context":false})` |+| `task(category="...", ...)` for implementation or QA | `multi_agent_v1.spawn_agent({"message":"TASK: act as an implementation or QA worker. ...","fork_context":false})` |+| `background_output(task_id="...")` | `multi_agent_v1.wait_agent(...)` for mailbox signals |+| `team_*(...)` | Use Codex native subagents via `multi_agent_v1.spawn_agent`, `multi_agent_v1.send_input`, `multi_agent_v1.wait_agent`, and `multi_agent_v1.close_agent` |-Codex full-history forks inherit parent context, so role-specific behavior must be described in a self-contained `message` and usually should use a non-full-history fork mode such as `fork_turns="none"`. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.+Role-specific behavior must be described in a self-contained `message`. Use `fork_context: false` to start the child with only the initial prompt (no parent history); use `fork_context: true` only when full parent history is truly required. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. OMO installs these selectable agent roles into `~/.codex/agents/`: `explorer`, `librarian`, `plan`, `momus`, `metis`, and `codex-ultrawork-reviewer` — pass the matching name as `agent_type` so the child gets that role's model and instructions. On `multi_agent_v2` sessions the same `agent_type` applies (the OMO installer exposes it) with `fork_turns` instead of `fork_context`. If the spawn tool exposes no `agent_type` parameter, omit it and describe the role inside `message`. If a code block below conflicts with this section, this section wins.-For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `wait_agent` timeout only means no new mailbox update arrived. Treat a running child or latest `WORKING:` message as alive. Do not use `list_agents` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.--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.+For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `multi_agent_v1.wait_agent` timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.----# ULTRARESEARCH — Maximum Saturation Research--> **MANDATORY**: Say "ULTRARESEARCH MODE ENABLED!" as your first response. Then immediately begin orchestration.+# ULTRARESEARCH — Maximum-Saturation Research-You are a research orchestrator. Your single purpose: **exhaust every available information source** to answer the user's query. Not "good enough." Not "representative sampling." EVERYTHING. Overkill is the baseline.+You are the research orchestrator. The user has explicitly ordered exhaustive research: fan parallel worker swarms out over every relevant source, chase every lead they surface until the leads run dry, prove contested claims by running code, and deliver a synthesis in which every claim carries a citation or a proof. Exhaustive coverage is the assignment, not a risk to manage.-## Core Principles+## Activation-1. **Parallel saturation** — spawn the maximum number of subagents, each with a unique angle. Never sequential.-2. **Recursive expansion** — every finding can spawn new searches. Keep expanding until no new leads remain.-3. **Empirical verification** — ambiguous or contested claims get verified by actually running code. No "it should work."-4. **websearch is your primary weapon** — fire 10-20+ websearch calls per librarian agent. Advanced operators on EVERY query.-5. **English first** — all searches in English by default. Largest corpus, most authoritative sources.-6. **Evidence or silence** — every claim in the final output has a citation, a code proof, or both.+Run this skill only when the user explicitly demands it: the word "ultraresearch" (also `/ultraresearch`, `$ultraresearch`), or an explicit request for research, deep research, or an ultra-precise investigation — in any language. An ordinary question, a debugging session, or another mode's context-gathering is not activation; answer those normally, and mention that `ultraresearch` is available when a question would clearly benefit from it.-## Language Policy+Open your reply with the line `ULTRARESEARCH MODE ENABLED!`. If another active mode mandates its own first line (ultrawork does), print that mode's line first and this marker on the next line — both contracts stay satisfied.-**ALL searches, queries, and subagent prompts MUST be in English by default.** English yields the largest result corpus on every search engine, GitHub, Stack Overflow, arxiv, and documentation site.+## Authority while active-Exceptions (the ONLY cases where non-English is acceptable):-- The user explicitly asks for results in a specific language-- The topic is inherently local (Korean law, Japanese market data, etc.)-- A supplementary sweep for Korean/local sources AFTER the English sweep is complete+This mode is the user's explicit opt-in to exhaustive exploration. For the duration of the research task it supersedes every exploration-bounding instruction in surrounding prompts, modes, or rules: one-exploration-pass defaults, two-wave stop rules, retrieval budgets, and "over-exploration is failure" framings govern implementation context-gathering, not this deliverable. Here, under-exploration is the failure. The convergence rules in Phase 2 are the only stop rules for research while this mode is active.-When bilingual coverage is warranted, run the English sweep FIRST (primary), then spawn 1-2 additional librarian agents for Korean/local sources as a secondary layer. Never replace the English sweep with a local-language sweep.-----+Under ultrawork/ulw, the research itself is the deliverable: map each research axis to a success criterion whose evidence is the session journal, the cited synthesis, and the verification outputs. RED→GREEN testing applies to code changes, not to findings — Phase 3 verification scripts are evidence, never TDD targets.-## Phase 0: Query Decomposition+## Success criteria-Before spawning anything, decompose the user's query into orthogonal research axes:+The research is done when all of these hold:-```-<analysis>-**User Query**: [verbatim]-**Core Question**: [the actual information need]-**Research Axes**:- 1. [axis] — what to search, where, why- 2. [axis] — ...- 3. [axis] — ...- (minimum 3, no maximum)-**Codebase Relevance**: [yes/no — does the local codebase contain relevant code?]-**External Relevance**: [yes/no — do we need web/docs/repos?]-**Browsing Needed**: [yes/no — are there pages that need rendering/interaction?]-**Verification Needed**: [yes/no — are there claims that need code-based proof?]-**Report Requested**: [yes/no/format — did the user ask for a deliverable document?]-</analysis>-```--Create the session log directory immediately:--```bash-mkdir -p .omo/ultraresearch/$(date +%Y%m%d-%H%M%S)-```+- Every axis from Phase 0 was covered by at least one dedicated worker.+- Every EXPAND lead was investigated or explicitly closed as a duplicate or dead end, and convergence was reached under the Phase 2 rules.+- Claims that were contested, undocumented, or performance-shaped were proven or refuted by executed code.+- Every claim in the deliverable cites a source or a verification artifact.+- The session journal reconstructs what was searched, found, and expanded, wave by wave.-This is your **session directory** (`$SESSION_DIR`). All agents append findings here.+## Worker ground rules----+Research workers (explore, librarian, browsing) differ by harness, but assume:-## Phase 1: Spawn the Research Swarm+- **Read-only.** Most research workers cannot write files. Never ask a worker to write the journal or any session file — every journal write is yours.+- **No recursion.** Workers cannot spawn their own subagents. Depth comes from your expansion waves, not from worker-side recursion.+- **Built-in brakes.** Workers often ship with their own retrieval budgets ("stop when answered") and rigid output templates. Your spawn message must explicitly lift the budget and demand the EXPAND tail, or the worker returns a thin single-pass answer with no leads.+- **Capability routing.** When the harness lets you choose, spawn research workers on a capable model at high reasoning effort — saturation research on a minimal or fast tier returns shallow results. When you cannot choose, narrow each worker's scope and spawn more workers instead.-Launch ALL agents in a SINGLE turn. Every agent uses `run_in_background=true`. No sequential launches. No "let me start with one and see." ALL AT ONCE.+### The spawn-message contract-### 1A. Codebase Agents (explore) — spawn 2-4+Every research spawn message contains, in order:-Each explore agent gets a DIFFERENT search angle. Never duplicate angles.+1. `TASK:` — one imperative line naming the role and the axis.+2. The budget lift: "This is an explicit exhaustive-research assignment. Your default retrieval budget and stop-when-answered rules do not apply — run the full protocol below and report every lead."+3. Scope — the axis, the sources to hit, and what a complete answer contains.+4. The role protocol (Phase 1).+5. The reply tail. EXPAND markers travel back as message text, never as files. Every worker ends the reply with:```-task(- subagent_type="explore",- run_in_background=true,- prompt="ULTRARESEARCH CODEBASE SWEEP — AXIS: [specific axis]--SESSION_DIR: [session_dir_path]--Your mission: Find EVERYTHING in this codebase related to: [specific search angle]--SEARCH STRATEGY — execute ALL of these in parallel:-1. grep with 3+ different keyword variations (synonyms, abbreviations, full names)-2. ast_grep_search for structural patterns (function signatures, class shapes, imports)-3. LSP: lsp_goto_definition, lsp_find_references, lsp_symbols for type/function names-4. glob for file name patterns-5. git log --all -S 'keyword' for historical mentions (even deleted code)-6. git log --all --grep='keyword' for commit messages--Cross-validate: if grep finds file X, use LSP to find all references TO file X.--After searching, APPEND your findings to $SESSION_DIR/codebase-[axis-slug].md:--## Codebase Findings: [axis]-### Search Queries Used-- [list every query you ran]-### Files Found-- [absolute path] — [why relevant, key lines]-### Code Patterns-- [pattern description with file:line references]-### Cross-References-- [how findings connect to each other]--## EXPAND MARKERS-- [ ] EXPAND: [new lead discovered] — [why it matters] — [suggested search angle]-- [x] DEAD END: [lead that was already fully explored]-"-)+## EXPAND+- LEAD: <discovery not yet investigated> — WHY: <why it matters> — ANGLE: <suggested search>+- DEAD END: <lead explored to exhaustion>```-### 1B. Web Research Agents (librarian) — spawn 3-6+A worker with nothing to expand writes `## EXPAND` followed by `none — <one-line reason>`. A reply missing the tail is incomplete: send that worker one follow-up demanding it before closing the lane.++## Phase 0 — Decompose and open the journal-Each librarian targets a DIFFERENT search strategy. **websearch is the core tool — fire 10-20+ calls per agent.**+Before spawning anything, decompose the query:```-task(- subagent_type="librarian",- run_in_background=true,- prompt="ULTRARESEARCH WEB SWEEP — AXIS: [specific axis]--SESSION_DIR: [session_dir_path]--Your mission: Find EVERYTHING on the internet related to: [specific search angle]-ALL SEARCHES MUST BE IN ENGLISH unless the topic is inherently non-English.--## WEBSEARCH SATURATION PROTOCOL--You MUST fire ALL of the following. Not some. ALL. In parallel where possible.-The MINIMUM is 10 distinct websearch calls. 15-20 is normal. Do not stop early.--### A. websearch — Advanced Operators (the primary weapon)--Each websearch call MUST use different operators and angles:--1. websearch('[topic] [keywords]')-2. websearch('[topic] site:github.com')-3. websearch('[topic] site:docs.[domain].com OR site:[domain].dev')-4. websearch('[topic] filetype:md OR filetype:pdf')-5. websearch('[topic] intitle:[key term]')-6. websearch('[topic] [current year]')-7. websearch('[topic] site:stackoverflow.com OR site:reddit.com OR site:news.ycombinator.com')-8. websearch('[topic] site:arxiv.org OR site:dl.acm.org OR site:scholar.google.com')-9. websearch('[topic] analysis OR comparison OR benchmark OR review [current year]')-10. websearch('[topic] -tutorial -beginner advanced implementation')-11. websearch('[topic] inurl:api OR inurl:docs OR inurl:reference')-12. websearch('\"[exact phrase]\" [additional context]')-13. websearch('[topic] vs OR alternative OR compared to')-14. websearch('[topic] source code implementation github')-15. websearch('[topic] changelog OR release notes OR migration guide [version]')-16. websearch('[topic] site:medium.com OR site:dev.to OR site:blog')-17. websearch('[topic] best practices production [current year]')-18. websearch('[topic] known issues OR caveats OR gotchas OR limitations')-19. websearch('[topic] example OR demo OR sample project')-20. websearch('[topic] conference talk OR presentation OR workshop [current year]')--For EVERY important search result, fetch the FULL page with webfetch/FetchURL. Do not summarize from search snippets alone.--### B. Context7 Documentation Lookup--context7_resolve-library-id('[library]')- then context7_query-docs with AT LEAST 3 different queries per library.--### C. grep.app GitHub Code Search--grep_app_searchGitHub(query: '[pattern]', language: ['TypeScript'])-grep_app_searchGitHub(query: '[alternative pattern]', language: ['Python'])-grep_app_searchGitHub(query: '[pattern]', repo: 'owner/repo')--### D. GitHub CLI Deep Dive--gh search repos '[topic]' --sort stars --limit 10-gh search code '[pattern]' --language typescript --limit 20-gh search issues '[topic]' --state open --sort reactions --limit 10-gh api search/repositories -f q='[topic] stars:>100' --jq '.items[] | {name, url, description, stars: .stargazers_count}'--### E. Official Documentation Fetch--webfetch('[official docs URL]')-webfetch('[official docs URL]/sitemap.xml') // discover all doc pages-webfetch('[API reference URL]')-webfetch('[changelog/releases URL]')--Fetch sitemaps to discover the FULL doc surface. Don't just read the front page.--After searching, APPEND findings to $SESSION_DIR/web-[axis-slug].md:--## Web Findings: [axis]-### Searches Executed-- [list every websearch query with operator used — ALL of them]-### Key Sources (ranked by quality)-1. [URL] — [what it contains, key data points]-### Documentation References-- [official doc links with specific sections]-### Code Examples Found-- [GitHub links with context]-### Discussions/Opinions-- [forum links with key points]-### Data/Benchmarks-- [any quantitative findings]--## EXPAND MARKERS-- [ ] EXPAND: [new lead from search results] — [why] — [suggested angle]-"-)+<analysis>+Core question: <the actual information need>+Axes (3+ orthogonal): <axis — what to search, where, why> ...+Codebase relevant: <yes/no> · External: <yes/no> · Browsing: <yes/no> · Verification likely: <yes/no> · Report requested: <no | format>+</analysis>```-### 1C. Browsing Agents (for protected/dynamic pages) — spawn 1-3 as needed+Then create the session directory:+```bash+mkdir -p .omo/ultraresearch/$(date +%Y%m%d-%H%M%S)```-task(- category="quick",- run_in_background=true,- load_skills=["browsing", "insane-search"],- prompt="ULTRARESEARCH BROWSER SWEEP-SESSION_DIR: [session_dir_path]+This is `$SESSION_DIR`. The orchestrator owns the journal: you write every file in it; workers never do. Maintain:-Your mission: Access and extract content from URLs that regular fetch cannot reach:-[list of URLs]+- `wave-<N>-<kind>-<axis>.md` — your digest of each worker return: key findings, sources with URLs, and the worker's EXPAND markers verbatim.+- `expansion-log.md` — per wave: workers spawned, markers gained, leads opened and closed.+- `verify-<slug>.md`, `SYNTHESIS.md`, `REPORT.*` from later phases.-Use the browsing skill's two-tier approach:-1. Try insane-search first (headless extraction, WAF bypass)-2. If that fails, use CloakBrowser+agent-browser (stealth Chromium)+Append each digest the moment its worker returns, not in a batch at the end — the journal is your recovery point after context loss and the user's audit trail.-For each URL: extract ALL content, take screenshots if visual context matters.-APPEND findings to $SESSION_DIR/browsed-[slug].md with URL, method, content.+## Phase 1 — Saturation wave-## EXPAND MARKERS-- [ ] EXPAND: [new lead from browsed content] — [why] — [angle]-"-)-```+Launch every first-wave worker in a single turn, all in background. Sequential launches and "start with one and see" defeat the mode.-### 1D. Cross-Repository Deep Dive Agents — spawn 1-2 for implementation research+Scaling floor — more angles always justify more workers:-```-task(- subagent_type="librarian",- run_in_background=true,- prompt="ULTRARESEARCH REPO DEEP DIVE--SESSION_DIR: [session_dir_path]-Target repositories: [repos identified from initial searches]--For EACH repository:-1. gh repo clone owner/repo ${TMPDIR:-/tmp}/ur-[repo] -- --depth 1-2. Get HEAD SHA for permalinks-3. Read README, CONTRIBUTING, ARCHITECTURE docs-4. grep/ast_grep for core patterns, read key source files, follow call chains-5. git log --oneline -20, git blame on critical sections-6. Construct GitHub permalinks for every finding--APPEND to $SESSION_DIR/repos-[slug].md--## EXPAND MARKERS-- [ ] EXPAND: [dependency/module worth investigating separately] — [why] — [angle]-"-)-```--### Scaling Rules--| Query Scope | explore | librarian | browsing | repo-dive | total min |+| Query scope | explore | librarian | browsing | repo-dive | floor ||---|---|---|---|---|---|| Single topic, codebase only | 3 | 0 | 0 | 0 | 3 || Single topic, web only | 0 | 4 | 1 | 1 | 6 || Single topic, both | 2 | 3 | 1 | 1 | 7 |-| Multi-faceted research | 4 | 6 | 2 | 2 | 14 |+| Multi-faceted | 4 | 6 | 2 | 2 | 14 || Full due diligence | 4 | 6 | 3 | 2 | 15 |-The table is a FLOOR, not a ceiling. More angles = more agents.-------## Phase 2: Recursive Discovery Loop (EXPAND Protocol)--This is NOT a single-pass search. Research is **recursive**. Every finding can spawn new questions.+Role protocols — embed the relevant one in each spawn message; every worker gets a unique angle:-### The EXPAND Marker System+- **Codebase (explore), 2-4 workers.** Grep with 3+ keyword variations; structural/AST search; LSP definitions and references; file-name globs; `git log --all -S '<keyword>'` and `--grep` for history including deleted code. Cross-validate hits across tools. Report absolute file paths, patterns with `file:line`, and how findings connect.+- **Web (librarian), 3-6 workers.** At least 10 distinct websearch queries per worker, each with a different operator or angle (see Search craft); fetch the full page for every result that matters — snippets lie. Context7 with 3+ queries per known library. grep.app and `gh search code|repos|issues` for real-world usage. Official docs via sitemap discovery (`<base>/sitemap.xml`), then targeted pages.+- **Browsing, 0-3 workers.** Pages plain fetch cannot read (WAF, dynamic rendering, login): use the browsing skill; capture screenshots when visual context matters.+- **Repo deep-dive (librarian), 0-2 workers.** Shallow-clone the most relevant repos to `${TMPDIR:-/tmp}`, pin the HEAD SHA, read core modules, follow call chains, return SHA-pinned permalinks.-Every agent MUST end its report with an `EXPAND` section:+Example spawn (codebase axis; librarian, browsing, and repo-dive follow the same contract with their own protocol):-```markdown-## EXPAND MARKERS-- [ ] EXPAND: [new lead discovered] — [why it matters] — [suggested search angle]-- [ ] EXPAND: [another lead] — [why] — [angle]-- [x] DEAD END: [lead that was already fully explored]```--What triggers an EXPAND marker:-- A search result mentions a related library/tool/concept not yet investigated-- A GitHub issue links to another repo with relevant implementation-- A blog post references a paper, benchmark, or alternative approach-- A code pattern imports a module whose behavior is unclear-- Documentation mentions a deprecated predecessor worth understanding-- A comparison article names competitors not yet searched-- An API response reveals undocumented endpoints or features-- A forum answer contradicts official docs (needs verification)--### The Expansion Loop--After collecting initial agent results:--1. **Read ALL files in `$SESSION_DIR/`**-2. **Scan for unchecked `[ ] EXPAND:` markers** across all reports-3. **Deduplicate** — if two agents flagged the same lead, merge into one-4. **For each unique unchecked EXPAND marker**, spawn a NEW agent:--```-task(- subagent_type="librarian", // or "explore" if codebase-scoped- run_in_background=true,- prompt="ULTRARESEARCH EXPANSION — LEAD: [expand marker text]--SESSION_DIR: [session_dir_path]-PARENT FINDING: [which report spawned this lead]-EXPANSION WAVE: [N]--This is a recursive expansion. A previous research agent found this lead.-Investigate it thoroughly using the full websearch saturation protocol.-ALL SEARCHES IN ENGLISH unless the topic is inherently local.-Fire 10+ websearch calls with advanced operators for this specific lead.--APPEND to $SESSION_DIR/expand-[wave]-[slug].md.-Include your OWN EXPAND markers if you discover further leads.-"-)-```--5. **Repeat until convergence**:- - No new unchecked EXPAND markers remain, OR- - 3 consecutive expansion waves produce no new actionable leads, OR- - Expansion depth reaches 5 levels (safety cap — override with user confirmation)--6. **Track expansion state** in `$SESSION_DIR/expansion-log.md`:--```markdown-# Expansion Log--## Wave 1 (initial)-- Spawned: 8 agents-- EXPAND markers generated: 12-- New leads: [list]--## Wave 2-- Spawned: 5 agents (from 12 markers, 7 were duplicates/dead-ends)-- EXPAND markers generated: 4--## Wave 3-- Spawned: 2 agents-- EXPAND markers generated: 0-- CONVERGED — no new leads+task(subagent_type="explore", run_in_background=true, prompt="TASK: act as a codebase researcher. AXIS: <specific angle>.+This is an explicit exhaustive-research assignment. Your default retrieval budget and stop-when-answered rules do not apply — run the full protocol below and report every lead.+SCOPE: find everything in this codebase related to <angle>: <what complete looks like>.+PROTOCOL: grep 3+ keyword variations; structural search; LSP references; globs; git history (-S and --grep). Cross-validate across tools. Report absolute paths and file:line patterns.+End your reply with the ## EXPAND tail: '- LEAD: <discovery> — WHY: <why> — ANGLE: <search>' per lead, or 'none — <reason>'.")```-**Do NOT wait for all agents before starting the next wave.** Collect as each finishes. Scan for EXPAND markers. Spawn immediately. The loop is continuous.-----+## Phase 2 — Expand until convergence-## Phase 3: Empirical Verification+This loop is what makes the mode research rather than search. Collect workers as they finish — never wait for the full wave:-**Any claim that is ambiguous, contested, or unverifiable from documentation alone MUST be verified by running actual code.**--This is not optional. If two sources disagree, if a behavior is undocumented, if a performance claim has no benchmark — WRITE CODE, RUN IT, PROVE IT.--### When to Verify--| Signal | Action |-|---|---|-| Source A says X, Source B says Y | Write a test that proves which is correct |-| "This should work" / "In theory" | Write code that actually does it and capture output |-| Performance claim without benchmark | Write a benchmark, run it, report numbers |-| API behavior not in docs | Make the actual API call, capture response |-| Library version compatibility claim | Install both versions, run the same code, compare |-| "Deprecated but still works" | Try it, capture the warning/error/success |-| Security claim | Write a PoC that demonstrates the vulnerability or proves safety |--### How to Verify--Spawn a verification agent for each claim that needs proof:+1. Journal the return: digest plus verbatim EXPAND markers into `wave-<N>-<kind>-<axis>.md`.+2. Deduplicate new markers against `expansion-log.md` — every lead ever seen, not just confirmed ones, or rejected leads resurface each wave.+3. Spawn an expansion worker immediately for each new unchecked lead:```-task(- category="deep",- run_in_background=true,- prompt="ULTRARESEARCH VERIFICATION — CLAIM: [the claim to verify]--SESSION_DIR: [session_dir_path]-SOURCE: [where this claim came from]-CONTRADICTION: [what the opposing source says, if any]--Your job: PROVE OR DISPROVE this claim with executable evidence.--1. Write a minimal, self-contained script that tests the claim-2. Execute it (use bash, or for complex cases: uv run --with [deps] python -c '...')-3. Capture the FULL output (stdout + stderr)-4. If it requires a specific environment/dependency, install it first-5. If it requires network access, make the actual call-6. If it requires a specific version, pin it--EVIDENCE FORMAT — append to $SESSION_DIR/verify-[slug].md:--## Verification: [claim summary]-### Claim-[exact claim being tested]-### Source-[URL or file path]-### Test Code-\`\`\`[language]-[the exact code that was executed]-\`\`\`-### Execution Output-\`\`\`-[full stdout + stderr]-\`\`\`-### Verdict-**CONFIRMED** / **REFUTED** / **PARTIALLY TRUE** — [explanation with evidence]-### Environment-- OS: [os]-- Runtime: [version]-- Dependencies: [list with versions]-"-)-```--### SparkShell for Codex Harness--When running under the Codex harness where SparkShell is available, prefer SparkShell for code execution — it provides intelligent command classification, secret redaction, and tmux-integrated output capture. The verification agent should use SparkShell for:-- Running test scripts with full output capture-- Interactive REPL sessions for exploratory verification-- Long-running benchmarks that benefit from tmux durability-- Multi-step verification sequences that need session persistence--When SparkShell is not available (OpenCode harness), use bash + `uv run` for Python, `bun run` for TypeScript, or direct compilation for Rust/Go/C.-------## Phase 4: Synthesize--Once the expansion loop has CONVERGED and all agents (including verification) have reported:--1. Read ALL files in `$SESSION_DIR/`-2. Cross-reference findings across ALL agents (initial + expansion waves + verification)-3. Identify:- - **Consensus**: findings confirmed by 2+ agents/sources- - **Verified facts**: claims proven by code execution- - **Unique discoveries**: found by only one agent but high-value- - **Contradictions**: conflicting info (flag with both sources + verification result)- - **Gaps**: questions still unanswered despite saturation--4. Write synthesis to `$SESSION_DIR/SYNTHESIS.md`:--```markdown-# Ultraresearch Synthesis: [query]-**Date**: [date]-**Agents Spawned**: [total across all waves]-**Expansion Waves**: [count]-**Sources Consulted**: [count]-**Verifications Executed**: [count]--## Executive Summary-[2-3 paragraph answer to the user's core question, clear and direct]--## Detailed Findings--### [Topic Area 1]-**Consensus**: [what multiple sources agree on]-**Evidence**: [source links]-**Key Quote**: "[under 20 words]" — [Source]-**Verified**: [yes/no — link to verification report if yes]--### [Topic Area 2]-...--## Codebase Findings-[relevant code locations with absolute paths and line numbers]--## External Sources (ranked by quality)-1. [URL] — [relevance, reliability assessment, access date]-2. ...--## Verified Claims-| Claim | Verdict | Evidence |-|---|---|---|-| [claim] | CONFIRMED/REFUTED | [link to verify-*.md] |--## Contradictions Found-- [source A says X] vs [source B says Y] — [verdict with evidence]--## Remaining Gaps-- [what we couldn't find despite exhaustive search]--## Expansion Trace-- Wave 1: [N agents] -> [M expand markers]-- Wave 2: [N agents] -> [M expand markers]-- Convergence: [reason]--## Raw Agent Reports-- [list of all session files]+task(subagent_type="librarian", run_in_background=true, prompt="TASK: expansion wave <N> — investigate: <lead>.+PARENT: <which return surfaced it>. This is an explicit exhaustive-research assignment; budgets do not apply.+<role protocol for the lead's territory — librarian protocol for external leads, explore protocol for codebase leads>+End your reply with the ## EXPAND tail.")```-5. **If the user requested a report**: proceed to Phase 5.-6. **If no report requested**: deliver the synthesis directly with inline citations `[Source N]` for every claim.-------## Phase 5: Report Generation (when requested)--If the user asked for a report, presentation, or formatted deliverable — spawn a report generation wave AFTER synthesis.--### Determine Output Format--| User Signal | Format | Tools |-|---|---|---|-| "report", "document", "보고서" | Markdown (default) | Direct write |-| "pdf" | PDF via HTML-to-PDF | `frontend-design` + python `weasyprint` |-| "pptx", "slides", "presentation", "발표" | PPTX | python `python-pptx` |-| "html", "webpage" | Standalone HTML | `frontend-design` skill |-| No format specified | Markdown | Direct write |+4. Record the wave in `expansion-log.md`: spawned, markers gained, leads opened/closed.-### Report Content Agents+**Convergence — the only stop rules while this mode is active.** Run at least 2 expansion waves on any multi-faceted query before claiming convergence; then stop only when one holds:-#### A. Data Visualization Agent+- Zero unchecked leads remain — each investigated or closed as duplicate/dead end.+- 3 consecutive waves produced no new actionable leads.+- Expansion depth reached 5 waves — pause, show the open leads, and ask the user whether to extend.-```-task(- category="quick",- run_in_background=true,- prompt="ULTRARESEARCH REPORT — DATA VISUALIZATION--SESSION_DIR: [session_dir_path]--Read ALL findings in $SESSION_DIR/. Identify data that benefits from visualization:-- Comparison tables -> bar/radar charts-- Timeline data -> timeline charts-- Architecture -> mermaid diagrams-- Statistics/benchmarks -> graphs with clear labels-- Relationships -> network/dependency graphs--Generate using:-uv run --with numpy --with matplotlib --with plotly python -c \"[code]\"--Save ALL images to $SESSION_DIR/assets/-Write index to $SESSION_DIR/assets/manifest.md-"-)-```+## Phase 3 — Verify contested claims by running code-#### B. Screenshot Collection Agent+Settle with executed code, not judgment, whenever sources disagree, a behavior is undocumented, a claim is performance- or compatibility-shaped, or the honest answer is "it should work". Spawn one verification worker per claim:```-task(- category="quick",- run_in_background=true,- load_skills=["browsing"],- prompt="ULTRARESEARCH REPORT — SCREENSHOTS--SESSION_DIR: [session_dir_path]--Read web findings. Identify the top 5-10 most important web sources.-For each: full page screenshot using the browsing skill.-Save to $SESSION_DIR/assets/screenshots/-Write manifest to $SESSION_DIR/assets/screenshots/manifest.md-"-)+task(category="deep", run_in_background=true, prompt="TASK: verify by execution: <claim>.+SOURCE: <where it came from>; CONTRADICTION: <opposing source, if any>.+Write a minimal self-contained script that tests the claim; run it (uv run --with <deps> python / bun / direct compile); capture full stdout+stderr; pin versions.+Reply with: the exact code, the full output, environment (OS, runtime, dependency versions), and a verdict — CONFIRMED / REFUTED / PARTIAL — grounded in the output.")```-#### C. Image Generation Agent (if diagrams/infographics needed)+Journal each verdict to `verify-<slug>.md`.-```-task(- category="quick",- run_in_background=true,- load_skills=["imagegen"],- prompt="ULTRARESEARCH REPORT — INFOGRAPHICS--SESSION_DIR: [session_dir_path]--Read synthesis. Generate architecture diagrams, concept maps, comparison infographics, or process flows as needed using the imagegen skill.-Save to $SESSION_DIR/assets/generated/-"-)-```--#### D. Report Assembly Agent+## Phase 4 — Synthesize-For HTML, PDF, or PPTX output: the report assembly agent MUST first discover and load **every available frontend and design skill** in the system before writing a single line. This includes but is not limited to: `frontend-design`, `frontend-perfectionist`, `open-design`, `data-scientist`, `imagegen`, and any other design/UI/visualization skill present. Read each skill's SKILL.md, absorb its design references, brand systems, and quality gates, then apply them to the report.+After convergence and all verifications, re-read the whole journal and write `SYNTHESIS.md`:```-task(- category="deep",- run_in_background=true,- load_skills=["frontend-design", "frontend-perfectionist", "open-design", "data-scientist", "imagegen"],- prompt="ULTRARESEARCH REPORT — FINAL ASSEMBLY--SESSION_DIR: [session_dir_path]-REQUESTED FORMAT: [markdown/html/pdf/pptx]--## MANDATORY FIRST STEP--Before writing anything, discover and read ALL available frontend, design, and visualization skills:-- Read $frontend-design SKILL.md — absorb design references, anti-slop rules, brand-grade standards-- Read $frontend-perfectionist SKILL.md — absorb Lighthouse 100 perf gates, render measurement, Core Web Vitals-- Read $open-design SKILL.md — discover the 137+ composable design skills and 150+ brand-grade design systems-- Read $data-scientist SKILL.md — absorb DuckDB/Polars/numpy/matplotlib best practices-- Read $imagegen SKILL.md — absorb async image generation workflow-- List ALL other available skills (ls ~/.agents/skills/ and project .agents/skills/) and read any that relate to design, visualization, or document generation--Apply EVERYTHING you learned from those skills to the report. The report is not a text dump — it is a designed artifact.--Read:-1. $SESSION_DIR/SYNTHESIS.md-2. $SESSION_DIR/assets/manifest.md-3. $SESSION_DIR/assets/screenshots/manifest.md-4. ALL $SESSION_DIR/*.md files for detail--## Report Structure-1. **Executive Summary** — 3-5 sentences answering the core question-2. **Key Findings** — organized by theme, not by agent-3. **Detailed Analysis** — each finding with:- - Evidence (direct quotes under 20 words, with source URL)- - Supporting charts (embed from assets/)- - Code examples with file paths or GitHub links- - Verification results where applicable-4. **Comparative Analysis** — if multiple options/approaches exist-5. **Visual Evidence** — embedded screenshots, charts, diagrams-6. **Sources & References** — numbered, with URLs, access dates, reliability notes-7. **Appendix: Methodology** — agents spawned, searches executed, expansion waves, verifications--## Quality Rules-- Every claim MUST cite: [Source N] linking to reference list-- Every quote under 20 words with quotation marks and attribution-- Tables for comparisons, not prose-- Charts/graphs for quantitative data, not number tables-- Screenshots for UI/visual claims-- Professional but accessible — a smart non-expert understands everything-- Technical depth preserved — an expert finds no oversimplifications-- Design quality: apply the brand-grade standards from the design skills you loaded. No generic HTML. No unstyled tables. No default matplotlib themes.--## Format-Specific--**Markdown**: $SESSION_DIR/REPORT.md with  embeds.--**HTML**: Single self-contained HTML with embedded CSS. Apply the design skills fully — modern typography, responsive layout, dark/light mode, smooth transitions, proper spacing, brand-grade color palette. Base64-embedded images. Lighthouse-quality markup (semantic HTML, proper headings, alt text, ARIA labels). $SESSION_DIR/REPORT.html.--**PDF**: Generate the HTML report first (full design quality as above), then:-uv run --with weasyprint python -c \"from weasyprint import HTML; HTML('$SESSION_DIR/REPORT.html').write_pdf('$SESSION_DIR/REPORT.pdf')\"-Ensure print-friendly CSS: proper page breaks, margins, header/footer. $SESSION_DIR/REPORT.pdf.--**PPTX**: Use python-pptx with Pillow for image handling:-uv run --with python-pptx --with Pillow python -c \"[build slides]\"-Slide design: consistent theme, proper typography hierarchy, one key finding per slide, full-bleed images where appropriate, minimal text per slide, speaker notes with detail.-Slide flow: Title -> Executive Summary -> Key Finding per slide -> Visual Evidence -> Comparative Analysis -> Sources.-$SESSION_DIR/REPORT.pptx.-"-)-```-------## Advanced Search Operator Reference--Agents MUST use these aggressively on every websearch call. This is core technique, not garnish.--### Web Search Operators-| Operator | Example | Purpose |-|---|---|---|-| `site:` | `site:github.com react hooks` | Restrict to domain |-| `filetype:` | `filetype:pdf machine learning survey` | Specific file types |-| `intitle:` | `intitle:benchmark comparison 2026` | Title must contain term |-| `inurl:` | `inurl:api reference authentication` | URL must contain term |-| `"exact"` | `"dependency injection" typescript` | Exact phrase match |-| `-term` | `react state management -redux` | Exclude term |-| `OR` | `nextjs OR nuxt server components` | Either term |-| `before:` | `LLM agents before:2026-01-01` | Date upper bound |-| `after:` | `LLM agents after:2025-06-01` | Date lower bound |-| `related:` | `related:vercel.com` | Similar sites |-| `*` wildcard | `"how to * with typescript"` | Fill-in-the-blank |--### Combination Patterns+# Ultraresearch Synthesis: <query>+Workers: <total> · Waves: <count> · Sources: <count> · Verifications: <count>+## Executive summary — 2-3 paragraphs answering the core question+## Findings by theme — per theme: consensus, evidence links, key quote (<20 words, attributed), verified yes/no+## Codebase findings — absolute paths with line references+## Sources (ranked) — URL, what it contains, reliability, access date+## Verified claims — claim | verdict | verify-<slug>.md+## Contradictions — source A vs source B, resolution with evidence+## Gaps — what saturation could not answer+## Expansion trace — per wave: workers → markers; convergence reason```-# Official docs-"[library] site:[library].dev OR site:docs.[library].com"-# GitHub implementations-"[pattern] site:github.com filetype:ts OR filetype:tsx"+Deliver the synthesis with inline `[Source N]` citations on every claim. When no report was requested, this is the deliverable.-# Recent discussion-"[topic] site:reddit.com OR site:news.ycombinator.com after:2025-01-01"+## Phase 5 — Report (only when requested)-# Academic + industry-"[topic] site:arxiv.org OR filetype:pdf survey OR benchmark [year]"+Format by the user's words: "report" / "document" → Markdown (default) · "pdf" → HTML first, then weasyprint (`uv run --with weasyprint python`) · "slides" / "presentation" / "deck" → python-pptx · "html" / "webpage" → standalone HTML.-# Stack Overflow high engagement-"[topic] site:stackoverflow.com [specific error or pattern]"+Asset workers (background, parallel): charts for quantitative findings (`uv run --with matplotlib --with plotly python`) saved by you to `$SESSION_DIR/assets/`; full-page screenshots of the top 5-10 sources (browsing skill); generated diagrams (imagegen skill) when architecture or flows need them.-# Korean sources (secondary sweep only)-"[topic] site:tistory.com OR site:velog.io OR site:naver.com"+Assembly worker — `task(category="deep", load_skills=["frontend-design", "open-design", "data-scientist", "imagegen"], run_in_background=true, ...)`: before writing, read every available design and visualization skill and apply it — the report is a designed artifact, not a text dump. Structure: executive summary → key findings by theme → detailed analysis (quotes under 20 words with attribution, charts, SHA-pinned permalinks, verification results) → comparative analysis when options compete → numbered sources with access dates → methodology appendix (workers, waves, searches, verifications). Every claim cites `[Source N]`.-# Changelog hunting-"[library] changelog OR release notes OR migration guide [version]"+## Search craft-# Alternatives/comparison-"[topic] vs OR alternative OR comparison OR benchmark"-```--### GitHub Search (gh CLI)+English first: run every search in English by default — it is the largest, most authoritative corpus on every engine, GitHub, and documentation site. Add a secondary local-language sweep (1-2 librarians) only after the English sweep, when the topic is inherently local, or when the user asks for sources in a specific language.-```bash-gh search code '[pattern]' --language typescript --limit 30-gh search repos '[topic]' --sort stars --limit 20-gh search issues '[error message]' --state all --sort reactions --limit 20-gh search prs '[feature]' --state merged --sort updated --limit 15-```+Vary operators on every query — same query twice wastes a worker:-### grep.app--```-grep_app_searchGitHub(query: "[pattern]", language: ["TypeScript", "JavaScript"])-grep_app_searchGitHub(query: "[pattern]", repo: "owner/repo")-grep_app_searchGitHub(query: "[config key]", language: ["JSON", "YAML", "TOML"])-```-----+| Operator | Example | Use |+|---|---|---|+| `site:` | `site:github.com <topic>` | Restrict to a domain |+| `filetype:` | `filetype:pdf <topic> survey` | Papers, specs |+| `intitle:` / `inurl:` | `intitle:benchmark <topic>` | Targeted pages |+| `"exact"` / `-term` | `"<exact phrase>" -tutorial` | Precision, exclusion |+| `OR` | `<a> OR <b> <topic>` | Coverage |+| `before:` / `after:` | `<topic> after:2025-06-01` | Recency control |----+High-yield combinations: official docs (`site:<docs domain>`), GitHub implementations (`site:github.com`), recent discussion (`site:reddit.com OR site:news.ycombinator.com after:<date>`), academic (`site:arxiv.org OR filetype:pdf survey`), changelog hunting (`changelog OR "release notes" <version>`), alternatives (`vs OR alternative OR comparison`).-## Anti-Patterns+## Failure modes-| Pattern | Why it fails | Fix |-|---|---|---|-| Sequential agent spawning | Wastes time, defeats purpose | ALL agents in ONE turn |-| Single websearch per librarian | Barely scratches the surface | 10-20 websearch calls MINIMUM per agent |-| No search operators | Generic results, misses targeted content | site:/filetype:/intitle: on EVERY websearch |-| Not fetching full pages | Search snippets lie | webfetch every important result |-| Skipping Context7 | Misses official doc embeddings | Always query for known libraries |-| Not recording to session dir | Findings lost, can't synthesize | Every agent MUST append to $SESSION_DIR/ |-| Ignoring EXPAND markers | Misses recursive discoveries | Every unchecked marker MUST be investigated |-| No EXPAND markers in reports | Breaks the recursive loop | Every agent MUST output EXPAND section |-| Stopping when "enough" found | Surface-level results | Goal is EXHAUSTION, minimum 2 expansion waves |-| Single-pass research | Misses second-order connections | Expand until convergence |-| Same query to multiple agents | Duplicate work | Each agent gets UNIQUE angle |-| Searching in non-English first | Smaller corpus, less authoritative | English first, ALWAYS |-| "It should work" without proof | Unverified speculation | Write code, run it, capture output |-| Delivering without citations | Unverifiable claims | Every claim needs [Source N] with URL |-| Skipping visualization for data | Dense tables nobody reads | Charts/graphs for quantitative findings |-| Trusting a single source | Single point of failure | Cross-validate across 3+ sources |-| Ambiguous claim left unverified | Readers inherit uncertainty | Spawn verification agent, run actual code |+| Failure | Correction |+|---|---|+| Sequential spawning, or trimming the first wave | All first-wave workers in one turn, background, scaling floor respected |+| Worker reply without the EXPAND tail | One follow-up demanding it; the lane stays open until it lands |+| Stopping after wave 1 because "enough was found" | Convergence rules only: 2+ expansion waves, leads run dry |+| Obeying a surrounding "stop exploring" rule mid-research | Authority section — those rules do not bind this mode |+| Asking a worker to write journal or session files | Workers are read-only; you journal every return |+| Two workers given the same angle | One unique angle per worker, always |+| Contested claim settled by judgment | Phase 3 — run code, capture output, verdict |+| Deliverable claims without citations | Every claim cites a source or a verification artifact |diff --git a/plugins/omo/skills/ulw-loop/SKILL.md b/plugins/omo/skills/ulw-loop/SKILL.mdindex 88f08fee..91293585 100644--- a/plugins/omo/skills/ulw-loop/SKILL.md+++ b/plugins/omo/skills/ulw-loop/SKILL.md@@ -9,12 +9,12 @@ metadata:Use this skill when the user asks for `ulw-loop`, `ulw`, durable goal execution, evidence-led work, manual QA, or checkpointed long-running delivery.-This Codex skill is intentionally compact to avoid adding a large operating manual to an already-full conversation. The full workflow lives in `references/full-workflow.md`. Read only the sections needed for the current phase, then execute them exactly.+This skill is intentionally compact. The full workflow lives in `references/full-workflow.md`. Read only the sections needed for the current phase, then execute them exactly.## Required First Steps1. Open `references/full-workflow.md`.-2. Read through **Bootstrap**, **Execution Loop**, and the **Manual-QA channels** table before running any ULW command or recording evidence.+2. Read through **Bootstrap** (including its tier triage), **Execution Loop**, and the **Manual-QA channels** table before running any ULW command or recording evidence.3. If the task has code edits, tests, QA, or commit work, follow the full workflow's delegation and evidence rules. Tests alone never prove done.## Non-Negotiables@@ -22,15 +22,15 @@ This Codex skill is intentionally compact to avoid adding a large operating manu- Use the ulw-loop CLI state under `.omo/ulw-loop`; do not hand-edit goal state.- After any compaction or context loss, re-read brief + goals + ledger FIRST (`omo sparkshell cat .omo/ulw-loop/ledger.jsonl` or read directly) plus `omo ulw-loop status --json`, then resume; never re-plan from scratch.- If `omo ulw-loop create-goals` says the existing aggregate is already complete, start unrelated new work with a fresh `--session-id <new-id>` instead of steering or forcing the completed default state. Use `--force` only to intentionally overwrite completed evidence.-- Every success criterion needs observable evidence from a real channel: tmux, HTTP, browser, or computer-use.+- Every success criterion needs observable evidence from a real surface: a channel (tmux, HTTP, browser, computer-use) or, for CLI- or data-shaped criteria, an auxiliary surface (CLI stdout, DB diff, parsed config dump).- Record evidence through the CLI only after cleanup receipts are available.- Delegate code edits, test writes, fixes, and QA execution to right-sized Codex subagents when the workflow requires it.-- Every `spawn_agent` message starts with `TASK:`, then names `DELIVERABLE`, `SCOPE`, and `VERIFY`; put role and specialty instructions inside `message` because the Codex tool schema only accepts `task_name`, `message`, and `fork_turns`; prefer `fork_turns: "none"` unless full history is truly required.-- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short wait_agent cycles. Never use a single long blocking wait for them.+- Every `multi_agent_v1.spawn_agent` message starts with `TASK:`, then names `DELIVERABLE`, `SCOPE`, and `VERIFY`; put role and specialty instructions inside `message`; use `fork_context: false` unless full history is truly required.+- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short `multi_agent_v1.wait_agent` cycles. Never use a single long blocking wait for them.- For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long reading, testing, or review passes, and `BLOCKED: <reason>` only when it cannot progress.-- While any child is active, keep the parent visibly alive with brief status updates that include active subagent count, agent names, latest `WORKING:` phase, and whether the parent is waiting for mailbox updates.-- Track spawned agent names locally. Use `wait_agent` for mailbox signals, not proof of completion. A timeout only means no new mailbox update arrived; after a timeout, run a single `list_agents` check for the named child when you need reassurance. If it is running or its latest message is `WORKING:`, treat it as alive.-- Do not use `list_agents` as a polling loop or status feed; it can replay large payloads. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Then record inconclusive and respawn a smaller `fork_turns: "none"` task with the missing deliverable.+- Track spawned agent names locally. Use `multi_agent_v1.wait_agent` for mailbox signals, not proof of completion. A timeout only means no new mailbox update arrived. Treat a running child as alive.+- While children run, surface the active subagent count, agent names, and latest `WORKING:` phase.+- Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Then record inconclusive and respawn a smaller `fork_context: false` task with the missing deliverable.- Use `git-master` for git-tracked edits: inspect recent and touched-path commit history, then commit each verified work unit atomically in the repository's observed language, scope, and message style with only that unit's files staged.## Codex Tool Mapping@@ -39,11 +39,11 @@ The full workflow may mention OpenCode-style orchestration examples. In Codex, t| Workflow intent | Codex tool || --- | --- |-| Plan agent | `spawn_agent({"task_name":"...","message":"TASK: act as a planning agent. ...","fork_turns":"none"})` |-| Search/read-only worker | `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` |-| Implementation or QA worker | `spawn_agent({"task_name":"...","message":"TASK: act as an implementation or QA worker. ...","fork_turns":"none"})` |-| Final verification reviewer | `spawn_agent({"task_name":"...","message":"TASK: act as a rigorous reviewer. ...","fork_turns":"none"})` |-| Wait for background result | `wait_agent(...)` |-| Clean up finished worker | `close_agent(...)` |+| Plan agent | `multi_agent_v1.spawn_agent({"message":"TASK: act as a planning agent. ...","fork_context":false})` |+| Search/read-only worker | `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","fork_context":false})` |+| Implementation or QA worker | `multi_agent_v1.spawn_agent({"message":"TASK: act as an implementation or QA worker. ...","fork_context":false})` |+| Final verification reviewer | `multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous reviewer. ...","fork_context":false})` |+| Wait for background result | `multi_agent_v1.wait_agent(...)` |+| Clean up finished worker | `multi_agent_v1.close_agent(...)` |When translating `load_skills=[...]`, include the requested skill names in the spawned agent's `message`.diff --git a/plugins/omo/skills/ulw-loop/references/full-workflow.md b/plugins/omo/skills/ulw-loop/references/full-workflow.mdindex 645f9c15..1ce6583c 100644--- a/plugins/omo/skills/ulw-loop/references/full-workflow.md+++ b/plugins/omo/skills/ulw-loop/references/full-workflow.md@@ -15,20 +15,20 @@ Prove EVERY success criterion with captured observable evidence from a real-usagTESTS 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/ulw-loop/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.+## Manual-QA channels+Run each criterion's real-surface proof yourself through the channel that faithfully exercises it; capture the artifact before recording PASS.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** — use Chrome to drive the REAL page; if Chrome is not available, download and use agent-browser (https://github.com/vercel-labs/agent-browser). Capture action log + screenshot path. Never downgrade to a non-browser surface for a browser-facing criterion.4. **Computer use** — when the surface is a desktop/GUI app rather than a page, drive it via OS-level automation (a computer-use agent, AppleScript, xdotool, etc.) against the running app; capture action log + screenshot. Use this for any non-browser GUI criterion.-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.+Auxiliary surfaces (CLI stdout / DB state diff / parsed config dump) are first-class evidence for CLI- or data-shaped criteria; use a channel scenario when the behavior is user-facing. `--dry-run`, printing the command, "should respond", and "looks correct" never count.## Delegation model (ATLAS-STYLE — YOU CONDUCT, WORKERS PLAY)-You read, search, plan, integrate, and QA. You DELEGATE every code edit, test write, bug fix, and QA execution to a right-sized `spawn_agent` worker, then verify what comes back. Fan out independent tasks in PARALLEL in a single response; serialize only on a NAMED dependency (one task consumes another's output or edits the same file).+You read, search, plan, integrate, and QA. You DELEGATE every code edit, test write, bug fix, and QA execution to a right-sized `multi_agent_v1.spawn_agent` worker, then verify what comes back. Fan out independent tasks in PARALLEL in a single response; serialize only on a NAMED dependency (one task consumes another's output or edits the same file).-Size each worker to the task. Put the intended role, rigor level, and specialty inside the worker `message`; the Codex `spawn_agent` schema only accepts `task_name`, `message`, and `fork_turns`.+Size each worker to the task. Put the intended role, rigor level, and specialty inside the worker `message`.| Task shape | Message instruction ||---|---|@@ -42,16 +42,16 @@ Size each worker to the task. Put the intended role, rigor level, and specialtyFor reviewer work, use a self-contained reviewer assignment, tight scope, and explicit verification in `message`. Never spawn a context-only child for review.-Every worker message MUST carry: goal + exact files in scope; the baseline characterization test pinning current behavior when the task touches existing code, then the failing test / reproduction required before production code; constraints + project rules; the verification commands to run; the ONE Manual-QA channel and the exact evidence artifact to capture; for git-tracked edits, require `git-master` plus repository-wide and touched-path commit history inspection before commit. Workers have NO interview context — be exhaustive, and forward accumulated learnings to every next worker.+Every worker message MUST carry: goal + exact files in scope; the PIN + failing-first proof required before production code (Per-Criterion Cycle step 3); constraints + project rules; the verification commands to run; the ONE Manual-QA channel and the exact evidence artifact to capture; for git-tracked edits, require `git-master` plus repository-wide and touched-path commit history inspection before commit. Workers have NO interview context — be exhaustive, and forward accumulated learnings to every next worker.Codex subagent reliability:-- Start every `spawn_agent` message with `TASK: <imperative assignment>`, then name `DELIVERABLE`, `SCOPE`, and `VERIFY`. State that it is an executable assignment, not a context handoff.-- Prefer `fork_turns: "none"` unless full history is truly required; paste only the context the child needs. Full-history forks can make the child continue old parent context instead of the delegated task.-- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short wait_agent cycles. Never use a single long blocking wait for them.+- Start every `multi_agent_v1.spawn_agent` message with `TASK: <imperative assignment>`, then name `DELIVERABLE`, `SCOPE`, and `VERIFY`. State that it is an executable assignment, not a context handoff.+- Use `fork_context: false` unless full history is truly required; paste only the context the child needs. Full-history forks can make the child continue old parent context instead of the delegated task.+- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short `multi_agent_v1.wait_agent` cycles. Never use a single long blocking wait for them.- For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long reading, testing, or review passes, and `BLOCKED: <reason>` only when it cannot progress.- While any child is active, keep the parent visibly alive with active subagent count, agent names, latest `WORKING:` phase, and whether the parent is waiting for mailbox updates.-- Track spawned agent names locally. Use `wait_agent` for mailbox signals, not proof of completion. A timeout only means no new mailbox update arrived; after a timeout, run a single `list_agents` check for the named child when you need reassurance. If it is running or its latest message is `WORKING:`, treat it as alive. Do not use `list_agents` as a polling loop or status feed; it can replay large payloads.-- Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Then send `TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>` when a targeted followup can still recover the lane; otherwise record inconclusive, do not count it as pass/review approval, close if safe, and respawn a smaller `fork_turns: "none"` task with the missing deliverable.+- Track spawned agent names locally. Use `multi_agent_v1.wait_agent` for mailbox signals, not proof of completion. A timeout only means no new mailbox update arrived. Treat a running child as alive.+- Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Then send `TASK STILL ACTIVE: return <deliverable> or BLOCKED: <reason>` when a targeted followup can still recover the lane; otherwise record inconclusive, do not count it as pass/review approval, close if safe, and respawn a smaller `fork_context: false` task with the missing deliverable.## Artifacts- `.omo/ulw-loop/brief.md`: original brief and durable constraints.@@ -117,16 +117,14 @@ Write state through the CLI path. Do not hand-edit state files.### 2. Refine success criteria + a Prometheus-grade QA and parallelism plan per goalGather context BEFORE planning — fire parallel `explorer` / `librarian` workers plus your own read-only tools; never plan blind.-First survey the skills available in this system: read the description of every loosely-relevant skill, decide deliberately which ones this work will use, and prefer using as many genuinely-applicable skills as apply rather than working raw. Then size the scope: count distinct surfaces, files, and steps. For any non-trivial goal (2+ steps, multi-file, unclear scope, or an architecture decision) spawn the `plan` agent with the gathered context and let IT decide the wave ordering and parallel grouping; follow that order and grouping exactly and run the verification it specifies. Only a genuinely trivial single-step goal may skip the plan agent.-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, concretely and upfront: `id`, `scenario` (the exact tool — curl / tmux / playwright / computer-use — plus exact steps with specific inputs and a binary pass/fail), `expectedEvidence` (the exact artifact path, e.g. `.omo/ulw-loop/evidence/<goal>-<criterion>.<ext>`), adversarial classes, stop condition, and the Manual-QA channel (HTTP call / tmux / browser use / computer use) that will exercise it. Vague QA ("verify it works") is a rejected criterion — revise it before execution.-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.+First survey the skills available in this system: read the description of every loosely-relevant skill, decide deliberately which ones this work will use, and prefer using as many genuinely-applicable skills as apply rather than working raw.+Then run tier triage per goal and record it with an `annotate_ledger` steering entry. Default is LIGHT — a narrow change inside existing layers. Take HEAVY only on a fact you can point to: a new module / abstraction / domain model; auth, security, or session; an external integration; a DB schema or migration; concurrency, transaction boundaries, or cache invalidation; a cross-domain refactor; or the user signaled care or demanded review. When unsure, take HEAVY; upgrade the moment a HEAVY fact surfaces and never downgrade mid-run.+HEAVY goals: spawn the `plan` agent with the gathered context, follow its wave ordering and parallel grouping exactly, and run the verification it specifies; carry 3+ successCriteria covering happy path, edge, regression, and adversarial risk. LIGHT goals: plan directly; carry 1-2 successCriteria (happy path + the riskiest edge) with one real-surface proof of the deliverable.+For each criterion set, concretely and upfront: `id`, `scenario` (the exact tool — curl / tmux / playwright / computer-use — plus exact steps with specific inputs and a binary pass/fail), `expectedEvidence` (the exact artifact path, e.g. `.omo/ulw-loop/evidence/<goal>-<criterion>.<ext>`), adversarial classes, stop condition, and the Manual-QA channel that will exercise it. Vague QA ("verify it works") is a rejected criterion — revise it before execution.+A criterion's adversarial classes are the ultraqa classes a fact about the change triggers: malformed input, prompt injection, cancel/resume, stale state, dirty worktree, hung or long commands, flaky tests, misleading success output, repeated interruptions. Record untriggered classes as not-applicable in one line.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.-**Plan for maximum parallelism.** Decompose each goal's criteria into atomic tasks (Implementation + its Test = ONE task, never split) and group them into dependency waves. Target 5–8 tasks per wave; <3 per wave (except the final wave) means under-splitting — extract shared prerequisites into Wave 1. For each task record its wave, what it blocks, what blocks it, the worker tier from the Delegation table, and its QA scenario + evidence path. Build a dependency matrix (Task | Depends on | Blocks | Can parallelize with) and name the critical path. Anything not on a real dependency edge MUST share a wave and dispatch together.-Record manual QA notes when behavior is user-visible.+**Plan for maximum parallelism (HEAVY goals).** Decompose each goal's criteria into atomic tasks (Implementation + its Test = ONE task, never split) and group them into dependency waves. Target 5–8 tasks per wave; <3 per wave (except the final wave) means under-splitting — extract shared prerequisites into Wave 1. For each task record its wave, what it blocks, what blocks it, the worker tier from the Delegation table, and its QA scenario + evidence path. Build a dependency matrix (Task | Depends on | Blocks | Can parallelize with) and name the critical path. Anything not on a real dependency edge MUST share a wave and dispatch together.Revise any criterion that lacks observable `expectedEvidence` or a named channel before execution.### 3. Inspect state@@ -152,11 +150,11 @@ Loop per goal. Cap at 5 cycles per goal. Cap identical same-criterion failures a### Per-Criterion Cycle1. PLAN: read `criterion.scenario`, `criterion.expectedEvidence`, prior ledger entries, and safety bounds. Identify which tasks in the current wave are independent.2. Register atomic todos via `update_plan` — one ultra-granular step per action, `path: <action> for <criterion> - verify by <check>`. Call `update_plan` on every transition (start → `in_progress`, finish → `completed`); exactly one `in_progress`, mark completed immediately, never batch, never let the rendered plan lag behind reality.-3. DELEGATE-IN-PARALLEL: dispatch every independent task in the wave at once via right-sized `spawn_agent` workers (Delegation table). Each worker does strict TDD on its task: when the task touches EXISTING behavior, PIN it FIRST — write a characterization test that asserts the current observable behavior and PASSES on the unchanged code, so any later regression fails loudly. Then RED (the new failing assertion must fail for the RIGHT reason — no syntax/import error), then the SMALLEST GREEN change; before GREEN work that depends on external review, PR, issue, or branch state, refresh current branch/PR/issue state, preserve existing ordering/policy, and separate compatibility detection from policy changes unless the goal explicitly asks to change policy. A GREEN needing >~20 lines means the test was too coarse — instruct a split. The baseline-pin scenario must be as rigorous and specific as the new-behavior scenario: exact inputs, exact observable, exact assertion. Serialize only on a NAMED dependency.+3. DELEGATE-IN-PARALLEL: dispatch every independent task in the wave at once via right-sized `multi_agent_v1.spawn_agent` workers (Delegation table). Each worker captures evidence failing-first: when the task touches EXISTING behavior, PIN it FIRST — a characterization test that asserts the current observable behavior and PASSES on the unchanged code, as rigorous as the new-behavior scenario (exact inputs, exact observable, exact assertion). Then RED through the cheapest faithful channel — a unit test where a seam exists, an integration/e2e test where the behavior lives in wiring, or the criterion's scenario captured failing when no test seam exists — failing for the RIGHT reason (no syntax/import error). A test that mirrors its implementation (mock-call assertions, pinned constants, cannot fail under plausible regression) is not evidence; use the scenario as the failing proof instead. Then the SMALLEST GREEN change; before GREEN work that depends on external review, PR, issue, or branch state, refresh current branch/PR/issue state, preserve existing ordering/policy, and separate compatibility detection from policy changes unless the goal explicitly asks to change policy. A GREEN far larger than the criterion implies means the proof was too coarse — instruct a split. Serialize only on a NAMED dependency.4. INTEGRATE + CRITICAL SELF-QA + GIT CHECKPOINT (EVERY WORKER RETURN): do NOT trust the worker's report. Read the diff yourself, re-run its tests, and run LSP diagnostics on the changed files. Treat "done" as a claim to disprove. If the diff drifts, the test is hollow, or evidence is missing, RESPAWN the worker with the specific failure context. Once the work unit is verified, use `git-master` before staging: inspect recent repository commits and touched-path history to infer commit language, Conventional Commit scope, message shape, and unit size. Stage only that unit's files and commit in the observed style; do not carry verified work forward into a later omnibus commit. If no git-tracked files changed or committing is unsafe, record the no-commit reason as evidence. Forward every finding/learning to subsequent workers.-5. EXECUTE-AS-SCENARIO: ACTUALLY run the Manual-QA channel scenario the criterion named (HTTP call / tmux / browser use / computer use — see the channel table above). Run it yourself for the orchestrator check; for heavier flows dispatch a dedicated QA worker (`worker`, `gpt-5.5`, `high`) whose ONLY job is to drive the channel and write the artifact to the named evidence path. The unit suite being green is NEVER substitute. If the scenario FAILS, respawn the implementing worker with the captured failure — do not hand-patch around it.+5. EXECUTE-AS-SCENARIO: ACTUALLY run the Manual-QA scenario the criterion named (channel table above). Run it yourself for the orchestrator check; for heavier flows dispatch a dedicated QA worker (`worker`, `gpt-5.5`, `high`) whose ONLY job is to drive the channel and write the artifact to the named evidence path. If the scenario FAILS, respawn the implementing worker with the captured failure — do not hand-patch around it.6. CAPTURE: collect the observable artifact path: transcript, stdout, screenshot, assertion, status+body, diff, or parsed dump. No artifact written at the evidence path — not done; record BLOCKED and respawn QA.-7. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 5 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, AND `close_agent` on every finished worker. Register each teardown as its own todo the moment the QA spawns the resource (scripts, tmux assets, browsers / agent-browser sessions, PIDs, ports) so none is forgotten. 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; close_agent w-3`. Missing receipt → record BLOCKED, not PASS.+7. CLEAN (PAIRED, NEVER SKIP): tear down every runtime artifact step 5 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, AND `multi_agent_v1.close_agent` on every finished worker. Register each teardown as its own todo the moment the QA spawns the resource (scripts, tmux assets, browsers / agent-browser sessions, PIDs, ports) so none is forgotten. 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; multi_agent_v1.close_agent w-3`. Missing receipt → record BLOCKED, not PASS.8. RECORD exactly one result:- PASS: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status pass --evidence "<observable> | <cleanup receipt>" --json`- FAIL: `omo ulw-loop record-evidence --goal-id <id> --criterion-id <id> --status fail --evidence "<observable> | <cleanup receipt>" --notes "<diagnosis>" --json`@@ -178,7 +176,7 @@ 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. Judge the change size. Spawn a rigorous reviewer with `spawn_agent({"task_name":"final_verification_review","message":"TASK: act as a rigorous final verification reviewer. DELIVERABLE: approve or cite blockers. SCOPE: <changed files and goal>. VERIFY: inspect diff and verification evidence.","fork_turns":"none"})` only when the work is large or risky (multi-file, cross-cutting, new architecture, security/data surfaces, or you are unsure it is sound); for a small, local, low-risk change, do the review yourself and record `codeReview` with `evidence` starting `UNCONDITIONAL APPROVAL` plus a one-line justification of why the change was small enough to self-review.+4. HEAVY tier — or any goal you are unsure is sound — spawns a rigorous reviewer with `multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous final verification reviewer. DELIVERABLE: approve or cite blockers. SCOPE: <changed files and goal>. VERIFY: inspect diff and verification evidence.","fork_context":false})`. LIGHT tier: review the diff yourself and record `codeReview` with `evidence` starting `UNCONDITIONAL APPROVAL` plus a one-line justification of why the tier held.5. Clean review means `codeReview.recommendation == "APPROVE"` and `codeReview.architectStatus == "CLEAR"`.6. If review is non-clean, run `omo ulw-loop record-review-blockers --goal-id <id> --title "<...>" --objective "<...>" --evidence "<review findings>" --codex-goal-json <snapshot> --json`.7. If clean, checkpoint final completion:@@ -194,6 +192,7 @@ omo ulw-loop checkpoint --goal-id <id> --status complete --evidence "<e2e eviden"criteriaCoverage": { "totalCriteria": N, "passCount": N, "adversarialClassesCovered": ["malformed_input", "..."] }}```+A LIGHT goal with no triggered adversarial class records `"adversarialClassesCovered": ["none-applicable: <reason>"]`.## Dynamic SteeringUse steering only for structured evidence-backed mutation. Reject natural-language steering requests.@@ -221,11 +220,11 @@ Structured prompt directives accepted: `OMO_ULW_LOOP_STEER: { ... }`, `omo.ulw-l7. 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.+10. Probe the adversarial classes each criterion's trigger facts name (list in Bootstrap step 2); record untriggered classes as not-applicable in one line.11. After completing an aggregate ulw-loop 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, or while any worker is still open. The evidence string MUST include the cleanup receipt. Leftover runtime state = BLOCKED, not PASS.-14. DELEGATE all code edits, test writes, fixes, and QA execution to right-sized `spawn_agent` workers (Delegation table); you read, search, plan, integrate, and QA. NEVER record `--status pass` from a worker's self-report — only from evidence you re-verified yourself. Dispatch independent tasks in parallel; serialize only on a NAMED dependency.+14. DELEGATE all code edits, test writes, fixes, and QA execution to right-sized `multi_agent_v1.spawn_agent` workers (Delegation table); you read, search, plan, integrate, and QA. NEVER record `--status pass` from a worker's self-report — only from evidence you re-verified yourself. Dispatch independent tasks in parallel; serialize only on a NAMED dependency.15. Every verified work unit that touched git-tracked files must leave either an atomic `git-master`-style commit hash or explicit no-commit blocker evidence before the next unit starts.## Stop Rulesdiff --git a/plugins/omo/skills/ulw-plan/SKILL.md b/plugins/omo/skills/ulw-plan/SKILL.mdindex 40f3e6c0..cbb6cae9 100644--- a/plugins/omo/skills/ulw-plan/SKILL.md+++ b/plugins/omo/skills/ulw-plan/SKILL.md@@ -14,7 +14,7 @@ This skill is intentionally compact. The full planning workflow lives in `refere## Required First Steps1. Open `references/full-workflow.md`.-2. Read **Phase 0 - Classify**, **Phase 1 - Ground**, and the **Approval gate** before you ask the user anything or draft a plan.+2. Read **Phase 0 - Classify**, **Phase 1 - Ground**, **Phase 2 - Interview**, and the **Approval gate** before you ask the user anything or draft a plan.3. Internalize the loop: explore exhaustively, surface the genuine unknowns, ask, then wait for approval before planning.## The Gate (non-negotiable behavior)@@ -24,6 +24,15 @@ This skill is intentionally compact. The full planning workflow lives in `refere- **Wait for the user's explicit okay before generating the plan.** Never auto-transition from interview to plan generation. No plan file, no Metis gap-analysis, no execution until the user approves the approach.- **Planner scope only.** Write only `.omo/plans/<slug>.md` and `.omo/drafts/*.md`. Never edit source. If asked to "just do it", decline: you plan; a worker executes.+## Interview Discipline (how to ask)++Exploration answers facts; the user decides preferences, tradeoffs, and safety. Bring those decisions to the user EARLY and well-formed:++- Every question must materially change the plan, confirm a load-bearing assumption, or choose between real tradeoffs. If a read-only search could answer it, asking is a failure.+- Ask 1-3 narrow questions per turn, each with 2-4 concrete options and your recommended default first, grounded in a file path or finding you cite. A skipped question resolves to that default, recorded in the draft as an assumption.+- Always ask test strategy (TDD / tests-after / none); agent-executed QA scenarios are included regardless.+- Record every answer and decision in `.omo/drafts/<slug>.md` immediately; run the Phase 2 clearance check after every turn; never end a turn passively — end with the question or the explicit next step.+## Dynamic Adversarial PlanningFor architecture work, no-plan `$start-work` bootstrap, or requests that cite Discord / external repositories, use **dynamic adversarial workflow phases** before writing the final plan:@@ -44,22 +53,22 @@ Subagent outputs are not success or approval without independent verification.You explore a LOT - fan out parallel read-only research before interviewing - but delegate with Codex discipline:-- Every `spawn_agent` message starts with `TASK:`, then names `DELIVERABLE`, `SCOPE`, and `VERIFY`. Put role and specialty instructions inside `message`; the Codex tool schema only accepts `task_name`, `message`, and `fork_turns`. Prefer `fork_turns: "none"` unless full history is truly required.-- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short wait_agent cycles. Never use a single long blocking wait for them.+- Every `multi_agent_v1.spawn_agent` message starts with `TASK:`, then names `DELIVERABLE`, `SCOPE`, and `VERIFY`. Put role and specialty instructions inside `message`. Use `fork_context: false` unless full history is truly required.+- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short `multi_agent_v1.wait_agent` cycles. Never use a single long blocking wait for them.- For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long reading, testing, or review passes, and `BLOCKED: <reason>` only when it cannot progress.- While any child is active, keep yourself visibly alive with active subagent count, agent names, latest `WORKING:` phase, and whether you are waiting for mailbox updates.-- Track spawned agent names locally. Use `wait_agent` for mailbox signals, not proof of completion. A timeout only means no new mailbox update arrived; after a timeout, run a single `list_agents` check for the named child when you need reassurance. If it is running or its latest message is `WORKING:`, treat it as alive.-- Do not use `list_agents` as a polling loop or status feed; it can replay large payloads. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Then record the lane inconclusive and respawn a smaller `fork_turns: "none"` task with the missing deliverable.+- Track spawned agent names locally. Use `multi_agent_v1.wait_agent` for mailbox signals, not proof of completion. A timeout only means no new mailbox update arrived. Treat a running child as alive.+- Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running. Then record the lane inconclusive and respawn a smaller `fork_context: false` task with the missing deliverable.## Codex Tool Mapping| Planning intent | Codex tool || --- | --- |-| Internal codebase research | `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` |-| External docs / library research | `spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})` |-| Pre-plan gap analysis (after approval) | `spawn_agent({"task_name":"...","message":"TASK: act as a Metis gap-analysis reviewer. ...","fork_turns":"none"})` |-| High-accuracy plan review (optional) | `spawn_agent({"task_name":"...","message":"TASK: act as a Momus plan reviewer. ...","fork_turns":"none"})` |-| Wait for a research result | `wait_agent(...)` |-| Release a finished subagent | `close_agent(...)` |+| Internal codebase research | `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","fork_context":false})` |+| External docs / library research | `multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","fork_context":false})` |+| Pre-plan gap analysis (after approval) | `multi_agent_v1.spawn_agent({"message":"TASK: act as a Metis gap-analysis reviewer. ...","fork_context":false})` |+| High-accuracy plan review (optional) | `multi_agent_v1.spawn_agent({"message":"TASK: act as a Momus plan reviewer. ...","fork_context":false})` |+| Wait for a research result | `multi_agent_v1.wait_agent(...)` |+| Release a finished subagent | `multi_agent_v1.close_agent(...)` |Name any skills the child needs directly inside its `message`. Your plan goes to `.omo/plans/<slug>.md`; never split one request into multiple plans.diff --git a/plugins/omo/skills/ulw-plan/references/full-workflow.md b/plugins/omo/skills/ulw-plan/references/full-workflow.mdindex d35d5ba2..b43973b8 100644--- a/plugins/omo/skills/ulw-plan/references/full-workflow.md+++ b/plugins/omo/skills/ulw-plan/references/full-workflow.md@@ -8,7 +8,7 @@ metadata:## RolePrometheus, strategic planning consultant inside Codex. You turn a vague or large request into ONE decision-complete work plan a downstream worker can execute with zero further interview. You are a PLANNER, not an implementer: read, search, run read-only analysis, and write only `.omo/plans/<slug>.md` and `.omo/drafts/*.md`. Never edit product code; if asked to "just do it", decline and offer to plan.-GPT-5.x style: outcome-first, evidence-bound, atomic decisions. Explore a lot. Ask little. Never plan blind, and never plan before the user approves.+GPT-5.x style: outcome-first, evidence-bound, atomic decisions. Explore a lot; ask few, decisive questions. Never plan blind, and never plan before the user approves.## North starA plan is **decision-complete** when the implementer needs ZERO judgment calls: every decision made, every ambiguity resolved, every pattern referenced with a concrete path.@@ -22,8 +22,8 @@ Size your interview depth before diving in:## Phase 1 - Ground (explore exhaustively BEFORE asking)Eliminate unknowns by discovering facts, not by asking the user. Before your first question, fan out parallel read-only research and keep working while it runs.-- `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` per internal aspect: existing patterns, conventions, similar implementations, naming/registration, test infrastructure. One agent per aspect.-- `spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})` per external aspect: official docs, API contracts, recommended patterns, pitfalls.+- `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","fork_context":false})` per internal aspect: existing patterns, conventions, similar implementations, naming/registration, test infrastructure. One agent per aspect.+- `multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","fork_context":false})` per external aspect: official docs, API contracts, recommended patterns, pitfalls.- While they run, use direct read-only tools (`read`, `rg`, `ast_grep_search`, `lsp_*`) for immediate context. Do not idle.### Dynamic workflow for architecture and bootstrap planning@@ -44,11 +44,17 @@ Two kinds of unknowns:Exhaust exploration first. "I could not find it" is true only after you actually looked.## Phase 2 - Interview (ask only what exploration cannot resolve)-Record everything to `.omo/drafts/<slug>.md` as you go: confirmed requirements, decisions + rationale, research findings, open questions, scope IN / OUT. The draft is your durable memory across turns.+Record everything to `.omo/drafts/<slug>.md` as you go: confirmed requirements (the user's exact words), decisions + rationale, research findings, open questions, scope IN / OUT. Update it after EVERY meaningful exchange - long interviews outlive your context, and plan generation reads the draft, not your memory.-Ask focused questions ONLY for genuine unknowns surfaced by Phase 1: goal + definition of done, scope boundaries, preference tradeoffs, test strategy (TDD / tests-after / none - agent-executed QA is always included), and hard constraints. Every question must materially change the plan. Never ask what a read-only search would answer.+Interview focus, informed by Phase 1 findings: goal + definition of done, scope boundaries (IN and explicitly OUT), technical approach ("I found pattern X at `src/path` - follow it?"), test strategy (TDD / tests-after / none - agent-executed QA is always included), and hard constraints.-Keep each turn conversational: 3-6 sentences plus 1-3 questions. Never end a turn passively; end with the specific question or the explicit next step.+Question rules:+- Every question must materially change the plan, confirm a load-bearing assumption, or choose between real tradeoffs. Never ask what a read-only search would answer.+- Ask 1-3 narrow questions per turn, each with 2-4 concrete options and your recommended default first with a one-line rationale. A question the user skips resolves to the recommended default, recorded in the draft as an assumption.+- Ground each question in evidence: cite the file path or research finding that raised it, so the user decides from facts rather than guesses.+- Keep each turn conversational: 3-6 sentences plus the questions. Never end a turn passively; end with the specific question or the explicit next step.++Clearance check - run after EVERY interview turn: core objective defined? scope IN/OUT explicit? technical approach decided? test strategy confirmed? no critical ambiguity or blocking question left? Any NO -> that unmet item is your next question. All YES -> present the approval brief (see Approval gate) and stop; never jump from interview into writing the plan.## Approval gate (DO NOT SKIP)When exploration is exhausted and the genuine unknowns are answered, do NOT auto-start planning. Present a short brief instead:@@ -61,7 +67,7 @@ Then **wait for the user's explicit okay** before generating the plan. No Metis,Narrow `$start-work` bootstrap exception: if `$start-work` invoked this skill because there was no active Boulder work and no selectable plan, the user's `start work` request counts as approval to generate the plan and begin execution. Preserve the normal gate for ordinary `ulw-plan`; ask one focused question only if the objective is missing, destructive, or has a safety/product ambiguity that exploration cannot resolve.## Phase 3 - Generate the plan (only after approval)-1. **Metis gap analysis (mandatory):** `spawn_agent({"task_name":"metis_gap_analysis","message":"TASK: act as a Metis gap-analysis reviewer and review this planning session for gaps. DELIVERABLE: contradictions, missing constraints, scope-creep risks, unvalidated assumptions, missing acceptance criteria. VERIFY: each gap names a concrete fix.","fork_turns":"none"})`. Fold the findings in silently.+1. **Metis gap analysis (mandatory):** `multi_agent_v1.spawn_agent({"message":"TASK: act as a Metis gap-analysis reviewer and review this planning session for gaps. DELIVERABLE: contradictions, missing constraints, scope-creep risks, unvalidated assumptions, missing acceptance criteria. VERIFY: each gap names a concrete fix.","fork_context":false})`. Fold the findings in silently.2. Write ONE plan to `.omo/plans/<slug>.md` using the template below. No "Phase 1 plan / Phase 2 plan" splits; 50+ todos is fine. Build it incrementally - skeleton first, then append todo batches - so output limits never truncate it; re-read the file to confirm completeness.3. **Self-review:** every todo has references + agent-executable acceptance criteria + QA scenarios; no business-logic assumption without evidence; zero acceptance criteria require a human.@@ -116,14 +122,14 @@ Critical path: ...```## Phase 4 - High-accuracy review (optional)-If the user wants maximum rigor, call `spawn_agent({"task_name":"momus_plan_review","message":"TASK: act as a Momus plan reviewer. DELIVERABLE: review .omo/plans/<slug>.md only. VERIFY: cite every required fix or approve.","fork_turns":"none"})` and pass ONLY the plan path in `message`. Fix every cited issue and resubmit until it approves.+If the user wants maximum rigor, call `multi_agent_v1.spawn_agent({"message":"TASK: act as a Momus plan reviewer. DELIVERABLE: review .omo/plans/<slug>.md only. VERIFY: cite every required fix or approve.","fork_context":false})` and pass ONLY the plan path in `message`. Fix every cited issue and resubmit until it approves.## Delegation discipline (Codex)-- Every `spawn_agent` message starts with `TASK:`, then `DELIVERABLE`, `SCOPE`, `VERIFY`. Put role and specialty instructions inside `message`; the Codex tool schema only accepts `task_name`, `message`, and `fork_turns`. Prefer `fork_turns: "none"`.-- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short wait_agent cycles. Never use a single long blocking wait for them.+- Every `multi_agent_v1.spawn_agent` message starts with `TASK:`, then `DELIVERABLE`, `SCOPE`, `VERIFY`. Put role and specialty instructions inside `message`. Use `fork_context: false` unless full history is truly required.+- Plan and reviewer agents may run for a long time; spawn them in the background, keep doing independent root work, and poll with short `multi_agent_v1.wait_agent` cycles. Never use a single long blocking wait for them.- For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops.- Keep yourself visibly alive while children run: active subagent count, agent names, latest `WORKING:` phase, and whether you are waiting on mailbox updates.-- Use `wait_agent` for mailbox signals, not proof. A timeout only means no new mailbox update arrived; after a timeout, run a single `list_agents` check for the named child when you need reassurance. If it is running or its latest message is `WORKING:`, treat it as alive. Do not use `list_agents` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running; then mark the lane inconclusive and respawn a smaller `fork_turns: "none"` task with the missing deliverable. `close_agent` after integrating each result.+- Use `multi_agent_v1.wait_agent` for mailbox signals, not proof. A timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running; then mark the lane inconclusive and respawn a smaller `fork_context: false` task with the missing deliverable. `multi_agent_v1.close_agent` after integrating each result.## Stop rules- Plan file exists, template filled, every todo has references + acceptance + QA + commit, dependency matrix consistent: DONE.diff --git a/plugins/omo/skills/visual-qa/SKILL.md b/plugins/omo/skills/visual-qa/SKILL.mdindex c0340d3e..5ba6d184 100644--- a/plugins/omo/skills/visual-qa/SKILL.md+++ b/plugins/omo/skills/visual-qa/SKILL.md@@ -9,17 +9,17 @@ This skill may include examples copied from the OpenCode harness. In Codex, do n| OpenCode example | Codex tool to use || --- | --- |-| `call_omo_agent(subagent_type="explore", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})` |-| `call_omo_agent(subagent_type="librarian", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a librarian. ...","fork_turns":"none"})` |-| `task(subagent_type="plan", ...)` | `spawn_agent({"task_name":"...","message":"TASK: act as a planning agent. ...","fork_turns":"none"})` |-| `task(subagent_type="oracle", ...)` for final verification | `spawn_agent({"task_name":"...","message":"TASK: act as a rigorous reviewer. ...","fork_turns":"none"})` |-| `task(category="...", ...)` for implementation or QA | `spawn_agent({"task_name":"...","message":"TASK: act as an implementation or QA worker. ...","fork_turns":"none"})` |-| `background_output(task_id="...")` | `wait_agent(...)` for mailbox signals; after a timeout, run one `list_agents` check for the named child if reassurance is needed |-| `team_*(...)` | Use Codex native subagents plus `send_message`, `followup_task`, `wait_agent`, and `close_agent` |+| `call_omo_agent(subagent_type="explore", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as an explorer. ...","agent_type":"explorer","fork_context":false})` |+| `call_omo_agent(subagent_type="librarian", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a librarian. ...","agent_type":"librarian","fork_context":false})` |+| `task(subagent_type="plan", ...)` | `multi_agent_v1.spawn_agent({"message":"TASK: act as a planning agent. ...","agent_type":"plan","fork_context":false})` |+| `task(subagent_type="oracle", ...)` for final verification | `multi_agent_v1.spawn_agent({"message":"TASK: act as a rigorous reviewer. ...","agent_type":"codex-ultrawork-reviewer","fork_context":false})` |+| `task(category="...", ...)` for implementation or QA | `multi_agent_v1.spawn_agent({"message":"TASK: act as an implementation or QA worker. ...","fork_context":false})` |+| `background_output(task_id="...")` | `multi_agent_v1.wait_agent(...)` for mailbox signals |+| `team_*(...)` | Use Codex native subagents via `multi_agent_v1.spawn_agent`, `multi_agent_v1.send_input`, `multi_agent_v1.wait_agent`, and `multi_agent_v1.close_agent` |-Codex full-history forks inherit parent context, so role-specific behavior must be described in a self-contained `message` and usually should use a non-full-history fork mode such as `fork_turns="none"`. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.+Role-specific behavior must be described in a self-contained `message`. Use `fork_context: false` to start the child with only the initial prompt (no parent history); use `fork_context: true` only when full parent history is truly required. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. OMO installs these selectable agent roles into `~/.codex/agents/`: `explorer`, `librarian`, `plan`, `momus`, `metis`, and `codex-ultrawork-reviewer` — pass the matching name as `agent_type` so the child gets that role's model and instructions. On `multi_agent_v2` sessions the same `agent_type` applies (the OMO installer exposes it) with `fork_turns` instead of `fork_context`. If the spawn tool exposes no `agent_type` parameter, omit it and describe the role inside `message`. If a code block below conflicts with this section, this section wins.-For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `wait_agent` timeout only means no new mailbox update arrived. Treat a running child or latest `WORKING:` message as alive. Do not use `list_agents` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.+For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `multi_agent_v1.wait_agent` timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.# Visual QA - Dual-Oracle Web and TUI Verificationdiff --git a/plugins/omo/test/aggregate-build.test.mjs b/plugins/omo/test/aggregate-build.test.mjsindex e2c7b428..2d5a8163 100644--- a/plugins/omo/test/aggregate-build.test.mjs+++ b/plugins/omo/test/aggregate-build.test.mjs@@ -18,8 +18,9 @@ test("#given aggregate plugin build script #when inspected #then hook status and// thenassert.equal(buildScript,- "node scripts/sync-hook-status-messages.mjs && node scripts/build-bundled-mcp-runtimes.mjs && node scripts/sync-skills.mjs && node ../scripts/sync-telemetry-component.mjs && node scripts/build-components.mjs",+ "node scripts/sync-version.mjs && node scripts/sync-hook-status-messages.mjs && node scripts/build-bundled-mcp-runtimes.mjs && node scripts/sync-skills.mjs && node ../scripts/sync-telemetry-component.mjs && node scripts/build-components.mjs",);+ assert.match(buildScript, /^node scripts\/sync-version\.mjs &&/);assert.equal(testScript, "node --test test/*.test.mjs");assert(packageJson.workspaces.includes("components/ultrawork"));assert.match(telemetrySyncScript, /syncTelemetryComponent/);diff --git a/plugins/omo/test/aggregate-mcp.test.mjs b/plugins/omo/test/aggregate-mcp.test.mjsindex ff262211..b4781a50 100644--- a/plugins/omo/test/aggregate-mcp.test.mjs+++ b/plugins/omo/test/aggregate-mcp.test.mjs@@ -33,7 +33,7 @@ test("#given aggregate MCP config #when inspected #then code MCPs reference packassert.match(bundledMcpBuildScript, /git-bash-mcp/);assert.doesNotMatch(packageJson.scripts.build, /--workspaces/);assert.equal(lspServer.command, "node");- assert.deepEqual(lspServer.args, ["../../lsp-tools-mcp/dist/cli.js", "mcp"]);+ assert.deepEqual(lspServer.args, ["../../lsp-daemon/dist/cli.js", "mcp"]);assert.equal(lspServer.cwd, ".");assert.equal(astGrepServer.command, "node");assert.deepEqual(astGrepServer.args, ["../../ast-grep-mcp/dist/cli.js", "mcp"]);diff --git a/plugins/omo/test/aggregate-plugin-fixture.mjs b/plugins/omo/test/aggregate-plugin-fixture.mjsindex 43b01838..02924370 100644--- a/plugins/omo/test/aggregate-plugin-fixture.mjs+++ b/plugins/omo/test/aggregate-plugin-fixture.mjs@@ -70,14 +70,14 @@ export function findInvalidSpawnAgentRoleParameters(content) {return [...content.matchAll(/spawn_agent\([^)\n]*(?:agent_type|model|reasoning_effort)\s*=/g)].map((match) => match[0]);}-export function findSpawnAgentCallsWithoutForkTurnsNone(content) {- const missingForkTurns = [];+export function findSpawnAgentCallsWithoutForkContextFalse(content) {+ const missingForkContext = [];const regex = /spawn_agent\(([^)]*)\)/g;for (const match of content.matchAll(regex)) {const call = match[0];- if (!/"fork_turns"\s*:\s*"none"|fork_turns:\s*"none"|fork_turns="none"/.test(call)) {- missingForkTurns.push(call);+ if (!/"fork_context"\s*:\s*false|fork_context:\s*false|fork_context=false/.test(call)) {+ missingForkContext.push(call);}}- return missingForkTurns;+ return missingForkContext;}diff --git a/plugins/omo/test/aggregate-skills.test.mjs b/plugins/omo/test/aggregate-skills.test.mjsindex 46436f2a..a59ef232 100644--- a/plugins/omo/test/aggregate-skills.test.mjs+++ b/plugins/omo/test/aggregate-skills.test.mjs@@ -5,7 +5,7 @@ import test from "node:test";import {findInvalidSpawnAgentRoleParameters,- findSpawnAgentCallsWithoutForkTurnsNone,+ findSpawnAgentCallsWithoutForkContextFalse,root,} from "./aggregate-plugin-fixture.mjs";@@ -27,7 +27,7 @@ test("#given synced skills with Codex compatibility guidance #when spawn_agent iassert.deepEqual(invalidCalls, []);});-test('#given synced skills and bundled rules #when role-specific agents are spawned #then they set fork_turns="none"', async () => {+test('#given synced skills and bundled rules #when role-specific agents are spawned #then they set fork_context=false', async () => {const skillsDir = join(root, "skills");const skillEntries = await readdir(skillsDir, { withFileTypes: true });const promptFiles = skillEntries@@ -35,15 +35,15 @@ test('#given synced skills and bundled rules #when role-specific agents are spaw.map((entry) => join(skillsDir, entry.name, "SKILL.md"));promptFiles.push(join(root, "components", "rules", "bundled-rules", "hephaestus.md"));- const missingForkTurns = [];+ const missingForkContext = [];for (const promptPath of promptFiles) {const content = await readFile(promptPath, "utf8");- for (const call of findSpawnAgentCallsWithoutForkTurnsNone(content)) {- missingForkTurns.push(`${basename(dirname(promptPath))}/${basename(promptPath)}: ${call}`);+ for (const call of findSpawnAgentCallsWithoutForkContextFalse(content)) {+ missingForkContext.push(`${basename(dirname(promptPath))}/${basename(promptPath)}: ${call}`);}}- assert.deepEqual(missingForkTurns, []);+ assert.deepEqual(missingForkContext, []);});test("#given long-running orchestration prompts #when waiting on child agents #then parent liveness is surfaced", async () => {diff --git a/plugins/omo/test/auto-update-restart-notice.test.mjs b/plugins/omo/test/auto-update-restart-notice.test.mjsnew file mode 100644index 00000000..c1881136--- /dev/null+++ b/plugins/omo/test/auto-update-restart-notice.test.mjs@@ -0,0 +1,194 @@+import assert from "node:assert/strict";+import { spawnSync } from "node:child_process";+import { mkdtemp, readFile, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++import { resolveAutoUpdatePlan, runAutoUpdateCheck } from "../scripts/auto-update.mjs";++const SCRIPT_PATH = fileURLToPath(new URL("../scripts/auto-update.mjs", import.meta.url));+const STARTED_NOTICE =+ "[LazyCodex] Auto-update started in the background: v1.0.0 -> v1.0.1. Tell the user a new LazyCodex version is installing and that they should start a new Codex session after it completes to apply it.";+const COMPLETED_NOTICE =+ "[LazyCodex] Auto-update completed: v1.0.0 -> v1.0.1. This session is already running the new version. Tell the user the auto-update was applied.";++function autoUpdateEnv(root, extra = {}) {+ return {+ CODEX_HOME: join(root, "codex-home"),+ LAZYCODEX_CURRENT_VERSION: "1.0.0",+ LAZYCODEX_LATEST_VERSION: "1.0.1",+ LAZYCODEX_MODEL_CATALOG_STATE_PATH: join(root, "model-state.json"),+ LAZYCODEX_AUTO_UPDATE_STATE_PATH: join(root, "state.json"),+ LAZYCODEX_AUTO_UPDATE_LOG_PATH: join(root, "auto-update.log"),+ ...extra,+ };+}++test("#given a newer version #when resolving auto update plan #then plan carries current and latest versions", () => {+ const plan = resolveAutoUpdatePlan({+ env: { LAZYCODEX_CURRENT_VERSION: "1.0.0", LAZYCODEX_LATEST_VERSION: "1.0.1" },+ now: 90_000_000,+ lastCheckedAt: 0,+ });++ assert.equal(plan.shouldRun, true);+ assert.equal(plan.currentVersion, "1.0.0");+ assert.equal(plan.latestVersion, "1.0.1");+});++test("#given a newer version #when waited update succeeds #then returns update-started notice and persists pendingNotice", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-restart-notice-started-"));+ const env = autoUpdateEnv(root, {+ LAZYCODEX_AUTO_UPDATE_INTERVAL_MS: "0",+ LAZYCODEX_AUTO_UPDATE_COMMAND: process.execPath,+ LAZYCODEX_AUTO_UPDATE_ARGS_JSON: JSON.stringify(["-e", "process.exit(0)"]),+ LAZYCODEX_AUTO_UPDATE_WAIT: "1",+ });++ const result = await runAutoUpdateCheck({+ env,+ now: 123_456,+ });++ assert.equal(result.started, true);+ assert.equal(result.status, 0);+ assert.deepEqual(result.notices, [STARTED_NOTICE]);+ const state = JSON.parse(await readFile(env.LAZYCODEX_AUTO_UPDATE_STATE_PATH, "utf8"));+ assert.deepEqual(state.pendingNotice, {+ fromVersion: "1.0.0",+ toVersion: "1.0.1",+ startedAt: 123_456,+ });+});++test("#given completed pending update #when startup check is throttled #then emits completed notice and clears pendingNotice", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-restart-notice-completed-"));+ const now = 90_000_000;+ const env = autoUpdateEnv(root, {+ LAZYCODEX_CURRENT_VERSION: "1.0.1",+ LAZYCODEX_LATEST_VERSION: "1.0.1",+ });+ await writeFile(env.LAZYCODEX_AUTO_UPDATE_STATE_PATH, JSON.stringify({+ lastCheckedAt: now - 1_000,+ lastStatus: "success",+ pendingNotice: { fromVersion: "1.0.0", toVersion: "1.0.1", startedAt: 1 },+ }));++ const result = await runAutoUpdateCheck({+ env,+ now,+ });++ assert.equal(result.started, false);+ assert.equal(result.reason, "throttled");+ assert.deepEqual(result.notices, [COMPLETED_NOTICE]);+ assert.deepEqual(JSON.parse(await readFile(env.LAZYCODEX_AUTO_UPDATE_STATE_PATH, "utf8")), {+ lastCheckedAt: now - 1_000,+ lastStatus: "success",+ });+});++test("#given incomplete pending update #when startup check runs #then no notice and pendingNotice retained", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-restart-notice-incomplete-"));+ const now = 90_000_000;+ const env = autoUpdateEnv(root);+ await writeFile(env.LAZYCODEX_AUTO_UPDATE_STATE_PATH, JSON.stringify({+ lastAttemptedAt: now - 60_000,+ lastStatus: "started",+ pendingNotice: { fromVersion: "1.0.0", toVersion: "1.0.1", startedAt: 1 },+ }));++ const result = await runAutoUpdateCheck({+ env,+ now,+ });++ assert.equal(result.started, false);+ assert.equal(result.reason, "retry-throttled");+ assert.deepEqual(result.notices, []);+ const state = JSON.parse(await readFile(env.LAZYCODEX_AUTO_UPDATE_STATE_PATH, "utf8"));+ assert.deepEqual(state.pendingNotice, {+ fromVersion: "1.0.0",+ toVersion: "1.0.1",+ startedAt: 1,+ });+});++test("#given waited update fails #then no notice and no pendingNotice", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-restart-notice-failed-"));+ const env = autoUpdateEnv(root, {+ LAZYCODEX_AUTO_UPDATE_INTERVAL_MS: "0",+ LAZYCODEX_AUTO_UPDATE_COMMAND: process.execPath,+ LAZYCODEX_AUTO_UPDATE_ARGS_JSON: JSON.stringify(["-e", "process.exit(1)"]),+ LAZYCODEX_AUTO_UPDATE_WAIT: "1",+ });++ const result = await runAutoUpdateCheck({+ env,+ now: 123_456,+ });++ assert.equal(result.started, true);+ assert.equal(result.status, 1);+ assert.deepEqual(result.notices, []);+ assert.deepEqual(JSON.parse(await readFile(env.LAZYCODEX_AUTO_UPDATE_STATE_PATH, "utf8")), {+ lastAttemptedAt: 123_456,+ lastStatus: "failed",+ });+});++test("#given malformed pendingNotice toVersion #when check runs #then pendingNotice dropped silently", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-restart-notice-malformed-"));+ const env = autoUpdateEnv(root, {+ LAZYCODEX_CURRENT_VERSION: "1.0.1",+ LAZYCODEX_LATEST_VERSION: "1.0.1",+ });+ await writeFile(env.LAZYCODEX_AUTO_UPDATE_STATE_PATH, JSON.stringify({+ pendingNotice: { fromVersion: "1.0.0", toVersion: "not-a-version", startedAt: 1 },+ }));++ const result = await runAutoUpdateCheck({+ env,+ now: 123_456,+ });++ assert.deepEqual(result.notices, []);+ const state = JSON.parse(await readFile(env.LAZYCODEX_AUTO_UPDATE_STATE_PATH, "utf8"));+ assert.equal("pendingNotice" in state, false);+});++test("#given completed pending update #when hook session-start runs as CLI #then prints one SessionStart JSON line", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-restart-notice-cli-"));+ const env = autoUpdateEnv(root, {+ LAZYCODEX_CURRENT_VERSION: "1.0.1",+ LAZYCODEX_LATEST_VERSION: "1.0.1",+ LAZYCODEX_CONFIG_MIGRATION_DISABLED: "1",+ });+ await writeFile(env.LAZYCODEX_AUTO_UPDATE_STATE_PATH, JSON.stringify({+ lastCheckedAt: Date.now() - 1_000,+ lastStatus: "success",+ pendingNotice: { fromVersion: "1.0.0", toVersion: "1.0.1", startedAt: 1 },+ }));++ const result = spawnSync(process.execPath, [SCRIPT_PATH, "hook", "session-start"], {+ encoding: "utf8",+ env: { ...process.env, ...env },+ });++ assert.equal(result.status, 0);+ const lines = result.stdout.split("\n").filter((line) => line.length > 0);+ assert.equal(lines.length, 1);+ const parsed = JSON.parse(lines[0]);+ assert.equal(parsed.hookSpecificOutput.hookEventName, "SessionStart");+ assert.match(parsed.hookSpecificOutput.additionalContext, /v1\.0\.0 -> v1\.0\.1/);++ const repeat = spawnSync(process.execPath, [SCRIPT_PATH, "hook", "session-start"], {+ encoding: "utf8",+ env: { ...process.env, ...env },+ });++ assert.equal(repeat.status, 0);+ assert.equal(repeat.stdout, "");+});diff --git a/plugins/omo/test/auto-update.test.mjs b/plugins/omo/test/auto-update.test.mjsindex b7eeec69..932dabff 100644--- a/plugins/omo/test/auto-update.test.mjs+++ b/plugins/omo/test/auto-update.test.mjs@@ -162,6 +162,11 @@ test("#given test command override #when running check #then records state and llastCheckedAt: 123_456,lastAttemptedAt: 123_456,lastStatus: "success",+ pendingNotice: {+ fromVersion: "1.0.0",+ toVersion: "1.0.1",+ startedAt: 123_456,+ },});assert.equal(await readFile(logPath, "utf8"), "ok");const updateLog = (await readFile(env.LAZYCODEX_AUTO_UPDATE_LOG_PATH, "utf8")).trim().split("\n").map((line) => JSON.parse(line));@@ -177,6 +182,13 @@ test("#given test command override #when running check #then records state and levent: "finished",status: 0,},+ {+ timestamp: "1970-01-01T00:02:03.456Z",+ event: "notified",+ kind: "update-started",+ fromVersion: "1.0.0",+ toVersion: "1.0.1",+ },]);assert.match(await readFile(join(env.CODEX_HOME, "config.toml"), "utf8"), /model = "gpt-5\.5"/);});@@ -262,6 +274,11 @@ test("#given stale lock #when running check #then removes lock and runs update",lastCheckedAt: 1_000_000,lastAttemptedAt: 1_000_000,lastStatus: "success",+ pendingNotice: {+ fromVersion: "1.0.0",+ toVersion: "1.0.1",+ startedAt: 1_000_000,+ },});});diff --git a/plugins/omo/test/global-review-debug-gate.test.mjs b/plugins/omo/test/global-review-debug-gate.test.mjsdeleted file mode 100644index 8d95d13d..00000000--- a/plugins/omo/test/global-review-debug-gate.test.mjs+++ /dev/null@@ -1,29 +0,0 @@-import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";-import { dirname, join } from "node:path";-import test from "node:test";-import { fileURLToPath } from "node:url";--const pluginRoot = dirname(dirname(fileURLToPath(import.meta.url)));--test("#given start-work continuation directive #when inspected #then final handoff requires review and debugging gate", async () => {- const text = await readFile(join(pluginRoot, "components", "start-work-continuation", "directive.md"), "utf8");-- assert.match(text, /Global Review and Debugging Gate/);- assert.match(text, /review-work/);- assert.match(text, /debugging/);- assert.match(text, /Do not print `ORCHESTRATION COMPLETE`/);- assert.match(text, /Do not create a PR, PR handoff, or branch handoff/);- assert.match(text, /redact.*secrets.*PII/s);-});--test("#given Hephaestus baseline rule #when inspected #then significant implementation and PR handoff require the same gate", async () => {- const text = await readFile(join(pluginRoot, "components", "rules", "bundled-rules", "hephaestus.md"), "utf8");-- assert.match(text, /Global Review and Debugging Gate/);- assert.match(text, /significant implementation work/);- assert.match(text, /review-work/);- assert.match(text, /debugging/);- assert.match(text, /PR handoff/);- assert.match(text, /redact.*secrets.*PII/s);-});diff --git a/plugins/omo/test/lcx-bug-skills.test.mjs b/plugins/omo/test/lcx-bug-skills.test.mjsindex f0edf27f..2746dff8 100644--- a/plugins/omo/test/lcx-bug-skills.test.mjs+++ b/plugins/omo/test/lcx-bug-skills.test.mjs@@ -16,22 +16,6 @@ test("#given synced lcx-report-bug skill #when inspected #then it files LazyCode// thenassert.match(skill, /^---\r?\nname: lcx-report-bug\r?\n/m);- assert.match(skill, /code-yeongyu\/lazycodex/);- assert.match(skill, /openai\/codex/);- assert.match(skill, /\/tmp\/openai-codex-source/);- assert.match(skill, /\$omo:debugging/);- assert.match(skill, /Repository Decision/);- assert.match(skill, /TARGET_REPO="code-yeongyu\/lazycodex" # or openai\/codex/);- assert.match(skill, /LABEL_ARGS=\(\)/);- assert.match(skill, /gh label create lazycodex-generated.*--force/);- assert.match(skill, /gh issue create --repo "\$TARGET_REPO".*"\$\{LABEL_ARGS\[@\]\}"/);- assert.match(skill, /gh pr create --repo "\$TARGET_REPO".*"\$\{LABEL_ARGS\[@\]\}"/);- assert.match(skill, /lazycodex-generated/);- assert.match(skill, /This issue or PR was generated by LazyCodex/);- assert.match(skill, /Tag: lazycodex-generated/);- assert.match(skill, /Browser use fallback/);- assert.match(skill, /Computer use fallback/);- assert.match(skill, /## Issue Body Template/);assert.match(interfaceMetadata, /display_name: "lcx-report-bug \(omo\)"/);assert.match(interfaceMetadata, /- "lazycodex bug"/);assert.match(interfaceMetadata, /- "openai codex bug"/);@@ -44,38 +28,25 @@ test("#given synced lcx-contribute-bug-fix skill #when inspected #then it contri// whenconst skill = await readFile(join(skillRoot, "SKILL.md"), "utf8");const interfaceMetadata = await readFile(join(skillRoot, "agents", "openai.yaml"), "utf8");- const script = await readFile(join(skillRoot, "scripts", "create-pr-body.mjs"), "utf8");// thenassert.match(skill, /^---\r?\nname: lcx-contribute-bug-fix\r?\n/m);- assert.match(skill, /Contribute a verified bug-fix PR/);- assert.match(skill, /fresh `\/tmp` clone\/worktree/);- assert.match(skill, /\/tmp\/lazycodex-fix-/);- assert.match(skill, /git worktree add/);- assert.match(skill, /apply `lazycodex-generated` when label management is available/);- assert.match(skill, /git add -A/);- assert.match(skill, /git commit -m/);- assert.match(skill, /git log --oneline "origin\/\$BASE_BRANCH\.\.HEAD"/);- assert.match(skill, /gh repo fork "\$TARGET_REPO" --remote --remote-name fork/);- assert.match(skill, /PUSH_REMOTE/);- assert.match(skill, /lazycodex-generated/);- assert.match(skill, /LABEL_ARGS=\(\)/);- assert.match(skill, /gh label create lazycodex-generated.*--force/);- assert.match(skill, /gh pr create --repo "\$TARGET_REPO".*"\$\{LABEL_ARGS\[@\]\}"/);- assert.match(skill, /--head "\$PR_HEAD"/);- assert.doesNotMatch(skill, /a PR without the `lazycodex-generated` label/);- assert.match(skill, /scripts\/create-pr-body\.mjs/);- assert.match(skill, /## Problem Situation/);- assert.match(skill, /## Reproduction Logs/);- assert.match(skill, /## Approach/);- assert.match(skill, /## Why I Am Confident/);- assert.match(skill, /## Risks/);- assert.match(skill, /## User-Visible Behavior Changes/);- assert.match(skill, /Clean up/);assert.match(interfaceMetadata, /display_name: "lcx-contribute-bug-fix \(omo\)"/);assert.match(interfaceMetadata, /- "contribute a bug fix"/);assert.match(interfaceMetadata, /- "fix bug pr"/);- assert.match(script, /createLazyCodexBugFixPrBody/);- assert.match(script, /Problem Situation/);- assert.match(script, /Why I Am Confident/);+});++test("#given synced lcx-doctor skill #when inspected #then it diagnoses installs against latest /tmp sources without mutating them", async () => {+ // given+ const skillRoot = join(root, "skills", "lcx-doctor");++ // when+ const skill = await readFile(join(skillRoot, "SKILL.md"), "utf8");+ const interfaceMetadata = await readFile(join(skillRoot, "agents", "openai.yaml"), "utf8");++ // then+ assert.match(skill, /^---\r?\nname: lcx-doctor\r?\n/m);+ assert.match(interfaceMetadata, /display_name: "lcx-doctor \(omo\)"/);+ assert.match(interfaceMetadata, /- "lazycodex doctor"/);+ assert.match(interfaceMetadata, /- "lazycodex health check"/);});diff --git a/plugins/omo/test/lsp-prebuild-layouts.test.mjs b/plugins/omo/test/lsp-prebuild-layouts.test.mjsnew file mode 100644index 00000000..37c6cc5d--- /dev/null+++ b/plugins/omo/test/lsp-prebuild-layouts.test.mjs@@ -0,0 +1,140 @@+import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";+import { copyFile, mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";++const REPO_SCRIPTS = fileURLToPath(new URL("../components/lsp/scripts", import.meta.url));+const BUILD_LSP_TOOLS = join(REPO_SCRIPTS, "build-lsp-tools.mjs");+const BUILD_LSP_DAEMON = join(REPO_SCRIPTS, "build-lsp-daemon.mjs");++// Run a copied script (built from HEAD sources) and return { status, stdout, stderr }.+// execFileSync throws on non-zero exit; we capture the SpawnError fields instead.+function runScript(script, cwd) {+ try {+ const stdout = execFileSync(process.execPath, [script], { cwd, encoding: "utf8" });+ return { status: 0, stdout, stderr: "" };+ } catch (err) {+ return {+ status: typeof err.status === "number" ? err.status : 1,+ stdout: err.stdout ?? "",+ stderr: err.stderr ?? "",+ };+ }+}++// Escape a string for use in a RegExp literal.+function escapeRegex(str) {+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++test("#given the installed cache layout #when running build-lsp-tools #then uses the bundled dist and exits 0", async () => {+ // given — mirror the installed plugin cache: scripts 2-up from components/lsp-tools-mcp/dist+ const root = await mkdtemp(join(tmpdir(), "lsp-prebuild-cache-tools-"));+ try {+ const scriptsDir = join(root, "components", "lsp", "scripts");+ await mkdir(scriptsDir, { recursive: true });+ await copyFile(BUILD_LSP_TOOLS, join(scriptsDir, "build-lsp-tools.mjs"));++ await mkdir(join(root, "components", "lsp-tools-mcp", "dist", "lsp"), { recursive: true });+ await writeFile(join(root, "components", "lsp-tools-mcp", "dist", "cli.js"), "");+ await writeFile(join(root, "components", "lsp-tools-mcp", "dist", "tools.js"), "");+ await writeFile(join(root, "components", "lsp-tools-mcp", "dist", "lsp", "manager.js"), "");++ // when+ const result = runScript(join(scriptsDir, "build-lsp-tools.mjs"), root);++ // then+ assert.equal(result.status, 0, `expected exit 0; stderr: ${result.stderr}`);+ assert.match(result.stdout, /Using bundled lsp-tools-mcp dist/);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("#given the installed cache layout #when running build-lsp-daemon #then uses the bundled dist and exits 0", async () => {+ // given — mirror the installed plugin cache: scripts 2-up from components/lsp-daemon/dist+ const root = await mkdtemp(join(tmpdir(), "lsp-prebuild-cache-daemon-"));+ try {+ const scriptsDir = join(root, "components", "lsp", "scripts");+ await mkdir(scriptsDir, { recursive: true });+ await copyFile(BUILD_LSP_DAEMON, join(scriptsDir, "build-lsp-daemon.mjs"));++ await mkdir(join(root, "components", "lsp-daemon", "dist"), { recursive: true });+ await writeFile(join(root, "components", "lsp-daemon", "dist", "cli.js"), "");+ await writeFile(join(root, "components", "lsp-daemon", "dist", "index.js"), "");+ await writeFile(join(root, "components", "lsp-daemon", "dist", "index.d.ts"), "");++ // when+ const result = runScript(join(scriptsDir, "build-lsp-daemon.mjs"), root);++ // then+ assert.equal(result.status, 0, `expected exit 0; stderr: ${result.stderr}`);+ assert.match(result.stdout, /Using bundled lsp-daemon dist/);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("#given neither layout #when running build-lsp-tools #then fails listing every probed path", async () => {+ // given — bare layout: only the script, no package.json anywhere, no dist outputs+ const root = await mkdtemp(join(tmpdir(), "lsp-prebuild-none-"));+ try {+ const scriptsDir = join(root, "components", "lsp", "scripts");+ await mkdir(scriptsDir, { recursive: true });+ await copyFile(BUILD_LSP_TOOLS, join(scriptsDir, "build-lsp-tools.mjs"));++ // when+ const result = runScript(join(scriptsDir, "build-lsp-tools.mjs"), root);++ // then — exit 1, stderr enumerates BOTH probed package.json paths+ // candidate 1: 5-up repo sibling (resolves outside the temp tree)+ const candidate1PkgJson = join(scriptsDir, "..", "..", "..", "..", "..", "lsp-tools-mcp", "package.json");+ // candidate 2: 2-up components sibling (inside the temp tree)+ const candidate2PkgJson = join(root, "components", "lsp-tools-mcp", "package.json");++ assert.equal(result.status, 1);+ assert.match(result.stderr, new RegExp(escapeRegex(candidate1PkgJson)));+ assert.match(result.stderr, new RegExp(escapeRegex(candidate2PkgJson)));+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("#given the repo sibling layout with fresh outputs #when running build-lsp-tools #then exits 0 without building", async () => {+ // given — simulate the repo layout: script at d1/d2/d3/components/lsp/scripts/,+ // lsp-tools-mcp at d1/ (5-up from the scripts dir), outputs newer than package.json+ const root = await mkdtemp(join(tmpdir(), "lsp-prebuild-repo-"));+ try {+ const scriptsDir = join(root, "d1", "d2", "d3", "components", "lsp", "scripts");+ await mkdir(scriptsDir, { recursive: true });+ await copyFile(BUILD_LSP_TOOLS, join(scriptsDir, "build-lsp-tools.mjs"));++ // 5-up from scriptsDir lands on join(root, "d1")+ const lspToolsDir = join(root, "d1", "lsp-tools-mcp");+ await mkdir(join(lspToolsDir, "dist", "lsp"), { recursive: true });++ // package.json gets an older mtime+ await writeFile(join(lspToolsDir, "package.json"), "{}");+ const older = new Date("2025-01-01T00:00:00.000Z");+ await utimes(join(lspToolsDir, "package.json"), older, older);++ // outputs get a newer mtime — isBuildFresh returns true+ const newer = new Date("2025-01-02T00:00:00.000Z");+ for (const rel of ["dist/cli.js", "dist/tools.js", "dist/lsp/manager.js"]) {+ await writeFile(join(lspToolsDir, rel), "");+ await utimes(join(lspToolsDir, rel), newer, newer);+ }++ // when+ const result = runScript(join(scriptsDir, "build-lsp-tools.mjs"), root);++ // then — exits 0 immediately (fresh build), no npm invocation+ assert.equal(result.status, 0, `expected exit 0; stderr: ${result.stderr}`);+ assert.doesNotMatch(result.stdout, /Installing/);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});diff --git a/plugins/omo/test/migrate-codex-config.test.mjs b/plugins/omo/test/migrate-codex-config.test.mjsindex cf496e66..3ff7a1d6 100644--- a/plugins/omo/test/migrate-codex-config.test.mjs+++ b/plugins/omo/test/migrate-codex-config.test.mjs@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";import { dirname, join } from "node:path";import test from "node:test";+import { forceDisableMultiAgentV2 } from "../scripts/migrate-codex-config/multi-agent-v2-guard.mjs";import { ensureCodexReasoningConfig, migrateCodexConfig } from "../scripts/migrate-codex-config.mjs";test("#given stale root reasoning config #when ensuring config #then replaces stale values without duplicate keys", () => {@@ -192,6 +193,9 @@ test("#given user-customized Codex model config #when migrating #then user value'model_reasoning_effort = "medium"','plan_mode_reasoning_effort = "medium"',"",+ "[features.multi_agent_v2]",+ "enabled = false",+ "",].join("\n"),);@@ -325,6 +329,9 @@ test("#given config already matches current catalog #when catalog version advanc'model_reasoning_effort = "high"','plan_mode_reasoning_effort = "xhigh"',"",+ "[features.multi_agent_v2]",+ "enabled = false",+ "",].join("\n"),);await writeFile(@@ -361,6 +368,260 @@ test("#given config already matches current catalog #when catalog version advancassert.equal(state.files[configPath].catalogVersion, "test.role-only");});+test("#given multi_agent_v2 enabled #when forcing disable #then flips the flag to false", () => {+ const config = [+ 'model = "gpt-5.5"',+ 'model_reasoning_effort = "high"',+ "",+ "[features.multi_agent_v2]",+ "enabled = true",+ "max_concurrent_threads_per_session = 10000",+ "",+ ].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.match(result, /enabled = false/);+ assert.doesNotMatch(result, /enabled = true/);+ assert.match(result, /max_concurrent_threads_per_session = 10000/);+});++test("#given no multi_agent_v2 section #when forcing disable #then appends a disabled section", () => {+ const config = [+ 'model = "gpt-5.5"',+ 'model_reasoning_effort = "high"',+ "",+ "[features]",+ "plugins = true",+ "",+ ].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.match(result, /\[features\.multi_agent_v2\]\nenabled = false\n/);+ assert.match(result, /plugins = true/);+});++test("#given multi_agent_v2 section without enabled key #when forcing disable #then inserts enabled = false", () => {+ const config = [+ 'model = "gpt-5.5"',+ "",+ "[features.multi_agent_v2]",+ "max_concurrent_threads_per_session = 10000",+ "",+ ].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.match(result, /\[features\.multi_agent_v2\]\nenabled = false\n/);+ assert.match(result, /max_concurrent_threads_per_session = 10000/);+});++test("#given [features] boolean shorthand multi_agent_v2 = true #when forcing disable #then removes it and appends a disabled section", () => {+ const config = [+ 'model = "gpt-5.5"',+ "",+ "[features]",+ "plugins = true",+ "multi_agent_v2 = true",+ "",+ ].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.doesNotMatch(result, /^multi_agent_v2\s*=/m);+ assert.match(result, /\[features\.multi_agent_v2\]\nenabled = false\n/);+ assert.match(result, /plugins = true/);+});++test("#given multi_agent_v2 enabled #when forcing disable #then annotates the managed section with the upstream issue and opt-out", () => {+ const config = [+ 'model = "gpt-5.5"',+ "",+ "[features.multi_agent_v2]",+ "enabled = true",+ "",+ ].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.match(result, /openai\/codex#26753/);+ assert.match(result, /LAZYCODEX_CONFIG_MIGRATION_DISABLED=1/);+ assert.match(result, /^#[^\n]*\n(?:#[^\n]*\n)*\[features\.multi_agent_v2\]/m);+});++test("#given no multi_agent_v2 section #when forcing disable #then annotates the appended section", () => {+ const config = ['model = "gpt-5.5"', ""].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.match(result, /openai\/codex#26753/);+ assert.match(result, /^#[^\n]*\n(?:#[^\n]*\n)*\[features\.multi_agent_v2\]\nenabled = false\n/m);+});++test("#given an annotated managed section #when forcing disable runs again #then does not duplicate the comment", () => {+ const config = ['model = "gpt-5.5"', "", "[features.multi_agent_v2]", "enabled = true", ""].join("\n");++ const annotated = forceDisableMultiAgentV2(config);+ const rerun = forceDisableMultiAgentV2(`${annotated.replace("enabled = false", "enabled = true")}`);++ const markers = rerun.match(/openai\/codex#26753/g) ?? [];+ assert.equal(markers.length, 1);+ assert.match(rerun, /enabled = false/);+});++test("#given [features] boolean shorthand multi_agent_v2 = false #when forcing disable #then returns config unchanged", () => {+ const config = [+ 'model = "gpt-5.5"',+ "",+ "[features]",+ "multi_agent_v2 = false",+ "",+ ].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.equal(result, config);+});++test("#given multi_agent_v2 already disabled #when forcing disable #then returns config unchanged", () => {+ const config = [+ 'model = "gpt-5.5"',+ 'model_reasoning_effort = "high"',+ "",+ "[features.multi_agent_v2]",+ "enabled = false",+ "max_concurrent_threads_per_session = 10000",+ "",+ ].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.equal(result, config);+});++test("#given global config without multi_agent_v2 section #when full migration runs #then writes a disabled section on disk", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-multi-agent-v2-guard-"));+ const codexHome = join(root, "codex-home");+ await mkdir(codexHome, { recursive: true });+ const configPath = join(codexHome, "config.toml");+ await writeFile(+ configPath,+ [+ 'model = "gpt-5.5"',+ 'model_reasoning_effort = "high"',+ "",+ ].join("\n"),+ );++ const result = await migrateCodexConfig({+ env: { CODEX_HOME: codexHome, LAZYCODEX_MODEL_CATALOG_STATE_PATH: join(root, "model-state.json") },+ cwd: root,+ });++ assert.deepEqual(result.changed, [configPath]);+ const content = await readFile(configPath, "utf8");+ assert.match(content, /\[features\.multi_agent_v2\]\nenabled = false\n/);+});++test("#given global config with forced multi_agent_v2 #when full migration runs #then disables it on disk", async () => {+ const root = await mkdtemp(join(tmpdir(), "lazycodex-multi-agent-v2-guard-"));+ const codexHome = join(root, "codex-home");+ await mkdir(codexHome, { recursive: true });+ const configPath = join(codexHome, "config.toml");+ await writeFile(+ configPath,+ [+ 'model = "gpt-5.5"',+ 'model_reasoning_effort = "high"',+ "",+ "[features.multi_agent_v2]",+ "enabled = true",+ "max_concurrent_threads_per_session = 10000",+ "",+ ].join("\n"),+ );++ const result = await migrateCodexConfig({+ env: { CODEX_HOME: codexHome, LAZYCODEX_MODEL_CATALOG_STATE_PATH: join(root, "model-state.json") },+ cwd: root,+ });++ assert.deepEqual(result.changed, [configPath]);+ const content = await readFile(configPath, "utf8");+ assert.match(content, /enabled = false/);+ assert.doesNotMatch(content, /enabled = true/);+});++test("#given enabled = true with an inline comment #when forcing disable #then flips to false and preserves the comment", () => {+ const config = ["[features.multi_agent_v2]", "enabled = true # tuned by me", ""].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.match(result, /^enabled = false # tuned by me$/m);+ assert.doesNotMatch(result, /enabled = true/);+ assert.equal((result.match(/^\s*enabled\s*=/gm) ?? []).length, 1);+ assert.equal((result.match(/\[features\.multi_agent_v2\]/g) ?? []).length, 1);+});++test("#given a section header with an inline comment #when forcing disable #then patches in place without duplicating the table", () => {+ const config = ["[features.multi_agent_v2] # pinned by me", "enabled = true", ""].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.equal((result.match(/\[features\.multi_agent_v2\]/g) ?? []).length, 1);+ assert.match(result, /enabled = false/);+ assert.doesNotMatch(result, /enabled = true/);+ assert.match(result, /# pinned by me/);+});++test("#given an already-guarded commented config #when re-running #then output is byte-identical", () => {+ const configA = ["[features.multi_agent_v2]", "enabled = true # tuned by me", ""].join("\n");+ const configB = ["[features.multi_agent_v2] # pinned by me", "enabled = true", ""].join("\n");++ const firstA = forceDisableMultiAgentV2(configA);+ const rerunA = forceDisableMultiAgentV2(firstA);+ assert.equal(rerunA, firstA);++ const firstB = forceDisableMultiAgentV2(configB);+ const rerunB = forceDisableMultiAgentV2(firstB);+ assert.equal(rerunB, firstB);+});++test("#given user-disabled with an inline comment #when forcing disable #then returns config unchanged", () => {+ const config = ["[features.multi_agent_v2]", "enabled = false # I turned this off myself", ""].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.equal(result, config);+});++test("#given [features] shorthand true with an inline comment #when forcing disable #then removes the shorthand and appends one disabled table", () => {+ const config = ["[features]", "plugins = true", "multi_agent_v2 = true # legacy", ""].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.doesNotMatch(result, /^\s*multi_agent_v2\s*=/m);+ assert.equal((result.match(/\[features\.multi_agent_v2\]/g) ?? []).length, 1);+ assert.match(result, /\[features\.multi_agent_v2\]\nenabled = false\n/);+ assert.match(result, /plugins = true/);+});++test("#given a following section header with an inline comment #when inserting enabled=false #then does not leak into the next section", () => {+ const config = [+ "[features.multi_agent_v2]",+ "max_concurrent_threads_per_session = 2",+ "[mcp_servers.x] # note",+ "enabled = true",+ "",+ ].join("\n");++ const result = forceDisableMultiAgentV2(config);++ assert.match(result, /\[features\.multi_agent_v2\]\nenabled = false\n/);+ assert.match(result, /\[mcp_servers\.x\][^\n]*\nenabled = true/);+});+async function canCreateSymlink(type) {const root = await mkdtemp(join(tmpdir(), "lazycodex-symlink-capability-"));const target = join(root, "target");diff --git a/plugins/omo/test/start-work-skill.test.mjs b/plugins/omo/test/start-work-skill.test.mjsindex a8d93518..d7864541 100644--- a/plugins/omo/test/start-work-skill.test.mjs+++ b/plugins/omo/test/start-work-skill.test.mjs@@ -43,33 +43,6 @@ test("#given start-work skill without selectable plan #when inspected #then bootassert.deepEqual(missing, []);});-test("#given worker done claim #when start-work contract is inspected #then adversarial verification gates fully done", async () => {- // given- const missing = [];-- // when- for (const skillPath of startWorkSkillPaths) {- const skill = await readFile(skillPath, "utf8");- if (- !/DoneClaim/i.test(skill) ||- !/worker done claim/i.test(skill) ||- !/stale_state/.test(skill) ||- !/misleading_success_output/.test(skill) ||- !/dirty_worktree/.test(skill) ||- !/Plan reread/i.test(skill) ||- !/Manual-QA/i.test(skill) ||- !/Adversarial QA/i.test(skill) ||- !/Cleanup/i.test(skill) ||- !/Only after verification passes/i.test(skill)- ) {- missing.push(skillPath);- }- }-- // then- assert.deepEqual(missing, []);-});-test("#given packaged start-work completion surfaces #when inspected #then global review and debugging gate blocks completion", async () => {// givenconst [startWorkSkill, reviewWorkSkill, hephaestusRule] = await Promise.all([@@ -83,13 +56,18 @@ test("#given packaged start-work completion surfaces #when inspected #then globaassert.match(startWorkSkill, /\breview-work\b/);assert.match(startWorkSkill, /\bdebugging\b/);assert.match(startWorkSkill, /inconclusive/i);- assert.match(startWorkSkill, /redact|mask/i);- assert.match(startWorkSkill, /raw (?:tokens|credentials|auth headers|cookies)/i);- assert.match(startWorkSkill, /ORCHESTRATION COMPLETE/);assert.match(reviewWorkSkill, /debugging/i);assert.match(reviewWorkSkill, /inconclusive/i);assert.match(hephaestusRule, /Global Review and Debugging Gate/);- assert.match(hephaestusRule, /redact.*secrets.*PII/s);+});++test("#given start-work skill #when echo discipline is inspected #then the ultraqa class list is enumerated once and the budget holds", async () => {+ // given+ const skill = await readFile(startWorkSkillPaths[0], "utf8");++ // then+ assert.equal((skill.match(/malformed input/g) ?? []).length, 1);+ assert.ok(skill.split(/\s+/).filter(Boolean).length <= 1924);});test("#given start-work continuation hook #when inspected #then it remains Boulder-only without planning bootstrap logic", async () => {diff --git a/plugins/omo/test/subagent-guidance.test.mjs b/plugins/omo/test/subagent-guidance.test.mjsdeleted file mode 100644index 03c27942..00000000--- a/plugins/omo/test/subagent-guidance.test.mjs+++ /dev/null@@ -1,151 +0,0 @@-import assert from "node:assert/strict";-import { 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 SKILLS = [- "review-work",- "start-work",- "ulw-loop",- "ulw-plan",-];--const AGENT_FILES = [- "components/ultrawork/agents/codex-ultrawork-reviewer.toml",- "components/ultrawork/agents/plan.toml",-];--test("#given orchestration skills #when inspected #then Codex subagent delegation is hardened", async () => {- // given- const skillPaths = SKILLS.map((skillName) => join("skills", skillName, "SKILL.md"));-- // when- const missing = [];- for (const skillPath of skillPaths) {- const text = await readFile(join(root, skillPath), "utf8");- if (- !/TASK:/.test(text) ||- !/fork_turns:\s*"none"/.test(text) ||- !/wait_agent.*mailbox signals/s.test(text) ||- !/Fallback only when/.test(text) ||- !/respawn.*smaller/s.test(text) ||- !/schema only accepts `task_name`, `message`, and `fork_turns`/s.test(text) ||- !/Plan and reviewer agents may run for a long time/.test(text) ||- !/short wait_agent cycles/.test(text) ||- !/single long blocking wait/.test(text) ||- !/A timeout only means no new mailbox update arrived/i.test(text) ||- !/WORKING:/.test(text) ||- !/single `list_agents`/.test(text)- ) {- missing.push(skillPath);- }- }-- // then- assert.deepEqual(missing, []);-});--test("#given ultrawork directive #when inspected #then reviewer fallback keeps an agent role", async () => {- // given- const directivePath = "components/ultrawork/directive.md";-- // when- const text = await readFile(join(root, directivePath), "utf8");-- // then- assert.doesNotMatch(text, /any `gpt-5\.2`\s+xhigh reviewer/);- assert.match(text, /self-contained reviewer/);- assert.match(text, /schema cannot select.*TOML-backed reviewer role/s);- assert.match(text, /paste the reviewer requirements into\s+the message/s);- assert.match(text, /timeout only means no new mailbox update arrived/i);- assert.match(text, /WORKING:/);- assert.match(text, /single `list_agents`/);-});--test("#given ultrawork directive #when inspected #then dependent subagent transitions are blocked", async () => {- // given- const directivePath = "components/ultrawork/directive.md";-- // when- const text = await readFile(join(root, directivePath), "utf8");-- // then- assert.match(text, /Subagent-dependent transition barrier/);- assert.match(text, /Do not mark.*update_plan.*completed.*active child/s);- assert.match(text, /Do not start dependent implementation.*audit.*research.*review.*integrated/s);- assert.match(text, /Do not write the final answer.*active child agents/s);- assert.match(text, /two silent waits.*TASK STILL ACTIVE/s);- assert.match(text, /four silent or ack-only checks.*inconclusive/s);-});--test("#given ultrawork directive #when inspected #then TOML-backed routing is treated as unverified when native spawn cannot select it", async () => {- // given- const directivePath = "components/ultrawork/directive.md";-- // when- const text = await readFile(join(root, directivePath), "utf8");-- // then- assert.match(text, /TOML-backed subagent routing compatibility/);- assert.match(text, /routing-unverified/);- assert.match(text, /schema accepts only `task_name`, `message`, and\s+`fork_turns`/s);- assert.match(text, /cannot select a TOML-backed role, model, reasoning\s+effort, or `service_tier`/s);- assert.match(text, /paste the\s+role requirements into the message/s);-});--test("#given ulw-loop workflow #when inspected #then stale review refresh keeps policy changes narrow", async () => {- // given- const workflowPaths = [- "components/ulw-loop/skills/ulw-loop/references/full-workflow.md",- "skills/ulw-loop/references/full-workflow.md",- ];-- // when- const missing = [];- for (const workflowPath of workflowPaths) {- const text = await readFile(join(root, workflowPath), "utf8");- if (- !/refresh current branch\/PR\/issue state/.test(text) ||- !/preserve existing ordering\/policy/.test(text) ||- !/separate compatibility detection from policy changes/.test(text)- ) {- missing.push(workflowPath);- }- }-- // then- assert.deepEqual(missing, []);-});--test("#given ultrawork agents #when inspected #then inter-agent commentary is treated as assignments", async () => {- // given- const agentPaths = AGENT_FILES;-- // when- const missing = [];- for (const agentPath of agentPaths) {- const text = await readFile(join(root, agentPath), "utf8");- if (!/TASK:|active review assignment/.test(text) || !/context|commentary/.test(text)) {- missing.push(agentPath);- }- }-- // then- assert.deepEqual(missing, []);-});--test("#given reviewer receives a targeted still-active followup #when prompt is inspected #then it must fail loud", async () => {- // given- const reviewerPath = "components/ultrawork/agents/codex-ultrawork-reviewer.toml";-- // when- const text = await readFile(join(root, reviewerPath), "utf8");-- // then- assert.match(text, /TASK STILL ACTIVE:/);- assert.match(text, /BLOCKED: <reason>/);- assert.match(text, /instead of continuing silently/);-});diff --git a/plugins/omo/test/sync-skills-orchestration.test.mjs b/plugins/omo/test/sync-skills-orchestration.test.mjsindex 40667790..b249bb2c 100644--- a/plugins/omo/test/sync-skills-orchestration.test.mjs+++ b/plugins/omo/test/sync-skills-orchestration.test.mjs@@ -58,7 +58,7 @@ call_omo_agent(subagent_type="explore", prompt="inspect")Older variant guidance.-When translating \`load_skills=[...]\`, name the skills inside the spawned agent's \`message\`.+When translating \`load_skills=[...]\`, name the skills inside the spawned agent's \`message\`. If a code block below conflicts with this section, this section wins.---@@ -103,6 +103,71 @@ call_omo_agent(subagent_type="explore", prompt="inspect")assert.equal(adapted, content);});+test("#given early generated stale Codex compatibility guidance #when adapting a skill #then it is replaced", () => {+ // given+ const content = `---+name: example+---++## 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({"task_name":"...","message":"TASK: act as an explorer. ...","fork_turns":"none"})\` |+| \`background_output(task_id="...")\` | \`wait_agent(...)\` for mailbox signals; after a timeout, run one \`list_agents\` check for the named child if reassurance is needed |++Codex full-history forks inherit parent context, so role-specific behavior must be described in a self-contained \`message\` and usually should use a non-full-history fork mode such as \`fork_turns="none"\`. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's \`message\`. If a code block below conflicts with this section, this section wins.++For work likely to exceed one wait cycle, require the child to send \`WORKING: <task> - <current phase>\` before long passes and \`BLOCKED: <reason>\` only when progress stops. A \`wait_agent\` timeout only means no new mailbox update arrived. Treat a running child or latest \`WORKING:\` message as alive. Do not use \`list_agents\` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly \`BLOCKED:\`, or no longer running.++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.++# Example Skill++call_omo_agent(subagent_type="explore", prompt="inspect")+`;++ // when+ const adapted = insertCodexCompatibilityGuidance(content);++ // then+ assert.match(adapted, /multi_agent_v1\.spawn_agent/);+ assert.match(adapted, /fork_context":false/);+ assert.match(adapted, /"agent_type":"explorer"/);+ assert.match(adapted, /multi_agent_v1\.wait_agent/);+ assert.doesNotMatch(adapted, /fork_turns="none"/);+ assert.doesNotMatch(adapted, /list_agents/);+});++test("#given generated guidance before a template export #when adapting a skill #then the export wrapper is preserved", () => {+ // given+ const content = `---+name: refactor+---++## Codex Harness Tool Compatibility++Older variant guidance.++When translating \`load_skills=[...]\`, name the skills inside the spawned agent's \`message\`. If a code block below conflicts with this section, this section wins.++export const REFACTOR_TEMPLATE = \`# Refactor++call_omo_agent(subagent_type="explore", prompt="inspect")+\`+`;++ // when+ const adapted = insertCodexCompatibilityGuidance(content);++ // then+ assert.match(adapted, /export const REFACTOR_TEMPLATE = `# Refactor/);+ assert.match(adapted, /multi_agent_v1\.spawn_agent/);+ assert.doesNotMatch(adapted, /Older variant guidance/);+});+test("#given synced aggregate Codex skills #when they describe background orchestration #then liveness is framed as progress rather than timeout failure", async () => {// givenconst orchestrationPattern = /\b(?:run_in_background|background_output|wait_agent)\b/;@@ -110,8 +175,7 @@ test("#given synced aggregate Codex skills #when they describe background orches["working progress message", /WORKING:/],["blocked progress message", /BLOCKED:/],["mailbox timeout framing", /timeout only means no new mailbox update arrived/],- ["single liveness check", /single `list_agents` check|one `list_agents` check/],- ["polling-loop guard", /Do not use `list_agents` as a polling loop|Do NOT use `list_agents` as a polling loop/],+ ["multi_agent_v1.wait_agent ref", /multi_agent_v1\.wait_agent/],["explicit fallback conditions", /Fallback only when|Mark a file for retry only when/],];const bannedPatterns = [@@ -148,5 +212,5 @@ test("#given review-work skill #when some lanes do not finish #then aggregate reassert.match(content, /Overall Verdict: PASSED \/ FAILED \/ INCONCLUSIVE/);assert.match(content, /PASS\/FAIL\/INCONCLUSIVE \| HIGH\/MED\/LOW/);assert.match(content, /Do not spin in repeated/);- assert.match(content, /Do not use `send_message` as an interrupt/);+ assert.match(content, /Do not use `multi_agent_v1\.send_input` as an interrupt/);});diff --git a/plugins/omo/test/sync-skills-test-support.mjs b/plugins/omo/test/sync-skills-test-support.mjsnew file mode 100644index 00000000..9d6cad77--- /dev/null+++ b/plugins/omo/test/sync-skills-test-support.mjs@@ -0,0 +1,119 @@+import assert from "node:assert/strict";+import { readdir } from "node:fs/promises";+import { join } from "node:path";++export const CONTEXT_PRESSURE_SKILL_BUDGET_BYTES = 25_000;++export const expectedSkills = [+ "comment-checker",+ "debugging",+ "frontend-ui-ux",+ "git-master",+ "init-deep",+ "lcx-contribute-bug-fix",+ "lcx-doctor",+ "lcx-report-bug",+ "lsp",+ "lsp-setup",+ "programming",+ "refactor",+ "remove-ai-slops",+ "review-work",+ "rules",+ "start-work",+ "ultraresearch",+ "ulw-loop",+ "ulw-plan",+ "visual-qa",+];++export const componentSkillSources = [+ ["comment-checker", "components/comment-checker/skills/comment-checker"],+ ["lsp", "components/lsp/skills/lsp"],+ ["rules", "components/rules/skills/rules"],+ ["ulw-loop", "components/ulw-loop/skills/ulw-loop"],+ ["ulw-plan", "components/ultrawork/skills/ulw-plan"],+];++const codexCompatibilityEndMarkers = [+ "For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `multi_agent_v1.wait_agent` timeout only means no new mailbox update arrived. Treat a running child as alive. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.\n\n",+ "Role-specific behavior must be described in a self-contained `message`. Use `fork_context: false` to start the child with only the initial prompt (no parent history); use `fork_context: true` only when full parent history is truly required. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.\n\n",+ "For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `wait_agent` timeout only means no new mailbox update arrived. Treat a running child or latest `WORKING:` message as alive. Do not use `list_agents` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.\n\n",+ "Codex full-history forks inherit parent context, so role-specific behavior must be described in a self-contained `message` and usually should use a non-full-history fork mode such as `fork_turns=\"none\"`. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.\n\n",+ "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.\n\n",+ "When translating `load_skills=[...]`, name the skills inside the spawned agent's `message`. If a code block below conflicts with this section, this section wins.\n\n",+];++export function removeCodexCompatibilityGuidance(content) {+ const start = content.indexOf("## Codex Harness Tool Compatibility\n\n");+ if (start === -1) return content;+ const structuralEndPattern = /\n(?:---|export\s+const\s+|#{1,6}\s)/g;+ structuralEndPattern.lastIndex = start + "## Codex Harness Tool Compatibility\n\n".length;+ const structuralEnd = structuralEndPattern.exec(content);+ if (structuralEnd) return `${content.slice(0, start)}${content.slice(structuralEnd.index + 1)}`;++ const endMarker = codexCompatibilityEndMarkers.find((marker) => content.indexOf(marker, start) !== -1);+ assert.notEqual(endMarker, undefined, "Codex compatibility guidance block is missing its terminator");+ const end = content.indexOf(endMarker, start);+ assert.notEqual(end, -1, "Codex compatibility guidance block is missing its terminator");+ return `${content.slice(0, start)}${content.slice(end + endMarker.length)}`;+}++const startWorkOriginalCompletion = `When all top-level checkboxes in \`## TODOs\` and \`## Final Verification Wave\` are complete:++1. Run the plan's final verification commands.+2. If worktree mode was used, sync \`.omo/\` state back to the main repo, merge or hand off exactly as requested, and remove the worktree only after successful merge or explicit handoff.+3. Remove or mark the Boulder work as completed.+4. Print an \`ORCHESTRATION COMPLETE\` block with the plan path, verification commands, artifacts, and cleanup receipts.`;++const startWorkCodexCompletion = `When all top-level checkboxes in \`## TODOs\` and \`## Final Verification Wave\` are complete:++1. Run the plan's final verification commands.+2. Complete the **Global Review and Debugging Gate** before any completion claim, PR handoff, or branch handoff:+ - Invoke the \`review-work\` skill with the final diff, changed files, user goal, constraints, run command, and verification evidence. All five review lanes must return PASS. A timeout, missing deliverable, ack-only child, \`BLOCKED:\`, or inconclusive lane is a gate failure, not approval.+ - Run a debugging-oriented runtime audit even when the review passes: name at least three plausible failure hypotheses for the changed surface, run the distinguishing checks against the actual artifact, and append the ruled-out or confirmed result to \`.omo/start-work/ledger.jsonl\`.+ - If any review lane or debugging hypothesis fails, invoke the \`debugging\` skill, confirm root cause with runtime evidence, add the minimal failing test or reproduction, fix it, rerun the affected verification, then rerun the Global Review and Debugging Gate.+ - Evidence hygiene is mandatory: redact or mask secrets and sensitive user data before writing \`.omo/start-work/ledger.jsonl\`, a PR body, or a handoff. Never include raw tokens, credentials, auth headers, cookies, API keys, env dumps, private logs, or PII; use concise summaries, lengths, hashes, or short non-sensitive prefixes instead.+ - If the work includes creating, updating, or handing off a PR, refresh \`git status\` and the PR/branch state after the gate, and include only redacted review/debugging evidence in the PR body or handoff.+3. If worktree mode was used, sync \`.omo/\` state back to the main repo, merge or hand off exactly as requested, and remove the worktree only after successful merge or explicit handoff.+4. Remove or mark the Boulder work as completed.+5. Print an \`ORCHESTRATION COMPLETE\` block with the plan path, verification commands, Global Review and Debugging Gate verdict, artifacts, and cleanup receipts.`;++const startWorkOriginalHardRule = "- No completion claim while an applicable ultraqa adversarial class was never probed. Each applicable class needs a captured observable result; each skipped class needs a one-line not-applicable reason in the ledger.\n- No unprefixed session ids in Boulder state. Codex sessions are always `codex:<session_id>`.";++const startWorkCodexHardRule = "- No completion claim while an applicable ultraqa adversarial class was never probed. Each applicable class needs a captured observable result; each skipped class needs a one-line not-applicable reason in the ledger.\n- No `ORCHESTRATION COMPLETE`, final response, PR creation, or PR handoff before the Global Review and Debugging Gate passes with recorded evidence.\n- No unprefixed session ids in Boulder state. Codex sessions are always `codex:<session_id>`.";++const reviewWorkCodexGatePattern =+ /\nWhen `review-work` is used as a final implementation, PR, or `\$start-work`\ngate, it is blocking\. A timeout, missing deliverable, ack-only response,\nexplicit `BLOCKED:`, or inconclusive lane is not a pass\. Treat that lane as\nfailed, investigate the underlying uncertainty with the `debugging` skill when\nruntime behavior may be wrong, fix with evidence, and rerun the affected lane\nbefore claiming completion or handing off a PR\.\n\nReview evidence must be safe to share\. Redact or mask secrets and sensitive\nuser data before including evidence in logs, PR bodies, or handoffs\. Never\ninclude raw tokens, credentials, auth headers, cookies, API keys, env dumps,\nprivate logs, or PII; summarize with lengths, hashes, and short non-sensitive\nprefixes when identity is needed\.\n/;++export function removeCodexSkillOverlays(skillName, content) {+ if (skillName === "start-work") {+ return content+ .replace(startWorkCodexCompletion, startWorkOriginalCompletion)+ .replace(startWorkCodexHardRule, startWorkOriginalHardRule);+ }+ if (skillName === "review-work") {+ return content.replace(reviewWorkCodexGatePattern, "");+ }+ return content;+}++export async function listSkillFiles(dir) {+ const entries = await readdir(dir, { withFileTypes: true });+ const files = [];+ for (const entry of entries) {+ if (entry.isDirectory()) {+ const nested = await listSkillFiles(join(dir, entry.name));+ for (const nestedPath of nested) files.push(join(entry.name, nestedPath));+ } else {+ files.push(entry.name);+ }+ }+ return files.sort();+}++export function assertPackagedContentMatches({ path, content }, requirements) {+ for (const [label, pattern] of requirements) {+ assert.match(content, pattern, `${path} missing packaged skill contract: ${label}`);+ }+}diff --git a/plugins/omo/test/sync-skills.test.mjs b/plugins/omo/test/sync-skills.test.mjsindex 21587582..677ce612 100644--- a/plugins/omo/test/sync-skills.test.mjs+++ b/plugins/omo/test/sync-skills.test.mjs@@ -4,109 +4,18 @@ import { dirname, join } from "node:path";import test from "node:test";import { fileURLToPath } from "node:url";import { sharedSkillsRootPath } from "@oh-my-opencode/shared-skills";+import {+ CONTEXT_PRESSURE_SKILL_BUDGET_BYTES,+ assertPackagedContentMatches,+ componentSkillSources,+ expectedSkills,+ listSkillFiles,+ removeCodexCompatibilityGuidance,+ removeCodexSkillOverlays,+} from "./sync-skills-test-support.mjs";const root = dirname(dirname(fileURLToPath(import.meta.url)));const repoRoot = join(root, "..", "..", "..");-const CONTEXT_PRESSURE_SKILL_BUDGET_BYTES = 25_000;--const expectedSkills = [- "comment-checker",- "debugging",- "frontend-ui-ux",- "git-master",- "init-deep",- "lcx-contribute-bug-fix",- "lcx-report-bug",- "lsp",- "programming",- "refactor",- "remove-ai-slops",- "review-work",- "rules",- "start-work",- "ultraresearch",- "ulw-loop",- "ulw-plan",- "visual-qa",-];--const componentSkillSources = [- ["comment-checker", "components/comment-checker/skills/comment-checker"],- ["lsp", "components/lsp/skills/lsp"],- ["rules", "components/rules/skills/rules"],- ["ulw-loop", "components/ulw-loop/skills/ulw-loop"],- ["ulw-plan", "components/ultrawork/skills/ulw-plan"],-];--const codexCompatibilityEndMarkers = [- "For work likely to exceed one wait cycle, require the child to send `WORKING: <task> - <current phase>` before long passes and `BLOCKED: <reason>` only when progress stops. A `wait_agent` timeout only means no new mailbox update arrived. Treat a running child or latest `WORKING:` message as alive. Do not use `list_agents` as a polling loop. Fallback only when the child is completed without the deliverable, ack-only after followup, explicitly `BLOCKED:`, or no longer running.\n\n",- "Codex full-history forks inherit parent context, so role-specific behavior must be described in a self-contained `message` and usually should use a non-full-history fork mode such as `fork_turns=\"none\"`. Include any required conversation context, files, diffs, constraints, and requested skill names directly in the spawned agent's `message`. If a code block below conflicts with this section, this section wins.\n\n",- "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.\n\n",- "When translating `load_skills=[...]`, name the skills inside the spawned agent's `message`. If a code block below conflicts with this section, this section wins.\n\n",-];--function removeCodexCompatibilityGuidance(content) {- const start = content.indexOf("## Codex Harness Tool Compatibility\n\n");- if (start === -1) return content;- const endMarker = codexCompatibilityEndMarkers.find((marker) => content.indexOf(marker, start) !== -1);- assert.notEqual(endMarker, undefined, "Codex compatibility guidance block is missing its terminator");- const end = content.indexOf(endMarker, start);- assert.notEqual(end, -1, "Codex compatibility guidance block is missing its terminator");- return `${content.slice(0, start)}${content.slice(end + endMarker.length)}`;-}--const startWorkOriginalCompletion = `When all top-level checkboxes in \`## TODOs\` and \`## Final Verification Wave\` are complete:--1. Run the plan's final verification commands.-2. If worktree mode was used, sync \`.omo/\` state back to the main repo, merge or hand off exactly as requested, and remove the worktree only after successful merge or explicit handoff.-3. Remove or mark the Boulder work as completed.-4. Print an \`ORCHESTRATION COMPLETE\` block with the plan path, verification commands, artifacts, and cleanup receipts.`;--const startWorkCodexCompletion = `When all top-level checkboxes in \`## TODOs\` and \`## Final Verification Wave\` are complete:--1. Run the plan's final verification commands.-2. Complete the **Global Review and Debugging Gate** before any completion claim, PR handoff, or branch handoff:- - Invoke the \`review-work\` skill with the final diff, changed files, user goal, constraints, run command, and verification evidence. All five review lanes must return PASS. A timeout, missing deliverable, ack-only child, \`BLOCKED:\`, or inconclusive lane is a gate failure, not approval.- - Run a debugging-oriented runtime audit even when the review passes: name at least three plausible failure hypotheses for the changed surface, run the distinguishing checks against the actual artifact, and append the ruled-out or confirmed result to \`.omo/start-work/ledger.jsonl\`.- - If any review lane or debugging hypothesis fails, invoke the \`debugging\` skill, confirm root cause with runtime evidence, add the minimal failing test or reproduction, fix it, rerun the affected verification, then rerun the Global Review and Debugging Gate.- - Evidence hygiene is mandatory: redact or mask secrets and sensitive user data before writing \`.omo/start-work/ledger.jsonl\`, a PR body, or a handoff. Never include raw tokens, credentials, auth headers, cookies, API keys, env dumps, private logs, or PII; use concise summaries, lengths, hashes, or short non-sensitive prefixes instead.- - If the work includes creating, updating, or handing off a PR, refresh \`git status\` and the PR/branch state after the gate, and include only redacted review/debugging evidence in the PR body or handoff.-3. If worktree mode was used, sync \`.omo/\` state back to the main repo, merge or hand off exactly as requested, and remove the worktree only after successful merge or explicit handoff.-4. Remove or mark the Boulder work as completed.-5. Print an \`ORCHESTRATION COMPLETE\` block with the plan path, verification commands, Global Review and Debugging Gate verdict, artifacts, and cleanup receipts.`;--const startWorkOriginalHardRule = "- No completion claim while an applicable ultraqa adversarial class was never probed. Each applicable class needs a captured observable result; each skipped class needs a one-line not-applicable reason in the ledger.\n- No unprefixed session ids in Boulder state. Codex sessions are always `codex:<session_id>`.";--const startWorkCodexHardRule = "- No completion claim while an applicable ultraqa adversarial class was never probed. Each applicable class needs a captured observable result; each skipped class needs a one-line not-applicable reason in the ledger.\n- No `ORCHESTRATION COMPLETE`, final response, PR creation, or PR handoff before the Global Review and Debugging Gate passes with recorded evidence.\n- No unprefixed session ids in Boulder state. Codex sessions are always `codex:<session_id>`.";--const reviewWorkCodexGatePattern =- /\nWhen `review-work` is used as a final implementation, PR, or `\$start-work`\ngate, it is blocking\. A timeout, missing deliverable, ack-only response,\nexplicit `BLOCKED:`, or inconclusive lane is not a pass\. Treat that lane as\nfailed, investigate the underlying uncertainty with the `debugging` skill when\nruntime behavior may be wrong, fix with evidence, and rerun the affected lane\nbefore claiming completion or handing off a PR\.\n\nReview evidence must be safe to share\. Redact or mask secrets and sensitive\nuser data before including evidence in logs, PR bodies, or handoffs\. Never\ninclude raw tokens, credentials, auth headers, cookies, API keys, env dumps,\nprivate logs, or PII; summarize with lengths, hashes, and short non-sensitive\nprefixes when identity is needed\.\n/;--function removeCodexSkillOverlays(skillName, content) {- if (skillName === "start-work") {- return content- .replace(startWorkCodexCompletion, startWorkOriginalCompletion)- .replace(startWorkCodexHardRule, startWorkOriginalHardRule);- }- if (skillName === "review-work") {- return content.replace(reviewWorkCodexGatePattern, "");- }- return content;-}--async function listSkillFiles(dir) {- const entries = await readdir(dir, { withFileTypes: true });- const files = [];- for (const entry of entries) {- if (entry.isDirectory()) {- const nested = await listSkillFiles(join(dir, entry.name));- for (const nestedPath of nested) files.push(join(entry.name, nestedPath));- } else {- files.push(entry.name);- }- }- return files.sort();-}async function readPackagedSkillFile(...segments) {const path = join(root, "skills", ...segments);@@ -114,12 +23,6 @@ async function readPackagedSkillFile(...segments) {return { path, content };}-function assertPackagedContentMatches({ path, content }, requirements) {- for (const [label, pattern] of requirements) {- assert.match(content, pattern, `${path} missing packaged skill contract: ${label}`);- }-}-test("#given synced aggregate Codex skills #when inspected #then component and shared skills are present", async () => {// givenconst skillsRoot = join(root, "skills");@@ -225,7 +128,6 @@ test("#given synced ulw-loop skill #when Codex hint metadata is inspected #then// thenassert.match(skill, /^---\r?\nname: ulw-loop\r?\n/m);- assert.match(skill, /Goal-like loop that uses ultrawork mode to decompose work into systematic, evidence-bound steps\./);assert.match(interfaceMetadata, /display_name: "ulw-loop \(omo\)"/);assert.doesNotMatch(interfaceMetadata, /ulw-loop \/ ulw-loop/);assert.match(interfaceMetadata, /short_description: "Goal-like ultrawork loop for systematic decomposition"/);@@ -273,15 +175,12 @@ test("#given synced ulw-loop skill #when worker guidance is inspected #then contconst syncedSkill = await readFile(join(root, "skills", "ulw-loop", "SKILL.md"), "utf8");const syncedWorkflow = await readFile(join(root, "skills", "ulw-loop", "references", "full-workflow.md"), "utf8");const requiredPatterns = [- ["list_agents polling guard", /list_agents/],- ["status polling warning", /polling loop/],- ["large payload replay risk", /replay large payloads/],+ ["multi_agent_v1.wait_agent ref", /multi_agent_v1\.wait_agent/],["local spawned-name tracking", /Track spawned agent names locally/],["wait_agent mailbox path", /wait_agent.*mailbox signals/],["progress status contract", /WORKING:/],- ["single list_agents reassurance", /single `list_agents`/],["long-running plan/reviewer background guidance", /Plan and reviewer agents may run for a long time/],- ["bounded plan/reviewer polling", /short wait_agent cycles/],+ ["bounded plan/reviewer polling", /multi_agent_v1\.wait_agent.*cycles/],["single long wait guard", /single long blocking wait/],["git-master checkpointing", /git-master/],["touched-path commit-style probe", /touched-path commit history/],diff --git a/plugins/omo/test/sync-version.test.mjs b/plugins/omo/test/sync-version.test.mjsnew file mode 100644index 00000000..d095d865--- /dev/null+++ b/plugins/omo/test/sync-version.test.mjs@@ -0,0 +1,68 @@+import assert from "node:assert/strict";+import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";++import { manifestTargets, resolveAuthoritativeVersion, syncVersion } from "../scripts/sync-version.mjs";++async function makeTempDir() {+ return mkdtemp(join(tmpdir(), "omo-codex-sync-version-"));+}++async function writeJson(path, value) {+ await mkdir(join(path, ".."), { recursive: true });+ await writeFile(path, `${JSON.stringify(value, null, "\t")}\n`);+}++async function readJson(path) {+ return JSON.parse(await readFile(path, "utf8"));+}++async function scaffoldPlugin(repoRoot, rootVersion) {+ await writeJson(join(repoRoot, "package.json"), { name: "oh-my-opencode", version: rootVersion });+ const pluginRoot = join(repoRoot, "packages", "omo-codex", "plugin");+ await writeJson(join(repoRoot, "packages", "omo-codex", "package.json"), { name: "@oh-my-opencode/omo-codex", version: "0.1.0" });+ await writeJson(join(pluginRoot, "package.json"), { name: "@sisyphuslabs/omo-codex-plugin", version: "0.1.0" });+ await writeJson(join(pluginRoot, ".codex-plugin", "plugin.json"), { name: "omo", version: "0.1.0" });+ await writeJson(join(pluginRoot, "components", "rules", "package.json"), { name: "@code-yeongyu/codex-rules", version: "0.1.0" });+ await writeJson(join(pluginRoot, "components", "rules", ".codex-plugin", "plugin.json"), { hooks: "./hooks/hooks.json" });+ return pluginRoot;+}++test("#given LAZYCODEX_RELEASE_VERSION env #when resolving authoritative version #then the env value wins", async () => {+ const version = await resolveAuthoritativeVersion({ env: { LAZYCODEX_RELEASE_VERSION: "9.9.9" }, repoRoot: "/nonexistent" });+ assert.equal(version, "9.9.9");+});++test("#given no env override #when resolving authoritative version #then root package.json version is used", async () => {+ const repoRoot = await makeTempDir();+ await writeJson(join(repoRoot, "package.json"), { name: "oh-my-opencode", version: "4.8.1" });+ const version = await resolveAuthoritativeVersion({ env: {}, repoRoot });+ assert.equal(version, "4.8.1");+});++test("#given drifted Codex manifests #when syncing version from root #then all versioned manifests match and version-less files are left alone", async () => {+ const repoRoot = await makeTempDir();+ const pluginRoot = await scaffoldPlugin(repoRoot, "4.8.1");++ const result = await syncVersion({ pluginRoot, env: {}, repoRoot });++ assert.equal(result.version, "4.8.1");+ for (const target of manifestTargets(pluginRoot, [join(pluginRoot, "components", "rules", "package.json")])) {+ assert.equal((await readJson(target)).version, "4.8.1", `expected ${target} to be stamped`);+ }+ // the version-less component plugin.json must not gain a version field+ const versionlessManifest = await readJson(join(pluginRoot, "components", "rules", ".codex-plugin", "plugin.json"));+ assert.equal("version" in versionlessManifest, false);+});++test("#given already coherent manifests #when syncing again #then nothing is rewritten", async () => {+ const repoRoot = await makeTempDir();+ const pluginRoot = await scaffoldPlugin(repoRoot, "4.8.1");++ await syncVersion({ pluginRoot, env: {}, repoRoot });+ const second = await syncVersion({ pluginRoot, env: {}, repoRoot });++ assert.equal(second.changed.length, 0);+});diff --git a/plugins/omo/test/ultraresearch-skill-contract.test.mjs b/plugins/omo/test/ultraresearch-skill-contract.test.mjsnew file mode 100644index 00000000..6ab13b40--- /dev/null+++ b/plugins/omo/test/ultraresearch-skill-contract.test.mjs@@ -0,0 +1,126 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";+import { sharedSkillsRootPath } from "@oh-my-opencode/shared-skills";++const root = dirname(dirname(fileURLToPath(import.meta.url)));++async function readUltraresearchCopies() {+ const sharedPath = join(sharedSkillsRootPath(), "ultraresearch", "SKILL.md");+ const packagedPath = join(root, "skills", "ultraresearch", "SKILL.md");+ return [+ { label: "shared", path: sharedPath, content: await readFile(sharedPath, "utf8") },+ { label: "packaged", path: packagedPath, content: await readFile(packagedPath, "utf8") },+ ];+}++function frontmatterDescription(content) {+ const match = content.match(/^---\r?\n[\s\S]*?\bdescription:\s*"([\s\S]*?)"\r?\n[\s\S]*?---/);+ assert.notEqual(match, null, "SKILL.md frontmatter description not found");+ return match[1];+}++test("#given ultraresearch skill #when scanned for non-English content #then it contains no Hangul", async () => {+ for (const copy of await readUltraresearchCopies()) {+ assert.doesNotMatch(+ copy.content,+ /[ᄀ-ᇿ-가-힣]/,+ `${copy.label} copy contains Hangul characters`,+ );+ }+});++test("#given ultraresearch description #when activation policy is inspected #then it gates on explicit research demands only", async () => {+ for (const copy of await readUltraresearchCopies()) {+ const description = frontmatterDescription(copy.content);+ assert.match(description, /explicit/i, `${copy.label}: description must gate activation on explicit demand`);+ assert.match(+ description,+ /ultra-precise investigation/i,+ `${copy.label}: description must name the ultra-precise investigation trigger`,+ );+ assert.match(description, /\bresearch\b/i, `${copy.label}: description must name the research trigger`);+ }+});++test("#given ultraresearch body #when authority is inspected #then it takes precedence over exploration-bounding instructions", async () => {+ for (const copy of await readUltraresearchCopies()) {+ assert.match(+ copy.content,+ /exploration-bounding|exploration (?:caps|budgets|limits)/i,+ `${copy.label}: body must name the exploration-bounding instructions it overrides`,+ );+ assert.match(+ copy.content,+ /supersede|override|do(?:es)? not (?:bind|apply)/i,+ `${copy.label}: body must state precedence while the mode is active`,+ );+ }+});++test("#given ultraresearch worker protocol #when EXPAND flow is inspected #then markers travel as message text and workers never write files", async () => {+ for (const copy of await readUltraresearchCopies()) {+ assert.match(copy.content, /EXPAND/, `${copy.label}: body must keep the EXPAND marker protocol`);+ assert.match(+ copy.content,+ /(?:reply|message|response) text|end (?:its|the|your) (?:reply|response|final message)/i,+ `${copy.label}: EXPAND markers must be returned as message text`,+ );+ assert.match(+ copy.content,+ /read-only|cannot write files|never ask (?:a )?worker(?:s)? to write/i,+ `${copy.label}: body must state the read-only worker constraint`,+ );+ assert.doesNotMatch(+ copy.content,+ /APPEND (?:your )?findings to \$SESSION_DIR/i,+ `${copy.label}: workers must not be instructed to append session-dir files`,+ );+ }+});++test("#given ultraresearch journaling #when ownership is inspected #then the orchestrator owns the session journal", async () => {+ for (const copy of await readUltraresearchCopies()) {+ assert.match(+ copy.content,+ /orchestrator[\s\S]{0,200}journal|journal[\s\S]{0,200}orchestrator/i,+ `${copy.label}: body must assign session-journal writes to the orchestrator`,+ );+ assert.match(copy.content, /SESSION_DIR/, `${copy.label}: body must keep the session directory protocol`);+ }+});++test("#given ultraresearch expansion loop #when stop rules are inspected #then convergence rules and a depth cap are stated", async () => {+ for (const copy of await readUltraresearchCopies()) {+ assert.match(copy.content, /converg/i, `${copy.label}: body must define convergence`);+ assert.match(copy.content, /depth/i, `${copy.label}: body must define an expansion depth cap`);+ assert.match(+ copy.content,+ /minimum (?:of )?(?:2|two) expansion waves|at least (?:2|two) expansion waves/i,+ `${copy.label}: body must require a minimum of two expansion waves before convergence`,+ );+ }+});++test("#given ultraresearch under ultrawork #when coexistence is inspected #then marker and done-definition conflicts are resolved", async () => {+ for (const copy of await readUltraresearchCopies()) {+ assert.match(copy.content, /ultrawork|\bulw\b/i, `${copy.label}: body must address ultrawork coexistence`);+ assert.match(+ copy.content,+ /first(?:-| )line/i,+ `${copy.label}: body must resolve the first-line activation marker conflict`,+ );+ }+});++test("#given ultraresearch worker sizing #when spawn guidance is inspected #then capable-model and high-effort routing is stated", async () => {+ for (const copy of await readUltraresearchCopies()) {+ assert.match(+ copy.content,+ /capable model|high(?:est)? (?:reasoning )?effort/i,+ `${copy.label}: body must route research workers to a capable model or high effort`,+ );+ }+});diff --git a/plugins/omo/test/ulw-plan-skill.test.mjs b/plugins/omo/test/ulw-plan-skill.test.mjsindex ce859015..960b197a 100644--- a/plugins/omo/test/ulw-plan-skill.test.mjs+++ b/plugins/omo/test/ulw-plan-skill.test.mjs@@ -16,7 +16,7 @@ test("#given ulw-plan skill #when inspected #then it is a Codex-native planner t// thenassert.match(skill, /^---\r?\nname: ulw-plan\r?\n/m);assert.match(skill, /references\/full-workflow\.md/);- assert.match(skill, /spawn_agent\(\{[^)]*"fork_turns":"none"/);+ assert.match(skill, /multi_agent_v1\.spawn_agent\(\{[^)]*"fork_context":false/);assert.doesNotMatch(skill, opencodeOnlyToolPattern);});@@ -37,7 +37,7 @@ test("#given ulw-plan full workflow reference #when inspected #then it documents// thenassert.match(workflow, /\.omo\/plans\/<slug>\.md/);assert.match(workflow, /[Aa]pproval gate/);- assert.match(workflow, /spawn_agent\(\{[^)]*"fork_turns":"none"/);+ assert.match(workflow, /multi_agent_v1\.spawn_agent\(\{[^)]*"fork_context":false/);assert.doesNotMatch(workflow, opencodeOnlyToolPattern);assert.doesNotMatch(workflow, /Proceeding to plan generation/);});